source map exposed
analyzed
https://4njbets.us.betfair.com/static/mybets/assets/mybets.c682591e30ec7093fdf7.js
map: https://4njbets.us.betfair.com/static/mybets/assets/mybets.c682591e30ec7093fdf7.js.map
2086 source files
10.9 MB map size
79 endpoints found
68 secrets found
discovered 6 hours, 29 minutes ago
2086
source files
10.9 MB
map size
68
secrets
79
endpoints
secrets from source map (68)
gcpKey
{'key': 'AIzaSyBwhD0RAB-vMDrx4IDcO_gezIVGpn7dFks'}
0.9
Source: webpack://frontend-mybets/../../packages/tvg-lib-conf/content/aws-prd/base.ts
gcpKey
{'key': 'AIzaSyBwhD0RAB-vMDrx4IDcO_gezIVGpn7dFks'}
0.9
Source: webpack://frontend-mybets/../../packages/tvg-lib-conf/content/production/base.ts
gcpKey
{'key': 'AIzaSyCvQe2IeP1DnZT6v0PLK-n4bjK9RqcEarQ'}
0.9
Source: webpack://frontend-mybets/../../packages/tvg-lib-conf/content/aws-int/base.ts
gcpKey
{'key': 'AIzaSyCvQe2IeP1DnZT6v0PLK-n4bjK9RqcEarQ'}
0.9
Source: webpack://frontend-mybets/../../packages/tvg-lib-conf/content/default.ts
gcpKey
{'key': 'AIzaSyCvQe2IeP1DnZT6v0PLK-n4bjK9RqcEarQ'}
0.9
Source: webpack://frontend-mybets/../../packages/tvg-lib-conf/content/qa/base.ts
gcpKey
{'key': 'AIzaSyBwhD0RAB-vMDrx4IDcO_gezIVGpn7dFks'}
0.9
Source: webpack://frontend-mybets/../../packages/tvg-lib-conf/content/aws-stg/base.ts
gcpKey
{'key': 'AIzaSyBwhD0RAB-vMDrx4IDcO_gezIVGpn7dFks'}
0.9
Source: webpack://frontend-mybets/../../packages/tvg-lib-conf/content/staging/base.ts
internal_url
typeof process.env.ENVIRONMENT === "string" &&
0.8
Source map: webpack://frontend-mybets/../../packages/tvg-lib-conf/src/environment.ts
// process.env instead.
typeof process !== "undefined" &&
typeof process.env.ENVIRONMENT === "string" &&
(process.env.ENVIRONMENT === "dev"
? ("qa" as Env)
internal_url
if (hostname === "10.0.2.2") {
0.8
Source map: webpack://frontend-mybets/../../packages/tvg-lib-conf/src/environment.ts
const getEnvironmentByHostname = (hostname?: string): Env => {
if (hostname === "10.0.2.2") {
return "aws-int";
}
internal_url
: `http://localhost:${process ? process.env.PORT : "8080"}`;
0.8
Source map: webpack://frontend-mybets/../../packages/tvg-lib-conf/src/buildurl.ts
: ""
}`
: `http://localhost:${process ? process.env.PORT : "8080"}`;
const pathName = `${path.indexOf("/") === 0 ? "" : "/"}${encodeURI(path)}`;
internal_url
: `http://localhost:${process ? process.env.PORT : "8080"}`;
0.8
Source map: webpack://frontend-mybets/../../packages/tvg-lib-conf/src/buildurl.ts
: ""
}`
: `http://localhost:${process ? process.env.PORT : "8080"}`;
const pathName = `${path.indexOf("/") === 0 ? "" : "/"}${encodeURI(path)}`;
internal_url
if (!tokenValue && process.env.NODE_ENV !== "production") {
0.8
Source map: webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/theming/hooks/useColorTokens.ts
const tokenValue = get(colorTokens, value);
if (!tokenValue && process.env.NODE_ENV !== "production") {
throw new Error(`Invalid color token: ${value}`);
}
internal_url
if (!tokenValue && process.env.NODE_ENV !== "production") {
0.8
Source map: webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/hooks/useColorTokens/index.ts
const tokenValue = get(colorTokens, value);
if (!tokenValue && process.env.NODE_ENV !== "production") {
throw new Error(`Invalid color token: ${value}`);
}
internal_url
if (process.env.NODE_ENV !== 'production') {
0.8
Source map: webpack://frontend-mybets/../../node_modules/css-to-react-native/index.js
var propertiesWithoutUnits;
if (process.env.NODE_ENV !== 'production') {
propertiesWithoutUnits = ['aspectRatio', 'elevation', 'flexGrow', 'flexShrink', 'opacity', 'shadowOpacity', 'zIndex'];
}
internal_url
var validateFormat = process.env.NODE_ENV !== "production" ? function (format) {
0.8
Source map: webpack://frontend-mybets/../../node_modules/fbjs/lib/invariant.js
'use strict';
var validateFormat = process.env.NODE_ENV !== "production" ? function (format) {
if (format === undefined) {
throw new Error('invariant(...): Second argument must be a string.');
internal_url
var warning = process.env.NODE_ENV !== "production" ? function (condition, format) {
0.8
Source map: webpack://frontend-mybets/../../node_modules/fbjs/lib/warning.js
}
var warning = process.env.NODE_ENV !== "production" ? function (condition, format) {
if (format === undefined) {
throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
internal_url
if (process.env.NODE_ENV === 'production') {
0.8
Source map: webpack://frontend-mybets/../../node_modules/hoist-non-react-statics/node_modules/react-is/index.js
'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/react-is.production.min.js');
} else {
internal_url
if (process.env.NODE_ENV !== 'production') {
0.8
Source map: webpack://frontend-mybets/../../node_modules/prop-types/index.js
*/
if (process.env.NODE_ENV !== 'production') {
var ReactIs = require('react-is');
internal_url
if (process.env.NODE_ENV === 'production') {
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-dom/client.js
var m = require('react-dom');
if (process.env.NODE_ENV === 'production') {
exports.createRoot = m.createRoot;
exports.hydrateRoot = m.hydrateRoot;
internal_url
if (process.env.NODE_ENV !== 'production') {
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-dom/index.js
return;
}
if (process.env.NODE_ENV !== 'production') {
// This branch is unreachable because this function is only called
// in production, but the condition is true only in development.
internal_url
if (process.env.NODE_ENV === 'production') {
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-is/index.js
'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/react-is.production.min.js');
} else {
internal_url
var isDevelopment = process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test';
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/AppRegistry/index.js
}
static runApplication(appKey, appParameters) {
var isDevelopment = process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test';
if (isDevelopment) {
var params = (0, _objectSpread2.default)({}, appParameters);
internal_url
if (process.env.NODE_ENV !== 'production') {
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Image/index.js
style = props.style,
rest = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
if (process.env.NODE_ENV !== 'production') {
if (props.children) {
throw new Error('The <Image> component cannot contain children. If you want to render content on top of the image, consider using the <ImageBackground> component or absolute positioning.');
internal_url
if (process.env.NODE_ENV === 'test') {
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Platform/index.js
select: obj => 'web' in obj ? obj.web : obj.default,
get isTesting() {
if (process.env.NODE_ENV === 'test') {
return true;
}
internal_url
if (process.env.NODE_ENV !== 'production') {
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/ScrollView/index.js
};
this._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.');
internal_url
return process.env.NODE_ENV !== 'production' ? prefix + "-" + name + "-" + hashedString : prefix + "-" + hashedString;
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/StyleSheet/compiler/index.js
function createIdentifier(prefix, name, key) {
var hashedString = (0, _hash.default)(name + key);
return process.env.NODE_ENV !== 'production' ? prefix + "-" + name + "-" + hashedString : prefix + "-" + hashedString;
}
internal_url
if (process.env.NODE_ENV !== 'production') {
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/StyleSheet/index.js
compiledStyles = compileAndInsertReset(styleObj, key.split('$raw')[0]);
} else {
if (process.env.NODE_ENV !== 'production') {
(0, _validate.validate)(styleObj);
styles[key] = Object.freeze(styleObj);
internal_url
if (process.env.NODE_ENV !== 'production') {
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Touchable/index.js
return null;
}
if (process.env.NODE_ENV !== 'production') {
throw Error('Touchable.TOUCH_TARGET_DEBUG should not be enabled in prod!');
}
internal_url
if (process.env.NODE_ENV !== 'production') {
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/View/index.js
onStartShouldSetResponderCapture = props.onStartShouldSetResponderCapture,
rest = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
if (process.env.NODE_ENV !== 'production') {
React.Children.toArray(props.children).forEach(item => {
if (typeof item === 'string') {
internal_url
var unimplementedViewStyles = process.env.NODE_ENV !== 'production' ? {
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/UnimplementedView/index.js
}
}
var unimplementedViewStyles = process.env.NODE_ENV !== 'production' ? {
alignSelf: 'flex-start',
borderColor: 'red',
internal_url
if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test') {
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/useElementLayout/index.js
}
} else if (!didWarn) {
if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test') {
console.warn('onLayout relies on ResizeObserver which is not supported by your browser. ' + 'Please include a polyfill, e.g., https://github.com/que-etc/resize-observer-polyfill.');
didWarn = true;
internal_url
var __DEV__ = process.env.NODE_ENV !== 'production';
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/useResponderEvents/ResponderTouchHistoryStore.js
*/
var __DEV__ = process.env.NODE_ENV !== 'production';
var MAX_TOUCH_BANK = 20;
function timestampForTouch(touch) {
internal_url
if (process.env.NODE_ENV !== 'production') {
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/warnOnce/index.js
*/
function warnOnce(key, message) {
if (process.env.NODE_ENV !== 'production') {
if (warnedKeys[key]) {
return;
internal_url
var __DEV__ = process.env.NODE_ENV !== 'production';
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/AnimatedEvent.js
var _NativeAnimatedHelper = _interopRequireWildcard(require("./NativeAnimatedHelper"));
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
var __DEV__ = process.env.NODE_ENV !== 'production';
function attachNativeEvent(viewRef, eventName, argMapping) {
// Find animated values in `argMapping` and create an array representing their
internal_url
var __DEV__ = process.env.NODE_ENV !== 'production';
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/nodes/AnimatedInterpolation.js
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
var _normalizeColors = _interopRequireDefault(require("@react-native/normalize-colors"));
var __DEV__ = process.env.NODE_ENV !== 'production';
var linear = t => t;
internal_url
var __DEV__ = process.env.NODE_ENV !== 'production';
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/LayoutAnimation/index.js
var _Platform = _interopRequireDefault(require("../../../exports/Platform"));
var _UIManager = _interopRequireDefault(require("../../../exports/UIManager"));
var __DEV__ = process.env.NODE_ENV !== 'production';
function configureNext(config, onAnimationDidEnd) {
if (!_Platform.default.isTesting) {
internal_url
var __DEV__ = process.env.NODE_ENV !== 'production';
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/VirtualizedList/VirtualizedListContext.js */ var __DEV__ = process.env.NODE_ENV !== 'production'; var VirtualizedListContext = /*#__PURE__*/React.createContext(null); exports.VirtualizedListContext = VirtualizedListContext;
internal_url
var __DEV__ = process.env.NODE_ENV !== 'production';
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/VirtualizedList/index.js */ var __DEV__ = process.env.NODE_ENV !== 'production'; var ON_EDGE_REACHED_EPSILON = 0.001; var _usedIndexForKey = false;
internal_url
if (process.env.NODE_ENV !== 'production') {
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-redux/es/components/Context.js
export var ReactReduxContext = /*#__PURE__*/React.createContext(null);
if (process.env.NODE_ENV !== 'production') {
ReactReduxContext.displayName = 'ReactRedux';
}
internal_url
if (process.env.NODE_ENV !== 'production') {
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-redux/es/components/Provider.js
}
if (process.env.NODE_ENV !== 'production') {
Provider.propTypes = {
store: PropTypes.shape({
internal_url
if (process.env.NODE_ENV !== 'production') {
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-redux/es/components/connectAdvanced.js
connectOptions = _objectWithoutPropertiesLoose(_ref2, ["getDisplayName", "methodName", "renderCountProp", "shouldHandleStateChanges", "storeKey", "withRef", "forwardRef", "context"]);
if (process.env.NODE_ENV !== 'production') {
if (renderCountProp !== undefined) {
throw new Error("renderCountProp is removed. render counting is built into the latest React Dev Tools profiling extension");
internal_url
if (process.env.NODE_ENV !== 'production') verifyPlainObject(props, displayName, methodName);
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-redux/es/connect/wrapMapToProps.js
}
if (process.env.NODE_ENV !== 'production') verifyPlainObject(props, displayName, methodName);
return props;
};
internal_url
if (process.env.NODE_ENV !== 'production') verifyPlainObject(mergedProps, displayName, 'mergeProps');
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-redux/es/connect/mergeProps.js
hasRunOnce = true;
mergedProps = nextMergedProps;
if (process.env.NODE_ENV !== 'production') verifyPlainObject(mergedProps, displayName, 'mergeProps');
}
internal_url
if (process.env.NODE_ENV !== 'production') {
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-redux/es/connect/selectorFactory.js
var mergeProps = initMergeProps(dispatch, options);
if (process.env.NODE_ENV !== 'production') {
verifySubselectors(mapStateToProps, mapDispatchToProps, mergeProps, options.displayName);
}
internal_url
if (process.env.NODE_ENV !== 'production' && !contextValue) {
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-redux/es/hooks/useReduxContext.js
var contextValue = useContext(ReactReduxContext);
if (process.env.NODE_ENV !== 'production' && !contextValue) {
throw new Error('could not find react-redux context value; please ensure the component is wrapped in a <Provider>');
}
internal_url
if (process.env.NODE_ENV !== 'production') {
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-redux/es/hooks/useSelector.js
}
if (process.env.NODE_ENV !== 'production') {
if (!selector) {
throw new Error("You must pass a selector to useSelector");
internal_url
if (process.env.NODE_ENV === 'production') {
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-redux/node_modules/react-is/index.js
'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/react-is.production.min.js');
} else {
internal_url
if (process.env.NODE_ENV === 'production') {
0.8
Source map: webpack://frontend-mybets/../../node_modules/react/index.js
'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/react.production.min.js');
} else {
internal_url
if (process.env.NODE_ENV !== 'production') {
0.8
Source map: webpack://frontend-mybets/../../node_modules/redux/es/redux.js
var typeOfVal = typeof val;
if (process.env.NODE_ENV !== 'production') {
// Inlined / shortened version of `kindOf` from https://github.com/jonschlinkert/kind-of
function miniKindOf(val) {
internal_url
if (process.env.NODE_ENV === 'production') {
0.8
Source map: webpack://frontend-mybets/../../node_modules/scheduler/index.js
'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/scheduler.production.min.js');
} else {
internal_url
import{typeOf as e,isElement as t,isValidElementType as n}from"react-is";import r,{useState as o,useContext as s,useMemo as i,useEffect as a,useRef as c,createElement as u,useDebugValue as l,useLayoutEffect as d}from"react";import h from"shallowequal";import p from"@emotion/stylis";import f from"@emotion/unitless";import m from"@emotion/is-prop-valid";import y from"hoist-non-react-statics";function v(){return(v=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}var g=function(e,t){for(var n=[e[0]],r=0,o=t.length;r<o;r+=1)n.push(t[r],e[r+1]);return n},S=function(t){return null!==t&&"object"==typeof t&&"[object Object]"===(t.toString?t.toString():Object.prototype.toString.call(t))&&!e(t)},w=Object.freeze([]),E=Object.freeze({});function b(e){return"function"==typeof e}function _(e){return"production"!==process.env.NODE_ENV&&"string"==typeof e&&e||e.displayName||e.name||"Component"}function N(e){return e&&"string"==typeof e.styledComponentId}var A="undefined"!=typeof process&&(process.env.REACT_APP_SC_ATTR||process.env.SC_ATTR)||"data-styled",C="5.3.1",I="undefined"!=typeof window&&"HTMLElement"in window,P=Boolean("boolean"==typeof SC_DISABLE_SPEEDY?SC_DISABLE_SPEEDY:"undefined"!=typeof process&&void 0!==process.env.REACT_APP_SC_DISABLE_SPEEDY&&""!==process.env.REACT_APP_SC_DISABLE_SPEEDY?"false"!==process.env.REACT_APP_SC_DISABLE_SPEEDY&&process.env.REACT_APP_SC_DISABLE_SPEEDY:"undefined"!=typeof process&&void 0!==process.env.SC_DISABLE_SPEEDY&&""!==process.env.SC_DISABLE_SPEEDY?"false"!==process.env.SC_DISABLE_SPEEDY&&process.env.SC_DISABLE_SPEEDY:"production"!==process.env.NODE_ENV),O={},R="production"!==process.env.NODE_ENV?{1:"Cannot create styled-component for component: %s.\n\n",2:"Can't collect styles once you've consumed a `ServerStyleSheet`'s styles! `ServerStyleSheet` is a one off instance for each server-side render cycle.\n\n- Are you trying to reuse it across renders?\n- Are you accidentally calling collectStyles twice?\n\n",3:"Streaming SSR is only supported in a Node.js environment; Please do not try to call this method in the browser.\n\n",4:"The `StyleSheetManager` expects a valid target or sheet prop!\n\n- Does this error occur on the client and is your target falsy?\n- Does this error occur on the server and is the sheet falsy?\n\n",5:"The clone method cannot be used on the client!\n\n- Are you running in a client-like environment on the server?\n- Are you trying to run SSR on the client?\n\n",6:"Trying to insert a new style tag, but the given Node is unmounted!\n\n- Are you using a custom target that isn't mounted?\n- Does your document not have a valid head element?\n- Have you accidentally removed a style tag manually?\n\n",7:'ThemeProvider: Please return an object from your "theme" prop function, e.g.\n\n```js\ntheme={() => ({})}\n```\n\n',8:'ThemeProvider: Please make your "theme" prop an object.\n\n',9:"Missing document `<head>`\n\n",10:"Cannot find a StyleSheet instance. Usually this happens if there are multiple copies of styled-components loaded at once. Check out this issue for how to troubleshoot and fix the common cases where this situation can happen: https://github.com/styled-components/styled-components/issues/1941#issuecomment-417862021\n\n",11:"_This error was replaced with a dev-time warning, it will be deleted for v4 final._ [createGlobalStyle] received children which will not be rendered. Please use the component without passing children elements.\n\n",12:"It seems you are interpolating a keyframe declaration (%s) into an untagged string. This was supported in styled-components v3, but is not longer supported in v4 as keyframes are now injected on-demand. Please wrap your string in the css\\`\\` helper which ensures the styles are injected correctly. See https://www.styled-components.com/docs/api#css\n\n",13:"%s is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details.\n\n",14:'ThemeProvider: "theme" prop is required.\n\n',15:"A stylis plugin has been supplied that is not named. We need a name for each plugin to be able to prevent styling collisions between different stylis configurations within the same app. Before you pass your plugin to `<StyleSheetManager stylisPlugins={[]}>`, please make sure each plugin is uniquely-named, e.g.\n\n```js\nObject.defineProperty(importedPlugin, 'name', { value: 'some-unique-name' });\n```\n\n",16:"Reached the limit of how many styled components may be created at group %s.\nYou may only create up to 1,073,741,824 components. If you're creating components dynamically,\nas for instance in your render method then you may be running into this limitation.\n\n",17:"CSSStyleSheet could not be found on HTMLStyleElement.\nHas styled-components' style tag been unmounted or altered by another script?\n"}:{};function D(){for(var e=arguments.length<=0?void 0:arguments[0],t=[],n=1,r=arguments.length;n<r;n+=1)t.push(n<0||arguments.length<=n?void 0:arguments[n]);return t.forEach((function(t){e=e.replace(/%[a-z]/,t)})),e}function j(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];throw"production"===process.env.NODE_ENV?new Error("An error occurred. See https://git.io/JUIaE#"+e+" for more information."+(n.length>0?" Args: "+n.join(", "):"")):new Error(D.apply(void 0,[R[e]].concat(n)).trim())}var T=function(){function e(e){this.groupSizes=new Uint32Array(512),this.length=512,this.tag=e}var t=e.prototype;return t.indexOfGroup=function(e){for(var t=0,n=0;n<e;n++)t+=this.groupSizes[n];return t},t.insertRules=function(e,t){if(e>=this.groupSizes.length){for(var n=this.groupSizes,r=n.length,o=r;e>=o;)(o<<=1)<0&&j(16,""+e);this.groupSizes=new Uint32Array(o),this.groupSizes.set(n),this.length=o;for(var s=r;s<o;s++)this.groupSizes[s]=0}for(var i=this.indexOfGroup(e+1),a=0,c=t.length;a<c;a++)this.tag.insertRule(i,t[a])&&(this.groupSizes[e]++,i++)},t.clearGroup=function(e){if(e<this.length){var t=this.groupSizes[e],n=this.indexOfGroup(e),r=n+t;this.groupSizes[e]=0;for(var o=n;o<r;o++)this.tag.deleteRule(n)}},t.getGroup=function(e){var t="";if(e>=this.length||0===this.groupSizes[e])return t;for(var n=this.groupSizes[e],r=this.indexOfGroup(e),o=r+n,s=r;s<o;s++)t+=this.tag.getRule(s)+"/*!sc*/\n";return t},e}(),k=new Map,x=new Map,V=1,B=function(e){if(k.has(e))return k.get(e);for(;x.has(V);)V++;var t=V++;return"production"!==process.env.NODE_ENV&&((0|t)<0||t>1<<30)&&j(16,""+t),k.set(e,t),x.set(t,e),t},M=function(e){return x.get(e)},z=function(e,t){t>=V&&(V=t+1),k.set(e,t),x.set(t,e)},L="style["+A+'][data-styled-version="5.3.1"]',G=new RegExp("^"+A+'\\.g(\\d+)\\[id="([\\w\\d-]+)"\\].*?"([^"]*)'),F=function(e,t,n){for(var r,o=n.split(","),s=0,i=o.length;s<i;s++)(r=o[s])&&e.registerName(t,r)},Y=function(e,t){for(var n=(t.innerHTML||"").split("/*!sc*/\n"),r=[],o=0,s=n.length;o<s;o++){var i=n[o].trim();if(i){var a=i.match(G);if(a){var c=0|parseInt(a[1],10),u=a[2];0!==c&&(z(u,c),F(e,u,a[3]),e.getTag().insertRules(c,r)),r.length=0}else r.push(i)}}},q=function(){return"undefined"!=typeof window&&void 0!==window.__webpack_nonce__?window.__webpack_nonce__:null},H=function(e){var t=document.head,n=e||t,r=document.createElement("style"),o=function(e){for(var t=e.childNodes,n=t.length;n>=0;n--){var r=t[n];if(r&&1===r.nodeType&&r.hasAttribute(A))return r}}(n),s=void 0!==o?o.nextSibling:null;r.setAttribute(A,"active"),r.setAttribute("data-styled-version","5.3.1");var i=q();return i&&r.setAttribute("nonce",i),n.insertBefore(r,s),r},$=function(){function e(e){var t=this.element=H(e);t.appendChild(document.createTextNode("")),this.sheet=function(e){if(e.sheet)return e.sheet;for(var t=document.styleSheets,n=0,r=t.length;n<r;n++){var o=t[n];if(o.ownerNode===e)return o}j(17)}(t),this.length=0}var t=e.prototype;return t.insertRule=function(e,t){try{return this.sheet.insertRule(t,e),this.length++,!0}catch(e){return!1}},t.deleteRule=function(e){this.sheet.deleteRule(e),this.length--},t.getRule=function(e){var t=this.sheet.cssRules[e];return void 0!==t&&"string"==typeof t.cssText?t.cssText:""},e}(),W=function(){function e(e){var t=this.element=H(e);this.nodes=t.childNodes,this.length=0}var t=e.prototype;return t.insertRule=function(e,t){if(e<=this.length&&e>=0){var n=document.createTextNode(t),r=this.nodes[e];return this.element.insertBefore(n,r||null),this.length++,!0}return!1},t.deleteRule=function(e){this.element.removeChild(this.nodes[e]),this.length--},t.getRule=function(e){return e<this.length?this.nodes[e].textContent:""},e}(),U=function(){function e(e){this.rules=[],this.length=0}var t=e.prototype;return t.insertRule=function(e,t){return e<=this.length&&(this.rules.splice(e,0,t),this.length++,!0)},t.deleteRule=function(e){this.rules.splice(e,1),this.length--},t.getRule=function(e){return e<this.length?this.rules[e]:""},e}(),J=I,X={isServer:!I,useCSSOMInjection:!P},Z=function(){function e(e,t,n){void 0===e&&(e=E),void 0===t&&(t={}),this.options=v({},X,{},e),this.gs=t,this.names=new Map(n),this.server=!!e.isServer,!this.server&&I&&J&&(J=!1,function(e){for(var t=document.querySelectorAll(L),n=0,r=t.length;n<r;n++){var o=t[n];o&&"active"!==o.getAttribute(A)&&(Y(e,o),o.parentNode&&o.parentNode.removeChild(o))}}(this))}e.registerId=function(e){return B(e)};var t=e.prototype;return t.reconstructWithOptions=function(t,n){return void 0===n&&(n=!0),new e(v({},this.options,{},t),this.gs,n&&this.names||void 0)},t.allocateGSInstance=function(e){return this.gs[e]=(this.gs[e]||0)+1},t.getTag=function(){return this.tag||(this.tag=(n=(t=this.options).isServer,r=t.useCSSOMInjection,o=t.target,e=n?new U(o):r?new $(o):new W(o),new T(e)));var e,t,n,r,o},t.hasNameForId=function(e,t){return this.names.has(e)&&this.names.get(e).has(t)},t.registerName=function(e,t){if(B(e),this.names.has(e))this.names.get(e).add(t);else{var n=new Set;n.add(t),this.names.set(e,n)}},t.insertRules=function(e,t,n){this.registerName(e,t),this.getTag().insertRules(B(e),n)},t.clearNames=function(e){this.names.has(e)&&this.names.get(e).clear()},t.clearRules=function(e){this.getTag().clearGroup(B(e)),this.clearNames(e)},t.clearTag=function(){this.tag=void 0},t.toString=function(){return function(e){for(var t=e.getTag(),n=t.length,r="",o=0;o<n;o++){var s=M(o);if(void 0!==s){var i=e.names.get(s),a=t.getGroup(o);if(i&&a&&i.size){var c=A+".g"+o+'[id="'+s+'"]',u="";void 0!==i&&i.forEach((function(e){e.length>0&&(u+=e+",")})),r+=""+a+c+'{content:"'+u+'"}/*!sc*/\n'}}}return r}(this)},e}(),K=/(a)(d)/gi,Q=function(e){return String.fromCharCode(e+(e>25?39:97))};function ee(e){var t,n="";for(t=Math.abs(e);t>52;t=t/52|0)n=Q(t%52)+n;return(Q(t%52)+n).replace(K,"$1-$2")}var te=function(e,t){for(var n=t.length;n;)e=33*e^t.charCodeAt(--n);return e},ne=function(e){return te(5381,e)};function re(e){for(var t=0;t<e.length;t+=1){var n=e[t];if(b(n)&&!N(n))return!1}return!0}var oe=ne("5.3.1"),se=function(){function e(e,t,n){this.rules=e,this.staticRulesId="",this.isStatic="production"===process.env.NODE_ENV&&(void 0===n||n.isStatic)&&re(e),this.componentId=t,this.baseHash=te(oe,t),this.baseStyle=n,Z.registerId(t)}return e.prototype.generateAndInjectStyles=function(e,t,n){var r=this.componentId,o=[];if(this.baseStyle&&o.push(this.baseStyle.generateAndInjectStyles(e,t,n)),this.isStatic&&!n.hash)if(this.staticRulesId&&t.hasNameForId(r,this.staticRulesId))o.push(this.staticRulesId);else{var s=Ne(this.rules,e,t,n).join(""),i=ee(te(this.baseHash,s)>>>0);if(!t.hasNameForId(r,i)){var a=n(s,"."+i,void 0,r);t.insertRules(r,i,a)}o.push(i),this.staticRulesId=i}else{for(var c=this.rules.length,u=te(this.baseHash,n.hash),l="",d=0;d<c;d++){var h=this.rules[d];if("string"==typeof h)l+=h,"production"!==process.env.NODE_ENV&&(u=te(u,h+d));else if(h){var p=Ne(h,e,t,n),f=Array.isArray(p)?p.join(""):p;u=te(u,f+d),l+=f}}if(l){var m=ee(u>>>0);if(!t.hasNameForId(r,m)){var y=n(l,"."+m,void 0,r);t.insertRules(r,m,y)}o.push(m)}}return o.join(" ")},e}(),ie=/^\s*\/\/.*$/gm,ae=[":","[",".","#"];function ce(e){var t,n,r,o,s=void 0===e?E:e,i=s.options,a=void 0===i?E:i,c=s.plugins,u=void 0===c?w:c,l=new p(a),d=[],h=function(e){function t(t){if(t)try{e(t+"}")}catch(e){}}return function(n,r,o,s,i,a,c,u,l,d){switch(n){case 1:if(0===l&&64===r.charCodeAt(0))return e(r+";"),"";break;case 2:if(0===u)return r+"/*|*/";break;case 3:switch(u){case 102:case 112:return e(o[0]+r),"";default:return r+(0===d?"/*|*/":"")}case-2:r.split("/*|*/}").forEach(t)}}}((function(e){d.push(e)})),f=function(e,r,s){return 0===r&&-1!==ae.indexOf(s[n.length])||s.match(o)?e:"."+t};function m(e,s,i,a){void 0===a&&(a="&");var c=e.replace(ie,""),u=s&&i?i+" "+s+" { "+c+" }":c;return t=a,n=s,r=new RegExp("\\"+n+"\\b","g"),o=new RegExp("(\\"+n+"\\b){2,}"),l(i||!s?"":s,u)}return l.use([].concat(u,[function(e,t,o){2===e&&o.length&&o[0].lastIndexOf(n)>0&&(o[0]=o[0].replace(r,f))},h,function(e){if(-2===e){var t=d;return d=[],t}}])),m.hash=u.length?u.reduce((function(e,t){return t.name||j(15),te(e,t.name)}),5381).toString():"",m}var ue=r.createContext(),le=ue.Consumer,de=r.createContext(),he=(de.Consumer,new Z),pe=ce();function fe(){return s(ue)||he}function me(){return s(de)||pe}function ye(e){var t=o(e.stylisPlugins),n=t[0],s=t[1],c=fe(),u=i((function(){var t=c;return e.sheet?t=e.sheet:e.target&&(t=t.reconstructWithOptions({target:e.target},!1)),e.disableCSSOMInjection&&(t=t.reconstructWithOptions({useCSSOMInjection:!1})),t}),[e.disableCSSOMInjection,e.sheet,e.target]),l=i((function(){return ce({options:{prefix:!e.disableVendorPrefixes},plugins:n})}),[e.disableVendorPrefixes,n]);return a((function(){h(n,e.stylisPlugins)||s(e.stylisPlugins)}),[e.stylisPlugins]),r.createElement(ue.Provider,{value:u},r.createElement(de.Provider,{value:l},"production"!==process.env.NODE_ENV?r.Children.only(e.children):e.children))}var ve=function(){function e(e,t){var n=this;this.inject=function(e,t){void 0===t&&(t=pe);var r=n.name+t.hash;e.hasNameForId(n.id,r)||e.insertRules(n.id,r,t(n.rules,r,"@keyframes"))},this.toString=function(){return j(12,String(n.name))},this.name=e,this.id="sc-keyframes-"+e,this.rules=t}return e.prototype.getName=function(e){return void 0===e&&(e=pe),this.name+e.hash},e}(),ge=/([A-Z])/,Se=/([A-Z])/g,we=/^ms-/,Ee=function(e){return"-"+e.toLowerCase()};function be(e){return ge.test(e)?e.replace(Se,Ee).replace(we,"-ms-"):e}var _e=function(e){return null==e||!1===e||""===e};function Ne(e,n,r,o){if(Array.isArray(e)){for(var s,i=[],a=0,c=e.length;a<c;a+=1)""!==(s=Ne(e[a],n,r,o))&&(Array.isArray(s)?i.push.apply(i,s):i.push(s));return i}if(_e(e))return"";if(N(e))return"."+e.styledComponentId;if(b(e)){if("function"!=typeof(l=e)||l.prototype&&l.prototype.isReactComponent||!n)return e;var u=e(n);return"production"!==process.env.NODE_ENV&&t(u)&&console.warn(_(e)+" is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details."),Ne(u,n,r,o)}var l;return e instanceof ve?r?(e.inject(r,o),e.getName(o)):e:S(e)?function e(t,n){var r,o,s=[];for(var i in t)t.hasOwnProperty(i)&&!_e(t[i])&&(Array.isArray(t[i])&&t[i].isCss||b(t[i])?s.push(be(i)+":",t[i],";"):S(t[i])?s.push.apply(s,e(t[i],i)):s.push(be(i)+": "+(r=i,null==(o=t[i])||"boolean"==typeof o||""===o?"":"number"!=typeof o||0===o||r in f?String(o).trim():o+"px")+";"));return n?[n+" {"].concat(s,["}"]):s}(e):e.toString()}var Ae=function(e){return Array.isArray(e)&&(e.isCss=!0),e};function Ce(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return b(e)||S(e)?Ae(Ne(g(w,[e].concat(n)))):0===n.length&&1===e.length&&"string"==typeof e[0]?e:Ae(Ne(g(e,n)))}var Ie=/invalid hook call/i,Pe=new Set,Oe=function(e,t){if("production"!==process.env.NODE_ENV){var n="The component "+e+(t?' with the id of "'+t+'"':"")+" has been created dynamically.\nYou may see this warning because you've called styled inside another component.\nTo resolve this only create new StyledComponents outside of any render method and function component.",r=console.error;try{var o=!0;console.error=function(e){if(Ie.test(e))o=!1,Pe.delete(n);else{for(var t=arguments.length,s=new Array(t>1?t-1:0),i=1;i<t;i++)s[i-1]=arguments[i];r.apply(void 0,[e].concat(s))}},c(),o&&!Pe.has(n)&&(console.warn(n),Pe.add(n))}catch(e){Ie.test(e.message)&&Pe.delete(n)}finally{console.error=r}}},Re=function(e,t,n){return void 0===n&&(n=E),e.theme!==n.theme&&e.theme||t||n.theme},De=/[!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~-]+/g,je=/(^-|-$)/g;function Te(e){return e.replace(De,"-").replace(je,"")}var ke=function(e){return ee(ne(e)>>>0)};function xe(e){return"string"==typeof e&&("production"===process.env.NODE_ENV||e.charAt(0)===e.charAt(0).toLowerCase())}var Ve=function(e){return"function"==typeof e||"object"==typeof e&&null!==e&&!Array.isArray(e)},Be=function(e){return"__proto__"!==e&&"constructor"!==e&&"prototype"!==e};function Me(e,t,n){var r=e[n];Ve(t)&&Ve(r)?ze(r,t):e[n]=t}function ze(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];for(var o=0,s=n;o<s.length;o++){var i=s[o];if(Ve(i))for(var a in i)Be(a)&&Me(e,i[a],a)}return e}var Le=r.createContext(),Ge=Le.Consumer;function Fe(e){var t=s(Le),n=i((function(){return function(e,t){if(!e)return j(14);if(b(e)){var n=e(t);return"production"===process.env.NODE_ENV||null!==n&&!Array.isArray(n)&&"object"==typeof n?n:j(7)}return Array.isArray(e)||"object"!=typeof e?j(8):t?v({},t,{},e):e}(e.theme,t)}),[e.theme,t]);return e.children?r.createElement(Le.Provider,{value:n},e.children):null}var Ye={};function qe(e,t,n){var o=N(e),i=!xe(e),a=t.attrs,c=void 0===a?w:a,d=t.componentId,h=void 0===d?function(e,t){var n="string"!=typeof e?"sc":Te(e);Ye[n]=(Ye[n]||0)+1;var r=n+"-"+ke("5.3.1"+n+Ye[n]);return t?t+"-"+r:r}(t.displayName,t.parentComponentId):d,p=t.displayName,f=void 0===p?function(e){return xe(e)?"styled."+e:"Styled("+_(e)+")"}(e):p,g=t.displayName&&t.componentId?Te(t.displayName)+"-"+t.componentId:t.componentId||h,S=o&&e.attrs?Array.prototype.concat(e.attrs,c).filter(Boolean):c,A=t.shouldForwardProp;o&&e.shouldForwardProp&&(A=t.shouldForwardProp?function(n,r,o){return e.shouldForwardProp(n,r,o)&&t.shouldForwardProp(n,r,o)}:e.shouldForwardProp);var C,I=new se(n,g,o?e.componentStyle:void 0),P=I.isStatic&&0===c.length,O=function(e,t){return function(e,t,n,r){var o=e.attrs,i=e.componentStyle,a=e.defaultProps,c=e.foldedComponentIds,d=e.shouldForwardProp,h=e.styledComponentId,p=e.target;"production"!==process.env.NODE_ENV&&l(h);var f=function(e,t,n){void 0===e&&(e=E);var r=v({},t,{theme:e}),o={};return n.forEach((function(e){var t,n,s,i=e;for(t in b(i)&&(i=i(r)),i)r[t]=o[t]="className"===t?(n=o[t],s=i[t],n&&s?n+" "+s:n||s):i[t]})),[r,o]}(Re(t,s(Le),a)||E,t,o),y=f[0],g=f[1],S=function(e,t,n,r){var o=fe(),s=me(),i=t?e.generateAndInjectStyles(E,o,s):e.generateAndInjectStyles(n,o,s);return"production"!==process.env.NODE_ENV&&l(i),"production"!==process.env.NODE_ENV&&!t&&r&&r(i),i}(i,r,y,"production"!==process.env.NODE_ENV?e.warnTooManyClasses:void 0),w=n,_=g.$as||t.$as||g.as||t.as||p,N=xe(_),A=g!==t?v({},t,{},g):t,C={};for(var I in A)"$"!==I[0]&&"as"!==I&&("forwardedAs"===I?C.as=A[I]:(d?d(I,m,_):!N||m(I))&&(C[I]=A[I]));return t.style&&g.style!==t.style&&(C.style=v({},t.style,{},g.style)),C.className=Array.prototype.concat(c,h,S!==h?S:null,t.className,g.className).filter(Boolean).join(" "),C.ref=w,u(_,C)}(C,e,t,P)};return O.displayName=f,(C=r.forwardRef(O)).attrs=S,C.componentStyle=I,C.displayName=f,C.shouldForwardProp=A,C.foldedComponentIds=o?Array.prototype.concat(e.foldedComponentIds,e.styledComponentId):w,C.styledComponentId=g,C.target=o?e.target:e,C.withComponent=function(e){var r=t.componentId,o=function(e,t){if(null==e)return{};var n,r,o={},s=Object.keys(e);for(r=0;r<s.length;r++)n=s[r],t.indexOf(n)>=0||(o[n]=e[n]);return o}(t,["componentId"]),s=r&&r+"-"+(xe(e)?e:Te(_(e)));return qe(e,v({},o,{attrs:S,componentId:s}),n)},Object.defineProperty(C,"defaultProps",{get:function(){return this._foldedDefaultProps},set:function(t){this._foldedDefaultProps=o?ze({},e.defaultProps,t):t}}),"production"!==process.env.NODE_ENV&&(Oe(f,g),C.warnTooManyClasses=function(e,t){var n={},r=!1;return function(o){if(!r&&(n[o]=!0,Object.keys(n).length>=200)){var s=t?' with the id of "'+t+'"':"";console.warn("Over 200 classes were generated for component "+e+s+".\nConsider using the attrs method, together with a style object for frequently changed styles.\nExample:\n const Component = styled.div.attrs(props => ({\n style: {\n background: props.background,\n },\n }))`width: 100%;`\n\n <Component />"),r=!0,n={}}}}(f,g)),C.toString=function(){return"."+C.styledComponentId},i&&y(C,e,{attrs:!0,componentStyle:!0,displayName:!0,foldedComponentIds:!0,shouldForwardProp:!0,styledComponentId:!0,target:!0,withComponent:!0}),C}var He=function(e){return function e(t,r,o){if(void 0===o&&(o=E),!n(r))return j(1,String(r));var s=function(){return t(r,o,Ce.apply(void 0,arguments))};return s.withConfig=function(n){return e(t,r,v({},o,{},n))},s.attrs=function(n){return e(t,r,v({},o,{attrs:Array.prototype.concat(o.attrs,n).filter(Boolean)}))},s}(qe,e)};["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","big","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","keygen","label","legend","li","link","main","map","mark","marquee","menu","menuitem","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","small","source","span","strong","style","sub","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr","circle","clipPath","defs","ellipse","foreignObject","g","image","line","linearGradient","marker","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","svg","text","textPath","tspan"].forEach((function(e){He[e]=He(e)}));var $e=function(){function e(e,t){this.rules=e,this.componentId=t,this.isStatic=re(e),Z.registerId(this.componentId+1)}var t=e.prototype;return t.createStyles=function(e,t,n,r){var o=r(Ne(this.rules,t,n,r).join(""),""),s=this.componentId+e;n.insertRules(s,s,o)},t.removeStyles=function(e,t){t.clearRules(this.componentId+e)},t.renderStyles=function(e,t,n,r){e>2&&Z.registerId(this.componentId+e),this.removeStyles(e,n),this.createStyles(e,t,n,r)},e}();function We(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];var i=Ce.apply(void 0,[e].concat(n)),a="sc-global-"+ke(JSON.stringify(i)),u=new $e(i,a);function l(e){var t=fe(),n=me(),o=s(Le),l=c(t.allocateGSInstance(a)).current;return"production"!==process.env.NODE_ENV&&r.Children.count(e.children)&&console.warn("The global style component "+a+" was given child JSX. createGlobalStyle does not render children."),"production"!==process.env.NODE_ENV&&i.some((function(e){return"string"==typeof e&&-1!==e.indexOf("@import")}))&&console.warn("Please do not use @import CSS syntax in createGlobalStyle at this time, as the CSSOM APIs we use in production do not handle it well. Instead, we recommend using a library such as react-helmet to inject a typical <link> meta tag to the stylesheet, or simply embedding it manually in your index.html <head> section for a simpler app."),t.server&&h(l,e,t,o,n),d((function(){if(!t.server)return h(l,e,t,o,n),function(){return u.removeStyles(l,t)}}),[l,e,t,o,n]),null}function h(e,t,n,r,o){if(u.isStatic)u.renderStyles(e,O,n,o);else{var s=v({},t,{theme:Re(t,r,l.defaultProps)});u.renderStyles(e,s,n,o)}}return"production"!==process.env.NODE_ENV&&Oe(a),r.memo(l)}function Ue(e){"production"!==process.env.NODE_ENV&&"undefined"!=typeof navigator&&"ReactNative"===navigator.product&&console.warn("`keyframes` cannot be used on ReactNative, only on the web. To do animation in ReactNative please use Animated.");for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];var o=Ce.apply(void 0,[e].concat(n)).join(""),s=ke(o);return new ve(s,o)}var Je=function(){function e(){var e=this;this._emitSheetCSS=function(){var t=e.instance.toString();if(!t)return"";var n=q();return"<style "+[n&&'nonce="'+n+'"',A+'="true"','data-styled-version="5.3.1"'].filter(Boolean).join(" ")+">"+t+"</style>"},this.getStyleTags=function(){return e.sealed?j(2):e._emitSheetCSS()},this.getStyleElement=function(){var t;if(e.sealed)return j(2);var n=((t={})[A]="",t["data-styled-version"]="5.3.1",t.dangerouslySetInnerHTML={__html:e.instance.toString()},t),o=q();return o&&(n.nonce=o),[r.createElement("style",v({},n,{key:"sc-0-0"}))]},this.seal=function(){e.sealed=!0},this.instance=new Z({isServer:!0}),this.sealed=!1}var t=e.prototype;return t.collectStyles=function(e){return this.sealed?j(2):r.createElement(ye,{sheet:this.instance},e)},t.interleaveWithNodeStream=function(e){return j(3)},e}(),Xe=function(e){var t=r.forwardRef((function(t,n){var o=s(Le),i=e.defaultProps,a=Re(t,o,i);return"production"!==process.env.NODE_ENV&&void 0===a&&console.warn('[withTheme] You are not using a ThemeProvider nor passing a theme prop or a theme in defaultProps in component class "'+_(e)+'"'),r.createElement(e,v({},t,{theme:a,ref:n}))}));return y(t,e),t.displayName="WithTheme("+_(e)+")",t},Ze=function(){return s(Le)},Ke={StyleSheet:Z,masterSheet:he};"production"!==process.env.NODE_ENV&&"undefined"!=typeof navigator&&"ReactNative"===navigator.product&&console.warn("It looks like you've imported 'styled-components' on React Native.\nPerhaps you're looking to import 'styled-components/native'?\nRead more about this at https://www.styled-components.com/docs/basics#react-native"),"production"!==process.env.NODE_ENV&&"test"!==process.env.NODE_ENV&&"undefined"!=typeof window&&(window["__styled-components-init__"]=window["__styled-components-init__"]||0,1===window["__styled-components-init__"]&&console.warn("It looks like there are several instances of 'styled-components' initialized in this application. This may cause dynamic styles to not render properly, errors during the rehydration process, a missing theme prop, and makes your application bigger without good reason.\n\nSee https://s-c.sh/2BAXzed for more info."),window["__styled-components-init__"]+=1);export default He;export{Je as ServerStyleSheet,le as StyleSheetConsumer,ue as StyleSheetContext,ye as StyleSheetManager,Ge as ThemeConsumer,Le as ThemeContext,Fe as ThemeProvider,Ke as __PRIVATE__,We as createGlobalStyle,Ce as css,N as isStyledComponent,Ue as keyframes,Ze as useTheme,C as version,Xe as withTheme};
0.8
Source map: webpack://frontend-mybets/../../node_modules/styled-components/dist/styled-components.browser.esm.js
import{typeOf as e,isElement as t,isValidElementType as n}from"react-is";import r,{useState as o,useContext as s,useMemo as i,useEffect as a,useRef as c,createElement as u,useDebugValue as l,useLayoutEffect as d}from"react";import h from"shallowequal";import p from"@emotion/stylis";import f from"@emotion/unitless";import m from"@emotion/is-prop-valid";import y from"hoist-non-react-statics";function v(){return(v=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}var g=function(e,t){for(var n=[e[0]],r=0,o=t.length;r<o;r+=1)n.push(t[r],e[r+1]);return n},S=function(t){return null!==t&&"object"==typeof t&&"[object Object]"===(t.toString?t.toString():Object.prototype.toString.call(t))&&!e(t)},w=Object.freeze([]),E=Object.freeze({});function b(e){return"function"==typeof e}function _(e){return"production"!==process.env.NODE_ENV&&"string"==typeof e&&e||e.displayName||e.name||"Component"}function N(e){return e&&"string"==typeof e.styledComponentId}var A="undefined"!=typeof process&&(process.env.REACT_APP_SC_ATTR||process.env.SC_ATTR)||"data-styled",C="5.3.1",I="undefined"!=typeof window&&"HTMLElement"in window,P=Boolean("boolean"==typeof SC_DISABLE_SPEEDY?SC_DISABLE_SPEEDY:"undefined"!=typeof process&&void 0!==process.env.REACT_APP_SC_DISABLE_SPEEDY&&""!==process.env.REACT_APP_SC_DISABLE_SPEEDY?"false"!==process.env.REACT_APP_SC_DISABLE_SPEEDY&&process.env.REACT_APP_SC_DISABLE_SPEEDY:"undefined"!=typeof process&&void 0!==process.env.SC_DISABLE_SPEEDY&&""!==process.env.SC_DISABLE_SPEEDY?"false"!==process.env.SC_DISABLE_SPEEDY&&process.env.SC_DISABLE_SPEEDY:"production"!==process.env.NODE_ENV),O={},R="production"!==process.env.NODE_ENV?{1:"Cannot create styled-component for component: %s.\n\n",2:"Can't collect styles once you've consumed a `ServerStyleSheet`'s styles! `ServerStyleSheet` is a one off instance for each server-side render cycle.\n\n- Are you trying to reuse it across renders?\n- Are you accidentally calling collectStyles twice?\n\n",3:"Streaming SSR is only supported in a Node.js environment; Please do not try to call this method in the browser.\n\n",4:"The `StyleSheetManager` expects a valid target or sheet prop!\n\n- Does this error occur on the client and is your target falsy?\n- Does this error occur on the server and is the sheet falsy?\n\n",5:"The clone method cannot be used on the client!\n\n- Are you running in a client-like environment on the server?\n- Are you trying to run SSR on the client?\n\n",6:"Trying to insert a new style tag, but the given Node is unmounted!\n\n- Are you using a custom target that isn't mounted?\n- Does your document not have a valid head element?\n- Have you accidentally removed a style tag manually?\n\n",7:'ThemeProvider: Please return an object from your "theme" prop function, e.g.\n\n```js\ntheme={() => ({})}\n```\n\n',8:'ThemeProvider: Please make your "theme" prop an object.\n\n',9:"Missing document `<head>`\n\n",10:"Cannot find a StyleSheet instance. Usually this happens if there are multiple copies of styled-components loaded at once. Check out this issue for how to troubleshoot and fix the common cases where this situation can happen: https://github.com/styled-components/styled-components/issues/1941#issuecomment-417862021\n\n",11:"_This error was replaced with a dev-time warning, it will be deleted for v4 final._ [createGlobalStyle] received children which will not be rendered. Please use the component without passing children elements.\n\n",12:"It seems you are interpolating a keyframe declaration (%s) into an untagged string. This was supported in styled-components v3, but is not longer supported in v4 as keyframes are now injected on-demand. Please wrap your string in the css\\`\\` helper which ensures the styles are injected correctly. See https://www.styled-components.com/docs/api#css\n\n",13:"%s is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details.\n\n",14:'ThemeProvider: "theme" prop is required.\n\n',15:"A stylis plugin has been supplied that is not named. We need a name for each plugin to be able to prevent styling collisions between different stylis configurations within the same app. Before you pass your plugin to `<StyleSheetManager stylisPlugins={[]}>`, please make sure each plugin is uniquely-named, e.g.\n\n```js\nObject.defineProperty(importedPlugin, 'name', { value: 'some-unique-name' });\n```\n\n",16:"Reached the limit of how many styled components may be created at group %s.\nYou may only create up to 1,073,741,824 components. If you're creating components dynamically,\nas for instance in your render method then you may be running into this limitation.\n\n",17:"CSSStyleSheet could not be found on HTMLStyleElement.\nHas styled-components' style tag been unmounted or altered by another script?\n"}:{};function D(){for(var e=arguments.length<=0?void 0:arguments[0],t=[],n=1,r=arguments.length;n<r;n+=1)t.push(n<0||arguments.length<=n?void 0:arguments[n]);return t.forEach((function(t){e=e.replace(/%[a-z]/,t)})),e}function j(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];throw"production"===process.env.NODE_ENV?new Error("An error occurred. See https://git.io/JUIaE#"+e+" for more information."+(n.length>0?" Args: "+n.join(", "):"")):new Error(D.apply(void 0,[R[e]].concat(n)).trim())}var T=function(){function e(e){this.groupSizes=new Uint32Array(512),this.length=512,this.tag=e}var t=e.prototype;return t.indexOfGroup=function(e){for(var t=0,n=0;n<e;n++)t+=this.groupSizes[n];return t},t.insertRules=function(e,t){if(e>=this.groupSizes.length){for(var n=this.groupSizes,r=n.length,o=r;e>=o;)(o<<=1)<0&&j(16,""+e);this.groupSizes=new Uint32Array(o),this.groupSizes.set(n),this.length=o;for(var s=r;s<o;s++)this.groupSizes[s]=0}for(var i=this.indexOfGroup(e+1),a=0,c=t.length;a<c;a++)this.tag.insertRule(i,t[a])&&(this.groupSizes[e]++,i++)},t.clearGroup=function(e){if(e<this.length){var t=this.groupSizes[e],n=this.indexOfGroup(e),r=n+t;this.groupSizes[e]=0;for(var o=n;o<r;o++)this.tag.deleteRule(n)}},t.getGroup=function(e){var t="";if(e>=this.length||0===this.groupSizes[e])return t;for(var n=this.groupSizes[e],r=this.indexOfGroup(e),o=r+n,s=r;s<o;s++)t+=this.tag.getRule(s)+"/*!sc*/\n";return t},e}(),k=new Map,x=new Map,V=1,B=function(e){if(k.has(e))return k.get(e);for(;x.has(V);)V++;var t=V++;return"production"!==process.env.NODE_ENV&&((0|t)<0||t>1<<30)&&j(16,""+t),k.set(e,t),x.set(t,e),t},M=function(e){return x.get(e)},z=function(e,t){t>=V&&(V=t+1),k.set(e,t),x.set(t,e)},L="style["+A+'][data-styled-version="5.3.1"]',G=new RegExp("^"+A+'\\.g(\\d+)\\[id="([\\w\\d-]+)"\\].*?"([^"]*)'),F=function(e,t,n){for(var r,o=n.split(","),s=0,i=o.length;s<i;s++)(r=o[s])&&e.registerName(t,r)},Y=function(e,t){for(var n=(t.innerHTML||"").split("/*!sc*/\n"),r=[],o=0,s=n.length;o<s;o++){var i=n[o].trim();if(i){var a=i.match(G);if(a){var c=0|parseInt(a[1],10),u=a[2];0!==c&&(z(u,c),F(e,u,a[3]),e.getTag().insertRules(c,r)),r.length=0}else r.push(i)}}},q=function(){return"undefined"!=typeof window&&void 0!==window.__webpack_nonce__?window.__webpack_nonce__:null},H=function(e){var t=document.head,n=e||t,r=document.createElement("style"),o=function(e){for(var t=e.childNodes,n=t.length;n>=0;n--){var r=t[n];if(r&&1===r.nodeType&&r.hasAttribute(A))return r}}(n),s=void 0!==o?o.nextSibling:null;r.setAttribute(A,"active"),r.setAttribute("data-styled-version","5.3.1");var i=q();return i&&r.setAttribute("nonce",i),n.insertBefore(r,s),r},$=function(){function e(e){var t=this.element=H(e);t.appendChild(document.createTextNode("")),this.sheet=function(e){if(e.sheet)return e.sheet;for(var t=document.styleSheets,n=0,r=t.length;n<r;n++){var o=t[n];if(o.ownerNode===e)return o}j(17)}(t),this.length=0}var t=e.prototype;return t.insertRule=function(e,t){try{return this.sheet.insertRule(t,e),this.length++,!0}catch(e){return!1}},t.deleteRule=function(e){this.sheet.deleteRule(e),this.length--},t.getRule=function(e){var t=this.sheet.cssRules[e];return void 0!==t&&"string"==typeof t.cssText?t.cssText:""},e}(),W=function(){function e(e){var t=this.element=H(e);this.nodes=t.childNodes,this.length=0}var t=e.prototype;return t.insertRule=function(e,t){if(e<=this.length&&e>=0){var n=document.createTextNode(t),r=this.nodes[e];return this.element.insertBefore(n,r||null),this.length++,!0}return!1},t.deleteRule=function(e){this.element.removeChild(this.nodes[e]),this.length--},t.getRule=function(e){return e<this.length?this.nodes[e].textContent:""},e}(),U=function(){function e(e){this.rules=[],this.length=0}var t=e.prototype;return t.insertRule=function(e,t){return e<=this.length&&(this.rules.splice(e,0,t),this.length++,!0)},t.deleteRule=function(e){this.rules.splice(e,1),this.length--},t.getRule=function(e){return e<this.length?this.rules[e]:""},e}(),J=I,X={isServer:!I,useCSSOMInjection:!P},Z=function(){function e(e,t,n){void 0===e&&(e=E),void 0===t&&(t={}),this.options=v({},X,{},e),this.gs=t,this.names=new Map(n),this.server=!!e.isServer,!this.server&&I&&J&&(J=!1,function(e){for(var t=document.querySelectorAll(L),n=0,r=t.length;n<r;n++){var o=t[n];o&&"active"!==o.getAttribute(A)&&(Y(e,o),o.parentNode&&o.parentNode.removeChild(o))}}(this))}e.registerId=function(e){return B(e)};var t=e.prototype;return t.reconstructWithOptions=function(t,n){return void 0===n&&(n=!0),new e(v({},this.options,{},t),this.gs,n&&this.names||void 0)},t.allocateGSInstance=function(e){return this.gs[e]=(this.gs[e]||0)+1},t.getTag=function(){return this.tag||(this.tag=(n=(t=this.options).isServer,r=t.useCSSOMInjection,o=t.target,e=n?new U(o):r?new $(o):new W(o),new T(e)));var e,t,n,r,o},t.hasNameForId=function(e,t){return this.names.has(e)&&this.names.get(e).has(t)},t.registerName=function(e,t){if(B(e),this.names.has(e))this.names.get(e).add(t);else{var n=new Set;n.add(t),this.names.set(e,n)}},t.insertRules=function(e,t,n){this.registerName(e,t),this.getTag().insertRules(B(e),n)},t.clearNames=function(e){this.names.has(e)&&this.names.get(e).clear()},t.clearRules=function(e){this.getTag().clearGroup(B(e)),this.clearNames(e)},t.clearTag=function(){this.tag=void 0},t.toString=function(){return function(e){for(var t=e.getTag(),n=t.length,r="",o=0;o<n;o++){var s=M(o);if(void 0!==s){var i=e.names.get(s),a=t.getGroup(o);if(i&&a&&i.size){var c=A+".g"+o+'[id="'+s+'"]',u="";void 0!==i&&i.forEach((function(e){e.length>0&&(u+=e+",")})),r+=""+a+c+'{content:"'+u+'"}/*!sc*/\n'}}}return r}(this)},e}(),K=/(a)(d)/gi,Q=function(e){return String.fromCharCode(e+(e>25?39:97))};function ee(e){var t,n="";for(t=Math.abs(e);t>52;t=t/52|0)n=Q(t%52)+n;return(Q(t%52)+n).replace(K,"$1-$2")}var te=function(e,t){for(var n=t.length;n;)e=33*e^t.charCodeAt(--n);return e},ne=function(e){return te(5381,e)};function re(e){for(var t=0;t<e.length;t+=1){var n=e[t];if(b(n)&&!N(n))return!1}return!0}var oe=ne("5.3.1"),se=function(){function e(e,t,n){this.rules=e,this.staticRulesId="",this.isStatic="production"===process.env.NODE_ENV&&(void 0===n||n.isStatic)&&re(e),this.componentId=t,this.baseHash=te(oe,t),this.baseStyle=n,Z.registerId(t)}return e.prototype.generateAndInjectStyles=function(e,t,n){var r=this.componentId,o=[];if(this.baseStyle&&o.push(this.baseStyle.generateAndInjectStyles(e,t,n)),this.isStatic&&!n.hash)if(this.staticRulesId&&t.hasNameForId(r,this.staticRulesId))o.push(this.staticRulesId);else{var s=Ne(this.rules,e,t,n).join(""),i=ee(te(this.baseHash,s)>>>0);if(!t.hasNameForId(r,i)){var a=n(s,"."+i,void 0,r);t.insertRules(r,i,a)}o.push(i),this.staticRulesId=i}else{for(var c=this.rules.length,u=te(this.baseHash,n.hash),l="",d=0;d<c;d++){var h=this.rules[d];if("string"==typeof h)l+=h,"production"!==process.env.NODE_ENV&&(u=te(u,h+d));else if(h){var p=Ne(h,e,t,n),f=Array.isArray(p)?p.join(""):p;u=te(u,f+d),l+=f}}if(l){var m=ee(u>>>0);if(!t.hasNameForId(r,m)){var y=n(l,"."+m,void 0,r);t.insertRules(r,m,y)}o.push(m)}}return o.join(" ")},e}(),ie=/^\s*\/\/.*$/gm,ae=[":","[",".","#"];function ce(e){var t,n,r,o,s=void 0===e?E:e,i=s.options,a=void 0===i?E:i,c=s.plugins,u=void 0===c?w:c,l=new p(a),d=[],h=function(e){function t(t){if(t)try{e(t+"}")}catch(e){}}return function(n,r,o,s,i,a,c,u,l,d){switch(n){case 1:if(0===l&&64===r.charCodeAt(0))return e(r+";"),"";break;case 2:if(0===u)return r+"/*|*/";break;case 3:switch(u){case 102:case 112:return e(o[0]+r),"";default:return r+(0===d?"/*|*/":"")}case-2:r.split("/*|*/}").forEach(t)}}}((function(e){d.push(e)})),f=function(e,r,s){return 0===r&&-1!==ae.indexOf(s[n.length])||s.match(o)?e:"."+t};function m(e,s,i,a){void 0===a&&(a="&");var c=e.replace(ie,""),u=s&&i?i+" "+s+" { "+c+" }":c;return t=a,n=s,r=new RegExp("\\"+n+"\\b","g"),o=new RegExp("(\\"+n+"\\b){2,}"),l(i||!s?"":s,u)}return l.use([].concat(u,[function(e,t,o){2===e&&o.length&&o[0].lastIndexOf(n)>0&&(o[0]=o[0].replace(r,f))},h,function(e){if(-2===e){var t=d;return d=[],t}}])),m.hash=u.length?u.reduce((function(e,t){return t.name||j(15),te(e,t.name)}),5381).toString():"",m}var ue=r.createContext(),le=ue.Consumer,de=r.createContext(),he=(de.Consumer,new Z),pe=ce();function fe(){return s(ue)||he}function me(){return s(de)||pe}function ye(e){var t=o(e.stylisPlugins),n=t[0],s=t[1],c=fe(),u=i((function(){var t=c;return e.sheet?t=e.sheet:e.target&&(t=t.reconstructWithOptions({target:e.target},!1)),e.disableCSSOMInjection&&(t=t.reconstructWithOptions({useCSSOMInjection:!1})),t}),[e.disableCSSOMInjection,e.sheet,e.target]),l=i((function(){return ce({options:{prefix:!e.disableVendorPrefixes},plugins:n})}),[e.disableVendorPrefixes,n]);return a((function(){h(n,e.stylisPlugins)||s(e.stylisPlugins)}),[e.stylisPlugins]),r.createElement(ue.Provider,{value:u},r.createElement(de.Provider,{value:l},"production"!==process.env.NODE_ENV?r.Children.only(e.children):e.children))}var ve=function(){function e(e,t){var n=this;this.inject=function(e,t){void 0===t&&(t=pe);var r=n.name+t.hash;e.hasNameForId(n.id,r)||e.insertRules(n.id,r,t(n.rules,r,"@keyframes"))},this.toString=function(){return j(12,String(n.name))},this.name=e,this.id="sc-keyframes-"+e,this.rules=t}return e.prototype.getName=function(e){return void 0===e&&(e=pe),this.name+e.hash},e}(),ge=/([A-Z])/,Se=/([A-Z])/g,we=/^ms-/,Ee=function(e){return"-"+e.toLowerCase()};function be(e){return ge.test(e)?e.replace(Se,Ee).replace(we,"-ms-"):e}var _e=function(e){return null==e||!1===e||""===e};function Ne(e,n,r,o){if(Array.isArray(e)){for(var s,i=[],a=0,c=e.length;a<c;a+=1)""!==(s=Ne(e[a],n,r,o))&&(Array.isArray(s)?i.push.apply(i,s):i.push(s));return i}if(_e(e))return"";if(N(e))return"."+e.styledComponentId;if(b(e)){if("function"!=typeof(l=e)||l.prototype&&l.prototype.isReactComponent||!n)return e;var u=e(n);return"production"!==process.env.NODE_ENV&&t(u)&&console.warn(_(e)+" is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details."),Ne(u,n,r,o)}var l;return e instanceof ve?r?(e.inject(r,o),e.getName(o)):e:S(e)?function e(t,n){var r,o,s=[];for(var i in t)t.hasOwnProperty(i)&&!_e(t[i])&&(Array.isArray(t[i])&&t[i].isCss||b(t[i])?s.push(be(i)+":",t[i],";"):S(t[i])?s.push.apply(s,e(t[i],i)):s.push(be(i)+": "+(r=i,null==(o=t[i])||"boolean"==typeof o||""===o?"":"number"!=typeof o||0===o||r in f?String(o).trim():o+"px")+";"));return n?[n+" {"].concat(s,["}"]):s}(e):e.toString()}var Ae=function(e){return Array.isArray(e)&&(e.isCss=!0),e};function Ce(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return b(e)||S(e)?Ae(Ne(g(w,[e].concat(n)))):0===n.length&&1===e.length&&"string"==typeof e[0]?e:Ae(Ne(g(e,n)))}var Ie=/invalid hook call/i,Pe=new Set,Oe=function(e,t){if("production"!==process.env.NODE_ENV){var n="The component "+e+(t?' with the id of "'+t+'"':"")+" has been created dynamically.\nYou may see this warning because you've called styled inside another component.\nTo resolve this only create new StyledComponents outside of any render method and function component.",r=console.error;try{var o=!0;console.error=function(e){if(Ie.test(e))o=!1,Pe.delete(n);else{for(var t=arguments.length,s=new Array(t>1?t-1:0),i=1;i<t;i++)s[i-1]=arguments[i];r.apply(void 0,[e].concat(s))}},c(),o&&!Pe.has(n)&&(console.warn(n),Pe.add(n))}catch(e){Ie.test(e.message)&&Pe.delete(n)}finally{console.error=r}}},Re=function(e,t,n){return void 0===n&&(n=E),e.theme!==n.theme&&e.theme||t||n.theme},De=/[!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~-]+/g,je=/(^-|-$)/g;function Te(e){return e.replace(De,"-").replace(je,"")}var ke=function(e){return ee(ne(e)>>>0)};function xe(e){return"string"==typeof e&&("production"===process.env.NODE_ENV||e.charAt(0)===e.charAt(0).toLowerCase())}var Ve=function(e){return"function"==typeof e||"object"==typeof e&&null!==e&&!Array.isArray(e)},Be=function(e){return"__proto__"!==e&&"constructor"!==e&&"prototype"!==e};function Me(e,t,n){var r=e[n];Ve(t)&&Ve(r)?ze(r,t):e[n]=t}function ze(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];for(var o=0,s=n;o<s.length;o++){var i=s[o];if(Ve(i))for(var a in i)Be(a)&&Me(e,i[a],a)}return e}var Le=r.createContext(),Ge=Le.Consumer;function Fe(e){var t=s(Le),n=i((function(){return function(e,t){if(!e)return j(14);if(b(e)){var n=e(t);return"production"===process.env.NODE_ENV||null!==n&&!Array.isArray(n)&&"object"==typeof n?n:j(7)}return Array.isArray(e)||"object"!=typeof e?j(8):t?v({},t,{},e):e}(e.theme,t)}),[e.theme,t]);return e.children?r.createElement(Le.Provider,{value:n},e.children):null}var Ye={};function qe(e,t,n){var o=N(e),i=!xe(e),a=t.attrs,c=void 0===a?w:a,d=t.componentId,h=void 0===d?function(e,t){var n="string"!=typeof e?"sc":Te(e);Ye[n]=(Ye[n]||0)+1;var r=n+"-"+ke("5.3.1"+n+Ye[n]);return t?t+"-"+r:r}(t.displayName,t.parentComponentId):d,p=t.displayName,f=void 0===p?function(e){return xe(e)?"styled."+e:"Styled("+_(e)+")"}(e):p,g=t.displayName&&t.componentId?Te(t.displayName)+"-"+t.componentId:t.componentId||h,S=o&&e.attrs?Array.prototype.concat(e.attrs,c).filter(Boolean):c,A=t.shouldForwardProp;o&&e.shouldForwardProp&&(A=t.shouldForwardProp?function(n,r,o){return e.shouldForwardProp(n,r,o)&&t.shouldForwardProp(n,r,o)}:e.shouldForwardProp);var C,I=new se(n,g,o?e.componentStyle:void 0),P=I.isStatic&&0===c.length,O=function(e,t){return function(e,t,n,r){var o=e.attrs,i=e.componentStyle,a=e.defaultProps,c=e.foldedComponentIds,d=e.shouldForwardProp,h=e.styledComponentId,p=e.target;"production"!==process.env.NODE_ENV&&l(h);var f=function(e,t,n){void 0===e&&(e=E);var r=v({},t,{theme:e}),o={};return n.forEach((function(e){var t,n,s,i=e;for(t in b(i)&&(i=i(r)),i)r[t]=o[t]="className"===t?(n=o[t],s=i[t],n&&s?n+" "+s:n||s):i[t]})),[r,o]}(Re(t,s(Le),a)||E,t,o),y=f[0],g=f[1],S=function(e,t,n,r){var o=fe(),s=me(),i=t?e.generateAndInjectStyles(E,o,s):e.generateAndInjectStyles(n,o,s);return"production"!==process.env.NODE_ENV&&l(i),"production"!==process.env.NODE_ENV&&!t&&r&&r(i),i}(i,r,y,"production"!==process.env.NODE_ENV?e.warnTooManyClasses:void 0),w=n,_=g.$as||t.$as||g.as||t.as||p,N=xe(_),A=g!==t?v({},t,{},g):t,C={};for(var I in A)"$"!==I[0]&&"as"!==I&&("forwardedAs"===I?C.as=A[I]:(d?d(I,m,_):!N||m(I))&&(C[I]=A[I]));return t.style&&g.style!==t.style&&(C.style=v({},t.style,{},g.style)),C.className=Array.prototype.concat(c,h,S!==h?S:null,t.className,g.className).filter(Boolean).join(" "),C.ref=w,u(_,C)}(C,e,t,P)};return O.displayName=f,(C=r.forwardRef(O)).attrs=S,C.componentStyle=I,C.displayName=f,C.shouldForwardProp=A,C.foldedComponentIds=o?Array.prototype.concat(e.foldedComponentIds,e.styledComponentId):w,C.styledComponentId=g,C.target=o?e.target:e,C.withComponent=function(e){var r=t.componentId,o=function(e,t){if(null==e)return{};var n,r,o={},s=Object.keys(e);for(r=0;r<s.length;r++)n=s[r],t.indexOf(n)>=0||(o[n]=e[n]);return o}(t,["componentId"]),s=r&&r+"-"+(xe(e)?e:Te(_(e)));return qe(e,v({},o,{attrs:S,componentId:s}),n)},Object.defineProperty(C,"defaultProps",{get:function(){return this._foldedDefaultProps},set:function(t){this._foldedDefaultProps=o?ze({},e.defaultProps,t):t}}),"production"!==process.env.NODE_ENV&&(Oe(f,g),C.warnTooManyClasses=function(e,t){var n={},r=!1;return function(o){if(!r&&(n[o]=!0,Object.keys(n).length>=200)){var s=t?' with the id of "'+t+'"':"";console.warn("Over 200 classes were generated for component "+e+s+".\nConsider using the attrs method, together with a style object for frequently changed styles.\nExample:\n const Component = styled.div.attrs(props => ({\n style: {\n background: props.background,\n },\n }))`width: 100%;`\n\n <Component />"),r=!0,n={}}}}(f,g)),C.toString=function(){return"."+C.styledComponentId},i&&y(C,e,{attrs:!0,componentStyle:!0,displayName:!0,foldedComponentIds:!0,shouldForwardProp:!0,styledComponentId:!0,target:!0,withComponent:!0}),C}var He=function(e){return function e(t,r,o){if(void 0===o&&(o=E),!n(r))return j(1,String(r));var s=function(){return t(r,o,Ce.apply(void 0,arguments))};return s.withConfig=function(n){return e(t,r,v({},o,{},n))},s.attrs=function(n){return e(t,r,v({},o,{attrs:Array.prototype.concat(o.attrs,n).filter(Boolean)}))},s}(qe,e)};["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","big","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","keygen","label","legend","li","link","main","map","mark","marquee","menu","menuitem","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","small","source","span","strong","style","sub","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr","circle","clipPath","defs","ellipse","foreignObject","g","image","line","linearGradient","marker","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","svg","text","textPath","tspan"].forEach((function(e){He[e]=He(e)}));var $e=function(){function e(e,t){this.rules=e,this.componentId=t,this.isStatic=re(e),Z.registerId(this.componentId+1)}var t=e.prototype;return t.createStyles=function(e,t,n,r){var o=r(Ne(this.rules,t,n,r).join(""),""),s=this.componentId+e;n.insertRules(s,s,o)},t.removeStyles=function(e,t){t.clearRules(this.componentId+e)},t.renderStyles=function(e,t,n,r){e>2&&Z.registerId(this.componentId+e),this.removeStyles(e,n),this.createStyles(e,t,n,r)},e}();function We(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];var i=Ce.apply(void 0,[e].concat(n)),a="sc-global-"+ke(JSON.stringify(i)),u=new $e(i,a);function l(e){var t=fe(),n=me(),o=s(Le),l=c(t.allocateGSInstance(a)).current;return"production"!==process.env.NODE_ENV&&r.Children.count(e.children)&&console.warn("The global style component "+a+" was given child JSX. createGlobalStyle does not render children."),"production"!==process.env.NODE_ENV&&i.some((function(e){return"string"==typeof e&&-1!==e.indexOf("@import")}))&&console.warn("Please do not use @import CSS syntax in createGlobalStyle at this time, as the CSSOM APIs we use in production do not handle it well. Instead, we recommend using a library such as react-helmet to inject a typical <link> meta tag to the stylesheet, or simply embedding it manually in your index.html <head> section for a simpler app."),t.server&&h(l,e,t,o,n),d((function(){if(!t.server)return h(l,e,t,o,n),function(){return u.removeStyles(l,t)}}),[l,e,t,o,n]),null}function h(e,t,n,r,o){if(u.isStatic)u.renderStyles(e,O,n,o);else{var s=v({},t,{theme:Re(t,r,l.defaultProps)});u.renderStyles(e,s,n,o)}}return"production"!==process.env.NODE_ENV&&Oe(a),r.memo(l)}function Ue(e){"production"!==process.env.NODE_ENV&&"undefined"!=typeof navigator&&"ReactNative"===navigator.product&&console.warn("`keyframes` cannot be used on ReactNative, only on the web. To do animation in ReactNative please use Animated.");for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];var o=Ce.apply(void 0,[e].concat(n)).join(""),s=ke(o);return new ve(s,o)}var Je=function(){function e(){var e=this;this._emitSheetCSS=function(){var t=e.instance.toString();if(!t)return"";var n=q();return"<style "+[n&&'nonce="'+n+'"',A+'="true"','data-styled-version="5.3.1"'].filter(Boolean).join(" ")+">"+t+"</style>"},this.getStyleTags=function(){return e.sealed?j(2):e._emitSheetCSS()},this.getStyleElement=function(){var t;if(e.sealed)return j(2);var n=((t={})[A]="",t["data-styled-version"]="5.3.1",t.dangerouslySetInnerHTML={__html:e.instance.toString()},t),o=q();return o&&(n.nonce=o),[r.createElement("style",v({},n,{key:"sc-0-0"}))]},this.seal=function(){e.sealed=!0},this.instance=new Z({isServer:!0}),this.sealed=!1}var t=e.prototype;return t.collectStyles=function(e){return this.sealed?j(2):r.createElement(ye,{sheet:this.instance},e)},t.interleaveWithNodeStream=function(e){return j(3)},e}(),Xe=function(e){var t=r.forwardRef((function(t,n){var o=s(Le),i=e.defaultProps,a=Re(t,o,i);return"production"!==process.env.NODE_ENV&&void 0===a&&console.warn('[withTheme] You are not using a ThemeProvider nor passing a theme prop or a theme in defaultProps in component class "'+_(e)+'"'),r.createElement(e,v({},t,{theme:a,ref:n}))}));return y(t,e),t.displayName="WithTheme("+_(e)+")",t},Ze=function(){return s(Le)},Ke={StyleSheet:Z,masterSheet:he};"production"!==process.env.NODE_ENV&&"undefined"!=typeof navigator&&"ReactNative"===navigator.product&&console.warn("It looks like you've imported 'styled-components' on React Native.\nPerhaps you're looking to import 'styled-components/native'?\nRead more about this at https://www.styled-components.com/docs/basics#react-native"),"production"!==process.env.NODE_ENV&&"test"!==process.env.NODE_ENV&&"undefined"!=typeof window&&(window["__styled-components-init__"]=window["__styled-components-init__"]||0,1===window["__styled-components-init__"]&&console.warn("It looks like there are several instances of 'styled-components' initialized in this application. This may cause dynamic styles to not render properly, errors during the rehydration process, a missing theme prop, and makes your application bigger without good reason.\n\nSee https://s-c.sh/2BAXzed for more info."),window["__styled-components-init__"]+=1);export default He;export{Je as ServerStyleSheet,le as StyleSheetConsumer,ue as StyleSheetContext,ye as StyleSheetManager,Ge as ThemeConsumer,Le as ThemeContext,Fe as ThemeProvider,Ke as __PRIVATE__,We as createGlobalStyle,Ce as css,N as isStyledComponent,Ue as keyframes,Ze as useTheme,C as version,Xe as withTheme};
//# sourceMappingURL=styled-components.browser.esm.js.map
internal_url
return (process.env.NODE_ENV !== 'production' ? typeof target === 'string' && target : false) || // $FlowFixMe
0.8
Source map: webpack://frontend-mybets/../../node_modules/styled-components/native/dist/styled-components.native.esm.js
//
function getComponentName(target) {
return (process.env.NODE_ENV !== 'production' ? typeof target === 'string' && target : false) || // $FlowFixMe
target.displayName || // $FlowFixMe
target.name || 'Component';
internal_url
if (process.env.NODE_ENV !== "production") {
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-router/dist/index.js
// from `getSnapshot`.
getServerSnapshot) {
if (process.env.NODE_ENV !== "production") {
if (!didWarnOld18Alpha) {
if ("startTransition" in React) {
internal_url
if (process.env.NODE_ENV !== "production") {
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-router-dom/dist/index.js
}
if (process.env.NODE_ENV !== "production") {
HistoryRouter.displayName = "unstable_HistoryRouter";
}
internal_url
* uri: 'http://localhost:4000/',
0.8
Source map: webpack://frontend-mybets/../../node_modules/@apollo/client/core/ApolloClient.js
* // Provide required constructor fields
* cache: cache,
* uri: 'http://localhost:4000/',
*
* // Provide some optional constructor fields
internal_url
Transition.propTypes = process.env.NODE_ENV !== "production" ? {
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-transition-group/esm/Transition.js
Transition.contextType = TransitionGroupContext;
Transition.propTypes = process.env.NODE_ENV !== "production" ? {
/**
* A React reference to DOM element that need to transition:
internal_url
CSSTransition.propTypes = process.env.NODE_ENV !== "production" ? _extends({}, Transition.propTypes, {
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-transition-group/esm/CSSTransition.js
classNames: ''
};
CSSTransition.propTypes = process.env.NODE_ENV !== "production" ? _extends({}, Transition.propTypes, {
/**
* The animation classNames applied to the component as it appears, enters,
internal_url
if (process.env.NODE_ENV !== "production") {
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-helmet/es/Helmet.js
HelmetWrapper.prototype.warnOnInvalidChildren = function warnOnInvalidChildren(child, nestedChildren) {
if (process.env.NODE_ENV !== "production") {
if (!VALID_TAG_NAMES.some(function (name) {
return child.type === name;
internal_url
throw process.env.NODE_ENV === "production" ? new InvariantError(17) : new InvariantError("The inline argument \"" + name.value + "\" of kind \"" + value.kind + "\"" +
0.8
Source map: webpack://frontend-mybets/../../node_modules/apollo-utilities/lib/bundle.esm.js
}
else {
throw process.env.NODE_ENV === "production" ? new InvariantError(17) : new InvariantError("The inline argument \"" + name.value + "\" of kind \"" + value.kind + "\"" +
'is not supported. Use variables instead of inline arguments to ' +
'overcome this limitation.');
internal_url
process.env.NODE_ENV === "production" ? invariant(hasOwnProperty.call(root, info.resultKey) ||
0.8
Source map: webpack://frontend-mybets/../../node_modules/graphql-anywhere/lib/bundle.esm.js
if (variables === void 0) { variables = {}; }
var resolver = function (fieldName, root, args, context, info) {
process.env.NODE_ENV === "production" ? invariant(hasOwnProperty.call(root, info.resultKey) ||
(!variables && hasVariableInclusions(info.field.directives)), 1) : invariant(hasOwnProperty.call(root, info.resultKey) ||
(!variables && hasVariableInclusions(info.field.directives)), info.resultKey + " missing on " + JSON.stringify(root));
internal_url
typeof process.env.ENVIRONMENT === "string" &&
0.8
Source map: webpack://frontend-mybets/../../packages/tvg-lib-conf/src/utils.ts
window.location.hostname.includes("local")) ||
(typeof window === "undefined" &&
typeof process.env.ENVIRONMENT === "string" &&
process.env.ENVIRONMENT === "dev");
internal_url
TransitionGroup.propTypes = process.env.NODE_ENV !== "production" ? {
0.8
Source map: webpack://frontend-mybets/../../node_modules/react-transition-group/esm/TransitionGroup.js
}(React.Component);
TransitionGroup.propTypes = process.env.NODE_ENV !== "production" ? {
/**
* `<TransitionGroup>` renders a `<div>` by default. You can change this
internal_url
url: "https://storage.googleapis.com",
0.8
Source map: webpack://frontend-mybets/../../packages/tvg-lib-conf/content/aws-int/base.ts
},
gcs: {
url: "https://storage.googleapis.com",
tvgStatic: "tvg-static-qa"
}
internal_url
url: "https://storage.googleapis.com",
0.8
Source map: webpack://frontend-mybets/../../packages/tvg-lib-conf/content/aws-prd/base.ts
},
gcs: {
url: "https://storage.googleapis.com",
tvgStatic: "tvg-static"
}
internal_url
url: "https://storage.googleapis.com",
0.8
Source map: webpack://frontend-mybets/../../packages/tvg-lib-conf/content/aws-stg/base.ts
},
gcs: {
url: "https://storage.googleapis.com",
tvgStatic: "tvg-static-staging"
}
internal_url
url: "https://storage.googleapis.com",
0.8
Source map: webpack://frontend-mybets/../../packages/tvg-lib-conf/content/production/base.ts
},
gcs: {
url: "https://storage.googleapis.com",
tvgStatic: "tvg-static"
}
internal_url
url: "https://storage.googleapis.com",
0.8
Source map: webpack://frontend-mybets/../../packages/tvg-lib-conf/content/qa/base.ts
},
gcs: {
url: "https://storage.googleapis.com",
tvgStatic: "tvg-static-qa"
}
internal_url
url: "https://storage.googleapis.com",
0.8
Source map: webpack://frontend-mybets/../../packages/tvg-lib-conf/content/staging/base.ts
},
gcs: {
url: "https://storage.googleapis.com",
tvgStatic: "tvg-static-staging"
}
endpoints from source map (79)
GET
../../version.js
GET
../common/stringifyForDisplay.js
GET
../globals/index.js
GET
../../utilities/index.js
GET
../../utilities/globals/index.js
GET
https://github.com/ungap/url-search-params
GET
../../utilities/caching/index.js
GET
../caching/getMemoryInternals.js
GET
../common/objects.js
GET
../common/canonicalStringify.js
GET
../utils/index.js
GET
../../../utilities/index.js
GET
../utilities/globals/index.js
GET
../utilities/index.js
GET
../../errors/index.js
GET
../../utilities/common/incrementalResult.js
GET
../caching/index.js
GET
../common/arrays.js
GET
../core/index.js
GET
../../utilities/caching/getMemoryInternals.js
GET
../common/canUse.js
GET
../core/types/common.js
GET
../core/cache.js
GET
../cache/index.js
GET
../link/core/index.js
GET
../utilities/common/incrementalResult.js
GET
../errors/index.js
GET
../version.js
GET
../link/http/index.js
GET
../utilities/caching/getMemoryInternals.js
GET
https://chrome.google.com/webstore/detail/
GET
../context/index.js
GET
../../core/index.js
GET
../parser/index.js
GET
../hooks/index.js
GET
../components/index.js
GET
../addDays/index.js
GET
../addWeeks/index.js
GET
../addMonths/index.js
GET
../differenceInCalendarDays/index.js
GET
../startOfDay/index.js
GET
/live
GET
/tracks
GET
/tracks/results
GET
/tracks/all-info
GET
../differenceInMilliseconds/index.js
GET
https://api.storyblok.com/v1/cdn/stories
GET
//stream.robertsstream.com/streammobile.php
GET
../toDate/index.js
GET
../_lib/toInteger/index.js
GET
../_lib/requiredArgs/index.js
GET
../../../_lib/buildFormatLongFn/index.js
GET
../../../_lib/buildLocalizeFn/index.js
GET
../../../_lib/buildMatchPatternFn/index.js
GET
../../../_lib/buildMatchFn/index.js
GET
../../addLeadingZeros/index.js
GET
../../toDate/index.js
GET
../requiredArgs/index.js
GET
../startOfUTCISOWeek/index.js
GET
../toInteger/index.js
GET
../startOfUTCWeek/index.js
GET
../lightFormatters/index.js
GET
../../../_lib/getUTCDayOfYear/index.js
GET
../../../_lib/getUTCISOWeek/index.js
GET
../../../_lib/getUTCISOWeekYear/index.js
GET
../../../_lib/getUTCWeek/index.js
GET
../../../_lib/getUTCWeekYear/index.js
GET
../startOfUTCWeekYear/index.js
GET
../getUTCWeekYear/index.js
GET
../startOfUTCISOWeekYear/index.js
GET
../getUTCISOWeekYear/index.js
GET
../isValid/index.js
GET
../locale/en-US/index.js
GET
../subMilliseconds/index.js
GET
../_lib/format/formatters/index.js
GET
../_lib/format/longFormatters/index.js
GET
../_lib/getTimezoneOffsetInMilliseconds/index.js
GET
../_lib/protectedTokens/index.js
GET
../addMilliseconds/index.js
source file tree (2086)
2086 files with original sourcewebpack://frontend-mybets/webpack/runtime/create fake namespace object
var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);
var leafPrototypes;
// create a fake namespace object
// mode & 1: value is a module id, require it
// mode & 2: merge all properties of value into the ns
// mode & 4: return value when already ns object
// mode & 16: return value when it's Promise-like
// mode & 8|1: behave like require
__webpack_require__.t = function(value, mode) {
if(mode & 1) value = this(value);
if(mode & 8) return value;
if(typeof value === 'object' && value) {
if((mode & 4) && value.__esModule) return value;
if((mode & 16) && typeof value.then === 'function') return value;
}
var ns = Object.create(null);
__webpack_require__.r(ns);
var def = {};
leafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];
for(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {
Object.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));
}
def['default'] = () => (value);
__webpack_require__.d(ns, def);
return ns;
};
webpack://frontend-mybets/webpack/runtime/load script
var inProgress = {};
var dataWebpackPrefix = "frontend-mybets:";
// loadScript function to load a script via script tag
__webpack_require__.l = (url, done, key, chunkId) => {
if(inProgress[url]) { inProgress[url].push(done); return; }
var script, needAttach;
if(key !== undefined) {
var scripts = document.getElementsByTagName("script");
for(var i = 0; i < scripts.length; i++) {
var s = scripts[i];
if(s.getAttribute("src") == url || s.getAttribute("data-webpack") == dataWebpackPrefix + key) { script = s; break; }
}
}
if(!script) {
needAttach = true;
script = document.createElement('script');
script.charset = 'utf-8';
script.timeout = 120;
if (__webpack_require__.nc) {
script.setAttribute("nonce", __webpack_require__.nc);
}
script.setAttribute("data-webpack", dataWebpackPrefix + key);
script.src = url;
}
inProgress[url] = [done];
var onScriptComplete = (prev, event) => {
// avoid mem leaks in IE.
script.onerror = script.onload = null;
clearTimeout(timeout);
var doneFns = inProgress[url];
delete inProgress[url];
script.parentNode && script.parentNode.removeChild(script);
doneFns && doneFns.forEach((fn) => (fn(event)));
if(prev) return prev(event);
}
var timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);
script.onerror = onScriptComplete.bind(null, script.onerror);
script.onload = onScriptComplete.bind(null, script.onload);
needAttach && document.head.appendChild(script);
};
webpack://frontend-mybets/../../node_modules/@amplitude/ua-parser-js/src/ua-parser.js
///////////////////////////////////////////////////////////////////////////////// /* UAParser.js v0.7.33 Copyright © 2012-2021 Faisal Salman <[email protected]> MIT License */ /* Detect Browser, Engine, OS, CPU, and Device type/model from User-Agent data. Supports browser & node.js environment. Demo : https://faisalman.github.io/ua-parser-js Source : https://github.com/faisalman/ua-parser-js */ ///////////////////////////////////////////////////////////////////////////////// (function (window, undefined) { "use strict"; ////////////// // Constants ///////////// var LIBVERSION = "0.7.33", EMPTY = "", UNKNOWN = "?", FUNC_TYPE = "function", UNDEF_TYPE = "undefined", OBJ_TYPE = "object", STR_TYPE = "string", MAJOR = "major", MODEL = "model", NAME = "name", TYPE = "type", VENDOR = "vendor", VERSION = "version", ARCHITECTURE = "architecture", CONSOLE = "console", MOBILE = "mobile", TABLET = "tablet", SMARTTV = "smarttv", WEARABLE = "wearable", EMBEDDED = "embedded", UA_MAX_LENGTH = 350; var AMAZON = "Amazon", APPLE = "Apple", ASUS = "ASUS", BLACKBERRY = "BlackBerry", BROWSER = "Browser", CHROME = "Chrome", EDGE = "Edge", FIREFOX = "Firefox", GOOGLE = "Google", HUAWEI = "Huawei", LG = "LG", MICROSOFT = "Microsoft", MOTOROLA = "Motorola", OPERA = "Opera", SAMSUNG = "Samsung", SHARP = "Sharp", SONY = "Sony", XIAOMI = "Xiaomi", ZEBRA = "Zebra", FACEBOOK = "Facebook"; /////////// // Helper ////////// var extend = function (regexes, extensions) { var mergedRegexes = {}; for (var i in regexes) { if (extensions[i] && extensions[i].length % 2 === 0) { mergedRegexes[i] = extensions[i].concat(regexes[i]); } else { mergedRegexes[i] = regexes[i]; } } return mergedRegexes; }, enumerize = function (arr) { var enums = {}; for (var i = 0; i < arr.length; i++) { enums[arr[i].toUpperCase()] = arr[i]; } return enums; }, has = function (str1, str2) { return typeof str1 === STR_TYPE ? lowerize(str2).indexOf(lowerize(str1)) !== -1 : false; }, lowerize = function (str) { return str.toLowerCase(); }, majorize = function (version) { return typeof version === STR_TYPE ? version.replace(/[^\d\.]/g, EMPTY).split(".")[0] : undefined; }, trim = function (str, len) { if (typeof str === STR_TYPE) { str = str.replace(/^\s\s*/, EMPTY); return typeof len === UNDEF_TYPE ? str : str.substring(0, UA_MAX_LENGTH); } }; /////////////// // Map helper ////////////// var rgxMapper = function (ua, arrays) { var i = 0, j, k, p, q, matches, match; // loop through all regexes maps while (i < arrays.length && !matches) { var regex = arrays[i], // even sequence (0,2,4,..) props = arrays[i + 1]; // odd sequence (1,3,5,..) j = k = 0; // try matching uastring with regexes while (j < regex.length && !matches) { matches = regex[j++].exec(ua); if (!!matches) { for (p = 0; p < props.length; p++) { match = matches[++k]; q = props[p]; // check if given property is actually array if (typeof q === OBJ_TYPE && q.length > 0) { if (q.length === 2) { if (typeof q[1] == FUNC_TYPE) { // assign modified match this[q[0]] = q[1].call(this, match); } else { // assign given value, ignore regex match this[q[0]] = q[1]; } } else if (q.length === 3) { // check whether function or regex if (typeof q[1] === FUNC_TYPE && !(q[1].exec && q[1].test)) { // call function (usually string mapper) this[q[0]] = match ? q[1].call(this, match, q[2]) : undefined; } else { // sanitize match using given regex this[q[0]] = match ? match.replace(q[1], q[2]) : undefined; } } else if (q.length === 4) { this[q[0]] = match ? q[3].call(this, match.replace(q[1], q[2])) : undefined; } } else { this[q] = match ? match : undefined; } } } } i += 2; } }, strMapper = function (str, map) { for (var i in map) { // check if current value is array if (typeof map[i] === OBJ_TYPE && map[i].length > 0) { for (var j = 0; j < map[i].length; j++) { if (has(map[i][j], str)) { return i === UNKNOWN ? undefined : i; } } } else if (has(map[i], str)) { return i === UNKNOWN ? undefined : i; } } return str; }; /////////////// // String map ////////////// // Safari < 3.0 var oldSafariMap = { "1.0": "/8", 1.2: "/1", 1.3: "/3", "2.0": "/412", "2.0.2": "/416", "2.0.3": "/417", "2.0.4": "/419", "?": "/" }, windowsVersionMap = { ME: "4.90", "NT 3.11": "NT3.51", "NT 4.0": "NT4.0", 2000: "NT 5.0", XP: ["NT 5.1", "NT 5.2"], Vista: "NT 6.0", 7: "NT 6.1", 8: "NT 6.2", 8.1: "NT 6.3", 10: ["NT 6.4", "NT 10.0"], RT: "ARM" }; ////////////// // Regex map ///////////// var regexes = { browser: [ [ /\b(?:crmo|crios)\/([\w\.]+)/i // Chrome for Android/iOS ], [VERSION, [NAME, "Chrome"]], [ /edg(?:e|ios|a)?\/([\w\.]+)/i // Microsoft Edge ], [VERSION, [NAME, "Edge"]], [ // Presto based /(opera mini)\/([-\w\.]+)/i, // Opera Mini /(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i, // Opera Mobi/Tablet /(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i // Opera ], [NAME, VERSION], [ /opios[\/ ]+([\w\.]+)/i // Opera mini on iphone >= 8.0 ], [VERSION, [NAME, OPERA + " Mini"]], [ /\bopr\/([\w\.]+)/i // Opera Webkit ], [VERSION, [NAME, OPERA]], [ // Mixed /(kindle)\/([\w\.]+)/i, // Kindle /(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i, // Lunascape/Maxthon/Netfront/Jasmine/Blazer // Trident based /(avant |iemobile|slim)(?:browser)?[\/ ]?([\w\.]*)/i, // Avant/IEMobile/SlimBrowser /(ba?idubrowser)[\/ ]?([\w\.]+)/i, // Baidu Browser /(?:ms|\()(ie) ([\w\.]+)/i, // Internet Explorer // Webkit/KHTML based // Flock/RockMelt/Midori/Epiphany/Silk/Skyfire/Bolt/Iron/Iridium/PhantomJS/Bowser/QupZilla/Falkon /(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i, // Rekonq/Puffin/Brave/Whale/QQBrowserLite/QQ, aka ShouQ /(weibo)__([\d\.]+)/i // Weibo ], [NAME, VERSION], [ /(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i // UCBrowser ], [VERSION, [NAME, "UC" + BROWSER]], [ /microm.+\bqbcore\/([\w\.]+)/i, // WeChat Desktop for Windows Built-in Browser /\bqbcore\/([\w\.]+).+microm/i ], [VERSION, [NAME, "WeChat(Win) Desktop"]], [ /micromessenger\/([\w\.]+)/i // WeChat ], [VERSION, [NAME, "WeChat"]], [ /konqueror\/([\w\.]+)/i // Konqueror ], [VERSION, [NAME, "Konqueror"]], [ /trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i // IE11 ], [VERSION, [NAME, "IE"]], [ /yabrowser\/([\w\.]+)/i // Yandex ], [VERSION, [NAME, "Yandex"]], [ /(avast|avg)\/([\w\.]+)/i // Avast/AVG Secure Browser ], [[NAME, /(.+)/, "$1 Secure " + BROWSER], VERSION], [ /\bfocus\/([\w\.]+)/i // Firefox Focus ], [VERSION, [NAME, FIREFOX + " Focus"]], [ /\bopt\/([\w\.]+)/i // Opera Touch ], [VERSION, [NAME, OPERA + " Touch"]], [ /coc_coc\w+\/([\w\.]+)/i // Coc Coc Browser ], [VERSION, [NAME, "Coc Coc"]], [ /dolfin\/([\w\.]+)/i // Dolphin ], [VERSION, [NAME, "Dolphin"]], [ /coast\/([\w\.]+)/i // Opera Coast ], [VERSION, [NAME, OPERA + " Coast"]], [ /miuibrowser\/([\w\.]+)/i // MIUI Browser ], [VERSION, [NAME, "MIUI " + BROWSER]], [ /fxios\/([-\w\.]+)/i // Firefox for iOS ], [VERSION, [NAME, FIREFOX]], [ /\bqihu|(qi?ho?o?|360)browser/i // 360 ], [[NAME, "360 " + BROWSER]], [/(oculus|samsung|sailfish|huawei)browser\/([\w\.]+)/i], [[NAME, /(.+)/, "$1 " + BROWSER], VERSION], [ // Oculus/Samsung/Sailfish/Huawei Browser /(comodo_dragon)\/([\w\.]+)/i // Comodo Dragon ], [[NAME, /_/g, " "], VERSION], [ /(electron)\/([\w\.]+) safari/i, // Electron-based App /(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i, // Tesla /m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i // QQBrowser/Baidu App/2345 Browser ], [NAME, VERSION], [ /(metasr)[\/ ]?([\w\.]+)/i, // SouGouBrowser /(lbbrowser)/i, // LieBao Browser /\[(linkedin)app\]/i // LinkedIn App for iOS & Android ], [NAME], [ // WebView /((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i // Facebook App for iOS & Android ], [[NAME, FACEBOOK], VERSION], [ /safari (line)\/([\w\.]+)/i, // Line App for iOS /\b(line)\/([\w\.]+)\/iab/i, // Line App for Android /(chromium|instagram)[\/ ]([-\w\.]+)/i // Chromium/Instagram ], [NAME, VERSION], [ /\bgsa\/([\w\.]+) .*safari\//i // Google Search Appliance on iOS ], [VERSION, [NAME, "GSA"]], [ /headlesschrome(?:\/([\w\.]+)| )/i // Chrome Headless ], [VERSION, [NAME, CHROME + " Headless"]], [ / wv\).+(chrome)\/([\w\.]+)/i // Chrome WebView ], [[NAME, CHROME + " WebView"], VERSION], [ /droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i // Android Browser ], [VERSION, [NAME, "Android " + BROWSER]], [ /(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i // Chrome/OmniWeb/Arora/Tizen/Nokia ], [NAME, VERSION], [ /version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i // Mobile Safari ], [VERSION, [NAME, "Mobile Safari"]], [ /version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i // Safari & Safari Mobile ], [VERSION, NAME], [ /webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i // Safari < 3.0 ], [NAME, [VERSION, strMapper, oldSafariMap]], [/(webkit|khtml)\/([\w\.]+)/i], [NAME, VERSION], [ // Gecko based /(navigator|netscape\d?)\/([-\w\.]+)/i // Netscape ], [[NAME, "Netscape"], VERSION], [ /mobile vr; rv:([\w\.]+)\).+firefox/i // Firefox Reality ], [VERSION, [NAME, FIREFOX + " Reality"]], [ /ekiohf.+(flow)\/([\w\.]+)/i, // Flow /(swiftfox)/i, // Swiftfox /(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i, // IceDragon/Iceweasel/Camino/Chimera/Fennec/Maemo/Minimo/Conkeror/Klar /(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i, // Firefox/SeaMonkey/K-Meleon/IceCat/IceApe/Firebird/Phoenix /(firefox)\/([\w\.]+)/i, // Other Firefox-based /(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i, // Mozilla // Other /(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i, // Polaris/Lynx/Dillo/iCab/Doris/Amaya/w3m/NetSurf/Sleipnir/Obigo/Mosaic/Go/ICE/UP.Browser /(links) \(([\w\.]+)/i // Links ], [NAME, VERSION], [ /(cobalt)\/([\w\.]+)/i // Cobalt ], [NAME, [VERSION, /master.|lts./, ""]] ], cpu: [ [ /(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i // AMD64 (x64) ], [[ARCHITECTURE, "amd64"]], [ /(ia32(?=;))/i // IA32 (quicktime) ], [[ARCHITECTURE, lowerize]], [ /((?:i[346]|x)86)[;\)]/i // IA32 (x86) ], [[ARCHITECTURE, "ia32"]], [ /\b(aarch64|arm(v?8e?l?|_?64))\b/i // ARM64 ], [[ARCHITECTURE, "arm64"]], [ /\b(arm(?:v[67])?ht?n?[fl]p?)\b/i // ARMHF ], [[ARCHITECTURE, "armhf"]], [ // PocketPC mistakenly identified as PowerPC /windows (ce|mobile); ppc;/i ], [[ARCHITECTURE, "arm"]], [ /((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i // PowerPC ], [[ARCHITECTURE, /ower/, EMPTY, lowerize]], [ /(sun4\w)[;\)]/i // SPARC ], [[ARCHITECTURE, "sparc"]], [ /((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i // IA64, 68K, ARM/64, AVR/32, IRIX/64, MIPS/64, SPARC/64, PA-RISC ], [[ARCHITECTURE, lowerize]] ], device: [ [ ////////////////////////// // MOBILES & TABLETS // Ordered by popularity ///////////////////////// // Samsung /\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i ], [MODEL, [VENDOR, SAMSUNG], [TYPE, TABLET]], [ /\b((?:s[cgp]h|gt|sm)-\w+|galaxy nexus)/i, /samsung[- ]([-\w]+)/i, /sec-(sgh\w+)/i ], [MODEL, [VENDOR, SAMSUNG], [TYPE, MOBILE]], [ // Apple /((ipod|iphone)\d+,\d+)/i // iPod/iPhone model ], [MODEL, [VENDOR, APPLE], [TYPE, MOBILE]], [ /(ipad\d+,\d+)/i // iPad model ], [MODEL, [VENDOR, APPLE], [TYPE, TABLET]], [ /\((ip(?:hone|od)[\w ]*);/i // iPod/iPhone ], [MODEL, [VENDOR, APPLE], [TYPE, MOBILE]], [ /\((ipad);[-\w\),; ]+apple/i, // iPad /applecoremedia\/[\w\.]+ \((ipad)/i, /\b(ipad)\d\d?,\d\d?[;\]].+ios/i ], [MODEL, [VENDOR, APPLE], [TYPE, TABLET]], [/(macintosh);/i], [MODEL, [VENDOR, APPLE]], [ // Huawei /\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i ], [MODEL, [VENDOR, HUAWEI], [TYPE, TABLET]], [ /(?:huawei|honor)([-\w ]+)[;\)]/i, /\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i ], [MODEL, [VENDOR, HUAWEI], [TYPE, MOBILE]], [ // Xiaomi /\b(poco[\w ]+)(?: bui|\))/i, // Xiaomi POCO /\b; (\w+) build\/hm\1/i, // Xiaomi Hongmi 'numeric' models /\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i, // Xiaomi Hongmi /\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i, // Xiaomi Redmi /\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i // Xiaomi Mi ], [ [MODEL, /_/g, " "], [VENDOR, XIAOMI], [TYPE, MOBILE] ], [ /\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i // Mi Pad tablets ], [ [MODEL, /_/g, " "], [VENDOR, XIAOMI], [TYPE, TABLET] ], [ // OPPO /; (\w+) bui.+ oppo/i, /\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i ], [MODEL, [VENDOR, "OPPO"], [TYPE, MOBILE]], [ // Vivo /vivo (\w+)(?: bui|\))/i, /\b(v[12]\d{3}\w?[at])(?: bui|;)/i ], [MODEL, [VENDOR, "Vivo"], [TYPE, MOBILE]], [ // Realme /\b(rmx[12]\d{3})(?: bui|;|\))/i ], [MODEL, [VENDOR, "Realme"], [TYPE, MOBILE]], [ // Motorola /\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i, /\bmot(?:orola)?[- ](\w*)/i, /((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i ], [MODEL, [VENDOR, MOTOROLA], [TYPE, MOBILE]], [/\b(mz60\d|xoom[2 ]{0,2}) build\//i], [MODEL, [VENDOR, MOTOROLA], [TYPE, TABLET]], [ // LG /((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i ], [MODEL, [VENDOR, LG], [TYPE, TABLET]], [ /(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i, /\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i, /\blg-?([\d\w]+) bui/i ], [MODEL, [VENDOR, LG], [TYPE, MOBILE]], [ // Lenovo /(ideatab[-\w ]+)/i, /lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i ], [MODEL, [VENDOR, "Lenovo"], [TYPE, TABLET]], [ // Nokia /(?:maemo|nokia).*(n900|lumia \d+)/i, /nokia[-_ ]?([-\w\.]*)/i ], [ [MODEL, /_/g, " "], [VENDOR, "Nokia"], [TYPE, MOBILE] ], [ // Google /(pixel c)\b/i // Google Pixel C ], [MODEL, [VENDOR, GOOGLE], [TYPE, TABLET]], [ /droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i // Google Pixel ], [MODEL, [VENDOR, GOOGLE], [TYPE, MOBILE]], [ // Sony /droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i ], [MODEL, [VENDOR, SONY], [TYPE, MOBILE]], [/sony tablet [ps]/i, /\b(?:sony)?sgp\w+(?: bui|\))/i], [ [MODEL, "Xperia Tablet"], [VENDOR, SONY], [TYPE, TABLET] ], [ // OnePlus / (kb2005|in20[12]5|be20[12][59])\b/i, /(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i ], [MODEL, [VENDOR, "OnePlus"], [TYPE, MOBILE]], [ // Amazon /(alexa)webm/i, /(kf[a-z]{2}wi)( bui|\))/i, // Kindle Fire without Silk /(kf[a-z]+)( bui|\)).+silk\//i // Kindle Fire HD ], [MODEL, [VENDOR, AMAZON], [TYPE, TABLET]], [ /((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i // Fire Phone ], [ [MODEL, /(.+)/g, "Fire Phone $1"], [VENDOR, AMAZON], [TYPE, MOBILE] ], [ // BlackBerry /(playbook);[-\w\),; ]+(rim)/i // BlackBerry PlayBook ], [MODEL, VENDOR, [TYPE, TABLET]], [ /\b((?:bb[a-f]|st[hv])100-\d)/i, /\(bb10; (\w+)/i // BlackBerry 10 ], [MODEL, [VENDOR, BLACKBERRY], [TYPE, MOBILE]], [ // Asus /(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i ], [MODEL, [VENDOR, ASUS], [TYPE, TABLET]], [/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i], [MODEL, [VENDOR, ASUS], [TYPE, MOBILE]], [ // HTC /(nexus 9)/i // HTC Nexus 9 ], [MODEL, [VENDOR, "HTC"], [TYPE, TABLET]], [ /(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i, // HTC // ZTE /(zte)[- ]([\w ]+?)(?: bui|\/|\))/i, /(alcatel|geeksphone|nexian|panasonic|sony(?!-bra))[-_ ]?([-\w]*)/i // Alcatel/GeeksPhone/Nexian/Panasonic/Sony ], [VENDOR, [MODEL, /_/g, " "], [TYPE, MOBILE]], [ // Acer /droid.+; ([ab][1-7]-?[0178a]\d\d?)/i ], [MODEL, [VENDOR, "Acer"], [TYPE, TABLET]], [ // Meizu /droid.+; (m[1-5] note) bui/i, /\bmz-([-\w]{2,})/i ], [MODEL, [VENDOR, "Meizu"], [TYPE, MOBILE]], [ // Sharp /\b(sh-?[altvz]?\d\d[a-ekm]?)/i ], [MODEL, [VENDOR, SHARP], [TYPE, MOBILE]], [ // MIXED /(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[-_ ]?([-\w]*)/i, // BlackBerry/BenQ/Palm/Sony-Ericsson/Acer/Asus/Dell/Meizu/Motorola/Polytron /(hp) ([\w ]+\w)/i, // HP iPAQ /(asus)-?(\w+)/i, // Asus /(microsoft); (lumia[\w ]+)/i, // Microsoft Lumia /(lenovo)[-_ ]?([-\w]+)/i, // Lenovo /(jolla)/i, // Jolla /(oppo) ?([\w ]+) bui/i // OPPO ], [VENDOR, MODEL, [TYPE, MOBILE]], [ /(archos) (gamepad2?)/i, // Archos /(hp).+(touchpad(?!.+tablet)|tablet)/i, // HP TouchPad /(kindle)\/([\w\.]+)/i, // Kindle /(nook)[\w ]+build\/(\w+)/i, // Nook /(dell) (strea[kpr\d ]*[\dko])/i, // Dell Streak /(le[- ]+pan)[- ]+(\w{1,9}) bui/i, // Le Pan Tablets /(trinity)[- ]*(t\d{3}) bui/i, // Trinity Tablets /(gigaset)[- ]+(q\w{1,9}) bui/i, // Gigaset Tablets /(vodafone) ([\w ]+)(?:\)| bui)/i // Vodafone ], [VENDOR, MODEL, [TYPE, TABLET]], [ /(surface duo)/i // Surface Duo ], [MODEL, [VENDOR, MICROSOFT], [TYPE, TABLET]], [ /droid [\d\.]+; (fp\du?)(?: b|\))/i // Fairphone ], [MODEL, [VENDOR, "Fairphone"], [TYPE, MOBILE]], [ /(u304aa)/i // AT&T ], [MODEL, [VENDOR, "AT&T"], [TYPE, MOBILE]], [ /\bsie-(\w*)/i // Siemens ], [MODEL, [VENDOR, "Siemens"], [TYPE, MOBILE]], [ /\b(rct\w+) b/i // RCA Tablets ], [MODEL, [VENDOR, "RCA"], [TYPE, TABLET]], [ /\b(venue[\d ]{2,7}) b/i // Dell Venue Tablets ], [MODEL, [VENDOR, "Dell"], [TYPE, TABLET]], [ /\b(q(?:mv|ta)\w+) b/i // Verizon Tablet ], [MODEL, [VENDOR, "Verizon"], [TYPE, TABLET]], [ /\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i // Barnes & Noble Tablet ], [MODEL, [VENDOR, "Barnes & Noble"], [TYPE, TABLET]], [/\b(tm\d{3}\w+) b/i], [MODEL, [VENDOR, "NuVision"], [TYPE, TABLET]], [ /\b(k88) b/i // ZTE K Series Tablet ], [MODEL, [VENDOR, "ZTE"], [TYPE, TABLET]], [ /\b(nx\d{3}j) b/i // ZTE Nubia ], [MODEL, [VENDOR, "ZTE"], [TYPE, MOBILE]], [ /\b(gen\d{3}) b.+49h/i // Swiss GEN Mobile ], [MODEL, [VENDOR, "Swiss"], [TYPE, MOBILE]], [ /\b(zur\d{3}) b/i // Swiss ZUR Tablet ], [MODEL, [VENDOR, "Swiss"], [TYPE, TABLET]], [ /\b((zeki)?tb.*\b) b/i // Zeki Tablets ], [MODEL, [VENDOR, "Zeki"], [TYPE, TABLET]], [ /\b([yr]\d{2}) b/i, /\b(dragon[- ]+touch |dt)(\w{5}) b/i // Dragon Touch Tablet ], [[VENDOR, "Dragon Touch"], MODEL, [TYPE, TABLET]], [ /\b(ns-?\w{0,9}) b/i // Insignia Tablets ], [MODEL, [VENDOR, "Insignia"], [TYPE, TABLET]], [ /\b((nxa|next)-?\w{0,9}) b/i // NextBook Tablets ], [MODEL, [VENDOR, "NextBook"], [TYPE, TABLET]], [ /\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i // Voice Xtreme Phones ], [[VENDOR, "Voice"], MODEL, [TYPE, MOBILE]], [ /\b(lvtel\-)?(v1[12]) b/i // LvTel Phones ], [[VENDOR, "LvTel"], MODEL, [TYPE, MOBILE]], [ /\b(ph-1) /i // Essential PH-1 ], [MODEL, [VENDOR, "Essential"], [TYPE, MOBILE]], [ /\b(v(100md|700na|7011|917g).*\b) b/i // Envizen Tablets ], [MODEL, [VENDOR, "Envizen"], [TYPE, TABLET]], [ /\b(trio[-\w\. ]+) b/i // MachSpeed Tablets ], [MODEL, [VENDOR, "MachSpeed"], [TYPE, TABLET]], [ /\btu_(1491) b/i // Rotor Tablets ], [MODEL, [VENDOR, "Rotor"], [TYPE, TABLET]], [ /(shield[\w ]+) b/i // Nvidia Shield Tablets ], [MODEL, [VENDOR, "Nvidia"], [TYPE, TABLET]], [ /(sprint) (\w+)/i // Sprint Phones ], [VENDOR, MODEL, [TYPE, MOBILE]], [ /(kin\.[onetw]{3})/i // Microsoft Kin ], [ [MODEL, /\./g, " "], [VENDOR, MICROSOFT], [TYPE, MOBILE] ], [ /droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i // Zebra ], [MODEL, [VENDOR, ZEBRA], [TYPE, TABLET]], [/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i], [MODEL, [VENDOR, ZEBRA], [TYPE, MOBILE]], [ /////////////////// // CONSOLES /////////////////// /(ouya)/i, // Ouya /(nintendo) ([wids3utch]+)/i // Nintendo ], [VENDOR, MODEL, [TYPE, CONSOLE]], [ /droid.+; (shield) bui/i // Nvidia ], [MODEL, [VENDOR, "Nvidia"], [TYPE, CONSOLE]], [ /(playstation [345portablevi]+)/i // Playstation ], [MODEL, [VENDOR, SONY], [TYPE, CONSOLE]], [ /\b(xbox(?: one)?(?!; xbox))[\); ]/i // Microsoft Xbox ], [MODEL, [VENDOR, MICROSOFT], [TYPE, CONSOLE]], [ /////////////////// // SMARTTVS /////////////////// /smart-tv.+(samsung)/i // Samsung ], [VENDOR, [TYPE, SMARTTV]], [/hbbtv.+maple;(\d+)/i], [ [MODEL, /^/, "SmartTV"], [VENDOR, SAMSUNG], [TYPE, SMARTTV] ], [ /(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i // LG SmartTV ], [ [VENDOR, LG], [TYPE, SMARTTV] ], [ /(apple) ?tv/i // Apple TV ], [VENDOR, [MODEL, APPLE + " TV"], [TYPE, SMARTTV]], [ /crkey/i // Google Chromecast ], [ [MODEL, CHROME + "cast"], [VENDOR, GOOGLE], [TYPE, SMARTTV] ], [ /droid.+aft(\w)( bui|\))/i // Fire TV ], [MODEL, [VENDOR, AMAZON], [TYPE, SMARTTV]], [ /\(dtv[\);].+(aquos)/i, /(aquos-tv[\w ]+)\)/i // Sharp ], [MODEL, [VENDOR, SHARP], [TYPE, SMARTTV]], [ /(bravia[\w ]+)( bui|\))/i // Sony ], [MODEL, [VENDOR, SONY], [TYPE, SMARTTV]], [ /(mitv-\w{5}) bui/i // Xiaomi ], [MODEL, [VENDOR, XIAOMI], [TYPE, SMARTTV]], [ /\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i, // Roku /hbbtv\/\d+\.\d+\.\d+ +\([\w ]*; *(\w[^;]*);([^;]*)/i // HbbTV devices ], [ [VENDOR, trim], [MODEL, trim], [TYPE, SMARTTV] ], [ /\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i // SmartTV from Unidentified Vendors ], [[TYPE, SMARTTV]], [ /////////////////// // WEARABLES /////////////////// /((pebble))app/i // Pebble ], [VENDOR, MODEL, [TYPE, WEARABLE]], [ /droid.+; (glass) \d/i // Google Glass ], [MODEL, [VENDOR, GOOGLE], [TYPE, WEARABLE]], [/droid.+; (wt63?0{2,3})\)/i], [MODEL, [VENDOR, ZEBRA], [TYPE, WEARABLE]], [ /(quest( 2)?)/i // Oculus Quest ], [MODEL, [VENDOR, FACEBOOK], [TYPE, WEARABLE]], [ /////////////////// // EMBEDDED /////////////////// /(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i // Tesla ], [VENDOR, [TYPE, EMBEDDED]], [ //////////////////// // MIXED (GENERIC) /////////////////// /droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i // Android Phones from Unidentified Vendors ], [MODEL, [TYPE, MOBILE]], [ /droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i // Android Tablets from Unidentified Vendors ], [MODEL, [TYPE, TABLET]], [ /\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i // Unidentifiable Tablet ], [[TYPE, TABLET]], [ /(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i // Unidentifiable Mobile ], [[TYPE, MOBILE]], [ /(android[-\w\. ]{0,9});.+buil/i // Generic Android Device ], [MODEL, [VENDOR, "Generic"]] ], engine: [ [ /windows.+ edge\/([\w\.]+)/i // EdgeHTML ], [VERSION, [NAME, EDGE + "HTML"]], [ /webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i // Blink ], [VERSION, [NAME, "Blink"]], [ /(presto)\/([\w\.]+)/i, // Presto /(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i, // WebKit/Trident/NetFront/NetSurf/Amaya/Lynx/w3m/Goanna /ekioh(flow)\/([\w\.]+)/i, // Flow /(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i, // KHTML/Tasman/Links /(icab)[\/ ]([23]\.[\d\.]+)/i // iCab ], [NAME, VERSION], [ /rv\:([\w\.]{1,9})\b.+(gecko)/i // Gecko ], [VERSION, NAME] ], os: [ [ // Windows /microsoft (windows) (vista|xp)/i // Windows (iTunes) ], [NAME, VERSION], [ /(windows) nt 6\.2; (arm)/i, // Windows RT /(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i, // Windows Phone /(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i ], [NAME, [VERSION, strMapper, windowsVersionMap]], [/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i], [ [NAME, "Windows"], [VERSION, strMapper, windowsVersionMap] ], [ // iOS/macOS /ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i, // iOS /cfnetwork\/.+darwin/i ], [ [VERSION, /_/g, "."], [NAME, "iOS"] ], [ /(mac os x) ?([\w\. ]*)/i, /(macintosh|mac_powerpc\b)(?!.+haiku)/i // Mac OS ], [ [NAME, "Mac OS"], [VERSION, /_/g, "."] ], [ // Mobile OSes /droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i // Android-x86/HarmonyOS ], [VERSION, NAME], [ // Android/WebOS/QNX/Bada/RIM/Maemo/MeeGo/Sailfish OS /(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i, /(blackberry)\w*\/([\w\.]*)/i, // Blackberry /(tizen|kaios)[\/ ]([\w\.]+)/i, // Tizen/KaiOS /\((series40);/i // Series 40 ], [NAME, VERSION], [ /\(bb(10);/i // BlackBerry 10 ], [VERSION, [NAME, BLACKBERRY]], [ /(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i // Symbian ], [VERSION, [NAME, "Symbian"]], [ /mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i // Firefox OS ], [VERSION, [NAME, FIREFOX + " OS"]], [ /web0s;.+rt(tv)/i, /\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i // WebOS ], [VERSION, [NAME, "webOS"]], [ // Google Chromecast /crkey\/([\d\.]+)/i // Google Chromecast ], [VERSION, [NAME, CHROME + "cast"]], [ /(cros) [\w]+ ([\w\.]+\w)/i // Chromium OS ], [[NAME, "Chromium OS"], VERSION], [ // Console /(nintendo|playstation) ([wids345portablevuch]+)/i, // Nintendo/Playstation /(xbox); +xbox ([^\);]+)/i, // Microsoft Xbox (360, One, X, S, Series X, Series S) // Other /\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i, // Joli/Palm /(mint)[\/\(\) ]?(\w*)/i, // Mint /(mageia|vectorlinux)[; ]/i, // Mageia/VectorLinux /([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i, // Ubuntu/Debian/SUSE/Gentoo/Arch/Slackware/Fedora/Mandriva/CentOS/PCLinuxOS/RedHat/Zenwalk/Linpus/Raspbian/Plan9/Minix/RISCOS/Contiki/Deepin/Manjaro/elementary/Sabayon/Linspire /(hurd|linux) ?([\w\.]*)/i, // Hurd/Linux /(gnu) ?([\w\.]*)/i, // GNU /\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i, // FreeBSD/NetBSD/OpenBSD/PC-BSD/GhostBSD/DragonFly /(haiku) (\w+)/i // Haiku ], [NAME, VERSION], [ /(sunos) ?([\w\.\d]*)/i // Solaris ], [[NAME, "Solaris"], VERSION], [ /((?:open)?solaris)[-\/ ]?([\w\.]*)/i, // Solaris /(aix) ((\d)(?=\.|\)| )[\w\.])*/i, // AIX /\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux)/i, // BeOS/OS2/AmigaOS/MorphOS/OpenVMS/Fuchsia/HP-UX /(unix) ?([\w\.]*)/i // UNIX ], [NAME, VERSION] ] }; ///////////////// // Constructor //////////////// var UAParser = function (ua, extensions) { if (typeof ua === OBJ_TYPE) { extensions = ua; ua = undefined; } if (!(this instanceof UAParser)) { return new UAParser(ua, extensions).getResult(); } var _ua = ua || (typeof window !== UNDEF_TYPE && window.navigator && window.navigator.userAgent ? window.navigator.userAgent : EMPTY); var _rgxmap = extensions ? extend(regexes, extensions) : regexes; this.getBrowser = function () { var _browser = {}; _browser[NAME] = undefined; _browser[VERSION] = undefined; rgxMapper.call(_browser, _ua, _rgxmap.browser); _browser.major = majorize(_browser.version); return _browser; }; this.getCPU = function () { var _cpu = {}; _cpu[ARCHITECTURE] = undefined; rgxMapper.call(_cpu, _ua, _rgxmap.cpu); return _cpu; }; this.getDevice = function () { var _device = {}; _device[VENDOR] = undefined; _device[MODEL] = undefined; _device[TYPE] = undefined; rgxMapper.call(_device, _ua, _rgxmap.device); return _device; }; this.getEngine = function () { var _engine = {}; _engine[NAME] = undefined; _engine[VERSION] = undefined; rgxMapper.call(_engine, _ua, _rgxmap.engine); return _engine; }; this.getOS = function () { var _os = {}; _os[NAME] = undefined; _os[VERSION] = undefined; rgxMapper.call(_os, _ua, _rgxmap.os); return _os; }; this.getResult = function () { return { ua: this.getUA(), browser: this.getBrowser(), engine: this.getEngine(), os: this.getOS(), device: this.getDevice(), cpu: this.getCPU() }; }; this.getUA = function () { return _ua; }; this.setUA = function (ua) { _ua = typeof ua === STR_TYPE && ua.length > UA_MAX_LENGTH ? trim(ua, UA_MAX_LENGTH) : ua; return this; }; this.setUA(_ua); return this; }; UAParser.VERSION = LIBVERSION; UAParser.BROWSER = enumerize([NAME, VERSION, MAJOR]); UAParser.CPU = enumerize([ARCHITECTURE]); UAParser.DEVICE = enumerize([ MODEL, VENDOR, TYPE, CONSOLE, MOBILE, SMARTTV, TABLET, WEARABLE, EMBEDDED ]); UAParser.ENGINE = UAParser.OS = enumerize([NAME, VERSION]); /////////// // Export ////////// // check js environment if (typeof exports !== UNDEF_TYPE) { // nodejs env if (typeof module !== UNDEF_TYPE && module.exports) { exports = module.exports = UAParser; } exports.UAParser = UAParser; } else { // requirejs env (optional) if (typeof define === FUNC_TYPE && define.amd) { define(function () { return UAParser; }); } else if (typeof window !== UNDEF_TYPE) { // browser env window.UAParser = UAParser; } } // jQuery/Zepto specific (optional) // Note: // In AMD env the global scope should be kept clean, but jQuery is an exception. // jQuery always exports to global scope, unless jQuery.noConflict(true) is used, // and we should catch that. var $ = typeof window !== UNDEF_TYPE && (window.jQuery || window.Zepto); if ($ && !$.ua) { var parser = new UAParser(); $.ua = parser.getResult(); $.ua.get = function () { return parser.getUA(); }; $.ua.set = function (ua) { parser.setUA(ua); var result = parser.getResult(); for (var prop in result) { $.ua[prop] = result[prop]; } }; } })(typeof window === "object" ? window : this);
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/arrayLikeToArray.js
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;
}
module.exports = _arrayLikeToArray;
module.exports["default"] = module.exports, module.exports.__esModule = true;
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/arrayWithoutHoles.js
var arrayLikeToArray = require("./arrayLikeToArray.js");
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return arrayLikeToArray(arr);
}
module.exports = _arrayWithoutHoles;
module.exports["default"] = module.exports, module.exports.__esModule = true;
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/assertThisInitialized.js
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
module.exports = _assertThisInitialized;
module.exports["default"] = module.exports, module.exports.__esModule = true;
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/classCallCheck.js
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
module.exports = _classCallCheck;
module.exports["default"] = module.exports, module.exports.__esModule = true;
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/createClass.js
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;
}
module.exports = _createClass;
module.exports["default"] = module.exports, module.exports.__esModule = true;
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/defineProperty.js
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;
}
module.exports = _defineProperty;
module.exports["default"] = module.exports, module.exports.__esModule = true;
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/getPrototypeOf.js
function _getPrototypeOf(o) {
module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
module.exports["default"] = module.exports, module.exports.__esModule = true;
return _getPrototypeOf(o);
}
module.exports = _getPrototypeOf;
module.exports["default"] = module.exports, module.exports.__esModule = true;
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/inherits.js
var setPrototypeOf = require("./setPrototypeOf.js");
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);
}
module.exports = _inherits;
module.exports["default"] = module.exports, module.exports.__esModule = true;
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/interopRequireDefault.js
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
module.exports = _interopRequireDefault;
module.exports["default"] = module.exports, module.exports.__esModule = true;
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/iterableToArray.js
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
module.exports = _iterableToArray;
module.exports["default"] = module.exports, module.exports.__esModule = true;
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/nonIterableSpread.js
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.");
}
module.exports = _nonIterableSpread;
module.exports["default"] = module.exports, module.exports.__esModule = true;
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/objectWithoutProperties.js
var objectWithoutPropertiesLoose = require("./objectWithoutPropertiesLoose.js");
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;
}
module.exports = _objectWithoutProperties;
module.exports["default"] = module.exports, module.exports.__esModule = true;
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/objectWithoutPropertiesLoose.js
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;
}
module.exports = _objectWithoutPropertiesLoose;
module.exports["default"] = module.exports, module.exports.__esModule = true;
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js
var _typeof = require("@babel/runtime/helpers/typeof")["default"];
var assertThisInitialized = require("./assertThisInitialized.js");
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return assertThisInitialized(self);
}
module.exports = _possibleConstructorReturn;
module.exports["default"] = module.exports, module.exports.__esModule = true;
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/setPrototypeOf.js
function _setPrototypeOf(o, p) {
module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
module.exports["default"] = module.exports, module.exports.__esModule = true;
return _setPrototypeOf(o, p);
}
module.exports = _setPrototypeOf;
module.exports["default"] = module.exports, module.exports.__esModule = true;
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/toConsumableArray.js
var arrayWithoutHoles = require("./arrayWithoutHoles.js");
var iterableToArray = require("./iterableToArray.js");
var unsupportedIterableToArray = require("./unsupportedIterableToArray.js");
var nonIterableSpread = require("./nonIterableSpread.js");
function _toConsumableArray(arr) {
return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();
}
module.exports = _toConsumableArray;
module.exports["default"] = module.exports, module.exports.__esModule = true;
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/typeof.js
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
module.exports = _typeof = function _typeof(obj) {
return typeof obj;
};
module.exports["default"] = module.exports, module.exports.__esModule = true;
} else {
module.exports = _typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
module.exports["default"] = module.exports, module.exports.__esModule = true;
}
return _typeof(obj);
}
module.exports = _typeof;
module.exports["default"] = module.exports, module.exports.__esModule = true;
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js
var arrayLikeToArray = require("./arrayLikeToArray.js");
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);
}
module.exports = _unsupportedIterableToArray;
module.exports["default"] = module.exports, module.exports.__esModule = true;
webpack://frontend-mybets/../../node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js
/**
* Copyright (c) 2014-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 runtime = (function (exports) {
"use strict";
var Op = Object.prototype;
var hasOwn = Op.hasOwnProperty;
var undefined; // More compressible than void 0.
var $Symbol = typeof Symbol === "function" ? Symbol : {};
var iteratorSymbol = $Symbol.iterator || "@@iterator";
var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
function define(obj, key, value) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
return obj[key];
}
try {
// IE 8 has a broken Object.defineProperty that only works on DOM objects.
define({}, "");
} catch (err) {
define = function(obj, key, value) {
return obj[key] = value;
};
}
function wrap(innerFn, outerFn, self, tryLocsList) {
// If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
var generator = Object.create(protoGenerator.prototype);
var context = new Context(tryLocsList || []);
// The ._invoke method unifies the implementations of the .next,
// .throw, and .return methods.
generator._invoke = makeInvokeMethod(innerFn, self, context);
return generator;
}
exports.wrap = wrap;
// Try/catch helper to minimize deoptimizations. Returns a completion
// record like context.tryEntries[i].completion. This interface could
// have been (and was previously) designed to take a closure to be
// invoked without arguments, but in all the cases we care about we
// already have an existing method we want to call, so there's no need
// to create a new function object. We can even get away with assuming
// the method takes exactly one argument, since that happens to be true
// in every case, so we don't have to touch the arguments object. The
// only additional allocation required is the completion record, which
// has a stable shape and so hopefully should be cheap to allocate.
function tryCatch(fn, obj, arg) {
try {
return { type: "normal", arg: fn.call(obj, arg) };
} catch (err) {
return { type: "throw", arg: err };
}
}
var GenStateSuspendedStart = "suspendedStart";
var GenStateSuspendedYield = "suspendedYield";
var GenStateExecuting = "executing";
var GenStateCompleted = "completed";
// Returning this object from the innerFn has the same effect as
// breaking out of the dispatch switch statement.
var ContinueSentinel = {};
// Dummy constructor functions that we use as the .constructor and
// .constructor.prototype properties for functions that return Generator
// objects. For full spec compliance, you may wish to configure your
// minifier not to mangle the names of these two functions.
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
// This is a polyfill for %IteratorPrototype% for environments that
// don't natively support it.
var IteratorPrototype = {};
IteratorPrototype[iteratorSymbol] = function () {
return this;
};
var getProto = Object.getPrototypeOf;
var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
if (NativeIteratorPrototype &&
NativeIteratorPrototype !== Op &&
hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
// This environment has a native %IteratorPrototype%; use it instead
// of the polyfill.
IteratorPrototype = NativeIteratorPrototype;
}
var Gp = GeneratorFunctionPrototype.prototype =
Generator.prototype = Object.create(IteratorPrototype);
GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
GeneratorFunctionPrototype.constructor = GeneratorFunction;
GeneratorFunction.displayName = define(
GeneratorFunctionPrototype,
toStringTagSymbol,
"GeneratorFunction"
);
// Helper for defining the .next, .throw, and .return methods of the
// Iterator interface in terms of a single ._invoke method.
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function(method) {
define(prototype, method, function(arg) {
return this._invoke(method, arg);
});
});
}
exports.isGeneratorFunction = function(genFun) {
var ctor = typeof genFun === "function" && genFun.constructor;
return ctor
? ctor === GeneratorFunction ||
// For the native GeneratorFunction constructor, the best we can
// do is to check its .name property.
(ctor.displayName || ctor.name) === "GeneratorFunction"
: false;
};
exports.mark = function(genFun) {
if (Object.setPrototypeOf) {
Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
} else {
genFun.__proto__ = GeneratorFunctionPrototype;
define(genFun, toStringTagSymbol, "GeneratorFunction");
}
genFun.prototype = Object.create(Gp);
return genFun;
};
// Within the body of any async function, `await x` is transformed to
// `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
// `hasOwn.call(value, "__await")` to determine if the yielded value is
// meant to be awaited.
exports.awrap = function(arg) {
return { __await: arg };
};
function AsyncIterator(generator, PromiseImpl) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if (record.type === "throw") {
reject(record.arg);
} else {
var result = record.arg;
var value = result.value;
if (value &&
typeof value === "object" &&
hasOwn.call(value, "__await")) {
return PromiseImpl.resolve(value.__await).then(function(value) {
invoke("next", value, resolve, reject);
}, function(err) {
invoke("throw", err, resolve, reject);
});
}
return PromiseImpl.resolve(value).then(function(unwrapped) {
// When a yielded Promise is resolved, its final value becomes
// the .value of the Promise<{value,done}> result for the
// current iteration.
result.value = unwrapped;
resolve(result);
}, function(error) {
// If a rejected Promise was yielded, throw the rejection back
// into the async generator function so it can be handled there.
return invoke("throw", error, resolve, reject);
});
}
}
var previousPromise;
function enqueue(method, arg) {
function callInvokeWithMethodAndArg() {
return new PromiseImpl(function(resolve, reject) {
invoke(method, arg, resolve, reject);
});
}
return previousPromise =
// If enqueue has been called before, then we want to wait until
// all previous Promises have been resolved before calling invoke,
// so that results are always delivered in the correct order. If
// enqueue has not been called before, then it is important to
// call invoke immediately, without waiting on a callback to fire,
// so that the async generator function has the opportunity to do
// any necessary setup in a predictable way. This predictability
// is why the Promise constructor synchronously invokes its
// executor callback, and why async functions synchronously
// execute code before the first await. Since we implement simple
// async functions in terms of async generators, it is especially
// important to get this right, even though it requires care.
previousPromise ? previousPromise.then(
callInvokeWithMethodAndArg,
// Avoid propagating failures to Promises returned by later
// invocations of the iterator.
callInvokeWithMethodAndArg
) : callInvokeWithMethodAndArg();
}
// Define the unified helper method that is used to implement .next,
// .throw, and .return (see defineIteratorMethods).
this._invoke = enqueue;
}
defineIteratorMethods(AsyncIterator.prototype);
AsyncIterator.prototype[asyncIteratorSymbol] = function () {
return this;
};
exports.AsyncIterator = AsyncIterator;
// Note that simple async functions are implemented on top of
// AsyncIterator objects; they just return a Promise for the value of
// the final result produced by the iterator.
exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
if (PromiseImpl === void 0) PromiseImpl = Promise;
var iter = new AsyncIterator(
wrap(innerFn, outerFn, self, tryLocsList),
PromiseImpl
);
return exports.isGeneratorFunction(outerFn)
? iter // If outerFn is a generator, return the full iterator.
: iter.next().then(function(result) {
return result.done ? result.value : iter.next();
});
};
function makeInvokeMethod(innerFn, self, context) {
var state = GenStateSuspendedStart;
return function invoke(method, arg) {
if (state === GenStateExecuting) {
throw new Error("Generator is already running");
}
if (state === GenStateCompleted) {
if (method === "throw") {
throw arg;
}
// Be forgiving, per 25.3.3.3.3 of the spec:
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
return doneResult();
}
context.method = method;
context.arg = arg;
while (true) {
var delegate = context.delegate;
if (delegate) {
var delegateResult = maybeInvokeDelegate(delegate, context);
if (delegateResult) {
if (delegateResult === ContinueSentinel) continue;
return delegateResult;
}
}
if (context.method === "next") {
// Setting context._sent for legacy support of Babel's
// function.sent implementation.
context.sent = context._sent = context.arg;
} else if (context.method === "throw") {
if (state === GenStateSuspendedStart) {
state = GenStateCompleted;
throw context.arg;
}
context.dispatchException(context.arg);
} else if (context.method === "return") {
context.abrupt("return", context.arg);
}
state = GenStateExecuting;
var record = tryCatch(innerFn, self, context);
if (record.type === "normal") {
// If an exception is thrown from innerFn, we leave state ===
// GenStateExecuting and loop back for another invocation.
state = context.done
? GenStateCompleted
: GenStateSuspendedYield;
if (record.arg === ContinueSentinel) {
continue;
}
return {
value: record.arg,
done: context.done
};
} else if (record.type === "throw") {
state = GenStateCompleted;
// Dispatch the exception by looping back around to the
// context.dispatchException(context.arg) call above.
context.method = "throw";
context.arg = record.arg;
}
}
};
}
// Call delegate.iterator[context.method](context.arg) and handle the
// result, either by returning a { value, done } result from the
// delegate iterator, or by modifying context.method and context.arg,
// setting context.delegate to null, and returning the ContinueSentinel.
function maybeInvokeDelegate(delegate, context) {
var method = delegate.iterator[context.method];
if (method === undefined) {
// A .throw or .return when the delegate iterator has no .throw
// method always terminates the yield* loop.
context.delegate = null;
if (context.method === "throw") {
// Note: ["return"] must be used for ES3 parsing compatibility.
if (delegate.iterator["return"]) {
// If the delegate iterator has a return method, give it a
// chance to clean up.
context.method = "return";
context.arg = undefined;
maybeInvokeDelegate(delegate, context);
if (context.method === "throw") {
// If maybeInvokeDelegate(context) changed context.method from
// "return" to "throw", let that override the TypeError below.
return ContinueSentinel;
}
}
context.method = "throw";
context.arg = new TypeError(
"The iterator does not provide a 'throw' method");
}
return ContinueSentinel;
}
var record = tryCatch(method, delegate.iterator, context.arg);
if (record.type === "throw") {
context.method = "throw";
context.arg = record.arg;
context.delegate = null;
return ContinueSentinel;
}
var info = record.arg;
if (! info) {
context.method = "throw";
context.arg = new TypeError("iterator result is not an object");
context.delegate = null;
return ContinueSentinel;
}
if (info.done) {
// Assign the result of the finished delegate to the temporary
// variable specified by delegate.resultName (see delegateYield).
context[delegate.resultName] = info.value;
// Resume execution at the desired location (see delegateYield).
context.next = delegate.nextLoc;
// If context.method was "throw" but the delegate handled the
// exception, let the outer generator proceed normally. If
// context.method was "next", forget context.arg since it has been
// "consumed" by the delegate iterator. If context.method was
// "return", allow the original .return call to continue in the
// outer generator.
if (context.method !== "return") {
context.method = "next";
context.arg = undefined;
}
} else {
// Re-yield the result returned by the delegate method.
return info;
}
// The delegate iterator is finished, so forget it and continue with
// the outer generator.
context.delegate = null;
return ContinueSentinel;
}
// Define Generator.prototype.{next,throw,return} in terms of the
// unified ._invoke helper method.
defineIteratorMethods(Gp);
define(Gp, toStringTagSymbol, "Generator");
// A Generator should always return itself as the iterator object when the
// @@iterator function is called on it. Some browsers' implementations of the
// iterator prototype chain incorrectly implement this, causing the Generator
// object to not be returned from this call. This ensures that doesn't happen.
// See https://github.com/facebook/regenerator/issues/274 for more details.
Gp[iteratorSymbol] = function() {
return this;
};
Gp.toString = function() {
return "[object Generator]";
};
function pushTryEntry(locs) {
var entry = { tryLoc: locs[0] };
if (1 in locs) {
entry.catchLoc = locs[1];
}
if (2 in locs) {
entry.finallyLoc = locs[2];
entry.afterLoc = locs[3];
}
this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal";
delete record.arg;
entry.completion = record;
}
function Context(tryLocsList) {
// The root entry object (effectively a try statement without a catch
// or a finally block) gives us a place to store values thrown from
// locations where there is no enclosing try statement.
this.tryEntries = [{ tryLoc: "root" }];
tryLocsList.forEach(pushTryEntry, this);
this.reset(true);
}
exports.keys = function(object) {
var keys = [];
for (var key in object) {
keys.push(key);
}
keys.reverse();
// Rather than returning an object with a next method, we keep
// things simple and return the next function itself.
return function next() {
while (keys.length) {
var key = keys.pop();
if (key in object) {
next.value = key;
next.done = false;
return next;
}
}
// To avoid creating an additional object, we just hang the .value
// and .done properties off the next function object itself. This
// also ensures that the minifier will not anonymize the function.
next.done = true;
return next;
};
};
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) {
return iteratorMethod.call(iterable);
}
if (typeof iterable.next === "function") {
return iterable;
}
if (!isNaN(iterable.length)) {
var i = -1, next = function next() {
while (++i < iterable.length) {
if (hasOwn.call(iterable, i)) {
next.value = iterable[i];
next.done = false;
return next;
}
}
next.value = undefined;
next.done = true;
return next;
};
return next.next = next;
}
}
// Return an iterator with no values.
return { next: doneResult };
}
exports.values = values;
function doneResult() {
return { value: undefined, done: true };
}
Context.prototype = {
constructor: Context,
reset: function(skipTempReset) {
this.prev = 0;
this.next = 0;
// Resetting context._sent for legacy support of Babel's
// function.sent implementation.
this.sent = this._sent = undefined;
this.done = false;
this.delegate = null;
this.method = "next";
this.arg = undefined;
this.tryEntries.forEach(resetTryEntry);
if (!skipTempReset) {
for (var name in this) {
// Not sure about the optimal order of these conditions:
if (name.charAt(0) === "t" &&
hasOwn.call(this, name) &&
!isNaN(+name.slice(1))) {
this[name] = undefined;
}
}
}
},
stop: function() {
this.done = true;
var rootEntry = this.tryEntries[0];
var rootRecord = rootEntry.completion;
if (rootRecord.type === "throw") {
throw rootRecord.arg;
}
return this.rval;
},
dispatchException: function(exception) {
if (this.done) {
throw exception;
}
var context = this;
function handle(loc, caught) {
record.type = "throw";
record.arg = exception;
context.next = loc;
if (caught) {
// If the dispatched exception was caught by a catch block,
// then let that catch block handle the exception normally.
context.method = "next";
context.arg = undefined;
}
return !! caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
var record = entry.completion;
if (entry.tryLoc === "root") {
// Exception thrown outside of any try block that could handle
// it, so set the completion value of the entire function to
// throw the exception.
return handle("end");
}
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc");
var hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
} else if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else if (hasCatch) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
}
} else if (hasFinally) {
if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else {
throw new Error("try statement without catch or finally");
}
}
}
},
abrupt: function(type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev &&
hasOwn.call(entry, "finallyLoc") &&
this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
if (finallyEntry &&
(type === "break" ||
type === "continue") &&
finallyEntry.tryLoc <= arg &&
arg <= finallyEntry.finallyLoc) {
// Ignore the finally entry if control is not jumping to a
// location outside the try/catch block.
finallyEntry = null;
}
var record = finallyEntry ? finallyEntry.completion : {};
record.type = type;
record.arg = arg;
if (finallyEntry) {
this.method = "next";
this.next = finallyEntry.finallyLoc;
return ContinueSentinel;
}
return this.complete(record);
},
complete: function(record, afterLoc) {
if (record.type === "throw") {
throw record.arg;
}
if (record.type === "break" ||
record.type === "continue") {
this.next = record.arg;
} else if (record.type === "return") {
this.rval = this.arg = record.arg;
this.method = "return";
this.next = "end";
} else if (record.type === "normal" && afterLoc) {
this.next = afterLoc;
}
return ContinueSentinel;
},
finish: function(finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) {
this.complete(entry.completion, entry.afterLoc);
resetTryEntry(entry);
return ContinueSentinel;
}
}
},
"catch": function(tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if (record.type === "throw") {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
// The context.catch method must only be called with a location
// argument that corresponds to a known catch block.
throw new Error("illegal catch attempt");
},
delegateYield: function(iterable, resultName, nextLoc) {
this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
};
if (this.method === "next") {
// Deliberately forget the last sent value so that we don't
// accidentally pass it on to the delegate.
this.arg = undefined;
}
return ContinueSentinel;
}
};
// Regardless of whether this script is executing as a CommonJS module
// or not, return the runtime object so that we can declare the variable
// regeneratorRuntime in the outer scope, which allows this module to be
// injected easily by `bin/regenerator --include-runtime script.js`.
return exports;
}(
// If this script is executing as a CommonJS module, use module.exports
// as the regeneratorRuntime namespace. Otherwise create a new empty
// object. Either way, the resulting object will be used to initialize
// the regeneratorRuntime variable at the top of this file.
typeof module === "object" ? module.exports : {}
));
try {
regeneratorRuntime = runtime;
} catch (accidentalStrictMode) {
// This module should not be running in strict mode, so the above
// assignment should always work unless something is misconfigured. Just
// in case runtime.js accidentally runs in strict mode, we can escape
// strict mode using a global Function call. This could conceivably fail
// if a Content Security Policy forbids using Function, but in that case
// the proper solution is to fix the accidental strict mode problem. If
// you've misconfigured your bundler to force strict mode and applied a
// CSP to forbid Function, and you're not willing to fix either of those
// problems, please detail your unique predicament in a GitHub issue.
Function("r", "regeneratorRuntime = r")(runtime);
}
webpack://frontend-mybets/../../node_modules/@babel/runtime/regenerator/index.js
module.exports = require("regenerator-runtime");
webpack://frontend-mybets/../../node_modules/@emotion/stylis/dist/stylis.browser.esm.js
function stylis_min (W) {
function M(d, c, e, h, a) {
for (var m = 0, b = 0, v = 0, n = 0, q, g, x = 0, K = 0, k, u = k = q = 0, l = 0, r = 0, I = 0, t = 0, B = e.length, J = B - 1, y, f = '', p = '', F = '', G = '', C; l < B;) {
g = e.charCodeAt(l);
l === J && 0 !== b + n + v + m && (0 !== b && (g = 47 === b ? 10 : 47), n = v = m = 0, B++, J++);
if (0 === b + n + v + m) {
if (l === J && (0 < r && (f = f.replace(N, '')), 0 < f.trim().length)) {
switch (g) {
case 32:
case 9:
case 59:
case 13:
case 10:
break;
default:
f += e.charAt(l);
}
g = 59;
}
switch (g) {
case 123:
f = f.trim();
q = f.charCodeAt(0);
k = 1;
for (t = ++l; l < B;) {
switch (g = e.charCodeAt(l)) {
case 123:
k++;
break;
case 125:
k--;
break;
case 47:
switch (g = e.charCodeAt(l + 1)) {
case 42:
case 47:
a: {
for (u = l + 1; u < J; ++u) {
switch (e.charCodeAt(u)) {
case 47:
if (42 === g && 42 === e.charCodeAt(u - 1) && l + 2 !== u) {
l = u + 1;
break a;
}
break;
case 10:
if (47 === g) {
l = u + 1;
break a;
}
}
}
l = u;
}
}
break;
case 91:
g++;
case 40:
g++;
case 34:
case 39:
for (; l++ < J && e.charCodeAt(l) !== g;) {
}
}
if (0 === k) break;
l++;
}
k = e.substring(t, l);
0 === q && (q = (f = f.replace(ca, '').trim()).charCodeAt(0));
switch (q) {
case 64:
0 < r && (f = f.replace(N, ''));
g = f.charCodeAt(1);
switch (g) {
case 100:
case 109:
case 115:
case 45:
r = c;
break;
default:
r = O;
}
k = M(c, r, k, g, a + 1);
t = k.length;
0 < A && (r = X(O, f, I), C = H(3, k, r, c, D, z, t, g, a, h), f = r.join(''), void 0 !== C && 0 === (t = (k = C.trim()).length) && (g = 0, k = ''));
if (0 < t) switch (g) {
case 115:
f = f.replace(da, ea);
case 100:
case 109:
case 45:
k = f + '{' + k + '}';
break;
case 107:
f = f.replace(fa, '$1 $2');
k = f + '{' + k + '}';
k = 1 === w || 2 === w && L('@' + k, 3) ? '@-webkit-' + k + '@' + k : '@' + k;
break;
default:
k = f + k, 112 === h && (k = (p += k, ''));
} else k = '';
break;
default:
k = M(c, X(c, f, I), k, h, a + 1);
}
F += k;
k = I = r = u = q = 0;
f = '';
g = e.charCodeAt(++l);
break;
case 125:
case 59:
f = (0 < r ? f.replace(N, '') : f).trim();
if (1 < (t = f.length)) switch (0 === u && (q = f.charCodeAt(0), 45 === q || 96 < q && 123 > q) && (t = (f = f.replace(' ', ':')).length), 0 < A && void 0 !== (C = H(1, f, c, d, D, z, p.length, h, a, h)) && 0 === (t = (f = C.trim()).length) && (f = '\x00\x00'), q = f.charCodeAt(0), g = f.charCodeAt(1), q) {
case 0:
break;
case 64:
if (105 === g || 99 === g) {
G += f + e.charAt(l);
break;
}
default:
58 !== f.charCodeAt(t - 1) && (p += P(f, q, g, f.charCodeAt(2)));
}
I = r = u = q = 0;
f = '';
g = e.charCodeAt(++l);
}
}
switch (g) {
case 13:
case 10:
47 === b ? b = 0 : 0 === 1 + q && 107 !== h && 0 < f.length && (r = 1, f += '\x00');
0 < A * Y && H(0, f, c, d, D, z, p.length, h, a, h);
z = 1;
D++;
break;
case 59:
case 125:
if (0 === b + n + v + m) {
z++;
break;
}
default:
z++;
y = e.charAt(l);
switch (g) {
case 9:
case 32:
if (0 === n + m + b) switch (x) {
case 44:
case 58:
case 9:
case 32:
y = '';
break;
default:
32 !== g && (y = ' ');
}
break;
case 0:
y = '\\0';
break;
case 12:
y = '\\f';
break;
case 11:
y = '\\v';
break;
case 38:
0 === n + b + m && (r = I = 1, y = '\f' + y);
break;
case 108:
if (0 === n + b + m + E && 0 < u) switch (l - u) {
case 2:
112 === x && 58 === e.charCodeAt(l - 3) && (E = x);
case 8:
111 === K && (E = K);
}
break;
case 58:
0 === n + b + m && (u = l);
break;
case 44:
0 === b + v + n + m && (r = 1, y += '\r');
break;
case 34:
case 39:
0 === b && (n = n === g ? 0 : 0 === n ? g : n);
break;
case 91:
0 === n + b + v && m++;
break;
case 93:
0 === n + b + v && m--;
break;
case 41:
0 === n + b + m && v--;
break;
case 40:
if (0 === n + b + m) {
if (0 === q) switch (2 * x + 3 * K) {
case 533:
break;
default:
q = 1;
}
v++;
}
break;
case 64:
0 === b + v + n + m + u + k && (k = 1);
break;
case 42:
case 47:
if (!(0 < n + m + v)) switch (b) {
case 0:
switch (2 * g + 3 * e.charCodeAt(l + 1)) {
case 235:
b = 47;
break;
case 220:
t = l, b = 42;
}
break;
case 42:
47 === g && 42 === x && t + 2 !== l && (33 === e.charCodeAt(t + 2) && (p += e.substring(t, l + 1)), y = '', b = 0);
}
}
0 === b && (f += y);
}
K = x;
x = g;
l++;
}
t = p.length;
if (0 < t) {
r = c;
if (0 < A && (C = H(2, p, r, d, D, z, t, h, a, h), void 0 !== C && 0 === (p = C).length)) return G + p + F;
p = r.join(',') + '{' + p + '}';
if (0 !== w * E) {
2 !== w || L(p, 2) || (E = 0);
switch (E) {
case 111:
p = p.replace(ha, ':-moz-$1') + p;
break;
case 112:
p = p.replace(Q, '::-webkit-input-$1') + p.replace(Q, '::-moz-$1') + p.replace(Q, ':-ms-input-$1') + p;
}
E = 0;
}
}
return G + p + F;
}
function X(d, c, e) {
var h = c.trim().split(ia);
c = h;
var a = h.length,
m = d.length;
switch (m) {
case 0:
case 1:
var b = 0;
for (d = 0 === m ? '' : d[0] + ' '; b < a; ++b) {
c[b] = Z(d, c[b], e).trim();
}
break;
default:
var v = b = 0;
for (c = []; b < a; ++b) {
for (var n = 0; n < m; ++n) {
c[v++] = Z(d[n] + ' ', h[b], e).trim();
}
}
}
return c;
}
function Z(d, c, e) {
var h = c.charCodeAt(0);
33 > h && (h = (c = c.trim()).charCodeAt(0));
switch (h) {
case 38:
return c.replace(F, '$1' + d.trim());
case 58:
return d.trim() + c.replace(F, '$1' + d.trim());
default:
if (0 < 1 * e && 0 < c.indexOf('\f')) return c.replace(F, (58 === d.charCodeAt(0) ? '' : '$1') + d.trim());
}
return d + c;
}
function P(d, c, e, h) {
var a = d + ';',
m = 2 * c + 3 * e + 4 * h;
if (944 === m) {
d = a.indexOf(':', 9) + 1;
var b = a.substring(d, a.length - 1).trim();
b = a.substring(0, d).trim() + b + ';';
return 1 === w || 2 === w && L(b, 1) ? '-webkit-' + b + b : b;
}
if (0 === w || 2 === w && !L(a, 1)) return a;
switch (m) {
case 1015:
return 97 === a.charCodeAt(10) ? '-webkit-' + a + a : a;
case 951:
return 116 === a.charCodeAt(3) ? '-webkit-' + a + a : a;
case 963:
return 110 === a.charCodeAt(5) ? '-webkit-' + a + a : a;
case 1009:
if (100 !== a.charCodeAt(4)) break;
case 969:
case 942:
return '-webkit-' + a + a;
case 978:
return '-webkit-' + a + '-moz-' + a + a;
case 1019:
case 983:
return '-webkit-' + a + '-moz-' + a + '-ms-' + a + a;
case 883:
if (45 === a.charCodeAt(8)) return '-webkit-' + a + a;
if (0 < a.indexOf('image-set(', 11)) return a.replace(ja, '$1-webkit-$2') + a;
break;
case 932:
if (45 === a.charCodeAt(4)) switch (a.charCodeAt(5)) {
case 103:
return '-webkit-box-' + a.replace('-grow', '') + '-webkit-' + a + '-ms-' + a.replace('grow', 'positive') + a;
case 115:
return '-webkit-' + a + '-ms-' + a.replace('shrink', 'negative') + a;
case 98:
return '-webkit-' + a + '-ms-' + a.replace('basis', 'preferred-size') + a;
}
return '-webkit-' + a + '-ms-' + a + a;
case 964:
return '-webkit-' + a + '-ms-flex-' + a + a;
case 1023:
if (99 !== a.charCodeAt(8)) break;
b = a.substring(a.indexOf(':', 15)).replace('flex-', '').replace('space-between', 'justify');
return '-webkit-box-pack' + b + '-webkit-' + a + '-ms-flex-pack' + b + a;
case 1005:
return ka.test(a) ? a.replace(aa, ':-webkit-') + a.replace(aa, ':-moz-') + a : a;
case 1e3:
b = a.substring(13).trim();
c = b.indexOf('-') + 1;
switch (b.charCodeAt(0) + b.charCodeAt(c)) {
case 226:
b = a.replace(G, 'tb');
break;
case 232:
b = a.replace(G, 'tb-rl');
break;
case 220:
b = a.replace(G, 'lr');
break;
default:
return a;
}
return '-webkit-' + a + '-ms-' + b + a;
case 1017:
if (-1 === a.indexOf('sticky', 9)) break;
case 975:
c = (a = d).length - 10;
b = (33 === a.charCodeAt(c) ? a.substring(0, c) : a).substring(d.indexOf(':', 7) + 1).trim();
switch (m = b.charCodeAt(0) + (b.charCodeAt(7) | 0)) {
case 203:
if (111 > b.charCodeAt(8)) break;
case 115:
a = a.replace(b, '-webkit-' + b) + ';' + a;
break;
case 207:
case 102:
a = a.replace(b, '-webkit-' + (102 < m ? 'inline-' : '') + 'box') + ';' + a.replace(b, '-webkit-' + b) + ';' + a.replace(b, '-ms-' + b + 'box') + ';' + a;
}
return a + ';';
case 938:
if (45 === a.charCodeAt(5)) switch (a.charCodeAt(6)) {
case 105:
return b = a.replace('-items', ''), '-webkit-' + a + '-webkit-box-' + b + '-ms-flex-' + b + a;
case 115:
return '-webkit-' + a + '-ms-flex-item-' + a.replace(ba, '') + a;
default:
return '-webkit-' + a + '-ms-flex-line-pack' + a.replace('align-content', '').replace(ba, '') + a;
}
break;
case 973:
case 989:
if (45 !== a.charCodeAt(3) || 122 === a.charCodeAt(4)) break;
case 931:
case 953:
if (!0 === la.test(d)) return 115 === (b = d.substring(d.indexOf(':') + 1)).charCodeAt(0) ? P(d.replace('stretch', 'fill-available'), c, e, h).replace(':fill-available', ':stretch') : a.replace(b, '-webkit-' + b) + a.replace(b, '-moz-' + b.replace('fill-', '')) + a;
break;
case 962:
if (a = '-webkit-' + a + (102 === a.charCodeAt(5) ? '-ms-' + a : '') + a, 211 === e + h && 105 === a.charCodeAt(13) && 0 < a.indexOf('transform', 10)) return a.substring(0, a.indexOf(';', 27) + 1).replace(ma, '$1-webkit-$2') + a;
}
return a;
}
function L(d, c) {
var e = d.indexOf(1 === c ? ':' : '{'),
h = d.substring(0, 3 !== c ? e : 10);
e = d.substring(e + 1, d.length - 1);
return R(2 !== c ? h : h.replace(na, '$1'), e, c);
}
function ea(d, c) {
var e = P(c, c.charCodeAt(0), c.charCodeAt(1), c.charCodeAt(2));
return e !== c + ';' ? e.replace(oa, ' or ($1)').substring(4) : '(' + c + ')';
}
function H(d, c, e, h, a, m, b, v, n, q) {
for (var g = 0, x = c, w; g < A; ++g) {
switch (w = S[g].call(B, d, x, e, h, a, m, b, v, n, q)) {
case void 0:
case !1:
case !0:
case null:
break;
default:
x = w;
}
}
if (x !== c) return x;
}
function T(d) {
switch (d) {
case void 0:
case null:
A = S.length = 0;
break;
default:
if ('function' === typeof d) S[A++] = d;else if ('object' === typeof d) for (var c = 0, e = d.length; c < e; ++c) {
T(d[c]);
} else Y = !!d | 0;
}
return T;
}
function U(d) {
d = d.prefix;
void 0 !== d && (R = null, d ? 'function' !== typeof d ? w = 1 : (w = 2, R = d) : w = 0);
return U;
}
function B(d, c) {
var e = d;
33 > e.charCodeAt(0) && (e = e.trim());
V = e;
e = [V];
if (0 < A) {
var h = H(-1, c, e, e, D, z, 0, 0, 0, 0);
void 0 !== h && 'string' === typeof h && (c = h);
}
var a = M(O, e, c, 0, 0);
0 < A && (h = H(-2, a, e, e, D, z, a.length, 0, 0, 0), void 0 !== h && (a = h));
V = '';
E = 0;
z = D = 1;
return a;
}
var ca = /^\0+/g,
N = /[\0\r\f]/g,
aa = /: */g,
ka = /zoo|gra/,
ma = /([,: ])(transform)/g,
ia = /,\r+?/g,
F = /([\t\r\n ])*\f?&/g,
fa = /@(k\w+)\s*(\S*)\s*/,
Q = /::(place)/g,
ha = /:(read-only)/g,
G = /[svh]\w+-[tblr]{2}/,
da = /\(\s*(.*)\s*\)/g,
oa = /([\s\S]*?);/g,
ba = /-self|flex-/g,
na = /[^]*?(:[rp][el]a[\w-]+)[^]*/,
la = /stretch|:\s*\w+\-(?:conte|avail)/,
ja = /([^-])(image-set\()/,
z = 1,
D = 1,
E = 0,
w = 1,
O = [],
S = [],
A = 0,
R = null,
Y = 0,
V = '';
B.use = T;
B.set = U;
void 0 !== W && U(W);
return B;
}
export default stylis_min;
webpack://frontend-mybets/../../node_modules/@emotion/unitless/dist/emotion-unitless.esm.js
var unitlessKeys = {
animationIterationCount: 1,
aspectRatio: 1,
borderImageOutset: 1,
borderImageSlice: 1,
borderImageWidth: 1,
boxFlex: 1,
boxFlexGroup: 1,
boxOrdinalGroup: 1,
columnCount: 1,
columns: 1,
flex: 1,
flexGrow: 1,
flexPositive: 1,
flexShrink: 1,
flexNegative: 1,
flexOrder: 1,
gridRow: 1,
gridRowEnd: 1,
gridRowSpan: 1,
gridRowStart: 1,
gridColumn: 1,
gridColumnEnd: 1,
gridColumnSpan: 1,
gridColumnStart: 1,
msGridRow: 1,
msGridRowSpan: 1,
msGridColumn: 1,
msGridColumnSpan: 1,
fontWeight: 1,
lineHeight: 1,
opacity: 1,
order: 1,
orphans: 1,
scale: 1,
tabSize: 1,
widows: 1,
zIndex: 1,
zoom: 1,
WebkitLineClamp: 1,
// SVG-related properties
fillOpacity: 1,
floodOpacity: 1,
stopOpacity: 1,
strokeDasharray: 1,
strokeDashoffset: 1,
strokeMiterlimit: 1,
strokeOpacity: 1,
strokeWidth: 1
};
export { unitlessKeys as default };
webpack://frontend-mybets/../../node_modules/@react-spring/animated/dist/react-spring-animated.esm.js
import { defineHidden, is, createInterpolator, eachProp, hasFluidValue, getFluidValue, each, isAnimatedString, useForceUpdate, useLayoutEffect, addFluidObserver, removeFluidObserver, raf, useOnce } from '@react-spring/shared';
import * as React from 'react';
import { forwardRef, useRef, useCallback, useEffect } from 'react';
const $node = Symbol.for('Animated:node');
const isAnimated = value => !!value && value[$node] === value;
const getAnimated = owner => owner && owner[$node];
const setAnimated = (owner, node) => defineHidden(owner, $node, node);
const getPayload = owner => owner && owner[$node] && owner[$node].getPayload();
class Animated {
constructor() {
this.payload = void 0;
setAnimated(this, this);
}
getPayload() {
return this.payload || [];
}
}
class AnimatedValue extends Animated {
constructor(_value) {
super();
this.done = true;
this.elapsedTime = void 0;
this.lastPosition = void 0;
this.lastVelocity = void 0;
this.v0 = void 0;
this.durationProgress = 0;
this._value = _value;
if (is.num(this._value)) {
this.lastPosition = this._value;
}
}
static create(value) {
return new AnimatedValue(value);
}
getPayload() {
return [this];
}
getValue() {
return this._value;
}
setValue(value, step) {
if (is.num(value)) {
this.lastPosition = value;
if (step) {
value = Math.round(value / step) * step;
if (this.done) {
this.lastPosition = value;
}
}
}
if (this._value === value) {
return false;
}
this._value = value;
return true;
}
reset() {
const {
done
} = this;
this.done = false;
if (is.num(this._value)) {
this.elapsedTime = 0;
this.durationProgress = 0;
this.lastPosition = this._value;
if (done) this.lastVelocity = null;
this.v0 = null;
}
}
}
class AnimatedString extends AnimatedValue {
constructor(value) {
super(0);
this._string = null;
this._toString = void 0;
this._toString = createInterpolator({
output: [value, value]
});
}
static create(value) {
return new AnimatedString(value);
}
getValue() {
let value = this._string;
return value == null ? this._string = this._toString(this._value) : value;
}
setValue(value) {
if (is.str(value)) {
if (value == this._string) {
return false;
}
this._string = value;
this._value = 1;
} else if (super.setValue(value)) {
this._string = null;
} else {
return false;
}
return true;
}
reset(goal) {
if (goal) {
this._toString = createInterpolator({
output: [this.getValue(), goal]
});
}
this._value = 0;
super.reset();
}
}
const TreeContext = {
dependencies: null
};
class AnimatedObject extends Animated {
constructor(source) {
super();
this.source = source;
this.setValue(source);
}
getValue(animated) {
const values = {};
eachProp(this.source, (source, key) => {
if (isAnimated(source)) {
values[key] = source.getValue(animated);
} else if (hasFluidValue(source)) {
values[key] = getFluidValue(source);
} else if (!animated) {
values[key] = source;
}
});
return values;
}
setValue(source) {
this.source = source;
this.payload = this._makePayload(source);
}
reset() {
if (this.payload) {
each(this.payload, node => node.reset());
}
}
_makePayload(source) {
if (source) {
const payload = new Set();
eachProp(source, this._addToPayload, payload);
return Array.from(payload);
}
}
_addToPayload(source) {
if (TreeContext.dependencies && hasFluidValue(source)) {
TreeContext.dependencies.add(source);
}
const payload = getPayload(source);
if (payload) {
each(payload, node => this.add(node));
}
}
}
class AnimatedArray extends AnimatedObject {
constructor(source) {
super(source);
}
static create(source) {
return new AnimatedArray(source);
}
getValue() {
return this.source.map(node => node.getValue());
}
setValue(source) {
const payload = this.getPayload();
if (source.length == payload.length) {
return payload.map((node, i) => node.setValue(source[i])).some(Boolean);
}
super.setValue(source.map(makeAnimated));
return true;
}
}
function makeAnimated(value) {
const nodeType = isAnimatedString(value) ? AnimatedString : AnimatedValue;
return nodeType.create(value);
}
function getAnimatedType(value) {
const parentNode = getAnimated(value);
return parentNode ? parentNode.constructor : is.arr(value) ? AnimatedArray : isAnimatedString(value) ? AnimatedString : AnimatedValue;
}
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);
}
const withAnimated = (Component, host) => {
const hasInstance = !is.fun(Component) || Component.prototype && Component.prototype.isReactComponent;
return forwardRef((givenProps, givenRef) => {
const instanceRef = useRef(null);
const ref = hasInstance && useCallback(value => {
instanceRef.current = updateRef(givenRef, value);
}, [givenRef]);
const [props, deps] = getAnimatedState(givenProps, host);
const forceUpdate = useForceUpdate();
const callback = () => {
const instance = instanceRef.current;
if (hasInstance && !instance) {
return;
}
const didUpdate = instance ? host.applyAnimatedValues(instance, props.getValue(true)) : false;
if (didUpdate === false) {
forceUpdate();
}
};
const observer = new PropsObserver(callback, deps);
const observerRef = useRef();
useLayoutEffect(() => {
observerRef.current = observer;
each(deps, dep => addFluidObserver(dep, observer));
return () => {
if (observerRef.current) {
each(observerRef.current.deps, dep => removeFluidObserver(dep, observerRef.current));
raf.cancel(observerRef.current.update);
}
};
});
useEffect(callback, []);
useOnce(() => () => {
const observer = observerRef.current;
each(observer.deps, dep => removeFluidObserver(dep, observer));
});
const usedProps = host.getComponentProps(props.getValue());
return React.createElement(Component, _extends({}, usedProps, {
ref: ref
}));
});
};
class PropsObserver {
constructor(update, deps) {
this.update = update;
this.deps = deps;
}
eventObserved(event) {
if (event.type == 'change') {
raf.write(this.update);
}
}
}
function getAnimatedState(props, host) {
const dependencies = new Set();
TreeContext.dependencies = dependencies;
if (props.style) props = _extends({}, props, {
style: host.createAnimatedStyle(props.style)
});
props = new AnimatedObject(props);
TreeContext.dependencies = null;
return [props, dependencies];
}
function updateRef(ref, value) {
if (ref) {
if (is.fun(ref)) ref(value);else ref.current = value;
}
return value;
}
const cacheKey = Symbol.for('AnimatedComponent');
const createHost = (components, {
applyAnimatedValues: _applyAnimatedValues = () => false,
createAnimatedStyle: _createAnimatedStyle = style => new AnimatedObject(style),
getComponentProps: _getComponentProps = props => props
} = {}) => {
const hostConfig = {
applyAnimatedValues: _applyAnimatedValues,
createAnimatedStyle: _createAnimatedStyle,
getComponentProps: _getComponentProps
};
const animated = Component => {
const displayName = getDisplayName(Component) || 'Anonymous';
if (is.str(Component)) {
Component = animated[Component] || (animated[Component] = withAnimated(Component, hostConfig));
} else {
Component = Component[cacheKey] || (Component[cacheKey] = withAnimated(Component, hostConfig));
}
Component.displayName = `Animated(${displayName})`;
return Component;
};
eachProp(components, (Component, key) => {
if (is.arr(components)) {
key = getDisplayName(Component);
}
animated[key] = animated(Component);
});
return {
animated
};
};
const getDisplayName = arg => is.str(arg) ? arg : arg && is.str(arg.displayName) ? arg.displayName : is.fun(arg) && arg.name || null;
export { Animated, AnimatedArray, AnimatedObject, AnimatedString, AnimatedValue, createHost, getAnimated, getAnimatedType, getPayload, isAnimated, setAnimated };
webpack://frontend-mybets/../../node_modules/@react-spring/native/dist/react-spring-native.esm.js
import { View, Text, Image, StyleSheet } from 'react-native';
import { AnimatedObject, createHost } from '@react-spring/animated';
import { eachProp, getFluidValue, each, Globals, createStringInterpolator, colors, is } from '@react-spring/shared';
export * from '@react-spring/core';
const primitives = {
View: View,
Text: Text,
Image
};
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);
}
class AnimatedTransform extends AnimatedObject {
constructor(source) {
super(source);
}
getValue() {
return this.source ? this.source.map(source => {
const transform = {};
eachProp(source, (source, key) => {
transform[key] = getFluidValue(source);
});
return transform;
}) : [];
}
setValue(source) {
this.source = source;
this.payload = this._makePayload(source);
}
_makePayload(source) {
if (!source) return [];
const payload = new Set();
each(source, transform => eachProp(transform, this._addToPayload, payload));
return Array.from(payload);
}
}
class AnimatedStyle extends AnimatedObject {
constructor(style) {
super(style);
}
setValue(style) {
super.setValue(style && style.transform ? _extends({}, style, {
transform: new AnimatedTransform(style.transform)
}) : style);
}
}
Globals.assign({
batchedUpdates: require('react-native').unstable_batchedUpdates,
createStringInterpolator,
colors
});
const host = createHost(primitives, {
applyAnimatedValues(instance, props) {
if (is.und(props.children) && instance.setNativeProps) {
instance.setNativeProps(props);
return true;
}
return false;
},
createAnimatedStyle(styles) {
styles = StyleSheet.flatten(styles);
if (is.obj(styles.shadowOffset)) {
styles.shadowOffset = new AnimatedObject(styles.shadowOffset);
}
return new AnimatedStyle(styles);
}
});
const animated = host.animated;
export { animated as a, animated };
webpack://frontend-mybets/../../node_modules/@react-spring/native/node_modules/@react-spring/core/dist/react-spring-core.esm.js
import { eachProp, is, toArray, isAnimatedString, Globals, getFluidValue, useLayoutEffect, each, raf, flush, FluidValue, deprecateInterpolate, callFluidObservers, frameLoop, hasFluidValue, flushCalls, isEqual, getFluidObservers, addFluidObserver, removeFluidObserver, noop, useMemoOne, deprecateDirectCall, useForceUpdate, usePrev, useOnce, createInterpolator, createStringInterpolator } from '@react-spring/shared';
export { Globals, createInterpolator } from '@react-spring/shared';
import * as React from 'react';
import { useContext, useMemo, useRef, useState } from 'react';
import { getAnimated, AnimatedValue, getPayload, AnimatedString, getAnimatedType, setAnimated } from '@react-spring/animated';
export * from '@react-spring/types/animated';
export * from '@react-spring/types/interpolation';
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 callProp(value, ...args) {
return is.fun(value) ? value(...args) : value;
}
const matchProp = (value, key) => value === true || !!(key && value && (is.fun(value) ? value(key) : toArray(value).includes(key)));
const resolveProp = (prop, key) => is.obj(prop) ? key && prop[key] : prop;
const getDefaultProp = (props, key) => props.default === true ? props[key] : props.default ? props.default[key] : undefined;
const noopTransform = value => value;
const getDefaultProps = (props, transform = noopTransform) => {
let keys = DEFAULT_PROPS;
if (props.default && props.default !== true) {
props = props.default;
keys = Object.keys(props);
}
const defaults = {};
for (const key of keys) {
const value = transform(props[key], key);
if (!is.und(value)) {
defaults[key] = value;
}
}
return defaults;
};
const DEFAULT_PROPS = ['config', 'onProps', 'onStart', 'onChange', 'onPause', 'onResume', 'onRest'];
const RESERVED_PROPS = {
config: 1,
from: 1,
to: 1,
ref: 1,
loop: 1,
reset: 1,
pause: 1,
cancel: 1,
reverse: 1,
immediate: 1,
default: 1,
delay: 1,
onProps: 1,
onStart: 1,
onChange: 1,
onPause: 1,
onResume: 1,
onRest: 1,
onResolve: 1,
items: 1,
trail: 1,
sort: 1,
expires: 1,
initial: 1,
enter: 1,
update: 1,
leave: 1,
children: 1,
onDestroyed: 1,
keys: 1,
callId: 1,
parentId: 1
};
function getForwardProps(props) {
const forward = {};
let count = 0;
eachProp(props, (value, prop) => {
if (!RESERVED_PROPS[prop]) {
forward[prop] = value;
count++;
}
});
if (count) {
return forward;
}
}
function inferTo(props) {
const to = getForwardProps(props);
if (to) {
const out = {
to
};
eachProp(props, (val, key) => key in to || (out[key] = val));
return out;
}
return _extends({}, props);
}
function computeGoal(value) {
value = getFluidValue(value);
return is.arr(value) ? value.map(computeGoal) : isAnimatedString(value) ? Globals.createStringInterpolator({
range: [0, 1],
output: [value, value]
})(1) : value;
}
function hasProps(props) {
for (const _ in props) return true;
return false;
}
function isAsyncTo(to) {
return is.fun(to) || is.arr(to) && is.obj(to[0]);
}
function detachRefs(ctrl, ref) {
var _ctrl$ref;
(_ctrl$ref = ctrl.ref) == null ? void 0 : _ctrl$ref.delete(ctrl);
ref == null ? void 0 : ref.delete(ctrl);
}
function replaceRef(ctrl, ref) {
if (ref && ctrl.ref !== ref) {
var _ctrl$ref2;
(_ctrl$ref2 = ctrl.ref) == null ? void 0 : _ctrl$ref2.delete(ctrl);
ref.add(ctrl);
ctrl.ref = ref;
}
}
function useChain(refs, timeSteps, timeFrame = 1000) {
useLayoutEffect(() => {
if (timeSteps) {
let prevDelay = 0;
each(refs, (ref, i) => {
const controllers = ref.current;
if (controllers.length) {
let delay = timeFrame * timeSteps[i];
if (isNaN(delay)) delay = prevDelay;else prevDelay = delay;
each(controllers, ctrl => {
each(ctrl.queue, props => {
const memoizedDelayProp = props.delay;
props.delay = key => delay + callProp(memoizedDelayProp || 0, key);
});
});
ref.start();
}
});
} else {
let p = Promise.resolve();
each(refs, ref => {
const controllers = ref.current;
if (controllers.length) {
const queues = controllers.map(ctrl => {
const q = ctrl.queue;
ctrl.queue = [];
return q;
});
p = p.then(() => {
each(controllers, (ctrl, i) => each(queues[i] || [], update => ctrl.queue.push(update)));
return Promise.all(ref.start());
});
}
});
}
});
}
const config = {
default: {
tension: 170,
friction: 26
},
gentle: {
tension: 120,
friction: 14
},
wobbly: {
tension: 180,
friction: 12
},
stiff: {
tension: 210,
friction: 20
},
slow: {
tension: 280,
friction: 60
},
molasses: {
tension: 280,
friction: 120
}
};
const c1 = 1.70158;
const c2 = c1 * 1.525;
const c3 = c1 + 1;
const c4 = 2 * Math.PI / 3;
const c5 = 2 * Math.PI / 4.5;
const bounceOut = x => {
const n1 = 7.5625;
const d1 = 2.75;
if (x < 1 / d1) {
return n1 * x * x;
} else if (x < 2 / d1) {
return n1 * (x -= 1.5 / d1) * x + 0.75;
} else if (x < 2.5 / d1) {
return n1 * (x -= 2.25 / d1) * x + 0.9375;
} else {
return n1 * (x -= 2.625 / d1) * x + 0.984375;
}
};
const easings = {
linear: x => x,
easeInQuad: x => x * x,
easeOutQuad: x => 1 - (1 - x) * (1 - x),
easeInOutQuad: x => x < 0.5 ? 2 * x * x : 1 - Math.pow(-2 * x + 2, 2) / 2,
easeInCubic: x => x * x * x,
easeOutCubic: x => 1 - Math.pow(1 - x, 3),
easeInOutCubic: x => x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2,
easeInQuart: x => x * x * x * x,
easeOutQuart: x => 1 - Math.pow(1 - x, 4),
easeInOutQuart: x => x < 0.5 ? 8 * x * x * x * x : 1 - Math.pow(-2 * x + 2, 4) / 2,
easeInQuint: x => x * x * x * x * x,
easeOutQuint: x => 1 - Math.pow(1 - x, 5),
easeInOutQuint: x => x < 0.5 ? 16 * x * x * x * x * x : 1 - Math.pow(-2 * x + 2, 5) / 2,
easeInSine: x => 1 - Math.cos(x * Math.PI / 2),
easeOutSine: x => Math.sin(x * Math.PI / 2),
easeInOutSine: x => -(Math.cos(Math.PI * x) - 1) / 2,
easeInExpo: x => x === 0 ? 0 : Math.pow(2, 10 * x - 10),
easeOutExpo: x => x === 1 ? 1 : 1 - Math.pow(2, -10 * x),
easeInOutExpo: x => x === 0 ? 0 : x === 1 ? 1 : x < 0.5 ? Math.pow(2, 20 * x - 10) / 2 : (2 - Math.pow(2, -20 * x + 10)) / 2,
easeInCirc: x => 1 - Math.sqrt(1 - Math.pow(x, 2)),
easeOutCirc: x => Math.sqrt(1 - Math.pow(x - 1, 2)),
easeInOutCirc: x => x < 0.5 ? (1 - Math.sqrt(1 - Math.pow(2 * x, 2))) / 2 : (Math.sqrt(1 - Math.pow(-2 * x + 2, 2)) + 1) / 2,
easeInBack: x => c3 * x * x * x - c1 * x * x,
easeOutBack: x => 1 + c3 * Math.pow(x - 1, 3) + c1 * Math.pow(x - 1, 2),
easeInOutBack: x => x < 0.5 ? Math.pow(2 * x, 2) * ((c2 + 1) * 2 * x - c2) / 2 : (Math.pow(2 * x - 2, 2) * ((c2 + 1) * (x * 2 - 2) + c2) + 2) / 2,
easeInElastic: x => x === 0 ? 0 : x === 1 ? 1 : -Math.pow(2, 10 * x - 10) * Math.sin((x * 10 - 10.75) * c4),
easeOutElastic: x => x === 0 ? 0 : x === 1 ? 1 : Math.pow(2, -10 * x) * Math.sin((x * 10 - 0.75) * c4) + 1,
easeInOutElastic: x => x === 0 ? 0 : x === 1 ? 1 : x < 0.5 ? -(Math.pow(2, 20 * x - 10) * Math.sin((20 * x - 11.125) * c5)) / 2 : Math.pow(2, -20 * x + 10) * Math.sin((20 * x - 11.125) * c5) / 2 + 1,
easeInBounce: x => 1 - bounceOut(1 - x),
easeOutBounce: bounceOut,
easeInOutBounce: x => x < 0.5 ? (1 - bounceOut(1 - 2 * x)) / 2 : (1 + bounceOut(2 * x - 1)) / 2
};
const defaults = _extends({}, config.default, {
mass: 1,
damping: 1,
easing: easings.linear,
clamp: false
});
class AnimationConfig {
constructor() {
this.tension = void 0;
this.friction = void 0;
this.frequency = void 0;
this.damping = void 0;
this.mass = void 0;
this.velocity = 0;
this.restVelocity = void 0;
this.precision = void 0;
this.progress = void 0;
this.duration = void 0;
this.easing = void 0;
this.clamp = void 0;
this.bounce = void 0;
this.decay = void 0;
this.round = void 0;
Object.assign(this, defaults);
}
}
function mergeConfig(config, newConfig, defaultConfig) {
if (defaultConfig) {
defaultConfig = _extends({}, defaultConfig);
sanitizeConfig(defaultConfig, newConfig);
newConfig = _extends({}, defaultConfig, newConfig);
}
sanitizeConfig(config, newConfig);
Object.assign(config, newConfig);
for (const key in defaults) {
if (config[key] == null) {
config[key] = defaults[key];
}
}
let {
mass,
frequency,
damping
} = config;
if (!is.und(frequency)) {
if (frequency < 0.01) frequency = 0.01;
if (damping < 0) damping = 0;
config.tension = Math.pow(2 * Math.PI / frequency, 2) * mass;
config.friction = 4 * Math.PI * damping * mass / frequency;
}
return config;
}
function sanitizeConfig(config, props) {
if (!is.und(props.decay)) {
config.duration = undefined;
} else {
const isTensionConfig = !is.und(props.tension) || !is.und(props.friction);
if (isTensionConfig || !is.und(props.frequency) || !is.und(props.damping) || !is.und(props.mass)) {
config.duration = undefined;
config.decay = undefined;
}
if (isTensionConfig) {
config.frequency = undefined;
}
}
}
const emptyArray = [];
class Animation {
constructor() {
this.changed = false;
this.values = emptyArray;
this.toValues = null;
this.fromValues = emptyArray;
this.to = void 0;
this.from = void 0;
this.config = new AnimationConfig();
this.immediate = false;
}
}
function scheduleProps(callId, {
key,
props,
defaultProps,
state,
actions
}) {
return new Promise((resolve, reject) => {
var _props$cancel;
let delay;
let timeout;
let cancel = matchProp((_props$cancel = props.cancel) != null ? _props$cancel : defaultProps == null ? void 0 : defaultProps.cancel, key);
if (cancel) {
onStart();
} else {
if (!is.und(props.pause)) {
state.paused = matchProp(props.pause, key);
}
let pause = defaultProps == null ? void 0 : defaultProps.pause;
if (pause !== true) {
pause = state.paused || matchProp(pause, key);
}
delay = callProp(props.delay || 0, key);
if (pause) {
state.resumeQueue.add(onResume);
actions.pause();
} else {
actions.resume();
onResume();
}
}
function onPause() {
state.resumeQueue.add(onResume);
state.timeouts.delete(timeout);
timeout.cancel();
delay = timeout.time - raf.now();
}
function onResume() {
if (delay > 0 && !Globals.skipAnimation) {
state.delayed = true;
timeout = raf.setTimeout(onStart, delay);
state.pauseQueue.add(onPause);
state.timeouts.add(timeout);
} else {
onStart();
}
}
function onStart() {
if (state.delayed) {
state.delayed = false;
}
state.pauseQueue.delete(onPause);
state.timeouts.delete(timeout);
if (callId <= (state.cancelId || 0)) {
cancel = true;
}
try {
actions.start(_extends({}, props, {
callId,
cancel
}), resolve);
} catch (err) {
reject(err);
}
}
});
}
const getCombinedResult = (target, results) => results.length == 1 ? results[0] : results.some(result => result.cancelled) ? getCancelledResult(target.get()) : results.every(result => result.noop) ? getNoopResult(target.get()) : getFinishedResult(target.get(), results.every(result => result.finished));
const getNoopResult = value => ({
value,
noop: true,
finished: true,
cancelled: false
});
const getFinishedResult = (value, finished, cancelled = false) => ({
value,
finished,
cancelled
});
const getCancelledResult = value => ({
value,
cancelled: true,
finished: false
});
function runAsync(to, props, state, target) {
const {
callId,
parentId,
onRest
} = props;
const {
asyncTo: prevTo,
promise: prevPromise
} = state;
if (!parentId && to === prevTo && !props.reset) {
return prevPromise;
}
return state.promise = (async () => {
state.asyncId = callId;
state.asyncTo = to;
const defaultProps = getDefaultProps(props, (value, key) => key === 'onRest' ? undefined : value);
let preventBail;
let bail;
const bailPromise = new Promise((resolve, reject) => (preventBail = resolve, bail = reject));
const bailIfEnded = bailSignal => {
const bailResult = callId <= (state.cancelId || 0) && getCancelledResult(target) || callId !== state.asyncId && getFinishedResult(target, false);
if (bailResult) {
bailSignal.result = bailResult;
bail(bailSignal);
throw bailSignal;
}
};
const animate = (arg1, arg2) => {
const bailSignal = new BailSignal();
const skipAnimationSignal = new SkipAniamtionSignal();
return (async () => {
if (Globals.skipAnimation) {
stopAsync(state);
skipAnimationSignal.result = getFinishedResult(target, false);
bail(skipAnimationSignal);
throw skipAnimationSignal;
}
bailIfEnded(bailSignal);
const props = is.obj(arg1) ? _extends({}, arg1) : _extends({}, arg2, {
to: arg1
});
props.parentId = callId;
eachProp(defaultProps, (value, key) => {
if (is.und(props[key])) {
props[key] = value;
}
});
const result = await target.start(props);
bailIfEnded(bailSignal);
if (state.paused) {
await new Promise(resume => {
state.resumeQueue.add(resume);
});
}
return result;
})();
};
let result;
if (Globals.skipAnimation) {
stopAsync(state);
return getFinishedResult(target, false);
}
try {
let animating;
if (is.arr(to)) {
animating = (async queue => {
for (const props of queue) {
await animate(props);
}
})(to);
} else {
animating = Promise.resolve(to(animate, target.stop.bind(target)));
}
await Promise.all([animating.then(preventBail), bailPromise]);
result = getFinishedResult(target.get(), true, false);
} catch (err) {
if (err instanceof BailSignal) {
result = err.result;
} else if (err instanceof SkipAniamtionSignal) {
result = err.result;
} else {
throw err;
}
} finally {
if (callId == state.asyncId) {
state.asyncId = parentId;
state.asyncTo = parentId ? prevTo : undefined;
state.promise = parentId ? prevPromise : undefined;
}
}
if (is.fun(onRest)) {
raf.batchedUpdates(() => {
onRest(result, target, target.item);
});
}
return result;
})();
}
function stopAsync(state, cancelId) {
flush(state.timeouts, t => t.cancel());
state.pauseQueue.clear();
state.resumeQueue.clear();
state.asyncId = state.asyncTo = state.promise = undefined;
if (cancelId) state.cancelId = cancelId;
}
class BailSignal extends Error {
constructor() {
super('An async animation has been interrupted. You see this error because you ' + 'forgot to use `await` or `.catch(...)` on its returned promise.');
this.result = void 0;
}
}
class SkipAniamtionSignal extends Error {
constructor() {
super('SkipAnimationSignal');
this.result = void 0;
}
}
const isFrameValue = value => value instanceof FrameValue;
let nextId$1 = 1;
class FrameValue extends FluidValue {
constructor(...args) {
super(...args);
this.id = nextId$1++;
this.key = void 0;
this._priority = 0;
}
get priority() {
return this._priority;
}
set priority(priority) {
if (this._priority != priority) {
this._priority = priority;
this._onPriorityChange(priority);
}
}
get() {
const node = getAnimated(this);
return node && node.getValue();
}
to(...args) {
return Globals.to(this, args);
}
interpolate(...args) {
deprecateInterpolate();
return Globals.to(this, args);
}
toJSON() {
return this.get();
}
observerAdded(count) {
if (count == 1) this._attach();
}
observerRemoved(count) {
if (count == 0) this._detach();
}
_attach() {}
_detach() {}
_onChange(value, idle = false) {
callFluidObservers(this, {
type: 'change',
parent: this,
value,
idle
});
}
_onPriorityChange(priority) {
if (!this.idle) {
frameLoop.sort(this);
}
callFluidObservers(this, {
type: 'priority',
parent: this,
priority
});
}
}
const $P = Symbol.for('SpringPhase');
const HAS_ANIMATED = 1;
const IS_ANIMATING = 2;
const IS_PAUSED = 4;
const hasAnimated = target => (target[$P] & HAS_ANIMATED) > 0;
const isAnimating = target => (target[$P] & IS_ANIMATING) > 0;
const isPaused = target => (target[$P] & IS_PAUSED) > 0;
const setActiveBit = (target, active) => active ? target[$P] |= IS_ANIMATING | HAS_ANIMATED : target[$P] &= ~IS_ANIMATING;
const setPausedBit = (target, paused) => paused ? target[$P] |= IS_PAUSED : target[$P] &= ~IS_PAUSED;
class SpringValue extends FrameValue {
constructor(arg1, arg2) {
super();
this.key = void 0;
this.animation = new Animation();
this.queue = void 0;
this.defaultProps = {};
this._state = {
paused: false,
delayed: false,
pauseQueue: new Set(),
resumeQueue: new Set(),
timeouts: new Set()
};
this._pendingCalls = new Set();
this._lastCallId = 0;
this._lastToId = 0;
this._memoizedDuration = 0;
if (!is.und(arg1) || !is.und(arg2)) {
const props = is.obj(arg1) ? _extends({}, arg1) : _extends({}, arg2, {
from: arg1
});
if (is.und(props.default)) {
props.default = true;
}
this.start(props);
}
}
get idle() {
return !(isAnimating(this) || this._state.asyncTo) || isPaused(this);
}
get goal() {
return getFluidValue(this.animation.to);
}
get velocity() {
const node = getAnimated(this);
return node instanceof AnimatedValue ? node.lastVelocity || 0 : node.getPayload().map(node => node.lastVelocity || 0);
}
get hasAnimated() {
return hasAnimated(this);
}
get isAnimating() {
return isAnimating(this);
}
get isPaused() {
return isPaused(this);
}
get isDelayed() {
return this._state.delayed;
}
advance(dt) {
let idle = true;
let changed = false;
const anim = this.animation;
let {
config,
toValues
} = anim;
const payload = getPayload(anim.to);
if (!payload && hasFluidValue(anim.to)) {
toValues = toArray(getFluidValue(anim.to));
}
anim.values.forEach((node, i) => {
if (node.done) return;
const to = node.constructor == AnimatedString ? 1 : payload ? payload[i].lastPosition : toValues[i];
let finished = anim.immediate;
let position = to;
if (!finished) {
position = node.lastPosition;
if (config.tension <= 0) {
node.done = true;
return;
}
let elapsed = node.elapsedTime += dt;
const from = anim.fromValues[i];
const v0 = node.v0 != null ? node.v0 : node.v0 = is.arr(config.velocity) ? config.velocity[i] : config.velocity;
let velocity;
if (!is.und(config.duration)) {
let p = 1;
if (config.duration > 0) {
if (this._memoizedDuration !== config.duration) {
this._memoizedDuration = config.duration;
if (node.durationProgress > 0) {
node.elapsedTime = config.duration * node.durationProgress;
elapsed = node.elapsedTime += dt;
}
}
p = (config.progress || 0) + elapsed / this._memoizedDuration;
p = p > 1 ? 1 : p < 0 ? 0 : p;
node.durationProgress = p;
}
position = from + config.easing(p) * (to - from);
velocity = (position - node.lastPosition) / dt;
finished = p == 1;
} else if (config.decay) {
const decay = config.decay === true ? 0.998 : config.decay;
const e = Math.exp(-(1 - decay) * elapsed);
position = from + v0 / (1 - decay) * (1 - e);
finished = Math.abs(node.lastPosition - position) < 0.1;
velocity = v0 * e;
} else {
velocity = node.lastVelocity == null ? v0 : node.lastVelocity;
const precision = config.precision || (from == to ? 0.005 : Math.min(1, Math.abs(to - from) * 0.001));
const restVelocity = config.restVelocity || precision / 10;
const bounceFactor = config.clamp ? 0 : config.bounce;
const canBounce = !is.und(bounceFactor);
const isGrowing = from == to ? node.v0 > 0 : from < to;
let isMoving;
let isBouncing = false;
const step = 1;
const numSteps = Math.ceil(dt / step);
for (let n = 0; n < numSteps; ++n) {
isMoving = Math.abs(velocity) > restVelocity;
if (!isMoving) {
finished = Math.abs(to - position) <= precision;
if (finished) {
break;
}
}
if (canBounce) {
isBouncing = position == to || position > to == isGrowing;
if (isBouncing) {
velocity = -velocity * bounceFactor;
position = to;
}
}
const springForce = -config.tension * 0.000001 * (position - to);
const dampingForce = -config.friction * 0.001 * velocity;
const acceleration = (springForce + dampingForce) / config.mass;
velocity = velocity + acceleration * step;
position = position + velocity * step;
}
}
node.lastVelocity = velocity;
if (Number.isNaN(position)) {
console.warn(`Got NaN while animating:`, this);
finished = true;
}
}
if (payload && !payload[i].done) {
finished = false;
}
if (finished) {
node.done = true;
} else {
idle = false;
}
if (node.setValue(position, config.round)) {
changed = true;
}
});
const node = getAnimated(this);
const currVal = node.getValue();
if (idle) {
const finalVal = getFluidValue(anim.to);
if ((currVal !== finalVal || changed) && !config.decay) {
node.setValue(finalVal);
this._onChange(finalVal);
} else if (changed && config.decay) {
this._onChange(currVal);
}
this._stop();
} else if (changed) {
this._onChange(currVal);
}
}
set(value) {
raf.batchedUpdates(() => {
this._stop();
this._focus(value);
this._set(value);
});
return this;
}
pause() {
this._update({
pause: true
});
}
resume() {
this._update({
pause: false
});
}
finish() {
if (isAnimating(this)) {
const {
to,
config
} = this.animation;
raf.batchedUpdates(() => {
this._onStart();
if (!config.decay) {
this._set(to, false);
}
this._stop();
});
}
return this;
}
update(props) {
const queue = this.queue || (this.queue = []);
queue.push(props);
return this;
}
start(to, arg2) {
let queue;
if (!is.und(to)) {
queue = [is.obj(to) ? to : _extends({}, arg2, {
to
})];
} else {
queue = this.queue || [];
this.queue = [];
}
return Promise.all(queue.map(props => {
const up = this._update(props);
return up;
})).then(results => getCombinedResult(this, results));
}
stop(cancel) {
const {
to
} = this.animation;
this._focus(this.get());
stopAsync(this._state, cancel && this._lastCallId);
raf.batchedUpdates(() => this._stop(to, cancel));
return this;
}
reset() {
this._update({
reset: true
});
}
eventObserved(event) {
if (event.type == 'change') {
this._start();
} else if (event.type == 'priority') {
this.priority = event.priority + 1;
}
}
_prepareNode(props) {
const key = this.key || '';
let {
to,
from
} = props;
to = is.obj(to) ? to[key] : to;
if (to == null || isAsyncTo(to)) {
to = undefined;
}
from = is.obj(from) ? from[key] : from;
if (from == null) {
from = undefined;
}
const range = {
to,
from
};
if (!hasAnimated(this)) {
if (props.reverse) [to, from] = [from, to];
from = getFluidValue(from);
if (!is.und(from)) {
this._set(from);
} else if (!getAnimated(this)) {
this._set(to);
}
}
return range;
}
_update(_ref, isLoop) {
let props = _extends({}, _ref);
const {
key,
defaultProps
} = this;
if (props.default) Object.assign(defaultProps, getDefaultProps(props, (value, prop) => /^on/.test(prop) ? resolveProp(value, key) : value));
mergeActiveFn(this, props, 'onProps');
sendEvent(this, 'onProps', props, this);
const range = this._prepareNode(props);
if (Object.isFrozen(this)) {
throw Error('Cannot animate a `SpringValue` object that is frozen. ' + 'Did you forget to pass your component to `animated(...)` before animating its props?');
}
const state = this._state;
return scheduleProps(++this._lastCallId, {
key,
props,
defaultProps,
state,
actions: {
pause: () => {
if (!isPaused(this)) {
setPausedBit(this, true);
flushCalls(state.pauseQueue);
sendEvent(this, 'onPause', getFinishedResult(this, checkFinished(this, this.animation.to)), this);
}
},
resume: () => {
if (isPaused(this)) {
setPausedBit(this, false);
if (isAnimating(this)) {
this._resume();
}
flushCalls(state.resumeQueue);
sendEvent(this, 'onResume', getFinishedResult(this, checkFinished(this, this.animation.to)), this);
}
},
start: this._merge.bind(this, range)
}
}).then(result => {
if (props.loop && result.finished && !(isLoop && result.noop)) {
const nextProps = createLoopUpdate(props);
if (nextProps) {
return this._update(nextProps, true);
}
}
return result;
});
}
_merge(range, props, resolve) {
if (props.cancel) {
this.stop(true);
return resolve(getCancelledResult(this));
}
const hasToProp = !is.und(range.to);
const hasFromProp = !is.und(range.from);
if (hasToProp || hasFromProp) {
if (props.callId > this._lastToId) {
this._lastToId = props.callId;
} else {
return resolve(getCancelledResult(this));
}
}
const {
key,
defaultProps,
animation: anim
} = this;
const {
to: prevTo,
from: prevFrom
} = anim;
let {
to = prevTo,
from = prevFrom
} = range;
if (hasFromProp && !hasToProp && (!props.default || is.und(to))) {
to = from;
}
if (props.reverse) [to, from] = [from, to];
const hasFromChanged = !isEqual(from, prevFrom);
if (hasFromChanged) {
anim.from = from;
}
from = getFluidValue(from);
const hasToChanged = !isEqual(to, prevTo);
if (hasToChanged) {
this._focus(to);
}
const hasAsyncTo = isAsyncTo(props.to);
const {
config
} = anim;
const {
decay,
velocity
} = config;
if (hasToProp || hasFromProp) {
config.velocity = 0;
}
if (props.config && !hasAsyncTo) {
mergeConfig(config, callProp(props.config, key), props.config !== defaultProps.config ? callProp(defaultProps.config, key) : void 0);
}
let node = getAnimated(this);
if (!node || is.und(to)) {
return resolve(getFinishedResult(this, true));
}
const reset = is.und(props.reset) ? hasFromProp && !props.default : !is.und(from) && matchProp(props.reset, key);
const value = reset ? from : this.get();
const goal = computeGoal(to);
const isAnimatable = is.num(goal) || is.arr(goal) || isAnimatedString(goal);
const immediate = !hasAsyncTo && (!isAnimatable || matchProp(defaultProps.immediate || props.immediate, key));
if (hasToChanged) {
const nodeType = getAnimatedType(to);
if (nodeType !== node.constructor) {
if (immediate) {
node = this._set(goal);
} else throw Error(`Cannot animate between ${node.constructor.name} and ${nodeType.name}, as the "to" prop suggests`);
}
}
const goalType = node.constructor;
let started = hasFluidValue(to);
let finished = false;
if (!started) {
const hasValueChanged = reset || !hasAnimated(this) && hasFromChanged;
if (hasToChanged || hasValueChanged) {
finished = isEqual(computeGoal(value), goal);
started = !finished;
}
if (!isEqual(anim.immediate, immediate) && !immediate || !isEqual(config.decay, decay) || !isEqual(config.velocity, velocity)) {
started = true;
}
}
if (finished && isAnimating(this)) {
if (anim.changed && !reset) {
started = true;
} else if (!started) {
this._stop(prevTo);
}
}
if (!hasAsyncTo) {
if (started || hasFluidValue(prevTo)) {
anim.values = node.getPayload();
anim.toValues = hasFluidValue(to) ? null : goalType == AnimatedString ? [1] : toArray(goal);
}
if (anim.immediate != immediate) {
anim.immediate = immediate;
if (!immediate && !reset) {
this._set(prevTo);
}
}
if (started) {
const {
onRest
} = anim;
each(ACTIVE_EVENTS, type => mergeActiveFn(this, props, type));
const result = getFinishedResult(this, checkFinished(this, prevTo));
flushCalls(this._pendingCalls, result);
this._pendingCalls.add(resolve);
if (anim.changed) raf.batchedUpdates(() => {
anim.changed = !reset;
onRest == null ? void 0 : onRest(result, this);
if (reset) {
callProp(defaultProps.onRest, result);
} else {
anim.onStart == null ? void 0 : anim.onStart(result, this);
}
});
}
}
if (reset) {
this._set(value);
}
if (hasAsyncTo) {
resolve(runAsync(props.to, props, this._state, this));
} else if (started) {
this._start();
} else if (isAnimating(this) && !hasToChanged) {
this._pendingCalls.add(resolve);
} else {
resolve(getNoopResult(value));
}
}
_focus(value) {
const anim = this.animation;
if (value !== anim.to) {
if (getFluidObservers(this)) {
this._detach();
}
anim.to = value;
if (getFluidObservers(this)) {
this._attach();
}
}
}
_attach() {
let priority = 0;
const {
to
} = this.animation;
if (hasFluidValue(to)) {
addFluidObserver(to, this);
if (isFrameValue(to)) {
priority = to.priority + 1;
}
}
this.priority = priority;
}
_detach() {
const {
to
} = this.animation;
if (hasFluidValue(to)) {
removeFluidObserver(to, this);
}
}
_set(arg, idle = true) {
const value = getFluidValue(arg);
if (!is.und(value)) {
const oldNode = getAnimated(this);
if (!oldNode || !isEqual(value, oldNode.getValue())) {
const nodeType = getAnimatedType(value);
if (!oldNode || oldNode.constructor != nodeType) {
setAnimated(this, nodeType.create(value));
} else {
oldNode.setValue(value);
}
if (oldNode) {
raf.batchedUpdates(() => {
this._onChange(value, idle);
});
}
}
}
return getAnimated(this);
}
_onStart() {
const anim = this.animation;
if (!anim.changed) {
anim.changed = true;
sendEvent(this, 'onStart', getFinishedResult(this, checkFinished(this, anim.to)), this);
}
}
_onChange(value, idle) {
if (!idle) {
this._onStart();
callProp(this.animation.onChange, value, this);
}
callProp(this.defaultProps.onChange, value, this);
super._onChange(value, idle);
}
_start() {
const anim = this.animation;
getAnimated(this).reset(getFluidValue(anim.to));
if (!anim.immediate) {
anim.fromValues = anim.values.map(node => node.lastPosition);
}
if (!isAnimating(this)) {
setActiveBit(this, true);
if (!isPaused(this)) {
this._resume();
}
}
}
_resume() {
if (Globals.skipAnimation) {
this.finish();
} else {
frameLoop.start(this);
}
}
_stop(goal, cancel) {
if (isAnimating(this)) {
setActiveBit(this, false);
const anim = this.animation;
each(anim.values, node => {
node.done = true;
});
if (anim.toValues) {
anim.onChange = anim.onPause = anim.onResume = undefined;
}
callFluidObservers(this, {
type: 'idle',
parent: this
});
const result = cancel ? getCancelledResult(this.get()) : getFinishedResult(this.get(), checkFinished(this, goal != null ? goal : anim.to));
flushCalls(this._pendingCalls, result);
if (anim.changed) {
anim.changed = false;
sendEvent(this, 'onRest', result, this);
}
}
}
}
function checkFinished(target, to) {
const goal = computeGoal(to);
const value = computeGoal(target.get());
return isEqual(value, goal);
}
function createLoopUpdate(props, loop = props.loop, to = props.to) {
let loopRet = callProp(loop);
if (loopRet) {
const overrides = loopRet !== true && inferTo(loopRet);
const reverse = (overrides || props).reverse;
const reset = !overrides || overrides.reset;
return createUpdate(_extends({}, props, {
loop,
default: false,
pause: undefined,
to: !reverse || isAsyncTo(to) ? to : undefined,
from: reset ? props.from : undefined,
reset
}, overrides));
}
}
function createUpdate(props) {
const {
to,
from
} = props = inferTo(props);
const keys = new Set();
if (is.obj(to)) findDefined(to, keys);
if (is.obj(from)) findDefined(from, keys);
props.keys = keys.size ? Array.from(keys) : null;
return props;
}
function declareUpdate(props) {
const update = createUpdate(props);
if (is.und(update.default)) {
update.default = getDefaultProps(update);
}
return update;
}
function findDefined(values, keys) {
eachProp(values, (value, key) => value != null && keys.add(key));
}
const ACTIVE_EVENTS = ['onStart', 'onRest', 'onChange', 'onPause', 'onResume'];
function mergeActiveFn(target, props, type) {
target.animation[type] = props[type] !== getDefaultProp(props, type) ? resolveProp(props[type], target.key) : undefined;
}
function sendEvent(target, type, ...args) {
var _target$animation$typ, _target$animation, _target$defaultProps$, _target$defaultProps;
(_target$animation$typ = (_target$animation = target.animation)[type]) == null ? void 0 : _target$animation$typ.call(_target$animation, ...args);
(_target$defaultProps$ = (_target$defaultProps = target.defaultProps)[type]) == null ? void 0 : _target$defaultProps$.call(_target$defaultProps, ...args);
}
const BATCHED_EVENTS = ['onStart', 'onChange', 'onRest'];
let nextId = 1;
class Controller {
constructor(props, flush) {
this.id = nextId++;
this.springs = {};
this.queue = [];
this.ref = void 0;
this._flush = void 0;
this._initialProps = void 0;
this._lastAsyncId = 0;
this._active = new Set();
this._changed = new Set();
this._started = false;
this._item = void 0;
this._state = {
paused: false,
pauseQueue: new Set(),
resumeQueue: new Set(),
timeouts: new Set()
};
this._events = {
onStart: new Map(),
onChange: new Map(),
onRest: new Map()
};
this._onFrame = this._onFrame.bind(this);
if (flush) {
this._flush = flush;
}
if (props) {
this.start(_extends({
default: true
}, props));
}
}
get idle() {
return !this._state.asyncTo && Object.values(this.springs).every(spring => {
return spring.idle && !spring.isDelayed && !spring.isPaused;
});
}
get item() {
return this._item;
}
set item(item) {
this._item = item;
}
get() {
const values = {};
this.each((spring, key) => values[key] = spring.get());
return values;
}
set(values) {
for (const key in values) {
const value = values[key];
if (!is.und(value)) {
this.springs[key].set(value);
}
}
}
update(props) {
if (props) {
this.queue.push(createUpdate(props));
}
return this;
}
start(props) {
let {
queue
} = this;
if (props) {
queue = toArray(props).map(createUpdate);
} else {
this.queue = [];
}
if (this._flush) {
return this._flush(this, queue);
}
prepareKeys(this, queue);
return flushUpdateQueue(this, queue);
}
stop(arg, keys) {
if (arg !== !!arg) {
keys = arg;
}
if (keys) {
const springs = this.springs;
each(toArray(keys), key => springs[key].stop(!!arg));
} else {
stopAsync(this._state, this._lastAsyncId);
this.each(spring => spring.stop(!!arg));
}
return this;
}
pause(keys) {
if (is.und(keys)) {
this.start({
pause: true
});
} else {
const springs = this.springs;
each(toArray(keys), key => springs[key].pause());
}
return this;
}
resume(keys) {
if (is.und(keys)) {
this.start({
pause: false
});
} else {
const springs = this.springs;
each(toArray(keys), key => springs[key].resume());
}
return this;
}
each(iterator) {
eachProp(this.springs, iterator);
}
_onFrame() {
const {
onStart,
onChange,
onRest
} = this._events;
const active = this._active.size > 0;
const changed = this._changed.size > 0;
if (active && !this._started || changed && !this._started) {
this._started = true;
flush(onStart, ([onStart, result]) => {
result.value = this.get();
onStart(result, this, this._item);
});
}
const idle = !active && this._started;
const values = changed || idle && onRest.size ? this.get() : null;
if (changed && onChange.size) {
flush(onChange, ([onChange, result]) => {
result.value = values;
onChange(result, this, this._item);
});
}
if (idle) {
this._started = false;
flush(onRest, ([onRest, result]) => {
result.value = values;
onRest(result, this, this._item);
});
}
}
eventObserved(event) {
if (event.type == 'change') {
this._changed.add(event.parent);
if (!event.idle) {
this._active.add(event.parent);
}
} else if (event.type == 'idle') {
this._active.delete(event.parent);
} else return;
raf.onFrame(this._onFrame);
}
}
function flushUpdateQueue(ctrl, queue) {
return Promise.all(queue.map(props => flushUpdate(ctrl, props))).then(results => getCombinedResult(ctrl, results));
}
async function flushUpdate(ctrl, props, isLoop) {
const {
keys,
to,
from,
loop,
onRest,
onResolve
} = props;
const defaults = is.obj(props.default) && props.default;
if (loop) {
props.loop = false;
}
if (to === false) props.to = null;
if (from === false) props.from = null;
const asyncTo = is.arr(to) || is.fun(to) ? to : undefined;
if (asyncTo) {
props.to = undefined;
props.onRest = undefined;
if (defaults) {
defaults.onRest = undefined;
}
} else {
each(BATCHED_EVENTS, key => {
const handler = props[key];
if (is.fun(handler)) {
const queue = ctrl['_events'][key];
props[key] = ({
finished,
cancelled
}) => {
const result = queue.get(handler);
if (result) {
if (!finished) result.finished = false;
if (cancelled) result.cancelled = true;
} else {
queue.set(handler, {
value: null,
finished: finished || false,
cancelled: cancelled || false
});
}
};
if (defaults) {
defaults[key] = props[key];
}
}
});
}
const state = ctrl['_state'];
if (props.pause === !state.paused) {
state.paused = props.pause;
flushCalls(props.pause ? state.pauseQueue : state.resumeQueue);
} else if (state.paused) {
props.pause = true;
}
const promises = (keys || Object.keys(ctrl.springs)).map(key => ctrl.springs[key].start(props));
const cancel = props.cancel === true || getDefaultProp(props, 'cancel') === true;
if (asyncTo || cancel && state.asyncId) {
promises.push(scheduleProps(++ctrl['_lastAsyncId'], {
props,
state,
actions: {
pause: noop,
resume: noop,
start(props, resolve) {
if (cancel) {
stopAsync(state, ctrl['_lastAsyncId']);
resolve(getCancelledResult(ctrl));
} else {
props.onRest = onRest;
resolve(runAsync(asyncTo, props, state, ctrl));
}
}
}
}));
}
if (state.paused) {
await new Promise(resume => {
state.resumeQueue.add(resume);
});
}
const result = getCombinedResult(ctrl, await Promise.all(promises));
if (loop && result.finished && !(isLoop && result.noop)) {
const nextProps = createLoopUpdate(props, loop, to);
if (nextProps) {
prepareKeys(ctrl, [nextProps]);
return flushUpdate(ctrl, nextProps, true);
}
}
if (onResolve) {
raf.batchedUpdates(() => onResolve(result, ctrl, ctrl.item));
}
return result;
}
function getSprings(ctrl, props) {
const springs = _extends({}, ctrl.springs);
if (props) {
each(toArray(props), props => {
if (is.und(props.keys)) {
props = createUpdate(props);
}
if (!is.obj(props.to)) {
props = _extends({}, props, {
to: undefined
});
}
prepareSprings(springs, props, key => {
return createSpring(key);
});
});
}
setSprings(ctrl, springs);
return springs;
}
function setSprings(ctrl, springs) {
eachProp(springs, (spring, key) => {
if (!ctrl.springs[key]) {
ctrl.springs[key] = spring;
addFluidObserver(spring, ctrl);
}
});
}
function createSpring(key, observer) {
const spring = new SpringValue();
spring.key = key;
if (observer) {
addFluidObserver(spring, observer);
}
return spring;
}
function prepareSprings(springs, props, create) {
if (props.keys) {
each(props.keys, key => {
const spring = springs[key] || (springs[key] = create(key));
spring['_prepareNode'](props);
});
}
}
function prepareKeys(ctrl, queue) {
each(queue, props => {
prepareSprings(ctrl.springs, props, key => {
return createSpring(key, ctrl);
});
});
}
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;
}
const _excluded$3 = ["children"];
const SpringContext = _ref => {
let {
children
} = _ref,
props = _objectWithoutPropertiesLoose(_ref, _excluded$3);
const inherited = useContext(ctx);
const pause = props.pause || !!inherited.pause,
immediate = props.immediate || !!inherited.immediate;
props = useMemoOne(() => ({
pause,
immediate
}), [pause, immediate]);
const {
Provider
} = ctx;
return React.createElement(Provider, {
value: props
}, children);
};
const ctx = makeContext(SpringContext, {});
SpringContext.Provider = ctx.Provider;
SpringContext.Consumer = ctx.Consumer;
function makeContext(target, init) {
Object.assign(target, React.createContext(init));
target.Provider._context = target;
target.Consumer._context = target;
return target;
}
const SpringRef = () => {
const current = [];
const SpringRef = function SpringRef(props) {
deprecateDirectCall();
const results = [];
each(current, (ctrl, i) => {
if (is.und(props)) {
results.push(ctrl.start());
} else {
const update = _getProps(props, ctrl, i);
if (update) {
results.push(ctrl.start(update));
}
}
});
return results;
};
SpringRef.current = current;
SpringRef.add = function (ctrl) {
if (!current.includes(ctrl)) {
current.push(ctrl);
}
};
SpringRef.delete = function (ctrl) {
const i = current.indexOf(ctrl);
if (~i) current.splice(i, 1);
};
SpringRef.pause = function () {
each(current, ctrl => ctrl.pause(...arguments));
return this;
};
SpringRef.resume = function () {
each(current, ctrl => ctrl.resume(...arguments));
return this;
};
SpringRef.set = function (values) {
each(current, ctrl => ctrl.set(values));
};
SpringRef.start = function (props) {
const results = [];
each(current, (ctrl, i) => {
if (is.und(props)) {
results.push(ctrl.start());
} else {
const update = this._getProps(props, ctrl, i);
if (update) {
results.push(ctrl.start(update));
}
}
});
return results;
};
SpringRef.stop = function () {
each(current, ctrl => ctrl.stop(...arguments));
return this;
};
SpringRef.update = function (props) {
each(current, (ctrl, i) => ctrl.update(this._getProps(props, ctrl, i)));
return this;
};
const _getProps = function _getProps(arg, ctrl, index) {
return is.fun(arg) ? arg(index, ctrl) : arg;
};
SpringRef._getProps = _getProps;
return SpringRef;
};
function useSprings(length, props, deps) {
const propsFn = is.fun(props) && props;
if (propsFn && !deps) deps = [];
const ref = useMemo(() => propsFn || arguments.length == 3 ? SpringRef() : void 0, []);
const layoutId = useRef(0);
const forceUpdate = useForceUpdate();
const state = useMemo(() => ({
ctrls: [],
queue: [],
flush(ctrl, updates) {
const springs = getSprings(ctrl, updates);
const canFlushSync = layoutId.current > 0 && !state.queue.length && !Object.keys(springs).some(key => !ctrl.springs[key]);
return canFlushSync ? flushUpdateQueue(ctrl, updates) : new Promise(resolve => {
setSprings(ctrl, springs);
state.queue.push(() => {
resolve(flushUpdateQueue(ctrl, updates));
});
forceUpdate();
});
}
}), []);
const ctrls = useRef([...state.ctrls]);
const updates = [];
const prevLength = usePrev(length) || 0;
useMemo(() => {
each(ctrls.current.slice(length, prevLength), ctrl => {
detachRefs(ctrl, ref);
ctrl.stop(true);
});
ctrls.current.length = length;
declareUpdates(prevLength, length);
}, [length]);
useMemo(() => {
declareUpdates(0, Math.min(prevLength, length));
}, deps);
function declareUpdates(startIndex, endIndex) {
for (let i = startIndex; i < endIndex; i++) {
const ctrl = ctrls.current[i] || (ctrls.current[i] = new Controller(null, state.flush));
const update = propsFn ? propsFn(i, ctrl) : props[i];
if (update) {
updates[i] = declareUpdate(update);
}
}
}
const springs = ctrls.current.map((ctrl, i) => getSprings(ctrl, updates[i]));
const context = useContext(SpringContext);
const prevContext = usePrev(context);
const hasContext = context !== prevContext && hasProps(context);
useLayoutEffect(() => {
layoutId.current++;
state.ctrls = ctrls.current;
const {
queue
} = state;
if (queue.length) {
state.queue = [];
each(queue, cb => cb());
}
each(ctrls.current, (ctrl, i) => {
ref == null ? void 0 : ref.add(ctrl);
if (hasContext) {
ctrl.start({
default: context
});
}
const update = updates[i];
if (update) {
replaceRef(ctrl, update.ref);
if (ctrl.ref) {
ctrl.queue.push(update);
} else {
ctrl.start(update);
}
}
});
});
useOnce(() => () => {
each(state.ctrls, ctrl => ctrl.stop(true));
});
const values = springs.map(x => _extends({}, x));
return ref ? [values, ref] : values;
}
function useSpring(props, deps) {
const isFn = is.fun(props);
const [[values], ref] = useSprings(1, isFn ? props : [props], isFn ? deps || [] : deps);
return isFn || arguments.length == 2 ? [values, ref] : values;
}
const initSpringRef = () => SpringRef();
const useSpringRef = () => useState(initSpringRef)[0];
function useTrail(length, propsArg, deps) {
var _passedRef;
const propsFn = is.fun(propsArg) && propsArg;
if (propsFn && !deps) deps = [];
let reverse = true;
let passedRef = undefined;
const result = useSprings(length, (i, ctrl) => {
const props = propsFn ? propsFn(i, ctrl) : propsArg;
passedRef = props.ref;
reverse = reverse && props.reverse;
return props;
}, deps || [{}]);
const ref = (_passedRef = passedRef) != null ? _passedRef : result[1];
useLayoutEffect(() => {
each(ref.current, (ctrl, i) => {
const parent = ref.current[i + (reverse ? 1 : -1)];
if (parent) {
ctrl.start({
to: parent.springs
});
} else {
ctrl.start();
}
});
}, deps);
if (propsFn || arguments.length == 3) {
ref['_getProps'] = (propsArg, ctrl, i) => {
const props = is.fun(propsArg) ? propsArg(i, ctrl) : propsArg;
if (props) {
const parent = ref.current[i + (props.reverse ? 1 : -1)];
if (parent) props.to = parent.springs;
return props;
}
};
return result;
}
ref['start'] = propsArg => {
const results = [];
each(ref.current, (ctrl, i) => {
const props = is.fun(propsArg) ? propsArg(i, ctrl) : propsArg;
const parent = ref.current[i + (reverse ? 1 : -1)];
if (parent) {
results.push(ctrl.start(_extends({}, props, {
to: parent.springs
})));
} else {
results.push(ctrl.start(_extends({}, props)));
}
});
return results;
};
return result[0];
}
let TransitionPhase;
(function (TransitionPhase) {
TransitionPhase["MOUNT"] = "mount";
TransitionPhase["ENTER"] = "enter";
TransitionPhase["UPDATE"] = "update";
TransitionPhase["LEAVE"] = "leave";
})(TransitionPhase || (TransitionPhase = {}));
function useTransition(data, props, deps) {
const propsFn = is.fun(props) && props;
const {
reset,
sort,
trail = 0,
expires = true,
exitBeforeEnter = false,
onDestroyed,
ref: propsRef,
config: propsConfig
} = propsFn ? propsFn() : props;
const ref = useMemo(() => propsFn || arguments.length == 3 ? SpringRef() : void 0, []);
const items = toArray(data);
const transitions = [];
const usedTransitions = useRef(null);
const prevTransitions = reset ? null : usedTransitions.current;
useLayoutEffect(() => {
usedTransitions.current = transitions;
});
useOnce(() => {
each(usedTransitions.current, t => {
var _t$ctrl$ref;
(_t$ctrl$ref = t.ctrl.ref) == null ? void 0 : _t$ctrl$ref.add(t.ctrl);
const change = changes.get(t);
if (change) {
t.ctrl.start(change.payload);
}
});
return () => {
each(usedTransitions.current, t => {
if (t.expired) {
clearTimeout(t.expirationId);
}
detachRefs(t.ctrl, ref);
t.ctrl.stop(true);
});
};
});
const keys = getKeys(items, propsFn ? propsFn() : props, prevTransitions);
const expired = reset && usedTransitions.current || [];
useLayoutEffect(() => each(expired, ({
ctrl,
item,
key
}) => {
detachRefs(ctrl, ref);
callProp(onDestroyed, item, key);
}));
const reused = [];
if (prevTransitions) each(prevTransitions, (t, i) => {
if (t.expired) {
clearTimeout(t.expirationId);
expired.push(t);
} else {
i = reused[i] = keys.indexOf(t.key);
if (~i) transitions[i] = t;
}
});
each(items, (item, i) => {
if (!transitions[i]) {
transitions[i] = {
key: keys[i],
item,
phase: TransitionPhase.MOUNT,
ctrl: new Controller()
};
transitions[i].ctrl.item = item;
}
});
if (reused.length) {
let i = -1;
const {
leave
} = propsFn ? propsFn() : props;
each(reused, (keyIndex, prevIndex) => {
const t = prevTransitions[prevIndex];
if (~keyIndex) {
i = transitions.indexOf(t);
transitions[i] = _extends({}, t, {
item: items[keyIndex]
});
} else if (leave) {
transitions.splice(++i, 0, t);
}
});
}
if (is.fun(sort)) {
transitions.sort((a, b) => sort(a.item, b.item));
}
let delay = -trail;
const forceUpdate = useForceUpdate();
const defaultProps = getDefaultProps(props);
const changes = new Map();
const exitingTransitions = useRef(new Map());
const forceChange = useRef(false);
each(transitions, (t, i) => {
const key = t.key;
const prevPhase = t.phase;
const p = propsFn ? propsFn() : props;
let to;
let phase;
let propsDelay = callProp(p.delay || 0, key);
if (prevPhase == TransitionPhase.MOUNT) {
to = p.enter;
phase = TransitionPhase.ENTER;
} else {
const isLeave = keys.indexOf(key) < 0;
if (prevPhase != TransitionPhase.LEAVE) {
if (isLeave) {
to = p.leave;
phase = TransitionPhase.LEAVE;
} else if (to = p.update) {
phase = TransitionPhase.UPDATE;
} else return;
} else if (!isLeave) {
to = p.enter;
phase = TransitionPhase.ENTER;
} else return;
}
to = callProp(to, t.item, i);
to = is.obj(to) ? inferTo(to) : {
to
};
if (!to.config) {
const config = propsConfig || defaultProps.config;
to.config = callProp(config, t.item, i, phase);
}
delay += trail;
const payload = _extends({}, defaultProps, {
delay: propsDelay + delay,
ref: propsRef,
immediate: p.immediate,
reset: false
}, to);
if (phase == TransitionPhase.ENTER && is.und(payload.from)) {
const _p = propsFn ? propsFn() : props;
const from = is.und(_p.initial) || prevTransitions ? _p.from : _p.initial;
payload.from = callProp(from, t.item, i);
}
const {
onResolve
} = payload;
payload.onResolve = result => {
callProp(onResolve, result);
const transitions = usedTransitions.current;
const t = transitions.find(t => t.key === key);
if (!t) return;
if (result.cancelled && t.phase != TransitionPhase.UPDATE) {
return;
}
if (t.ctrl.idle) {
const idle = transitions.every(t => t.ctrl.idle);
if (t.phase == TransitionPhase.LEAVE) {
const expiry = callProp(expires, t.item);
if (expiry !== false) {
const expiryMs = expiry === true ? 0 : expiry;
t.expired = true;
if (!idle && expiryMs > 0) {
if (expiryMs <= 0x7fffffff) t.expirationId = setTimeout(forceUpdate, expiryMs);
return;
}
}
}
if (idle && transitions.some(t => t.expired)) {
exitingTransitions.current.delete(t);
if (exitBeforeEnter) {
forceChange.current = true;
}
forceUpdate();
}
}
};
const springs = getSprings(t.ctrl, payload);
if (phase === TransitionPhase.LEAVE && exitBeforeEnter) {
exitingTransitions.current.set(t, {
phase,
springs,
payload
});
} else {
changes.set(t, {
phase,
springs,
payload
});
}
});
const context = useContext(SpringContext);
const prevContext = usePrev(context);
const hasContext = context !== prevContext && hasProps(context);
useLayoutEffect(() => {
if (hasContext) {
each(transitions, t => {
t.ctrl.start({
default: context
});
});
}
}, [context]);
each(changes, (_, t) => {
if (exitingTransitions.current.size) {
const ind = transitions.findIndex(state => state.key === t.key);
transitions.splice(ind, 1);
}
});
useLayoutEffect(() => {
each(exitingTransitions.current.size ? exitingTransitions.current : changes, ({
phase,
payload
}, t) => {
const {
ctrl
} = t;
t.phase = phase;
ref == null ? void 0 : ref.add(ctrl);
if (hasContext && phase == TransitionPhase.ENTER) {
ctrl.start({
default: context
});
}
if (payload) {
replaceRef(ctrl, payload.ref);
if (ctrl.ref && !forceChange.current) {
ctrl.update(payload);
} else {
ctrl.start(payload);
if (forceChange.current) {
forceChange.current = false;
}
}
}
});
}, reset ? void 0 : deps);
const renderTransitions = render => React.createElement(React.Fragment, null, transitions.map((t, i) => {
const {
springs
} = changes.get(t) || t.ctrl;
const elem = render(_extends({}, springs), t.item, t, i);
return elem && elem.type ? React.createElement(elem.type, _extends({}, elem.props, {
key: is.str(t.key) || is.num(t.key) ? t.key : t.ctrl.id,
ref: elem.ref
})) : elem;
}));
return ref ? [renderTransitions, ref] : renderTransitions;
}
let nextKey = 1;
function getKeys(items, {
key,
keys = key
}, prevTransitions) {
if (keys === null) {
const reused = new Set();
return items.map(item => {
const t = prevTransitions && prevTransitions.find(t => t.item === item && t.phase !== TransitionPhase.LEAVE && !reused.has(t));
if (t) {
reused.add(t);
return t.key;
}
return nextKey++;
});
}
return is.und(keys) ? items : is.fun(keys) ? items.map(keys) : toArray(keys);
}
const _excluded$2 = ["children"];
function Spring(_ref) {
let {
children
} = _ref,
props = _objectWithoutPropertiesLoose(_ref, _excluded$2);
return children(useSpring(props));
}
const _excluded$1 = ["items", "children"];
function Trail(_ref) {
let {
items,
children
} = _ref,
props = _objectWithoutPropertiesLoose(_ref, _excluded$1);
const trails = useTrail(items.length, props);
return items.map((item, index) => {
const result = children(item, index);
return is.fun(result) ? result(trails[index]) : result;
});
}
const _excluded = ["items", "children"];
function Transition(_ref) {
let {
items,
children
} = _ref,
props = _objectWithoutPropertiesLoose(_ref, _excluded);
return useTransition(items, props)(children);
}
class Interpolation extends FrameValue {
constructor(source, args) {
super();
this.key = void 0;
this.idle = true;
this.calc = void 0;
this._active = new Set();
this.source = source;
this.calc = createInterpolator(...args);
const value = this._get();
const nodeType = getAnimatedType(value);
setAnimated(this, nodeType.create(value));
}
advance(_dt) {
const value = this._get();
const oldValue = this.get();
if (!isEqual(value, oldValue)) {
getAnimated(this).setValue(value);
this._onChange(value, this.idle);
}
if (!this.idle && checkIdle(this._active)) {
becomeIdle(this);
}
}
_get() {
const inputs = is.arr(this.source) ? this.source.map(getFluidValue) : toArray(getFluidValue(this.source));
return this.calc(...inputs);
}
_start() {
if (this.idle && !checkIdle(this._active)) {
this.idle = false;
each(getPayload(this), node => {
node.done = false;
});
if (Globals.skipAnimation) {
raf.batchedUpdates(() => this.advance());
becomeIdle(this);
} else {
frameLoop.start(this);
}
}
}
_attach() {
let priority = 1;
each(toArray(this.source), source => {
if (hasFluidValue(source)) {
addFluidObserver(source, this);
}
if (isFrameValue(source)) {
if (!source.idle) {
this._active.add(source);
}
priority = Math.max(priority, source.priority + 1);
}
});
this.priority = priority;
this._start();
}
_detach() {
each(toArray(this.source), source => {
if (hasFluidValue(source)) {
removeFluidObserver(source, this);
}
});
this._active.clear();
becomeIdle(this);
}
eventObserved(event) {
if (event.type == 'change') {
if (event.idle) {
this.advance();
} else {
this._active.add(event.parent);
this._start();
}
} else if (event.type == 'idle') {
this._active.delete(event.parent);
} else if (event.type == 'priority') {
this.priority = toArray(this.source).reduce((highest, parent) => Math.max(highest, (isFrameValue(parent) ? parent.priority : 0) + 1), 0);
}
}
}
function isIdle(source) {
return source.idle !== false;
}
function checkIdle(active) {
return !active.size || Array.from(active).every(isIdle);
}
function becomeIdle(self) {
if (!self.idle) {
self.idle = true;
each(getPayload(self), node => {
node.done = true;
});
callFluidObservers(self, {
type: 'idle',
parent: self
});
}
}
const to = (source, ...args) => new Interpolation(source, args);
const interpolate = (source, ...args) => (deprecateInterpolate(), new Interpolation(source, args));
Globals.assign({
createStringInterpolator,
to: (source, args) => new Interpolation(source, args)
});
const update = frameLoop.advance;
export { BailSignal, Controller, FrameValue, Interpolation, Spring, SpringContext, SpringRef, SpringValue, Trail, Transition, config, easings, inferTo, interpolate, to, update, useChain, useSpring, useSpringRef, useSprings, useTrail, useTransition };
webpack://frontend-mybets/../../node_modules/@react-spring/rafz/dist/react-spring-rafz.esm.js
let updateQueue = makeQueue();
const raf = fn => schedule(fn, updateQueue);
let writeQueue = makeQueue();
raf.write = fn => schedule(fn, writeQueue);
let onStartQueue = makeQueue();
raf.onStart = fn => schedule(fn, onStartQueue);
let onFrameQueue = makeQueue();
raf.onFrame = fn => schedule(fn, onFrameQueue);
let onFinishQueue = makeQueue();
raf.onFinish = fn => schedule(fn, onFinishQueue);
let timeouts = [];
raf.setTimeout = (handler, ms) => {
let time = raf.now() + ms;
let cancel = () => {
let i = timeouts.findIndex(t => t.cancel == cancel);
if (~i) timeouts.splice(i, 1);
pendingCount -= ~i ? 1 : 0;
};
let timeout = {
time,
handler,
cancel
};
timeouts.splice(findTimeout(time), 0, timeout);
pendingCount += 1;
start();
return timeout;
};
let findTimeout = time => ~(~timeouts.findIndex(t => t.time > time) || ~timeouts.length);
raf.cancel = fn => {
onStartQueue.delete(fn);
onFrameQueue.delete(fn);
updateQueue.delete(fn);
writeQueue.delete(fn);
onFinishQueue.delete(fn);
};
raf.sync = fn => {
sync = true;
raf.batchedUpdates(fn);
sync = false;
};
raf.throttle = fn => {
let lastArgs;
function queuedFn() {
try {
fn(...lastArgs);
} finally {
lastArgs = null;
}
}
function throttled(...args) {
lastArgs = args;
raf.onStart(queuedFn);
}
throttled.handler = fn;
throttled.cancel = () => {
onStartQueue.delete(queuedFn);
lastArgs = null;
};
return throttled;
};
let nativeRaf = typeof window != 'undefined' ? window.requestAnimationFrame : () => {};
raf.use = impl => nativeRaf = impl;
raf.now = typeof performance != 'undefined' ? () => performance.now() : Date.now;
raf.batchedUpdates = fn => fn();
raf.catch = console.error;
raf.frameLoop = 'always';
raf.advance = () => {
if (raf.frameLoop !== 'demand') {
console.warn('Cannot call the manual advancement of rafz whilst frameLoop is not set as demand');
} else {
update();
}
};
let ts = -1;
let pendingCount = 0;
let sync = false;
function schedule(fn, queue) {
if (sync) {
queue.delete(fn);
fn(0);
} else {
queue.add(fn);
start();
}
}
function start() {
if (ts < 0) {
ts = 0;
if (raf.frameLoop !== 'demand') {
nativeRaf(loop);
}
}
}
function stop() {
ts = -1;
}
function loop() {
if (~ts) {
nativeRaf(loop);
raf.batchedUpdates(update);
}
}
function update() {
let prevTs = ts;
ts = raf.now();
let count = findTimeout(ts);
if (count) {
eachSafely(timeouts.splice(0, count), t => t.handler());
pendingCount -= count;
}
onStartQueue.flush();
updateQueue.flush(prevTs ? Math.min(64, ts - prevTs) : 16.667);
onFrameQueue.flush();
writeQueue.flush();
onFinishQueue.flush();
if (!pendingCount) {
stop();
}
}
function makeQueue() {
let next = new Set();
let current = next;
return {
add(fn) {
pendingCount += current == next && !next.has(fn) ? 1 : 0;
next.add(fn);
},
delete(fn) {
pendingCount -= current == next && next.has(fn) ? 1 : 0;
return next.delete(fn);
},
flush(arg) {
if (current.size) {
next = new Set();
pendingCount -= current.size;
eachSafely(current, fn => fn(arg) && next.add(fn));
pendingCount += next.size;
current = next;
}
}
};
}
function eachSafely(values, each) {
values.forEach(value => {
try {
each(value);
} catch (e) {
raf.catch(e);
}
});
}
const __raf = {
count() {
return pendingCount;
},
isRunning() {
return ts >= 0;
},
clear() {
ts = -1;
timeouts = [];
onStartQueue = makeQueue();
updateQueue = makeQueue();
onFrameQueue = makeQueue();
writeQueue = makeQueue();
onFinishQueue = makeQueue();
pendingCount = 0;
}
};
export { __raf, raf };
webpack://frontend-mybets/../../node_modules/@react-spring/shared/dist/react-spring-shared.esm.js
import { raf } from '@react-spring/rafz';
export { raf } from '@react-spring/rafz';
import * as React from 'react';
import { useRef, useState, useEffect } from 'react';
function noop() {}
const defineHidden = (obj, key, value) => Object.defineProperty(obj, key, {
value,
writable: true,
configurable: true
});
const is = {
arr: Array.isArray,
obj: a => !!a && a.constructor.name === 'Object',
fun: a => typeof a === 'function',
str: a => typeof a === 'string',
num: a => typeof a === 'number',
und: a => a === undefined
};
function isEqual(a, b) {
if (is.arr(a)) {
if (!is.arr(b) || a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false;
}
return true;
}
return a === b;
}
const each = (obj, fn) => obj.forEach(fn);
function eachProp(obj, fn, ctx) {
if (is.arr(obj)) {
for (let i = 0; i < obj.length; i++) {
fn.call(ctx, obj[i], `${i}`);
}
return;
}
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
fn.call(ctx, obj[key], key);
}
}
}
const toArray = a => is.und(a) ? [] : is.arr(a) ? a : [a];
function flush(queue, iterator) {
if (queue.size) {
const items = Array.from(queue);
queue.clear();
each(items, iterator);
}
}
const flushCalls = (queue, ...args) => flush(queue, fn => fn(...args));
const isSSR = () => typeof window === 'undefined' || !window.navigator || /ServerSideRendering|^Deno\//.test(window.navigator.userAgent);
let createStringInterpolator$1;
let to;
let colors$1 = null;
let skipAnimation = false;
let willAdvance = noop;
const assign = globals => {
if (globals.to) to = globals.to;
if (globals.now) raf.now = globals.now;
if (globals.colors !== undefined) colors$1 = globals.colors;
if (globals.skipAnimation != null) skipAnimation = globals.skipAnimation;
if (globals.createStringInterpolator) createStringInterpolator$1 = globals.createStringInterpolator;
if (globals.requestAnimationFrame) raf.use(globals.requestAnimationFrame);
if (globals.batchedUpdates) raf.batchedUpdates = globals.batchedUpdates;
if (globals.willAdvance) willAdvance = globals.willAdvance;
if (globals.frameLoop) raf.frameLoop = globals.frameLoop;
};
var globals = /*#__PURE__*/Object.freeze({
__proto__: null,
get createStringInterpolator () { return createStringInterpolator$1; },
get to () { return to; },
get colors () { return colors$1; },
get skipAnimation () { return skipAnimation; },
get willAdvance () { return willAdvance; },
assign: assign
});
const startQueue = new Set();
let currentFrame = [];
let prevFrame = [];
let priority = 0;
const frameLoop = {
get idle() {
return !startQueue.size && !currentFrame.length;
},
start(animation) {
if (priority > animation.priority) {
startQueue.add(animation);
raf.onStart(flushStartQueue);
} else {
startSafely(animation);
raf(advance);
}
},
advance,
sort(animation) {
if (priority) {
raf.onFrame(() => frameLoop.sort(animation));
} else {
const prevIndex = currentFrame.indexOf(animation);
if (~prevIndex) {
currentFrame.splice(prevIndex, 1);
startUnsafely(animation);
}
}
},
clear() {
currentFrame = [];
startQueue.clear();
}
};
function flushStartQueue() {
startQueue.forEach(startSafely);
startQueue.clear();
raf(advance);
}
function startSafely(animation) {
if (!currentFrame.includes(animation)) startUnsafely(animation);
}
function startUnsafely(animation) {
currentFrame.splice(findIndex(currentFrame, other => other.priority > animation.priority), 0, animation);
}
function advance(dt) {
const nextFrame = prevFrame;
for (let i = 0; i < currentFrame.length; i++) {
const animation = currentFrame[i];
priority = animation.priority;
if (!animation.idle) {
willAdvance(animation);
animation.advance(dt);
if (!animation.idle) {
nextFrame.push(animation);
}
}
}
priority = 0;
prevFrame = currentFrame;
prevFrame.length = 0;
currentFrame = nextFrame;
return currentFrame.length > 0;
}
function findIndex(arr, test) {
const index = arr.findIndex(test);
return index < 0 ? arr.length : index;
}
const colors = {
transparent: 0x00000000,
aliceblue: 0xf0f8ffff,
antiquewhite: 0xfaebd7ff,
aqua: 0x00ffffff,
aquamarine: 0x7fffd4ff,
azure: 0xf0ffffff,
beige: 0xf5f5dcff,
bisque: 0xffe4c4ff,
black: 0x000000ff,
blanchedalmond: 0xffebcdff,
blue: 0x0000ffff,
blueviolet: 0x8a2be2ff,
brown: 0xa52a2aff,
burlywood: 0xdeb887ff,
burntsienna: 0xea7e5dff,
cadetblue: 0x5f9ea0ff,
chartreuse: 0x7fff00ff,
chocolate: 0xd2691eff,
coral: 0xff7f50ff,
cornflowerblue: 0x6495edff,
cornsilk: 0xfff8dcff,
crimson: 0xdc143cff,
cyan: 0x00ffffff,
darkblue: 0x00008bff,
darkcyan: 0x008b8bff,
darkgoldenrod: 0xb8860bff,
darkgray: 0xa9a9a9ff,
darkgreen: 0x006400ff,
darkgrey: 0xa9a9a9ff,
darkkhaki: 0xbdb76bff,
darkmagenta: 0x8b008bff,
darkolivegreen: 0x556b2fff,
darkorange: 0xff8c00ff,
darkorchid: 0x9932ccff,
darkred: 0x8b0000ff,
darksalmon: 0xe9967aff,
darkseagreen: 0x8fbc8fff,
darkslateblue: 0x483d8bff,
darkslategray: 0x2f4f4fff,
darkslategrey: 0x2f4f4fff,
darkturquoise: 0x00ced1ff,
darkviolet: 0x9400d3ff,
deeppink: 0xff1493ff,
deepskyblue: 0x00bfffff,
dimgray: 0x696969ff,
dimgrey: 0x696969ff,
dodgerblue: 0x1e90ffff,
firebrick: 0xb22222ff,
floralwhite: 0xfffaf0ff,
forestgreen: 0x228b22ff,
fuchsia: 0xff00ffff,
gainsboro: 0xdcdcdcff,
ghostwhite: 0xf8f8ffff,
gold: 0xffd700ff,
goldenrod: 0xdaa520ff,
gray: 0x808080ff,
green: 0x008000ff,
greenyellow: 0xadff2fff,
grey: 0x808080ff,
honeydew: 0xf0fff0ff,
hotpink: 0xff69b4ff,
indianred: 0xcd5c5cff,
indigo: 0x4b0082ff,
ivory: 0xfffff0ff,
khaki: 0xf0e68cff,
lavender: 0xe6e6faff,
lavenderblush: 0xfff0f5ff,
lawngreen: 0x7cfc00ff,
lemonchiffon: 0xfffacdff,
lightblue: 0xadd8e6ff,
lightcoral: 0xf08080ff,
lightcyan: 0xe0ffffff,
lightgoldenrodyellow: 0xfafad2ff,
lightgray: 0xd3d3d3ff,
lightgreen: 0x90ee90ff,
lightgrey: 0xd3d3d3ff,
lightpink: 0xffb6c1ff,
lightsalmon: 0xffa07aff,
lightseagreen: 0x20b2aaff,
lightskyblue: 0x87cefaff,
lightslategray: 0x778899ff,
lightslategrey: 0x778899ff,
lightsteelblue: 0xb0c4deff,
lightyellow: 0xffffe0ff,
lime: 0x00ff00ff,
limegreen: 0x32cd32ff,
linen: 0xfaf0e6ff,
magenta: 0xff00ffff,
maroon: 0x800000ff,
mediumaquamarine: 0x66cdaaff,
mediumblue: 0x0000cdff,
mediumorchid: 0xba55d3ff,
mediumpurple: 0x9370dbff,
mediumseagreen: 0x3cb371ff,
mediumslateblue: 0x7b68eeff,
mediumspringgreen: 0x00fa9aff,
mediumturquoise: 0x48d1ccff,
mediumvioletred: 0xc71585ff,
midnightblue: 0x191970ff,
mintcream: 0xf5fffaff,
mistyrose: 0xffe4e1ff,
moccasin: 0xffe4b5ff,
navajowhite: 0xffdeadff,
navy: 0x000080ff,
oldlace: 0xfdf5e6ff,
olive: 0x808000ff,
olivedrab: 0x6b8e23ff,
orange: 0xffa500ff,
orangered: 0xff4500ff,
orchid: 0xda70d6ff,
palegoldenrod: 0xeee8aaff,
palegreen: 0x98fb98ff,
paleturquoise: 0xafeeeeff,
palevioletred: 0xdb7093ff,
papayawhip: 0xffefd5ff,
peachpuff: 0xffdab9ff,
peru: 0xcd853fff,
pink: 0xffc0cbff,
plum: 0xdda0ddff,
powderblue: 0xb0e0e6ff,
purple: 0x800080ff,
rebeccapurple: 0x663399ff,
red: 0xff0000ff,
rosybrown: 0xbc8f8fff,
royalblue: 0x4169e1ff,
saddlebrown: 0x8b4513ff,
salmon: 0xfa8072ff,
sandybrown: 0xf4a460ff,
seagreen: 0x2e8b57ff,
seashell: 0xfff5eeff,
sienna: 0xa0522dff,
silver: 0xc0c0c0ff,
skyblue: 0x87ceebff,
slateblue: 0x6a5acdff,
slategray: 0x708090ff,
slategrey: 0x708090ff,
snow: 0xfffafaff,
springgreen: 0x00ff7fff,
steelblue: 0x4682b4ff,
tan: 0xd2b48cff,
teal: 0x008080ff,
thistle: 0xd8bfd8ff,
tomato: 0xff6347ff,
turquoise: 0x40e0d0ff,
violet: 0xee82eeff,
wheat: 0xf5deb3ff,
white: 0xffffffff,
whitesmoke: 0xf5f5f5ff,
yellow: 0xffff00ff,
yellowgreen: 0x9acd32ff
};
const NUMBER = '[-+]?\\d*\\.?\\d+';
const PERCENTAGE = NUMBER + '%';
function call(...parts) {
return '\\(\\s*(' + parts.join(')\\s*,\\s*(') + ')\\s*\\)';
}
const rgb = new RegExp('rgb' + call(NUMBER, NUMBER, NUMBER));
const rgba = new RegExp('rgba' + call(NUMBER, NUMBER, NUMBER, NUMBER));
const hsl = new RegExp('hsl' + call(NUMBER, PERCENTAGE, PERCENTAGE));
const hsla = new RegExp('hsla' + call(NUMBER, PERCENTAGE, PERCENTAGE, NUMBER));
const hex3 = /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/;
const hex4 = /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/;
const hex6 = /^#([0-9a-fA-F]{6})$/;
const hex8 = /^#([0-9a-fA-F]{8})$/;
function normalizeColor(color) {
let match;
if (typeof color === 'number') {
return color >>> 0 === color && color >= 0 && color <= 0xffffffff ? color : null;
}
if (match = hex6.exec(color)) return parseInt(match[1] + 'ff', 16) >>> 0;
if (colors$1 && colors$1[color] !== undefined) {
return colors$1[color];
}
if (match = rgb.exec(color)) {
return (parse255(match[1]) << 24 | parse255(match[2]) << 16 | parse255(match[3]) << 8 | 0x000000ff) >>> 0;
}
if (match = rgba.exec(color)) {
return (parse255(match[1]) << 24 | parse255(match[2]) << 16 | parse255(match[3]) << 8 | parse1(match[4])) >>> 0;
}
if (match = hex3.exec(color)) {
return parseInt(match[1] + match[1] + match[2] + match[2] + match[3] + match[3] + 'ff', 16) >>> 0;
}
if (match = hex8.exec(color)) return parseInt(match[1], 16) >>> 0;
if (match = hex4.exec(color)) {
return parseInt(match[1] + match[1] + match[2] + match[2] + match[3] + match[3] + match[4] + match[4], 16) >>> 0;
}
if (match = hsl.exec(color)) {
return (hslToRgb(parse360(match[1]), parsePercentage(match[2]), parsePercentage(match[3])) | 0x000000ff) >>> 0;
}
if (match = hsla.exec(color)) {
return (hslToRgb(parse360(match[1]), parsePercentage(match[2]), parsePercentage(match[3])) | parse1(match[4])) >>> 0;
}
return null;
}
function hue2rgb(p, q, t) {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1 / 6) return p + (q - p) * 6 * t;
if (t < 1 / 2) return q;
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
}
function hslToRgb(h, s, l) {
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
const r = hue2rgb(p, q, h + 1 / 3);
const g = hue2rgb(p, q, h);
const b = hue2rgb(p, q, h - 1 / 3);
return Math.round(r * 255) << 24 | Math.round(g * 255) << 16 | Math.round(b * 255) << 8;
}
function parse255(str) {
const int = parseInt(str, 10);
if (int < 0) return 0;
if (int > 255) return 255;
return int;
}
function parse360(str) {
const int = parseFloat(str);
return (int % 360 + 360) % 360 / 360;
}
function parse1(str) {
const num = parseFloat(str);
if (num < 0) return 0;
if (num > 1) return 255;
return Math.round(num * 255);
}
function parsePercentage(str) {
const int = parseFloat(str);
if (int < 0) return 0;
if (int > 100) return 1;
return int / 100;
}
function colorToRgba(input) {
let int32Color = normalizeColor(input);
if (int32Color === null) return input;
int32Color = int32Color || 0;
let r = (int32Color & 0xff000000) >>> 24;
let g = (int32Color & 0x00ff0000) >>> 16;
let b = (int32Color & 0x0000ff00) >>> 8;
let a = (int32Color & 0x000000ff) / 255;
return `rgba(${r}, ${g}, ${b}, ${a})`;
}
const createInterpolator = (range, output, extrapolate) => {
if (is.fun(range)) {
return range;
}
if (is.arr(range)) {
return createInterpolator({
range,
output: output,
extrapolate
});
}
if (is.str(range.output[0])) {
return createStringInterpolator$1(range);
}
const config = range;
const outputRange = config.output;
const inputRange = config.range || [0, 1];
const extrapolateLeft = config.extrapolateLeft || config.extrapolate || 'extend';
const extrapolateRight = config.extrapolateRight || config.extrapolate || 'extend';
const easing = config.easing || (t => t);
return input => {
const range = findRange(input, inputRange);
return interpolate(input, inputRange[range], inputRange[range + 1], outputRange[range], outputRange[range + 1], easing, extrapolateLeft, extrapolateRight, config.map);
};
};
function interpolate(input, inputMin, inputMax, outputMin, outputMax, easing, extrapolateLeft, extrapolateRight, map) {
let result = map ? map(input) : input;
if (result < inputMin) {
if (extrapolateLeft === 'identity') return result;else if (extrapolateLeft === 'clamp') result = inputMin;
}
if (result > inputMax) {
if (extrapolateRight === 'identity') return result;else if (extrapolateRight === 'clamp') result = inputMax;
}
if (outputMin === outputMax) return outputMin;
if (inputMin === inputMax) return input <= inputMin ? outputMin : outputMax;
if (inputMin === -Infinity) result = -result;else if (inputMax === Infinity) result = result - inputMin;else result = (result - inputMin) / (inputMax - inputMin);
result = easing(result);
if (outputMin === -Infinity) result = -result;else if (outputMax === Infinity) result = result + outputMin;else result = result * (outputMax - outputMin) + outputMin;
return result;
}
function findRange(input, inputRange) {
for (var i = 1; i < inputRange.length - 1; ++i) if (inputRange[i] >= input) break;
return i - 1;
}
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);
}
const $get = Symbol.for('FluidValue.get');
const $observers = Symbol.for('FluidValue.observers');
const hasFluidValue = arg => Boolean(arg && arg[$get]);
const getFluidValue = arg => arg && arg[$get] ? arg[$get]() : arg;
const getFluidObservers = target => target[$observers] || null;
function callFluidObserver(observer, event) {
if (observer.eventObserved) {
observer.eventObserved(event);
} else {
observer(event);
}
}
function callFluidObservers(target, event) {
let observers = target[$observers];
if (observers) {
observers.forEach(observer => {
callFluidObserver(observer, event);
});
}
}
class FluidValue {
constructor(get) {
this[$get] = void 0;
this[$observers] = void 0;
if (!get && !(get = this.get)) {
throw Error('Unknown getter');
}
setFluidGetter(this, get);
}
}
const setFluidGetter = (target, get) => setHidden(target, $get, get);
function addFluidObserver(target, observer) {
if (target[$get]) {
let observers = target[$observers];
if (!observers) {
setHidden(target, $observers, observers = new Set());
}
if (!observers.has(observer)) {
observers.add(observer);
if (target.observerAdded) {
target.observerAdded(observers.size, observer);
}
}
}
return observer;
}
function removeFluidObserver(target, observer) {
let observers = target[$observers];
if (observers && observers.has(observer)) {
const count = observers.size - 1;
if (count) {
observers.delete(observer);
} else {
target[$observers] = null;
}
if (target.observerRemoved) {
target.observerRemoved(count, observer);
}
}
}
const setHidden = (target, key, value) => Object.defineProperty(target, key, {
value,
writable: true,
configurable: true
});
const numberRegex = /[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
const colorRegex = /(#(?:[0-9a-f]{2}){2,4}|(#[0-9a-f]{3})|(rgb|hsl)a?\((-?\d+%?[,\s]+){2,3}\s*[\d\.]+%?\))/gi;
const unitRegex = new RegExp(`(${numberRegex.source})(%|[a-z]+)`, 'i');
const rgbaRegex = /rgba\(([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+)\)/gi;
const cssVariableRegex = /var\((--[a-zA-Z0-9-_]+),? ?([a-zA-Z0-9 ()%#.,-]+)?\)/;
const variableToRgba = input => {
const [token, fallback] = parseCSSVariable(input);
if (!token || isSSR()) {
return input;
}
const value = window.getComputedStyle(document.documentElement).getPropertyValue(token);
if (value) {
return value.trim();
} else if (fallback && fallback.startsWith('--')) {
const _value = window.getComputedStyle(document.documentElement).getPropertyValue(fallback);
if (_value) {
return _value;
} else {
return input;
}
} else if (fallback && cssVariableRegex.test(fallback)) {
return variableToRgba(fallback);
} else if (fallback) {
return fallback;
}
return input;
};
const parseCSSVariable = current => {
const match = cssVariableRegex.exec(current);
if (!match) return [,];
const [, token, fallback] = match;
return [token, fallback];
};
let namedColorRegex;
const rgbaRound = (_, p1, p2, p3, p4) => `rgba(${Math.round(p1)}, ${Math.round(p2)}, ${Math.round(p3)}, ${p4})`;
const createStringInterpolator = config => {
if (!namedColorRegex) namedColorRegex = colors$1 ? new RegExp(`(${Object.keys(colors$1).join('|')})(?!\\w)`, 'g') : /^\b$/;
const output = config.output.map(value => {
return getFluidValue(value).replace(cssVariableRegex, variableToRgba).replace(colorRegex, colorToRgba).replace(namedColorRegex, colorToRgba);
});
const keyframes = output.map(value => value.match(numberRegex).map(Number));
const outputRanges = keyframes[0].map((_, i) => keyframes.map(values => {
if (!(i in values)) {
throw Error('The arity of each "output" value must be equal');
}
return values[i];
}));
const interpolators = outputRanges.map(output => createInterpolator(_extends({}, config, {
output
})));
return input => {
var _output$find;
const missingUnit = !unitRegex.test(output[0]) && ((_output$find = output.find(value => unitRegex.test(value))) == null ? void 0 : _output$find.replace(numberRegex, ''));
let i = 0;
return output[0].replace(numberRegex, () => `${interpolators[i++](input)}${missingUnit || ''}`).replace(rgbaRegex, rgbaRound);
};
};
const prefix = 'react-spring: ';
const once = fn => {
const func = fn;
let called = false;
if (typeof func != 'function') {
throw new TypeError(`${prefix}once requires a function parameter`);
}
return (...args) => {
if (!called) {
func(...args);
called = true;
}
};
};
const warnInterpolate = once(console.warn);
function deprecateInterpolate() {
warnInterpolate(`${prefix}The "interpolate" function is deprecated in v9 (use "to" instead)`);
}
const warnDirectCall = once(console.warn);
function deprecateDirectCall() {
warnDirectCall(`${prefix}Directly calling start instead of using the api object is deprecated in v9 (use ".start" instead), this will be removed in later 0.X.0 versions`);
}
function isAnimatedString(value) {
return is.str(value) && (value[0] == '#' || /\d/.test(value) || !isSSR() && cssVariableRegex.test(value) || value in (colors$1 || {}));
}
const useLayoutEffect = typeof window !== 'undefined' && window.document && window.document.createElement ? React.useLayoutEffect : React.useEffect;
const useIsMounted = () => {
const isMounted = useRef(false);
useLayoutEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
};
}, []);
return isMounted;
};
function useForceUpdate() {
const update = useState()[1];
const isMounted = useIsMounted();
return () => {
if (isMounted.current) {
update(Math.random());
}
};
}
function useMemoOne(getResult, inputs) {
const [initial] = useState(() => ({
inputs,
result: getResult()
}));
const committed = useRef();
const prevCache = committed.current;
let cache = prevCache;
if (cache) {
const useCache = Boolean(inputs && cache.inputs && areInputsEqual(inputs, cache.inputs));
if (!useCache) {
cache = {
inputs,
result: getResult()
};
}
} else {
cache = initial;
}
useEffect(() => {
committed.current = cache;
if (prevCache == initial) {
initial.inputs = initial.result = undefined;
}
}, [cache]);
return cache.result;
}
function areInputsEqual(next, prev) {
if (next.length !== prev.length) {
return false;
}
for (let i = 0; i < next.length; i++) {
if (next[i] !== prev[i]) {
return false;
}
}
return true;
}
const useOnce = effect => useEffect(effect, emptyDeps);
const emptyDeps = [];
function usePrev(value) {
const prevRef = useRef();
useEffect(() => {
prevRef.current = value;
});
return prevRef.current;
}
export { FluidValue, globals as Globals, addFluidObserver, callFluidObserver, callFluidObservers, colorToRgba, colors, createInterpolator, createStringInterpolator, defineHidden, deprecateDirectCall, deprecateInterpolate, each, eachProp, flush, flushCalls, frameLoop, getFluidObservers, getFluidValue, hasFluidValue, hex3, hex4, hex6, hex8, hsl, hsla, is, isAnimatedString, isEqual, isSSR, noop, removeFluidObserver, rgb, rgba, setFluidGetter, toArray, useForceUpdate, useLayoutEffect, useMemoOne, useOnce, usePrev };
webpack://frontend-mybets/../../node_modules/accounting/accounting.js
/*!
* accounting.js v0.4.1
* Copyright 2014 Open Exchange Rates
*
* Freely distributable under the MIT license.
* Portions of accounting.js are inspired or borrowed from underscore.js
*
* Full details and documentation:
* http://openexchangerates.github.io/accounting.js/
*/
(function(root, undefined) {
/* --- Setup --- */
// Create the local library object, to be exported or referenced globally later
var lib = {};
// Current version
lib.version = '0.4.1';
/* --- Exposed settings --- */
// The library's settings configuration object. Contains default parameters for
// currency and number formatting
lib.settings = {
currency: {
symbol : "$", // default currency symbol is '$'
format : "%s%v", // controls output: %s = symbol, %v = value (can be object, see docs)
decimal : ".", // decimal point separator
thousand : ",", // thousands separator
precision : 2, // decimal places
grouping : 3 // digit grouping (not implemented yet)
},
number: {
precision : 0, // default precision on numbers is 0
grouping : 3, // digit grouping (not implemented yet)
thousand : ",",
decimal : "."
}
};
/* --- Internal Helper Methods --- */
// Store reference to possibly-available ECMAScript 5 methods for later
var nativeMap = Array.prototype.map,
nativeIsArray = Array.isArray,
toString = Object.prototype.toString;
/**
* Tests whether supplied parameter is a string
* from underscore.js
*/
function isString(obj) {
return !!(obj === '' || (obj && obj.charCodeAt && obj.substr));
}
/**
* Tests whether supplied parameter is a string
* from underscore.js, delegates to ECMA5's native Array.isArray
*/
function isArray(obj) {
return nativeIsArray ? nativeIsArray(obj) : toString.call(obj) === '[object Array]';
}
/**
* Tests whether supplied parameter is a true object
*/
function isObject(obj) {
return obj && toString.call(obj) === '[object Object]';
}
/**
* Extends an object with a defaults object, similar to underscore's _.defaults
*
* Used for abstracting parameter handling from API methods
*/
function defaults(object, defs) {
var key;
object = object || {};
defs = defs || {};
// Iterate over object non-prototype properties:
for (key in defs) {
if (defs.hasOwnProperty(key)) {
// Replace values with defaults only if undefined (allow empty/zero values):
if (object[key] == null) object[key] = defs[key];
}
}
return object;
}
/**
* Implementation of `Array.map()` for iteration loops
*
* Returns a new Array as a result of calling `iterator` on each array value.
* Defers to native Array.map if available
*/
function map(obj, iterator, context) {
var results = [], i, j;
if (!obj) return results;
// Use native .map method if it exists:
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
// Fallback for native .map:
for (i = 0, j = obj.length; i < j; i++ ) {
results[i] = iterator.call(context, obj[i], i, obj);
}
return results;
}
/**
* Check and normalise the value of precision (must be positive integer)
*/
function checkPrecision(val, base) {
val = Math.round(Math.abs(val));
return isNaN(val)? base : val;
}
/**
* Parses a format string or object and returns format obj for use in rendering
*
* `format` is either a string with the default (positive) format, or object
* containing `pos` (required), `neg` and `zero` values (or a function returning
* either a string or object)
*
* Either string or format.pos must contain "%v" (value) to be valid
*/
function checkCurrencyFormat(format) {
var defaults = lib.settings.currency.format;
// Allow function as format parameter (should return string or object):
if ( typeof format === "function" ) format = format();
// Format can be a string, in which case `value` ("%v") must be present:
if ( isString( format ) && format.match("%v") ) {
// Create and return positive, negative and zero formats:
return {
pos : format,
neg : format.replace("-", "").replace("%v", "-%v"),
zero : format
};
// If no format, or object is missing valid positive value, use defaults:
} else if ( !format || !format.pos || !format.pos.match("%v") ) {
// If defaults is a string, casts it to an object for faster checking next time:
return ( !isString( defaults ) ) ? defaults : lib.settings.currency.format = {
pos : defaults,
neg : defaults.replace("%v", "-%v"),
zero : defaults
};
}
// Otherwise, assume format was fine:
return format;
}
/* --- API Methods --- */
/**
* Takes a string/array of strings, removes all formatting/cruft and returns the raw float value
* Alias: `accounting.parse(string)`
*
* Decimal must be included in the regular expression to match floats (defaults to
* accounting.settings.number.decimal), so if the number uses a non-standard decimal
* separator, provide it as the second argument.
*
* Also matches bracketed negatives (eg. "$ (1.99)" => -1.99)
*
* Doesn't throw any errors (`NaN`s become 0) but this may change in future
*/
var unformat = lib.unformat = lib.parse = function(value, decimal) {
// Recursively unformat arrays:
if (isArray(value)) {
return map(value, function(val) {
return unformat(val, decimal);
});
}
// Fails silently (need decent errors):
value = value || 0;
// Return the value as-is if it's already a number:
if (typeof value === "number") return value;
// Default decimal point comes from settings, but could be set to eg. "," in opts:
decimal = decimal || lib.settings.number.decimal;
// Build regex to strip out everything except digits, decimal point and minus sign:
var regex = new RegExp("[^0-9-" + decimal + "]", ["g"]),
unformatted = parseFloat(
("" + value)
.replace(/\((.*)\)/, "-$1") // replace bracketed values with negatives
.replace(regex, '') // strip out any cruft
.replace(decimal, '.') // make sure decimal point is standard
);
// This will fail silently which may cause trouble, let's wait and see:
return !isNaN(unformatted) ? unformatted : 0;
};
/**
* Implementation of toFixed() that treats floats more like decimals
*
* Fixes binary rounding issues (eg. (0.615).toFixed(2) === "0.61") that present
* problems for accounting- and finance-related software.
*/
var toFixed = lib.toFixed = function(value, precision) {
precision = checkPrecision(precision, lib.settings.number.precision);
var power = Math.pow(10, precision);
// Multiply up by precision, round accurately, then divide and use native toFixed():
return (Math.round(lib.unformat(value) * power) / power).toFixed(precision);
};
/**
* Format a number, with comma-separated thousands and custom precision/decimal places
* Alias: `accounting.format()`
*
* Localise by overriding the precision and thousand / decimal separators
* 2nd parameter `precision` can be an object matching `settings.number`
*/
var formatNumber = lib.formatNumber = lib.format = function(number, precision, thousand, decimal) {
// Resursively format arrays:
if (isArray(number)) {
return map(number, function(val) {
return formatNumber(val, precision, thousand, decimal);
});
}
// Clean up number:
number = unformat(number);
// Build options object from second param (if object) or all params, extending defaults:
var opts = defaults(
(isObject(precision) ? precision : {
precision : precision,
thousand : thousand,
decimal : decimal
}),
lib.settings.number
),
// Clean up precision
usePrecision = checkPrecision(opts.precision),
// Do some calc:
negative = number < 0 ? "-" : "",
base = parseInt(toFixed(Math.abs(number || 0), usePrecision), 10) + "",
mod = base.length > 3 ? base.length % 3 : 0;
// Format the number:
return negative + (mod ? base.substr(0, mod) + opts.thousand : "") + base.substr(mod).replace(/(\d{3})(?=\d)/g, "$1" + opts.thousand) + (usePrecision ? opts.decimal + toFixed(Math.abs(number), usePrecision).split('.')[1] : "");
};
/**
* Format a number into currency
*
* Usage: accounting.formatMoney(number, symbol, precision, thousandsSep, decimalSep, format)
* defaults: (0, "$", 2, ",", ".", "%s%v")
*
* Localise by overriding the symbol, precision, thousand / decimal separators and format
* Second param can be an object matching `settings.currency` which is the easiest way.
*
* To do: tidy up the parameters
*/
var formatMoney = lib.formatMoney = function(number, symbol, precision, thousand, decimal, format) {
// Resursively format arrays:
if (isArray(number)) {
return map(number, function(val){
return formatMoney(val, symbol, precision, thousand, decimal, format);
});
}
// Clean up number:
number = unformat(number);
// Build options object from second param (if object) or all params, extending defaults:
var opts = defaults(
(isObject(symbol) ? symbol : {
symbol : symbol,
precision : precision,
thousand : thousand,
decimal : decimal,
format : format
}),
lib.settings.currency
),
// Check format (returns object with pos, neg and zero):
formats = checkCurrencyFormat(opts.format),
// Choose which format to use for this value:
useFormat = number > 0 ? formats.pos : number < 0 ? formats.neg : formats.zero;
// Return with currency symbol added:
return useFormat.replace('%s', opts.symbol).replace('%v', formatNumber(Math.abs(number), checkPrecision(opts.precision), opts.thousand, opts.decimal));
};
/**
* Format a list of numbers into an accounting column, padding with whitespace
* to line up currency symbols, thousand separators and decimals places
*
* List should be an array of numbers
* Second parameter can be an object containing keys that match the params
*
* Returns array of accouting-formatted number strings of same length
*
* NB: `white-space:pre` CSS rule is required on the list container to prevent
* browsers from collapsing the whitespace in the output strings.
*/
lib.formatColumn = function(list, symbol, precision, thousand, decimal, format) {
if (!list) return [];
// Build options object from second param (if object) or all params, extending defaults:
var opts = defaults(
(isObject(symbol) ? symbol : {
symbol : symbol,
precision : precision,
thousand : thousand,
decimal : decimal,
format : format
}),
lib.settings.currency
),
// Check format (returns object with pos, neg and zero), only need pos for now:
formats = checkCurrencyFormat(opts.format),
// Whether to pad at start of string or after currency symbol:
padAfterSymbol = formats.pos.indexOf("%s") < formats.pos.indexOf("%v") ? true : false,
// Store value for the length of the longest string in the column:
maxLength = 0,
// Format the list according to options, store the length of the longest string:
formatted = map(list, function(val, i) {
if (isArray(val)) {
// Recursively format columns if list is a multi-dimensional array:
return lib.formatColumn(val, opts);
} else {
// Clean up the value
val = unformat(val);
// Choose which format to use for this value (pos, neg or zero):
var useFormat = val > 0 ? formats.pos : val < 0 ? formats.neg : formats.zero,
// Format this value, push into formatted list and save the length:
fVal = useFormat.replace('%s', opts.symbol).replace('%v', formatNumber(Math.abs(val), checkPrecision(opts.precision), opts.thousand, opts.decimal));
if (fVal.length > maxLength) maxLength = fVal.length;
return fVal;
}
});
// Pad each number in the list and send back the column of numbers:
return map(formatted, function(val, i) {
// Only if this is a string (not a nested array, which would have already been padded):
if (isString(val) && val.length < maxLength) {
// Depending on symbol position, pad after symbol or at index 0:
return padAfterSymbol ? val.replace(opts.symbol, opts.symbol+(new Array(maxLength - val.length + 1).join(" "))) : (new Array(maxLength - val.length + 1).join(" ")) + val;
}
return val;
});
};
/* --- Module Definition --- */
// Export accounting for CommonJS. If being loaded as an AMD module, define it as such.
// Otherwise, just add `accounting` to the global object
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = lib;
}
exports.accounting = lib;
} else if (typeof define === 'function' && define.amd) {
// Return the library as an AMD module:
define([], function() {
return lib;
});
} else {
// Use accounting.noConflict to restore `accounting` back to its original value.
// Returns a reference to the library's `accounting` object;
// e.g. `var numbers = accounting.noConflict();`
lib.noConflict = (function(oldAccounting) {
return function() {
// Reset the value of the root's `accounting` variable:
root.accounting = oldAccounting;
// Delete the noConflict method:
lib.noConflict = undefined;
// Return reference to the library to re-assign it:
return lib;
};
})(root.accounting);
// Declare `fx` on the root (global/window) object:
root['accounting'] = lib;
}
// Root will be `window` in browser or `global` on the server:
}(this));
webpack://frontend-mybets/../../node_modules/axios/index.js
module.exports = require('./lib/axios');
webpack://frontend-mybets/../../node_modules/axios/lib/adapters/xhr.js
'use strict';
var utils = require('./../utils');
var settle = require('./../core/settle');
var cookies = require('./../helpers/cookies');
var buildURL = require('./../helpers/buildURL');
var buildFullPath = require('../core/buildFullPath');
var parseHeaders = require('./../helpers/parseHeaders');
var isURLSameOrigin = require('./../helpers/isURLSameOrigin');
var transitionalDefaults = require('../defaults/transitional');
var AxiosError = require('../core/AxiosError');
var CanceledError = require('../cancel/CanceledError');
var parseProtocol = require('../helpers/parseProtocol');
module.exports = function xhrAdapter(config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
var requestData = config.data;
var requestHeaders = config.headers;
var responseType = config.responseType;
var onCanceled;
function done() {
if (config.cancelToken) {
config.cancelToken.unsubscribe(onCanceled);
}
if (config.signal) {
config.signal.removeEventListener('abort', onCanceled);
}
}
if (utils.isFormData(requestData) && utils.isStandardBrowserEnv()) {
delete requestHeaders['Content-Type']; // Let the browser set it
}
var request = new XMLHttpRequest();
// HTTP basic authentication
if (config.auth) {
var username = config.auth.username || '';
var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
}
var fullPath = buildFullPath(config.baseURL, config.url);
request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
// Set the request timeout in MS
request.timeout = config.timeout;
function onloadend() {
if (!request) {
return;
}
// Prepare the response
var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
var responseData = !responseType || responseType === 'text' || responseType === 'json' ?
request.responseText : request.response;
var response = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config: config,
request: request
};
settle(function _resolve(value) {
resolve(value);
done();
}, function _reject(err) {
reject(err);
done();
}, response);
// Clean up request
request = null;
}
if ('onloadend' in request) {
// Use onloadend if available
request.onloadend = onloadend;
} else {
// Listen for ready state to emulate onloadend
request.onreadystatechange = function handleLoad() {
if (!request || request.readyState !== 4) {
return;
}
// The request errored out and we didn't get a response, this will be
// handled by onerror instead
// With one exception: request that using file: protocol, most browsers
// will return status as 0 even though it's a successful request
if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
return;
}
// readystate handler is calling before onerror or ontimeout handlers,
// so we should call onloadend on the next 'tick'
setTimeout(onloadend);
};
}
// Handle browser request cancellation (as opposed to a manual cancellation)
request.onabort = function handleAbort() {
if (!request) {
return;
}
reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
// Clean up request
request = null;
};
// Handle low level network errors
request.onerror = function handleError() {
// Real errors are hidden from us by the browser
// onerror should only fire if it's a network error
reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request, request));
// Clean up request
request = null;
};
// Handle timeout
request.ontimeout = function handleTimeout() {
var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
var transitional = config.transitional || transitionalDefaults;
if (config.timeoutErrorMessage) {
timeoutErrorMessage = config.timeoutErrorMessage;
}
reject(new AxiosError(
timeoutErrorMessage,
transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
config,
request));
// Clean up request
request = null;
};
// Add xsrf header
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (utils.isStandardBrowserEnv()) {
// Add xsrf header
var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
cookies.read(config.xsrfCookieName) :
undefined;
if (xsrfValue) {
requestHeaders[config.xsrfHeaderName] = xsrfValue;
}
}
// Add headers to the request
if ('setRequestHeader' in request) {
utils.forEach(requestHeaders, function setRequestHeader(val, key) {
if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
// Remove Content-Type if data is undefined
delete requestHeaders[key];
} else {
// Otherwise add header to the request
request.setRequestHeader(key, val);
}
});
}
// Add withCredentials to request if needed
if (!utils.isUndefined(config.withCredentials)) {
request.withCredentials = !!config.withCredentials;
}
// Add responseType to request if needed
if (responseType && responseType !== 'json') {
request.responseType = config.responseType;
}
// Handle progress if needed
if (typeof config.onDownloadProgress === 'function') {
request.addEventListener('progress', config.onDownloadProgress);
}
// Not all browsers support upload events
if (typeof config.onUploadProgress === 'function' && request.upload) {
request.upload.addEventListener('progress', config.onUploadProgress);
}
if (config.cancelToken || config.signal) {
// Handle cancellation
// eslint-disable-next-line func-names
onCanceled = function(cancel) {
if (!request) {
return;
}
reject(!cancel || (cancel && cancel.type) ? new CanceledError() : cancel);
request.abort();
request = null;
};
config.cancelToken && config.cancelToken.subscribe(onCanceled);
if (config.signal) {
config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
}
}
if (!requestData) {
requestData = null;
}
var protocol = parseProtocol(fullPath);
if (protocol && [ 'http', 'https', 'file' ].indexOf(protocol) === -1) {
reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
return;
}
// Send the request
request.send(requestData);
});
};
webpack://frontend-mybets/../../node_modules/axios/lib/axios.js
'use strict';
var utils = require('./utils');
var bind = require('./helpers/bind');
var Axios = require('./core/Axios');
var mergeConfig = require('./core/mergeConfig');
var defaults = require('./defaults');
/**
* Create an instance of Axios
*
* @param {Object} defaultConfig The default config for the instance
* @return {Axios} A new instance of Axios
*/
function createInstance(defaultConfig) {
var context = new Axios(defaultConfig);
var instance = bind(Axios.prototype.request, context);
// Copy axios.prototype to instance
utils.extend(instance, Axios.prototype, context);
// Copy context to instance
utils.extend(instance, context);
// Factory for creating new instances
instance.create = function create(instanceConfig) {
return createInstance(mergeConfig(defaultConfig, instanceConfig));
};
return instance;
}
// Create the default instance to be exported
var axios = createInstance(defaults);
// Expose Axios class to allow class inheritance
axios.Axios = Axios;
// Expose Cancel & CancelToken
axios.CanceledError = require('./cancel/CanceledError');
axios.CancelToken = require('./cancel/CancelToken');
axios.isCancel = require('./cancel/isCancel');
axios.VERSION = require('./env/data').version;
axios.toFormData = require('./helpers/toFormData');
// Expose AxiosError class
axios.AxiosError = require('../lib/core/AxiosError');
// alias for CanceledError for backward compatibility
axios.Cancel = axios.CanceledError;
// Expose all/spread
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = require('./helpers/spread');
// Expose isAxiosError
axios.isAxiosError = require('./helpers/isAxiosError');
module.exports = axios;
// Allow use of default import syntax in TypeScript
module.exports.default = axios;
webpack://frontend-mybets/../../node_modules/axios/lib/cancel/CancelToken.js
'use strict';
var CanceledError = require('./CanceledError');
/**
* A `CancelToken` is an object that can be used to request cancellation of an operation.
*
* @class
* @param {Function} executor The executor function.
*/
function CancelToken(executor) {
if (typeof executor !== 'function') {
throw new TypeError('executor must be a function.');
}
var resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
var token = this;
// eslint-disable-next-line func-names
this.promise.then(function(cancel) {
if (!token._listeners) return;
var i;
var l = token._listeners.length;
for (i = 0; i < l; i++) {
token._listeners[i](cancel);
}
token._listeners = null;
});
// eslint-disable-next-line func-names
this.promise.then = function(onfulfilled) {
var _resolve;
// eslint-disable-next-line func-names
var promise = new Promise(function(resolve) {
token.subscribe(resolve);
_resolve = resolve;
}).then(onfulfilled);
promise.cancel = function reject() {
token.unsubscribe(_resolve);
};
return promise;
};
executor(function cancel(message) {
if (token.reason) {
// Cancellation has already been requested
return;
}
token.reason = new CanceledError(message);
resolvePromise(token.reason);
});
}
/**
* Throws a `CanceledError` if cancellation has been requested.
*/
CancelToken.prototype.throwIfRequested = function throwIfRequested() {
if (this.reason) {
throw this.reason;
}
};
/**
* Subscribe to the cancel signal
*/
CancelToken.prototype.subscribe = function subscribe(listener) {
if (this.reason) {
listener(this.reason);
return;
}
if (this._listeners) {
this._listeners.push(listener);
} else {
this._listeners = [listener];
}
};
/**
* Unsubscribe from the cancel signal
*/
CancelToken.prototype.unsubscribe = function unsubscribe(listener) {
if (!this._listeners) {
return;
}
var index = this._listeners.indexOf(listener);
if (index !== -1) {
this._listeners.splice(index, 1);
}
};
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
* cancels the `CancelToken`.
*/
CancelToken.source = function source() {
var cancel;
var token = new CancelToken(function executor(c) {
cancel = c;
});
return {
token: token,
cancel: cancel
};
};
module.exports = CancelToken;
webpack://frontend-mybets/../../node_modules/axios/lib/cancel/CanceledError.js
'use strict';
var AxiosError = require('../core/AxiosError');
var utils = require('../utils');
/**
* A `CanceledError` is an object that is thrown when an operation is canceled.
*
* @class
* @param {string=} message The message.
*/
function CanceledError(message) {
// eslint-disable-next-line no-eq-null,eqeqeq
AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED);
this.name = 'CanceledError';
}
utils.inherits(CanceledError, AxiosError, {
__CANCEL__: true
});
module.exports = CanceledError;
webpack://frontend-mybets/../../node_modules/axios/lib/cancel/isCancel.js
'use strict';
module.exports = function isCancel(value) {
return !!(value && value.__CANCEL__);
};
webpack://frontend-mybets/../../node_modules/axios/lib/core/Axios.js
'use strict';
var utils = require('./../utils');
var buildURL = require('../helpers/buildURL');
var InterceptorManager = require('./InterceptorManager');
var dispatchRequest = require('./dispatchRequest');
var mergeConfig = require('./mergeConfig');
var buildFullPath = require('./buildFullPath');
var validator = require('../helpers/validator');
var validators = validator.validators;
/**
* Create a new instance of Axios
*
* @param {Object} instanceConfig The default config for the instance
*/
function Axios(instanceConfig) {
this.defaults = instanceConfig;
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
};
}
/**
* Dispatch a request
*
* @param {Object} config The config specific for this request (merged with this.defaults)
*/
Axios.prototype.request = function request(configOrUrl, config) {
/*eslint no-param-reassign:0*/
// Allow for axios('example/url'[, config]) a la fetch API
if (typeof configOrUrl === 'string') {
config = config || {};
config.url = configOrUrl;
} else {
config = configOrUrl || {};
}
config = mergeConfig(this.defaults, config);
// Set config.method
if (config.method) {
config.method = config.method.toLowerCase();
} else if (this.defaults.method) {
config.method = this.defaults.method.toLowerCase();
} else {
config.method = 'get';
}
var transitional = config.transitional;
if (transitional !== undefined) {
validator.assertOptions(transitional, {
silentJSONParsing: validators.transitional(validators.boolean),
forcedJSONParsing: validators.transitional(validators.boolean),
clarifyTimeoutError: validators.transitional(validators.boolean)
}, false);
}
// filter out skipped interceptors
var requestInterceptorChain = [];
var synchronousRequestInterceptors = true;
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
return;
}
synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
});
var responseInterceptorChain = [];
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
});
var promise;
if (!synchronousRequestInterceptors) {
var chain = [dispatchRequest, undefined];
Array.prototype.unshift.apply(chain, requestInterceptorChain);
chain = chain.concat(responseInterceptorChain);
promise = Promise.resolve(config);
while (chain.length) {
promise = promise.then(chain.shift(), chain.shift());
}
return promise;
}
var newConfig = config;
while (requestInterceptorChain.length) {
var onFulfilled = requestInterceptorChain.shift();
var onRejected = requestInterceptorChain.shift();
try {
newConfig = onFulfilled(newConfig);
} catch (error) {
onRejected(error);
break;
}
}
try {
promise = dispatchRequest(newConfig);
} catch (error) {
return Promise.reject(error);
}
while (responseInterceptorChain.length) {
promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());
}
return promise;
};
Axios.prototype.getUri = function getUri(config) {
config = mergeConfig(this.defaults, config);
var fullPath = buildFullPath(config.baseURL, config.url);
return buildURL(fullPath, config.params, config.paramsSerializer);
};
// Provide aliases for supported request methods
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, config) {
return this.request(mergeConfig(config || {}, {
method: method,
url: url,
data: (config || {}).data
}));
};
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
/*eslint func-names:0*/
function generateHTTPMethod(isForm) {
return function httpMethod(url, data, config) {
return this.request(mergeConfig(config || {}, {
method: method,
headers: isForm ? {
'Content-Type': 'multipart/form-data'
} : {},
url: url,
data: data
}));
};
}
Axios.prototype[method] = generateHTTPMethod();
Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
});
module.exports = Axios;
webpack://frontend-mybets/../../node_modules/axios/lib/core/AxiosError.js
'use strict';
var utils = require('../utils');
/**
* Create an Error with the specified message, config, error code, request and response.
*
* @param {string} message The error message.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [config] The config.
* @param {Object} [request] The request.
* @param {Object} [response] The response.
* @returns {Error} The created error.
*/
function AxiosError(message, code, config, request, response) {
Error.call(this);
this.message = message;
this.name = 'AxiosError';
code && (this.code = code);
config && (this.config = config);
request && (this.request = request);
response && (this.response = response);
}
utils.inherits(AxiosError, Error, {
toJSON: function toJSON() {
return {
// Standard
message: this.message,
name: this.name,
// Microsoft
description: this.description,
number: this.number,
// Mozilla
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
// Axios
config: this.config,
code: this.code,
status: this.response && this.response.status ? this.response.status : null
};
}
});
var prototype = AxiosError.prototype;
var descriptors = {};
[
'ERR_BAD_OPTION_VALUE',
'ERR_BAD_OPTION',
'ECONNABORTED',
'ETIMEDOUT',
'ERR_NETWORK',
'ERR_FR_TOO_MANY_REDIRECTS',
'ERR_DEPRECATED',
'ERR_BAD_RESPONSE',
'ERR_BAD_REQUEST',
'ERR_CANCELED'
// eslint-disable-next-line func-names
].forEach(function(code) {
descriptors[code] = {value: code};
});
Object.defineProperties(AxiosError, descriptors);
Object.defineProperty(prototype, 'isAxiosError', {value: true});
// eslint-disable-next-line func-names
AxiosError.from = function(error, code, config, request, response, customProps) {
var axiosError = Object.create(prototype);
utils.toFlatObject(error, axiosError, function filter(obj) {
return obj !== Error.prototype;
});
AxiosError.call(axiosError, error.message, code, config, request, response);
axiosError.name = error.name;
customProps && Object.assign(axiosError, customProps);
return axiosError;
};
module.exports = AxiosError;
webpack://frontend-mybets/../../node_modules/axios/lib/core/InterceptorManager.js
'use strict';
var utils = require('./../utils');
function InterceptorManager() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
*
* @return {Number} An ID used to remove interceptor later
*/
InterceptorManager.prototype.use = function use(fulfilled, rejected, options) {
this.handlers.push({
fulfilled: fulfilled,
rejected: rejected,
synchronous: options ? options.synchronous : false,
runWhen: options ? options.runWhen : null
});
return this.handlers.length - 1;
};
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*/
InterceptorManager.prototype.eject = function eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
};
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*/
InterceptorManager.prototype.forEach = function forEach(fn) {
utils.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
};
module.exports = InterceptorManager;
webpack://frontend-mybets/../../node_modules/axios/lib/core/buildFullPath.js
'use strict';
var isAbsoluteURL = require('../helpers/isAbsoluteURL');
var combineURLs = require('../helpers/combineURLs');
/**
* Creates a new URL by combining the baseURL with the requestedURL,
* only when the requestedURL is not already an absolute URL.
* If the requestURL is absolute, this function returns the requestedURL untouched.
*
* @param {string} baseURL The base URL
* @param {string} requestedURL Absolute or relative URL to combine
* @returns {string} The combined full path
*/
module.exports = function buildFullPath(baseURL, requestedURL) {
if (baseURL && !isAbsoluteURL(requestedURL)) {
return combineURLs(baseURL, requestedURL);
}
return requestedURL;
};
webpack://frontend-mybets/../../node_modules/axios/lib/core/dispatchRequest.js
'use strict';
var utils = require('./../utils');
var transformData = require('./transformData');
var isCancel = require('../cancel/isCancel');
var defaults = require('../defaults');
var CanceledError = require('../cancel/CanceledError');
/**
* Throws a `CanceledError` if cancellation has been requested.
*/
function throwIfCancellationRequested(config) {
if (config.cancelToken) {
config.cancelToken.throwIfRequested();
}
if (config.signal && config.signal.aborted) {
throw new CanceledError();
}
}
/**
* Dispatch a request to the server using the configured adapter.
*
* @param {object} config The config that is to be used for the request
* @returns {Promise} The Promise to be fulfilled
*/
module.exports = function dispatchRequest(config) {
throwIfCancellationRequested(config);
// Ensure headers exist
config.headers = config.headers || {};
// Transform request data
config.data = transformData.call(
config,
config.data,
config.headers,
config.transformRequest
);
// Flatten headers
config.headers = utils.merge(
config.headers.common || {},
config.headers[config.method] || {},
config.headers
);
utils.forEach(
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
function cleanHeaderConfig(method) {
delete config.headers[method];
}
);
var adapter = config.adapter || defaults.adapter;
return adapter(config).then(function onAdapterResolution(response) {
throwIfCancellationRequested(config);
// Transform response data
response.data = transformData.call(
config,
response.data,
response.headers,
config.transformResponse
);
return response;
}, function onAdapterRejection(reason) {
if (!isCancel(reason)) {
throwIfCancellationRequested(config);
// Transform response data
if (reason && reason.response) {
reason.response.data = transformData.call(
config,
reason.response.data,
reason.response.headers,
config.transformResponse
);
}
}
return Promise.reject(reason);
});
};
webpack://frontend-mybets/../../node_modules/axios/lib/core/mergeConfig.js
'use strict';
var utils = require('../utils');
/**
* Config-specific merge-function which creates a new config-object
* by merging two configuration objects together.
*
* @param {Object} config1
* @param {Object} config2
* @returns {Object} New object resulting from merging config2 to config1
*/
module.exports = function mergeConfig(config1, config2) {
// eslint-disable-next-line no-param-reassign
config2 = config2 || {};
var config = {};
function getMergedValue(target, source) {
if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
return utils.merge(target, source);
} else if (utils.isPlainObject(source)) {
return utils.merge({}, source);
} else if (utils.isArray(source)) {
return source.slice();
}
return source;
}
// eslint-disable-next-line consistent-return
function mergeDeepProperties(prop) {
if (!utils.isUndefined(config2[prop])) {
return getMergedValue(config1[prop], config2[prop]);
} else if (!utils.isUndefined(config1[prop])) {
return getMergedValue(undefined, config1[prop]);
}
}
// eslint-disable-next-line consistent-return
function valueFromConfig2(prop) {
if (!utils.isUndefined(config2[prop])) {
return getMergedValue(undefined, config2[prop]);
}
}
// eslint-disable-next-line consistent-return
function defaultToConfig2(prop) {
if (!utils.isUndefined(config2[prop])) {
return getMergedValue(undefined, config2[prop]);
} else if (!utils.isUndefined(config1[prop])) {
return getMergedValue(undefined, config1[prop]);
}
}
// eslint-disable-next-line consistent-return
function mergeDirectKeys(prop) {
if (prop in config2) {
return getMergedValue(config1[prop], config2[prop]);
} else if (prop in config1) {
return getMergedValue(undefined, config1[prop]);
}
}
var mergeMap = {
'url': valueFromConfig2,
'method': valueFromConfig2,
'data': valueFromConfig2,
'baseURL': defaultToConfig2,
'transformRequest': defaultToConfig2,
'transformResponse': defaultToConfig2,
'paramsSerializer': defaultToConfig2,
'timeout': defaultToConfig2,
'timeoutMessage': defaultToConfig2,
'withCredentials': defaultToConfig2,
'adapter': defaultToConfig2,
'responseType': defaultToConfig2,
'xsrfCookieName': defaultToConfig2,
'xsrfHeaderName': defaultToConfig2,
'onUploadProgress': defaultToConfig2,
'onDownloadProgress': defaultToConfig2,
'decompress': defaultToConfig2,
'maxContentLength': defaultToConfig2,
'maxBodyLength': defaultToConfig2,
'beforeRedirect': defaultToConfig2,
'transport': defaultToConfig2,
'httpAgent': defaultToConfig2,
'httpsAgent': defaultToConfig2,
'cancelToken': defaultToConfig2,
'socketPath': defaultToConfig2,
'responseEncoding': defaultToConfig2,
'validateStatus': mergeDirectKeys
};
utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {
var merge = mergeMap[prop] || mergeDeepProperties;
var configValue = merge(prop);
(utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
});
return config;
};
webpack://frontend-mybets/../../node_modules/axios/lib/core/settle.js
'use strict';
var AxiosError = require('./AxiosError');
/**
* Resolve or reject a Promise based on response status.
*
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*/
module.exports = function settle(resolve, reject, response) {
var validateStatus = response.config.validateStatus;
if (!response.status || !validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(new AxiosError(
'Request failed with status code ' + response.status,
[AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
response.config,
response.request,
response
));
}
};
webpack://frontend-mybets/../../node_modules/axios/lib/core/transformData.js
'use strict';
var utils = require('./../utils');
var defaults = require('../defaults');
/**
* Transform the data for a request or a response
*
* @param {Object|String} data The data to be transformed
* @param {Array} headers The headers for the request or response
* @param {Array|Function} fns A single function or Array of functions
* @returns {*} The resulting transformed data
*/
module.exports = function transformData(data, headers, fns) {
var context = this || defaults;
/*eslint no-param-reassign:0*/
utils.forEach(fns, function transform(fn) {
data = fn.call(context, data, headers);
});
return data;
};
webpack://frontend-mybets/../../node_modules/axios/lib/defaults/index.js
'use strict';
var utils = require('../utils');
var normalizeHeaderName = require('../helpers/normalizeHeaderName');
var AxiosError = require('../core/AxiosError');
var transitionalDefaults = require('./transitional');
var toFormData = require('../helpers/toFormData');
var DEFAULT_CONTENT_TYPE = {
'Content-Type': 'application/x-www-form-urlencoded'
};
function setContentTypeIfUnset(headers, value) {
if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
headers['Content-Type'] = value;
}
}
function getDefaultAdapter() {
var adapter;
if (typeof XMLHttpRequest !== 'undefined') {
// For browsers use XHR adapter
adapter = require('../adapters/xhr');
} else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
// For node use HTTP adapter
adapter = require('../adapters/http');
}
return adapter;
}
function stringifySafely(rawValue, parser, encoder) {
if (utils.isString(rawValue)) {
try {
(parser || JSON.parse)(rawValue);
return utils.trim(rawValue);
} catch (e) {
if (e.name !== 'SyntaxError') {
throw e;
}
}
}
return (encoder || JSON.stringify)(rawValue);
}
var defaults = {
transitional: transitionalDefaults,
adapter: getDefaultAdapter(),
transformRequest: [function transformRequest(data, headers) {
normalizeHeaderName(headers, 'Accept');
normalizeHeaderName(headers, 'Content-Type');
if (utils.isFormData(data) ||
utils.isArrayBuffer(data) ||
utils.isBuffer(data) ||
utils.isStream(data) ||
utils.isFile(data) ||
utils.isBlob(data)
) {
return data;
}
if (utils.isArrayBufferView(data)) {
return data.buffer;
}
if (utils.isURLSearchParams(data)) {
setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
return data.toString();
}
var isObjectPayload = utils.isObject(data);
var contentType = headers && headers['Content-Type'];
var isFileList;
if ((isFileList = utils.isFileList(data)) || (isObjectPayload && contentType === 'multipart/form-data')) {
var _FormData = this.env && this.env.FormData;
return toFormData(isFileList ? {'files[]': data} : data, _FormData && new _FormData());
} else if (isObjectPayload || contentType === 'application/json') {
setContentTypeIfUnset(headers, 'application/json');
return stringifySafely(data);
}
return data;
}],
transformResponse: [function transformResponse(data) {
var transitional = this.transitional || defaults.transitional;
var silentJSONParsing = transitional && transitional.silentJSONParsing;
var forcedJSONParsing = transitional && transitional.forcedJSONParsing;
var strictJSONParsing = !silentJSONParsing && this.responseType === 'json';
if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) {
try {
return JSON.parse(data);
} catch (e) {
if (strictJSONParsing) {
if (e.name === 'SyntaxError') {
throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);
}
throw e;
}
}
}
return data;
}],
/**
* A timeout in milliseconds to abort a request. If set to 0 (default) a
* timeout is not created.
*/
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: {
FormData: require('./env/FormData')
},
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;
},
headers: {
common: {
'Accept': 'application/json, text/plain, */*'
}
}
};
utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
defaults.headers[method] = {};
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
});
module.exports = defaults;
webpack://frontend-mybets/../../node_modules/axios/lib/defaults/transitional.js
'use strict';
module.exports = {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
};
webpack://frontend-mybets/../../node_modules/axios/lib/env/data.js
module.exports = {
"version": "0.27.2"
};
webpack://frontend-mybets/../../node_modules/axios/lib/helpers/bind.js
'use strict';
module.exports = function bind(fn, thisArg) {
return function wrap() {
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
return fn.apply(thisArg, args);
};
};
webpack://frontend-mybets/../../node_modules/axios/lib/helpers/buildURL.js
'use strict';
var utils = require('./../utils');
function encode(val) {
return encodeURIComponent(val).
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, '+').
replace(/%5B/gi, '[').
replace(/%5D/gi, ']');
}
/**
* Build a URL by appending params to the end
*
* @param {string} url The base of the url (e.g., http://www.google.com)
* @param {object} [params] The params to be appended
* @returns {string} The formatted url
*/
module.exports = function buildURL(url, params, paramsSerializer) {
/*eslint no-param-reassign:0*/
if (!params) {
return url;
}
var serializedParams;
if (paramsSerializer) {
serializedParams = paramsSerializer(params);
} else if (utils.isURLSearchParams(params)) {
serializedParams = params.toString();
} else {
var parts = [];
utils.forEach(params, function serialize(val, key) {
if (val === null || typeof val === 'undefined') {
return;
}
if (utils.isArray(val)) {
key = key + '[]';
} else {
val = [val];
}
utils.forEach(val, function parseValue(v) {
if (utils.isDate(v)) {
v = v.toISOString();
} else if (utils.isObject(v)) {
v = JSON.stringify(v);
}
parts.push(encode(key) + '=' + encode(v));
});
});
serializedParams = parts.join('&');
}
if (serializedParams) {
var hashmarkIndex = url.indexOf('#');
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex);
}
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
}
return url;
};
webpack://frontend-mybets/../../node_modules/axios/lib/helpers/combineURLs.js
'use strict';
/**
* Creates a new URL by combining the specified URLs
*
* @param {string} baseURL The base URL
* @param {string} relativeURL The relative URL
* @returns {string} The combined URL
*/
module.exports = function combineURLs(baseURL, relativeURL) {
return relativeURL
? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
: baseURL;
};
webpack://frontend-mybets/../../node_modules/axios/lib/helpers/cookies.js
'use strict';
var utils = require('./../utils');
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs support document.cookie
(function standardBrowserEnv() {
return {
write: function write(name, value, expires, path, domain, secure) {
var cookie = [];
cookie.push(name + '=' + encodeURIComponent(value));
if (utils.isNumber(expires)) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
if (utils.isString(path)) {
cookie.push('path=' + path);
}
if (utils.isString(domain)) {
cookie.push('domain=' + domain);
}
if (secure === true) {
cookie.push('secure');
}
document.cookie = cookie.join('; ');
},
read: function read(name) {
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove: function remove(name) {
this.write(name, '', Date.now() - 86400000);
}
};
})() :
// Non standard browser env (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return {
write: function write() {},
read: function read() { return null; },
remove: function remove() {}
};
})()
);
webpack://frontend-mybets/../../node_modules/axios/lib/helpers/isAbsoluteURL.js
'use strict';
/**
* Determines whether the specified URL is absolute
*
* @param {string} url The URL to test
* @returns {boolean} True if the specified URL is absolute, otherwise false
*/
module.exports = function isAbsoluteURL(url) {
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
};
webpack://frontend-mybets/../../node_modules/axios/lib/helpers/isAxiosError.js
'use strict';
var utils = require('./../utils');
/**
* Determines whether the payload is an error thrown by Axios
*
* @param {*} payload The value to test
* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
*/
module.exports = function isAxiosError(payload) {
return utils.isObject(payload) && (payload.isAxiosError === true);
};
webpack://frontend-mybets/../../node_modules/axios/lib/helpers/isURLSameOrigin.js
'use strict';
var utils = require('./../utils');
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs have full support of the APIs needed to test
// whether the request URL is of the same origin as current location.
(function standardBrowserEnv() {
var msie = /(msie|trident)/i.test(navigator.userAgent);
var urlParsingNode = document.createElement('a');
var originURL;
/**
* Parse a URL to discover it's components
*
* @param {String} url The URL to be parsed
* @returns {Object}
*/
function resolveURL(url) {
var href = url;
if (msie) {
// IE needs attribute set twice to normalize properties
urlParsingNode.setAttribute('href', href);
href = urlParsingNode.href;
}
urlParsingNode.setAttribute('href', href);
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
host: urlParsingNode.host,
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
hostname: urlParsingNode.hostname,
port: urlParsingNode.port,
pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
urlParsingNode.pathname :
'/' + urlParsingNode.pathname
};
}
originURL = resolveURL(window.location.href);
/**
* Determine if a URL shares the same origin as the current location
*
* @param {String} requestURL The URL to test
* @returns {boolean} True if URL shares the same origin, otherwise false
*/
return function isURLSameOrigin(requestURL) {
var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
return (parsed.protocol === originURL.protocol &&
parsed.host === originURL.host);
};
})() :
// Non standard browser envs (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return function isURLSameOrigin() {
return true;
};
})()
);
webpack://frontend-mybets/../../node_modules/axios/lib/helpers/normalizeHeaderName.js
'use strict';
var utils = require('../utils');
module.exports = function normalizeHeaderName(headers, normalizedName) {
utils.forEach(headers, function processHeader(value, name) {
if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
headers[normalizedName] = value;
delete headers[name];
}
});
};
webpack://frontend-mybets/../../node_modules/axios/lib/helpers/null.js
// eslint-disable-next-line strict module.exports = null;
webpack://frontend-mybets/../../node_modules/axios/lib/helpers/parseHeaders.js
'use strict';
var utils = require('./../utils');
// Headers whose duplicates are ignored by node
// c.f. https://nodejs.org/api/http.html#http_message_headers
var ignoreDuplicateOf = [
'age', 'authorization', 'content-length', 'content-type', 'etag',
'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
'last-modified', 'location', 'max-forwards', 'proxy-authorization',
'referer', 'retry-after', 'user-agent'
];
/**
* Parse headers into an object
*
* ```
* Date: Wed, 27 Aug 2014 08:58:49 GMT
* Content-Type: application/json
* Connection: keep-alive
* Transfer-Encoding: chunked
* ```
*
* @param {String} headers Headers needing to be parsed
* @returns {Object} Headers parsed into an object
*/
module.exports = function parseHeaders(headers) {
var parsed = {};
var key;
var val;
var i;
if (!headers) { return parsed; }
utils.forEach(headers.split('\n'), function parser(line) {
i = line.indexOf(':');
key = utils.trim(line.substr(0, i)).toLowerCase();
val = utils.trim(line.substr(i + 1));
if (key) {
if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
return;
}
if (key === 'set-cookie') {
parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
} else {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
}
});
return parsed;
};
webpack://frontend-mybets/../../node_modules/axios/lib/helpers/parseProtocol.js
'use strict';
module.exports = function parseProtocol(url) {
var match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
return match && match[1] || '';
};
webpack://frontend-mybets/../../node_modules/axios/lib/helpers/spread.js
'use strict';
/**
* Syntactic sugar for invoking a function and expanding an array for arguments.
*
* Common use case would be to use `Function.prototype.apply`.
*
* ```js
* function f(x, y, z) {}
* var args = [1, 2, 3];
* f.apply(null, args);
* ```
*
* With `spread` this example can be re-written.
*
* ```js
* spread(function(x, y, z) {})([1, 2, 3]);
* ```
*
* @param {Function} callback
* @returns {Function}
*/
module.exports = function spread(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
};
webpack://frontend-mybets/../../node_modules/axios/lib/helpers/toFormData.js
'use strict';
var utils = require('../utils');
/**
* Convert a data object to FormData
* @param {Object} obj
* @param {?Object} [formData]
* @returns {Object}
**/
function toFormData(obj, formData) {
// eslint-disable-next-line no-param-reassign
formData = formData || new FormData();
var stack = [];
function convertValue(value) {
if (value === null) return '';
if (utils.isDate(value)) {
return value.toISOString();
}
if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {
return typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
}
return value;
}
function build(data, parentKey) {
if (utils.isPlainObject(data) || utils.isArray(data)) {
if (stack.indexOf(data) !== -1) {
throw Error('Circular reference detected in ' + parentKey);
}
stack.push(data);
utils.forEach(data, function each(value, key) {
if (utils.isUndefined(value)) return;
var fullKey = parentKey ? parentKey + '.' + key : key;
var arr;
if (value && !parentKey && typeof value === 'object') {
if (utils.endsWith(key, '{}')) {
// eslint-disable-next-line no-param-reassign
value = JSON.stringify(value);
} else if (utils.endsWith(key, '[]') && (arr = utils.toArray(value))) {
// eslint-disable-next-line func-names
arr.forEach(function(el) {
!utils.isUndefined(el) && formData.append(fullKey, convertValue(el));
});
return;
}
}
build(value, fullKey);
});
stack.pop();
} else {
formData.append(parentKey, convertValue(data));
}
}
build(obj);
return formData;
}
module.exports = toFormData;
webpack://frontend-mybets/../../node_modules/axios/lib/helpers/validator.js
'use strict';
var VERSION = require('../env/data').version;
var AxiosError = require('../core/AxiosError');
var validators = {};
// eslint-disable-next-line func-names
['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) {
validators[type] = function validator(thing) {
return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
};
});
var deprecatedWarnings = {};
/**
* Transitional option validator
* @param {function|boolean?} validator - set to false if the transitional option has been removed
* @param {string?} version - deprecated version / removed since version
* @param {string?} message - some message with additional info
* @returns {function}
*/
validators.transitional = function transitional(validator, version, message) {
function formatMessage(opt, desc) {
return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
}
// eslint-disable-next-line func-names
return function(value, opt, opts) {
if (validator === false) {
throw new AxiosError(
formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
AxiosError.ERR_DEPRECATED
);
}
if (version && !deprecatedWarnings[opt]) {
deprecatedWarnings[opt] = true;
// eslint-disable-next-line no-console
console.warn(
formatMessage(
opt,
' has been deprecated since v' + version + ' and will be removed in the near future'
)
);
}
return validator ? validator(value, opt, opts) : true;
};
};
/**
* Assert object's properties type
* @param {object} options
* @param {object} schema
* @param {boolean?} allowUnknown
*/
function assertOptions(options, schema, allowUnknown) {
if (typeof options !== 'object') {
throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
}
var keys = Object.keys(options);
var i = keys.length;
while (i-- > 0) {
var opt = keys[i];
var validator = schema[opt];
if (validator) {
var value = options[opt];
var result = value === undefined || validator(value, opt, options);
if (result !== true) {
throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);
}
continue;
}
if (allowUnknown !== true) {
throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);
}
}
}
module.exports = {
assertOptions: assertOptions,
validators: validators
};
webpack://frontend-mybets/../../node_modules/axios/lib/utils.js
'use strict';
var bind = require('./helpers/bind');
// utils is a library of generic helper functions non-specific to axios
var toString = Object.prototype.toString;
// eslint-disable-next-line func-names
var kindOf = (function(cache) {
// eslint-disable-next-line func-names
return function(thing) {
var str = toString.call(thing);
return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
};
})(Object.create(null));
function kindOfTest(type) {
type = type.toLowerCase();
return function isKindOf(thing) {
return kindOf(thing) === type;
};
}
/**
* Determine if a value is an Array
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Array, otherwise false
*/
function isArray(val) {
return Array.isArray(val);
}
/**
* Determine if a value is undefined
*
* @param {Object} val The value to test
* @returns {boolean} True if the value is undefined, otherwise false
*/
function isUndefined(val) {
return typeof val === 'undefined';
}
/**
* Determine if a value is a Buffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Buffer, otherwise false
*/
function isBuffer(val) {
return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
&& typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
}
/**
* Determine if a value is an ArrayBuffer
*
* @function
* @param {Object} val The value to test
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
*/
var isArrayBuffer = kindOfTest('ArrayBuffer');
/**
* Determine if a value is a view on an ArrayBuffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
*/
function isArrayBufferView(val) {
var result;
if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
result = ArrayBuffer.isView(val);
} else {
result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
}
return result;
}
/**
* Determine if a value is a String
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a String, otherwise false
*/
function isString(val) {
return typeof val === 'string';
}
/**
* Determine if a value is a Number
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Number, otherwise false
*/
function isNumber(val) {
return typeof val === 'number';
}
/**
* Determine if a value is an Object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Object, otherwise false
*/
function isObject(val) {
return val !== null && typeof val === 'object';
}
/**
* Determine if a value is a plain Object
*
* @param {Object} val The value to test
* @return {boolean} True if value is a plain Object, otherwise false
*/
function isPlainObject(val) {
if (kindOf(val) !== 'object') {
return false;
}
var prototype = Object.getPrototypeOf(val);
return prototype === null || prototype === Object.prototype;
}
/**
* Determine if a value is a Date
*
* @function
* @param {Object} val The value to test
* @returns {boolean} True if value is a Date, otherwise false
*/
var isDate = kindOfTest('Date');
/**
* Determine if a value is a File
*
* @function
* @param {Object} val The value to test
* @returns {boolean} True if value is a File, otherwise false
*/
var isFile = kindOfTest('File');
/**
* Determine if a value is a Blob
*
* @function
* @param {Object} val The value to test
* @returns {boolean} True if value is a Blob, otherwise false
*/
var isBlob = kindOfTest('Blob');
/**
* Determine if a value is a FileList
*
* @function
* @param {Object} val The value to test
* @returns {boolean} True if value is a File, otherwise false
*/
var isFileList = kindOfTest('FileList');
/**
* Determine if a value is a Function
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Function, otherwise false
*/
function isFunction(val) {
return toString.call(val) === '[object Function]';
}
/**
* Determine if a value is a Stream
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Stream, otherwise false
*/
function isStream(val) {
return isObject(val) && isFunction(val.pipe);
}
/**
* Determine if a value is a FormData
*
* @param {Object} thing The value to test
* @returns {boolean} True if value is an FormData, otherwise false
*/
function isFormData(thing) {
var pattern = '[object FormData]';
return thing && (
(typeof FormData === 'function' && thing instanceof FormData) ||
toString.call(thing) === pattern ||
(isFunction(thing.toString) && thing.toString() === pattern)
);
}
/**
* Determine if a value is a URLSearchParams object
* @function
* @param {Object} val The value to test
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
*/
var isURLSearchParams = kindOfTest('URLSearchParams');
/**
* Trim excess whitespace off the beginning and end of a string
*
* @param {String} str The String to trim
* @returns {String} The String freed of excess whitespace
*/
function trim(str) {
return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
}
/**
* Determine if we're running in a standard browser environment
*
* This allows axios to run in a web worker, and react-native.
* Both environments support XMLHttpRequest, but not fully standard globals.
*
* web workers:
* typeof window -> undefined
* typeof document -> undefined
*
* react-native:
* navigator.product -> 'ReactNative'
* nativescript
* navigator.product -> 'NativeScript' or 'NS'
*/
function isStandardBrowserEnv() {
if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
navigator.product === 'NativeScript' ||
navigator.product === 'NS')) {
return false;
}
return (
typeof window !== 'undefined' &&
typeof document !== 'undefined'
);
}
/**
* Iterate over an Array or an Object invoking a function for each item.
*
* If `obj` is an Array callback will be called passing
* the value, index, and complete array for each item.
*
* If 'obj' is an Object callback will be called passing
* the value, key, and complete object for each property.
*
* @param {Object|Array} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*/
function forEach(obj, fn) {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
// Force an array if not already something iterable
if (typeof obj !== 'object') {
/*eslint no-param-reassign:0*/
obj = [obj];
}
if (isArray(obj)) {
// Iterate over array values
for (var i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
// Iterate over object keys
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
fn.call(null, obj[key], key, obj);
}
}
}
}
/**
* Accepts varargs expecting each argument to be an object, then
* immutably merges the properties of each object and returns result.
*
* When multiple objects contain the same key the later object in
* the arguments list will take precedence.
*
* Example:
*
* ```js
* var result = merge({foo: 123}, {foo: 456});
* console.log(result.foo); // outputs 456
* ```
*
* @param {Object} obj1 Object to merge
* @returns {Object} Result of all merge properties
*/
function merge(/* obj1, obj2, obj3, ... */) {
var result = {};
function assignValue(val, key) {
if (isPlainObject(result[key]) && isPlainObject(val)) {
result[key] = merge(result[key], val);
} else if (isPlainObject(val)) {
result[key] = merge({}, val);
} else if (isArray(val)) {
result[key] = val.slice();
} else {
result[key] = val;
}
}
for (var i = 0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
}
return result;
}
/**
* Extends object a by mutably adding to it the properties of object b.
*
* @param {Object} a The object to be extended
* @param {Object} b The object to copy properties from
* @param {Object} thisArg The object to bind function to
* @return {Object} The resulting value of object a
*/
function extend(a, b, thisArg) {
forEach(b, function assignValue(val, key) {
if (thisArg && typeof val === 'function') {
a[key] = bind(val, thisArg);
} else {
a[key] = val;
}
});
return a;
}
/**
* Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
*
* @param {string} content with BOM
* @return {string} content value without BOM
*/
function stripBOM(content) {
if (content.charCodeAt(0) === 0xFEFF) {
content = content.slice(1);
}
return content;
}
/**
* Inherit the prototype methods from one constructor into another
* @param {function} constructor
* @param {function} superConstructor
* @param {object} [props]
* @param {object} [descriptors]
*/
function inherits(constructor, superConstructor, props, descriptors) {
constructor.prototype = Object.create(superConstructor.prototype, descriptors);
constructor.prototype.constructor = constructor;
props && Object.assign(constructor.prototype, props);
}
/**
* Resolve object with deep prototype chain to a flat object
* @param {Object} sourceObj source object
* @param {Object} [destObj]
* @param {Function} [filter]
* @returns {Object}
*/
function toFlatObject(sourceObj, destObj, filter) {
var props;
var i;
var prop;
var merged = {};
destObj = destObj || {};
do {
props = Object.getOwnPropertyNames(sourceObj);
i = props.length;
while (i-- > 0) {
prop = props[i];
if (!merged[prop]) {
destObj[prop] = sourceObj[prop];
merged[prop] = true;
}
}
sourceObj = Object.getPrototypeOf(sourceObj);
} while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
return destObj;
}
/*
* determines whether a string ends with the characters of a specified string
* @param {String} str
* @param {String} searchString
* @param {Number} [position= 0]
* @returns {boolean}
*/
function endsWith(str, searchString, position) {
str = String(str);
if (position === undefined || position > str.length) {
position = str.length;
}
position -= searchString.length;
var lastIndex = str.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
}
/**
* Returns new array from array like object
* @param {*} [thing]
* @returns {Array}
*/
function toArray(thing) {
if (!thing) return null;
var i = thing.length;
if (isUndefined(i)) return null;
var arr = new Array(i);
while (i-- > 0) {
arr[i] = thing[i];
}
return arr;
}
// eslint-disable-next-line func-names
var isTypedArray = (function(TypedArray) {
// eslint-disable-next-line func-names
return function(thing) {
return TypedArray && thing instanceof TypedArray;
};
})(typeof Uint8Array !== 'undefined' && Object.getPrototypeOf(Uint8Array));
module.exports = {
isArray: isArray,
isArrayBuffer: isArrayBuffer,
isBuffer: isBuffer,
isFormData: isFormData,
isArrayBufferView: isArrayBufferView,
isString: isString,
isNumber: isNumber,
isObject: isObject,
isPlainObject: isPlainObject,
isUndefined: isUndefined,
isDate: isDate,
isFile: isFile,
isBlob: isBlob,
isFunction: isFunction,
isStream: isStream,
isURLSearchParams: isURLSearchParams,
isStandardBrowserEnv: isStandardBrowserEnv,
forEach: forEach,
merge: merge,
extend: extend,
trim: trim,
stripBOM: stripBOM,
inherits: inherits,
toFlatObject: toFlatObject,
kindOf: kindOf,
kindOfTest: kindOfTest,
endsWith: endsWith,
toArray: toArray,
isTypedArray: isTypedArray,
isFileList: isFileList
};
webpack://frontend-mybets/../../packages/sh-lib-geolocation/src/redux/actions.ts
import {
GeolocationStatus,
GeolocationRejectedErrorMessage,
GeolocationRetryStatus,
GeolocationRetryState
} from "../types";
import {
GeoLocationMessageShownAction,
GeoLocationStatusAction,
GeoLocationStatusClearAction,
GeoLocationErrorAction,
GeoLocationRetryStatusAction,
TryGeoLocationRetryAction,
GeoLocationRetryClearAction,
GeoComplyErrorModalAction,
OpenLocationServicesErrorAction,
CloseLocationServicesErrorAction
} from "./types";
export const geolocationMessageShown = (
isMessageShown: boolean
): GeoLocationMessageShownAction => ({
type: "GEOLOCATION_MESSAGE_SHOWN",
payload: {
geolocationMessageShown: isMessageShown
}
});
export const setGeolocationStatus = (
status: GeolocationStatus
): GeoLocationStatusAction => ({
type: "GEOLOCATION_STATUS",
payload: {
geolocationStatus: status
}
});
export const setGeolocationError = (
errorType: string,
errorData: GeolocationRejectedErrorMessage[] | string,
isErrorRetryable: boolean
): GeoLocationErrorAction => ({
type: "GEOLOCATION_ERROR",
payload: {
geolocationError: {
[errorType]:
typeof errorData === "string" ? [{ message: errorData }] : errorData
},
isErrorRetryable
}
});
export const geolocationStatusClear = (): GeoLocationStatusClearAction => ({
type: "GEOLOCATION_STATUS_CLEAR"
});
export const setGeolocationRetryStatus = (
retryStatus: GeolocationRetryStatus
): GeoLocationRetryStatusAction => ({
type: "SET_GEOLOCATION_RETRY_STATUS",
payload: retryStatus
});
export const tryGeolocationRetry = (
status: boolean
): TryGeoLocationRetryAction => ({
type: "TRY_GEOLOCATION_RETRY",
payload: status
? GeolocationRetryState.REQUESTED
: GeolocationRetryState.RETRYING
});
export const geolocationRetryClear = (): GeoLocationRetryClearAction => ({
type: "GEOLOCATION_RETRY_CLEAR"
});
export const geoComplyErrorModal = (): GeoComplyErrorModalAction => ({
type: "GEOCOMPLY_ERROR_MODAL"
});
export const openLocationServicesErrorModal =
(): OpenLocationServicesErrorAction => ({
type: "OPEN_LOCATION_SERVICES_ERROR_MODAL"
});
export const closeLocationServicesErrorModal =
(): CloseLocationServicesErrorAction => ({
type: "CLOSE_LOCATION_SERVICES_ERROR_MODAL"
});
webpack://frontend-mybets/../../packages/sh-lib-geolocation/src/redux/selectors.ts
import { get } from "lodash";
import { Store } from "redux";
import {
GeolocationRetryState,
GeolocationRetryStatus,
GeolocationStatus,
GeolocationError
} from "../types";
export const getGeolocationStatus = (
store: Store
): GeolocationStatus | undefined => get(store, "geolocation.geolocationStatus");
export const getGeolocationError = (store: Store): GeolocationError =>
get(store, "geolocation.geolocationError", {});
export const getGeolocationErrorRetryable = (
store: Store
): boolean | undefined => get(store, "geolocation.isErrorRetryable", true);
export const getGeolocationMessageShown = (store: Store): boolean =>
get(store, "geolocation.geolocationMessageShown", false);
export const getGeoComplyRetryStatus = (store: Store): GeolocationRetryStatus =>
get(
store,
"geolocation.geolocationRetryStatus.state",
GeolocationRetryState.IDLE
);
export const getGeoComplyRetryState = (store: Store): GeolocationRetryState =>
get(
store,
"geolocation.geolocationRetryStatus.state",
GeolocationRetryState.IDLE
);
export const getGeoComplyRetryAttempts = (store: Store): number =>
get(store, "geolocation.geolocationRetryStatus.attempts", 0);
export const getGeoComplyErrorOpen = (store: Store): boolean =>
get(store, "geolocation.geoComplyErrorOpen", false);
export const getLocationServicesErrorModalIsOpen = (store: Store): boolean =>
get(store, "geolocation.locationServicesErrorModalOpen", false);
export const isShowingStateSelector = (store: Store): boolean =>
get(store, "geolocation.showStateSelector", false);
webpack://frontend-mybets/../../packages/sh-lib-geolocation/src/solus/types/solus.ts
import { BinaryFn, NullaryFn, UnaryFn } from "@tvg/ts-types/Functional";
import type { Troubleshooter } from "@fdr/types/ts/GeoLocation";
import { GeoClientErrorCodes, GeoClientErrorMessages } from "./gcHtml5";
// @ts-ignore -> Added this type because FDR doesnt exist anymore
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type GeoLocationResponseRejected = any;
// @ts-ignore -> Added this type because FDR doesnt exist anymore
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type GeoLocationResponseSuccess = any;
export interface GeolocationSession {
userId: string;
sessionId: string;
userAuthToken?: string;
}
export interface GeoPacket {
geopacket: string;
state: string;
product: string;
}
export type GeolocationCallbackSuccess = BinaryFn<
GeoLocationResponseSuccess,
string,
void
>;
export type GeolocationCallbackFailure = UnaryFn<
GeolocationFailureResponse,
void
>;
export interface GeolocationFailureResponse {
code: GeoClientErrorCodes;
message: GeoClientErrorMessages;
}
export type GeolocationRejectionCallback = BinaryFn<
GeoLocationResponseRejected,
string,
void
>;
export interface GeolocationCallbacks {
onSuccess: GeolocationCallbackSuccess;
onFailed: GeolocationCallbackFailure;
onReject: GeolocationRejectionCallback;
onProcess: (isProcessing?: boolean) => void;
onRetry: (attemptsCounter?: number) => void;
onRefresh: GeolocationCallbackSuccess;
}
export enum GeolocationReason {
LOGIN = "Login",
PERIODIC = "PERIODIC"
}
export interface GeolocationRejection {
message: string;
troubleshooter: Array<Troubleshooter>;
state?: string;
}
export enum GeoLocationLicenseType {
SOLUS = "SOLUS",
GEOLOCATION = "GEO"
}
export interface GeoLocationConfig {
state: string;
product: "RACING";
licenseType: GeoLocationLicenseType;
}
export enum GeoStorageKey {
LICENSE = "X-Geo-License",
GEO_PACKET = "X-Geo-Packet",
RELOCATE_ID = "GEO_RELOCATE_PROCESS_ID"
}
export enum GeoClientFields {
SESSION_ID = "session_id",
PREVIOUS_TOKEN_STATUS = "previousTokenStatus"
}
export enum GeoClientTokenStatus {
NO_TOKEN = "NO_TOKEN",
SUCCESSFUL_TOKEN = "successful_token",
FAILED_TOKEN = "failed_token"
}
export enum GeolocationCustomErrorCodes {
USER_UNAUTHORIZED = 1401,
INVALID_LICENSE = 1606,
UNAUTHORIZED_LOCATION_PERMISSION = 1801
}
export enum GeolocationCustomErrorMessages {
USER_UNAUTHORIZED = "User Unauthorized",
INVALID_LICENSE = "Error trying to get license",
UNAUTHORIZED_LOCATION_PERMISSION = "Browser location unauthorized"
}
export interface GeoComplyCache {
saveCache: UnaryFn<string, void>;
removeCache: NullaryFn<void>;
getCache: NullaryFn<string>;
}
export type GeoComplyCacheEntries = Record<GeoStorageKey, GeoComplyCache>;
export type GeolocationRelocateUserCallback = UnaryFn<
GeoClientTokenStatus,
void
>;
webpack://frontend-mybets/../../packages/sh-lib-geolocation/src/types.ts
export enum GeolocationStatus {
PROGRESS = "LOCATION_IN_PROGRESS",
FAILURE = "LOCATION_FAILURE",
PASSED = "GEOLOCATION_PASSED",
REJECTED = "GEOLOCATION_REJECTED"
}
export interface GeolocationRejectedErrorMessage {
retry: boolean;
title: string;
message: string;
rule: string;
}
export interface GeolocationRejectedError {
message: string;
region: string;
troubleshooters: GeolocationRejectedErrorMessage[];
}
export interface GeolocationFailureError {
geoErrorName: string;
geoErrorCode: number;
}
export interface GeolocationData {
geoToken?: string;
ipAddress: string;
}
export interface GeolocationFailureErrorName {
message: string;
}
export enum GeolocationRetryState {
IDLE = "idle",
REQUESTED = "requested",
RETRYING = "retrying"
}
export interface GeolocationRetryStatus {
state: GeolocationRetryState;
attempts: number;
}
export type GeolocationError = Record<
string,
Array<GeolocationRejectedErrorMessage | GeolocationFailureErrorName>
>;
export type GeolocationRejectedErrorModalTitle = Record<string, string>;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/redux/actions.ts
import { RaceInfoMyBets } from "@tvg/ts-types/Race";
import {
ActiveTabEnum,
SettledTabEnum,
ActiveBetsInfoType,
OnBetCancelPayload,
OnRacePageBetCancelPayload,
OnBetCancelClosePayload,
StatusFilters,
MyBetsDynamicFilters,
OnBetSocialSharePayload,
MyBetsPastPerformanceTab
} from "../utils/types";
type ModalOpen = {
type: "OPEN_MYBETS_STANDALONE";
};
type ModalClose = {
type: "CLOSE_MYBETS_STANDALONE";
};
type SetActiveBetsAction = {
type: "SET_ACTIVE_BETS_MYBETS_STANDALONE";
payload: ActiveBetsInfoType;
};
type SetActiveBetsActionLegacy = {
type: "MYBETS_GET_ACTIVE_BETS";
payload: ActiveBetsInfoType;
};
type SetSelectedTab = {
type: "SET_SELECTED_TAB_MYBETS_STANDALONE";
payload: ActiveTabEnum;
};
type SetSelectedSettledTab = {
type: "SET_SELECTED_SETTLED_TAB_MYBETS_STANDALONE";
payload: SettledTabEnum;
};
type SetCounter = {
type: "SET_COUNTER_MYBETS_STANDALONE";
payload: number;
};
type SetSettledCounter = {
type: "SET_SETTLED_COUNTER_MYBETS_STANDALONE";
payload: number;
};
type SetFutureCounter = {
type: "SET_FUTURE_COUNTER_MYBETS_STANDALONE";
payload: number;
};
type SetActiveWageredAmount = {
type: "SET_ACTIVE_WAGERED_AMOUNT_MYBETS_STANDALONE";
payload: number;
};
type SetSettledWageredAmount = {
type: "SET_SETTLED_WAGERED_AMOUNT_MYBETS_STANDALONE";
payload: number;
};
type SetFutureWageredAmount = {
type: "SET_FUTURE_WAGERED_AMOUNT_MYBETS_STANDALONE";
payload: number;
};
export type BetCancelOpenModalAction = {
type: "OPEN_BET_CANCEL_MODAL";
payload?: OnBetCancelPayload | OnRacePageBetCancelPayload;
};
export type SocialShareOpenModalAction = {
type: "OPEN_BET_SOCIAL_SHARE_MODAL";
payload: OnBetSocialSharePayload;
};
export type SocialShareCloseModalAction = {
type: "CLOSE_BET_SOCIAL_SHARE_MODAL";
};
export type BetCancelUpdateModalAction = {
type: "MY_BETS_UPDATING_RACES";
payload: RaceInfoMyBets[];
};
export type BetCancelCloseModalAction = {
type: "CLOSE_BET_CANCEL_MODAL";
payload?: OnBetCancelClosePayload;
};
export type BetCancelLoadingModalActionOn = {
type: "LOADING_BET_CANCEL_MODAL_ON";
};
export type BetCancelLoadingModalActionOff = {
type: "LOADING_BET_CANCEL_MODAL_OFF";
};
export type BetCancelLoadingModalActionError = {
type: "LOADING_BET_CANCEL_MODAL_ERROR";
payload: string;
};
export type CleanBetCancelResultAction = {
type: "CLEAN_BET_CANCEL_RESULT";
};
export type OpenApproxPayoutModalAction = {
type: "OPEN_APPROX_PAYOUT_MODAL";
};
export type CloseApproxPayoutModalAction = {
type: "CLOSE_APPROX_PAYOUT_MODAL";
};
export type CloseWagerCancellationRulesModalAction = {
type: "CLOSE_WAGER_CANCELLATION_RULES_MODAL";
};
export type OpenWagerCancellationRulesModalAction = {
type: "OPEN_WAGER_CANCELLATION_RULES_MODAL";
payload: { hasBack: boolean };
};
type SetLoadMoreWagerGroups = {
type: "SET_LOAD_MORE_WAGER_GROUPS";
payload: boolean;
};
export type OpenTrackRulesModalAction = {
type: "OPEN_TRACK_RULES_MODAL";
payload: { betType: string; alternates?: boolean };
};
export type CloseTrackRulesModalAction = {
type: "CLOSE_TRACK_RULES_MODAL";
};
export type SelectedRace = {
trackCode: string;
raceNumber: number;
raceDate: string;
};
export type OpenMyBetsPastPerformance = {
type: "OPEN_MYBETS_PAST_PERFORMANCE";
payload: {
selectedRace: SelectedRace;
modalTitle: string;
selectedTab?: MyBetsPastPerformanceTab;
hasBack: boolean;
};
};
export type CloseMyBetsPastPerfomance = {
type: "CLOSE_MYBETS_PAST_PERFORMANCE";
};
export type IsLoadingAction = {
type: "IS_LOADING_MYBETS";
payload: {
isLoading: boolean;
};
};
export type SelectStatusFiltersAction = {
type: "SELECT_MYBETS_STATUS_FILTERS";
payload: {
statusFilter: StatusFilters;
};
};
export type ClearStatusFiltersAction = {
type: "CLEAR_MYBETS_STATUS_FILTERS";
};
export type SetStatusFilterCount = {
type: "SET_MYBETS_STATUS_FILTER_COUNT";
payload: {
count: number;
};
};
export type SelectTrackFiltersAction = {
type: "SELECT_MYBETS_TRACKS_FILTERS";
payload: {
trackFilter: MyBetsDynamicFilters;
};
};
export type ClearTrackFiltersAction = {
type: "CLEAR_MYBETS_TRACKS_FILTERS";
};
export type SetTrackFilterCount = {
type: "SET_MYBETS_TRACKS_FILTER_COUNT";
payload: {
count: number;
};
};
export type SetBetTypeFiltersAction = {
type: "SET_MYBETS_BET_TYPE_FILTERS";
payload: {
betTypeFilter: MyBetsDynamicFilters;
};
};
export type SetBetTypeFilterCount = {
type: "SET_MYBETS_BET_TYPE_FILTER_COUNT";
payload: {
count: number;
};
};
export type SetCustomEndDate = {
type: "SET_MYBETS_CUSTOM_END_DATE";
payload: {
date: Date | null;
};
};
export type SetCustomStartDate = {
type: "SET_MYBETS_CUSTOM_START_DATE";
payload: {
date: Date | null;
};
};
export type SetIsCustomTimeFrame = {
type: "SET_MYBETS_IS_CUSTOM_TIMEFRAME";
payload: {
isCustomTimeFrame: boolean;
};
};
export type SetIsDefaultSettled = {
type: "SET_SHOULD_DEFAULT_TO_SETTLED";
payload: {
isDefaultSettled: boolean;
};
};
export type SetIsDefaultFuture = {
type: "SET_SHOULD_DEFAULT_TO_FUTURE";
payload: {
isDefaultFuture: boolean;
};
};
export type SetRacesActiveBetsStandalone = {
type: "SET_RACES_ACTIVE_BETS_STANDALONE";
payload: Record<number, number>;
};
export type Actions =
| ModalOpen
| ModalClose
| SetActiveBetsAction
| SetSelectedTab
| SetSelectedSettledTab
| SetCounter
| SetSettledCounter
| SetFutureCounter
| BetCancelCloseModalAction
| BetCancelOpenModalAction
| BetCancelLoadingModalActionOn
| BetCancelLoadingModalActionOff
| BetCancelLoadingModalActionError
| CleanBetCancelResultAction
| OpenApproxPayoutModalAction
| CloseApproxPayoutModalAction
| OpenWagerCancellationRulesModalAction
| SetLoadMoreWagerGroups
| CloseWagerCancellationRulesModalAction
| OpenTrackRulesModalAction
| CloseTrackRulesModalAction
| OpenMyBetsPastPerformance
| CloseMyBetsPastPerfomance
| IsLoadingAction
| BetCancelUpdateModalAction
| SetActiveWageredAmount
| SetSettledWageredAmount
| SetFutureWageredAmount
| SelectStatusFiltersAction
| ClearStatusFiltersAction
| SetStatusFilterCount
| SelectTrackFiltersAction
| ClearTrackFiltersAction
| SetTrackFilterCount
| SetBetTypeFiltersAction
| SetBetTypeFilterCount
| SetCustomStartDate
| SetCustomEndDate
| SetIsCustomTimeFrame
| SetIsDefaultSettled
| SetIsDefaultFuture
| SocialShareOpenModalAction
| SocialShareCloseModalAction
| SetRacesActiveBetsStandalone;
export const openMyBetsStandalone = (): ModalOpen => ({
type: "OPEN_MYBETS_STANDALONE"
});
export const closeMyBetsStandalone = (): ModalClose => ({
type: "CLOSE_MYBETS_STANDALONE"
});
export const setRacesActiveBetsStandalone = (
payload: Record<number, number>
): SetRacesActiveBetsStandalone => ({
type: "SET_RACES_ACTIVE_BETS_STANDALONE",
payload
});
export const setActiveBetsInfoMyBetsStandalone = (
activeBetsInfo: ActiveBetsInfoType
): SetActiveBetsAction => ({
type: "SET_ACTIVE_BETS_MYBETS_STANDALONE",
payload: activeBetsInfo
});
export const setSelectedTabMyBetsStandalone = (
selectedTab: ActiveTabEnum
): SetSelectedTab => ({
type: "SET_SELECTED_TAB_MYBETS_STANDALONE",
payload: selectedTab
});
export const setSelectedSettledTabMyBetsStandalone = (
selectedSettledTab: SettledTabEnum
): SetSelectedSettledTab => ({
type: "SET_SELECTED_SETTLED_TAB_MYBETS_STANDALONE",
payload: selectedSettledTab
});
export const setCounterMyBetsStandalone = (total: number): SetCounter => ({
type: "SET_COUNTER_MYBETS_STANDALONE",
payload: total
});
export const setSettledCounterMyBetsStandalone = (
total: number
): SetSettledCounter => ({
type: "SET_SETTLED_COUNTER_MYBETS_STANDALONE",
payload: total
});
export const setActiveWagerAmountMyBetsStandalone = (
totalAmount: number
): SetActiveWageredAmount => ({
type: "SET_ACTIVE_WAGERED_AMOUNT_MYBETS_STANDALONE",
payload: totalAmount
});
export const setSettledWagerAmountMyBetsStandalone = (
totalAmount: number
): SetSettledWageredAmount => ({
type: "SET_SETTLED_WAGERED_AMOUNT_MYBETS_STANDALONE",
payload: totalAmount
});
export const setFutureCounterMyBetsStandalone = (
total: number
): SetFutureCounter => ({
type: "SET_FUTURE_COUNTER_MYBETS_STANDALONE",
payload: total
});
export const setFutureWageredAmountMyBetsStandalone = (
totalAmount: number
): SetFutureWageredAmount => ({
type: "SET_FUTURE_WAGERED_AMOUNT_MYBETS_STANDALONE",
payload: totalAmount
});
export const loadingBetCancelModalOn = (): BetCancelLoadingModalActionOn => ({
type: "LOADING_BET_CANCEL_MODAL_ON"
});
export const loadingBetCancelModalOff = (): BetCancelLoadingModalActionOff => ({
type: "LOADING_BET_CANCEL_MODAL_OFF"
});
export const betCancelRequestError = ({
payload
}: {
payload: string;
}): BetCancelLoadingModalActionError => ({
type: "LOADING_BET_CANCEL_MODAL_ERROR",
payload
});
export const closeBetCancelModal = (
payload?: OnBetCancelClosePayload
): BetCancelCloseModalAction => ({
type: "CLOSE_BET_CANCEL_MODAL",
payload
});
export const updateRacesMyBets = (
races: RaceInfoMyBets[]
): BetCancelUpdateModalAction => ({
type: "MY_BETS_UPDATING_RACES",
payload: races
});
export const openBetCancelModal = (
payload?: OnBetCancelPayload | OnRacePageBetCancelPayload
): BetCancelOpenModalAction => ({
type: "OPEN_BET_CANCEL_MODAL",
payload
});
export const openBetSocialShareModal = (
payload: OnBetSocialSharePayload
): SocialShareOpenModalAction => ({
type: "OPEN_BET_SOCIAL_SHARE_MODAL",
payload
});
export const closeBetSocialShareModal = (): SocialShareCloseModalAction => ({
type: "CLOSE_BET_SOCIAL_SHARE_MODAL"
});
export const cleanBetCancelResult = () => ({
type: "CLEAN_BET_CANCEL_RESULT"
});
export const closeApproxPayoutModal = () => ({
type: "CLOSE_APPROX_PAYOUT_MODAL"
});
export const openApproxPayoutModal = () => ({
type: "OPEN_APPROX_PAYOUT_MODAL"
});
export const openWagerCancellationRulesModal = (payload: {
hasBack: boolean;
}): OpenWagerCancellationRulesModalAction => ({
type: "OPEN_WAGER_CANCELLATION_RULES_MODAL",
payload
});
export const closeWagerCancellationRulesModal =
(): CloseWagerCancellationRulesModalAction => ({
type: "CLOSE_WAGER_CANCELLATION_RULES_MODAL"
});
export const openTrackRulesModal = (payload: {
betType: string;
alternates?: boolean;
}): OpenTrackRulesModalAction => ({
type: "OPEN_TRACK_RULES_MODAL",
payload
});
export const closeTrackRulesModal = (): CloseTrackRulesModalAction => ({
type: "CLOSE_TRACK_RULES_MODAL"
});
export const openMybetsPastPerformance = (
selectedRace: SelectedRace,
modalTitle: string,
selectedTab?: MyBetsPastPerformanceTab,
hasBack = true
): OpenMyBetsPastPerformance => ({
type: "OPEN_MYBETS_PAST_PERFORMANCE",
payload: {
selectedRace,
modalTitle,
selectedTab,
hasBack
}
});
export const closeMybetsPastPerformance = (): CloseMyBetsPastPerfomance => ({
type: "CLOSE_MYBETS_PAST_PERFORMANCE"
});
export const isLoadingMyBets = (isLoading: boolean): IsLoadingAction => ({
type: "IS_LOADING_MYBETS",
payload: {
isLoading
}
});
export const selectStatusFilters = (
statusFilter: StatusFilters
): SelectStatusFiltersAction => ({
type: "SELECT_MYBETS_STATUS_FILTERS",
payload: {
statusFilter
}
});
export const clearStatusFilters = (): ClearStatusFiltersAction => ({
type: "CLEAR_MYBETS_STATUS_FILTERS"
});
export const setStatusFilterCount = (count: number): SetStatusFilterCount => ({
type: "SET_MYBETS_STATUS_FILTER_COUNT",
payload: {
count
}
});
export const selectTrackFilters = (
trackFilter: MyBetsDynamicFilters
): SelectTrackFiltersAction => ({
type: "SELECT_MYBETS_TRACKS_FILTERS",
payload: {
trackFilter
}
});
export const setTrackFilterCount = (count: number): SetTrackFilterCount => ({
type: "SET_MYBETS_TRACKS_FILTER_COUNT",
payload: {
count
}
});
export const setBetTypeFilters = (
betTypeFilter: MyBetsDynamicFilters
): SetBetTypeFiltersAction => ({
type: "SET_MYBETS_BET_TYPE_FILTERS",
payload: {
betTypeFilter
}
});
export const setBetTypeFilterCount = (
count: number
): SetBetTypeFilterCount => ({
type: "SET_MYBETS_BET_TYPE_FILTER_COUNT",
payload: {
count
}
});
export const setCustomEndDate = (date: Date): SetCustomEndDate => ({
type: "SET_MYBETS_CUSTOM_END_DATE",
payload: {
date
}
});
export const setCustomStartDate = (date: Date | null): SetCustomStartDate => ({
type: "SET_MYBETS_CUSTOM_START_DATE",
payload: {
date
}
});
export const setIsCustomTimeFrame = (
isCustomTimeFrame: boolean
): SetIsCustomTimeFrame => ({
type: "SET_MYBETS_IS_CUSTOM_TIMEFRAME",
payload: {
isCustomTimeFrame
}
});
export const setShouldDefaultToSettled = (
isDefaultSettled: boolean
): SetIsDefaultSettled => ({
type: "SET_SHOULD_DEFAULT_TO_SETTLED",
payload: { isDefaultSettled }
});
export const setShouldDefaultToFuture = (
isDefaultFuture: boolean
): SetIsDefaultFuture => ({
type: "SET_SHOULD_DEFAULT_TO_FUTURE",
payload: { isDefaultFuture }
});
export const setActiveBetsInfo = (
payload: ActiveBetsInfoType
): SetActiveBetsActionLegacy => ({
type: "MYBETS_GET_ACTIVE_BETS",
payload
});
export const setRacesActiveBets = (payload: Record<number, number>) => ({
type: "MYBETS_GET_RACES_ACTIVE_BETS",
payload
});
webpack://frontend-mybets/../../packages/sh-lib-my-bets/redux/reducers.ts
import { RaceInfoMyBets } from "@tvg/ts-types/Race";
import { WroWager, WroWagerGroup } from "@tvg/ts-types/WroWager";
import { BetBasicInfo } from "@tvg/ts-types/Bet";
import { Actions, SelectedRace } from "./actions";
import {
ActiveTabEnum,
SettledTabEnum,
StatusFilters,
MyBetsDynamicFilters,
MyBetsPastPerformanceTab
} from "../utils/types";
export interface ActiveBets {
totalBets: number;
totalAmount: number;
bets: WroWagerGroup[];
}
export interface BetCancelModal {
isOpen?: boolean;
wager?: WroWager | BetBasicInfo;
races?: RaceInfoMyBets[];
isLoading?: boolean;
result?: {
status?: "success" | "failure" | "aborted";
errorCode?: string;
};
cancelRequestError?: unknown;
hasBackgroundModal?: boolean;
queryError?: null;
}
export interface BetSocialShareModal {
isOpen?: boolean;
wager?: WroWager;
races?: RaceInfoMyBets[];
isLoading?: boolean;
}
export interface WagerCancellationModal {
isOpen: boolean;
hasBack: boolean;
}
export interface TrackRulesModal {
isOpen: boolean;
betType: string;
alternates?: boolean;
}
export interface State {
isOpen: boolean;
activeBets: ActiveBets;
selectedTab: ActiveTabEnum;
selectedSettledTab: SettledTabEnum;
totalActiveBets: number;
totalSettledBets: number;
totalFutureBets: number;
deletedBets: string[];
isLoading: boolean;
betCancelModal: BetCancelModal;
betSocialShareModal: BetSocialShareModal;
approxPayoutModal: {
isOpen?: boolean;
};
wagerCancellationModal: WagerCancellationModal;
trackRulesModal: TrackRulesModal;
pastPerformance: {
isOpen: boolean;
selectedRace: SelectedRace | {};
modalTitle?: string;
selectedTab: MyBetsPastPerformanceTab;
hasBack: boolean;
races?: RaceInfoMyBets[];
};
activeWageredAmount: number;
settledWageredAmount: number;
futureWageredAmount: number;
statusFilters: StatusFilters;
statusFilterCount: number;
trackFilters: MyBetsDynamicFilters;
trackFilterCount: number;
betTypeFilters: MyBetsDynamicFilters;
betTypeFilterCount: number;
customStartDate?: Date | null;
customEndDate: Date | null;
isCustomTimeFrame: boolean;
shouldDefaultToSettled: boolean;
shouldDefaultToFuture: boolean;
racesActiveBets: Record<number, number>;
}
const initialMyBetsIPP = {
isOpen: false,
selectedRace: {},
modalTitle: "My Bets",
selectedTab: MyBetsPastPerformanceTab.FULL_RESULT,
hasBack: true,
races: []
};
export const initialState: State = {
isOpen: false,
activeBets: {
totalBets: 0,
totalAmount: 0,
bets: []
},
selectedTab: ActiveTabEnum.SETTLED,
selectedSettledTab: SettledTabEnum.TODAY,
totalActiveBets: 0,
totalSettledBets: 0,
totalFutureBets: 0,
deletedBets: [],
isLoading: false,
betCancelModal: {
isOpen: false,
hasBackgroundModal: false
},
betSocialShareModal: {
isOpen: false
},
approxPayoutModal: {
isOpen: false
},
wagerCancellationModal: {
isOpen: false,
hasBack: false
},
trackRulesModal: {
isOpen: false,
betType: "",
alternates: false
},
pastPerformance: {
...initialMyBetsIPP
},
activeWageredAmount: 0,
settledWageredAmount: 0,
futureWageredAmount: 0,
statusFilters: {
Cancelled: false,
Won: false,
Lost: false,
Refunded: false
},
statusFilterCount: 0,
trackFilters: [],
trackFilterCount: 0,
betTypeFilters: [],
betTypeFilterCount: 0,
customStartDate: null,
customEndDate: null,
isCustomTimeFrame: false,
shouldDefaultToSettled: true,
shouldDefaultToFuture: false,
racesActiveBets: {}
};
export default function reducer(
// eslint-disable-next-line
state: State = initialState,
action: Actions
): State {
switch (action.type) {
case "OPEN_MYBETS_STANDALONE":
return { ...state, isOpen: true };
case "CLOSE_MYBETS_STANDALONE":
return {
...state,
isOpen: false,
pastPerformance: {
...initialMyBetsIPP
}
};
case "SET_ACTIVE_BETS_MYBETS_STANDALONE":
return {
...state,
activeBets: {
...state.activeBets,
...action.payload
}
};
case "SET_SELECTED_TAB_MYBETS_STANDALONE":
return { ...state, selectedTab: action.payload };
case "SET_SELECTED_SETTLED_TAB_MYBETS_STANDALONE":
return { ...state, selectedSettledTab: action.payload };
case "SET_RACES_ACTIVE_BETS_STANDALONE":
return { ...state, racesActiveBets: action.payload };
case "SET_COUNTER_MYBETS_STANDALONE":
if (action.payload === state.totalActiveBets) return state;
return { ...state, totalActiveBets: action.payload };
case "SET_SETTLED_COUNTER_MYBETS_STANDALONE":
if (action.payload === state.totalSettledBets) return state;
return { ...state, totalSettledBets: action.payload };
case "SET_ACTIVE_WAGERED_AMOUNT_MYBETS_STANDALONE":
if (action.payload === state.activeWageredAmount) return state;
return { ...state, activeWageredAmount: action.payload };
case "SET_SETTLED_WAGERED_AMOUNT_MYBETS_STANDALONE":
if (action.payload === state.settledWageredAmount) return state;
return { ...state, settledWageredAmount: action.payload };
case "SET_FUTURE_WAGERED_AMOUNT_MYBETS_STANDALONE":
if (action.payload === state.futureWageredAmount) return state;
return { ...state, futureWageredAmount: action.payload };
case "SET_FUTURE_COUNTER_MYBETS_STANDALONE":
if (action.payload === state.totalFutureBets) return state;
return { ...state, totalFutureBets: action.payload };
case "SET_SHOULD_DEFAULT_TO_SETTLED":
return {
...state,
shouldDefaultToSettled: action.payload.isDefaultSettled,
selectedTab:
!state.isOpen && state.totalActiveBets
? ActiveTabEnum.ACTIVE
: state.selectedTab
};
case "SET_SHOULD_DEFAULT_TO_FUTURE":
return {
...state,
shouldDefaultToFuture: action.payload.isDefaultFuture,
selectedTab:
!state.isOpen && action.payload.isDefaultFuture
? ActiveTabEnum.FUTURES
: state.selectedTab
};
case "MY_BETS_UPDATING_RACES":
return {
...state,
betCancelModal: {
...state.betCancelModal,
races: action.payload
},
pastPerformance: {
...state.pastPerformance,
races: action.payload
}
};
case "OPEN_BET_CANCEL_MODAL": {
const { betCancelModal } = state;
return {
...state,
betCancelModal: {
...betCancelModal,
...action.payload,
isLoading: false,
isOpen: true
}
};
}
case "CLOSE_BET_CANCEL_MODAL": {
const { betCancelModal } = state;
return {
...state,
betCancelModal: {
...betCancelModal,
...action.payload,
isOpen: false
}
};
}
case "OPEN_BET_SOCIAL_SHARE_MODAL": {
const { betSocialShareModal } = state;
return {
...state,
betSocialShareModal: {
...betSocialShareModal,
...action.payload,
isLoading: false,
isOpen: true
}
};
}
case "CLOSE_BET_SOCIAL_SHARE_MODAL": {
return {
...state,
betSocialShareModal: {
isOpen: false
}
};
}
case "LOADING_BET_CANCEL_MODAL_ON": {
const { betCancelModal } = state;
betCancelModal.isLoading = true;
return {
...state,
betCancelModal
};
}
case "LOADING_BET_CANCEL_MODAL_OFF": {
const { betCancelModal } = state;
betCancelModal.isLoading = false;
return {
...state,
betCancelModal
};
}
case "LOADING_BET_CANCEL_MODAL_ERROR": {
const { betCancelModal } = state;
betCancelModal.isLoading = false;
betCancelModal.cancelRequestError = action.payload;
return {
...state,
betCancelModal
};
}
case "CLEAN_BET_CANCEL_RESULT": {
const { betCancelModal } = state;
betCancelModal.result = {};
betCancelModal.cancelRequestError = null;
betCancelModal.queryError = null;
return {
...state,
betCancelModal
};
}
case "OPEN_APPROX_PAYOUT_MODAL": {
return {
...state,
approxPayoutModal: {
isOpen: true
}
};
}
case "CLOSE_APPROX_PAYOUT_MODAL": {
return {
...state,
approxPayoutModal: {
isOpen: false
}
};
}
case "OPEN_WAGER_CANCELLATION_RULES_MODAL": {
return {
...state,
wagerCancellationModal: {
isOpen: true,
hasBack: action.payload.hasBack
}
};
}
case "CLOSE_WAGER_CANCELLATION_RULES_MODAL": {
return {
...state,
wagerCancellationModal: {
isOpen: false,
hasBack: false
}
};
}
case "OPEN_TRACK_RULES_MODAL": {
return {
...state,
trackRulesModal: {
isOpen: true,
betType: action.payload.betType,
alternates: action.payload.alternates
}
};
}
case "CLOSE_TRACK_RULES_MODAL": {
return {
...state,
trackRulesModal: {
isOpen: false,
betType: "",
alternates: false
}
};
}
case "CLOSE_MYBETS_PAST_PERFORMANCE": {
return {
...state,
pastPerformance: {
...initialMyBetsIPP
}
};
}
case "OPEN_MYBETS_PAST_PERFORMANCE": {
return {
...state,
pastPerformance: {
...state.pastPerformance,
isOpen: true,
selectedRace: action.payload.selectedRace,
modalTitle: action.payload.modalTitle || initialMyBetsIPP.modalTitle,
selectedTab:
action.payload.selectedTab || state.pastPerformance.selectedTab,
hasBack: action.payload.hasBack
}
};
}
case "IS_LOADING_MYBETS": {
return {
...state,
isLoading: action.payload.isLoading
};
}
default: {
return state;
}
case "SELECT_MYBETS_STATUS_FILTERS": {
return {
...state,
statusFilters: action.payload.statusFilter
};
}
case "CLEAR_MYBETS_STATUS_FILTERS": {
return {
...state,
statusFilters: initialState.statusFilters
};
}
case "SET_MYBETS_STATUS_FILTER_COUNT": {
return {
...state,
statusFilterCount: action.payload.count
};
}
case "SELECT_MYBETS_TRACKS_FILTERS": {
return {
...state,
trackFilters: action.payload.trackFilter
};
}
case "SET_MYBETS_TRACKS_FILTER_COUNT": {
return {
...state,
trackFilterCount: action.payload.count
};
}
case "SET_MYBETS_BET_TYPE_FILTERS": {
return {
...state,
betTypeFilters: action.payload.betTypeFilter
};
}
case "SET_MYBETS_BET_TYPE_FILTER_COUNT": {
return {
...state,
betTypeFilterCount: action.payload.count
};
}
case "SET_MYBETS_CUSTOM_END_DATE": {
return {
...state,
customEndDate: action.payload.date
};
}
case "SET_MYBETS_CUSTOM_START_DATE": {
return {
...state,
customStartDate: action.payload.date
};
}
case "SET_MYBETS_IS_CUSTOM_TIMEFRAME": {
return {
...state,
isCustomTimeFrame: action.payload.isCustomTimeFrame
};
}
}
}
webpack://frontend-mybets/../../packages/sh-lib-my-bets/redux/selectors.ts
import { Store } from "redux";
import { get } from "lodash";
import parseCAPIMessage from "@tvg/utils/capiUtils";
import { WroWager, WroWagerGroup } from "@tvg/ts-types/WroWager";
import { RaceInfoMyBets, RaceProgram } from "@tvg/ts-types/Race";
import { XsellHeaderMessage } from "@urp/my-bets/components/modals/mybets/alertXsell/types";
import {
BetCancelModal,
initialState,
TrackRulesModal,
WagerCancellationModal
} from "./reducers";
import {
ActiveTabEnum,
BetCancelResult,
MyBetsDynamicFilters,
SettledTabEnum,
StatusFilters,
XsellBlacklistedBets
} from "../utils/types";
// Feature Toggles
export const getMyBetsCounterToggle = (store: Store): boolean =>
get(store, "capi.featureToggles.myBetsCounterToggle", false);
export const getWatchReplayWithinMyBets = (store: Store): boolean =>
get(store, "capi.featureToggles.watchReplayWithinMyBets", false);
export const getShowSeeResult = (store: Store): boolean =>
get(store, "capi.featureToggles.showSeeResult", false);
export const getMyBetsTrackRulesToggle = (store: Store): boolean =>
get(store, "capi.featureToggles.myBetsTrackRules", false);
export const getRedirectWithoutActiveBetsToggle = (store: Store): boolean =>
get(store, "capi.featureToggles.redirectWithoutActiveBetsToggle", false);
export const getSocialShareToggle = (store: Store): boolean =>
get(store, "capi.featureToggles.betSocialShareModalFlow", false);
export const getBetCancelModalToggle = (store: Store): boolean =>
get(store, "capi.featureToggles.betCancelModalFlow", false);
export const getMyBetsResultedBetTicketToggle = (store: Store): boolean =>
get(store, "capi.featureToggles.myBetsResultedBetTicket", false);
// End feature toggles
export const getIsMyBetsOpen = (store: Store): boolean =>
get(store, "myBetsStandalone.isOpen", initialState.isOpen);
export const getRacesActiveBets = (store: Store): Record<number, number> =>
get(store, "myBetsStandalone.racesActiveBets", initialState.racesActiveBets);
export const getSelectedTab = (store: Store): ActiveTabEnum =>
get(store, "myBetsStandalone.selectedTab", initialState.selectedTab);
export const getSelectedSettledTab = (store: Store): SettledTabEnum =>
get(
store,
"myBetsStandalone.selectedSettledTab",
initialState.selectedSettledTab
);
export const getTotalActiveBets = (store: Store): number =>
get(store, "myBetsStandalone.totalActiveBets", initialState.totalActiveBets);
export const getTotalSettledBets = (store: Store): number =>
get(
store,
"myBetsStandalone.totalSettledBets",
initialState.totalSettledBets
);
export const getBetCancel = (store: Store): BetCancelModal | undefined =>
get(store, "myBetsStandalone.betCancelModal");
export const getBetCancelWager = (store: Store): WroWager | undefined =>
get(store, "myBetsStandalone.betCancelModal.wager");
export const getBetCancelRaceNumber = (store: Store): number | undefined =>
get(store, "myBetsStandalone.betCancelModal.raceNumber");
export const getBetCancelIsLoadingBetCancelRequest = (
store: Store
): boolean | undefined =>
get(store, "myBetsStandalone.betCancelModal.isLoading");
export const getBetCancelRequestError = (store: Store): unknown | undefined =>
get(store, "myBetsStandalone.betCancelModal.cancelRequestError");
export const getBetCancelIsLoadingRequest = (
store: Store
): boolean | undefined =>
get(store, "myBetsStandalone.betCancelModal.isLoading");
export const getBetCancelIsOpen = (store: Store): boolean =>
get(store, "myBetsStandalone.betCancelModal.isOpen", false);
export const getBetCancelNotification = (
store: Store
): BetCancelResult | undefined =>
get(store, "myBetsStandalone.betCancelModal.result");
export const getBetSocialShareIsOpen = (store: Store): boolean =>
get(store, "myBetsStandalone.betSocialShareModal.isOpen", false);
export const getBetSocialShareWager = (store: Store): WroWager =>
get(store, "myBetsStandalone.betSocialShareModal.wager");
export const getBetSocialSelectionsUrl = (store: Store): string =>
get(store, "myBetsStandalone.betSocialShareModal.repeatButtonSearch");
export const getBetSocialShareBet = (store: Store): Array<WroWagerGroup> =>
get(store, "myBetsStandalone.betSocialShareModal.bet");
export const getBetSocialShareModule = (store: Store): boolean =>
get(store, "myBetsStandalone.betSocialShareModal.isMyBets");
export const getBetSocialCurrentRace = (store: Store): RaceProgram =>
get(store, "myBetsStandalone.betSocialShareModal.currentRace");
export const getBetSocialShareMessage = (store: Store): string =>
get(store, "capi.messages.Homepage.betSocialSharingMessage", "");
export const getWebBetSocialShareMessage = (store: Store): string =>
get(store, "capi.messages.betSocialSharingMessage", "");
export const getTrackRulesModalTitleMessage = (store: Store): string =>
get(store, "capi.messages.trackRulesModalTitleLabel", "Scratch Rules");
export const getBetCancelRaces = (store: Store): Array<RaceInfoMyBets> =>
get(store, "myBetsStandalone.betCancelModal.races");
export const getBetCancelLimitations = (store: Store): string | undefined =>
get(store, "capi.messages.myBetsCancelLimitations");
export const getBetCancelLimitationsByState = (
store: Store
): string | undefined =>
get(store, "capi.messages.myBetsCancelLimitationsByState");
export const getFeatureUseTvgPotReturn = (store: Store): boolean =>
get(store, "capi.featureToggles.useTvgPotReturn", false);
export const getIsWagerCancellationRulesModalOpen = (
store: Store
): WagerCancellationModal =>
get(
store,
"myBetsStandalone.wagerCancellationModal",
initialState.wagerCancellationModal
);
export const getIsTrackRulesModalOpen = (store: Store): TrackRulesModal =>
get(store, "myBetsStandalone.trackRulesModal", initialState.trackRulesModal);
export const getPickBetRebetToggle = (store: Store): boolean =>
get(store, "capi.featureToggles.enablePickBetRebetMyBetsStandalone", false);
export const enableRepeatBetsMyBets = (store: Store): boolean =>
get(store, "capi.featureToggles.enableRepeatBetsMyBets", false);
export const getFeatureIsMTPNewRules = (store: Store): boolean =>
get(store, "capi.featureToggles.MTPColoursRules", true);
export const getShowMyBetsCardDesign = (store: Store): boolean =>
get(store, "capi.featureToggles.showMyBetsCardDesign", false);
export const getTodayActiveCounter = (store: Store): number =>
get(store, "myBetsStandalone.totalActiveBets", 0);
export const getTodaySettledCounter = (store: Store): number =>
get(
store,
"myBetsStandalone.totalSettledBets",
initialState.totalSettledBets
);
export const getTodayFutureCounter = (store: Store): number =>
get(store, "myBetsStandalone.totalFutureBets", 0);
export const getActiveWageredAmountCounter = (store: Store): number =>
get(store, "myBetsStandalone.activeWageredAmount", 0);
export const getSettledWageredAmountCounter = (store: Store): number =>
get(store, "myBetsStandalone.settledWageredAmount", 0);
export const getFutureWageredAmountCounter = (store: Store): number =>
get(store, "myBetsStandalone.futureWageredAmount", 0);
export const getMyBetsPastPerformanceRaces = (
store: Store
): Array<RaceInfoMyBets> =>
get(store, "myBetsStandalone.pastPerformance.races", []);
export const getIsMyBetsPastPerformanceOpen = (store: Store): boolean =>
get(store, "myBetsStandalone.pastPerformance.isOpen", false);
export const getHasMyBetsPastPerformanceBack = (store: Store): SettledTabEnum =>
get(
store,
"myBetsStandalone.pastPerformance.hasBack",
initialState.pastPerformance.hasBack
);
export const getMyBetsPastPerformanceTrackCode = (store: Store): string =>
get(store, "myBetsStandalone.pastPerformance.selectedRace.trackCode", "");
export const getMyBetsPastPerformanceRaceNumber = (store: Store): number =>
get(store, "myBetsStandalone.pastPerformance.selectedRace.raceNumber", 1);
export const getMyBetsPastPerformanceDate = (store: Store): string =>
get(store, "myBetsStandalone.pastPerformance.selectedRace.raceDate", "");
export const getBetCancelBet = (store: Store): WroWagerGroup | undefined =>
get(store, "myBetsStandalone.betCancelModal.bet");
export const getIsLoadingMyBets = (store: Store): boolean | undefined =>
get(store, "myBetsStandalone.isLoading");
export const getMyBetsTrackRulesMessage = (store: Store): string =>
get(store, "capi.messages.myBetsTrackRulesMessage", "");
export const getMyBetsPaginationConf = (store: Store): string | undefined =>
parseCAPIMessage(store, "capi.messages.myBetsPaginationConf");
export const getStatusFilters = (store: Store): StatusFilters | undefined =>
get(store, "myBetsStandalone.statusFilters");
export const getStatusFiltersCount = (store: Store): number | undefined =>
get(store, "myBetsStandalone.statusFilterCount");
export const getIsApproxPayoutModalOpen = (store: Store): boolean =>
get(store, "myBetsStandalone.approxPayoutModal.isOpen", false);
export const getTrackFilters = (store: Store): Array<MyBetsDynamicFilters> =>
get(store, "myBetsStandalone.trackFilters", []);
export const getTrackFiltersCount = (store: Store): number =>
get(store, "myBetsStandalone.trackFilterCount", 0);
export const getBetTypeFilters = (store: Store): Array<MyBetsDynamicFilters> =>
get(store, "myBetsStandalone.betTypeFilters", []);
export const getBetTypeFiltersCount = (store: Store): number =>
get(store, "myBetsStandalone.betTypeFilterCount", 0);
export const getCustomStartDate = (store: Store): string | null =>
get(store, "myBetsStandalone.customStartDate", null);
export const getCustomEndDate = (store: Store): Date =>
get(store, "myBetsStandalone.customEndDate", new Date());
export const getIsCustomTimeFrame = (store: Store): boolean =>
get(store, "myBetsStandalone.isCustomTimeFrame", false);
export const getIsDefaultSettled = (store: Store): boolean =>
get(store, "myBetsStandalone.shouldDefaultToSettled", false);
export const getIsDefaultFuture = (store: Store): boolean =>
get(store, "myBetsStandalone.shouldDefaultToFuture", false);
export const getPastPerformanceModaLTitle = (store: Store): string =>
get(store, "myBetsStandalone.pastPerformance.modalTitle", "");
// TODO: try to figured out those types.
export const getDeletedBets = (store: Store) =>
get(store, "myBetsStandalone.deletedBets");
// This one have this redux selector but we don't have the bettingInterests inside the interface BetCancelModal
export const getMyBetBettingInterests = (store: Store) =>
get(store, "myBetsStandalone.betCancelModal.bettingInterests");
export const getBetSocialProgramPageWagerType = (store: Store) =>
get(store, "RaceProgram.betType");
export const getHeaderMessage = (store: Store): XsellHeaderMessage =>
parseCAPIMessage(store, "capi.messages.myBetsInfoMessage");
export const getXsellBlacklistedMyBets = (store: Store): XsellBlacklistedBets =>
parseCAPIMessage(store, "capi.messages.FDRBlacklistedBets", {
blacklistedBets: []
});
export const getHasBackgroundModal = (store: Store): boolean =>
get(store, "myBetsStandalone.betCancelModal.hasBackgroundModal", false);
webpack://frontend-mybets/../../packages/sh-lib-my-bets/utils/filters.ts
import { batch } from "react-redux";
import { Dispatch } from "redux";
import { UnaryFn } from "@tvg/ts-types/Functional";
import { WroWager, WroWagerGroup } from "@tvg/ts-types/WroWager";
import {
selectStatusFilters,
clearStatusFilters,
setStatusFilterCount,
selectTrackFilters,
setTrackFilterCount,
setBetTypeFilters,
setBetTypeFilterCount,
setSelectedSettledTabMyBetsStandalone,
setCustomStartDate,
setCustomEndDate,
setIsCustomTimeFrame
} from "../redux/actions";
import {
clearFilterDropdown,
selectedNewFiltersGtm,
clearAllFiltersGtm,
selectedNewCustomDateGtm
} from "./gtm";
import {
StatusFilters,
MyBetsDynamicFilter,
MyBetsDynamicFilters,
QueryTrackFilter,
QueryBetTypeFilter,
ActiveTabEnum,
SelectedFilters,
SettledTabEnum
} from "./types";
export const clearDrowpdownFilters = (dispatch: Dispatch) => {
dispatch(selectTrackFilters([]));
dispatch(setTrackFilterCount(0));
dispatch(setBetTypeFilters([]));
dispatch(setBetTypeFilterCount(0));
dispatch(clearStatusFilters());
dispatch(setStatusFilterCount(0));
};
export const clearAllFilters = (dispatch: Dispatch, date?: Date) => {
clearDrowpdownFilters(dispatch);
dispatch(setCustomEndDate(date || new Date()));
dispatch(setCustomStartDate(null));
};
export const selectNewTimeFrame =
(dispatch: Dispatch, currentFrame: string, tab: string) =>
(newTimeFrame: SettledTabEnum) => {
if (currentFrame !== newTimeFrame && tab === "SETTLED") {
dispatch(setSelectedSettledTabMyBetsStandalone(newTimeFrame));
}
};
export const filterByTrack = (bets: WroWagerGroup[], trackNames: string[]) => {
if (trackNames.length) {
const filteredBets = bets.filter((bet: WroWagerGroup) =>
trackNames.includes(bet.wagers[0].trackName)
);
return filteredBets;
}
return bets;
};
export const getTrackListFromBets = (bets: WroWagerGroup[]) => {
const trackListBuffer: string[] = [];
bets.forEach((bet) => {
bet.wagers.forEach((wager: WroWager) => {
if (!trackListBuffer.includes(wager.trackName)) {
trackListBuffer.push(wager.trackName);
}
});
});
return trackListBuffer;
};
export const getQueryDynamicOptions = (
filters: Array<QueryTrackFilter & QueryBetTypeFilter>,
selected: MyBetsDynamicFilters
) => {
const constructed: MyBetsDynamicFilters = [];
const filterCopy = [...filters];
filterCopy.sort((a, b) => {
if (a.id && b.id) {
return a.id - b.id;
}
return a.name ? a.name.localeCompare(b.name) : 0;
});
filterCopy.forEach((filter) => {
const currentOption = selected.find(
(option) => option.code === filter.code && option.name === filter.name
);
constructed.push({
code: filter.code,
name: filter.name,
isActive: currentOption?.isActive || false
});
});
return constructed;
};
export const reduceDynamicFilters = (filters: MyBetsDynamicFilters) =>
filters.reduce<{ keys: string[]; values: boolean[] }>(
(prev, filter) => {
prev.keys.push(filter.name);
prev.values.push(filter.isActive);
return prev;
},
{ keys: [], values: [] }
);
export const selectNewStatusFilters =
(
filters: StatusFilters,
dispatch: Dispatch,
settledTab: string,
activeCounter: number,
settledCounter: number,
closeDropdown: UnaryFn<boolean, void>
) =>
(newType: keyof StatusFilters | "clear") => {
if (newType === "clear") {
dispatch(clearStatusFilters());
dispatch(setStatusFilterCount(0));
closeDropdown(false);
clearFilterDropdown("Status", settledTab, activeCounter, settledCounter);
return;
}
const newFilters: StatusFilters = { ...filters };
newFilters[newType] = !filters[newType];
let newCounter = 0;
const activeStatus: string[] = [];
Object.keys(newFilters).forEach((type) => {
if (newFilters[type as keyof StatusFilters]) {
newCounter += 1;
activeStatus.push(type);
}
});
dispatch(selectStatusFilters(newFilters));
dispatch(setStatusFilterCount(newCounter));
selectedNewFiltersGtm(
`Status - ${activeStatus.length ? activeStatus.join(", ") : "None"}`,
settledTab,
activeCounter,
settledCounter
);
};
export const setDynamicFilters =
(
dispatch: Dispatch,
type: string,
filters: MyBetsDynamicFilters,
settledTab: string,
activeCounter: number,
settledCounter: number,
closeDropdown: UnaryFn<boolean, void>
) =>
(toggledType: string) => {
if (toggledType === "clear") {
if (type === "Tracks") {
closeDropdown(false);
dispatch(selectTrackFilters([]));
dispatch(setTrackFilterCount(0));
clearFilterDropdown(
"Tracks",
settledTab,
activeCounter,
settledCounter
);
} else {
closeDropdown(false);
dispatch(setBetTypeFilters([]));
dispatch(setBetTypeFilterCount(0));
clearFilterDropdown(
"Bet Type",
settledTab,
activeCounter,
settledCounter
);
}
} else {
const toggledIndex = filters.findIndex(
(filter) => filter.name === toggledType
);
if (toggledIndex === -1) return;
const newFilters = filters.map((filter) => ({
...filter,
isActive:
filter.name === toggledType ? !filter.isActive : filter.isActive
}));
const activeStatus = newFilters
.filter((filter) => filter.isActive)
.map((filter) => filter.name);
if (type === "Tracks") {
dispatch(selectTrackFilters(newFilters));
dispatch(setTrackFilterCount(activeStatus.length));
selectedNewFiltersGtm(
`Tracks - ${activeStatus.length ? activeStatus.join(", ") : "None"}`,
settledTab,
activeCounter,
settledCounter
);
} else {
dispatch(setBetTypeFilters(newFilters));
dispatch(setBetTypeFilterCount(activeStatus.length));
selectedNewFiltersGtm(
`Bet Type - ${
activeStatus.length ? activeStatus.join(", ") : "None"
}`,
settledTab,
activeCounter,
settledCounter
);
}
}
};
export const resetAllFilters =
(
dispatch: Dispatch,
settledTab: string,
activeCounter: number,
settledCounter: number
) =>
() => {
batch(() => {
clearDrowpdownFilters(dispatch);
});
clearAllFiltersGtm(settledTab, activeCounter, settledCounter);
};
export const statusKeyMapper = (statusList: string[]): string[] => {
const newStatusList: string[] = [];
statusList.forEach((track: string) => {
switch (track) {
case "Cancelled":
newStatusList.push("Canceled");
break;
case "Won":
newStatusList.push("Winners");
break;
case "Lost":
newStatusList.push("Losses");
break;
case "Refunded":
newStatusList.push(track);
break;
default:
break;
}
});
return newStatusList.map((newStatus: string) => newStatus?.toUpperCase());
};
export const getQueryFilters = (
selectedTab: ActiveTabEnum,
filters: SelectedFilters | null
) => {
if (selectedTab !== "SETTLED" || filters === null) {
return null;
}
const { statusFilters, trackFilters, betTypeFilters } = filters;
const activeStatusFilters: string[] = [];
if (statusFilters) {
Object.keys(statusFilters).forEach((type) => {
if (statusFilters[type as keyof StatusFilters]) {
activeStatusFilters.push(type);
}
});
}
const activeTrackFilter: MyBetsDynamicFilter[] = [];
if (trackFilters && trackFilters.length) {
trackFilters.forEach((filter) => {
if (filter.isActive) {
activeTrackFilter.push(filter);
}
});
}
const activeBetTypeFilter: MyBetsDynamicFilter[] = [];
if (betTypeFilters && betTypeFilters.length) {
betTypeFilters.forEach((filter) => {
if (filter.isActive) {
activeBetTypeFilter.push(filter);
}
});
}
const statusFiltersMap = statusKeyMapper(activeStatusFilters);
return {
statusList: statusFiltersMap.length > 0 ? statusFiltersMap : ["RESOLVED"],
trackCodes:
activeTrackFilter.length > 0
? activeTrackFilter.map((filter: MyBetsDynamicFilter) => filter.code)
: null,
wagerTypes:
activeBetTypeFilter.length > 0
? activeBetTypeFilter.map((filter: MyBetsDynamicFilter) => filter.code)
: null
};
};
export const dateSelectionHook =
(
type: string,
dispatch: Dispatch,
closePicker: Function,
customStartDate?: Date,
activeBets?: number,
settledBets?: number
) =>
(event: Date, info: { disabled?: boolean }) => {
if (info?.disabled) {
return;
}
batch(() => {
if (type === "start") {
dispatch(setCustomStartDate(event));
clearDrowpdownFilters(dispatch);
} else if (type === "end") {
dispatch(setCustomEndDate(event));
if (customStartDate) {
clearDrowpdownFilters(dispatch);
if (new Date(event) < customStartDate) {
dispatch(setCustomStartDate(null));
}
}
}
closePicker(false);
});
selectedNewCustomDateGtm(activeBets, settledBets);
};
export const updateIsCustomTimeFrame =
(dispatch: Dispatch) => (isCustom: boolean) => {
if (!isCustom) {
batch(() => {
dispatch(setIsCustomTimeFrame(isCustom));
clearAllFilters(dispatch);
});
} else {
dispatch(setIsCustomTimeFrame(isCustom));
}
};
webpack://frontend-mybets/../../packages/sh-lib-my-bets/utils/gtm.ts
import mediator from "@tvg/mediator";
import { Dispatch } from "redux";
import { MultiLegCreateBetGTM, PayloadRepeatBetGTM } from "@tvg/ts-types/Bet";
import { get } from "lodash";
import { UnaryFn } from "@tvg/ts-types/Functional";
import {
openApproxPayoutModal,
openBetCancelModal,
openTrackRulesModal
} from "../redux/actions";
import {
ActiveTabEnum,
MyBetsBaseGtm,
OnBetCancelPayload,
SettledTabEnum
} from "./types";
export const sendTabSelectionGtmEvent = (tabSelected: ActiveTabEnum) =>
mediator.base.dispatch({
type: "MYBETS_TAB_SELECT",
payload: {
tab: tabSelected.toLocaleLowerCase()
}
});
export const sendTimeframeSelectionGtmEvent = (
timeframe: string,
tab: ActiveTabEnum | SettledTabEnum,
totalActiveBets: number,
totalSettledBets: number
) =>
mediator.base.dispatch({
type: "MYBETS_TIMEFRAME_SELECTED",
payload: {
timeframe,
tab,
activeBets: totalActiveBets,
settledBets: totalSettledBets
}
});
export const onApproxPayoutModalGtm = (
dispatch: Dispatch,
payload: MyBetsBaseGtm
) => {
dispatch(openApproxPayoutModal());
mediator.base.dispatch({ type: "OPEN_APPROX_PAYOUT_MODAL" });
mediator.base.dispatch({
type: "MYBETS_POTENTIAL_PAYOUT_CLICK",
payload: {
selectedTab: payload.selectedTab,
selectedSettledTab: payload.selectedSettledTab,
activeBets: payload.activeBetsCount,
settledBets: payload.settledBetsCount
}
});
};
export const onCancelBetModalGtm = (
dispatch: Dispatch,
payload: OnBetCancelPayload,
selectedTab: string,
selectedSettledTab: string,
totalActiveBets?: number,
totalSettledBets?: number
) => {
dispatch(openBetCancelModal(payload));
mediator.base.dispatch({
type: "MYBETS_CANCEL_BET",
payload: {
selectedTab,
selectedSettledTab,
activeBets: totalActiveBets,
settledBets: totalSettledBets
}
});
mediator.base.dispatch({ type: "OPEN_BET_CANCEL_MODAL" });
};
export const handleCreateBetGtm = (payload: MultiLegCreateBetGTM) => {
mediator.base.dispatch({
type: "MYBETS_PICKBET_CREATE_BET",
payload
});
};
export const onHideShowLegsGTM = (payload: {
isOpening: boolean;
activeBets: number;
settledBets: number;
}) => {
mediator.base.dispatch({
type: "HIDE-SHOW-LEGS-GTM",
payload
});
};
export const onToggleShowDetails = (payload: MyBetsBaseGtm) => {
mediator.base.dispatch({
type: "MYBETS_SHOW_DETAILS",
payload: {
selectedTab: payload.selectedTab,
selectedSettledTab: payload.selectedSettledTab,
show: payload.show,
totalActiveBets: payload.activeBetsCount,
totalSettledBets: payload.settledBetsCount
}
});
};
export const showTrackRulesGtm = (
dispatch: Dispatch,
selectedTab: string,
selectedSettledTab: string,
betType: string,
alternates: boolean = false
) => {
dispatch(openTrackRulesModal({ betType, alternates }));
mediator.base.dispatch({
type: "MYBETS_OPEN_TRACK_RULES",
payload: {
selectedTab,
selectedSettledTab
}
});
};
export const expandCollapseLegGtm = (
action: string,
legNumber: number,
selectedTab: string,
selectedSettledTab: string,
activeBetsCounter: number,
settledBetsCounter: number
) => {
mediator.base.dispatch({
type: "MYBETS_EXPAND_COLLAPSE_INDIVIDUAL_LEG",
payload: {
gaEventAction: action,
legNumber: `Leg ${legNumber}`,
selectedTab,
selectedSettledTab,
activeBets: activeBetsCounter,
settledBets: settledBetsCounter
}
});
};
export type RaceHeaderGTM = {
selectedTab: string;
selectedSettledTab: string;
activeBets: number;
settledBets: number;
gaEventLabel?: string;
};
export const handleRaceHeaderGtm = (type: string, payload: RaceHeaderGTM) => {
mediator.base.dispatch({
type,
payload
});
};
export const onReturnBettingGtm = (
selectedTab: string,
selectedSettledTab: string
) => {
mediator.base.dispatch({
type: "MYBETS_RETURN_TO_BETTING",
payload: {
selectedTab,
selectedSettledTab
}
});
};
export const handleCancelBetNotificationGtm = (
selectedTab: string,
selectedSettledTab: string,
activeBetsCounter: number,
settledBetsCounter: number
) => {
mediator.base.dispatch({
type: "MYBETS_USER_CLICKS_SEE_RULES_ON_CANCELLED_BET",
payload: {
selectedTab,
selectedSettledTab,
activeBets: activeBetsCounter,
settledBets: settledBetsCounter
}
});
};
export const onTabClickGtm = (payload: MyBetsBaseGtm) => {
mediator.base.dispatch({
type: "MYBETS_TAB_CLICK",
payload: {
selectedTab: get(payload, "selectedTab"),
selectedSettledTab: get(payload, "selectedSettledTab"),
activeBets: get(payload, "activeBetsCount"),
settledBets: get(payload, "settledBetsCount"),
futureBets: get(payload, "futureBetsCount"),
previousSelectedTab: get(payload, "previousSelectedTab")
}
});
};
export const onMyBetsStartupGtm = (
isMyBetsModalOpen: boolean,
activeBetsCounter: number,
settledBetsCounter: number,
isComponentLoading: boolean,
hasSentGtm: boolean,
setHasSentGtm: UnaryFn<boolean, void>
) => {
if (
isMyBetsModalOpen &&
activeBetsCounter >= 0 &&
settledBetsCounter >= 0 &&
!isComponentLoading &&
!hasSentGtm
) {
mediator.base.dispatch({
type: "MYBETS_STARTUP",
payload: {
activeBetsCounter,
settledBetsCounter
}
});
setHasSentGtm(true);
return true;
}
return false;
};
export const onMyBetsFilterHandling = (
filter: string,
tab: string,
settledTab: string,
activeBets: number,
settledBets: number,
isOpening: boolean
) =>
mediator.base.dispatch({
type: "MYBETS_FILTERS_HANDLING",
payload: {
filter,
tab,
settledTab,
activeBets,
settledBets,
isOpening
}
});
export const clearFilterDropdown = (
name: string,
activeFilter: string,
activeBets: number,
settledBets: number
) =>
mediator.base.dispatch({
type: "CLEAR_MYBETS_FILTER_DROPDOWN",
payload: {
name,
activeFilter,
activeBets,
settledBets
}
});
export const selectedNewFiltersGtm = (
name: string,
activeFilter: string,
activeBets: number,
settledBets: number
) =>
mediator.base.dispatch({
type: "SELECT_MYBETS_FILTER_TYPE",
payload: {
name,
activeFilter,
activeBets,
settledBets
}
});
export const selectedNewCustomDateGtm = (
activeBets?: number,
settledBets?: number
) =>
mediator.base.dispatch({
type: "SELECT_MYBETS_CUSTOM_DATE",
payload: {
activeBets,
settledBets
}
});
export const clearAllFiltersGtm = (
activeFilter: string,
activeBets: number,
settledBets: number
) =>
mediator.base.dispatch({
type: "CLEAR_ALL_MYBETS_FILTERS",
payload: {
activeFilter,
activeBets,
settledBets
}
});
export const onNavigateToTrackGtm = (
selectedTab: string,
selectedSettledTab: string,
activeBetsCounter: number,
settledBetsCounter: number,
destinationUrl: string
) => {
mediator.base.dispatch({
type: "MYBETS_NAVIGATE_TO_TRACK",
payload: {
selectedTab,
selectedSettledTab,
activeBets: activeBetsCounter,
settledBets: settledBetsCounter,
destinationUrl
}
});
};
export const onRepeatBetGTM = (payload: PayloadRepeatBetGTM) => {
mediator.base.dispatch({
type: "MYBETS_REPEAT_BET",
payload
});
};
webpack://frontend-mybets/../../packages/sh-lib-my-bets/utils/service.ts
import { Dispatch } from "redux";
import { batch } from "react-redux";
import { TabItem } from "@tvg/ts-types/Common";
import { attempt, isError } from "lodash";
import { formatDateToMMDDYYYY } from "@tvg/formatter/dates";
import { NullaryFn, UnaryFn } from "@tvg/ts-types/Functional";
import {
setIsCustomTimeFrame,
setSelectedSettledTabMyBetsStandalone,
setSelectedTabMyBetsStandalone
} from "../redux/actions";
import { onTabClickGtm } from "./gtm";
import {
ActiveTabEnum,
SettledTabEnum,
SafeJSONParseArg,
StartTimerArgs
} from "./types";
import { clearAllFilters } from "./filters";
export const getEmptyStateTitle = (
selectedTab?: ActiveTabEnum,
selectedSettledTab?: SettledTabEnum,
isCustomTimeFrame?: boolean,
customStartDate?: Date,
customEndDate?: Date,
hasOtherFilters?: boolean
): string => {
const category = selectedTab === ActiveTabEnum.ACTIVE ? "active" : "Settled";
const isSettledTab = selectedTab === ActiveTabEnum.SETTLED;
let since = "";
if (isSettledTab && isCustomTimeFrame) {
if (customStartDate && customEndDate) {
if (hasOtherFilters) {
return "No filtered Settled Bets for the selected dates";
}
return `No Settled Bets from ${formatDateToMMDDYYYY(
customStartDate
)} to ${formatDateToMMDDYYYY(customEndDate)}`;
}
if (!customStartDate) {
return "No Settled Bets for the selected dates";
}
}
switch (selectedSettledTab) {
case SettledTabEnum.TODAY:
since = "for today";
break;
case SettledTabEnum.YESTERDAY:
since = "since yesterday";
break;
case SettledTabEnum.LAST_WEEK:
since = "since last week";
break;
case SettledTabEnum.LAST_MONTH:
since = "since last month";
break;
default:
since = "for today";
}
return `No ${category} ${
selectedTab === ActiveTabEnum.SETTLED ? `Bets ${since}` : "bets"
}`;
};
export const getEmptyStateMessage = (selectedTab?: ActiveTabEnum): string =>
`${
selectedTab === ActiveTabEnum.ACTIVE
? "Currently you don't have active bets."
: ""
}`;
export const switchToActiveBets = (
dispatch: Dispatch,
selectedTab: string,
totalActiveBets: number,
totalSettledBets: number
) => {
if (selectedTab !== ActiveTabEnum.ACTIVE) {
batch(() => {
dispatch(setSelectedTabMyBetsStandalone(ActiveTabEnum.ACTIVE));
clearAllFilters(dispatch);
dispatch(setIsCustomTimeFrame(false));
dispatch(setSelectedSettledTabMyBetsStandalone(SettledTabEnum.TODAY));
});
onTabClickGtm({
selectedTab: ActiveTabEnum.ACTIVE,
selectedSettledTab: "None",
activeBetsCount: totalActiveBets,
settledBetsCount: totalSettledBets,
previousSelectedTab: selectedTab
});
}
};
export const switchToSettledBets = (
dispatch: Dispatch,
selectedTab: string
) => {
if (selectedTab !== ActiveTabEnum.SETTLED) {
batch(() => {
dispatch(setSelectedTabMyBetsStandalone(ActiveTabEnum.SETTLED));
dispatch(setSelectedSettledTabMyBetsStandalone(SettledTabEnum.TODAY));
});
}
};
export const switchToFutureBets = (dispatch: Dispatch, selectedTab: string) => {
if (selectedTab !== ActiveTabEnum.FUTURES) {
batch(() => {
dispatch(setSelectedTabMyBetsStandalone(ActiveTabEnum.FUTURES));
dispatch(setSelectedSettledTabMyBetsStandalone(SettledTabEnum.TODAY));
});
}
};
export const switchTimeframe = (
selectedSettledTabID: SettledTabEnum,
dispatch: Dispatch
) => {
dispatch(setSelectedTabMyBetsStandalone(ActiveTabEnum.SETTLED));
dispatch(setSelectedSettledTabMyBetsStandalone(selectedSettledTabID));
};
export const buildTabs = (
totalActiveBets: number,
totalFutureBets: number,
selectedTab: ActiveTabEnum,
dispatch: Dispatch
): TabItem[] => {
const tabItems: TabItem[] = [
{
title: "Active",
isTitleUppercase: false,
isActive: selectedTab === ActiveTabEnum.ACTIVE,
counter: totalActiveBets,
onClick: () =>
switchToActiveBets(
dispatch,
selectedTab,
totalActiveBets,
totalFutureBets
),
qaLabel: "bets-active-tab"
},
{
title: "Settled",
isTitleUppercase: false,
isActive: selectedTab === ActiveTabEnum.SETTLED,
counter: 0,
onClick: () => switchToSettledBets(dispatch, selectedTab),
qaLabel: "bets-settled-tab"
}
];
const futureBetsTabItem = {
title: "Futures",
isTitleUppercase: false,
isActive: selectedTab === ActiveTabEnum.FUTURES,
counter: totalFutureBets,
onClick: () => switchToFutureBets(dispatch, selectedTab),
qaLabel: "bets-futures-tab"
};
if (totalFutureBets > 0) {
tabItems.splice(1, 0, futureBetsTabItem);
}
return tabItems;
};
export const buildTimeFrameTabs = (
selectedSettledTab: SettledTabEnum,
isLoading: boolean,
dispatch: Dispatch
): TabItem[] => {
const timeFrames: { title: string; id: SettledTabEnum }[] = [
{ title: "Today", id: SettledTabEnum.TODAY },
{ title: "Since Yesterday", id: SettledTabEnum.YESTERDAY },
{ title: "Since Last Week", id: SettledTabEnum.LAST_WEEK },
{ title: "Since Last Month", id: SettledTabEnum.LAST_MONTH }
];
return timeFrames.map((timeFrame) => ({
id: timeFrame.id,
title: timeFrame.title,
isTitleUppercase: false,
isActive: selectedSettledTab === timeFrame.id,
isDisabled: isLoading,
counter: 0,
onClick: () => {
switchTimeframe(timeFrame.id, dispatch);
},
qaLabel: `bets-settled-${timeFrame.id.toLowerCase()}-tab`
}));
};
export const safeJSONParse = <Type = Object>({
defaultValue,
jsonToParse
}: SafeJSONParseArg): Type => {
let result = attempt(() => JSON.parse(jsonToParse));
if (isError(result)) {
result = defaultValue;
}
return result || {};
};
interface GtimerType {
timer: number | null;
clearTimer: NullaryFn<void>;
startTimer: UnaryFn<StartTimerArgs, void>;
}
const GenericTimer: GtimerType = {
timer: null,
clearTimer() {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
},
startTimer({ time, fn }) {
this.clearTimer();
// @ts-ignore
this.timer = setTimeout(() => {
fn();
}, time);
}
};
export const createTimer = () => Object.create(GenericTimer);
export const shouldRedirectToSettled = (
isLoadingActiveTotals: boolean,
totalActiveBets: number,
totalFutureBets: number,
firstRender: { current: boolean },
dispatch: Dispatch,
selectedTab: string,
redirectWithoutActiveBetsToggle?: boolean
) => {
if (firstRender.current) {
if (
isLoadingActiveTotals !== undefined &&
!isLoadingActiveTotals &&
redirectWithoutActiveBetsToggle
) {
if (totalActiveBets === 0 && totalFutureBets === 0) {
switchToSettledBets(dispatch, selectedTab);
// eslint-disable-next-line no-param-reassign
firstRender.current = false;
} else if (totalActiveBets > 0) {
dispatch(setSelectedTabMyBetsStandalone(ActiveTabEnum.ACTIVE));
} else if (totalFutureBets > 0) {
switchToFutureBets(dispatch, selectedTab);
// eslint-disable-next-line no-param-reassign
firstRender.current = false;
}
}
if (isLoadingActiveTotals !== undefined && !isLoadingActiveTotals) {
// eslint-disable-next-line no-param-reassign
firstRender.current = false;
}
}
};
webpack://frontend-mybets/../../packages/sh-lib-my-bets/utils/types.ts
import { Dispatch } from "redux";
import { Location, History } from "history";
import { UnaryFn, BinaryFn, NullaryFn } from "@tvg/ts-types/Functional";
import {
RaceInfoMyBets,
RaceStatusEnum,
BettingInterest,
PickBetFavorite,
RaceProgram
} from "@tvg/ts-types/Race";
import { BetSelection, BetBasicInfo, BetStatus } from "@tvg/ts-types/Bet";
import { ApolloClient, NormalizedCacheObject } from "@apollo/client";
import { WroWager, WroWagerGroup } from "@tvg/ts-types/WroWager";
import { Selections } from "@tvg/ts-types/Selections";
import { NavigationLayoutType } from "@tvg/ts-types/Generic";
import { WagerTypeCodesEnum } from "@tvg/ts-types/Wager";
export enum ActiveTabEnum {
ACTIVE = "ACTIVE",
SETTLED = "SETTLED",
FUTURES = "FUTURES"
}
export enum SettledTabEnum {
TODAY = "TODAY",
YESTERDAY = "YESTERDAY",
LAST_WEEK = "LAST_WEEK",
LAST_MONTH = "LAST_MONTH"
}
export enum MyBetsPastPerformanceTab {
BETS = "bets",
RESULTS = "results",
FULL_RESULT = "fullresult",
RACECARD = "racecard"
}
export interface MyBetsDynamicFilter {
name: string;
code: string;
isActive: boolean;
}
export type MyBetsDynamicFilters = MyBetsDynamicFilter[];
export interface QueryTrackFilter {
name: string;
code: string;
}
export interface QueryBetTypeFilter {
id: number;
name: string;
code: string;
}
export interface GraphWagerType {
type: {
code: string;
};
isKey: boolean;
isBox: boolean;
isWheel: boolean;
legCount: number;
positionCount: number;
columnCount: number;
}
export interface GraphResponse {
raceDate: string;
wagerTypes: GraphWagerType[];
races: RaceInfoMyBets[];
subscribeToMore: UnaryFn<unknown, void>;
loading: boolean;
networkStatus: number;
refetch: UnaryFn<unknown, void>;
}
export interface ActiveBetsInfoType {
bets?: WroWagerGroup[];
totalBets?: number;
totalAmount?: number;
}
export interface BetCancelResult {
status?: "success" | "failure" | "aborted";
errorCode?: string;
}
export interface OnBetCancelClosePayload {
result?: BetCancelResult;
}
export interface StatusFilters {
Cancelled: boolean;
Won: boolean;
Refunded: boolean;
Lost: boolean;
}
export interface BetCancelRedux {
betAmount?: number;
betsNumber?: number;
bettingInterests?: number[];
cancelRequestError?: unknown;
dateDiff?: number;
index?: number;
isGreyhound?: boolean;
isLoading?: boolean;
isOpen?: boolean;
mtp?: number;
queryError?: unknown;
raceNumber?: string;
racePostTime?: string;
result?: BetCancelResult;
statusCode?: RaceStatusEnum;
trackCode?: string;
trackName?: string;
wager?: WroWager;
winningsAmount?: number;
}
interface RulesMessage {
text: string;
title?: string;
}
export interface ExternalProps {
behgClient?: ApolloClient<NormalizedCacheObject>;
isDesktop: boolean;
accountNumber: string;
}
export interface Props {
dispatch: Dispatch;
location: Location;
history: History;
device: "mobile" | "tablet" | "desktop";
isLogged: boolean;
accountNumber: string;
behgClient?: ApolloClient<NormalizedCacheObject>;
fcpClient?: ApolloClient<NormalizedCacheObject>;
totalActiveBets: number;
totalFutureBets: number;
totalSettledBets: number;
activeWageredAmount: number;
futureWageredAmount: number;
settledWageredAmount: number;
selectedTab: ActiveTabEnum;
selectedSettledTab: SettledTabEnum;
// Graph types
isLoadingGraph: boolean;
subscribeToMore: UnaryFn<unknown, void>;
subscribeToMoreGraph: UnaryFn<unknown, void>;
queryBets: ActiveBetsInfoType;
races: RaceInfoMyBets[];
// Conditional for dates fix in IOS
betCancel: BetCancelRedux;
raceDate: string;
isMyBetsModalOpen: boolean;
wagerCancellationModal: {
isOpen: boolean;
hasBack: boolean;
};
trackRulesModal: {
isOpen: boolean;
betType: string;
};
userLocation: string;
cancelRulesMessages: Record<string, Array<RulesMessage>>;
cancelLimitationsByState?: string;
// Race Results
trackRulesMessages: string;
fetchMore: BinaryFn<UnaryFn<boolean, void>, number, void>;
isLoadingBehg: boolean;
myBetsPaginationConf: {
wagersPerPage: number;
intersectionWagerPercentage: number;
};
modalScrollableRef: HTMLDivElement;
isMyBetsPastPerformanceOpen: boolean;
isLoading: boolean;
isLoadingActiveTotals: boolean;
isLoadingSettledTotals: boolean;
scrollYPosition: number;
customStartDate?: string;
customEndDate?: string;
statusFilters?: StatusFilters;
refetchSettled?: NullaryFn<void>;
trackFilters?: MyBetsDynamicFilters;
betTypeFilters?: MyBetsDynamicFilters;
wagerProfile: string;
isCustomTimeFrame?: boolean;
isDesktop?: boolean;
redirectWithoutActiveBetsToggle?: boolean;
isDefaultSettled: boolean;
isDefaultFuture: boolean;
statusFilterCount: number;
trackFilterCount: number;
betTypeFilterCount: number;
queryTrackList: Array<QueryTrackFilter & QueryBetTypeFilter>;
wagerTypeFilter: Array<QueryTrackFilter & QueryBetTypeFilter>;
}
export interface BetCanceDataCommonInfo {
trackCode: string;
trackName: string;
raceNumber: number;
isGreyhound: boolean;
racePostTime: string;
mtp: number;
statusCode: RaceStatusEnum;
betsNumber: number;
betAmount: number;
dateDiff: number;
winningsAmount: number;
bettingInterests: BettingInterest[][];
}
export interface OnBetCancelPayload {
bet: WroWagerGroup;
wager: WroWager;
hasBackgroundModal?: boolean;
}
export interface OnRacePageBetCancelPayload {
bet: { value: string; wagers: Array<BetBasicInfo> };
wager: BetBasicInfo;
}
export type OnCancelFunction = UnaryFn<OnBetCancelPayload, void>;
export interface SafeJSONParseArg<T = Object> {
defaultValue: T;
jsonToParse: string;
}
export interface StartTimerArgs {
time: number;
fn: NullaryFn<void>;
}
export interface MyBetsBaseGtm {
selectedTab?: string;
selectedSettledTab?: string;
show?: boolean;
activeBetsCount?: number;
settledBetsCount?: number;
futureBetsCount?: number;
previousSelectedTab?: string;
}
export interface OnWatchReplayEvent {
trackName: string;
raceNumber: number;
index: number;
}
export type BetComboHash = Record<string, number>;
export type ProbableValueList = number[];
export interface PotentialReturn {
betSelections: string[][];
betCombosHash: Record<string, number>;
minWagerAmount: number;
betAmount: number;
wagerTypeId?: number;
}
export interface CheckRaceStatus {
isAllRunnersScratched: boolean;
legContainsScratch: boolean;
isMultiRace: boolean;
selectionIndex: number;
selection: BetSelection[] | Selections[];
races: RaceInfoMyBets[];
raceNumber: number;
selectionLength: number;
isCanceled: boolean;
betStatusName?: string;
wagerType: string;
favoriteRunner?: PickBetFavorite;
shouldShowReplacement: boolean;
}
export interface CheckSelectionLabel {
raceNumber: number;
selectionLength: number;
selectionIndex: number;
selectionsModifier?: string;
isMultiRace: boolean;
isKey?: boolean;
isBox?: boolean;
isDesktop?: boolean;
isSpecialWager?: boolean;
}
export type MyBetsCounterType = { counter: number; amount: number };
type FooterLinkType = {
name: string;
href: string;
onClick?: NullaryFn<unknown>;
};
export interface FooterProps {
dispatch: Dispatch;
isLogged: boolean;
accountNumber: string;
totalActiveBets: number;
links: FooterLinkType[];
activePath: string;
layout: NavigationLayoutType;
behgClient: ApolloClient<NormalizedCacheObject>;
subscribeToMore: UnaryFn<unknown, void>;
selectedTab: ActiveTabEnum;
selectedSettledTab: SettledTabEnum;
subscribeToMoreSettled: UnaryFn<unknown, void>;
refetchSettled: NullaryFn<void>;
activeBetsCounter: number;
isCustomTimeFrame?: boolean;
customStartDate?: Date;
customEndDate?: Date;
}
export interface SelectedFilters {
statusFilters?: StatusFilters;
trackFilters?: MyBetsDynamicFilters;
betTypeFilters?: MyBetsDynamicFilters;
}
export type OnBetSocialSharePayload = {
bet: WroWagerGroup;
wager: WroWager;
currentRace?: RaceProgram;
repeatButtonSearch?: string;
isMyBets?: boolean;
};
export interface WagerGroup {
betStatus: BetStatus;
tvgRaceId: number;
trackCode?: string;
}
export interface WagerHistory {
id: string;
futureWagersList: {
totals: {
totalCount: number;
totalAmount: number;
};
};
totals: {
totalBets: number;
totalAmount: number;
totalGambledCount: number;
totalGambledAmount: number;
};
groupWagers?: {
wagers: WagerGroup[];
}[];
}
export interface WagerHistoryProps {
wagerHistory: WagerHistory;
}
export interface BetsType {
totalActiveBets?: number;
totalFutureBets?: number;
activeWageredAmount?: number;
futureWageredAmount?: number;
}
export type XsellBlacklistedBets = {
blacklistedBets: [WagerTypeCodesEnum];
};
webpack://frontend-mybets/../../packages/sh-lib-preferences/utils/types.ts
import { AlertInlineVariants } from "@tvg/design-system/src/components/alertInline/types";
export type NullaryFn<R> = () => R;
export type UnaryFn<A, R> = (a: A) => R;
export type BinaryFn<A, B, R> = (a: A, b: B) => R;
export type TernaryFn<A, B, C, R> = (a: A, b: B, c: C) => R;
export type QuadFn<A, B, C, D, R> = (a: A, b: B, c: C, d: D) => R;
export type QuinFn<A, B, C, D, F, R> = (a: A, b: B, c: C, d: D, f: F) => R;
export type ConfirmationModalType = "BETTING" | "NOTIFICATIONS" | "";
export enum PreferencesTabEnum {
ACCOUNT = "ACCOUNT",
NOTIFICATIONS = "NOTIFICATIONS",
BETTING = "BETTING",
HOMEPAGE_CONFIG = "HOMEPAGE_LAYOUTS"
}
export type GraphWagerType = {
type: {
id: number;
name: string;
};
};
export type GraphResponse = {
wagerTypes: GraphWagerType[];
};
enum WagerGroupsEnum {
WIN = "10",
PLACE = "20",
SHOW = "30",
EXACTA = "110",
TRIFECTA = "160",
SUPERFECTA = "210",
SUPERHIGHFIVE = "260",
PICK = "P"
}
type WagerGroupTypes =
| WagerGroupsEnum.WIN
| WagerGroupsEnum.PLACE
| WagerGroupsEnum.SHOW
| WagerGroupsEnum.EXACTA
| WagerGroupsEnum.TRIFECTA
| WagerGroupsEnum.SUPERFECTA
| WagerGroupsEnum.SUPERHIGHFIVE
| WagerGroupsEnum.PICK;
export type WagerGroups = {
[key in WagerGroupTypes]: WagerGroupsItem;
};
export type PreferencesBetAmount = {
"10": string;
"20": string;
"30": string;
"110": string;
"160": string;
"210": string;
"260": string;
P: string;
};
export type WagerGroupsItem = {
errorMessage?: string;
group: string;
title: string;
value: string;
};
export type DefaultBetPrefs = {
defaultBetType: string;
useMinimumBetAmount: boolean;
useCustomBetAmount: boolean;
default_bet_amount: PreferencesBetAmount;
};
export type AlertTypePref =
| AlertInlineVariants
| "error-single"
| "success.mute"
| "success.unmute"
| "error.mute"
| "error.unmute";
export type AlertPrefs = {
show: boolean;
type: AlertTypePref;
isToggling: boolean;
shouldShowButton?: boolean;
};
export type BettingCapi = {
betConfirmation: {
title: string;
titlePick?: string;
description: string;
label: string;
labelPick?: string;
};
betType: {
title: string;
};
betAmount: {
title: string;
label: Array<string>;
message: string;
placeholder: string;
};
resetButton: string;
};
export type NotificationsCapi = {
raceAlerts: {
title: string;
description: string;
label: [string, string, string];
footer: Array<string>;
};
offersNews: {
title: string;
description: string;
label: Array<string>;
};
promotionActivity: {
title: string;
description: string;
label: Array<string>;
};
talentPicks: {
title: string;
description: string;
label: Array<string>;
btnText: string;
};
other: {
title: string;
description: string;
label: Array<string>;
};
muteBtn: {
mute: string;
unmute: string;
};
alerts: {
error: {
title: string;
message: string;
};
};
};
export type AlertsCapi = {
error: {
title: string;
message: string;
hasButton: boolean;
};
"error-single": {
title: string;
message: string;
hasButton: boolean;
};
success: {
title: string;
message: string;
hasButton: boolean;
};
};
export interface ConfirmationModal {
isOpen: boolean;
type: ConfirmationModalType;
}
export interface ConfirmModalMessage {
BETTING: {
title: string;
firstParagraph: string;
btnText: string;
};
}
export enum ToggleStateEnum {
OFF = "0",
ON = "1"
}
export interface AccountPrefsMessage {
account: {
auth: {
title: string;
toggleTitle: string;
};
};
}
export interface HomepageConfigPrefsMessage {
title: string;
description: string;
}
export type RaceMtpAlertBlock = {
name: string;
onClick: () => void;
enable: boolean;
};
export type MtpOptions = "0" | "2" | "5";
export enum RaceMtpOptions {
zero = "0",
two = "2",
five = "5"
}
export type TalentAlertsCapi = {
headerMessage: string;
};
export type TalentType = {
isActive: boolean;
name: string;
phrases: Array<string>;
pictureUrl: string;
popularity: number;
talentId: string;
tvgAccountId: string;
};
export type SubscribedType = {
favoriteId: number;
entityDob: number;
entityName: string;
entityType: string;
subscriptions: Array<SubscriptionsType>;
};
export type SubscriptionsType = {
channels: Array<SubscriptionsChannelsType>;
eventType: string;
};
export type SubscriptionsChannelsType = {
type: string;
};
export enum NotificationSwitch {
push_offers_and_news = "offersPush",
email_offers_news = "offersEmail",
push_promotion_activity = "promoPush",
email_promotion_activity = "promoEmail",
talent_picks = "talentPicksPush",
push_fanduel_comms = "otherFanduelPush",
email_fanduel_comms = "otherFanduelEmail"
}
export type NotificationsSwitchState = {
[NotificationSwitch.push_offers_and_news]: boolean;
[NotificationSwitch.email_offers_news]: boolean;
[NotificationSwitch.push_promotion_activity]: boolean;
[NotificationSwitch.email_promotion_activity]: boolean;
[NotificationSwitch.talent_picks]: boolean;
[NotificationSwitch.push_fanduel_comms]: boolean;
[NotificationSwitch.email_fanduel_comms]: boolean;
};
export enum PushStringTypes {
push_offers_and_news = "push_offers_and_news",
push_promotion_activity = "push_promotion_activity",
talent_picks = "talent_picks",
push_fanduel_comms = "push_fanduel_comms"
}
export type PushTypes = {
[PushStringTypes.push_offers_and_news]?: boolean;
[PushStringTypes.push_promotion_activity]?: boolean;
[PushStringTypes.talent_picks]?: boolean;
[PushStringTypes.push_fanduel_comms]?: boolean;
};
export enum SubscriptionGroupEnum {
email_offers_news = "email_offers_news",
email_promotion_activity = "email_promotion_activity",
email_fanduel_comms = "email_fanduel_comms"
}
export type SubscriptionGroupType = {
name: SubscriptionGroupEnum;
isSubscribed: boolean;
};
export type EmailParams = {
accountId: string;
email: string;
category: SubscriptionGroupEnum;
};
type UnsubscribeBodyContent = {
description: string;
};
export interface MessageBlock {
name: string;
title: string;
bodyContent: UnsubscribeBodyContent[];
label?: string;
buttonTextPrimary?: string;
buttonTextSecondary: string;
secondaryUrl?: string;
}
export interface EmailUnsubscribeMessage {
unsubscribe: MessageBlock;
confirmation: MessageBlock;
error: MessageBlock;
fallback: MessageBlock;
subscriptionGroups: { [key: string]: string };
}
export type Address = {
streetNumber: string;
address1: string;
address2: string;
city: string;
stateAbbr: string;
zip: string;
};
export type User = {
accountNumber: string;
firstName: string;
lastName: string;
primaryPhone: string;
wagerStatus: number;
emailAddress: string;
homeAddress: Address;
signalProviderId: string;
userName: string;
profile: string;
pin: string;
};
export type LoginServerResponse = {
userDetails: User;
};
export type LoginSuccess = {
status: string;
data?: LoginServerResponse;
fromLogin?: boolean;
};
export type LoginError = {
status?: string;
message?: string;
redirectUrl?: string;
};
webpack://frontend-mybets/../../packages/sh-lib-geolocation/src/solus/utils.ts
import { get } from "lodash";
import {
createGeoTokenCookie,
createLicenseCached,
getGeoTokenCookie,
getLicenseCached,
clearGeoTokenCookie,
clearLicenseCached,
getTemporaryRelocateUserProcessId,
createTemporaryRelocateUserProcessId,
clearTemporaryRelocateUserProcessId
} from "@tvg/sh-utils/sessionUtils";
import { amplitudeRemovedGeoToken } from "@urp/amplitude/src/modules/geolocation/utils";
import {
GeoClientTokenStatus,
GeoComplyCacheEntries,
GeoStorageKey
} from "./types/solus";
export const geoDataMapped: GeoComplyCacheEntries = {
[GeoStorageKey.GEO_PACKET]: {
saveCache: createGeoTokenCookie,
removeCache: clearGeoTokenCookie,
getCache: getGeoTokenCookie
},
[GeoStorageKey.LICENSE]: {
saveCache: createLicenseCached,
removeCache: clearLicenseCached,
getCache: getLicenseCached
},
[GeoStorageKey.RELOCATE_ID]: {
saveCache: createTemporaryRelocateUserProcessId,
removeCache: clearTemporaryRelocateUserProcessId,
getCache: getTemporaryRelocateUserProcessId
}
};
export const setCacheGeoData = (
storageKey: GeoStorageKey,
storageValue: string
) => {
const saveCache = get(geoDataMapped, `${storageKey}.saveCache`);
if (typeof window !== "undefined" && typeof saveCache === "function") {
saveCache(storageValue);
}
};
export const cleanCacheGeoData = (removedBy?: string) => {
if (typeof window !== "undefined") {
if (removedBy) {
amplitudeRemovedGeoToken(removedBy);
}
Object.values(GeoStorageKey).forEach((geoStorageKey) => {
const removeCache = get(geoDataMapped, `${geoStorageKey}.removeCache`);
if (typeof removeCache === "function") {
removeCache();
}
});
}
};
export const getCacheGeoData = (storageKey: GeoStorageKey) => {
const getCache = get(geoDataMapped, `${storageKey}.getCache`);
let geoData = null;
if (typeof window !== "undefined" && typeof getCache === "function") {
geoData = getCache();
}
return geoData;
};
export const getPreviousTokenStatus = (tokenStatus?: boolean) => {
if (typeof tokenStatus === "undefined") {
return GeoClientTokenStatus.NO_TOKEN;
}
return tokenStatus
? GeoClientTokenStatus.SUCCESSFUL_TOKEN
: GeoClientTokenStatus.FAILED_TOKEN;
};
export const getCacheGeoClientLicense = () =>
getCacheGeoData(GeoStorageKey.LICENSE);
export const getCacheGeoPacket = () =>
getCacheGeoData(GeoStorageKey.GEO_PACKET);
// @deprecated
export const getGeoExpiryTime = (geolocateIn: number) => {
const MAX_GEOLOCATE_TIME = 300;
const MAX_GEOLOCATE_DIFF = geolocateIn - 30; // reduce by 30 seconds // 3570
const MIN_GEOLOCATE_DIFF = geolocateIn * 0.7; // reduce by 30% // 2499
const buffer =
geolocateIn >= MAX_GEOLOCATE_TIME ? MAX_GEOLOCATE_DIFF : MIN_GEOLOCATE_DIFF;
const bufferInMilliseconds = buffer * 1000;
return bufferInMilliseconds;
};
export const getGeoExpiryTimeByNow = (geolocateIn: number, expires: Date) => {
const now = Date.now();
const maxGeoLocateTime = getGeoExpiryTime(geolocateIn);
const expirationDiff = +expires - now;
if (expirationDiff > maxGeoLocateTime) {
return maxGeoLocateTime;
}
return Math.max(0, expirationDiff);
};
webpack://frontend-mybets/../../packages/sh-lib-utils/hybridBridge.ts
import mediator from "@tvg/mediator";
import decodeJWT from "jwt-decode";
import { BinaryFn } from "@tvg/ts-types/Functional";
import { get } from "lodash";
import {
GeolocationFailureError,
GeolocationRejectedError
} from "@tvg/sh-geolocation/src/types";
import { GeoLocationResponseSuccess } from "./types/GeoLocation";
import { GeolocationVerified, UpdatedToken } from "./types/generalTypes";
import { getAuthTokenCookie, isSessionExpired } from "./sessionUtils";
const openExternalLink = (uri: string) => {
mediator.ios.dispatch({
type: "OPEN_EXTERNAL_APP",
payload: { openExternalApp: uri }
});
};
const askLocation = () => {
mediator.ios.dispatch({ type: "ASK_LOCATION" });
};
const onTriggerGeolocation = (reason: string) => {
mediator.ios.dispatch({
type: "TRIGGER_GEOLOCATION",
payload: {
reason
}
});
};
const subscribeGeolocationRequest = (callback: Function) => {
mediator.ios.subscribe("GEOLOCATION_IN_PROGRESS", () => {
callback();
});
};
const subscribeLocationFailure = (callback: Function) => {
mediator.ios.subscribe(
"LOCATION_FAILURE",
(data: { payload: GeolocationFailureError }) => {
callback(data.payload?.geoErrorName);
}
);
};
const subscribeLocationRejected = (callback: Function) => {
mediator.ios.subscribe(
"GEOLOCATION_REJECTED",
(data: { payload: GeolocationRejectedError }) => {
const troubleshooters = data.payload?.troubleshooters;
const region = data.payload?.region;
callback(troubleshooters, region);
}
);
};
const subscribeGeolocationUpdate = (callback: Function) => {
mediator.ios.subscribe(
"GEOLOCATION_TOKEN_UPDATED",
(data: { payload: UpdatedToken }) => {
const token = data.payload.geolocationData?.geoToken;
return callback(token);
}
);
};
const subscribeLaunchInRegion = (
callback: BinaryFn<string | undefined, string, void>
) => {
mediator.ios.subscribe("LAUNCH_IN_REGION", callback);
};
const subscribeGeolocationVerified = (callback: Function) => {
mediator.ios.subscribe(
"GEOLOCATION_PASSED",
(data: { payload: GeolocationVerified }) => {
try {
const { region_code }: GeoLocationResponseSuccess = decodeJWT(
get(data, "payload.geoToken", "")
);
const token = data.payload?.geoToken;
callback(token, region_code);
} catch (error) {
console.error("Error decompile geocomply: ", error);
}
}
);
};
const subscribeWebViewForeground = () => {
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible") {
const authToken = getAuthTokenCookie();
if (isSessionExpired(authToken)) {
mediator.base.dispatch({ type: "TRIGGER_LOGOUT" });
}
}
});
};
export default {
openExternalLink,
askLocation,
onTriggerGeolocation,
subscribeGeolocationRequest,
subscribeGeolocationVerified,
subscribeGeolocationUpdate,
subscribeLocationFailure,
subscribeLocationRejected,
subscribeLaunchInRegion,
subscribeWebViewForeground
};
webpack://frontend-mybets/../../packages/sh-lib-utils/mobileUtils.ts
import TvgConfig from "@tvg/conf";
import mediator from "@tvg/mediator";
import { BinaryFn } from "@tvg/ts-types/Functional";
import { PRODUCTS_FDR_X_SELL, PRODUCTS_FDR } from "@tvg/conf/src/product";
import {
GeolocationFailureError,
GeolocationRejectedError
} from "@tvg/sh-geolocation/src/types";
import { cleanCacheGeoData } from "@tvg/sh-geolocation/src/solus/utils";
import xSellBridge from "./xSellBridge";
import hybridBridge from "./hybridBridge";
import { GeolocationVerified, UpdatedToken } from "./types/generalTypes";
export const isXSell = (product?: string) =>
PRODUCTS_FDR_X_SELL.includes(product || TvgConfig().product);
export const isMobile = (product?: string) =>
["fdrios", "fdrandroid", "fdrandroidgps", "androidwrapper"].includes(
product || TvgConfig().product
) || isXSell(product);
export const isIos = (product?: string) =>
["fdrios", "fdriosxsell"].includes(product || TvgConfig().product);
export const isAndroid = (product?: string) =>
["fdrandroid", "androidwrapper", "fdrandroidxsell", "fdrandroidgps"].includes(
product || TvgConfig().product
);
export const isMobileServerSide = () => {
if (typeof window === "undefined") {
return PRODUCTS_FDR.some((product) => product === TvgConfig().product);
}
return false;
};
export const isFdrProduct = () =>
PRODUCTS_FDR.some((product) => product === TvgConfig().product);
export const getAppBridge = () => {
if (!isMobile()) return null;
return isXSell() ? xSellBridge : hybridBridge;
};
export const buildUrl = (url: string) => {
const fullUrlPattern = /^https?:\/\//;
const relativeUrlPattern = /^\/.+/;
const emailOrTelPattern = /^(mailto|tel|sms):.+/;
let fullUrl = (url ?? "").trim();
if (relativeUrlPattern.test(fullUrl) && typeof window !== "undefined") {
fullUrl = `${window.location.protocol}//${window.location.host}${fullUrl}`;
} else if (
!fullUrlPattern.test(fullUrl) &&
!emailOrTelPattern.test(fullUrl)
) {
fullUrl = `http://${fullUrl}`;
}
return fullUrl;
};
export const openExternalLink = (link: string) => {
const appBridge = getAppBridge();
if (appBridge) {
appBridge.openExternalLink(buildUrl(link));
} else if (window) {
// eslint-disable-next-line security/detect-non-literal-fs-filename
const tab = window.open(link, "_blank");
tab?.focus();
}
};
export const askLocation = (reason: string = "") => {
const appBridge = getAppBridge();
if (!appBridge) {
console.error("[askLocation]: App bridge not in use!");
} else {
appBridge.askLocation(reason);
}
};
export const onTriggerGeolocation = (reason: string) => {
const appBridge = getAppBridge();
if (!appBridge) {
const type =
reason === "login" || "Normal" ? "GEOCOMPLY_REQUEST" : "GEOCOMPLY_RETRY";
if (type === "GEOCOMPLY_RETRY") {
cleanCacheGeoData();
}
mediator.base.dispatch({
type
});
} else {
appBridge.onTriggerGeolocation(reason);
}
};
export const subscribeGeolocationUpdate = (callback: Function) => {
const appBridge = getAppBridge();
if (!appBridge) {
mediator.base.subscribe(
"GEOCOMPLY_UPDATE",
(data: { payload: UpdatedToken }) => {
const token = data.payload.geolocationData?.geoToken;
return callback(token);
}
);
} else {
appBridge.subscribeGeolocationUpdate(callback);
}
};
export const subscribeGeolocationRequest = (callback: Function) => {
const appBridge = getAppBridge();
if (appBridge) {
appBridge.subscribeGeolocationRequest(callback);
} else {
mediator.base.subscribe("GEOCOMPLY_REQUEST", () => {
callback();
});
}
};
export const subscribeGeolocationVerified = (callback: Function) => {
if (isXSell()) {
return;
}
if (isMobile()) {
hybridBridge.subscribeGeolocationVerified(callback);
} else {
mediator.base.subscribe(
"GEOCOMPLY_VERIFIED",
(data: { payload: GeolocationVerified }) => {
const region = data.payload?.region;
const token = data.payload?.geoToken;
callback(token, region);
}
);
}
};
export const subscribeLocationFailure = (callback: Function) => {
if (isXSell()) {
return;
}
if (isMobile()) {
hybridBridge.subscribeLocationFailure(callback);
} else {
mediator.base.subscribe(
"GEOCOMPLY_FAILURE",
(data: { payload: GeolocationFailureError }) => {
callback(data.payload?.geoErrorName);
}
);
}
};
export const subscribeLocationRejected = (callback: Function) => {
if (isXSell()) {
return;
}
if (isMobile()) {
hybridBridge.subscribeLocationRejected(callback);
} else {
mediator.base.subscribe(
"GEOCOMPLY_REJECT",
(data: { payload: GeolocationRejectedError }) => {
const troubleshooters = data.payload?.troubleshooters;
const region = data.payload?.region;
callback(troubleshooters, region);
}
);
}
};
export const subscribeGeolocationRetry = (callback: Function) => {
if (!isMobile()) {
mediator.base.subscribe("GEOCOMPLY_RETRY", () => {
callback();
});
}
};
export const subscribeLaunchInRegion = (
callback: BinaryFn<string | undefined, string, void>
) => {
const appBridge = getAppBridge();
if (appBridge) {
appBridge.subscribeLaunchInRegion(callback);
}
};
export const subscribeWebViewForeground = () => {
const appBridge = getAppBridge();
if (appBridge) {
appBridge.subscribeWebViewForeground();
}
};
webpack://frontend-mybets/../../node_modules/universal-cookie/es6/utils.js
import * as cookie from 'cookie';
export function hasDocumentCookie() {
// Can we get/set cookies on document.cookie?
return typeof document === 'object' && typeof document.cookie === 'string';
}
export function cleanCookies() {
document.cookie.split(';').forEach(function (c) {
document.cookie = c
.replace(/^ +/, '')
.replace(/=.*/, '=;expires=' + new Date().toUTCString() + ';path=/');
});
}
export function parseCookies(cookies, options) {
if (typeof cookies === 'string') {
return cookie.parse(cookies, options);
}
else if (typeof cookies === 'object' && cookies !== null) {
return cookies;
}
else {
return {};
}
}
export function isParsingCookie(value, doNotParse) {
if (typeof doNotParse === 'undefined') {
// We guess if the cookie start with { or [, it has been serialized
doNotParse =
!value || (value[0] !== '{' && value[0] !== '[' && value[0] !== '"');
}
return !doNotParse;
}
export function readCookie(value, options = {}) {
const cleanValue = cleanupCookieValue(value);
if (isParsingCookie(cleanValue, options.doNotParse)) {
try {
return JSON.parse(cleanValue);
}
catch (e) {
// At least we tried
}
}
// Ignore clean value if we failed the deserialization
// It is not relevant anymore to trim those values
return value;
}
function cleanupCookieValue(value) {
// express prepend j: before serializing a cookie
if (value && value[0] === 'j' && value[1] === ':') {
return value.substr(2);
}
return value;
}
webpack://frontend-mybets/../../packages/sh-lib-utils/cookieUtils.ts
import tvgConf from "@tvg/conf";
import Cookies from "universal-cookie";
export const cookies = new Cookies();
export const getDomainForCookie = () => {
let cookieDomain: string | undefined;
if (typeof window !== "undefined") {
const domain = window.location.hostname;
const environment = tvgConf().environment as string;
cookieDomain = ["local", environment].some((env) => domain.startsWith(env))
? domain.substring(domain.indexOf("."))
: `.${domain}`;
}
return cookieDomain;
};
const getDomainWithoutSubdomain = () => {
if (typeof window === "undefined") return undefined;
const hostnameParts = window.location.hostname.split(".");
const domainWithoutSubdomain = hostnameParts.slice(-2).join(".");
return `.${domainWithoutSubdomain}`;
};
export const getCookieOptions = (removeSubdomain = false) => ({
domain: !removeSubdomain ? getDomainForCookie() : getDomainWithoutSubdomain(),
path: "/",
doNotParse: false
});
export const addCookie = (
cookieName: string,
cookieValue: string,
maxAge?: number,
removeSubdomain = false
): void => {
if (getCookieValue(cookieName)) {
removeCookie(cookieName);
}
cookies.set(cookieName, cookieValue, {
...getCookieOptions(removeSubdomain),
maxAge
});
};
export const getCookieValue = <T = string>(
cookieName: string,
defaultValue?: T,
forceParse = true
): T =>
cookies.get(cookieName, {
...getCookieOptions(),
doNotParse: !forceParse
}) || defaultValue;
export const removeCookie = (cookieName: string): void => {
cookies.remove(cookieName, getCookieOptions());
};
webpack://frontend-mybets/../../node_modules/universal-cookie/es6/Cookies.js
import * as cookie from 'cookie';
import { hasDocumentCookie, parseCookies, readCookie } from './utils';
export default class Cookies {
constructor(cookies, options) {
this.changeListeners = [];
this.HAS_DOCUMENT_COOKIE = false;
this.cookies = parseCookies(cookies, options);
new Promise(() => {
this.HAS_DOCUMENT_COOKIE = hasDocumentCookie();
}).catch(() => { });
}
_updateBrowserValues(parseOptions) {
if (!this.HAS_DOCUMENT_COOKIE) {
return;
}
this.cookies = cookie.parse(document.cookie, parseOptions);
}
_emitChange(params) {
for (let i = 0; i < this.changeListeners.length; ++i) {
this.changeListeners[i](params);
}
}
get(name, options = {}, parseOptions) {
this._updateBrowserValues(parseOptions);
return readCookie(this.cookies[name], options);
}
getAll(options = {}, parseOptions) {
this._updateBrowserValues(parseOptions);
const result = {};
for (let name in this.cookies) {
result[name] = readCookie(this.cookies[name], options);
}
return result;
}
set(name, value, options) {
if (typeof value === 'object') {
value = JSON.stringify(value);
}
this.cookies = Object.assign(Object.assign({}, this.cookies), { [name]: value });
if (this.HAS_DOCUMENT_COOKIE) {
document.cookie = cookie.serialize(name, value, options);
}
this._emitChange({ name, value, options });
}
remove(name, options) {
const finalOptions = (options = Object.assign(Object.assign({}, options), { expires: new Date(1970, 1, 1, 0, 0, 1), maxAge: 0 }));
this.cookies = Object.assign({}, this.cookies);
delete this.cookies[name];
if (this.HAS_DOCUMENT_COOKIE) {
document.cookie = cookie.serialize(name, '', finalOptions);
}
this._emitChange({ name, value: undefined, options });
}
addChangeListener(callback) {
this.changeListeners.push(callback);
}
removeChangeListener(callback) {
const idx = this.changeListeners.indexOf(callback);
if (idx >= 0) {
this.changeListeners.splice(idx, 1);
}
}
}
webpack://frontend-mybets/../../packages/sh-lib-utils/sessionUtils.ts
import { Store } from "redux";
import jwt_decode from "jwt-decode";
import { get } from "lodash";
import { fromUnixTime, isAfter } from "date-fns";
import { PRODUCTS_FDR } from "@tvg/conf/src/product";
import tvgConf from "@tvg/conf";
import { amplitudeRemovedGeoToken } from "@urp/amplitude/src/modules/geolocation/utils";
import { addCookie, getCookieValue, removeCookie } from "./cookieUtils";
interface AuthToken {
ses: number;
sub: number;
usn: string;
prd: string;
crt: number;
eml: string;
src: number;
mfa: boolean;
typ: number;
exp: number;
}
// como divido este? um com as coisas genericas, outro AUTH_TOKEN_COOKIE, LOGIN_TOKEN_COOKIE e WRAPPER_CONFIG_COOKIE,e outro com o resto
export const AUTH_TOKEN_COOKIE = "X-Auth-Token";
export const LOGIN_TOKEN_COOKIE = "X-Login-Token";
export const GEO_TOKEN_COOKIE = "X-Geo-Token";
export const GEO_LICENSE_COOKIE = "X-Geo-License";
export const SPORTSBOOK_REGION_COOKIE = "X-Sportsbook-Region";
export const WRAPPER_CONFIG_COOKIE = "wrapperAppConfig";
export const GEO_RELOCATE_PROCESS_ID = "geoRelocateProcessId";
export const KEEP_LOGOUT_PATH_SESSION_STORAGE = "lkp";
export const isTvg5 = () => tvgConf().product === "tvg5";
const isFdrProduct = () =>
PRODUCTS_FDR.some((product) => product === tvgConf().product);
export const decodeToken = (token?: string): AuthToken | {} => {
try {
if (token) {
return jwt_decode(token);
}
return {};
} catch (erro) {
console.warn("Error trying decode jwt:", erro);
return {};
}
};
export const getUserSessionData = (authToken: string) => {
const tokenDecoded = decodeToken(authToken);
return {
authToken,
sessionId: get(tokenDecoded, "ses", ""),
sessionExpireDate: get(tokenDecoded, "exp", ""),
fdUserId: get(tokenDecoded, "sub", ""),
userName: get(tokenDecoded, "usn", ""),
userEmail: get(tokenDecoded, "eml", "")
};
};
export const getUserSessionStartDate = (
authToken?: string
): Date | undefined => {
const tokenDecoded: AuthToken | {} = decodeToken(authToken);
return authToken || authToken === "undefined"
? fromUnixTime(get(tokenDecoded, "crt", new Date()))
: undefined;
};
export const createAuthTokenCookie = (token: string) => {
addCookie(AUTH_TOKEN_COOKIE, token);
};
export const getAuthTokenCookie = () => getCookieValue(AUTH_TOKEN_COOKIE, "");
export const clearAuthTokenCookie = () => removeCookie(AUTH_TOKEN_COOKIE);
export const clearLoginTokenCookie = () => removeCookie(LOGIN_TOKEN_COOKIE);
export const getGeoTokenCookie = () => {
let geoToken = "";
if (typeof window !== "undefined") {
geoToken = localStorage.getItem(GEO_TOKEN_COOKIE) || "";
}
return geoToken;
};
export const createGeoTokenCookie = (token: string) => {
if (typeof window !== "undefined") {
localStorage.setItem(GEO_TOKEN_COOKIE, token);
}
};
export const setLogoutKeepPage = (keepCurrentPage: boolean) => {
if (typeof window !== "undefined") {
if (keepCurrentPage) {
sessionStorage.setItem(
KEEP_LOGOUT_PATH_SESSION_STORAGE,
`${+keepCurrentPage}`
);
} else {
sessionStorage.removeItem(KEEP_LOGOUT_PATH_SESSION_STORAGE);
}
}
};
export const getLogoutKeepPage = (): boolean => {
if (typeof window !== "undefined") {
return Boolean(sessionStorage.getItem(KEEP_LOGOUT_PATH_SESSION_STORAGE));
}
return false;
};
export const clearGeoTokenCookie = (removedBy?: string) => {
if (typeof window !== "undefined") {
if (removedBy) {
amplitudeRemovedGeoToken(removedBy);
}
localStorage.removeItem(GEO_TOKEN_COOKIE);
}
};
export const getLicenseCached = () => {
let license = "";
if (typeof window !== "undefined") {
license = localStorage.getItem(GEO_LICENSE_COOKIE) || "";
}
return license;
};
export const createLicenseCached = (token: string) => {
if (typeof window !== "undefined") {
localStorage.setItem(GEO_LICENSE_COOKIE, token);
}
};
export const clearLicenseCached = () => {
if (typeof window !== "undefined") {
localStorage.removeItem(GEO_LICENSE_COOKIE);
}
};
export const getTemporaryRelocateUserProcessId = () => {
let processId = "";
if (typeof window !== "undefined") {
processId = sessionStorage.getItem(GEO_RELOCATE_PROCESS_ID) || "";
}
return processId;
};
export const createTemporaryRelocateUserProcessId = (processId: string) => {
if (typeof window !== "undefined") {
sessionStorage.setItem(GEO_RELOCATE_PROCESS_ID, processId);
}
};
export const clearTemporaryRelocateUserProcessId = () => {
if (typeof window !== "undefined") {
sessionStorage.removeItem(GEO_RELOCATE_PROCESS_ID);
}
};
export const createSportsbookRegionCookie = (region: string) => {
addCookie(SPORTSBOOK_REGION_COOKIE, region);
};
export const getSportsbookRegionCookie = () =>
getCookieValue(SPORTSBOOK_REGION_COOKIE);
export const clearSportsbookRegionCookie = () => {
removeCookie(SPORTSBOOK_REGION_COOKIE);
};
export const getLoginAuthToken = () => getCookieValue(LOGIN_TOKEN_COOKIE);
export const isSessionExpired = (authToken: string) => {
const { sessionExpireDate } = getUserSessionData(authToken);
return isAfter(new Date(), fromUnixTime(sessionExpireDate));
};
export const isAccountCompliantSelector = (store: Store): boolean => {
const enableAWFlows = get(store, "capi.featureToggles.enableAWFlows", false);
const logged = get(store, "userData.logged");
const isVerified = get(store, "userData.isVerified");
const requiresVerification = (enableAWFlows && isTvg5()) || isFdrProduct();
if (logged && requiresVerification) {
return !!isVerified;
}
return !!logged;
};
export const checkValidWageringState = (
selectedState: string,
allowedStates: Array<string>
): boolean =>
!!selectedState && allowedStates && allowedStates.includes(selectedState);
export const createWrapperAppConfigCookie = (token: string) => {
addCookie(WRAPPER_CONFIG_COOKIE, token);
};
export const removeWrapperAppConfigCookie = () => {
removeCookie(WRAPPER_CONFIG_COOKIE);
};
export const getWrapperAppConfigCookie = () =>
getCookieValue<string | undefined>(WRAPPER_CONFIG_COOKIE, undefined, false);
webpack://frontend-mybets/../../node_modules/date-fns/esm/fromUnixTime/index.js
import toDate from '../toDate/index.js';
import toInteger from '../_lib/toInteger/index.js';
import requiredArgs from '../_lib/requiredArgs/index.js';
/**
* @name fromUnixTime
* @category Timestamp Helpers
* @summary Create a date from a Unix timestamp.
*
* @description
* Create a date from a Unix timestamp.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Number} unixTime - the given Unix timestamp
* @returns {Date} the date
* @throws {TypeError} 1 argument required
*
* @example
* // Create the date 29 February 2012 11:45:05:
* var result = fromUnixTime(1330515905)
* //=> Wed Feb 29 2012 11:45:05
*/
export default function fromUnixTime(dirtyUnixTime) {
requiredArgs(1, arguments);
var unixTime = toInteger(dirtyUnixTime);
return toDate(unixTime * 1000);
}
webpack://frontend-mybets/../../packages/sh-lib-utils/xSellBridge.ts
import mediator from "@tvg/mediator";
import { BinaryFn } from "@tvg/ts-types/Functional";
import { noop } from "lodash";
import { createAuthTokenCookie } from "./sessionUtils";
import { UpdatedToken, LaunchInRegionDataXSell } from "./types/generalTypes";
import { isValidSessionByTokenXSell } from "./isValidSessionByToken";
export const geolocationTokenUpdatedActionType =
"x-sell/bridge/to-native/geolocationTokenUpdated";
const isXSellLink = (url: string) => url.includes("/sportsbook");
const openExternalLink = (uri: string) => {
const isDeepLink = uri && isXSellLink(uri);
const event = isDeepLink
? {
type: "x-sell/bridge/to-react/onHandleUrl",
payload: { url: uri }
}
: {
type: "x-sell/bridge/to-react/onLoadExternalUrl",
payload: { webViewUrl: uri }
};
mediator.ios.dispatch(event);
};
const askLocation = (reason: string) => {
mediator.ios.dispatch({
type: "x-sell/bridge/to-react/onTriggerGeolocationRefresh",
payload: {
reason
}
});
};
const onTriggerGeolocation = (reason: string) => {
mediator.ios.dispatch({
type: "x-sell/bridge/to-react/onTriggerGeolocationRefresh",
payload: {
reason
}
});
};
const onTriggerSBMyBets = () =>
mediator.ios.dispatch({
type: "x-sell/bridge/to-react/onTriggerSBMyBets"
});
// XSell don't have way to understand if GeoComply is in progress
const subscribeGeolocationRequest = noop;
const subscribeGeolocationUpdate = (callback: Function) => {
const subscribeCallback = (data: { payload: UpdatedToken }) =>
callback(data.payload.geolocationData.geoToken);
mediator.ios.subscribe(geolocationTokenUpdatedActionType, subscribeCallback);
// trigged in subscribeLoginComplete
mediator.base.subscribe(geolocationTokenUpdatedActionType, subscribeCallback);
};
const subscribeLaunchInRegion = (
callback: BinaryFn<string | undefined, string, void>
) => {
mediator.ios.subscribe(
"x-sell/bridge/to-native/launchInRegion",
(data: { payload: LaunchInRegionDataXSell }) => {
const { authToken, sportsbookRegion } = data.payload;
if (authToken) {
createAuthTokenCookie(authToken);
}
callback(authToken, sportsbookRegion);
}
);
};
const subscribeWebViewForeground = () => {
document.addEventListener("visibilitychange", () => {
if (
document.visibilityState === "visible" &&
!isValidSessionByTokenXSell()
) {
mediator.base.dispatch({ type: "TRIGGER_LOGOUT" });
}
});
};
export default {
isXSellLink,
openExternalLink,
askLocation,
onTriggerGeolocation,
onTriggerSBMyBets,
subscribeGeolocationRequest,
subscribeGeolocationUpdate,
subscribeLaunchInRegion,
subscribeWebViewForeground
};
webpack://frontend-mybets/../../packages/sh-lib-utils/isValidSessionByToken.ts
import { PRODUCTS_FDR_X_SELL } from "@tvg/conf/src/product";
import TvgConfig from "@tvg/conf";
import { getAuthTokenCookie, isSessionExpired } from "./sessionUtils";
export const isXSell = () => PRODUCTS_FDR_X_SELL.includes(TvgConfig().product);
export const isValidSessionByToken = () =>
!isSessionExpired(getAuthTokenCookie());
export const isValidSessionByTokenXSell = () =>
isXSell() && isValidSessionByToken();
webpack://frontend-mybets/../../packages/tvg-lib-api/protocolSetter.ts
import { get } from "lodash";
const getProtocol = () => (get(global, "appConf", false) ? "https:" : "");
export default getProtocol;
webpack://frontend-mybets/../../packages/tvg-lib-api/requester/index.ts
import axios from "axios";
import { get } from "lodash";
import tvgConf from "@tvg/conf";
const instance = axios.create();
function getInstance() {
if (tvgConf().isRN) {
if (get(global, "session.sessionId")) {
instance.defaults.headers = {
// @ts-ignore
"tvg-session-id": get(global, "session.sessionId", null)
};
}
}
return instance;
}
export default getInstance;
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/aws-int/4njbets.ts
module.exports = {
domain: {
desktop: "4njbets-qa.us.betfair.com",
mobile: "4njbets-qa.us.betfair.com",
talentPicks: "4njbets-qa.us.betfair.com/talent-picks/",
equibase: "equibase-store-qa.us.betfair.com"
},
service_host: "service-qa.us.betfair.com",
recaptchaID: "6Lf-4hUqAAAAAGupa6W70kpZVsaFd7yaxz5pHD8r",
recaptchaIdNative: "6Le9B1YqAAAAAJEWJZsQittPtHDcjz6xLNORgHyI"
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/aws-int/base.ts
const {
AMPLITUDE_API_KEYS: AMPLITUDE_API_KEYS_INT
} = require("../../utils/urp/amplitude");
const {
AMPLITUDE_API_KEYS: AMPLITUDE_API_KEYS_FDR_INT,
AMPLITUDE_API_KEYS_XSELL: AMPLITUDE_API_KEYS_FDR_XSELL_INT
} = require("../../utils/fdr/amplitude");
const {
AMPLITUDE_API_KEYS: AMPLITUDE_API_KEYS_MEP_INT
} = require("../../utils/mep/amplitude");
const {
AMPLITUDE_API_KEYS: AMPLITUDE_API_KEYS_TVG4_INT
} = require("../../utils/tvg4/amplitude");
module.exports = {
domain: {
desktop: "www-qa.tvg.com",
mobile: "www-qa.tvg.com",
talentPicks: "www-qa.tvg.com/talent-picks/",
equibase: "equibase-store-qa.tvg.com"
},
externalDomain: {
support: "https://support.tvg.com",
contactSupport:
"https://support.tvg.com/tvg/s/articles/360005946853-Contact-Support",
NCPGamblingChat: "http://www.ncpgambling.org/chat"
},
service_host: "service-qa.tvg.com",
google: {
tvg4: {
gtmId: "KTDSBG",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "desktop",
productVersion: "TVG4"
},
tvg5: {
gtmId: "KTDSBG",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "desktop",
productVersion: "TVG5"
},
touch2: {
gtmId: "KTDSBG",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "mobile_web",
productVersion: "MEP"
},
touch3: {
gtmId: "KTDSBG",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "mobile_web",
productVersion: "MEP"
},
ios: {
gtmId: "KTDSBG",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "ios_native"
},
ios2: {
gtmId: "KTDSBG",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "ios_native"
},
fdrdesktop: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "desktop",
productVersion: "URP"
},
fdrmobile: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "mobile_web",
productVersion: "MEP"
},
fdrios: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "ios_native",
productVersion: "MEP"
},
fdrandroid: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "android_native",
productVersion: "android_apk"
},
fdrandroidwrapper: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "android_native",
productVersion: "android_apk"
},
fdrandroidgps: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "android_native",
productVersion: "android_apk"
},
fdriosxsell: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "x-sell",
productVersion: "MEP"
},
fdrandroidxsell: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "x-sell",
productVersion: "android_apk"
},
androidwrapper: {
gtmId: "KTDSBG",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "android_native",
productVersion: "android_gps"
},
tvgandroid: {
gtmId: "KTDSBG",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "android_native",
productVersion: "android_apk"
},
iosnative: {
gtmId: "KTDSBG",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "ios_native",
productVersion: "ios_native"
},
gcs: {
url: "https://storage.googleapis.com",
tvgStatic: "tvg-static-qa"
}
},
amplitude: {
tvg5: {
amplitudeAPI: AMPLITUDE_API_KEYS_INT.QA,
siteVersion: "desktop",
sitePlatform: "desktop",
product: "tvg_urp"
},
tvg5fdr: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_INT.QA,
siteVersion: "desktop",
sitePlatform: "desktop",
product: "fdr_standalone_lobby"
},
fdrmobile: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_INT.QA,
siteVersion: "mobile_web",
sitePlatform: "mobile_web",
product: "fdr_standalone_lobby"
},
fdrios: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_INT.QA,
siteVersion: "native",
sitePlatform: "ios",
product: "fdr_standalone_lobby"
},
fdrandroid: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_INT.QA,
siteVersion: "native",
sitePlatform: "android",
product: "fdr_standalone_lobby",
androidDistributionMethod: "self_dist"
},
fdrandroidwrapper: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_INT.QA,
siteVersion: "native",
sitePlatform: "android",
product: "fdr_standalone_lobby",
androidDistributionMethod: "google_playstore"
},
fdrandroidgps: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_INT.QA,
siteVersion: "native",
sitePlatform: "android",
product: "fdr_standalone_lobby",
androidDistributionMethod: "google_playstore"
},
fdriosxsell: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_XSELL_INT.QA,
siteVersion: "native",
sitePlatform: "ios",
product: "fdr_xsell_lobby"
},
fdrandroidxsell: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_XSELL_INT.QA,
siteVersion: "native",
sitePlatform: "android",
product: "fdr_xsell_lobby"
},
touch3: {
amplitudeAPI: AMPLITUDE_API_KEYS_MEP_INT.QA,
siteVersion: "mobile_web",
sitePlatform: "mobile_web",
product: "tvg_mep"
},
androidwrapper: {
amplitudeAPI: AMPLITUDE_API_KEYS_MEP_INT.QA,
siteVersion: "native",
sitePlatform: "android",
product: "tvg_mep",
androidDistributionMethod: "self_dist"
},
tvgandroid: {
amplitudeAPI: AMPLITUDE_API_KEYS_MEP_INT.QA,
siteVersion: "native",
sitePlatform: "android",
product: "tvg_mep",
androidDistributionMethod: "self_dist"
},
tvg4: {
amplitudeAPI: AMPLITUDE_API_KEYS_TVG4_INT.QA,
siteVersion: "desktop",
sitePlatform: "desktop",
product: "tvg_tvg4"
}
},
clientId: "88a7876dc4c330f0dfa6c5c611818d62",
brazeId: "a728acfe-5f28-42c0-9c08-174ecb4394d5",
perimeterxId: "y2WzFjbX",
storyblokToken: "nfQPQOsxD6kiFQUOovpcEQtt",
storyblokVersion: "draft",
placesAPI: "AIzaSyCvQe2IeP1DnZT6v0PLK-n4bjK9RqcEarQ",
paypalID:
"AbOXWUz9wwf1L17esie_vpZ99gwz9hxQmobirFtIirrZbE3levMoS_lb7BWll5DnB2qB1m11Mmmge8JV",
apptentiveID: "61f08786218b3765d7000024",
apptentiveTvg5: "6204200f48b9d649d700005d",
apptentiveIosKey: "IOS-TVG-DEVELOPMENT-b03e074ea0dd",
apptentiveIosSignature: "693be9827104eaa410239b062acd34b8",
apptentiveAndroidKey: "ANDROID-TVG-DEVELOPMENT",
apptentiveAndroidSignature: "809f6458570a7d899a7ff37684765a4d",
sonarQube: {
serverUrl: "https://sonarqube.gcp-dev.tvg.com",
token: "8836caf742bb1c13755da2d957ba5d1674adbc43",
projectKey: "tvg-monorepo"
},
datadogRum: {
desktopApplicationId: "123b949b-108c-4306-bea0-9227242f5b17",
desktopClientToken: "pub748e107dd1bd28256dad4b1425dda2e3",
mobileApplicationId: "03715ae6-b7e2-4b30-ac7b-cf6a5bfdf763",
mobileClientToken: "pub333a7706c3a954d17d9db1becba22673",
fdrApplicationId: "c15f8a9f-f7a7-4108-97f3-9e81d2e936fb",
fdrClientToken: "pubf5bbdc9d5e227feae77a9ad9f5e1013a",
site: "datadoghq.com"
},
siftAccountId: "60f88a09293fb116c8220753",
siftBeaconKey: "d9c3d7901c",
externalServices: {
cpp: "https://promos-api.racing.fanduel.com"
}
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/aws-int/fdr.ts
const {
STORYBLOK_TOKENS: STORYBLOK_TOKENS_INT
} = require("../../utils/fdr/storyblok");
const {
APPTENTIVE_TOKENS: APPTENTIVE_TOKENS_INT
} = require("../../utils/fdr/apptentive");
module.exports = {
domain: {
desktop: "racing.qa.fndl.dev",
mobile: "racing.qa.fndl.dev",
talentPicks: "racing.qa.fndl.dev/talent-picks/",
accountWallet: "account.racing.qa.fndl.dev",
equibase: "equibase-store.qa.fndl.dev"
},
service_host: "racing.qa.fndl.dev",
externalDomain: {
FDTermsConditions: "https://www.qa.fndl.dev/terms",
FDPolicy: "https://www.qa.fndl.dev/privacy",
FDRLoginBridge: "https://www.qa.fndl.dev/sso-auth/fdracing",
FDRSignup:
"https://www.qa.fndl.dev/join?next=%2Fsso-auth%2Ffdracing%3Fredirect_uri%3D"
},
externalServices: {
fanduel: "https://api.qa.fndl.dev",
cpp: "https://promos-api.racing.fanduel.qa.fndl.dev"
},
clientId: "a301e728606047a5b6522727d495b3ed",
brazeId: "d1c732dc-ad0d-49a5-acb7-d360cd0fee38",
storyblokToken: STORYBLOK_TOKENS_INT.QA,
storyblokVersion: "draft",
appTentiveIos: APPTENTIVE_TOKENS_INT.IOS.QA,
appTentiveAndroid: APPTENTIVE_TOKENS_INT.ANDROID.QA,
appTentiveWeb: APPTENTIVE_TOKENS_INT.WEB.QA
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/aws-int/iowa.ts
module.exports = {
domain: {
desktop: "ia-qa.tvg.com",
mobile: "ia-qa.tvg.com",
talentPicks: "ia-qa.tvg.com/talent-picks/",
equibase: "equibase-store-qa.tvg.com"
},
recaptchaID: "6Lf-4hUqAAAAAGupa6W70kpZVsaFd7yaxz5pHD8r",
recaptchaIdNative: "6Le9B1YqAAAAAJEWJZsQittPtHDcjz6xLNORgHyI"
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/aws-int/pabets.ts
module.exports = {
domain: {
desktop: "pabets-qa.tvg.com",
mobile: "pabets-qa.tvg.com",
talentPicks: "pabets-qa.tvg.com/talent-picks/",
equibase: "equibase-store-qa.tvg.com"
},
recaptchaID: "6Lf-4hUqAAAAAGupa6W70kpZVsaFd7yaxz5pHD8r",
recaptchaIdNative: "6Le9B1YqAAAAAJEWJZsQittPtHDcjz6xLNORgHyI"
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/aws-int/tvg.ts
module.exports = {
domain: {
desktop: "www-qa.tvg.com",
mobile: "www-qa.tvg.com",
talentPicks: "www-qa.tvg.com/talent-picks/",
accountWallet: "account.racing.qa.fndl.dev",
equibase: "equibase-store-qa.tvg.com"
},
recaptchaID: "6Lf-4hUqAAAAAGupa6W70kpZVsaFd7yaxz5pHD8r",
recaptchaIdNative: "6Le9B1YqAAAAAJEWJZsQittPtHDcjz6xLNORgHyI"
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/aws-prd/4njbets.ts
module.exports = {
domain: {
desktop: "4njbets.us.betfair.com",
mobile: "4njbets.us.betfair.com",
talentPicks: "4njbets.us.betfair.com/talent-picks/",
equibase: "equibase-store.us.betfair.com"
},
service_host: "service.us.betfair.com",
recaptchaID: "6LdrNBgqAAAAAKKs_ZP23RQvTYPkSFdZQ9KK_j6K",
recaptchaIdNative: "6LfSQloqAAAAAFKuurdHLnObQ-r2CGo0TuuYdNq-"
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/aws-prd/base.ts
const {
AMPLITUDE_API_KEYS: AMPLITUDE_API_KEYS_PRD
} = require("../../utils/urp/amplitude");
const {
AMPLITUDE_API_KEYS: AMPLITUDE_API_KEYS_FDR_PRD,
AMPLITUDE_API_KEYS_XSELL: AMPLITUDE_API_KEYS_FDR_XSELL_PRD
} = require("../../utils/fdr/amplitude");
const {
AMPLITUDE_API_KEYS: AMPLITUDE_API_KEYS_MEP_PRD
} = require("../../utils/mep/amplitude");
const {
AMPLITUDE_API_KEYS: AMPLITUDE_API_KEYS_TVG4_PRD
} = require("../../utils/tvg4/amplitude");
module.exports = {
service_host: "service.tvg.com",
domain: {
desktop: "www.tvg.com",
mobile: "www.tvg.com",
talentPicks: "www.tvg.com/talent-picks/",
equibase: "equibase-store.tvg.com"
},
externalDomain: {
support: "https://support.tvg.com",
contactSupport:
"https://support.tvg.com/tvg/s/articles/360005946853-Contact-Support",
NCPGamblingChat: "http://www.ncpgambling.org/chat"
},
google: {
tvg4: {
gtmId: "KTDSBG",
gtmEnv: "",
gtmAuth: "",
siteVersion: "desktop",
productVersion: "TVG4"
},
tvg5: {
gtmId: "KTDSBG",
gtmEnv: "",
gtmAuth: "",
siteVersion: "desktop",
productVersion: "TVG5"
},
touch2: {
gtmId: "KTDSBG",
gtmEnv: "",
gtmAuth: "",
siteVersion: "mobile_web",
productVersion: "MEP"
},
ios: {
gtmId: "KTDSBG",
gtmEnv: "",
gtmAuth: "",
siteVersion: "ios_native"
},
touch3: {
gtmId: "KTDSBG",
gtmEnv: "",
gtmAuth: "",
siteVersion: "mobile_web",
productVersion: "MEP"
},
ios2: {
gtmId: "KTDSBG",
gtmEnv: "",
gtmAuth: "",
siteVersion: "ios_native"
},
fdrdesktop: {
gtmId: "NSHBQSR",
gtmEnv: "",
gtmAuth: "",
siteVersion: "desktop",
productVersion: "URP"
},
fdrmobile: {
gtmId: "NSHBQSR",
gtmEnv: "",
gtmAuth: "",
siteVersion: "mobile_web",
productVersion: "MEP"
},
fdrios: {
gtmId: "NSHBQSR",
gtmEnv: "",
gtmAuth: "",
siteVersion: "ios_native",
productVersion: "MEP"
},
fdrandroid: {
gtmId: "NSHBQSR",
gtmEnv: "",
gtmAuth: "",
siteVersion: "android_native",
productVersion: "android_apk"
},
fdrandroidwrapper: {
gtmId: "NSHBQSR",
gtmEnv: "",
gtmAuth: "",
siteVersion: "android_native",
productVersion: "android_apk"
},
fdrandroidgps: {
gtmId: "NSHBQSR",
gtmEnv: "",
gtmAuth: "",
siteVersion: "android_native",
productVersion: "android_apk"
},
fdriosxsell: {
gtmId: "NSHBQSR",
gtmEnv: "",
gtmAuth: "",
siteVersion: "x-sell",
productVersion: "MEP"
},
fdrandroidxsell: {
gtmId: "NSHBQSR",
gtmEnv: "",
gtmAuth: "",
siteVersion: "x-sell",
productVersion: "android_apk"
},
androidwrapper: {
gtmId: "KTDSBG",
gtmEnv: "",
gtmAuth: "",
siteVersion: "android_native",
productVersion: "android_gps"
},
tvgandroid: {
gtmId: "KTDSBG",
gtmEnv: "",
gtmAuth: "",
siteVersion: "android_native",
productVersion: "android_apk"
},
iosnative: {
gtmId: "KTDSBG",
gtmEnv: "",
gtmAuth: "",
siteVersion: "ios_native",
productVersion: "ios_native"
},
gcs: {
url: "https://storage.googleapis.com",
tvgStatic: "tvg-static"
}
},
amplitude: {
tvg5: {
amplitudeAPI: AMPLITUDE_API_KEYS_PRD.PRODUCTION,
siteVersion: "desktop",
sitePlatform: "desktop",
product: "tvg_urp"
},
tvg5fdr: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_PRD.PRODUCTION,
siteVersion: "desktop",
sitePlatform: "desktop",
product: "fdr_standalone_lobby"
},
fdrmobile: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_PRD.PRODUCTION,
siteVersion: "mobile_web",
sitePlatform: "mobile_web",
product: "fdr_standalone_lobby"
},
fdrios: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_PRD.PRODUCTION,
siteVersion: "native",
sitePlatform: "ios",
product: "fdr_standalone_lobby"
},
fdrandroid: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_PRD.PRODUCTION,
siteVersion: "native",
sitePlatform: "android",
product: "fdr_standalone_lobby",
androidDistributionMethod: "self_dist"
},
fdrandroidwrapper: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_PRD.PRODUCTION,
siteVersion: "native",
sitePlatform: "android",
product: "fdr_standalone_lobby",
androidDistributionMethod: "google_playstore"
},
fdrandroidgps: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_PRD.PRODUCTION,
siteVersion: "native",
sitePlatform: "android",
product: "fdr_standalone_lobby",
androidDistributionMethod: "google_playstore"
},
fdriosxsell: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_XSELL_PRD.PRODUCTION,
siteVersion: "native",
sitePlatform: "ios",
product: "fdr_xsell_lobby"
},
fdrandroidxsell: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_XSELL_PRD.PRODUCTION,
siteVersion: "native",
sitePlatform: "android",
product: "fdr_xsell_lobby"
},
touch3: {
amplitudeAPI: AMPLITUDE_API_KEYS_MEP_PRD.PRODUCTION,
siteVersion: "mobile_web",
sitePlatform: "mobile_web",
product: "tvg_mep"
},
androidwrapper: {
amplitudeAPI: AMPLITUDE_API_KEYS_MEP_PRD.PRODUCTION,
siteVersion: "native",
sitePlatform: "android",
product: "tvg_mep",
androidDistributionMethod: "self_dist"
},
tvgandroid: {
amplitudeAPI: AMPLITUDE_API_KEYS_MEP_PRD.PRODUCTION,
siteVersion: "native",
sitePlatform: "android",
product: "tvg_mep",
androidDistributionMethod: "self_dist"
},
tvg4: {
amplitudeAPI: AMPLITUDE_API_KEYS_TVG4_PRD.PRODUCTION,
siteVersion: "desktop",
sitePlatform: "desktop",
product: "tvg_tvg4"
}
},
brazeId: "908c5857-650b-4f31-8ec7-63b15dc11d1d",
siftAccountId: "60f88a09293fb116c8220750",
siftBeaconKey: "df80113946",
clientId: "eaf77f127ea003d4e275a3ed07d6f527",
perimeterxId: "TK74ox9H",
storyblokToken: "mBZqhnrYeUYWqvVh3OTCDgtt",
storyblokVersion: "published",
placesAPI: "AIzaSyBwhD0RAB-vMDrx4IDcO_gezIVGpn7dFks",
paypalID:
"AfOWmRjlT73hGanCAUypmRtFas_NsPcXek2_fL8XOIrJHBDoUxcSEVBQ72Ls4fc_2xgJSWK3gTDrgjhI",
apptentiveID: "61f087a65a8827645c000039",
apptentiveTvg5: "62041fcb5a88277d4900018f",
apptentiveIosKey: "IOS-TVG-HORSE-RACING-BETTING-APP",
apptentiveIosSignature: "c0b078503398c5fec509b1235058c955",
apptentiveAndroidKey: "ANDROID-TVG-PRODUCTION",
apptentiveAndroidSignature: "b09205fa5b98d7fdc161f1ca98b5d9b1",
sonarQube: {
serverUrl: "https://sonarqube.gcp-dev.tvg.com",
token: "8836caf742bb1c13755da2d957ba5d1674adbc43",
projectKey: "tvg-monorepo"
},
datadogRum: {
desktopApplicationId: "123b949b-108c-4306-bea0-9227242f5b17",
desktopClientToken: "pub748e107dd1bd28256dad4b1425dda2e3",
mobileApplicationId: "03715ae6-b7e2-4b30-ac7b-cf6a5bfdf763",
mobileClientToken: "pub333a7706c3a954d17d9db1becba22673",
fdrApplicationId: "c15f8a9f-f7a7-4108-97f3-9e81d2e936fb",
fdrClientToken: "pubf5bbdc9d5e227feae77a9ad9f5e1013a",
site: "datadoghq.com"
},
externalServices: {
cpp: "https://promos-api.racing.fanduel.com"
}
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/aws-prd/fdr.ts
const {
STORYBLOK_TOKENS: STORYBLOK_TOKENS_PRD
} = require("../../utils/fdr/storyblok");
const {
APPTENTIVE_TOKENS: APPTENTIVE_TOKENS_PRD
} = require("../../utils/fdr/apptentive");
module.exports = {
domain: {
desktop: "racing.fanduel.com",
mobile: "racing.fanduel.com",
talentPicks: "racing.fanduel.com/talent-picks/",
accountWallet: "account.racing.fanduel.com",
equibase: "equibase-store.fanduel.com"
},
service_host: "service.racing.fanduel.com",
externalDomain: {
FDTermsConditions: "https://fanduel.com/terms",
FDPolicy: "https://fanduel.com/privacy",
FDRLoginBridge: "https://fanduel.com/sso-auth/fdracing",
FDRSignup:
"https://www.fanduel.com/join?next=%2Fsso-auth%2Ffdracing%3Fredirect_uri%3D"
},
externalServices: {
fanduel: "https://api.fanduel.com",
cpp: "https://promos-api.racing.fanduel.com"
},
clientId: "a301e728606047a5b6522727d495b3ed",
brazeId: "e0b90c9d-dfd9-4809-a627-565a5cd7f3b2",
storyblokToken: STORYBLOK_TOKENS_PRD.PRODUCTION,
storyblokVersion: "published",
appTentiveIos: APPTENTIVE_TOKENS_PRD.IOS.PRODUCTION,
appTentiveAndroid: APPTENTIVE_TOKENS_PRD.ANDROID.PRODUCTION,
appTentiveWeb: APPTENTIVE_TOKENS_PRD.WEB.PRODUCTION
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/aws-prd/iowa.ts
module.exports = {
domain: {
desktop: "ia.tvg.com",
mobile: "ia.tvg.com",
talentPicks: "ia.tvg.com/talent-picks/",
equibase: "equibase-store.tvg.com"
},
recaptchaID: "6LdrNBgqAAAAAKKs_ZP23RQvTYPkSFdZQ9KK_j6K",
recaptchaIdNative: "6LfSQloqAAAAAFKuurdHLnObQ-r2CGo0TuuYdNq-"
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/aws-prd/pabets.ts
module.exports = {
domain: {
desktop: "pabets.tvg.com",
mobile: "pabets.tvg.com",
talentPicks: "pabets.tvg.com/talent-picks/",
equibase: "equibase-store.tvg.com"
},
recaptchaID: "6LdrNBgqAAAAAKKs_ZP23RQvTYPkSFdZQ9KK_j6K",
recaptchaIdNative: "6LfSQloqAAAAAFKuurdHLnObQ-r2CGo0TuuYdNq-"
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/aws-prd/tvg.ts
module.exports = {
domain: {
desktop: "www.tvg.com",
mobile: "www.tvg.com",
talentPicks: "www.tvg.com/talent-picks/",
accountWallet: "account.racing.fanduel.com",
equibase: "equibase-store.tvg.com"
},
recaptchaID: "6LdrNBgqAAAAAKKs_ZP23RQvTYPkSFdZQ9KK_j6K",
recaptchaIdNative: "6LfSQloqAAAAAFKuurdHLnObQ-r2CGo0TuuYdNq-"
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/aws-stg/4njbets.ts
module.exports = {
domain: {
desktop: "4njbets-staging.us.betfair.com",
mobile: "4njbets-staging.us.betfair.com",
talentPicks: "4njbets-staging.us.betfair.com/talent-picks/",
equibase: "equibase-store.us.betfair.com"
},
service_host: "service-staging.us.betfair.com",
recaptchaID: "6LeIYBcqAAAAAE2wDhSub9Ic8oeidAiiUt4gYM4a",
recaptchaIdNative: "6LfRQloqAAAAABY9v2RydlB10Lfgb5ODmvygHy3G"
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/aws-stg/base.ts
const {
AMPLITUDE_API_KEYS: AMPLITUDE_API_KEYS_STG
} = require("../../utils/urp/amplitude");
const {
AMPLITUDE_API_KEYS: AMPLITUDE_API_KEYS_FDR_STG,
AMPLITUDE_API_KEYS_XSELL: AMPLITUDE_API_KEYS_FDR_XSELL_STG
} = require("../../utils/fdr/amplitude");
const {
AMPLITUDE_API_KEYS: AMPLITUDE_API_KEYS_MEP_STG
} = require("../../utils/mep/amplitude");
const {
AMPLITUDE_API_KEYS: AMPLITUDE_API_KEYS_TVG4_STG
} = require("../../utils/tvg4/amplitude");
module.exports = {
domain: {
desktop: "www-staging.tvg.com",
mobile: "www-staging.tvg.com",
talentPicks: "www-staging.tvg.com/talent-picks/",
equibase: "equibase-store.tvg.com"
},
externalDomain: {
support: "https://support.tvg.com",
contactSupport:
"https://support.tvg.com/tvg/s/articles/360005946853-Contact-Support",
NCPGamblingChat: "http://www.ncpgambling.org/chat"
},
service_host: "service-staging.tvg.com",
google: {
tvg4: {
gtmId: "KTDSBG",
gtmEnv: "668",
gtmAuth: "Q3mmSetXL-9o6LJDN6Tz1A",
siteVersion: "desktop",
productVersion: "TVG4"
},
tvg5: {
gtmId: "KTDSBG",
gtmEnv: "668",
gtmAuth: "Q3mmSetXL-9o6LJDN6Tz1A",
siteVersion: "desktop",
productVersion: "TVG5"
},
touch2: {
gtmId: "KTDSBG",
gtmEnv: "668",
gtmAuth: "Q3mmSetXL-9o6LJDN6Tz1A",
siteVersion: "mobile_web",
productVersion: "MEP"
},
ios: {
gtmId: "KTDSBG",
gtmEnv: "668",
gtmAuth: "Q3mmSetXL-9o6LJDN6Tz1A",
siteVersion: "ios_native"
},
touch3: {
gtmId: "KTDSBG",
gtmEnv: "668",
gtmAuth: "Q3mmSetXL-9o6LJDN6Tz1A",
siteVersion: "mobile_web",
productVersion: "MEP"
},
androidwrapper: {
gtmId: "KTDSBG",
gtmEnv: "668",
gtmAuth: "Q3mmSetXL-9o6LJDN6Tz1A",
siteVersion: "android_native",
productVersion: "android_gps"
},
tvgandroid: {
gtmId: "KTDSBG",
gtmEnv: "668",
gtmAuth: "Q3mmSetXL-9o6LJDN6Tz1A",
siteVersion: "android_native",
productVersion: "android_apk"
},
ios2: {
gtmId: "KTDSBG",
gtmEnv: "668",
gtmAuth: "Q3mmSetXL-9o6LJDN6Tz1A",
siteVersion: "ios_native"
},
fdrdesktop: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "desktop",
productVersion: "URP"
},
fdrmobile: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "mobile_web",
productVersion: "MEP"
},
fdrios: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "ios_native",
productVersion: "MEP"
},
fdrandroid: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "android_native",
productVersion: "android_apk"
},
fdrandroidwrapper: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "android_native",
productVersion: "android_apk"
},
fdrandroidgps: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "android_native",
productVersion: "android_apk"
},
fdriosxsell: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "x-sell",
productVersion: "MEP"
},
fdrandroidxsell: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "x-sell",
productVersion: "android_apk"
},
iosnative: {
gtmId: "KTDSBG",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "ios_native",
productVersion: "ios_native"
},
gcs: {
url: "https://storage.googleapis.com",
tvgStatic: "tvg-static-staging"
}
},
amplitude: {
tvg5: {
amplitudeAPI: AMPLITUDE_API_KEYS_STG.STAGING,
siteVersion: "desktop",
sitePlatform: "desktop",
product: "tvg_urp"
},
tvg5fdr: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_STG.STAGING,
siteVersion: "desktop",
sitePlatform: "desktop",
product: "fdr_standalone_lobby"
},
fdrmobile: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_STG.STAGING,
siteVersion: "mobile_web",
sitePlatform: "mobile_web",
product: "fdr_standalone_lobby"
},
fdrios: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_STG.STAGING,
siteVersion: "native",
sitePlatform: "ios",
product: "fdr_standalone_lobby"
},
fdrandroid: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_STG.STAGING,
siteVersion: "native",
sitePlatform: "android",
product: "fdr_standalone_lobby",
androidDistributionMethod: "self_dist"
},
fdrandroidwrapper: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_STG.STAGING,
siteVersion: "native",
sitePlatform: "android",
product: "fdr_standalone_lobby",
androidDistributionMethod: "google_playstore"
},
fdrandroidgps: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_STG.STAGING,
siteVersion: "native",
sitePlatform: "android",
product: "fdr_standalone_lobby",
androidDistributionMethod: "google_playstore"
},
fdriosxsell: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_XSELL_STG.STAGING,
siteVersion: "native",
sitePlatform: "ios",
product: "fdr_xsell_lobby"
},
fdrandroidxsell: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_XSELL_STG.STAGING,
siteVersion: "native",
sitePlatform: "android",
product: "fdr_xsell_lobby"
},
touch3: {
amplitudeAPI: AMPLITUDE_API_KEYS_MEP_STG.STAGING,
siteVersion: "mobile_web",
sitePlatform: "mobile_web",
product: "tvg_mep"
},
androidwrapper: {
amplitudeAPI: AMPLITUDE_API_KEYS_MEP_STG.STAGING,
siteVersion: "native",
sitePlatform: "android",
product: "tvg_mep",
androidDistributionMethod: "self_dist"
},
tvgandroid: {
amplitudeAPI: AMPLITUDE_API_KEYS_TVG4_STG.STAGING,
siteVersion: "native",
sitePlatform: "android",
product: "tvg_mep",
androidDistributionMethod: "self_dist"
},
tvg4: {
amplitudeAPI: AMPLITUDE_API_KEYS_TVG4_STG.STAGING,
siteVersion: "desktop",
sitePlatform: "desktop",
product: "tvg_tvg4"
}
},
clientId: "88a7876dc4c330f0dfa6c5c611818d62",
brazeId: "908c5857-650b-4f31-8ec7-63b15dc11d1d",
siftAccountId: "60f88a09293fb116c8220750",
siftBeaconKey: "df80113946",
perimeterxId: "BMkUl9nm",
storyblokToken: "4LYunuxrMxUarw6vBokjKAtt",
storyblokVersion: "draft",
placesAPI: "AIzaSyBwhD0RAB-vMDrx4IDcO_gezIVGpn7dFks",
paypalID:
"AfOWmRjlT73hGanCAUypmRtFas_NsPcXek2_fL8XOIrJHBDoUxcSEVBQ72Ls4fc_2xgJSWK3gTDrgjhI",
apptentiveID: "61f08786218b3765d7000024",
apptentiveTvg5: "6204200f48b9d649d700005d",
apptentiveIosKey: "IOS-TVG-DEVELOPMENT-b03e074ea0dd",
apptentiveIosSignature: "693be9827104eaa410239b062acd34b8",
apptentiveAndroidKey: "ANDROID-TVG-DEVELOPMENT",
apptentiveAndroidSignature: "809f6458570a7d899a7ff37684765a4d",
sonarQube: {
serverUrl: "https://sonarqube.gcp-dev.tvg.com",
token: "8836caf742bb1c13755da2d957ba5d1674adbc43",
projectKey: "tvg-monorepo"
},
datadogRum: {
desktopApplicationId: "123b949b-108c-4306-bea0-9227242f5b17",
desktopClientToken: "pub748e107dd1bd28256dad4b1425dda2e3",
mobileApplicationId: "03715ae6-b7e2-4b30-ac7b-cf6a5bfdf763",
mobileClientToken: "pub333a7706c3a954d17d9db1becba22673",
fdrApplicationId: "c15f8a9f-f7a7-4108-97f3-9e81d2e936fb",
fdrClientToken: "pubf5bbdc9d5e227feae77a9ad9f5e1013a",
site: "datadoghq.com"
},
externalServices: {
cpp: "https://promos-api.racing.fanduel.com"
}
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/aws-stg/fdr.ts
const {
STORYBLOK_TOKENS: STORYBLOK_TOKENS_STG
} = require("../../utils/fdr/storyblok");
const {
APPTENTIVE_TOKENS: APPTENTIVE_TOKENS_STG
} = require("../../utils/fdr/apptentive");
module.exports = {
domain: {
desktop: "staging.racing.fanduel.com",
mobile: "staging.racing.fanduel.com",
talentPicks: "staging.racing.fanduel.com/talent-picks/",
accountWallet: "account.racing.fanduel.com",
equibase: "equibase-store.fanduel.com"
},
service_host: "service-staging.racing.fanduel.com",
externalDomain: {
FDTermsConditions: "https://fanduel.com/terms",
FDPolicy: "https://fanduel.com/privacy",
FDRLoginBridge: "https://fanduel.com/sso-auth/fdracing",
FDRSignup:
"https://www.fanduel.com/join?next=%2Fsso-auth%2Ffdracing%3Fredirect_uri%3D"
},
externalServices: {
fanduel: "https://api.fanduel.com",
cpp: "https://promos-api.racing.fanduel.com"
},
clientId: "a301e728606047a5b6522727d495b3ed",
brazeId: "e0b90c9d-dfd9-4809-a627-565a5cd7f3b2",
storyblokToken: STORYBLOK_TOKENS_STG.STAGING,
storyblokVersion: "draft",
appTentiveIos: APPTENTIVE_TOKENS_STG.IOS.PRODUCTION,
appTentiveAndroid: APPTENTIVE_TOKENS_STG.ANDROID.PRODUCTION,
appTentiveWeb: APPTENTIVE_TOKENS_STG.WEB.PRODUCTION
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/aws-stg/iowa.ts
module.exports = {
domain: {
desktop: "ia-staging.tvg.com",
mobile: "ia-staging.tvg.com",
talentPicks: "ia-staging.tvg.com/talent-picks/",
equibase: "equibase-store.tvg.com"
},
recaptchaID: "6LeIYBcqAAAAAE2wDhSub9Ic8oeidAiiUt4gYM4a",
recaptchaIdNative: "6LfRQloqAAAAABY9v2RydlB10Lfgb5ODmvygHy3G"
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/aws-stg/pabets.ts
module.exports = {
domain: {
desktop: "pabets-staging.tvg.com",
mobile: "pabets-staging.tvg.com",
talentPicks: "pabets-staging.tvg.com/talent-picks/",
equibase: "equibase-store.tvg.com"
},
recaptchaID: "6LeIYBcqAAAAAE2wDhSub9Ic8oeidAiiUt4gYM4a",
recaptchaIdNative: "6LfRQloqAAAAABY9v2RydlB10Lfgb5ODmvygHy3G"
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/aws-stg/tvg.ts
module.exports = {
domain: {
desktop: "www-staging.tvg.com",
mobile: "www-staging.tvg.com",
talentPicks: "www-staging.tvg.com/talent-picks/",
accountWallet: "account.racing.fanduel.com",
equibase: "equibase-store.tvg.com"
},
recaptchaID: "6LeIYBcqAAAAAE2wDhSub9Ic8oeidAiiUt4gYM4a",
recaptchaIdNative: "6LfRQloqAAAAABY9v2RydlB10Lfgb5ODmvygHy3G"
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/production/4njbets.ts
module.exports = {
domain: {
desktop: "4njbets.us.betfair.com",
mobile: "4njbets.us.betfair.com",
talentPicks: "4njbets.us.betfair.com/talent-picks/",
equibase: "equibase-store.us.betfair.com"
},
service_host: "service.us.betfair.com",
recaptchaID: "6LdrNBgqAAAAAKKs_ZP23RQvTYPkSFdZQ9KK_j6K",
recaptchaIdNative: "6LfSQloqAAAAAFKuurdHLnObQ-r2CGo0TuuYdNq-"
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/production/base.ts
const {
AMPLITUDE_API_KEYS: AMPLITUDE_API_KEYS_PROD
} = require("../../utils/urp/amplitude");
const {
AMPLITUDE_API_KEYS: AMPLITUDE_API_KEYS_FDR_PROD,
AMPLITUDE_API_KEYS_XSELL: AMPLITUDE_API_KEYS_FDR_XSELL_PROD
} = require("../../utils/fdr/amplitude");
const {
AMPLITUDE_API_KEYS: AMPLITUDE_API_KEYS_MEP_PROD
} = require("../../utils/mep/amplitude");
const {
AMPLITUDE_API_KEYS: AMPLITUDE_API_KEYS_TVG4_PROD
} = require("../../utils/tvg4/amplitude");
module.exports = {
service_host: "service.tvg.com",
domain: {
desktop: "www.tvg.com",
mobile: "www.tvg.com",
talentPicks: "www.tvg.com/talent-picks/",
equibase: "equibase-store.tvg.com"
},
externalDomain: {
support: "https://support.tvg.com",
contactSupport:
"https://support.tvg.com/tvg/s/articles/360005946853-Contact-Support",
NCPGamblingChat: "http://www.ncpgambling.org/chat"
},
google: {
tvg4: {
gtmId: "KTDSBG",
gtmEnv: "",
gtmAuth: "",
siteVersion: "desktop",
productVersion: "TVG4"
},
tvg5: {
gtmId: "KTDSBG",
gtmEnv: "",
gtmAuth: "",
siteVersion: "desktop",
productVersion: "TVG5"
},
touch2: {
gtmId: "KTDSBG",
gtmEnv: "",
gtmAuth: "",
siteVersion: "mobile_web",
productVersion: "MEP"
},
ios: {
gtmId: "KTDSBG",
gtmEnv: "",
gtmAuth: "",
siteVersion: "ios_native"
},
touch3: {
gtmId: "KTDSBG",
gtmEnv: "",
gtmAuth: "",
siteVersion: "mobile_web",
productVersion: "MEP"
},
ios2: {
gtmId: "KTDSBG",
gtmEnv: "",
gtmAuth: "",
siteVersion: "ios_native"
},
fdrdesktop: {
gtmId: "NSHBQSR",
gtmEnv: "",
gtmAuth: "",
siteVersion: "desktop",
productVersion: "URP"
},
fdrmobile: {
gtmId: "NSHBQSR",
gtmEnv: "",
gtmAuth: "",
siteVersion: "mobile_web",
productVersion: "MEP"
},
fdrios: {
gtmId: "NSHBQSR",
gtmEnv: "",
gtmAuth: "",
siteVersion: "ios_native",
productVersion: "MEP"
},
fdrandroid: {
gtmId: "NSHBQSR",
gtmEnv: "",
gtmAuth: "",
siteVersion: "android_native",
productVersion: "android_apk"
},
fdrandroidwrapper: {
gtmId: "NSHBQSR",
gtmEnv: "",
gtmAuth: "",
siteVersion: "android_native",
productVersion: "android_apk"
},
fdrandroidgps: {
gtmId: "NSHBQSR",
gtmEnv: "",
gtmAuth: "",
siteVersion: "android_native",
productVersion: "android_apk"
},
fdriosxsell: {
gtmId: "NSHBQSR",
gtmEnv: "",
gtmAuth: "",
siteVersion: "x-sell",
productVersion: "MEP"
},
fdrandroidxsell: {
gtmId: "NSHBQSR",
gtmEnv: "",
gtmAuth: "",
siteVersion: "x-sell",
productVersion: "android_apk"
},
androidwrapper: {
gtmId: "KTDSBG",
gtmEnv: "",
gtmAuth: "",
siteVersion: "android_native",
productVersion: "android_gps"
},
tvgandroid: {
gtmId: "KTDSBG",
gtmEnv: "",
gtmAuth: "",
siteVersion: "android_native",
productVersion: "android_apk"
},
iosnative: {
gtmId: "KTDSBG",
gtmEnv: "",
gtmAuth: "",
siteVersion: "ios_native",
productVersion: "ios_native"
},
gcs: {
url: "https://storage.googleapis.com",
tvgStatic: "tvg-static"
}
},
amplitude: {
tvg5: {
amplitudeAPI: AMPLITUDE_API_KEYS_PROD.PRODUCTION,
siteVersion: "desktop",
sitePlatform: "desktop",
product: "tvg_urp"
},
tvg5fdr: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_PROD.PRODUCTION,
siteVersion: "desktop",
sitePlatform: "desktop",
product: "fdr_standalone_lobby"
},
fdrmobile: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_PROD.PRODUCTION,
siteVersion: "mobile_web",
sitePlatform: "mobile_web",
product: "fdr_standalone_lobby"
},
fdrios: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_PROD.PRODUCTION,
siteVersion: "native",
sitePlatform: "ios",
product: "fdr_standalone_lobby"
},
fdrandroid: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_PROD.PRODUCTION,
siteVersion: "native",
sitePlatform: "android",
product: "fdr_standalone_lobby",
androidDistributionMethod: "self_dist"
},
fdrandroidwrapper: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_PROD.PRODUCTION,
siteVersion: "native",
sitePlatform: "android",
product: "fdr_standalone_lobby",
androidDistributionMethod: "google_playstore"
},
fdrandroidgps: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_PROD.PRODUCTION,
siteVersion: "native",
sitePlatform: "android",
product: "fdr_standalone_lobby",
androidDistributionMethod: "google_playstore"
},
fdriosxsell: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_XSELL_PROD.PRODUCTION,
siteVersion: "native",
sitePlatform: "ios",
product: "fdr_xsell_lobby"
},
fdrandroidxsell: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_XSELL_PROD.PRODUCTION,
siteVersion: "native",
sitePlatform: "android",
product: "fdr_xsell_lobby"
},
touch3: {
amplitudeAPI: AMPLITUDE_API_KEYS_MEP_PROD.PRODUCTION,
siteVersion: "mobile_web",
sitePlatform: "mobile_web",
product: "tvg_mep"
},
androidwrapper: {
amplitudeAPI: AMPLITUDE_API_KEYS_MEP_PROD.PRODUCTION,
siteVersion: "native",
sitePlatform: "android",
product: "tvg_mep",
androidDistributionMethod: "self_dist"
},
tvgandroid: {
amplitudeAPI: AMPLITUDE_API_KEYS_MEP_PROD.PRODUCTION,
siteVersion: "native",
sitePlatform: "android",
product: "tvg_mep",
androidDistributionMethod: "self_dist"
},
tvg4: {
amplitudeAPI: AMPLITUDE_API_KEYS_TVG4_PROD.PRODUCTION,
siteVersion: "desktop",
sitePlatform: "desktop",
product: "tvg_tvg4"
}
},
brazeId: "908c5857-650b-4f31-8ec7-63b15dc11d1d",
siftAccountId: "60f88a09293fb116c8220750",
siftBeaconKey: "df80113946",
clientId: "eaf77f127ea003d4e275a3ed07d6f527",
perimeterxId: "TK74ox9H",
storyblokToken: "mBZqhnrYeUYWqvVh3OTCDgtt",
storyblokVersion: "published",
placesAPI: "AIzaSyBwhD0RAB-vMDrx4IDcO_gezIVGpn7dFks",
paypalID:
"AfOWmRjlT73hGanCAUypmRtFas_NsPcXek2_fL8XOIrJHBDoUxcSEVBQ72Ls4fc_2xgJSWK3gTDrgjhI",
apptentiveID: "61f087a65a8827645c000039",
apptentiveTvg5: "62041fcb5a88277d4900018f",
apptentiveIosKey: "IOS-TVG-HORSE-RACING-BETTING-APP",
apptentiveIosSignature: "c0b078503398c5fec509b1235058c955",
apptentiveAndroidKey: "ANDROID-TVG-PRODUCTION",
apptentiveAndroidSignature: "b09205fa5b98d7fdc161f1ca98b5d9b1",
sonarQube: {
serverUrl: "https://sonarqube.gcp-dev.tvg.com",
token: "8836caf742bb1c13755da2d957ba5d1674adbc43",
projectKey: "tvg-monorepo"
},
datadogRum: {
desktopApplicationId: "123b949b-108c-4306-bea0-9227242f5b17",
desktopClientToken: "pub748e107dd1bd28256dad4b1425dda2e3",
mobileApplicationId: "03715ae6-b7e2-4b30-ac7b-cf6a5bfdf763",
mobileClientToken: "pub333a7706c3a954d17d9db1becba22673",
fdrApplicationId: "c15f8a9f-f7a7-4108-97f3-9e81d2e936fb",
fdrClientToken: "pubf5bbdc9d5e227feae77a9ad9f5e1013a",
site: "datadoghq.com"
},
externalServices: {
cpp: "https://promos-api.racing.fanduel.com"
}
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/production/fdr.ts
const {
STORYBLOK_TOKENS: STORYBLOK_TOKENS_PROD
} = require("../../utils/fdr/storyblok");
const {
APPTENTIVE_TOKENS: APPTENTIVE_TOKENS_PROD
} = require("../../utils/fdr/apptentive");
module.exports = {
domain: {
desktop: "racing.fanduel.com",
mobile: "racing.fanduel.com",
talentPicks: "racing.fanduel.com/talent-picks/",
accountWallet: "account.racing.fanduel.com",
equibase: "equibase-store.fanduel.com"
},
service_host: "service.racing.fanduel.com",
externalDomain: {
FDTermsConditions: "https://fanduel.com/terms",
FDPolicy: "https://fanduel.com/privacy",
FDRLoginBridge: "https://fanduel.com/sso-auth/fdracing",
FDRSignup:
"https://www.fanduel.com/join?next=%2Fsso-auth%2Ffdracing%3Fredirect_uri%3D"
},
externalServices: {
fanduel: "https://api.fanduel.com",
cpp: "https://promos-api.racing.fanduel.com"
},
clientId: "a301e728606047a5b6522727d495b3ed",
brazeId: "e0b90c9d-dfd9-4809-a627-565a5cd7f3b2",
storyblokToken: STORYBLOK_TOKENS_PROD.PRODUCTION,
storyblokVersion: "published",
appTentiveIos: APPTENTIVE_TOKENS_PROD.IOS.PRODUCTION,
appTentiveAndroid: APPTENTIVE_TOKENS_PROD.ANDROID.PRODUCTION,
appTentiveWeb: APPTENTIVE_TOKENS_PROD.WEB.PRODUCTION
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/production/iowa.ts
module.exports = {
domain: {
desktop: "ia.tvg.com",
mobile: "ia.tvg.com",
talentPicks: "ia.tvg.com/talent-picks/",
equibase: "equibase-store.tvg.com"
},
recaptchaID: "6LdrNBgqAAAAAKKs_ZP23RQvTYPkSFdZQ9KK_j6K",
recaptchaIdNative: "6LfSQloqAAAAAFKuurdHLnObQ-r2CGo0TuuYdNq-"
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/production/pabets.ts
module.exports = {
domain: {
desktop: "pabets.tvg.com",
mobile: "pabets.tvg.com",
talentPicks: "pabets.tvg.com/talent-picks/",
equibase: "equibase-store.tvg.com"
},
recaptchaID: "6LdrNBgqAAAAAKKs_ZP23RQvTYPkSFdZQ9KK_j6K",
recaptchaIdNative: "6LfSQloqAAAAAFKuurdHLnObQ-r2CGo0TuuYdNq-"
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/production/tvg.ts
module.exports = {
domain: {
desktop: "www.tvg.com",
mobile: "www.tvg.com",
talentPicks: "www.tvg.com/talent-picks/",
accountWallet: "account.racing.fanduel.com",
equibase: "equibase-store.tvg.com"
},
recaptchaID: "6LdrNBgqAAAAAKKs_ZP23RQvTYPkSFdZQ9KK_j6K",
recaptchaIdNative: "6LfSQloqAAAAAFKuurdHLnObQ-r2CGo0TuuYdNq-"
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/qa/4njbets.ts
module.exports = {
domain: {
desktop: "4njbets-qa.us.betfair.com",
mobile: "4njbets-qa.us.betfair.com",
talentPicks: "4njbets-qa.us.betfair.com/talent-picks/",
equibase: "equibase-store-qa.us.betfair.com"
},
service_host: "service-qa.us.betfair.com",
recaptchaID: "6Lf-4hUqAAAAAGupa6W70kpZVsaFd7yaxz5pHD8r",
recaptchaIdNative: "6Le9B1YqAAAAAJEWJZsQittPtHDcjz6xLNORgHyI"
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/qa/base.ts
const {
AMPLITUDE_API_KEYS: AMPLITUDE_API_KEYS_QA
} = require("../../utils/urp/amplitude");
const {
AMPLITUDE_API_KEYS: AMPLITUDE_API_KEYS_FDR_QA,
AMPLITUDE_API_KEYS_XSELL: AMPLITUDE_API_KEYS_FDR_XSELL_QA
} = require("../../utils/fdr/amplitude");
const {
AMPLITUDE_API_KEYS: AMPLITUDE_API_KEYS_MEP_QA
} = require("../../utils/mep/amplitude");
const {
AMPLITUDE_API_KEYS: AMPLITUDE_API_KEYS_TVG4_QA
} = require("../../utils/tvg4/amplitude");
module.exports = {
domain: {
desktop: "www-qa.tvg.com",
mobile: "www-qa.tvg.com",
talentPicks: "www-qa.tvg.com/talent-picks/",
equibase: "equibase-store-qa.tvg.com"
},
externalDomain: {
support: "https://support.tvg.com",
contactSupport:
"https://support.tvg.com/tvg/s/articles/360005946853-Contact-Support",
NCPGamblingChat: "http://www.ncpgambling.org/chat"
},
service_host: "service-qa.tvg.com",
google: {
tvg4: {
gtmId: "KTDSBG",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "desktop",
productVersion: "TVG4"
},
tvg5: {
gtmId: "KTDSBG",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "desktop",
productVersion: "TVG5"
},
touch2: {
gtmId: "KTDSBG",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "mobile_web",
productVersion: "MEP"
},
touch3: {
gtmId: "KTDSBG",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "mobile_web",
productVersion: "MEP"
},
ios: {
gtmId: "KTDSBG",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "ios_native"
},
ios2: {
gtmId: "KTDSBG",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "ios_native"
},
fdrdesktop: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "desktop",
productVersion: "URP"
},
fdrmobile: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "mobile_web",
productVersion: "MEP"
},
fdrios: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "ios_native",
productVersion: "MEP"
},
fdrandroid: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "android_native",
productVersion: "android_apk"
},
fdrandroidwrapper: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "android_native",
productVersion: "android_apk"
},
fdrandroidgps: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "android_native",
productVersion: "android_apk"
},
fdriosxsell: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "x-sell",
productVersion: "MEP"
},
fdrandroidxsell: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "x-sell",
productVersion: "android_apk"
},
androidwrapper: {
gtmId: "KTDSBG",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "android_native",
productVersion: "android_gps"
},
tvgandroid: {
gtmId: "KTDSBG",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "android_native",
productVersion: "android_apk"
},
iosnative: {
gtmId: "KTDSBG",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "ios_native",
productVersion: "ios_native"
},
gcs: {
url: "https://storage.googleapis.com",
tvgStatic: "tvg-static-qa"
}
},
amplitude: {
tvg5: {
amplitudeAPI: AMPLITUDE_API_KEYS_QA.QA,
siteVersion: "desktop",
sitePlatform: "desktop",
product: "tvg_urp"
},
tvg5fdr: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_QA.QA,
siteVersion: "desktop",
sitePlatform: "desktop",
product: "fdr_standalone_lobby"
},
fdrmobile: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_QA.QA,
siteVersion: "mobile_web",
sitePlatform: "mobile_web",
product: "fdr_standalone_lobby"
},
fdrios: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_QA.QA,
siteVersion: "native",
sitePlatform: "ios",
product: "fdr_standalone_lobby"
},
fdrandroid: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_QA.QA,
siteVersion: "native",
sitePlatform: "android",
product: "fdr_standalone_lobby",
androidDistributionMethod: "self_dist"
},
fdrandroidwrapper: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_QA.QA,
siteVersion: "native",
sitePlatform: "android",
product: "fdr_standalone_lobby",
androidDistributionMethod: "google_playstore"
},
fdrandroidgps: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_QA.QA,
siteVersion: "native",
sitePlatform: "android",
product: "fdr_standalone_lobby",
androidDistributionMethod: "google_playstore"
},
fdriosxsell: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_XSELL_QA.QA,
siteVersion: "native",
sitePlatform: "ios",
product: "fdr_xsell_lobby"
},
fdrandroidxsell: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_XSELL_QA.QA,
siteVersion: "native",
sitePlatform: "android",
product: "fdr_xsell_lobby"
},
touch3: {
amplitudeAPI: AMPLITUDE_API_KEYS_MEP_QA.QA,
siteVersion: "mobile_web",
sitePlatform: "mobile_web",
product: "tvg_mep"
},
androidwrapper: {
amplitudeAPI: AMPLITUDE_API_KEYS_MEP_QA.QA,
siteVersion: "native",
sitePlatform: "android",
product: "tvg_mep",
androidDistributionMethod: "self_dist"
},
tvgandroid: {
amplitudeAPI: AMPLITUDE_API_KEYS_MEP_QA.QA,
siteVersion: "native",
sitePlatform: "android",
product: "tvg_mep",
androidDistributionMethod: "self_dist"
},
tvg4: {
amplitudeAPI: AMPLITUDE_API_KEYS_TVG4_QA.QA,
siteVersion: "desktop",
sitePlatform: "desktop",
product: "tvg_tvg4"
}
},
clientId: "88a7876dc4c330f0dfa6c5c611818d62",
brazeId: "a728acfe-5f28-42c0-9c08-174ecb4394d5",
perimeterxId: "y2WzFjbX",
storyblokToken: "nfQPQOsxD6kiFQUOovpcEQtt",
storyblokVersion: "draft",
placesAPI: "AIzaSyCvQe2IeP1DnZT6v0PLK-n4bjK9RqcEarQ",
paypalID:
"AbOXWUz9wwf1L17esie_vpZ99gwz9hxQmobirFtIirrZbE3levMoS_lb7BWll5DnB2qB1m11Mmmge8JV",
apptentiveID: "61f08786218b3765d7000024",
apptentiveTvg5: "6204200f48b9d649d700005d",
apptentiveIosKey: "IOS-TVG-DEVELOPMENT-b03e074ea0dd",
apptentiveIosSignature: "693be9827104eaa410239b062acd34b8",
apptentiveAndroidKey: "ANDROID-TVG-DEVELOPMENT",
apptentiveAndroidSignature: "809f6458570a7d899a7ff37684765a4d",
sonarQube: {
serverUrl: "https://sonarqube.gcp-dev.tvg.com",
token: "8836caf742bb1c13755da2d957ba5d1674adbc43",
projectKey: "tvg-monorepo"
},
datadogRum: {
desktopApplicationId: "123b949b-108c-4306-bea0-9227242f5b17",
desktopClientToken: "pub748e107dd1bd28256dad4b1425dda2e3",
mobileApplicationId: "03715ae6-b7e2-4b30-ac7b-cf6a5bfdf763",
mobileClientToken: "pub333a7706c3a954d17d9db1becba22673",
fdrApplicationId: "c15f8a9f-f7a7-4108-97f3-9e81d2e936fb",
fdrClientToken: "pubf5bbdc9d5e227feae77a9ad9f5e1013a",
site: "datadoghq.com"
},
siftAccountId: "60f88a09293fb116c8220753",
siftBeaconKey: "d9c3d7901c",
externalServices: {
cpp: "https://promos-api.racing.fanduel.com"
}
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/qa/fdr.ts
const {
STORYBLOK_TOKENS: STORYBLOK_TOKENS_QA
} = require("../../utils/fdr/storyblok");
const {
APPTENTIVE_TOKENS: APPTENTIVE_TOKENS_QA
} = require("../../utils/fdr/apptentive");
module.exports = {
domain: {
desktop: "racing.qa.fndl.dev",
mobile: "racing.qa.fndl.dev",
talentPicks: "racing.qa.fndl.dev/talent-picks/",
accountWallet: "account.racing.qa.fndl.dev",
equibase: "equibase-store.qa.fndl.dev"
},
service_host: "racing.qa.fndl.dev",
externalDomain: {
FDTermsConditions: "https://www.qa.fndl.dev/terms",
FDPolicy: "https://www.qa.fndl.dev/privacy",
FDRLoginBridge: "https://www.qa.fndl.dev/sso-auth/fdracing",
FDRSignup:
"https://www.qa.fndl.dev/join?next=%2Fsso-auth%2Ffdracing%3Fredirect_uri%3D"
},
externalServices: {
fanduel: "https://api.qa.fndl.dev",
cpp: "https://promos-api.racing.fanduel.qa.fndl.dev"
},
clientId: "a301e728606047a5b6522727d495b3ed",
brazeId: "d1c732dc-ad0d-49a5-acb7-d360cd0fee38",
storyblokToken: STORYBLOK_TOKENS_QA.QA,
storyblokVersion: "draft",
appTentiveIos: APPTENTIVE_TOKENS_QA.IOS.QA,
appTentiveAndroid: APPTENTIVE_TOKENS_QA.ANDROID.QA,
appTentiveWeb: APPTENTIVE_TOKENS_QA.WEB.QA
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/qa/iowa.ts
module.exports = {
domain: {
desktop: "ia-qa.tvg.com",
mobile: "ia-qa.tvg.com",
talentPicks: "ia-qa.tvg.com/talent-picks/",
equibase: "equibase-store-qa.tvg.com"
},
recaptchaID: "6Lf-4hUqAAAAAGupa6W70kpZVsaFd7yaxz5pHD8r",
recaptchaIdNative: "6Le9B1YqAAAAAJEWJZsQittPtHDcjz6xLNORgHyI"
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/qa/pabets.ts
module.exports = {
domain: {
desktop: "pabets-qa.tvg.com",
mobile: "pabets-qa.tvg.com",
talentPicks: "pabets-qa.tvg.com/talent-picks/",
equibase: "equibase-store-qa.tvg.com"
},
recaptchaID: "6Lf-4hUqAAAAAGupa6W70kpZVsaFd7yaxz5pHD8r",
recaptchaIdNative: "6Le9B1YqAAAAAJEWJZsQittPtHDcjz6xLNORgHyI"
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/qa/tvg.ts
module.exports = {
domain: {
desktop: "www-qa.tvg.com",
mobile: "www-qa.tvg.com",
talentPicks: "www-qa.tvg.com/talent-picks/",
accountWallet: "account.racing.qa.fndl.dev",
equibase: "equibase-store-qa.tvg.com"
},
recaptchaID: "6Lf-4hUqAAAAAGupa6W70kpZVsaFd7yaxz5pHD8r",
recaptchaIdNative: "6Le9B1YqAAAAAJEWJZsQittPtHDcjz6xLNORgHyI"
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/staging/4njbets.ts
module.exports = {
domain: {
desktop: "4njbets-staging.us.betfair.com",
mobile: "4njbets-staging.us.betfair.com",
talentPicks: "4njbets-staging.us.betfair.com/talent-picks/",
equibase: "equibase-store.us.betfair.com"
},
service_host: "service-staging.us.betfair.com",
recaptchaID: "6LeIYBcqAAAAAE2wDhSub9Ic8oeidAiiUt4gYM4a",
recaptchaIdNative: "6LfRQloqAAAAABY9v2RydlB10Lfgb5ODmvygHy3G"
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/staging/base.ts
const {
AMPLITUDE_API_KEYS: AMPLITUDE_API_KEYS_STAGING
} = require("../../utils/urp/amplitude");
const {
AMPLITUDE_API_KEYS: AMPLITUDE_API_KEYS_FDR_STAGING,
AMPLITUDE_API_KEYS_XSELL: AMPLITUDE_API_KEYS_FDR_XSELL_STAGING
} = require("../../utils/fdr/amplitude");
const {
AMPLITUDE_API_KEYS: AMPLITUDE_API_KEYS_MEP_STAGING
} = require("../../utils/mep/amplitude");
const {
AMPLITUDE_API_KEYS: AMPLITUDE_API_KEYS_TVG4_STAGING
} = require("../../utils/tvg4/amplitude");
module.exports = {
domain: {
desktop: "www-staging.tvg.com",
mobile: "www-staging.tvg.com",
talentPicks: "www-staging.tvg.com/talent-picks/",
equibase: "equibase-store.tvg.com"
},
externalDomain: {
support: "https://support.tvg.com",
contactSupport:
"https://support.tvg.com/tvg/s/articles/360005946853-Contact-Support",
NCPGamblingChat: "http://www.ncpgambling.org/chat"
},
service_host: "service-staging.tvg.com",
google: {
tvg4: {
gtmId: "KTDSBG",
gtmEnv: "668",
gtmAuth: "Q3mmSetXL-9o6LJDN6Tz1A",
siteVersion: "desktop",
productVersion: "TVG4"
},
tvg5: {
gtmId: "KTDSBG",
gtmEnv: "668",
gtmAuth: "Q3mmSetXL-9o6LJDN6Tz1A",
siteVersion: "desktop",
productVersion: "TVG5"
},
touch2: {
gtmId: "KTDSBG",
gtmEnv: "668",
gtmAuth: "Q3mmSetXL-9o6LJDN6Tz1A",
siteVersion: "mobile_web",
productVersion: "MEP"
},
ios: {
gtmId: "KTDSBG",
gtmEnv: "668",
gtmAuth: "Q3mmSetXL-9o6LJDN6Tz1A",
siteVersion: "ios_native"
},
touch3: {
gtmId: "KTDSBG",
gtmEnv: "668",
gtmAuth: "Q3mmSetXL-9o6LJDN6Tz1A",
siteVersion: "mobile_web",
productVersion: "MEP"
},
androidwrapper: {
gtmId: "KTDSBG",
gtmEnv: "668",
gtmAuth: "Q3mmSetXL-9o6LJDN6Tz1A",
siteVersion: "android_native",
productVersion: "android_gps"
},
tvgandroid: {
gtmId: "KTDSBG",
gtmEnv: "668",
gtmAuth: "Q3mmSetXL-9o6LJDN6Tz1A",
siteVersion: "android_native",
productVersion: "android_apk"
},
ios2: {
gtmId: "KTDSBG",
gtmEnv: "668",
gtmAuth: "Q3mmSetXL-9o6LJDN6Tz1A",
siteVersion: "ios_native"
},
fdrdesktop: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "desktop",
productVersion: "URP"
},
fdrmobile: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "mobile_web",
productVersion: "MEP"
},
fdrios: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "ios_native",
productVersion: "MEP"
},
fdrandroid: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "android_native",
productVersion: "android_apk"
},
fdrandroidwrapper: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "android_native",
productVersion: "android_apk"
},
fdrandroidgps: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "android_native",
productVersion: "android_apk"
},
fdriosxsell: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "x-sell",
productVersion: "MEP"
},
fdrandroidxsell: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "x-sell",
productVersion: "android_apk"
},
iosnative: {
gtmId: "KTDSBG",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "ios_native",
productVersion: "ios_native"
},
gcs: {
url: "https://storage.googleapis.com",
tvgStatic: "tvg-static-staging"
}
},
amplitude: {
tvg5: {
amplitudeAPI: AMPLITUDE_API_KEYS_STAGING.STAGING,
siteVersion: "desktop",
sitePlatform: "desktop",
product: "tvg_urp"
},
tvg5fdr: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_STAGING.STAGING,
siteVersion: "desktop",
sitePlatform: "desktop",
product: "fdr_standalone_lobby"
},
fdrmobile: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_STAGING.STAGING,
siteVersion: "mobile_web",
sitePlatform: "mobile_web",
product: "fdr_standalone_lobby"
},
fdrios: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_STAGING.STAGING,
siteVersion: "native",
sitePlatform: "ios",
product: "fdr_standalone_lobby"
},
fdrandroid: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_STAGING.STAGING,
siteVersion: "native",
sitePlatform: "android",
product: "fdr_standalone_lobby",
androidDistributionMethod: "self_dist"
},
fdrandroidwrapper: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_STAGING.STAGING,
siteVersion: "native",
sitePlatform: "android",
product: "fdr_standalone_lobby",
androidDistributionMethod: "google_playstore"
},
fdrandroidgps: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_STAGING.STAGING,
siteVersion: "native",
sitePlatform: "android",
product: "fdr_standalone_lobby",
androidDistributionMethod: "google_playstore"
},
fdriosxsell: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_XSELL_STAGING.STAGING,
siteVersion: "native",
sitePlatform: "ios",
product: "fdr_xsell_lobby"
},
fdrandroidxsell: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_XSELL_STAGING.STAGING,
siteVersion: "native",
sitePlatform: "android",
product: "fdr_xsell_lobby"
},
touch3: {
amplitudeAPI: AMPLITUDE_API_KEYS_MEP_STAGING.STAGING,
siteVersion: "mobile_web",
sitePlatform: "mobile_web",
product: "tvg_mep"
},
androidwrapper: {
amplitudeAPI: AMPLITUDE_API_KEYS_MEP_STAGING.STAGING,
siteVersion: "native",
sitePlatform: "android",
product: "tvg_mep",
androidDistributionMethod: "self_dist"
},
tvgandroid: {
amplitudeAPI: AMPLITUDE_API_KEYS_TVG4_STAGING.STAGING,
siteVersion: "native",
sitePlatform: "android",
product: "tvg_mep",
androidDistributionMethod: "self_dist"
},
tvg4: {
amplitudeAPI: AMPLITUDE_API_KEYS_TVG4_STAGING.STAGING,
siteVersion: "desktop",
sitePlatform: "desktop",
product: "tvg_tvg4"
}
},
clientId: "88a7876dc4c330f0dfa6c5c611818d62",
brazeId: "908c5857-650b-4f31-8ec7-63b15dc11d1d",
siftAccountId: "60f88a09293fb116c8220750",
siftBeaconKey: "df80113946",
perimeterxId: "BMkUl9nm",
storyblokToken: "4LYunuxrMxUarw6vBokjKAtt",
storyblokVersion: "draft",
placesAPI: "AIzaSyBwhD0RAB-vMDrx4IDcO_gezIVGpn7dFks",
paypalID:
"AfOWmRjlT73hGanCAUypmRtFas_NsPcXek2_fL8XOIrJHBDoUxcSEVBQ72Ls4fc_2xgJSWK3gTDrgjhI",
apptentiveID: "61f08786218b3765d7000024",
apptentiveTvg5: "6204200f48b9d649d700005d",
apptentiveIosKey: "IOS-TVG-DEVELOPMENT-b03e074ea0dd",
apptentiveIosSignature: "693be9827104eaa410239b062acd34b8",
apptentiveAndroidKey: "ANDROID-TVG-DEVELOPMENT",
apptentiveAndroidSignature: "809f6458570a7d899a7ff37684765a4d",
sonarQube: {
serverUrl: "https://sonarqube.gcp-dev.tvg.com",
token: "8836caf742bb1c13755da2d957ba5d1674adbc43",
projectKey: "tvg-monorepo"
},
datadogRum: {
desktopApplicationId: "123b949b-108c-4306-bea0-9227242f5b17",
desktopClientToken: "pub748e107dd1bd28256dad4b1425dda2e3",
mobileApplicationId: "03715ae6-b7e2-4b30-ac7b-cf6a5bfdf763",
mobileClientToken: "pub333a7706c3a954d17d9db1becba22673",
fdrApplicationId: "c15f8a9f-f7a7-4108-97f3-9e81d2e936fb",
fdrClientToken: "pubf5bbdc9d5e227feae77a9ad9f5e1013a",
site: "datadoghq.com"
},
externalServices: {
cpp: "https://promos-api.racing.fanduel.com"
}
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/staging/fdr.ts
const {
STORYBLOK_TOKENS: STORYBLOK_TOKENS_STAGING
} = require("../../utils/fdr/storyblok");
const {
APPTENTIVE_TOKENS: APPTENTIVE_TOKENS_STAGING
} = require("../../utils/fdr/apptentive");
module.exports = {
domain: {
desktop: "staging.racing.fanduel.com",
mobile: "staging.racing.fanduel.com",
talentPicks: "staging.racing.fanduel.com/talent-picks/",
accountWallet: "account.racing.fanduel.com",
equibase: "equibase-store.fanduel.com"
},
service_host: "service-staging.racing.fanduel.com",
externalDomain: {
FDTermsConditions: "https://fanduel.com/terms",
FDPolicy: "https://fanduel.com/privacy",
FDRLoginBridge: "https://fanduel.com/sso-auth/fdracing",
FDRSignup:
"https://www.fanduel.com/join?next=%2Fsso-auth%2Ffdracing%3Fredirect_uri%3D"
},
externalServices: {
fanduel: "https://api.fanduel.com",
cpp: "https://promos-api.racing.fanduel.com"
},
clientId: "a301e728606047a5b6522727d495b3ed",
brazeId: "e0b90c9d-dfd9-4809-a627-565a5cd7f3b2",
storyblokToken: STORYBLOK_TOKENS_STAGING.STAGING,
storyblokVersion: "draft",
appTentiveIos: APPTENTIVE_TOKENS_STAGING.IOS.PRODUCTION,
appTentiveAndroid: APPTENTIVE_TOKENS_STAGING.ANDROID.PRODUCTION,
appTentiveWeb: APPTENTIVE_TOKENS_STAGING.WEB.PRODUCTION
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/staging/iowa.ts
module.exports = {
domain: {
desktop: "ia-staging.tvg.com",
mobile: "ia-staging.tvg.com",
talentPicks: "ia-staging.tvg.com/talent-picks/",
equibase: "equibase-store.tvg.com"
},
recaptchaID: "6LeIYBcqAAAAAE2wDhSub9Ic8oeidAiiUt4gYM4a",
recaptchaIdNative: "6LfRQloqAAAAABY9v2RydlB10Lfgb5ODmvygHy3G"
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/staging/pabets.ts
module.exports = {
domain: {
desktop: "pabets-staging.tvg.com",
mobile: "pabets-staging.tvg.com",
talentPicks: "pabets-staging.tvg.com/talent-picks/",
equibase: "equibase-store.tvg.com"
},
recaptchaID: "6LeIYBcqAAAAAE2wDhSub9Ic8oeidAiiUt4gYM4a",
recaptchaIdNative: "6LfRQloqAAAAABY9v2RydlB10Lfgb5ODmvygHy3G"
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/staging/tvg.ts
module.exports = {
domain: {
desktop: "www-staging.tvg.com",
mobile: "www-staging.tvg.com",
talentPicks: "www-staging.tvg.com/talent-picks/",
accountWallet: "account.racing.fanduel.com",
equibase: "equibase-store.tvg.com"
},
recaptchaID: "6LeIYBcqAAAAAE2wDhSub9Ic8oeidAiiUt4gYM4a",
recaptchaIdNative: "6LfRQloqAAAAABY9v2RydlB10Lfgb5ODmvygHy3G"
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/src/brand.ts
import type { Brand } from "./types";
export const AWS_HOSTNAME_SUBDOMAIN = "racing.fndlext.net"; // AWS subdomain
export const BRAND_TVG = "tvg";
export const BRAND_FDR = "fdr";
export const BRAND_4NGBETS = "4njbets";
export const BRAND_PABETS = "pabets";
export const BRAND_IOWA = "iowa";
export const BRAND_ALL = [
BRAND_TVG,
BRAND_FDR,
BRAND_4NGBETS,
BRAND_PABETS,
BRAND_IOWA
];
export default (hostname: string | undefined): Brand => {
if (hostname) {
if (/(nj|4njbets)(\.|-)/gi.test(hostname)) {
return BRAND_4NGBETS;
}
if (/(pa|pabets)(\.|-)/gi.test(hostname)) {
return BRAND_PABETS;
}
if (/ia(\.|-)/gi.test(hostname)) {
return BRAND_IOWA;
}
if (
/fdbox|fanduel(\.|-)|racing/gi.test(
hostname.replace(AWS_HOSTNAME_SUBDOMAIN, "")
)
) {
return BRAND_FDR;
}
}
return BRAND_TVG;
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/src/environment.ts
import type { Env } from "./types";
import { isBrowser } from "./utils";
export const AW_ENV_MAPPING = {
dev: "dev",
qa: "qa",
staging: "prod",
production: "prod",
// aws environments
int: "qa",
stg: "prod",
prd: "prod"
};
const env: Env[] = [
"production",
"staging",
"qa",
"aws-stg",
"aws-int",
"aws-prd"
];
const defaultEnv: Env = env[5];
const getEnvironmentByHostname = (hostname?: string): Env => {
if (hostname === "10.0.2.2") {
return "aws-int";
}
if (!hostname) {
return defaultEnv;
}
// aws environments
if (/stg\./gi.test(hostname)) {
return "aws-stg";
}
if (/int\./gi.test(hostname)) {
return "aws-int";
}
if (/prd\./gi.test(hostname)) {
return "aws-prd";
}
// gcp environments
if (/(stage\.|staging\.|cert\.)/gi.test(hostname)) {
return "aws-stg";
}
if (/qa\.|dev\./gi.test(hostname)) {
return "aws-int";
}
return defaultEnv;
};
/* eslint-disable */
const getEnvironmentInBrowser = (): Env | false =>
!!window.__TVG_GLOBALS__ &&
!!window.__TVG_GLOBALS__.ENVIRONMENT &&
(window.__TVG_GLOBALS__.ENVIRONMENT as Env);
/* eslint-enable */
const getEnvironmentInServer = (): Env | false =>
// @FIXME in the next line we are doing an explicit typecast, that's why we
// need the `any` type. However we could try to find how to extend the type of
// process.env instead.
typeof process !== "undefined" &&
typeof process.env.ENVIRONMENT === "string" &&
(process.env.ENVIRONMENT === "dev"
? ("qa" as Env)
: env.includes(process.env.ENVIRONMENT as Env) &&
(process.env.ENVIRONMENT as Env));
/**
* When fetching an environment two variables have priority:
* - in the browser, node-grid should inject a global variable `__TVG_GLOBALS__.ENVIRONMENT`
* - in the server, the container has the variable ENVIRONMENT
* These two variables allows to be deterministic about the environment, and only
* if by some unknown reason they fail, then we check the hostname as a last resourt
*/
export default (hostname?: string): Env =>
// eslint-disable-next-line
isBrowser() && window.__TVG_GLOBALS__
? getEnvironmentInBrowser() || getEnvironmentByHostname(hostname)
: getEnvironmentInServer() || getEnvironmentByHostname(hostname);
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/default.ts
const { STORYBLOK_TOKENS } = require("../utils/fdr/storyblok");
const { APPTENTIVE_TOKENS } = require("../utils/fdr/apptentive");
const { AMPLITUDE_API_KEYS } = require("../utils/urp/amplitude");
const {
AMPLITUDE_API_KEYS: AMPLITUDE_API_KEYS_FDR,
AMPLITUDE_API_KEYS_XSELL: AMPLITUDE_API_KEYS_FDR_XSELL
} = require("../utils/fdr/amplitude");
const {
AMPLITUDE_API_KEYS: AMPLITUDE_API_KEYS_MEP
} = require("../utils/mep/amplitude");
const {
AMPLITUDE_API_KEYS: AMPLITUDE_API_KEYS_TVG4
} = require("../utils/tvg4/amplitude");
const defaultOption = {
domain: {
desktop: "www.tvg.com",
mobile: "touch.tvg.com",
talentPicks: "www.tvg.com/talent-picks/"
},
externalDomain: {
support: "https://support.tvg.com",
contactSupport:
"https://support.tvg.com/tvg/s/articles/360005946853-Contact-Support",
NCPGamblingChat: "http://www.ncpgambling.org/chat"
},
externalServices: {
cpp: "https://promos-api.racing.fanduel.com"
},
service_host: "service.tvg.com",
service: {
graph: "/graph/v2/query",
graphWS: "/graph/v2/subscriptions",
wtx: "/wtx/v1",
pay: "/pay/v1",
capi: "/capi/v1",
log: "/uel/v1/log-event",
usa: "/usa/v2",
uam: "/uam/v1",
prf: "/prf/v1",
geo: "/geo/v1",
uwt: "/uwt/v1",
wro: "/wro/v1",
uas: "/uas/v1",
slp: "/slp/v2",
ufc: "/ufc/v1",
rcn: "/rcn/v1",
tpm: "/tpm/v1",
fcp: "/fcp/v2/query",
rwd: "/rwd/v1",
pes: "/pes/v1",
pro: "/pro/v1",
rda: "/rda/v1/query",
fdr: "/fdr/v2",
wrc: "/wrc/v1",
cus: "/cus/v1",
pxp: "/pxp/v1/proxy",
gas: "/gas/v1/query",
gasUsers: "/gas/v1/users",
gasWS: "/gas/v1/subscriptions",
behg: "/behg/v1/query", // behg -> bets history graph
behgWS: "/behg/v1/subscriptions", // behg -> bets history graph
fem: "/fem/v1",
crf: "/crf/v1",
ach: "/ach/v1",
ccp: "/ccp/v1",
uc: "/uc/v1",
mpak: "/mpak/v1",
chk: "/chk/v1",
pnm: "/pnm/v1",
mzm: "/mzm/v1",
fed: "/gatewayfederation/v1/query",
fedWS: "/gatewayfederation/v1/subscription",
cosmo: "/cosmo/v1/graphql",
cosmoWS: "/cosmo/v1/graphql",
seo: "/seo/v1"
},
serviceName: {
graph: "service-javagraph",
graphWS: "service-javagraph-subscriptions",
wtx: "service-wtx",
pay: "service-pay",
capi: "service-capi",
log: "service-uel",
usa: "service-usa",
uam: "service-uam",
prf: "service-prf",
geo: "service-geo",
uwt: "service-uwt",
wro: "service-wro",
uas: "service-uas",
slp: "service-slp",
ufc: "service-ufc",
rcn: "service-rcn",
tpm: "service-tpm",
fcp: "service-fcp",
rwd: "service-rwd",
pes: "service-pes",
pro: "service-pro",
rda: "service-rda",
fdr: "service-fdr",
wrc: "service-wrc",
cus: "service-cus",
pxp: "service-pxp",
gas: "service-gas",
gasUsers: "service-gas",
gasWS: "service-gas-subscriptions",
behg: "service-behg",
behgWS: "service-behg",
fem: "service-fem",
crf: "service-crf",
ach: "service-ach",
ccp: "service-ccp",
uc: "service-uc",
mpak: "service-mpak",
chk: "service-chk",
pnm: "service-pnm",
mzm: "service-mzm",
seo: "service-seo"
},
google: {
tvg4: {
gtmId: "KTDSBG",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "desktop",
productVersion: "TVG4"
},
tvg5: {
gtmId: "KTDSBG",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "desktop",
productVersion: "TVG5"
},
touch2: {
gtmId: "NX7J29",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "mobile_web",
productVersion: "MEP"
},
touch3: {
gtmId: "NX7J29",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "mobile_web",
productVersion: "MEP"
},
androidwrapper: {
gtmId: "NX7J29",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "android_native",
productVersion: "android_gps"
},
tvgandroid: {
gtmId: "NX7J29",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "android_native",
productVersion: "android_apk"
},
ios: {
gtmId: "NX7J29",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "ios_native"
},
ios2: {
gtmId: "NX7J29",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "ios_native"
},
fdrmobile: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "mobile_web",
productVersion: "MEP"
},
fdrios: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "ios_native",
productVersion: "MEP"
},
fdrandroid: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "android_native",
productVersion: "android_apk"
},
fdrandroidwrapper: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "android_native",
productVersion: "android_apk"
},
fdrandroidgps: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "android_native",
productVersion: "android_apk"
},
fdriosxsell: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "x-sell",
productVersion: "MEP"
},
fdrandroidxsell: {
gtmId: "NSHBQSR",
gtmEnv: "5",
gtmAuth: "brY2SVdkc5NjBXD6t4kZTg",
siteVersion: "x-sell",
productVersion: "android_apk"
},
iosnative: {
gtmId: "NX7J29",
gtmEnv: "482",
gtmAuth: "EM7EyobnJbhcGWCe5IOyyw",
siteVersion: "ios_native",
productVersion: "ios_native"
}
},
amplitude: {
tvg5: {
amplitudeAPI: AMPLITUDE_API_KEYS.QA,
siteVersion: "desktop",
sitePlatform: "desktop",
product: "tvg_urp"
},
fdrmobile: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR.QA,
siteVersion: "mobile_web",
sitePlatform: "mobile_web",
product: "fdr_standalone_lobby"
},
fdrios: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR.QA,
siteVersion: "native",
sitePlatform: "ios",
product: "fdr_standalone_lobby"
},
fdrandroid: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR.QA,
siteVersion: "native",
sitePlatform: "android",
product: "fdr_standalone_lobby",
androidDistributionMethod: "self_dist"
},
fdrandroidwrapper: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR.QA,
siteVersion: "native",
sitePlatform: "android",
product: "fdr_standalone_lobby",
androidDistributionMethod: "google_playstore"
},
fdrandroidgps: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR.QA,
siteVersion: "native",
sitePlatform: "android",
product: "fdr_standalone_lobby",
androidDistributionMethod: "google_playstore"
},
fdriosxsell: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_XSELL.QA,
siteVersion: "x-sell",
sitePlatform: "ios",
product: "fdr_xsell_lobby"
},
fdrandroidxsell: {
amplitudeAPI: AMPLITUDE_API_KEYS_FDR_XSELL.QA,
siteVersion: "x-sell",
sitePlatform: "android",
product: "fdr_xsell_lobby"
},
touch3: {
amplitudeAPI: AMPLITUDE_API_KEYS_MEP.QA,
siteVersion: "mobile_web",
sitePlatform: "mobile_web",
product: "tvg_mep"
},
androidwrapper: {
amplitudeAPI: AMPLITUDE_API_KEYS_MEP.QA,
siteVersion: "native",
sitePlatform: "android",
product: "tvg_mep",
androidDistributionMethod: "self_dist"
},
tvgandroid: {
amplitudeAPI: AMPLITUDE_API_KEYS_MEP.QA,
siteVersion: "native",
sitePlatform: "android",
product: "tvg_mep",
androidDistributionMethod: "self_dist"
},
tvg4: {
amplitudeAPI: AMPLITUDE_API_KEYS_TVG4.QA,
siteVersion: "desktop",
sitePlatform: "desktop",
product: "tvg_tvg4"
}
},
clientId: "88a7876dc4c330f0dfa6c5c611818d62",
brazeId: "a728acfe-5f28-42c0-9c08-174ecb4394d5",
perimeterxId: "TK74ox9H",
storyblokToken: STORYBLOK_TOKENS.QA,
storyblokVersion: "draft",
placesAPI: "AIzaSyCvQe2IeP1DnZT6v0PLK-n4bjK9RqcEarQ",
paypalID:
"AbOXWUz9wwf1L17esie_vpZ99gwz9hxQmobirFtIirrZbE3levMoS_lb7BWll5DnB2qB1m11Mmmge8JV",
apptentiveID: "61f08786218b3765d7000024",
apptentiveTvg5: "6204200f48b9d649d700005d",
sonarQube: {
serverUrl: "https://sonarqube.gcp-dev.tvg.com",
token: "8836caf742bb1c13755da2d957ba5d1674adbc43",
projectKey: "tvg-monorepo"
},
datadogRum: {
desktopApplicationId: "123b949b-108c-4306-bea0-9227242f5b17",
desktopClientToken: "pub748e107dd1bd28256dad4b1425dda2e3",
mobileApplicationId: "03715ae6-b7e2-4b30-ac7b-cf6a5bfdf763",
mobileClientToken: "pub333a7706c3a954d17d9db1becba22673",
fdrApplicationId: "c15f8a9f-f7a7-4108-97f3-9e81d2e936fb",
fdrClientToken: "pubf5bbdc9d5e227feae77a9ad9f5e1013a",
site: "datadoghq.com"
},
siftAccountId: "60f88a09293fb116c8220753",
siftBeaconKey: "d9c3d7901c",
appTentiveIos: APPTENTIVE_TOKENS.IOS.PRODUCTION,
appTentiveAndroid: APPTENTIVE_TOKENS.ANDROID.PRODUCTION,
appTentiveWeb: APPTENTIVE_TOKENS.WEB.PRODUCTION
};
export default defaultOption;
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/base.ts
/* eslint-disable global-require */
const base = {
qa: require("./qa/base"),
staging: require("./staging/base"),
production: require("./production/base"),
// aws environments
"aws-int": require("./aws-int/base"),
"aws-stg": require("./aws-stg/base"),
"aws-prd": require("./aws-prd/base")
};
export default base;
webpack://frontend-mybets/../../packages/tvg-lib-conf/content/brand.ts
/* eslint-disable global-require */
const brand = {
qa: {
"4njbets": require("./qa/4njbets"),
iowa: require("./qa/iowa"),
pabets: require("./qa/pabets"),
tvg: require("./qa/tvg"),
fdr: require("./qa/fdr"),
base: require("./qa/base")
},
staging: {
"4njbets": require("./staging/4njbets"),
iowa: require("./staging/iowa"),
pabets: require("./staging/pabets"),
tvg: require("./staging/tvg"),
fdr: require("./staging/fdr"),
base: require("./staging/base")
},
production: {
"4njbets": require("./production/4njbets"),
iowa: require("./production/iowa"),
pabets: require("./production/pabets"),
tvg: require("./production/tvg"),
fdr: require("./production/fdr"),
base: require("./production/base")
},
"aws-int": {
"4njbets": require("./aws-int/4njbets"),
iowa: require("./aws-int/iowa"),
pabets: require("./aws-int/pabets"),
tvg: require("./aws-int/tvg"),
fdr: require("./aws-int/fdr"),
base: require("./aws-int/base")
},
"aws-stg": {
"4njbets": require("./aws-stg/4njbets"),
iowa: require("./aws-stg/iowa"),
pabets: require("./aws-stg/pabets"),
tvg: require("./aws-stg/tvg"),
fdr: require("./aws-stg/fdr"),
base: require("./aws-stg/base")
},
"aws-prd": {
"4njbets": require("./aws-prd/4njbets"),
iowa: require("./aws-prd/iowa"),
pabets: require("./aws-prd/pabets"),
tvg: require("./aws-prd/tvg"),
fdr: require("./aws-prd/fdr"),
base: require("./aws-prd/base")
}
};
export default brand;
webpack://frontend-mybets/../../packages/tvg-lib-conf/src/brazeDevice.ts
import { get } from "lodash";
import type { Product } from "./types";
const deviceMapped = {
touch3: {
iOS: "web_ios",
AndroidOS: "web_android"
},
ios2: {
iOS: "iOS",
AndroidOS: "Android"
},
tvg4: {
iOS: "desktop",
AndroidOS: "desktop"
},
fdrmobile: {
iOS: "web_ios",
AndroidOS: "web_android"
},
fdrios: {
iOS: "iOS",
AndroidOS: "Android"
},
fdrandroid: {
iOS: "iOS",
AndroidOS: "Android"
},
androidwrapper: {
iOS: "iOS",
AndroidOS: "Android"
}
};
export default (os: string, product: Product) =>
get(deviceMapped, `${product}.${os}`, "web_ios");
webpack://frontend-mybets/../../packages/tvg-lib-conf/src/features.ts
import axios from "axios";
import { attempt } from "./utils";
import type {
ServiceConfig,
FeatureToggles,
Product,
Device,
Brand
} from "./types";
const parseFeatures = (featuresData: string): FeatureToggles | false => {
let features;
const data = attempt(() => JSON.parse(decodeURIComponent(featuresData)));
if (!(data instanceof Error) && typeof data === "object") {
features = data as FeatureToggles;
}
return features || false;
};
const readFeatures = (): FeatureToggles | false => {
let featuresObject;
/* eslint-disable */
if (
typeof window !== "undefined" &&
window.__TVG_GLOBALS__ &&
window.__TVG_GLOBALS__.FEATURE_TOGGLES
) {
featuresObject = parseFeatures(
window.__TVG_GLOBALS__.FEATURE_TOGGLES
) as FeatureToggles;
}
/* eslint-enable */
return featuresObject || false;
};
const getFeatures = (
service: ServiceConfig,
product: Product,
device: Device,
brand: Brand,
serverSide: boolean
): Promise<FeatureToggles | false> => {
const features = readFeatures();
if (features || (typeof window === "undefined" && !serverSide)) {
return Promise.resolve().then(() => features);
}
const requestOptions = {
url: `${service.capi}/featureToggles/${product}/${device}/${brand}`,
method: "GET",
withCredentials: true
};
return axios(requestOptions).then((result) =>
result.data
? result.data
: Promise.reject(new Error("No feature toggles returned"))
);
};
export default { readFeatures, getFeatures };
webpack://frontend-mybets/../../packages/tvg-lib-conf/src/messages.ts
import axios from "axios";
import { attempt } from "./utils";
import type { Messages, Product, Device, Brand } from "./types";
let cachedMessages: Record<string, string> = {};
const parseMessages = (messagesData: string): Messages | {} => {
let messages = {};
const data = attempt(() => JSON.parse(decodeURIComponent(messagesData))) as
| { response: { [key: string]: string } }
| Error;
if (!(data instanceof Error) && typeof data === "object" && data.response) {
messages = data.response;
}
return messages;
};
const readMessages = (
namespaces: Array<string> | undefined = undefined
): Messages => {
let messagesObject = {};
// reads messages from server side injection stores in cache
/* eslint-disable */
if (
typeof window !== "undefined" &&
window.__TVG_GLOBALS__ &&
window.__TVG_GLOBALS__.MESSAGES
) {
messagesObject = parseMessages(window.__TVG_GLOBALS__.MESSAGES);
cachedMessages = { ...messagesObject, ...cachedMessages };
messagesObject = cachedMessages;
}
/* eslint-enable */
if (cachedMessages && Object.keys(cachedMessages).length > 0) {
// reads messages from cached data
if (namespaces) {
messagesObject = Object.assign(
{},
...namespaces.map((name) => cachedMessages[name])
);
} else {
const namespaceMap = Object.keys(cachedMessages);
messagesObject = Object.assign(
{},
...namespaceMap.map((name) => cachedMessages[name])
);
}
}
return messagesObject;
};
// @deprecated
const getMessages = (
namespaces: string[],
capiEndpoint: string,
product: Product,
device: Device,
brand: Brand,
forceFetch: boolean
): Promise<Messages | false> => {
if (!namespaces || !(namespaces instanceof Array)) {
return Promise.reject(new Error("No namespaces were provided"));
}
if (!forceFetch) {
const messages = readMessages(namespaces);
if (Object.keys(messages).length > 0 && messages.constructor === Object) {
return Promise.resolve().then(() => messages);
}
}
const requestOptions = {
url: `${capiEndpoint}/messages/namespace?product=${product}&device=${device}&brand=${brand}&namespace=${namespaces.join(
","
)}`,
method: "GET",
withCredentials: true
};
return axios(requestOptions).then((result) => {
let messagesMap = [];
let messages = {};
if (
!result.data ||
!result.data.response ||
result.data.response.length < 1
) {
Promise.reject(new Error("No messages returned"));
} else {
messagesMap = namespaces.map((k) => result.data.response[k]);
messages = messagesMap.reduce((cache, values, i) => {
const msgs: Record<string, string> = {};
msgs[namespaces[i]] = values;
return { ...cache, ...msgs };
}, messages);
cachedMessages = { ...cachedMessages, ...messages };
}
return Object.assign({}, ...messagesMap);
});
};
export default { readMessages, getMessages };
webpack://frontend-mybets/../../packages/tvg-lib-conf/src/buildurl.ts
import queryString from "query-string";
import { get } from "lodash";
import type {
App,
Product,
Location,
Domain,
Params,
BrazeDevice
} from "./types";
import { isBrowser, isDev } from "./utils";
const microapps: App[] = ["rma", "dma", "prf", "referral"];
export default (
app: App | Product = "tvg4",
wrapper: boolean = false,
callback: string | boolean = false,
path: string = "",
params: Params | null = null,
relative: boolean = false
) =>
(
domain: Domain,
location: Location,
product: Product,
brazeDevice: BrazeDevice
) => {
let target: string = "";
let query: string = "";
const urlParams =
typeof params === "string" ? queryString.parse(params) : params;
const localhost = isBrowser()
? `http://${get(window, "location.hostname", "").trim()}${
get(window, "location.port", "").trim()
? `:${get(window, "location.port", "").trim()}`
: ""
}`
: `http://localhost:${process ? process.env.PORT : "8080"}`;
const pathName = `${path.indexOf("/") === 0 ? "" : "/"}${encodeURI(path)}`;
switch (app) {
case "rma":
target = `https://${domain.desktop}/registration${pathName}`;
break;
case "dma":
target = `https://${domain.desktop}/deposit${pathName}`;
break;
case "prf":
target = `https://${domain.desktop}/tvg-password-recovery/#${
path ? pathName : "/forgotcredentials"
}`;
break;
case "rgnative":
target = `https://${domain.desktop}/responsible-gaming-native`;
break;
case "promos":
target = `https://${domain.desktop}/promos${pathName}`;
break;
case "referral":
target = `https://${domain.desktop}/referral${pathName}`;
break;
case "talentPicks":
target = `https://${domain.talentPicks}${encodeURI(path)}`;
break;
case "accountWallet":
target = `https://${
domain.accountWallet || `account.${domain.mobile}`
}${pathName}`;
break;
case "tvg4":
case "touch3":
case "touch2":
case "ios":
case "ios2":
target = isDev()
? `${localhost}${pathName}`
: `https://${domain.mobile}${pathName}`;
break;
default:
target = isDev()
? `${localhost}${pathName}`
: `https://${domain.desktop}${pathName}`;
}
if (urlParams && Object.keys(urlParams)) {
query = Object.keys(urlParams)
.map((key) => {
const value = urlParams[key] || "";
return `${encodeURIComponent(key)}=${encodeURIComponent(
value as string
)}`;
})
.join("&");
}
let url = relative ? pathName : target;
if (microapps.includes(app as App)) {
url = `${target}?location=${location}&product=${product}${
wrapper ? "&wrapper=true" : ""
}&device=${brazeDevice}`;
if (callback) {
url = `${url}&callback=`;
if (typeof callback === "string") {
url = `${url}${encodeURIComponent(callback)}`;
} else if (
typeof callback === "boolean" &&
typeof document === "object"
) {
url = `${url}${encodeURIComponent(
`${document.location.host}${
document.location.pathname !== "/"
? document.location.pathname
: ""
}${document.location.search}`
)}`;
} else {
url = `${url}${encodeURIComponent(domain.desktop)}`;
}
}
url = `${url}${query ? "&" : ""}`;
} else {
url = `${url}${query ? "?" : ""}`;
}
return `${url}${query}`;
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/src/states.ts
export type StateType = {
abbreviation: string;
name: string;
wageringState: boolean;
};
export default [
{ abbreviation: "AL", name: "Alabama", wageringState: false },
{ abbreviation: "AK", name: "Alaska", wageringState: false },
{ abbreviation: "AZ", name: "Arizona", wageringState: true },
{ abbreviation: "AR", name: "Arkansas", wageringState: true },
{ abbreviation: "CA", name: "California", wageringState: true },
{ abbreviation: "CO", name: "Colorado", wageringState: true },
{ abbreviation: "CT", name: "Connecticut", wageringState: true },
{ abbreviation: "DE", name: "Delaware", wageringState: true },
{ abbreviation: "DC", name: "District of Columbia", wageringState: false },
{ abbreviation: "FL", name: "Florida", wageringState: true },
{ abbreviation: "GA", name: "Georgia", wageringState: false },
{ abbreviation: "HI", name: "Hawaii", wageringState: false },
{ abbreviation: "ID", name: "Idaho", wageringState: true },
{ abbreviation: "IL", name: "Illinois", wageringState: true },
{ abbreviation: "IN", name: "Indiana", wageringState: true },
{ abbreviation: "IA", name: "Iowa", wageringState: true },
{ abbreviation: "KS", name: "Kansas", wageringState: false },
{ abbreviation: "KY", name: "Kentucky", wageringState: true },
{ abbreviation: "LA", name: "Louisiana", wageringState: true },
{ abbreviation: "ME", name: "Maine", wageringState: false },
{ abbreviation: "MD", name: "Maryland", wageringState: true },
{ abbreviation: "MA", name: "Massachusetts", wageringState: true },
{ abbreviation: "MI", name: "Michigan", wageringState: true },
{ abbreviation: "MN", name: "Minnesota", wageringState: true },
{ abbreviation: "MS", name: "Mississippi", wageringState: false },
{ abbreviation: "MO", name: "Missouri", wageringState: false },
{ abbreviation: "MT", name: "Montana", wageringState: true },
{ abbreviation: "NE", name: "Nebraska", wageringState: false },
{ abbreviation: "NV", name: "Nevada", wageringState: false },
{ abbreviation: "NH", name: "New Hampshire", wageringState: true },
{ abbreviation: "NJ", name: "New Jersey", wageringState: true },
{ abbreviation: "NM", name: "New Mexico", wageringState: true },
{ abbreviation: "NY", name: "New York", wageringState: true },
{ abbreviation: "NC", name: "North Carolina", wageringState: false },
{ abbreviation: "ND", name: "North Dakota", wageringState: true },
{ abbreviation: "OH", name: "Ohio", wageringState: true },
{ abbreviation: "OK", name: "Oklahoma", wageringState: false },
{ abbreviation: "OR", name: "Oregon", wageringState: true },
{ abbreviation: "PA", name: "Pennsylvania", wageringState: true },
{ abbreviation: "RI", name: "Rhode Island", wageringState: true },
{ abbreviation: "SC", name: "South Carolina", wageringState: false },
{ abbreviation: "SD", name: "South Dakota", wageringState: true },
{ abbreviation: "TN", name: "Tennessee", wageringState: true },
{ abbreviation: "TX", name: "Texas", wageringState: false },
{ abbreviation: "UT", name: "Utah", wageringState: false },
{ abbreviation: "VT", name: "Vermont", wageringState: true },
{ abbreviation: "VA", name: "Virginia", wageringState: true },
{ abbreviation: "WA", name: "Washington", wageringState: true },
{ abbreviation: "WV", name: "West Virginia", wageringState: true },
{ abbreviation: "WI", name: "Wisconsin", wageringState: false },
{ abbreviation: "WY", name: "Wyoming", wageringState: true }
];
webpack://frontend-mybets/../../packages/tvg-lib-conf/src/graphContext.ts
import type {
Context,
Brand,
Product,
Device,
GraphBrand,
GraphProduct,
GraphDevice
} from "./types";
const productMap = {
tvg4: "TVG4",
tvg5: "TVG5",
touch2: "Touch",
touch3: "Touch3",
ios2: "IOS2",
ios: "ios",
exchange: "exchange",
login: "login",
fdrmobile: "FDRMOBILE",
fdrios: "FDRIOS",
fdriosxsell: "FDRIOS",
fdrandroid: "FDRANDROID",
fdrandroidgps: "FDRANDROID",
fdrandroidxsell: "FDRANDROID",
iosnative: "iosnative",
androidnative: "androidnative",
androidwrapper: "ANDROIDWRAPPER",
tvgandroid: "TVGANDROID"
};
const deviceMap = { desktop: "Desktop", mobile: "Mobile", tablet: "Mobile" };
const brandMap = {
"4njbets": "4NJBets",
pabets: "PABets",
iowa: "IA",
tvg: "TVG",
fdr: "FDR"
};
export default (brand: Brand, product: Product, device: Device): Context => ({
brand: brandMap[brand] as GraphBrand,
product: productMap[product] as GraphProduct,
device: deviceMap[device] as GraphDevice
});
webpack://frontend-mybets/../../packages/tvg-lib-conf/src/index.ts
import { get } from "lodash";
import MobileDetect from "mobile-detect";
import type { TvgConf, Product, Env } from "./types";
import tvgBrand, { BRAND_FDR } from "./brand";
import tvgEnvironment from "./environment";
import content from "./content";
import tvgDevice from "./device";
import getBrazeDevice from "./brazeDevice";
import tvgProduct, {
PRODUCTS_IOS,
PRODUCTS_FDR,
PRODUCTS_FDR_X_SELL
} from "./product";
import tvgLocation from "./location";
import tvgFeatures from "./features";
import tvgMessages from "./messages";
import tvgMetadata from "./metadata";
import buildUrl from "./buildurl";
import states from "./states";
import getGraphContext from "./graphContext";
import { isBrowser, isRN as isRNFunc } from "./utils";
const OS_IOS = "iOS";
let hostname: string;
let userAgent: string;
let setProduct = "tvg4" as Product;
const getBrand = (product: string, hostnameParam: string) =>
PRODUCTS_FDR.includes(product) ? BRAND_FDR : tvgBrand(hostnameParam);
const getAmplitudeConfig = (product: string, brand: string) => {
if (product === "tvg5" && brand === "fdr") {
return "tvg5fdr";
}
return product;
};
// appConf
// appConf is set on the react native app and contains the necessary info
// to instatiate tvgConf
const tvgConf = (
givenHostname: string | undefined = hostname,
givenUserAgent: string | undefined = userAgent,
givenProduct: Product | undefined = setProduct
): TvgConf => {
if (!givenHostname && typeof window !== "undefined" && window.location) {
// eslint-disable-next-line
hostname = window.location.hostname;
} else {
hostname = get(global, "appConf.hostname", null) || givenHostname;
}
if (!givenUserAgent && typeof window !== "undefined" && window.navigator) {
// eslint-disable-next-line
userAgent = window.navigator.userAgent;
} else {
userAgent = get(global, "appConf.userAgent", null) || givenUserAgent;
}
setProduct =
get(global, "appConf.product", null) || givenProduct || setProduct;
const uaInfo = new MobileDetect(userAgent);
const environment: Env =
get(global, "appConf.environment", null) || tvgEnvironment(hostname);
const isProduction = ["production", "aws-prd"].includes(environment);
const isStaging = ["staging", "aws-stg"].includes(environment);
const product = tvgProduct(setProduct);
const device =
get(global, "appConf.device", null) || tvgDevice(userAgent, product);
const os = PRODUCTS_IOS.includes(product)
? OS_IOS
: // @ts-ignore
(uaInfo.os(userAgent) as OS);
const features = tvgFeatures.readFeatures();
const messages = tvgMessages.readMessages();
const metadata = tvgMetadata();
const configs = content(environment);
const brand = getBrand(product, hostname);
const brandConfig = configs[brand];
const location = tvgLocation(brand);
const isRN = isRNFunc();
const gaContext = () => {
let finalProduct: string = product;
if (product === "androidwrapper" && brand === "fdr") {
finalProduct = "fdrandroidwrapper";
} else if (product === "tvg5" && brand === "fdr") {
finalProduct = "fdrdesktop";
}
return `google.${finalProduct}`;
};
const getForcedProductName = (forcedProduct: Product): Product => {
let finalProduct = forcedProduct;
if (PRODUCTS_FDR_X_SELL.includes(forcedProduct)) {
finalProduct = forcedProduct.replace("xsell", "") as Product; // Forcing cast to use Product type
} else if (forcedProduct === "fdrandroidgps") {
// FDR Google play store to side-loaded
finalProduct = "fdrandroid";
}
return finalProduct;
};
const amplitudeContext = `amplitude.${getAmplitudeConfig(product, brand)}`;
const brazeDevice = getBrazeDevice(os, product);
return {
brand,
device,
environment,
isProduction,
isStaging,
product,
features,
messages,
metadata,
os,
brazeDevice,
context: (productContext = product, forceStandalone = false) => {
const finalProduct = forceStandalone
? getForcedProductName(productContext)
: product;
return `${finalProduct}-${brand}`;
},
// @ts-ignore
config: (configPath) => get(brandConfig, configPath, brandConfig),
gaConfig: () => get(brandConfig, gaContext(), brandConfig),
amplitudeConfig: () => get(brandConfig, amplitudeContext, brandConfig),
getFeatures: (localDevice = device, serverSide = false) =>
tvgFeatures.getFeatures(
brandConfig.service,
getForcedProductName(product),
localDevice,
brand,
serverSide
),
getMessages: (namespaces, forceFetch = false) =>
tvgMessages.getMessages(
namespaces,
brandConfig.service.capi,
getForcedProductName(product),
device,
brand,
forceFetch
),
getStates: () => states,
getDomains: (name = "desktop") => {
const brandMap = Object.keys(configs);
// @ts-ignore
return brandMap.map((configBrand) => configs[configBrand].domain[name]);
},
getClientId: () =>
isBrowser()
? btoa(`${brandConfig.clientId}:`)
: Buffer.from(`${brandConfig.clientId}:`).toString("base64"),
getExternalDomain: () => get(brandConfig, "externalDomain", {}),
buildUrl: (options) => {
const {
app = product,
wrapper = false,
callback = false,
path = "",
params = null,
relative = false
} = options;
return buildUrl(
app,
wrapper,
callback,
path,
params,
relative
)(
brandConfig.domain,
brand === BRAND_FDR ? BRAND_FDR : location,
product,
brazeDevice
);
},
graphContext: () => getGraphContext(brand, product, device),
isRN,
isBrowser
};
};
let tvgConfInstance: TvgConf;
export default (
givenHostname: string | undefined = hostname,
givenUserAgent: string | undefined = userAgent,
givenProduct: Product | undefined = setProduct
) => {
if (
givenHostname !== hostname ||
givenUserAgent !== userAgent ||
givenProduct !== setProduct ||
!tvgConfInstance
) {
tvgConfInstance = tvgConf(givenHostname, givenUserAgent, givenProduct);
}
return tvgConfInstance;
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/src/device.ts
import MobileDetect from "mobile-detect";
import type { Device } from "./types";
import { PRODUCTS_MOBILE } from "./product";
export default (userAgent?: string, product?: string): Device => {
const uaInfo = new MobileDetect(userAgent || "");
let device = "desktop";
device = (uaInfo.mobile() && "mobile") || device;
device = (uaInfo.tablet() && "tablet") || device;
// tablet exception
if (device === "desktop") {
return PRODUCTS_MOBILE.includes(product || "") ? "tablet" : device;
}
return device as Device;
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/src/metadata.ts
import { attempt } from "./utils";
import type { Metadata } from "./types";
/* eslint-disable */
export default (): Metadata | false => {
let metadata;
if (
typeof window !== "undefined" &&
window.__TVG_GLOBALS__ &&
window.__TVG_GLOBALS__.METADATA
) {
const data = attempt(() =>
JSON.parse(decodeURIComponent(window.__TVG_GLOBALS__.METADATA || ""))
);
if (!(data instanceof Error)) {
metadata = data as Metadata;
}
}
return metadata || false;
};
/* eslint-enable */
webpack://frontend-mybets/../../packages/tvg-lib-conf/src/content.ts
import type { Env, Content } from "./types";
import configBase from "./base";
import { BRAND_ALL } from "./brand";
import defaults from "../content/default";
import base from "../content/base";
import tvgBrand from "../content/brand";
export default (env: Env): Content => {
const confDefault: Content = {
tvg: defaults,
pabets: defaults,
iowa: defaults,
"4njbets": defaults,
fdr: defaults
};
const content: {
production: Content;
staging: Content;
qa: Content;
"aws-int": Content;
"aws-stg": Content;
"aws-prd": Content;
} = {
production: { ...confDefault },
staging: { ...confDefault },
qa: { ...confDefault },
"aws-int": { ...confDefault },
"aws-stg": { ...confDefault },
"aws-prd": { ...confDefault }
};
Object.keys(content).forEach((envName) =>
BRAND_ALL.map((brand) => {
// @ts-ignore
const baseConf = base[envName];
// @ts-ignore
const brandConf = tvgBrand[envName][brand];
// @ts-ignore
content[envName][brand] = {
// @ts-ignore
...content[envName][brand],
...baseConf,
...brandConf
};
return brand;
})
);
const config = BRAND_ALL.reduce(
(acc, brand) => ({
...acc,
// @ts-ignore
[brand]: configBase.config(content[env][brand])
}),
{}
);
// @ts-ignore
return config;
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/src/base.ts
import type { Config } from "./types";
import { isBrowser, isRN, getServiceHost } from "./utils";
import { ServiceConfig } from "./types";
export default {
config(envConfig: Config) {
const serviceHost = getServiceHost(envConfig);
const service: Record<string, string> = {};
const servicePort = 8080;
Object.keys(envConfig.service).forEach((key) => {
const serviceName = envConfig.serviceName[key as keyof ServiceConfig];
const servicePath = envConfig.service[key as keyof ServiceConfig];
service[key] =
isBrowser() || isRN()
? // not proud but for now we can live with this for cosmo instead of a major refactor
`${
key.includes("cosmo")
? serviceHost
.replace("service", "api")
// pregaria da avo ana mas a vida é dura
.replace("api.us.betfair.com", "tvg-api.us.betfair.com")
.replace(
"api-qa.us.betfair.com",
"tvg-api-qa.us.betfair.com"
)
.replace(
"api-staging.us.betfair.com",
"tvg-api-staging.us.betfair.com"
)
// again not proud but life is hard so this qa domain
.replace("racing.qa.fndl.dev", "api.racing.qa.fndl.dev")
.replace("api.int.api", "api.int")
: serviceHost
}${servicePath}`
: `http://${serviceName}:${servicePort}${servicePath}`;
});
return {
service_host: serviceHost,
service,
google: envConfig.google,
amplitude: envConfig.amplitude,
domain: {
desktop: envConfig.domain.desktop,
mobile: envConfig.domain.mobile,
talentPicks: envConfig.domain.talentPicks,
accountWallet: envConfig.domain.accountWallet,
equibase: envConfig.domain.equibase
},
externalDomain: envConfig.externalDomain,
externalServices: envConfig.externalServices,
clientId: envConfig.clientId,
brazeId: envConfig.brazeId,
perimeterxId: envConfig.perimeterxId,
paypalID: envConfig.paypalID,
apptentiveID: envConfig.apptentiveID,
apptentiveTvg5: envConfig.apptentiveTvg5,
storyblokToken: envConfig.storyblokToken,
storyblokVersion: envConfig.storyblokVersion,
placesAPI: envConfig.placesAPI,
sonarQube: envConfig.sonarQube,
datadogRum: envConfig.datadogRum,
siftAccountId: envConfig.siftAccountId,
siftBeaconKey: envConfig.siftBeaconKey,
appTentiveIos: envConfig.appTentiveIos,
appTentiveAndroid: envConfig.appTentiveAndroid,
appTentiveWeb: envConfig.appTentiveWeb,
recaptchaID: envConfig.recaptchaID,
recaptchaIdNative: envConfig.recaptchaIdNative
};
}
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/src/location.ts
import type { Location, Brand } from "./types";
export default (brand: Brand): Location => {
switch (brand) {
case "4njbets":
return "nj";
case "pabets":
return "pa";
case "iowa":
return "ia";
default:
return "all";
}
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/src/product.ts
import type { Product } from "./types";
export const PRODUCTS_WEB = ["touch2", "touch3", "fdrmobile"];
export const PRODUCTS_IOS = [
"ios",
"ios2",
"fdrios",
"fdriosxsell",
"iosnative"
];
export const PRODUCTS_FDR_X_SELL = ["fdriosxsell", "fdrandroidxsell"];
export const PRODUCTS_FDR = [
"fdrmobile",
"fdrios",
"fdrandroid",
"fdrandroidgps",
...PRODUCTS_FDR_X_SELL
];
export const PRODUCTS_ANDROID = [
"androidnative",
"fdrandroid",
"androidwrapper",
"tvgandroid",
"fdrandroidxsell",
"fdrandroidgps"
];
export const PRODUCTS_MOBILE = [
...new Set([
...PRODUCTS_WEB,
...PRODUCTS_IOS,
...PRODUCTS_FDR,
...PRODUCTS_ANDROID
])
];
/* eslint-disable */
export default (product: Product): Product => {
if (
typeof window !== "undefined" &&
window.__TVG_GLOBALS__ &&
window.__TVG_GLOBALS__.PRODUCT
) {
return window.__TVG_GLOBALS__.PRODUCT;
}
return product;
};
/* eslint-enable */
webpack://frontend-mybets/../../packages/tvg-lib-conf/src/utils.ts
import { get } from "lodash";
import type { Config } from "./types";
export const attempt = (fn: () => unknown): unknown | Error => {
let result;
try {
result = fn();
} catch (e) {
result = e;
}
return result;
};
export const isBrowser = (): boolean => typeof window !== "undefined";
export const isRN = (): boolean =>
typeof navigator !== "undefined" && navigator.product === "ReactNative";
export const isDev = (): boolean =>
(isBrowser() &&
typeof get(window, "location.hostname.includes") === "function" &&
window.location.hostname.includes("local")) ||
(typeof window === "undefined" &&
typeof process.env.ENVIRONMENT === "string" &&
process.env.ENVIRONMENT === "dev");
export const getServiceHost = (envConfig: Config) =>
isBrowser()
? `//${envConfig.service_host}`
: `http://${envConfig.service_host}`;
webpack://frontend-mybets/../../packages/tvg-lib-conf/utils/fdr/amplitude.ts
module.exports = {
AMPLITUDE_API_KEYS: {
QA: "4a003fec5c6b5c9075661fd874943089",
STAGING: "405e14af37a3efefe3ff469d65339811",
PRODUCTION: "7a02b3ee70357df0fedb2f073ee6b9d0"
},
AMPLITUDE_API_KEYS_XSELL: {
QA: "64d1bda80ee432dabc671f9f8e7ec563",
STAGING: "64d1bda80ee432dabc671f9f8e7ec563",
PRODUCTION: "e23053be3d840ae45b2a1f786ba058f3"
}
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/utils/fdr/apptentive.ts
module.exports = {
APPTENTIVE_TOKENS: {
IOS: {
QA: {
APP_KEY: "IOS-FANDUEL-RACING-DEVELOPMENT",
APP_SIGNATURE: "b54c8aadfa24aa1dcb03dc8df0c725e7",
APPTENTIVE_ID: "61ead8decdc4334729000151"
},
STAGING: {
APP_KEY: "IOS-FANDUEL-RACING-BET-ON-HORSES",
APP_SIGNATURE: "625f98c1c017603845ead137e69e1e0e",
APPTENTIVE_ID: "61ead7d3cdc4334729000139"
},
PRODUCTION: {
APP_KEY: "IOS-FANDUEL-RACING-BET-ON-HORSES",
APP_SIGNATURE: "625f98c1c017603845ead137e69e1e0e",
APPTENTIVE_ID: "61ead7d3cdc4334729000139"
}
},
ANDROID: {
QA: {
APP_KEY: "ANDROID-FANDUEL-RACING-DEVELOPME",
APP_SIGNATURE: "a5ef70979e53a2691f4977ff2c03dfc1",
APPTENTIVE_ID: "61f056825a88276417000000"
},
STAGING: {
APP_KEY: "ANDROID-FANDUEL-RACING-PRODUCTIO",
APP_SIGNATURE: "b4eb937e986299560e802a801370b69d",
APPTENTIVE_ID: "61f0566e5a88276441000002"
},
PRODUCTION: {
APP_KEY: "ANDROID-FANDUEL-RACING-PRODUCTIO",
APP_SIGNATURE: "b4eb937e986299560e802a801370b69d",
APPTENTIVE_ID: "61f0566e5a88276441000002"
}
},
WEB: {
QA: {
APPTENTIVE_ID: "6204200f48b9d649d700005d"
},
STAGING: {
APPTENTIVE_ID: "62041fcb5a88277d4900018f"
},
PRODUCTION: {
APPTENTIVE_ID: "62041fcb5a88277d4900018f"
}
}
}
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/utils/fdr/storyblok.ts
module.exports = {
STORYBLOK_TOKENS: {
QA: "O5iNnduumLUeBTEXgAUvRgtt",
STAGING: "gH2jxeroVxBkGa6Uvekv1wtt",
PRODUCTION: "YngyYOiNVuwhQx0qf0oynQtt"
}
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/utils/mep/amplitude.ts
module.exports = {
AMPLITUDE_API_KEYS: {
QA: "9f0f370fab408d6e388b0aedce7d7f5d",
STAGING: "fe68f6456a5b8261fb971f9ef7b0825f",
PRODUCTION: "b632c2d052db2bf1e2da225654d64cce"
}
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/utils/tvg4/amplitude.ts
module.exports = {
AMPLITUDE_API_KEYS: {
QA: "5c88fe8d83b3fe0e258ce1ebb0e2963d",
STAGING: "e3cca0c4e7b31d9282bc6afa3538b70e",
PRODUCTION: "29fd9abf9fb0e60e22136ab6f59a84b1"
}
};
webpack://frontend-mybets/../../packages/tvg-lib-conf/utils/urp/amplitude.ts
module.exports = {
AMPLITUDE_API_KEYS: {
QA: "5c88fe8d83b3fe0e258ce1ebb0e2963d",
STAGING: "e3cca0c4e7b31d9282bc6afa3538b70e",
PRODUCTION: "29fd9abf9fb0e60e22136ab6f59a84b1"
}
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/_static/colorPalette/index.tsx
import palette from "./palette.json"; export const buildColor = < Color extends keyof typeof palette, Variation extends keyof typeof palette[Color] >( color: Color, variation: Variation ) => palette[color][variation]; export default buildColor;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/alertInline/styled-components.ts
import styled, { css } from "styled-components/native";
import { View, Text } from "react-native";
import { useQaLabel } from "../../hooks/useQaLabel";
import {
AlertInlineStyleProps,
AlertInlineContainerProps,
AlertInlineHasLinkProp,
AlertInlineHasTitleAndMessageProp,
AlertInlineTypes,
AlertInlineRoundedStyleProp
} from "./types";
import { variant, space, compose } from "../../theming/styledSystem";
export const alertInlinePressableVariants = {
success: {
base: "green.800",
hover: "green.600",
active: "green.700"
},
informational: {
base: "blue_accent.700",
hover: "blue_accent.600",
active: "blue_accent.700"
},
error: {
base: "red.700",
hover: "red.600",
active: "red.700"
},
warning: {
base: "orange.900",
hover: "orange.600",
active: "orange.700"
},
promo: {
base: "yellow.900",
hover: "yellow.600",
active: "yellow.700"
}
};
export const alertToastPressableVariants = {
success: {
base: "white.900",
hover: "white.700",
active: "white.800"
},
informational: {
base: "white.900",
hover: "white.700",
active: "white.800"
},
error: {
base: "white.900",
hover: "white.700",
active: "white.800"
},
warning: {
base: "white.900",
hover: "white.700",
active: "white.800"
},
promo: {
base: "grey.900",
hover: "black.900",
active: "black.900"
}
};
const alertInlineTextVariants = {
prop: "variant",
variants: {
success: {
color: "green.800"
},
informational: {
color: "blue_accent.700"
},
error: {
color: "red.700"
},
warning: {
color: "orange.900"
},
promo: {
color: "yellow.900"
}
}
};
const alertToastTextVariants = {
prop: "variant",
variants: {
success: {
color: "white.900"
},
informational: {
color: "white.900"
},
error: {
color: "white.900"
},
warning: {
color: "white.900"
},
promo: {
color: "grey.900"
}
}
};
export const alertInlineVariants = {
prop: "variant",
variants: {
success: {
backgroundColor: "green.100",
border: `1px solid`,
borderColor: "green.300"
},
informational: {
backgroundColor: "blue_accent.000",
border: `1px solid`,
borderColor: "blue_accent.200"
},
error: {
backgroundColor: "red.000",
border: `1px solid`,
borderColor: "red.200"
},
warning: {
backgroundColor: "orange.000",
border: `1px solid`,
borderColor: "orange.200"
},
promo: {
backgroundColor: "yellow.000",
border: `1px solid`,
borderColor: "yellow.200"
}
}
};
export const alertToastVariants = {
prop: "variant",
variants: {
success: {
backgroundColor: "green.600",
boxShadow: "0px 1px 16px rgba(17, 43, 68, 0.25)"
},
informational: {
backgroundColor: "blue_accent.600",
boxShadow: "0px 1px 16px rgba(17, 43, 68, 0.25)"
},
error: {
backgroundColor: "red.500",
boxShadow: "0px 1px 16px rgba(17, 43, 68, 0.25)"
},
warning: {
backgroundColor: "orange.500",
boxShadow: "0px 1px 16px rgba(17, 43, 68, 0.25)"
},
promo: {
backgroundColor: "yellow.500",
boxShadow: "0px 1px 16px rgba(17, 43, 68, 0.25)"
}
}
};
const styledSystemStyles = (type: AlertInlineTypes) =>
compose(
space,
type === "toast"
? variant(alertToastVariants)
: variant(alertInlineVariants)
);
export const AlertInlineContainer = styled(View).attrs<{
qaLabel: string;
}>((props) => ({
...useQaLabel(props.qaLabel)
}))<AlertInlineContainerProps & AlertInlineRoundedStyleProp>`
width: ${({ isFullWidth }) => (isFullWidth ? "100%" : "fit-content")};
flex-direction: row;
align-items: stretch;
column-gap: ${({ theme }) => theme.space["space-4"]};
border-radius: ${({ theme, hasRoundedStyle }) =>
hasRoundedStyle ? theme.radii["2xl"] : theme.radii.s};
padding: ${({ theme, hasRoundedStyle }) =>
hasRoundedStyle
? `0 ${theme.space["space-1"]} 0 ${theme.space["space-5"]}`
: `0 0 0 ${theme.space["space-4"]}`};
${({ theme, hasRoundedStyle, hasOnDismissPress }) =>
!hasOnDismissPress &&
css`
padding-right: ${hasRoundedStyle
? theme.space["space-5"]
: theme.space["space-4"]};
`}
${({ type }) => styledSystemStyles(type || "floating")};
${(props) =>
props.type === "fixed" &&
css`
border-left-width: 0;
border-right-width: 0;
border-radius: 0;
`}
${({ isFullWidth }) =>
!isFullWidth &&
css`
margin: auto;
`}
`;
export const AlertInlineIconWrapper = styled(View)<AlertInlineRoundedStyleProp>`
justify-content: ${({ hasRoundedStyle }) =>
hasRoundedStyle ? "center" : "flex-start"};
${({ hasRoundedStyle }) =>
!hasRoundedStyle &&
css`
padding-top: ${({ theme }) => theme.space["space-4"]};
`}
`;
export const AlertInlineInfo = styled(View)<
AlertInlineHasLinkProp &
AlertInlineRoundedStyleProp &
AlertInlineHasTitleAndMessageProp
>`
flex: 1;
justify-content: center;
gap: ${({ theme }) => theme.space["space-1"]}
${({ theme }) => theme.space["space-4"]};
padding: ${({ theme }) => `${theme.space["space-4"]} 0`};
${({ hasRoundedStyle, hasLink, hasTitleAndMessage }) =>
hasLink &&
(!hasTitleAndMessage || (hasTitleAndMessage && hasRoundedStyle)) &&
css`
flex-flow: row;
flex-wrap: wrap;
`}
`;
export const AlertInlineActions = styled(View)<AlertInlineRoundedStyleProp>`
flex-direction: row;
column-gap: ${({ theme }) => theme.space["space-3"]};
align-items: ${({ hasRoundedStyle }) =>
hasRoundedStyle ? "center" : "flex-start"};
`;
export const AlertInlineMessage = styled(Text).attrs<{
qaLabel: string;
}>((props) => ({
...useQaLabel(props.qaLabel)
}))<
AlertInlineStyleProps &
AlertInlineHasLinkProp &
AlertInlineRoundedStyleProp &
AlertInlineHasTitleAndMessageProp & { qaLabel?: string }
>`
${({ type }) =>
type === "toast"
? variant(alertToastTextVariants)
: variant(alertInlineTextVariants)};
font-size: ${({ theme }) => theme.fontSizes.s};
font-family: ${({ theme, type, hasTitleAndMessage }) => {
if (type === "toast") {
return hasTitleAndMessage ? theme.fonts.regular : theme.fonts.bold;
}
return theme.fonts.regular;
}};
${({ hasLink, hasTitleAndMessage }) =>
!hasTitleAndMessage &&
hasLink &&
css`
flex: 1;
`}
${({ hasRoundedStyle, hasLink, hasTitleAndMessage }) =>
hasRoundedStyle &&
hasLink &&
hasTitleAndMessage &&
css`
order: 1;
flex-basis: 100%;
`}
`;
export const AlertInlineTitle = styled(Text)<
AlertInlineStyleProps & AlertInlineHasLinkProp & AlertInlineRoundedStyleProp
>`
${({ type }) =>
type === "toast"
? variant(alertToastTextVariants)
: variant(alertInlineTextVariants)}
font-size: ${({ theme }) => theme.fontSizes.s};
font-family: ${({ theme, type }) =>
type === "toast" ? theme.fonts.bold : theme.fonts.medium};
${({ hasRoundedStyle, hasLink }) =>
hasRoundedStyle &&
hasLink &&
css`
flex: 1;
`}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/alertInline/utils/getPressableColor.ts
import { EventsState } from "../../../hooks/useEvents";
import {
alertInlinePressableVariants,
alertToastPressableVariants
} from "../styled-components";
import { AlertInlineVariants, AlertInlineTypes } from "../types";
export const getPressableColor = (
type: AlertInlineTypes,
variant: AlertInlineVariants,
events?: EventsState
): string => {
const variantStyle =
type === "toast"
? alertToastPressableVariants[variant]
: alertInlinePressableVariants[variant];
if (events?.isPressed || events?.isFocused) return variantStyle.active;
if (events?.isHovered) return variantStyle.hover;
return variantStyle.base;
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/alertInline/components/link/styled-components.ts
import styled from "styled-components/native";
import { get } from "lodash";
import { Link } from "../../../link";
import { StyledLinkProps } from "./types";
import { AlertInlineVariants } from "../../types";
import { getPressableColor } from "../../utils/getPressableColor";
export const StyledLink = styled(Link)<StyledLinkProps>`
color: ${({ type = "floating", variant = "success", events, theme }) =>
get(
theme.colors,
getPressableColor(type, variant as AlertInlineVariants, events)
)};
text-decoration: underline;
text-decoration-color: ${({ type = "floating", variant, events, theme }) =>
get(
theme.colors,
getPressableColor(type, variant as AlertInlineVariants, events)
)};
line-height: 16px;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/alertInline/components/icon/styled-components.ts
import { AlertInlineIconVariants } from "./types";
export const alertInlineIconVariants: AlertInlineIconVariants = {
success: {
backgroundColor: "green.100",
lineColor: "green.700",
name: "success"
},
informational: {
backgroundColor: "blue_accent.200",
lineColor: "blue_accent.600",
name: "info"
},
error: {
backgroundColor: "red.100",
lineColor: "red.600",
name: "exclamation"
},
warning: {
backgroundColor: "orange.200",
lineColor: "orange.700",
name: "warning"
},
promo: {
backgroundColor: "yellow.200",
lineColor: "yellow.800",
name: "promo"
}
};
export const alertToastIconVariants: AlertInlineIconVariants = {
success: {
lineColor: "white.900",
name: "success"
},
informational: {
lineColor: "white.900",
name: "info"
},
error: {
lineColor: "white.900",
name: "exclamation"
},
warning: {
lineColor: "white.900",
name: "warning"
},
promo: {
lineColor: "grey.900",
name: "promo"
}
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/alertInline/components/icon/index.tsx
import React, { memo } from "react";
import { EventsState } from "../../../../hooks/useEvents";
import { Icon } from "../../../icon";
import { SpaceProps } from "../../../../theming/styledSystem";
import { AlertInlineStyleProps, AlertInlineVariants } from "../../types";
import {
alertInlineIconVariants,
alertToastIconVariants
} from "./styled-components";
import { getPressableColor } from "../../utils/getPressableColor";
export const AlertInlineIcon = memo(
({
type = "floating",
variant,
isClose = false,
events,
icon,
...rest
}: AlertInlineStyleProps &
SpaceProps & { isClose?: boolean; events?: EventsState }) => {
const { backgroundColor, lineColor, name } =
type === "toast"
? alertToastIconVariants[variant as AlertInlineVariants]
: alertInlineIconVariants[variant as AlertInlineVariants];
return (
<Icon
size="s"
name={isClose ? "close" : icon || name}
backgroundColor={backgroundColor || "none"}
lineColor={
isClose ? getPressableColor(type, variant, events) : lineColor
}
qaLabel={`alert-inline-icon-${isClose ? "close" : name}`}
{...rest}
/>
);
}
);
export default AlertInlineIcon;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/alertInline/index.tsx
import React, {
useState,
useEffect,
useRef,
memo,
isValidElement,
cloneElement,
forwardRef
} from "react";
import { View, Animated, Platform, Pressable } from "react-native";
import { AlertInlineProps, AlertInlineCompoundComponent } from "./types";
import {
AlertInlineContainer,
AlertInlineMessage,
AlertInlineTitle,
AlertInlineIconWrapper,
AlertInlineInfo,
AlertInlineActions
} from "./styled-components";
import { Icon as AlertInlineIcon, Link as AlertInlineLink } from "./components";
import { useEvents } from "../../hooks/useEvents";
import { useQaLabel } from "../../hooks/useQaLabel";
const isWeb = Platform.OS === "web";
export const AlertInline = memo(
forwardRef<View, AlertInlineProps>(
(
{
message,
title,
qaLabel,
variant = "informational",
type = "floating",
hasDismissButton = false,
hasDismissAnimation = true,
onDismissPress,
actionLink,
icon,
hasRoundedStyle,
isFullWidth = true,
children,
...styledSystemProps
}: AlertInlineProps,
ref
) => {
const [isVisible, setVisibility] = useState(true);
const [hasAnimationEnded, setAnimationEnded] = useState(false);
const opacity = useRef(new Animated.Value(1)).current;
const hasTitleAndMessage = !!(title && message);
const hasOnDismissPress = !!(
hasDismissButton ||
(onDismissPress && typeof onDismissPress === "function")
);
const hasLink = !!(actionLink && isValidElement(actionLink));
const { events, eventsHandlers } = useEvents({});
const dismissTestProps = useQaLabel("alert-inline-dismiss");
useEffect(() => {
if (hasDismissAnimation && !isVisible) {
Animated.timing(opacity, {
toValue: 0,
duration: 400,
useNativeDriver: !isWeb
}).start(() => setAnimationEnded(true));
}
}, [isVisible, hasDismissAnimation]);
const display = hasAnimationEnded ? "none" : "flex";
return (
<Animated.View style={{ opacity, display }}>
<AlertInlineContainer
variant={variant}
type={type}
hasOnDismissPress={hasOnDismissPress}
hasRoundedStyle={hasRoundedStyle}
isFullWidth={isFullWidth}
ref={ref}
qaLabel={qaLabel}
{...styledSystemProps}
>
<AlertInlineIconWrapper hasRoundedStyle={hasRoundedStyle}>
<AlertInlineIcon variant={variant} type={type} icon={icon} />
</AlertInlineIconWrapper>
<AlertInlineInfo
hasRoundedStyle={hasRoundedStyle}
hasLink={hasLink}
hasTitleAndMessage={hasTitleAndMessage}
>
{typeof title === "string" && title !== "" && (
<AlertInlineTitle
variant={variant}
type={type}
hasRoundedStyle={hasRoundedStyle}
hasLink={hasLink}
>
{isWeb ? (
<span
dangerouslySetInnerHTML={{
__html: title
}}
/>
) : (
title
)}
</AlertInlineTitle>
)}
<AlertInlineMessage
variant={variant}
type={type}
hasLink={hasLink}
hasRoundedStyle={hasRoundedStyle}
hasTitleAndMessage={hasTitleAndMessage}
qaLabel="alert-inline-message"
>
{children}
{isWeb ? (
<span
dangerouslySetInnerHTML={{
__html: message
}}
/>
) : (
message
)}
</AlertInlineMessage>
{hasLink &&
cloneElement(actionLink, { variant, type } as Partial<unknown>)}
</AlertInlineInfo>
{hasOnDismissPress && (
<AlertInlineActions hasRoundedStyle={hasRoundedStyle}>
<Pressable
onPress={(e) => {
if (typeof onDismissPress === "function") onDismissPress(e);
setVisibility(false);
}}
accessibilityRole="button"
{...eventsHandlers}
{...dismissTestProps}
>
<AlertInlineIcon
p="space-4"
type={type}
variant={variant}
events={events}
isClose
/>
</Pressable>
</AlertInlineActions>
)}
</AlertInlineContainer>
</Animated.View>
);
}
)
) as AlertInlineCompoundComponent<typeof AlertInlineLink>;
export type { AlertInlineProps };
AlertInline.Link = AlertInlineLink;
export default AlertInline;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/alertInline/components/link/index.tsx
import React from "react";
import { View } from "react-native";
import { useEvents } from "../../../../hooks/useEvents";
import { AlertInlineLinkProps } from "../../types";
import { StyledLink } from "./styled-components";
export const AlertInlineLink = ({
type,
variant,
...props
}: AlertInlineLinkProps) => {
const { events, eventsHandlers } = useEvents({});
return (
<View {...eventsHandlers}>
<StyledLink {...props} variant={variant} type={type} events={events} />
</View>
);
};
export type { AlertInlineLinkProps };
export default AlertInlineLink;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/badge/utils/calculate-badge-width/index.ts
const CHAR_WIDTH_PX = 7;
const BADGE_PADDING_X = 12;
const BADGE_WIDTH_DEFAULT = 16;
export const calculateBadgeWidth = (counter: number, counterLimit?: number) => {
const valueOfNotifications =
counterLimit && counter > counterLimit ? `${counterLimit}+` : counter;
const counterLength = String(valueOfNotifications).length;
const width = CHAR_WIDTH_PX * counterLength;
return counterLength === 1 ? BADGE_WIDTH_DEFAULT : width + BADGE_PADDING_X;
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/badge/components/badge-counter/styled-components.ts
import styled from "styled-components/native";
import { BadgeContainerProps } from "../../types";
import { space } from "../../../../theming/styledSystem";
import { themeGet } from "../../../../theming";
export const BadgeContainer = styled.View<BadgeContainerProps>`
background-color: ${(props) =>
props.variant === "primary"
? props.theme.colors.red[500]
: props.theme.colors.blue_accent[500]};
border-radius: 12px;
height: 16px;
justify-content: center;
max-width: ${(props) => props.badgeWidth}px;
min-width: 16px;
padding: ${(props) =>
props.isCircle ? "0" : `1px ${props.theme.space["space-2"]}`};
${space};
`;
export const BadgeText = styled.Text`
color: ${themeGet("colors.white.900")};
font-family: ${themeGet("fonts.condensedRegular")};
font-size: ${themeGet("fontSizes.xs")};
text-align: center;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/badge/components/badge-counter/index.tsx
import React, { forwardRef, memo } from "react";
import { View } from "react-native";
import { BadgeCounterProps } from "../../types";
import { useQaLabel } from "../../../../hooks";
import { calculateBadgeWidth } from "../../utils";
import { BadgeContainer, BadgeText } from "./styled-components";
export const BadgeCounter = memo(
forwardRef<View, BadgeCounterProps>(
(
{
qaLabel = "badge",
counter,
counterLimit = 99,
variant = "primary",
accessibilityLabel,
...rest
}: BadgeCounterProps,
ref
) => {
const viewTestProps = useQaLabel(qaLabel);
const valueOfNotifications =
counterLimit && counter > counterLimit ? `${counterLimit}+` : counter;
return (
<BadgeContainer
{...viewTestProps}
variant={variant}
accessibilityLabel={
accessibilityLabel || `${valueOfNotifications} notifications`
}
badgeWidth={calculateBadgeWidth(counter, counterLimit)}
// @ts-ignore
ref={ref}
isCircle={String(valueOfNotifications).length === 1}
{...rest}
>
<BadgeText selectable={false}>{valueOfNotifications}</BadgeText>
</BadgeContainer>
);
}
)
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/badge/styled-components.ts
import styled from "styled-components/native";
import { View } from "react-native";
import { themeGet } from "../../theming";
import { space } from "../../theming/styledSystem";
import { BadgeWidthProps } from "./types";
export const WrapperContainer = styled(View)`
margin: ${themeGet("space.space-3")};
flex-direction: row;
position: relative;
${space}
`;
export const ChildrenContainer = styled(View)`
position: relative;
width: auto;
`;
export const Positioner = styled(View)<BadgeWidthProps>`
position: absolute;
flex-wrap: wrap;
top: -20%;
right: -${(props) => props.badgeWidth * 0.5}px;
min-width: ${(props) => props.badgeWidth}px;
elevation: 1;
z-index: 1;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/badge/index.tsx
import React, { memo, forwardRef } from "react";
import { View } from "react-native";
import { useQaLabel } from "../../hooks/useQaLabel";
import { calculateBadgeWidth } from "./utils";
import { BadgeProps, BadgeCounterProps, BadgeCompoundComponent } from "./types";
import { BadgeCounter } from "./components";
import {
WrapperContainer,
Positioner,
ChildrenContainer
} from "./styled-components";
export const Badge = memo(
forwardRef<View, BadgeProps>(
({ children, ...badgeInnerProps }: BadgeProps, ref) => {
const containerQaProps = useQaLabel("badge-container");
return (
<WrapperContainer {...containerQaProps}>
<ChildrenContainer>
<Positioner
badgeWidth={calculateBadgeWidth(
badgeInnerProps.counter,
badgeInnerProps.counterLimit
)}
pointerEvents="none"
>
<BadgeCounter {...badgeInnerProps} ref={ref} />
</Positioner>
{children}
</ChildrenContainer>
</WrapperContainer>
);
}
)
) as BadgeCompoundComponent<typeof BadgeCounter>;
Badge.Counter = BadgeCounter;
export type { BadgeProps, BadgeCounterProps };
export default Badge;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/types/bets.ts
export enum BetTypeCodesEnum {
EXACTA = "EX",
EXACTA_KEY_BOX = "EKB",
PLACE = "PL",
SHOW = "SH",
SUPERFECTA = "SU",
SUPERHIGHFIVE = "SH5",
TRIFECTA = "TR",
WIN = "WN",
WIN_PLACE = "WP",
PLACE_SHOW = "PS",
WIN_SHOW = "WS",
WIN_PLACE_SHOW = "WPS"
}
export enum BetTypeCodesReversedEnum {
EX = "Exacta",
EKB = "Exacta/Key/Box",
PL = "Place",
SH = "Show",
SU = "Superfecta",
SH5 = "Super high five",
TR = "Trifecta",
WN = "Win",
WP = "Win/Place",
WPS = "Win/Place/Show"
}
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/betButtons/styled-components.ts
import styled, { css } from "styled-components/native";
import { View } from "react-native";
export const Container = styled(View)`
flex-direction: row;
`;
export const ButtonGroup = styled(View)<{
hasMaxWidth?: boolean;
isSimpleBetButtons?: boolean;
}>`
flex-direction: row;
border-radius: ${({ theme }) => theme.radii.xs};
box-shadow: ${({ theme }) => theme.elevations.low};
overflow: hidden;
${({ hasMaxWidth, isSimpleBetButtons }) =>
hasMaxWidth &&
css`
width: ${isSimpleBetButtons ? "151px" : "220px"};
`}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/betButtons/components/button/styled-components.ts
import styled, { css } from "styled-components/native";
import { useQaLabel, useQaLabelActive } from "../../../../hooks";
import { space } from "../../../../theming/styledSystem";
import { StyledButtonProps, ButtonContainerProps } from "./types";
import { Theme } from "../../../../theming/types";
export const ButtonContainer = styled.View<ButtonContainerProps>`
${space};
position: relative;
z-index: ${({ isActive, isHovering }) =>
isActive || isHovering ? "1" : "0"};
flex-direction: row;
${({ isFullWidth }) =>
isFullWidth &&
css`
flex-grow: 1;
flex-basis: 0;
flex-shrink: 0;
`}
`;
export const StyledButton = styled.TouchableHighlight.attrs<{
qaLabel: string;
isActive: boolean;
theme: Theme;
}>((props) => ({
accessibilityRole: "button",
underlayColor:
props.theme.colorTokens.component.button.secondary.background.hover,
...useQaLabelActive(props.qaLabel, props.isActive ? "selected" : "")
}))<StyledButtonProps>`
${space};
align-self: flex-start;
flex-grow: 0;
align-items: center;
justify-content: center;
height: 42px;
padding: 0 ${({ theme }) => theme.space["space-5"]};
${({ hasBorderRadius }) =>
hasBorderRadius &&
css`
border-radius: ${({ theme }) => theme.radii.xs};
`}
${({ hasShadow }) =>
hasShadow &&
css`
box-shadow: ${({ theme }) => theme.elevations.low};
`}
${({ isFullWidth }) =>
isFullWidth &&
css`
flex-grow: 1;
flex-basis: 0;
flex-shrink: 0;
padding: 0;
`}
${({ isHovering }) =>
isHovering &&
css`
background-color: ${({ theme }) =>
theme.colorTokens.component.button.buttonLink.background.hover};
`}
${({ isActive }) =>
isActive &&
css`
background-color: ${({ theme }) =>
theme.colorTokens.component.button.secondary.background.hover};
`}
${({ isActive, isHovering }) =>
isActive &&
isHovering &&
css`
background-color: ${({ theme }) =>
theme.colorTokens.component.button.secondary.background.base};
`}
`;
export const ButtonText = styled.Text.attrs<{ qaLabel: string }>((props) => ({
...useQaLabel(props.qaLabel)
}))<{
isActive: boolean;
isHovering: boolean;
qaLabel: string;
color: string;
theme: Theme;
children?: React.ReactNode;
}>`
font-family: ${({ theme }) => theme.fonts.medium};
font-size: ${({ theme }) => theme.fontSizes.s};
font-weight: ${({ theme }) => theme.fontWeights.medium};
color: ${({ theme, color }) =>
color || theme.colorTokens.component.button.tertiary.content.base};
`;
export const ButtonRing = styled.View<{
isLastChild?: boolean;
isFirstChild?: boolean;
isActive: boolean;
isHovering: boolean;
theme: Theme;
}>`
position: absolute;
top: 0;
right: ${({ isLastChild }) => (isLastChild ? "0" : "-1px")};
bottom: 0;
left: 0;
border: 1px solid
${({ theme }) => theme.colorTokens.component.button.tertiary.border.base};
${({ isFirstChild }) =>
isFirstChild &&
css`
border-bottom-left-radius: ${({ theme }) => theme.radii.xs};
border-top-left-radius: ${({ theme }) => theme.radii.xs};
`}
${({ isLastChild }) =>
isLastChild &&
css`
border-bottom-right-radius: ${({ theme }) => theme.radii.xs};
border-top-right-radius: ${({ theme }) => theme.radii.xs};
`}
${({ isHovering }) =>
isHovering &&
css`
border: 1px solid
${({ theme }) =>
theme.colorTokens.component.button.tertiary.border.hover};
`}
${({ isActive }) =>
isActive &&
css`
border: 1px solid
${({ theme }) =>
theme.colorTokens.component.button.tertiary.border.active};
`}
`;
export const TextContainer = styled.View<{ children?: React.ReactNode }>`
flex-direction: row;
align-items: center;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/betSelections/styled-components.ts
import styled from "styled-components/native";
import { View, Text } from "react-native";
import { BetSelectionProps } from "./types";
export const BetSelectionContainer = styled(View)<
Pick<BetSelectionProps, "isDark">
>`
align-items: center;
background-color: ${({ theme, isDark }) =>
isDark
? theme.colorTokens.component.betslip.backgroundExpanded
: "transparent"};
border: 1px solid
${({ theme, isDark }) =>
isDark
? theme.colorTokens.component.betslip.backgroundExpanded
: theme.colors.blue[100]};
border-radius: 4px;
flex-direction: row;
height: 42px;
padding: 0 11px;
`;
export const BetText = styled(Text)<Pick<BetSelectionProps, "isDark">>`
color: ${({ theme, isDark }) =>
isDark ? theme.colorTokens.content.onDark : theme.colors.black[900]};
font-family: ${({ theme }) => theme.fonts.regular};
font-size: ${({ theme }) => theme.fontSizes.s};
font-weight: ${({ theme }) => theme.fontWeights.medium};
padding-right: 6px;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/betSelections/index.tsx
import React from "react";
import { useQaLabel } from "@tvg/design-system/src/hooks";
import SaddleSelections from "../saddleSelections";
import { BetSelectionContainer, BetText } from "./styled-components";
import { BetSelectionProps } from "./types";
export const BetSelections = ({
numWagerableRunners,
type,
breed = "thoroughbred",
selections,
isDark = true,
qaLabel = "bet-selection",
showBetType = true,
scratches,
wagerDetails,
shouldShowRefundTag,
onHandicaping,
hideWillPaysTag,
enableMyBetsBehavior = false,
showOdds,
favoriteRunner,
showReplacedRunners,
raceStatus,
isAlternateView,
showAlternatePlaceholder
}: BetSelectionProps) => {
const betSelectionQaLabel = useQaLabel(qaLabel);
return showBetType ? (
<BetSelectionContainer {...betSelectionQaLabel} isDark={isDark}>
<BetText isDark={isDark}>{type}</BetText>
<SaddleSelections
selections={selections}
isDark={isDark}
showBetType={showBetType}
scratches={scratches}
breed={breed}
hideWillPaysTag={hideWillPaysTag}
enableMyBetsBehavior={enableMyBetsBehavior}
showOdds={showOdds}
favoriteRunner={favoriteRunner}
showReplacedRunners={showReplacedRunners}
raceStatus={raceStatus}
isAlternateView={isAlternateView}
showAlternatePlaceholder={showAlternatePlaceholder}
/>
</BetSelectionContainer>
) : (
<SaddleSelections
numWagerableRunners={numWagerableRunners}
selections={selections}
isDark={isDark}
showBetType={showBetType}
scratches={scratches}
breed={breed}
wagerDetails={wagerDetails}
shouldShowRefundTag={shouldShowRefundTag}
onHandicaping={onHandicaping}
hideWillPaysTag={hideWillPaysTag}
enableMyBetsBehavior={enableMyBetsBehavior}
favoriteRunner={favoriteRunner}
showReplacedRunners={showReplacedRunners}
raceStatus={raceStatus}
{...betSelectionQaLabel}
showOdds={showOdds}
isAlternateView={isAlternateView}
showAlternatePlaceholder={showAlternatePlaceholder}
/>
);
};
export default BetSelections;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/betTypeCell/types.ts
import { GestureResponderEvent } from "react-native";
import { SpaceProps, LayoutProps } from "styled-system";
import { WagerTypeCodesEnum } from "@tvg/ts-types/Wager";
import { SaddleSelectionsProps } from "../saddleSelections";
import { Breed } from "../saddle";
type BetStatusType = "NONE" | "PLACED" | "ERROR" | "PROCESSING";
export enum BetStatusCodesEnum {
ACTIVE = "A",
REFUNDED = "R",
LOSER = "L",
WINNER = "W",
CANCELED = "C"
}
export interface BetTypeCellProps extends SpaceProps, LayoutProps {
/** Bet Amount */
betAmount: number | string;
/** Bet type name */
betTypeName: string;
/** Bet Ticket value */
betTicket: number | string;
/** Number Wagerable Runners */
numWagerableRunners?: string[] | undefined;
/** Approximated Payout */
approximatedPayout: string;
/** Bet type */
type: WagerTypeCodesEnum;
/** Type of race */
breed?: Breed;
/** Saddle selections */
selections: SaddleSelectionsProps[];
/** Complete Selection Array */
completeSelection?: SaddleSelectionsProps[][];
/** Status of the bet */
betStatus: BetStatusType;
/** Repeat bet handler */
onRepeatBetHandler?: (event: GestureResponderEvent) => void;
/** Cancel bet handler */
onCancelBetHandler?: (event: GestureResponderEvent) => void;
/** Custom data-qa-label attribute applied to element */
qaLabel?: string;
/** Is leg bet * */
isLeg: boolean;
/** If include scratch in selections */
scratches?: string[][];
/** Is Key bet */
isKey?: boolean;
/** Is Box bet */
isBox?: boolean;
/** Is Wheel bet */
isWheel?: boolean;
/** Current race number */
raceNumber?: string;
/** No header and no border */
showOnlySelections?: boolean;
betStatusCode?: BetStatusCodesEnum;
winAmountBet?: number | string;
/** Is the bet refund amount */
betRefund?: number | string;
/** Is the bet repeatable */
isRepeatable?: boolean;
/** Is the bet done on a special wager track */
isSpecialWager?: boolean;
/** If is on handicaping */
onHandicaping?: boolean;
/** If alternates should be displayed */
displayAlternateSelection?: boolean;
/** If alternate placeholder should be displayed */
showAlternatePlaceholder?: boolean;
/** Has race started */
isRaceOff?: boolean;
}
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/betTypeCell/styled-components.ts
import styled, { css } from "styled-components/native";
import { View } from "react-native";
import { space, layout, compose } from "styled-system";
const styledUtils = compose(space, layout);
export const Container = styled(View)<{ showOnlySelections?: boolean }>`
overflow: hidden;
${styledUtils}
border-radius: ${({ theme }) => theme.radii.xs};
${({ showOnlySelections }) =>
!showOnlySelections &&
css`
border: 1px solid ${({ theme }) => theme.colorTokens.border.default};
`}
`;
export const Header = styled(View)`
flex-direction: row;
justify-content: space-between;
align-items: center;
border-bottom-width: 1px;
background-color: ${({ theme }) => theme.colorTokens.background.layer};
border-bottom-color: ${({ theme }) => theme.colors.blue["100"]};
padding: ${({ theme }) =>
`${theme.space["space-2"]} ${theme.space["space-4"]}`};
`;
export const ContentActionsWrapper = styled(View)`
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: flex-start;
`;
export const Content = styled(View)<{ hasButtons: boolean }>`
background-color: ${({ theme }) => theme.colorTokens.surface};
padding: ${({ theme }) => theme.space["space-4"]};
max-width: ${({ hasButtons }) => (hasButtons ? "calc(100% - 72px)" : "100%")};
`;
export const Actions = styled(View)`
display: flex;
flex-direction: row;
gap: ${({ theme }) => theme.space["space-3"]};
margin: ${({ theme }) =>
`${theme.space["space-2"]} ${theme.space["space-4"]} ${theme.space["space-2"]} 0`};
`;
export const VerticalParagraphLeft = styled(View)`
text-align: left;
`;
export const VerticalParagraphRight = styled(View)`
text-align: right;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/betTypeCell/components/CustomBetSelectionsView/styled-components.ts
import styled from "styled-components/native";
import { View } from "react-native";
export const PositionsGrid = styled(View)<{
isLeg?: boolean;
isSpecialWager?: boolean;
}>`
display: grid;
grid-template-columns: ${({ isLeg, isSpecialWager }) =>
isLeg && !isSpecialWager ? "58px" : "25px"} auto;
column-gap: ${({ theme }) => theme.space["space-3"]};
row-gap: ${({ theme }) => theme.space["space-4"]};
`;
export const Content = styled(View)`
width: 65px;
justify-content: center;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/betTypeCell/components/CustomBetSelectionsView/index.tsx
import React, { Fragment } from "react";
import formatSequencial from "@tvg/formatter/numeric";
import BetSelection from "../../../betSelections";
import { Paragraph } from "../../../typography";
import { CustomBetSelectionsViewProps } from "../types";
import Icon from "../../../icon";
import { PositionsGrid, Content } from "./styled-components";
export const CustomBetSelectionsView: React.FC<
CustomBetSelectionsViewProps
> = ({
completeSelection,
numWagerableRunners,
type,
isKey,
isBox,
isWheel,
isLeg,
isExoticBet,
isSpecialWager,
currentRaceNumber,
scratches,
breed,
isAlternateView,
showAlternatePlaceholder
}) => {
const renderKeyOrKeyBox = (index: number) => {
const isKeyBox = isKey && isBox;
const defaultText = isKeyBox ? "Box" : "w/";
return (
<Paragraph qaLabel={`selection-label-key${isKeyBox ? "-box" : ""}`}>
{index === 0 ? <Icon name="key" size="s" qaLabel="key" /> : defaultText}
</Paragraph>
);
};
const renderKeyBoxOrKeyOrBox = (index: number) => {
if (isKey) {
return renderKeyOrKeyBox(index);
}
return <Paragraph qaLabel="selection-label-box">Box</Paragraph>;
};
const renderExoticOrLegBet = (index: number) =>
isExoticBet ? (
<Paragraph qaLabel={`selection-label-${formatSequencial(index + 1)}`}>
{formatSequencial(index + 1)}
</Paragraph>
) : (
<Content>
<Paragraph qaLabel={`selection-label-${formatSequencial(index + 1)}`}>
{isSpecialWager
? `L${Number(currentRaceNumber) + index}`
: `L${index + 1} - R${Number(currentRaceNumber) + index}`}
</Paragraph>
</Content>
);
const renderWheel = (index: number) => (
<Paragraph qaLabel="selection-label-wheel">
{index === 0 ? <></> : "w/"}
</Paragraph>
);
return completeSelection?.length ? (
<PositionsGrid isLeg={isLeg} isSpecialWager={isSpecialWager}>
{completeSelection.map((selection, index) => (
<Fragment key={`${type}-${index.toString()}`}>
{(isKey || isBox) && renderKeyBoxOrKeyOrBox(index)}
{(isExoticBet || isLeg) && renderExoticOrLegBet(index)}
{isWheel && renderWheel(index)}
<BetSelection
scratches={scratches?.[index]}
numWagerableRunners={
isLeg ? numWagerableRunners?.[index] : numWagerableRunners?.[0]
}
selections={selection}
type={type}
showBetType={false}
breed={breed}
isAlternateView={isAlternateView}
showAlternatePlaceholder={showAlternatePlaceholder}
/>
</Fragment>
))}
</PositionsGrid>
) : null;
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/betTypeCell/index.tsx
import React from "react";
import { View } from "react-native";
import { WagerTypeCodesEnum } from "@tvg/ts-types/Wager";
import { isZeroLike } from "@tvg/utils/generalUtils";
import { useQaLabel } from "../../hooks";
import { useTheme } from "../../theming";
import BetSelection from "../betSelections";
import Loading from "../loading";
import { IconButton } from "../iconButton";
import { Tag } from "../tag";
import { Paragraph } from "../typography";
import {
Container,
ContentActionsWrapper,
Content,
Actions,
Header,
VerticalParagraphLeft,
VerticalParagraphRight
} from "./styled-components";
import { BetTypeCellProps, BetStatusCodesEnum } from "./types";
import { CustomBetSelectionsView } from "./components/CustomBetSelectionsView";
const exoticBets = [
WagerTypeCodesEnum.EXACTA,
WagerTypeCodesEnum.TRIFECTA,
WagerTypeCodesEnum.SUPERFECTA,
WagerTypeCodesEnum.SUPERHIGHFIVE
];
export const BetTypeCell = ({
numWagerableRunners,
type,
breed = "thoroughbred",
betTypeName,
selections,
completeSelection,
qaLabel = "bet-type-cell",
approximatedPayout,
betAmount,
betStatus,
betTicket,
isLeg,
scratches,
onRepeatBetHandler,
onCancelBetHandler,
isKey,
isBox,
isWheel,
raceNumber,
betStatusCode,
winAmountBet,
showOnlySelections,
betRefund,
isSpecialWager = false,
isRepeatable = true,
displayAlternateSelection,
showAlternatePlaceholder,
isRaceOff = false,
...rest
}: BetTypeCellProps) => {
const betTypeCellQaLabel = useQaLabel(qaLabel);
const { colors } = useTheme();
const isExoticBet = exoticBets.includes(type);
const isCustomSelectionsView =
isKey || isLeg || isBox || isWheel || isExoticBet;
const hasPayout = !isZeroLike(approximatedPayout);
const isWon = betStatusCode === BetStatusCodesEnum.WINNER;
const isRefund = betStatusCode === BetStatusCodesEnum.REFUNDED;
const betStatusCodeMap: Record<
BetStatusCodesEnum,
{ label: string; value?: number | string }
> = {
A: {
label: hasPayout ? "APPROX. PAYOUT" : "",
value: hasPayout ? approximatedPayout : ""
},
R: { label: "REFUND", value: betRefund },
L: { label: "RETURN", value: "$0.00" },
W: { label: "WON", value: winAmountBet },
C: { label: "REFUND", value: betRefund }
};
const renderRightColumn = () => {
switch (betStatus) {
case "PROCESSING":
return (
<View>
<Loading />
</View>
);
case "ERROR":
return (
<View>
<Tag size="s" variant="warning" label="Failed" />
</View>
);
case "PLACED":
return (
<View>
<Tag size="s" variant="optedin" label="Placed" />
</View>
);
default:
return (
<VerticalParagraphRight>
<Paragraph
fontFamily={isWon || isRefund ? "medium" : "regular"}
fontWeight={isWon || isRefund ? 500 : 400}
color={isWon ? colors.green["700"] : colors.grey["900"]}
qaLabel="approximate-payout-value"
>
<>
{
betStatusCodeMap[betStatusCode || BetStatusCodesEnum.ACTIVE]
.value
}
</>
</Paragraph>
<Paragraph
qaLabel="approximate-payout"
fontFamily="condensedRegular"
color={isWon ? colors.green["700"] : colors.grey["800"]}
fontSize="xs"
textAlign={isWon ? "end" : "start"}
>
<>
{
betStatusCodeMap[betStatusCode || BetStatusCodesEnum.ACTIVE]
.label
}
</>
</Paragraph>
</VerticalParagraphRight>
);
}
};
const renderSelections = () =>
isCustomSelectionsView ? (
<CustomBetSelectionsView
isKey={isKey}
isBox={isBox}
isLeg={isLeg}
isWheel={isWheel}
isSpecialWager={isSpecialWager}
isExoticBet={isExoticBet}
completeSelection={completeSelection}
numWagerableRunners={numWagerableRunners}
type={type}
currentRaceNumber={raceNumber}
scratches={scratches}
breed={breed}
isAlternateView={displayAlternateSelection}
showAlternatePlaceholder={showAlternatePlaceholder}
/>
) : (
<BetSelection
numWagerableRunners={numWagerableRunners?.[0]}
selections={selections}
type={type}
breed={breed}
showBetType={false}
scratches={Array.from(new Set(scratches?.flat(1)))} // remove duplicates
onHandicaping={rest.onHandicaping}
isAlternateView={displayAlternateSelection}
showAlternatePlaceholder={showAlternatePlaceholder}
/>
);
return (
<Container
showOnlySelections={showOnlySelections}
{...betTypeCellQaLabel}
{...rest}
>
{!showOnlySelections && (
<Header>
<VerticalParagraphLeft>
<Paragraph qaLabel="bet-amount">{`${betAmount} ${betTypeName}`}</Paragraph>
<Paragraph
qaLabel="ticket-amount"
fontFamily="condensedRegular"
color={colors.grey["800"]}
fontSize="xs"
>
{`${betTicket} TICKET`}
</Paragraph>
</VerticalParagraphLeft>
{renderRightColumn()}
</Header>
)}
<ContentActionsWrapper>
<Content hasButtons={!!onRepeatBetHandler || !!onCancelBetHandler}>
{selections?.length ? renderSelections() : null}
</Content>
{(onRepeatBetHandler && !isRaceOff) ||
(onCancelBetHandler && !isRaceOff) ? (
<Actions>
{onRepeatBetHandler && isRepeatable && (
<IconButton
iconName="repeat"
qaLabel="repeat-bet-btn"
size="s"
variant="tertiary"
tertiaryColor="grey.800"
onPress={onRepeatBetHandler}
/>
)}
{onCancelBetHandler && (
<IconButton
iconName="trash"
qaLabel="cancel-bet-btn"
size="s"
variant="tertiary"
tertiaryColor="grey.800"
onPress={onCancelBetHandler}
/>
)}
</Actions>
) : null}
</ContentActionsWrapper>
</Container>
);
};
export default BetTypeCell;
export { BetStatusCodesEnum };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/betTypeSelector/components/betTypeButton/styled-components.ts
import styled, { css } from "styled-components/native";
import { StyledProps } from "./types";
export const BetTypesTouchable = styled.TouchableHighlight<StyledProps>`
height: 100%;
padding: ${({ theme }) =>
`${theme.space["space-6"]} ${theme.space["space-4"]}`};
border-top-color: ${({ theme }) => theme.colorTokens.background.surface};
border-top-width: 2px;
${({ isHovered, theme }) =>
isHovered &&
css`
background-color: ${theme.colorTokens.component.button.buttonLink
.background.hover};
`}
${({ isPressed, theme }) =>
isPressed &&
css`
background-color: ${theme.colorTokens.component.input.pressed};
border-bottom-color: ${theme.colorTokens.content.link};
border-bottom-width: 2px;
`}
${({ isSelected, theme }) =>
isSelected &&
css`
border-bottom-color: ${theme.colorTokens.content.link};
border-bottom-width: 2px;
`};
`;
export const BetTypesText = styled.Text<StyledProps>`
color: ${({ theme }) => theme.colorTokens.content.default};
font-family: ${({ theme }) => theme.fonts.medium};
font-size: ${({ theme }) => theme.fontSizes.s};
text-align: center;
${({ isSelected, isPressed, theme }) =>
(isSelected || isPressed) &&
css`
color: ${theme.colorTokens.content.link};
`};
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/betTypeSelector/components/betTypeExpandableButton/styled-components.ts
import { ForwardedRef } from "react";
import styled, { css } from "styled-components/native";
import { View, TouchableHighlight, Text } from "react-native";
import { StyledProps } from "./types";
export const Container = styled(View)<{
ref: ForwardedRef<View & HTMLDivElement>;
}>`
position: relative;
`;
export const ButtonContent = styled(View)`
display: flex;
flex-direction: row;
`;
export const BetTypesTouchable = styled(TouchableHighlight)<StyledProps>`
height: 100%;
padding: ${({ theme }) =>
`${theme.space["space-6"]} ${theme.space["space-4"]}`};
border-top-color: ${({ theme }) => theme.colorTokens.background.surface};
border-top-width: 2px;
${({ isHovered, theme }) =>
isHovered &&
css`
background-color: ${theme.colorTokens.component.button.buttonLink
.background.hover};
`}
${({ isPressed, theme }) =>
isPressed &&
css`
background-color: ${theme.colorTokens.component.input.pressed};
border-bottom-color: ${theme.colorTokens.content.link};
border-bottom-width: 2px;
`}
${({ isSelected, theme }) =>
isSelected &&
css`
border-bottom-color: ${theme.colorTokens.content.link};
border-bottom-width: 2px;
`};
`;
export const BetTypesText = styled(Text)<StyledProps>`
color: ${({ theme }) => theme.colorTokens.content.default};
font-family: ${({ theme }) => theme.fonts.medium};
font-size: ${({ theme }) => theme.fontSizes.s};
text-align: center;
${({ isSelected, isPressed, theme }) =>
(isSelected || isPressed) &&
css`
color: ${theme.colorTokens.content.link};
`};
margin-right: 4px;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/betTypeSelector/components/betTypeExpandableButton/animatedDropdown/styled-components.ts
import styled from "styled-components/native";
import { AnimatedDropdownProps } from "./types";
import { Theme } from "../../../../../theming/types";
export const Container = styled.View<
Pick<AnimatedDropdownProps, "top" | "left" | "width" | "isTop">
>`
display: flex;
left: ${({ left }) => left}px;
padding-top: 8px;
position: ${({ isTop }) => (isTop ? "fixed" : "absolute")};
top: ${({ top }) => top}px;
width: ${({ width }) => width}px;
`;
export const ContentContainer = styled.View`
display: flex;
flex-direction: column;
position: absolute;
z-index: 999;
`;
export const Dropdown = styled.View<{
theme: Theme;
children?: React.ReactNode;
}>`
background-color: ${({ theme }) => theme.colorTokens.background.surface};
border-color: ${({ theme }) => theme.colorTokens.border.default};
border-radius: 4px;
border-width: 1px;
`;
export const ListItem = styled.View<{ children?: React.ReactNode }>`
display: flex;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/betTypeSelector/components/betTypeExpandableButton/dropdownSelection/styled-components.ts
import styled, { css } from "styled-components/native";
import { StyledProps } from "./types";
export const BetTypeTouchable = styled.TouchableHighlight<StyledProps>`
height: 100%;
border-bottom-color: ${({ theme }) => theme.colorTokens.border.default};
border-bottom-width: 1px;
padding-left: ${({ theme }) => `${theme.space["space-4"]}`};
padding-top: ${({ theme }) => `${theme.space["space-5"]}`};
padding-bottom: ${({ theme }) => `${theme.space["space-5"]}`};
${({ isHovered, theme }) =>
isHovered &&
css`
background-color: ${theme.colorTokens.component.button.buttonLink
.background.hover};
`}
${({ isPressed, theme }) =>
isPressed &&
css`
background-color: ${theme.colorTokens.component.input.pressed};
border-bottom-color: ${theme.colorTokens.content.link};
border-bottom-width: 1px;
`}
${({ isSelected, theme }) =>
isSelected &&
css`
border-bottom-color: ${theme.colorTokens.content.link};
border-bottom-width: 1px;
`}
${({ isHovered, isSelected, isParentHovered, theme }) =>
!isHovered &&
isSelected &&
!isParentHovered &&
css`
background-color: ${theme.colorTokens.component.button.buttonLink
.background.hover};
`}
`;
export const BetTypeText = styled.Text<StyledProps>`
color: ${({ theme }) => theme.colorTokens.content.default};
font-family: ${({ theme }) => theme.fonts.medium};
font-size: ${({ theme }) => theme.fontSizes.s};
${({ isSelected, isPressed, theme }) =>
(isSelected || isPressed) &&
css`
color: ${theme.colorTokens.content.link};
`};
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/betTypeSelector/components/betTypeExpandableButton/animatedDropdown/index.tsx
import React from "react";
import { useTransition, config, animated } from "@react-spring/native";
import ReactDOM from "react-dom";
import { useQaLabel } from "../../../../../hooks/useQaLabel";
import { useEvents } from "../../../../../hooks/useEvents";
import {
Container,
ContentContainer,
Dropdown,
ListItem
} from "./styled-components";
import { AnimatedDropdownProps } from "./types";
import { DropdownSelection } from "../dropdownSelection";
const AnimatedContainer = animated(ContentContainer);
export const AnimatedDropdown: React.FC<AnimatedDropdownProps> = ({
isDropdownVisible,
onSelectValue,
values,
selectedValue,
qaLabel,
isTop,
top,
left,
width
}) => {
const viewTestProps = useQaLabel(qaLabel);
const { events, eventsHandlers, hoverHandlers } = useEvents({});
const dropdownTransition = useTransition(isDropdownVisible, {
config: isDropdownVisible ? { ...config.stiff } : { duration: 150 },
from: { opacity: 0 },
enter: { opacity: 1 },
leave: { opacity: 0 }
});
return ReactDOM.createPortal(
<>
{dropdownTransition(
(styles, isOpen) =>
values.length > 0 &&
isOpen && (
// @ts-ignore
<Container
{...viewTestProps}
{...eventsHandlers}
{...events}
{...hoverHandlers}
isTop={isTop}
top={top}
left={left}
width={width}
>
<AnimatedContainer style={styles}>
<Dropdown>
{values.map((item, index) => (
<ListItem key={index.toString()}>
<DropdownSelection
item={item}
onSelectValue={onSelectValue}
selectedValue={selectedValue}
isParentHovered={events.isHovered}
qaLabel={qaLabel}
/>
</ListItem>
))}
</Dropdown>
</AnimatedContainer>
</Container>
)
)}
</>,
document.body
);
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/betTypeSelector/components/betTypeExpandableButton/animatedDropdown/index.native.tsx
import React from "react";
import { useTransition, config, animated } from "@react-spring/native";
import { useQaLabel } from "../../../../../hooks/useQaLabel";
import { useEvents } from "../../../../../hooks/useEvents";
import {
Container,
ContentContainer,
Dropdown,
ListItem
} from "./styled-components";
import { AnimatedDropdownProps } from "./types";
import { DropdownSelection } from "../dropdownSelection";
const AnimatedContainer = animated(ContentContainer);
export const AnimatedDropdownNative: React.FC<AnimatedDropdownProps> = ({
isDropdownVisible,
onSelectValue,
values,
selectedValue,
qaLabel,
isTop,
top,
left,
width
}) => {
const viewTestProps = useQaLabel(qaLabel);
const { events, eventsHandlers, hoverHandlers } = useEvents({});
const dropdownTransition = useTransition(isDropdownVisible, {
config: isDropdownVisible ? { ...config.stiff } : { duration: 150 },
from: { opacity: 0 },
enter: { opacity: 1 },
leave: { opacity: 0 }
});
return (
<>
{dropdownTransition(
(styles, isOpen) =>
isOpen &&
values.length > 0 && (
// @ts-ignore
<Container
{...viewTestProps}
{...eventsHandlers}
{...events}
{...hoverHandlers}
isTop={isTop}
top={top}
left={left}
width={width}
>
<AnimatedContainer style={styles}>
<Dropdown>
{values.map((item, index) => (
<ListItem key={index.toString()}>
<DropdownSelection
item={item}
onSelectValue={onSelectValue}
selectedValue={selectedValue}
isParentHovered={events.isHovered}
qaLabel={qaLabel}
/>
</ListItem>
))}
</Dropdown>
</AnimatedContainer>
</Container>
)
)}
</>
);
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/betTypeSelector/styled-components.ts
import styled from "styled-components/native";
import { View, Text } from "react-native";
import { space } from "../../theming/styledSystem";
export const BetTypeSelectorContainer = styled(View)`
display: flex;
flex-direction: row;
flex-grow: 1;
${space};
z-index: 1;
width: 100%;
background-color: ${({ theme }) => theme.colorTokens.background.surface};
`;
export const InfoContainer = styled(View)`
width: 94px;
flex-grow: 0;
padding: ${({ theme }) =>
`${theme.space["space-3"]} ${theme.space["space-4"]}`};
background-color: ${({ theme }) => theme.colorTokens.background.accent};
border-bottom-color: ${({ theme }) => theme.colorTokens.border.default};
border-bottom-width: 1px;
border-top-color: ${({ theme }) => theme.colorTokens.border.default};
border-top-width: 1px;
border-right-color: ${({ theme }) => theme.colorTokens.border.default};
border-right-width: 1px;
border-top-left-radius: 4px;
`;
export const InfoText = styled(Text)`
font-size: ${({ theme }) => theme.fontSizes.m};
font-family: ${({ theme }) => theme.fonts.bold};
color: ${({ theme }) => theme.colorTokens.content.default};
text-align: center;
width: 70px;
height: 40px;
line-height: 20px;
`;
export const FadeLayer = styled(View)<{
orientation: "left" | "right";
width: number;
}>`
width: ${({ width }) => width}px;
position: absolute;
height: 55px;
left: 94px;
pointer-events: none;
background-image: linear-gradient(
to ${({ orientation }) => orientation},
rgba(255, 255, 255, 1) 0%,
rgba(255, 255, 255, 0) 5%
);
`;
export const BetTypesContainer = styled(View)<{ isOverFlowing: boolean }>`
flex: auto;
height: 60px;
display: flex;
flex-direction: row;
border-bottom-color: ${({ theme }) => theme.colorTokens.border.default};
border-bottom-width: 1px;
background-color: ${({ theme }) => theme.colorTokens.background.surface};
width: ${({ isOverFlowing }) =>
isOverFlowing ? "calc(100% - 166px)" : "calc(100% - 94px)"};
overflow-x: hidden;
border-top-right-radius: 4px;
`;
export const Navigation = styled(View)`
flex-shrink: 0;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
gap: 8px;
padding: 6px 12px 6px 12px;
background-color: ${({ theme }) => theme.colorTokens.background.surface};
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/button/styled-components.ts
import styled from "styled-components/native";
import { View, Text, TouchableHighlight } from "react-native";
import {
space,
SpaceProps,
width,
minWidth,
compose,
variant,
border
} from "../../theming/styledSystem";
import { Colors } from "../../theming";
import { useQaLabel } from "../../hooks/useQaLabel";
import { getAccessibilityRole } from "../../utils/accessibility";
import { ButtonProps, ButtonVariant, ButtonSize, IconPosition } from "./types";
export const TERNARY_COLOR_CODE = "blue_accent.500";
export const getTertiaryColor = (
colors: Colors,
colorCode: string,
event?: "hover" | "press",
isMobile?: boolean
) => {
if (isMobile) return null;
const eventVariantColor = {
hover: 100,
press: 200
};
const [color, variantColor] = colorCode.split(".");
const newVariantColor = event ? eventVariantColor[event] : variantColor;
// @ts-ignore
return colors[color][newVariantColor];
};
export const buttonSizes = {
s: {
height: "25px",
paddingX: "space-3"
},
m: {
height: "32px",
paddingX: "space-3"
},
l: {
height: "44px",
paddingX: "space-5"
}
};
const buttonStyles = compose(
space,
width,
minWidth,
border,
variant({ prop: "size", variants: buttonSizes })
);
export const StyledButton = styled(TouchableHighlight).attrs<{
qaLabel: string;
variant: string;
tertiaryColor: string;
isMobile?: boolean;
}>((props) => ({
...useQaLabel(props.qaLabel),
accessibilityRole: "button",
underlayColor:
props.variant === "tertiary"
? getTertiaryColor(
props.theme.colors,
props.tertiaryColor,
"press",
props.isMobile
)
: props.theme.buttons[props.variant as ButtonVariant]?.pressed?.background
}))<
ButtonProps & {
isPressed: boolean;
isHovered: boolean;
tertiaryColor: string;
isMobile?: boolean;
}
>`
align-items: center;
justify-content: center;
border-radius: ${({ theme }) => theme.radii.xs};
${({ theme, variant: buttonVariant }) =>
theme.buttons[buttonVariant as ButtonVariant]?.default};
${({
theme,
variant: buttonVariant,
isHovered,
isPressed,
isDisabled,
isLoading,
tertiaryColor,
isMobile
}) =>
(!isDisabled &&
!isLoading &&
isPressed &&
(buttonVariant === "tertiary"
? `background-color:${getTertiaryColor(
theme.colors,
tertiaryColor,
"press",
isMobile
)}`
: theme.buttons[buttonVariant as ButtonVariant]?.pressed)) ||
(!isDisabled &&
!isLoading &&
isHovered &&
(buttonVariant === "tertiary"
? `background-color:${getTertiaryColor(
theme.colors,
tertiaryColor,
"hover",
isMobile
)}`
: theme.buttons[buttonVariant as ButtonVariant]?.hovered))};
${buttonStyles};
opacity: ${(props) => (props.isDisabled || props.isLoading ? 0.5 : 1)};
${(props) => (props.isStretched ? "width: 100%;" : "align-self: flex-start;")}
flex-grow: ${(props) => (props.isStretched ? "1" : "0")};
`;
export const ButtonRow = styled(View)<{ iconPosition?: IconPosition }>`
align-items: center;
flex-direction: ${(props) =>
props.iconPosition === "end" ? "row-reverse" : "row"};
`;
const textSizes = {
s: {
fontFamily: "medium",
fontSize: "xs"
},
m: {
fontFamily: "medium",
fontSize: "s"
},
l: {
fontFamily: "medium",
fontSize: "s"
}
};
const textStyles = compose(
space,
variant({ prop: "size", variants: textSizes })
);
export const StyledText = styled(Text).attrs<{
color?: string;
}>(({ color }: { color?: string }) => ({
accessibilityRole: getAccessibilityRole("span"),
color
}))<{ variant?: ButtonVariant; size: ButtonSize; color?: string } & SpaceProps>`
${textStyles};
color: ${({ color, theme }) => color || theme.colors.white[900]};
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/button/container/index.tsx
import React from "react";
import { useTheme } from "../../../theming";
import { Icon, IconNames } from "../../icon";
import LoadingSpinner from "../../loading";
import {
ButtonRow,
StyledText,
getTertiaryColor,
TERNARY_COLOR_CODE
} from "../styled-components";
import { ButtonIcon, ButtonProps, ButtonVariant } from "../types";
const getButtonIcon = (icon: ButtonIcon, color: string) =>
React.isValidElement(icon) ? (
icon
) : (
<Icon
name={icon as IconNames}
size="s"
lineColor={color}
backgroundColor="transparent"
qaLabel="button-icon"
/>
);
export const ButtonContainer = ({
iconPosition,
variant,
isLoading,
size = "l",
icon,
children,
tertiaryColor
}: ButtonProps) => {
const { buttons, colors } = useTheme();
const color =
variant === "tertiary"
? getTertiaryColor(colors, tertiaryColor || TERNARY_COLOR_CODE)
: buttons[variant as ButtonVariant]?.default.color;
const bgColor =
variant === "tertiary"
? getTertiaryColor(colors, tertiaryColor || TERNARY_COLOR_CODE, "press")
: buttons[variant as ButtonVariant]?.loading?.background;
return (
<ButtonRow iconPosition={iconPosition}>
{isLoading ? (
<LoadingSpinner size={size || "l"} color={color} bgColor={bgColor} />
) : (
<>
{icon && getButtonIcon(icon, color || colors.white[900])}
{React.isValidElement(children) ? (
children
) : (
<StyledText
variant={variant}
color={color as string}
size={size}
ml={
children && icon && iconPosition === "start" ? "space-3" : "0px"
}
mr={
children && icon && iconPosition === "end" ? "space-3" : "0px"
}
>
{children}
</StyledText>
)}
</>
)}
</ButtonRow>
);
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/button/index.tsx
import React from "react";
import { type ButtonProps, ButtonSize } from "./types";
import { StyledButton, TERNARY_COLOR_CODE } from "./styled-components";
import { ButtonContainer } from "./container";
import { useEvents } from "../../hooks/useEvents";
export const Button = ({
variant,
size = "l",
children,
onPress,
isLoading = false,
iconPosition = "start",
icon,
tertiaryColor = TERNARY_COLOR_CODE,
isMobile = false,
qaLabel,
...rest
}: ButtonProps) => {
const { events, hoverHandlers, pressHandlers, focusHandlers } = useEvents({});
const disabled = rest.isDisabled || isLoading;
return (
<StyledButton
variant={variant}
size={size}
disabled={disabled}
isLoading={isLoading}
activeOpacity={1}
tertiaryColor={tertiaryColor}
isMobile={isMobile}
onPress={onPress}
qaLabel={qaLabel}
{...rest}
{...events}
{...hoverHandlers}
{...pressHandlers}
{...focusHandlers}
>
<ButtonContainer
iconPosition={iconPosition}
variant={variant}
isLoading={isLoading}
size={size}
icon={icon}
onPress={onPress}
qaLabel={qaLabel}
tertiaryColor={tertiaryColor}
isMobile={isMobile}
>
{children}
</ButtonContainer>
</StyledButton>
);
};
export { ButtonSize, StyledButton, TERNARY_COLOR_CODE };
export type { ButtonProps };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/buttonBar/styled-components.ts
import styled, { css } from "styled-components/native";
import { rgba } from "polished";
import { TouchableHighlight, Text } from "react-native";
import { EventsProps } from "./types";
import { borderRadius, compose } from "../../theming/styledSystem";
const buttonStyles = compose(borderRadius);
export const StyledTouchableHighlight = styled(TouchableHighlight)<EventsProps>`
height: 32px;
align-self: flex-start;
justify-content: center;
background-color: ${({ theme }) => theme.colorTokens.component.input.surface};
padding-left: ${({ theme, isCondensed }) =>
isCondensed ? 10 : theme.space["space-5"]};
padding-right: ${({ theme, isCondensed }) =>
isCondensed ? 10 : theme.space["space-5"]};
${({ isHovered, isPressed, isSelected, theme }) =>
(isHovered || isSelected) &&
css`
background-color: ${isPressed
? theme.colorTokens.component.button.buttonLink
: theme.colorTokens.component.button.tertiary.background.hover};
`}
${({ isCondensed, theme }) =>
!isCondensed &&
css`
box-shadow: 0 1px 3px ${rgba(17, 43, 68, 0.12)};
margin-right: 8px;
height: 44px;
border-width: 1px;
border-radius: ${theme.radii.xs};
border-color: ${theme.colorTokens.border.default};
`}
${({ isHovered, isCondensed }) =>
isHovered &&
!isCondensed &&
css`
box-shadow: 0 2px 4px ${rgba(17, 43, 68, 0.14)};
`}
${({ isSelected, theme }) =>
isSelected &&
css`
background-color: ${theme.colorTokens.component.button.buttonLink
.background.active};
border-color: ${theme.colorTokens.border.default};
box-shadow: none;
`};
${({ isPressed, theme }) =>
isPressed &&
css`
border-color: ${theme.colorTokens.border.default};
background-color: ${theme.colorTokens.component.button.tertiary.background
.hover};
box-shadow: none;
`}
${buttonStyles};
`;
export const StyledText = styled(Text)<EventsProps>`
display: flex;
justify-content: center;
font-family: ${({ theme }) => theme.fonts.medium};
font-size: ${({ theme }) => theme.fontSizes.s};
color: ${({ theme }) => theme.colorTokens.content.default};
${({ isHovered, theme }) =>
isHovered &&
css`
color: ${theme.colorTokens.content.default};
`}
${({ isPressed, theme }) =>
isPressed &&
css`
color: ${theme.colorTokens.content.default};
`}
${({ isSelected, isPressed, theme }) =>
isSelected &&
!isPressed &&
css`
color: ${theme.colorTokens.component.button.buttonLink.content.active};
`}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/buttonBar/buttonBarGroup/styled-components.ts
import styled, { css } from "styled-components/native";
import { Platform } from "react-native";
import { rgba } from "polished";
import { margin } from "styled-system";
import { Theme } from "../../../theming/types";
export const StyleViewContainer = styled.View<{
isCondensed: boolean;
theme: Theme;
children?: React.ReactNode;
}>`
${margin}
flex-direction: row;
${Platform.OS === "web" && `width: auto;`}
${({ isCondensed, theme }) =>
isCondensed &&
css`
border-width: 1px;
border-color: ${theme.colors.blue[100]};
border-radius: ${theme.radii.xs};
box-shadow: 0 1px 3px ${rgba(17, 43, 68, 0.12)};
width: fit-content;
`}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/buttonBar/buttonBarGroup/index.tsx
import React, { createContext } from "react";
import { ButtonBarGroupProps, ButtonBarGroupContextProps } from "./types";
import { StyleViewContainer } from "./styled-components";
import { ScrollViewFading } from "../../scrollViewFading";
const initialState = {
selectedValue: "",
onChange: () => {},
isCondensed: false
};
export const GroupContext =
createContext<ButtonBarGroupContextProps>(initialState);
export const ButtonBarGroup = ({
children,
selectedValue,
onChange,
isCondensed = false,
showScrollBars = true,
...rest
}: ButtonBarGroupProps) => (
<GroupContext.Provider value={{ selectedValue, onChange, isCondensed }}>
<StyleViewContainer isCondensed={isCondensed} {...rest}>
<ScrollViewFading showScrollBars={showScrollBars} {...rest}>
{children}
</ScrollViewFading>
</StyleViewContainer>
</GroupContext.Provider>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/buttonBar/index.tsx
import React, { useContext, useEffect, useRef } from "react";
import { TouchableHighlight } from "react-native";
import { useColorTokens } from "../../theming";
import { useQaLabel } from "../../hooks/useQaLabel";
import { ButtonBarProps, ButtonBarCompoundComponent } from "./types";
import { StyledTouchableHighlight, StyledText } from "./styled-components";
import { ButtonBarGroup, GroupContext } from "./buttonBarGroup";
import { useEvents } from "../../hooks/useEvents";
export const ButtonBar = (({
children,
isSelected = false,
value,
qaLabel,
focusOnSelected = false,
...rest
}) => {
const viewTestProps = useQaLabel(qaLabel);
const colorTokens = useColorTokens();
const { isCondensed = false } = useContext(GroupContext);
const { events, eventsHandlers, setEvents } = useEvents({});
const { selectedValue, onChange = () => {} } = useContext(GroupContext);
const buttonRef = useRef<typeof TouchableHighlight | null>(null);
useEffect(() => {
setEvents({ ...events, isSelected });
}, [isSelected]);
useEffect(() => {
setEvents({
...events,
isSelected: isSelected || selectedValue === value
});
}, [selectedValue]);
useEffect(() => {
if (focusOnSelected && events.isSelected) {
// @ts-ignore
buttonRef?.current?.scrollIntoView({
behavior: "smooth",
block: "nearest",
inline: "center"
});
}
}, [focusOnSelected, events.isSelected]);
const pressHandler = () => {
onChange(value);
};
return (
<StyledTouchableHighlight
// @ts-ignore
ref={buttonRef}
{...rest}
{...viewTestProps}
{...eventsHandlers}
{...events}
isCondensed={isCondensed}
onPress={pressHandler}
accessibilityRole="button"
underlayColor={colorTokens.border.info}
onLongPress={pressHandler}
>
{typeof children === "string" ? (
<StyledText {...events} isCondensed={isCondensed}>
{children}
</StyledText>
) : (
children
)}
</StyledTouchableHighlight>
);
}) as ButtonBarCompoundComponent<typeof ButtonBarGroup>;
export type { ButtonBarProps };
ButtonBar.Group = ButtonBarGroup;
export default ButtonBar;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/checkbox/checkboxGroup/styled-components.ts
import styled from "styled-components/native";
import { margin } from "styled-system";
import { Theme } from "../../../theming/types";
export const StyledViewContainer = styled.View`
${margin}
border-width: 1px;
border-color: transparent;
`;
export const StyledTextLabel = styled.Text<{
theme: Theme;
children?: React.ReactNode;
}>`
font-family: ${({ theme }) => theme.fonts.medium};
color: ${({ theme }) => theme.colors.grey[900]};
margin-bottom: ${({ theme }) => theme.space["space-4"]};
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/checkbox/checkboxGroup/index.tsx
import { View } from "react-native";
import React, { createContext, forwardRef, useState, useEffect } from "react";
import { useQaLabel } from "../../../hooks/useQaLabel";
import { CheckboxGroupProps, CheckboxGroupContextProps } from "./types";
import { StyledViewContainer, StyledTextLabel } from "./styled-components";
const initialState = {
selectedValues: [],
onChange: () => {},
values: new Set<string>()
};
export const GroupContext = createContext<
CheckboxGroupContextProps & {
values: Set<string>;
}
>(initialState);
export const CheckboxGroup = forwardRef<View, CheckboxGroupProps>(
(
{
label = "",
children,
selectedValues,
qaLabel,
isDisabled = false,
onChange,
...rest
},
ref
) => {
const viewTestProps = useQaLabel(qaLabel);
const [values, setValues] = useState<Set<string>>(new Set([]));
useEffect(() => {
setValues(new Set(selectedValues));
}, [String(selectedValues)]);
return (
// @ts-ignore
<StyledViewContainer ref={ref} {...rest} {...viewTestProps}>
<GroupContext.Provider
value={{ values, selectedValues, onChange, isDisabled }}
>
{label !== "" && (
<View>
<StyledTextLabel accessibilityLabel={label}>
{label}
</StyledTextLabel>
</View>
)}
<View>{children}</View>
</GroupContext.Provider>
</StyledViewContainer>
);
}
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/checkbox/checker.tsx
import React from "react";
import Svg, { Path } from "react-native-svg";
import { useTheme } from "../../theming";
import { CheckerProps } from "./types";
export const Checker = ({ isDisabled }: CheckerProps) => {
const { colors } = useTheme();
return (
<Svg
width="14"
height="10"
viewBox="0 0 14 10"
fill="none"
focusable={false}
>
<Path
d="M1.5 5L5 8.5L12.5 1"
stroke={isDisabled ? colors.blue[200] : colors.white[900]}
strokeWidth="1.5"
strokeLinejoin="round"
/>
</Svg>
);
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/checkbox/styled-components.ts
import styled from "styled-components/native";
import { Platform, Pressable, Text, View } from "react-native";
import { margin, flex } from "styled-system";
import { CheckboxProps } from "./types";
const setDefaultCursor = Platform.OS === "web" && `cursor: default;`;
export const StyledPressableContainer = styled(Pressable)<{
isHovered: boolean;
isDisabled: boolean;
isInvalid: boolean;
isChecked: boolean;
isPressed: boolean;
}>`
height: 24px;
width: 24px;
background-color: ${({ theme }) => theme.colors.white[900]};
border-radius: ${({ theme }) => theme.radii.s};
border: 1px solid ${({ theme }) => theme.colors.blue[200]};
justify-content: center;
align-items: center;
box-shadow: ${({ theme }) => theme.elevations.low};
${setDefaultCursor}
${({ isHovered, isDisabled, theme }) =>
isHovered &&
`
border: 2px solid ${
isDisabled ? theme.colors.blue[100] : theme.colors.blue_accent[500]
};
box-shadow: ${theme.elevations.medium};
`}
${({ isInvalid, isDisabled, theme }) =>
isInvalid &&
`
border: 2px solid ${
isDisabled ? theme.colors.blue[100] : theme.colors.orange[600]
};
`}
${({ isChecked, theme }) =>
isChecked &&
`
background-color: ${theme.colors.blue_accent[500]};
border: 2px solid ${theme.colors.blue_accent[500]};
box-shadow: none;
`}
${({ isPressed, theme }) =>
isPressed &&
`
background-color: ${theme.colors.blue_accent[500]};
border: 2px solid ${theme.colors.blue_accent[500]};
box-shadow: none;
`}
${({ isDisabled, isChecked, theme }) =>
isDisabled &&
`
background-color: ${theme.colors.blue["000"]};
border: ${isChecked ? "2px" : "1px"} solid ${theme.colors.blue[100]};
box-shadow: none;
${setDefaultCursor}
`}
`;
export const StyledPressableLabelContainer = styled(Pressable)`
${setDefaultCursor}
flex-shrink: 1;
`;
export const StyledTextLabel = styled(Text)<{ isDisabled: boolean }>`
flex-shrink: 1;
font-family: ${({ theme }) => theme.fonts.regular};
color: ${({ theme }) => theme.colors.grey[900]};
margin-left: ${({ theme }) => theme.space["space-3"]};
margin-right: ${({ theme }) => theme.space["space-6"]};
${({ isDisabled, theme }) =>
isDisabled &&
`
color: ${theme.colors.grey[600]};
`}
`;
export const StyledViewContainer = styled(View)`
flex-direction: row;
align-items: center;
margin-bottom: ${({ theme }) => theme.space["space-4"]};
${margin}
`;
export const Checkbox = styled(Text).attrs<CheckboxProps>((props) => ({
alignLabel: props.flex === "start" ? "start" : "end"
}))<CheckboxProps>`
${flex}
`;
Checkbox.defaultProps = {
alignLabel: "center"
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/checkbox/index.tsx
import React, { useContext, forwardRef, useState, useEffect } from "react";
import { View } from "react-native";
import { useQaLabel } from "../../hooks/useQaLabel";
import { CheckboxGroup, GroupContext } from "./checkboxGroup";
import { CheckboxProps, CheckboxCompoundComponent } from "./types";
import { useEvents } from "../../hooks/useEvents";
import { Checker } from "./checker";
import {
StyledPressableContainer,
StyledTextLabel,
StyledViewContainer,
StyledPressableLabelContainer
} from "./styled-components";
export const Checkbox = forwardRef<View, CheckboxProps>(
({ value, label, isInvalid = false, qaLabel = value, ...rest }, ref) => {
const [isChecked, setIsChecked] = useState(false);
const { events, eventsHandlers } = useEvents({});
const { onChange, isDisabled = false, values } = useContext(GroupContext);
useEffect(() => {
setIsChecked(values.has(value));
}, [values]);
const pressHandler = () => {
if (isDisabled) return;
const currentState = !isChecked;
setIsChecked(currentState);
if (currentState) {
values?.add(value);
} else {
values?.delete(value);
}
onChange(Array.from(values));
};
return (
<StyledViewContainer {...useQaLabel(qaLabel)} {...rest}>
<StyledPressableContainer
{...rest}
{...useQaLabel(`${qaLabel}-input`)}
{...events}
{...eventsHandlers}
onPress={pressHandler}
ref={ref}
accessibilityRole="checkbox"
focusable
isInvalid={isInvalid}
isChecked={isChecked}
isDisabled={isDisabled}
accessibilityState={{ checked: isChecked }}
>
{isChecked && <Checker isDisabled={isDisabled} />}
</StyledPressableContainer>
{label !== "" && (
<StyledPressableLabelContainer
focusable={false}
onPress={pressHandler}
{...events}
{...eventsHandlers}
>
<StyledTextLabel
isDisabled={isDisabled}
{...useQaLabel(`${qaLabel}-label`)}
>
{label}
</StyledTextLabel>
</StyledPressableLabelContainer>
)}
</StyledViewContainer>
);
}
) as CheckboxCompoundComponent<typeof CheckboxGroup>;
export type { CheckboxProps };
Checkbox.Group = CheckboxGroup;
export default Checkbox;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/iconWithBackground/styled-components.ts
import styled from "styled-components/native";
import { View } from "react-native";
export const StyledComponent = styled(View)`
justify-content: center;
align-items: center;
`;
export const IconContainer = styled(View)`
position: absolute;
width: ${({ theme }) => theme.space["space-7"]};
height: ${({ theme }) => theme.space["space-7"]};
`;
export const BagdeContainer = styled(View)`
position: absolute;
right: 0.5px;
top: 0.2px;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/dialogMessage/styled-components.ts
import styled, { css } from "styled-components/native";
import { View, Text } from "react-native";
import { space, layout, compose } from "styled-system";
import { Paragraph } from "../typography";
const styledUtils = compose(space, layout);
export const StyledViewContainer = styled(View)`
${styledUtils};
align-items: center;
`;
export const StyledParagraph = styled(Paragraph)`
text-align: center;
color: ${({ theme }) => theme.colors.grey[800]};
`;
export const StyledTextTitle = styled(Text)`
text-align: center;
${({ theme }) => css`
font-family: ${theme.fonts.bold};
font-size: ${theme.fontSizes.m};
color: ${theme.colors.grey[900]};
margin-top: ${theme.space["space-6"]};
margin-bottom: ${theme.space["space-3"]};
`}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/filterCells/components/filterButton/styled-components.ts
import styled, { css } from "styled-components/native";
import { Pressable } from "react-native";
import { FilterButtonProps, ButtonStates } from "./types";
import { Theme } from "../../../../theming/types";
const buttonSizes = {
s: css`
height: 25px;
padding: 4px 7px;
`,
m: css`
height: 32px;
padding: 6px 7px;
`,
l: css`
height: 44px;
padding: 12px 15px;
`
} as const;
const buttonStates = {
default: css`
background: transparent;
border: solid 1px transparent;
`,
hover: css`
background: ${({ theme }) =>
theme.colorTokens.component.button.tertiary.background.hover};
border: 1px solid ${({ theme }) => theme.colorTokens.border.default};
`,
active: css`
background: ${({ theme }) =>
theme.colorTokens.component.activeGroupedFilterCell.background};
border: 1px solid
${({ theme }) =>
theme.colorTokens.component.activeGroupedFilterCell.border};
z-index: 1;
`,
pressed: css`
background: ${({ theme }) =>
theme.colorTokens.component.button.buttonLink.background.hover};
border: 1px solid ${({ theme }) => theme.colorTokens.border.default};
`
} as const;
export const StyledButton = styled(Pressable)<
Pick<
FilterButtonProps,
"size" | "iconSide" | "minWidth" | "isStretch" | "hasWidth"
> &
ButtonStates
>`
align-items: center;
justify-content: center;
border-radius: 2px;
flex-direction: ${({ iconSide }) =>
iconSide === "left" ? "row" : "row-reverse"};
gap: 10px;
line-height: 18px;
margin: 0 -1px;
transition: all 0.2s ease-in-out;
${({ hasWidth }) =>
hasWidth &&
css`
width: max-content;
`}
${({ isStretch }) =>
isStretch &&
css`
flex: 1;
`}
${({ minWidth }) =>
minWidth &&
css`
min-width: ${minWidth}px;
`}
${({ size }) => buttonSizes[size as FilterButtonProps["size"]]}
${({ isHovered, isPressed, isActive }) => {
if (isActive) return buttonStates.active;
if (isPressed) return buttonStates.pressed;
if (isHovered) return buttonStates.hover;
return buttonStates.default;
}}
`;
export const StyledText = styled.Text<
Pick<ButtonStates, "isActive"> &
Pick<FilterButtonProps, "size"> & {
theme: Theme;
children?: React.ReactNode;
}
>`
color: ${({ theme, isActive }) =>
isActive
? theme.colorTokens.component.activeGroupedFilterCell.content
: theme.colorTokens.content.default};
font-family: ${({ theme }) => theme.fonts.medium};
font-size: ${({ theme, size }) =>
size === "s" ? theme.fontSizes.xs : theme.fontSizes.s};
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/filterCells/styled-components.ts
import styled, { css } from "styled-components/native";
import { View } from "react-native";
import { space, color, compose } from "styled-system";
import { FilterCellsProps } from "./types";
const stylesFn = compose(space, color);
const containerSizes = {
s: css`
height: 25px;
`,
m: css`
height: 32px;
`,
l: css`
height: 44px;
`
} as const;
const containerWidth = {
stretch: css`
width: 100%;
`,
maxContent: css`
width: max-content;
`
} as const;
export const FilterCellContainer = styled(View)<
Pick<FilterCellsProps, "size" | "hasShadow" | "isStretch" | "hasWidth">
>`
align-items: center;
border-radius: 2px;
${({ hasShadow }) =>
hasShadow &&
css`
box-shadow: ${({ theme }) => theme.elevations.low};
`}
border: 1px solid ${({ theme }) => theme.colorTokens.border.default};
flex-direction: row;
${({ hasWidth, isStretch }) => {
if (hasWidth && isStretch) return containerWidth.stretch;
return hasWidth && !isStretch && containerWidth.maxContent;
}}
${({ size }) => containerSizes[size as FilterCellsProps["size"]]};
${stylesFn}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/flag/styled-components.ts
import styled from "styled-components/native";
import { Svg } from "react-native-svg";
import { space } from "../../theming/styledSystem";
export const StyledSvg = styled(Svg)`
border-radius: 2px;
${space}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/headers/sectionHeader/styled-components.ts
import styled from "styled-components/native";
import { View } from "react-native";
import { layout } from "styled-system";
import { colors } from "../../../theming/themes/common/colors";
import { Paragraph } from "../../typography";
export const StyledComponent = styled(View)<{ isDesktop: boolean }>`
justify-content: center;
padding-left: ${({ theme }) => theme.space["space-4"]};
background-color: ${colors.white["900"]};
box-shadow: 0 1px 0 ${colors.blue["100"]};
min-height: ${({ isDesktop }) => (isDesktop ? "64px" : "48px")};
${layout}
`;
export const TextContainer = styled(View)`
flex-shrink: 1;
`;
export const Subtitle = styled(Paragraph)`
color: var(--fd-colors-content-subtle);
line-height: 125%;
margin-top: var(--fd-space-space-05, 2px);
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/headers/baseHeaders/styled-components.ts
import styled, { css } from "styled-components/native";
import { View } from "react-native";
import { Header, Paragraph } from "../../typography";
import { colors } from "../../../theming/themes/common/colors";
export const StyledComponent = styled(View)<{
hasRoundedCorners: boolean;
hasBorderBottom?: boolean;
hasShadow: boolean;
hasSubtitle: boolean;
isMobile: boolean;
isDarkMode?: boolean;
}>`
flex-direction: row;
align-content: space-between;
padding: ${({ isMobile, theme }) =>
isMobile ? theme.space["space-3"] : "14px"};
background-color: ${({ theme, isDarkMode }) =>
isDarkMode
? theme.colorTokens.background.promotional
: "var(--fd-colors-background-surface)"};
border-bottom-color: var(--fd-colors-border-subtle);
${({ hasBorderBottom }) =>
hasBorderBottom ? "border-bottom-width: 1px;" : "border-bottom-width: 0px;"}
${({ hasShadow }) =>
hasShadow && `box-shadow: 0 1px 3px ${colors.blue["100"]}`};
${({ hasSubtitle, isMobile }) =>
isMobile
? `min-height: ${hasSubtitle ? "69px" : "48px"}`
: `min-height: ${hasSubtitle ? "85px" : "64px"}`};
${({ hasRoundedCorners }) =>
hasRoundedCorners &&
"border-top-left-radius: var(--fd-radii-border-radius-020); border-top-right-radius: var(--fd-radii-border-radius-020);"}
`;
export const StyledHeader = styled(Header)`
font-size: var(--fd-font-sizes-font-size-060);
line-height: var(--fd-line-heights-line-height-010);
${({ isDarkMode }) =>
isDarkMode
? "color: var(--fd-colors-content-on-dark)"
: "color: var(--fd-colors-content-strong)"};
`;
const trackModalleftPadding = (isTrackRulesModal?: boolean) =>
isTrackRulesModal ? "4px" : "0";
export const TextContainer = styled(View)<{
isMobile: boolean;
isPaddingLeft: boolean;
isPaddingRight: boolean;
withoutButton: boolean;
titlePosition?: string;
isTrackRulesModal?: boolean;
}>`
flex-direction: column;
${({ titlePosition }) =>
titlePosition &&
css`
align-items: ${titlePosition};
`};
justify-content: center;
flex-grow: 1;
flex-shrink: 1;
padding: ${({
isMobile,
theme,
isPaddingLeft,
isPaddingRight,
isTrackRulesModal
}) =>
isMobile
? `${theme.space["space-1"]}
${isPaddingRight ? theme.space["space-8"] : "0"}
${theme.space["space-1"]}
${
isPaddingLeft && !isTrackRulesModal
? theme.space["space-8"]
: trackModalleftPadding(isTrackRulesModal)
}`
: `${theme.space["space-2"]}
${isPaddingRight ? theme.space["space-8"] : "0"}
${theme.space["space-2"]}
${isPaddingLeft ? theme.space["space-8"] : "0"}`};
${({ withoutButton, isMobile, theme }) =>
withoutButton &&
`padding: ${isMobile ? theme.space["space-1"] : theme.space["space-2"]}`};
`;
export const DescriptionContainer = styled(View)`
flex-direction: row;
align-items: center;
padding-top: ${({ theme }) => theme.space["space-1"]};
`;
export const ButtonIconContainer = styled(View)`
padding: 2px 0;
`;
export const ContainerLink = styled(View)`
flex-shrink: 1;
`;
export const StyledParagraph = styled(Paragraph)`
text-align: center;
`;
export const LeftElement = styled(View)`
justify-content: center;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/headers/baseHeaders/index.tsx
import React, { useContext } from "react";
import { useTheme } from "../../../theming";
import { TvgConfContext } from "../../../utils/tvgConfProvider";
import { useQaLabel } from "../../../hooks/useQaLabel";
import { Icon } from "../../icon";
import { IconButton } from "../../iconButton";
import {
DescriptionContainer,
StyledComponent,
StyledHeader,
TextContainer,
ButtonIconContainer,
ContainerLink,
StyledParagraph,
LeftElement
} from "./styled-components";
import { ModalHeaderProps, PagesHeaderProps } from "./types";
import { Link } from "../../link";
export const BaseHeader = ({
qaLabel = "modal-label",
title,
subtitle = "",
subtitleType = "description",
hasRoundedCorners = false,
hasShadow = false,
linkUrl,
onBack,
onClose,
headerLeftElement,
isDarkMode = false,
titlePosition,
isTrackRulesModal,
hasBorderBottom = false,
...rest
}: PagesHeaderProps & ModalHeaderProps) => {
const viewTestProps = useQaLabel(qaLabel);
const { device } = useContext(TvgConfContext);
const isMobile = device === "mobile";
const { fonts } = useTheme();
return (
<StyledComponent
hasRoundedCorners={hasRoundedCorners}
hasSubtitle={!!subtitle}
hasShadow={hasShadow}
isMobile={isMobile}
isDarkMode={isDarkMode}
hasBorderBottom={hasBorderBottom}
{...viewTestProps}
{...rest}
>
{React.isValidElement(headerLeftElement) && (
<LeftElement>{headerLeftElement}</LeftElement>
)}
{onBack && (
<ButtonIconContainer>
<IconButton
qaLabel="back-button-pages"
iconName="arrowLeft"
size="s"
variant="tertiary"
onPress={onBack}
/>
</ButtonIconContainer>
)}
<TextContainer
isMobile={isMobile}
isPaddingLeft={!onBack && !!onClose && !headerLeftElement}
isPaddingRight={!!onBack && !onClose}
withoutButton={!onClose && !onBack}
titlePosition={titlePosition}
isTrackRulesModal={isTrackRulesModal}
>
{typeof title === "string" && (
<StyledHeader
isDarkMode={isDarkMode}
tag="h2"
qaLabel="pages-header"
fontFamily="bold"
>
{title}
</StyledHeader>
)}
{React.isValidElement(title) && <>{title}</>}
{subtitle !== "" && (
<DescriptionContainer>
{subtitleType === "link" && (
<>
<Icon
name="info"
size="s"
pr="space-1"
qaLabel="description-icon"
lineColor="var(--fd-colors-system-info-content-accent)"
backgroundColor="var(--fd-colors-system-info-background-subtle)"
/>
<ContainerLink>
<Link
qaLabel="link"
href={linkUrl}
// eslint-disable-next-line react-native/no-inline-styles, react-native/no-color-literals
style={{
color: "var(--fd-colors-link-default-base)",
fontFamily: fonts.regular,
textAlign: "center"
}}
>
{subtitle}
</Link>
</ContainerLink>
</>
)}
{subtitleType === "description" && (
<StyledParagraph
qaLabel="pages-paragraph"
color="var(--fd-colors-content-subtle)"
>
{subtitle}
</StyledParagraph>
)}
{subtitleType === "element" && React.isValidElement(subtitle) && (
<>{subtitle}</>
)}
</DescriptionContainer>
)}
</TextContainer>
{onClose && (
<ButtonIconContainer>
<IconButton
qaLabel="close-button-pages"
iconName="close"
size="s"
variant={isDarkMode ? "tertiary_dark" : "tertiary"}
onPress={onClose}
/>
</ButtonIconContainer>
)}
</StyledComponent>
);
};
export type { PagesHeaderProps, ModalHeaderProps };
export default BaseHeader;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/headers/modalHeader/index.tsx
import React from "react";
import { BaseHeader } from "../baseHeaders";
import { ModalHeaderProps } from "../baseHeaders/types";
export const ModalHeader = ({
qaLabel = "modalHeader",
title,
subtitle = "",
subtitleType = "description",
hasRoundedCorners = false,
hasShadow = false,
hasBorderBottom = true,
isDarkMode = false,
linkUrl,
onBack,
onClose,
titlePosition,
headerLeftElement,
isTrackRulesModal
}: ModalHeaderProps) => (
<BaseHeader
qaLabel={qaLabel}
title={title}
subtitle={subtitle}
hasRoundedCorners={hasRoundedCorners}
hasShadow={hasShadow}
subtitleType={subtitleType}
linkUrl={linkUrl}
onBack={onBack}
onClose={onClose}
hasBorderBottom={hasBorderBottom}
headerLeftElement={headerLeftElement}
isDarkMode={isDarkMode}
titlePosition={titlePosition}
isTrackRulesModal={isTrackRulesModal}
/>
);
export type { ModalHeaderProps };
export default ModalHeader;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/headers/pageHeader/index.tsx
import React from "react";
import { BaseHeader } from "../baseHeaders";
import { PagesHeaderProps } from "../baseHeaders/types";
export const PageHeader = ({
qaLabel = "pageHeader",
title,
subtitle = "",
subtitleType = "description",
hasShadow = false,
linkUrl,
onBack,
titlePosition,
isTrackRulesModal,
hasBorderBottom = false
}: PagesHeaderProps) => (
<BaseHeader
qaLabel={qaLabel}
title={title}
subtitle={subtitle}
subtitleType={subtitleType}
hasShadow={hasShadow}
linkUrl={linkUrl}
onBack={onBack}
titlePosition={titlePosition}
isTrackRulesModal={isTrackRulesModal}
hasBorderBottom={hasBorderBottom}
/>
);
export type { PagesHeaderProps };
export default PageHeader;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/icon/iconContent.tsx
import React from "react";
import * as IconPaths from "../../../web/components/Icon/components/IconPaths";
import { IconContentProps, IconNames } from "./types";
const IconContent = ({
iconName,
lineColor,
backgroundColor,
strokeWidth
}: IconContentProps) =>
React.createElement(IconPaths[iconName as IconNames], {
lineColor,
backgroundColor,
strokeWidth
});
export default React.memo(IconContent);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/icon/styled-components.ts
import styled from "styled-components/native";
import { View } from "react-native";
import { space } from "../../theming/styledSystem";
export const Container = styled(View)(space);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/icon/constraints.ts
import { DefaultIconsColor } from "../../../web/components/Icon/types";
export const defaultIconColor: Partial<DefaultIconsColor> = {
info: {
background: "blue_accent.200",
line: "blue_accent.600"
},
exclamation: {
background: "yellow.200",
line: "yellow.700"
},
support: {
background: "blue_accent.200",
line: "blue_accent.600"
},
error: {
background: "red.100",
line: "red.600"
},
success: {
background: "green.100",
line: "green.600"
},
warning: {
background: "orange.200",
line: "orange.700"
},
changes: {
background: "orange.400",
line: "grey.900"
},
optedIn: {
background: "green.100",
line: "green.600"
},
promo: {
background: "yellow.200",
line: "yellow.800"
},
trash: {
background: "red.100",
line: "red.600"
}
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/icon/index.tsx
import React from "react";
import Svg from "react-native-svg";
import { useColorTokens, useTheme } from "../../theming";
import { useIconSize, useQaLabel } from "../../hooks";
import IconContent from "./iconContent";
import { IconProps, IconNames } from "./types";
import { Container } from "./styled-components";
import { getDefaultColor } from "./utils";
import { useIconList, useIsValidIcon } from "./hooks/index";
export const Icon = React.memo(
({
name,
size,
lineColor,
backgroundColor,
qaLabel,
ariaLabel,
shouldUseColorTokens,
overrideSize,
...props
}: IconProps) => {
const { colors } = useTheme();
const { iconSize, strokeWidth } = useIconSize(size);
const viewTestProps = useQaLabel(qaLabel || name);
const iconColor = getDefaultColor(name, colors, {
line: lineColor,
background: backgroundColor
});
const lineColorValue =
lineColor && lineColor?.indexOf("#") > -1 ? lineColor : iconColor.line;
const backgroundColorValue =
backgroundColor &&
backgroundColor?.includes("#") &&
backgroundColor?.includes("transparent")
? backgroundColor
: iconColor.background;
return (
<Container {...props}>
<Svg
width={overrideSize ?? iconSize}
height={overrideSize ?? iconSize}
viewBox="0 0 24 24"
fill="none"
accessibilityLabel={ariaLabel || name}
// @ts-ignore
tabIndex="0"
{...viewTestProps}
{...props}
>
<IconContent
iconName={name}
lineColor={
shouldUseColorTokens ? useColorTokens(lineColor) : lineColorValue
}
backgroundColor={backgroundColorValue}
strokeWidth={strokeWidth}
/>
</Svg>
</Container>
);
}
);
export { IconNames, useIconList, useIsValidIcon };
export default Icon;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/icon/utils.ts
import { get } from "lodash";
import { DefaultColor, IconNames } from "./types";
import { defaultIconColor } from "./constraints";
import { Colors } from "../../theming";
export const getDefaultColor = (
name: IconNames,
themeColor: Colors,
colors: Partial<DefaultColor>
): DefaultColor => {
const defaultColor = get(defaultIconColor, name, {
line: "grey.800",
background: "white.000"
});
const line = get(themeColor, colors.line || defaultColor.line, colors.line);
const background = get(
themeColor,
colors.background || defaultColor.background,
colors.background
);
return {
line,
background
};
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/iconButton/styled-components.ts
import styled from "styled-components/native";
import { View, TouchableHighlight } from "react-native";
import { space, compose, variant } from "../../theming/styledSystem";
import { useQaLabel } from "../../hooks/useQaLabel";
import { IconButtonProps } from "./types";
export const iconButtonSizes = {
s: {
width: "32px",
height: "32px",
padding: "space-2",
borderRadius: "16px"
},
m: {
width: "44px",
height: "44px",
padding: "space-4",
borderRadius: "22px"
},
l: {
width: "48px",
height: "48px",
padding: "14px",
borderRadius: "24px"
}
};
const buttonStyles = compose(
space,
variant({ prop: "size", variants: iconButtonSizes })
);
export const StyledButton = styled(TouchableHighlight).attrs<{
qaLabel: string;
}>((props: IconButtonProps) => ({
accessibilityRole: "button",
accessibilityLabel: props.textTooltip,
...useQaLabel(props.qaLabel)
}))<
IconButtonProps & {
hoveredColor: boolean;
pressedColor: boolean;
isHovered: boolean;
isPressed: boolean;
}
>`
align-items: center;
justify-content: center;
border-radius: var(--fd-radii-border-radius-010);
${({ theme, variant: buttonVariant }) =>
theme.iconButtons[buttonVariant]?.default};
${({
theme,
variant: buttonVariant,
isDisabled,
hoveredColor,
pressedColor,
isHovered,
isPressed,
isActive
}) =>
isActive
? theme.iconButtons[buttonVariant]?.pressed
: (!isDisabled &&
isPressed &&
(buttonVariant !== "tertiary"
? theme.iconButtons[buttonVariant]?.pressed
: `background-color:${pressedColor}`)) ||
(!isDisabled &&
(isHovered || isActive) &&
(buttonVariant !== "tertiary"
? theme.iconButtons[buttonVariant]?.hovered
: `background-color:${hoveredColor}`))};
opacity: ${(props) => (props.isDisabled ? 0.5 : 1)};
${buttonStyles}
`;
export const Container = styled(View)`
align-items: center;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/iconButton/index.tsx
import React, { useContext } from "react";
import { useTheme } from "../../theming";
import { Icon } from "../icon";
import type { IconButtonProps } from "./types";
import { StyledButton, Container } from "./styled-components";
import Tooltip from "../tooltip";
import { useEvents } from "../../hooks/useEvents";
import { TvgConfContext } from "../../utils/tvgConfProvider";
export const IconButton = ({
variant,
size = "l",
iconSize = "m",
iconName = "arrowLeft",
placementTooltip = "bottom-mid",
tertiaryColor = "grey.900",
textTooltip = "",
qaLabel,
onPress,
isActive,
...rest
}: IconButtonProps) => {
const { iconButtons, colors } = useTheme();
const { events, hoverHandlers, pressHandlers, focusHandlers } = useEvents({});
const { device } = useContext(TvgConfContext);
const isDesktop = device === "desktop";
const containerIconButton = () => (
<StyledButton
variant={variant}
size={size}
textTooltip={textTooltip || undefined}
tertiaryColor={tertiaryColor}
hoveredColor={getTertiaryColor(tertiaryColor, true, false, true)}
pressedColor={getTertiaryColor(tertiaryColor, false, true, true)}
disabled={rest.isDisabled}
activeOpacity={1}
underlayColor={
variant !== "tertiary"
? iconButtons[variant]?.pressed?.background
: getTertiaryColor(tertiaryColor, false, true, true)
}
isActive={isActive}
onPress={onPress}
qaLabel={qaLabel}
{...rest}
{...events}
{...(isDesktop ? hoverHandlers : {})}
{...pressHandlers}
{...focusHandlers}
>
<Icon
name={iconName}
size={iconSize}
lineColor={
variant !== "tertiary"
? iconButtons[variant]?.default?.color
: getTertiaryColor(tertiaryColor, false, false)
}
backgroundColor="transparent"
qaLabel="button-icon"
/>
</StyledButton>
);
const getTertiaryColor = (
colorValue: string,
isHovered: boolean,
isPressed: boolean,
isMobile?: boolean
) => {
if (colorValue.startsWith("#") || colorValue.startsWith("var")) {
return colorValue;
}
const [color, variantColor] = colorValue.split(".");
// @ts-ignore
const getColor = colors[color];
let setColor;
if (isMobile) return null;
if (isHovered) setColor = getColor[100];
if (isPressed) setColor = getColor[200];
return setColor ?? getColor[variantColor];
};
return (
<Container>
{textTooltip ? (
<Tooltip
qaLabel="tooltip"
content={textTooltip}
placement={placementTooltip}
isDarkMode={
variant === "secondary_dark" || variant === "tertiary_dark"
}
isDisabled={rest.isDisabled}
>
{containerIconButton()}
</Tooltip>
) : (
containerIconButton()
)}
</Container>
);
};
export type { IconButtonProps };
export default IconButton;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/illustration/styled-components.ts
import styled from "styled-components";
import { space } from "styled-system";
import { Svg } from "react-native-svg";
export const StyledSVG = styled(Svg)`
${space}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/image/styled-components.ts
import styled from "styled-components/native";
import { View } from "react-native";
import { space } from "styled-system";
export const StyledImage = styled.Image(space);
export const Container = styled(View)`
width: 100%;
`;
export const ErrorContainer = styled(View)`
flex-direction: row;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/input/styled-components.ts
import { Platform, View, Pressable, TextInput, Text } from "react-native";
import styled, { css } from "styled-components/native";
import {
space,
width,
color,
borderColor,
compose
} from "../../theming/styledSystem";
import { InputBoxProps, StyledInputProps } from "./types";
const backgroundColors = {
default: "white.900",
disabled: "blue.000",
pressed: "blue_accent.100",
hover: "blue_accent.000"
};
const borderColors = {
default: "blue.100",
hovered: "blue_accent.300",
focused: "blue_accent.500",
invalid: "orange.600"
};
const borderDefault = {
borderWidth: "1px",
borderStyle: "solid",
borderRadius: "2px",
borderColor: borderColors.default
};
const cssBorder = ({ isInvalid, isFocused }: InputBoxProps) => ({
...borderDefault,
borderWidth: isFocused || isInvalid ? "2px" : borderDefault.borderWidth
});
const cssBoxShadow = ({
isPressed,
isDisabled,
isHovered,
theme
}: InputBoxProps) => {
if (isDisabled || isPressed) {
return { boxShadow: "none" };
}
return isHovered
? { boxShadow: theme.elevations.medium }
: { boxShadow: theme.elevations.low };
};
const styledUtils = compose(space, width, color, borderColor);
export const InputBox = styled(View).attrs<InputBoxProps>((props) => ({
bg:
((props.isDisabled || !props.editable) && backgroundColors.disabled) ||
(props.isPressed && backgroundColors.pressed) ||
(props.isHovered && backgroundColors.hover) ||
backgroundColors.default,
borderColor:
(props.isFocused && borderColors.focused) ||
(props.isInvalid && borderColors.invalid) ||
(props.isHovered && borderColors.hovered) ||
borderColors.default
}))<InputBoxProps>`
flex-grow: 1;
width: auto;
height: 42px;
flex-direction: row;
align-content: space-between;
align-items: center;
${cssBoxShadow}
${cssBorder};
${styledUtils};
${({ isSelect }) =>
isSelect &&
css`
margin-left: 0;
margin-right: 0;
`}
`;
export const StyledInput = styled(TextInput).attrs<{
isDisabled: boolean;
}>((props) => ({
placeholderTextColor: props.isDisabled
? props.theme.colors?.blue[300]
: props.theme.colors?.grey[700]
}))<StyledInputProps>`
${Platform.OS === "web" &&
css`
outline-style: none;
`};
flex-grow: 1;
width: auto;
height: ${({ isNested }) => (isNested ? "100%" : "42px")};
${({ theme, isDisabled }) => css`
padding: ${theme.space["space-4"]};
font-family: ${theme.fonts?.regular};
font-size: ${theme.fontSizes?.s};
color: ${isDisabled ? theme.colors?.blue[300] : theme.colors?.grey[900]};
`}
`;
export const StyledPressable = styled(Pressable)`
align-items: stretch;
height: 42px;
flex-grow: 1;
flex-shrink: 1;
`;
export const TopWrapper = styled(View)`
flex-direction: row;
justify-content: space-between;
`;
export const LabelWrapper = styled(View)`
flex-direction: row;
align-content: flex-start;
align-items: center;
`;
export const StyledLabel = styled(Text)`
${space};
${({ theme }) => css`
font-family: ${theme.fonts?.medium};
font-size: ${theme.fontSizes?.s};
color: ${theme.colors?.grey[900]};
`}
`;
export const StyledOptionalTag = styled(Text)`
${({ theme }) => css`
margin-left: ${theme.space["space-1"]};
font-family: ${theme.fonts?.medium};
font-size: ${theme.fontSizes?.xs};
color: ${theme.colors?.grey[700]};
`}
`;
export const InputWrapper = styled(View)(compose(space, width));
export const IconWrapper = styled(View)`
margin-left: ${({ theme }) => theme.space["space-1"]};
`;
export const MessageWrapper = styled(View)`
${space};
flex-direction: row;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/input/inputSelect/styled-components.ts
// @ts-ignore
import { createElement, View } from "react-native";
import styled from "styled-components/native";
import type { OptionsProps, SelectProps } from "../types";
export const SelectElement = (props: SelectProps) =>
createElement("select", props);
export const OptionElement = (props: OptionsProps) =>
createElement("option", props);
export const Select = styled(SelectElement)<
Pick<SelectProps, "fonts" | "fontsizes" | "colors">
>`
appearance: none;
height: 42px;
background-color: transparent;
border: transparent;
z-index: 1;
padding-left: 12px;
padding-right: 36px;
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
font-family: ${({ fonts }) => fonts.regular};
font-size: ${({ fontsizes }) => fontsizes.s};
color: ${({ disabled, value, placeholder }) =>
disabled || (!value && placeholder)
? "var(--fd-colors-component-data-input-content-disabled)"
: "var(--fd-colors-component-data-input-content-base)"};
`;
export const Option = styled(OptionElement)<OptionsProps>`
font-family: ${({ fonts }) => fonts.regular};
`;
export const SelectWrapper = styled(View)`
margin-top: var(--fd-space-space-4);
padding: var(--fd-space-space-3);
width: 100%;
box-shadow: 0 2px 2px rgba(17, 43, 68, 0.15);
border-color: blue;
border-radius: 2px;
`;
export const SelectIconWrapper = styled(View)<{
isDisabled: boolean;
isMobile?: boolean;
}>`
position: absolute;
align-items: center;
justify-content: center;
right: 5px;
${({ isMobile }) =>
isMobile &&
`
top: calc(var(--fd-space-space-2)-2);
`};
border-radius: 100px;
height: var(--fd-space-space-8);
width: var(--fd-space-space-8);
`;
export const RnSelectWrapper = styled(View)`
align-items: center;
justify-content: center;
padding-left: var(--fd-space-space-3);
flex-grow: 1;
height: 42px;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/link/styled-components.ts
import styled from "styled-components/native";
import { View, Pressable } from "react-native";
import { space } from "styled-system";
export const StyledView = styled(View)(space);
export const StyledPressable = styled(Pressable)`
align-self: flex-start;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/link/utils/getColor.ts
export const getColor = (
isHovered: boolean,
isPressed: boolean,
isActive: boolean,
isLight: boolean
): string => {
const baseColor = "blue_accent";
const baseVariation = isLight ? 400 : 500;
if (isActive || isPressed) return `${baseColor}.${baseVariation + 200}`;
if (isHovered) return `${baseColor}.${baseVariation + 100}`;
return `${baseColor}.${baseVariation}`;
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/hooks/webEvents/createPseudoHook.ts
// Code from https://github.com/EvanBacon/react-native-web-hooks
// MIT License
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable consistent-return */
import * as React from "react";
import { Platform } from "react-native";
export function createPseudoHook<T>({
events
}: {
events: string[];
}): (ref: React.MutableRefObject<T> & any) => any {
return function inner(ref) {
if (
// Pseudo classes only work in the browser
Platform.OS !== "web"
) {
return false;
}
const [isActive, setActive] = React.useState(false);
React.useEffect(() => {
const [eventIn, eventOut] = events;
const node = ref && (ref.current || ref);
if (!node) {
return;
}
const resolve = (value: any) => {
setActive(value);
};
// @ts-ignore
const onStart = resolve.bind(this, true);
// @ts-ignore
const onEnd = resolve.bind(this, false);
node.addEventListener(eventIn, onStart);
node.addEventListener(eventOut, onEnd);
// Special case for useActive to respond when the user drags out of the view and releases.
if (eventOut === "mouseup") {
document.addEventListener(eventOut, onEnd, false);
}
return () => {
document.removeEventListener(eventOut, onEnd, false);
node.removeEventListener(eventIn, onStart);
node.removeEventListener(eventOut, onEnd);
};
}, [ref && ref.current]);
return isActive;
};
}
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/hooks/webEvents/index.ts
// Code from https://github.com/EvanBacon/react-native-web-hooks
// MIT License
import { MutableRefObject } from "react";
import { createPseudoHook } from "./createPseudoHook";
export const useActive = createPseudoHook({
events: ["mousedown", "mouseup"]
}) as <T>(ref: MutableRefObject<T>) => boolean;
export const useFocus = createPseudoHook({
events: ["focus", "blur"]
}) as <T>(ref: MutableRefObject<T>) => boolean;
export const useHover = createPseudoHook({
events: ["mouseenter", "mouseleave"]
}) as <T>(ref: MutableRefObject<T>) => boolean;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/link/index.tsx
import React, { forwardRef, useRef } from "react";
import { GestureResponderEvent, Linking, Platform, View } from "react-native";
import { useQaLabel } from "../../hooks/useQaLabel";
import Paragraph from "../typography/paragraph";
import { StyledPressable, StyledView } from "./styled-components";
import { LinkProps } from "./types";
import { getColor } from "./utils/getColor";
import { useEvents } from "../../hooks/useEvents";
import { useActive } from "../../hooks/webEvents";
const isWeb = Platform.OS === "web";
export const Link = forwardRef<View, LinkProps>(
(
{
qaLabel,
href,
children,
isDarkMode = false,
onPress,
style,
target = "_self",
...props
},
ref
) => {
const viewTestProps = useQaLabel(qaLabel);
const refLink = useRef(null);
const { events, eventsHandlers } = useEvents({});
const isActive = useActive(refLink);
const pressHandler = (e: GestureResponderEvent): void => {
// Allow always to have a onPress call if function is passed
if (typeof onPress === "function") {
onPress();
}
if (!isWeb || target === "_blank") {
Linking.openURL(href!);
e.preventDefault();
}
};
return (
<StyledView ref={ref} {...props}>
<StyledPressable
accessibilityRole="link"
// @ts-ignore
href={isWeb && target !== "_blank" && href}
onPress={pressHandler}
ref={refLink}
{...viewTestProps}
{...eventsHandlers}
>
<Paragraph
fontFamily="medium"
color={getColor(
events.isHovered,
events.isPressed,
isActive,
isDarkMode
)}
qaLabel={`${qaLabel}-text`}
style={style}
>
{children}
</Paragraph>
</StyledPressable>
</StyledView>
);
}
);
export type { LinkProps };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/linkCard/linkCardList/styled-components.ts
import styled from "styled-components/native";
import { View } from "react-native";
import { compose, space, border } from "../../../theming/styledSystem";
export const borderStyles = {
borderWidth: "1px",
borderColor: "blue.100",
borderRadius: "s"
};
export const getListElemDividerStyles = (index: number, listLength: number) => {
let styles = {};
const isFirstElement = index === 0;
const isLastElement = index === listLength - 1;
if (isFirstElement) {
styles = {
borderTopLeftRadius: borderStyles.borderRadius,
borderTopRightRadius: borderStyles.borderRadius
};
} else {
styles = {
borderTopWidth: borderStyles.borderWidth,
borderTopColor: borderStyles.borderColor
};
}
if (isLastElement) {
styles = {
...styles,
borderBottomLeftRadius: borderStyles.borderRadius,
borderBottomRightRadius: borderStyles.borderRadius
};
}
return styles;
};
const StyledCardListUtils = compose(space, border);
export const StyledCardList = styled(View)(StyledCardListUtils);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/linkCard/linkCardList/index.tsx
import React, { cloneElement } from "react";
import { useQaLabel } from "../../../hooks/useQaLabel";
import {
StyledCardList,
getListElemDividerStyles,
borderStyles
} from "./styled-components";
import { LinkCardListProps } from "../types";
const resetBorderStyles = {
borderWidth: 0,
borderRadius: 0
};
export const LinkCardList = ({
children,
qaLabel,
...rest
}: LinkCardListProps) => {
const listElements = React.Children.toArray(children);
const listLength = listElements.length;
return (
<StyledCardList
accessibilityRole="menu"
{...borderStyles}
{...useQaLabel(qaLabel)}
{...rest}
>
{listElements.map(
(elem, index) =>
React.isValidElement(elem) &&
cloneElement(elem, {
key: `list-${index}`,
accessibilityRole: "menuitem",
...resetBorderStyles,
...getListElemDividerStyles(index, listLength)
} as Partial<unknown>)
)}
</StyledCardList>
);
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/linkCard/index.tsx
import React, { forwardRef } from "react";
import { TouchableHighlight } from "react-native";
import { LinkCardProps, LinkCardCompoundComponent } from "./types";
import { LinkCardList } from "./linkCardList";
import { borderStyles } from "./linkCardList/styled-components";
import { LinkItem, LinkItemTitle } from "../linkItem";
export const LinkCard = forwardRef<typeof TouchableHighlight, LinkCardProps>(
(props, ref) => (
<LinkItem ref={ref} bg="blue_accent.000" {...borderStyles} {...props} />
)
) as LinkCardCompoundComponent<typeof LinkCardList>;
export type { LinkCardProps };
export { LinkItemTitle as LinkCardTitle, borderStyles as linkCardBorderStyles };
LinkCard.List = LinkCardList;
export default LinkCard;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/linkItem/styled-components.ts
import { Platform, View, Pressable } from "react-native";
import styled, { css } from "styled-components/native";
import { compose, space, color, border } from "../../theming/styledSystem";
import { Header } from "../typography";
const styledComponentUtils = compose(space, color, border);
export const StyledComponent = styled(Pressable).attrs<{
isDisabled?: boolean;
isHovered: boolean;
isPressed: boolean;
}>(({ isDisabled, isHovered, isPressed }) => ({
...(Platform.OS === "web"
? {
disabled: isDisabled
}
: {}),
...(isDisabled || isPressed || isHovered
? {
backgroundColor:
(isDisabled && "blue.000") ||
(isPressed && "blue_accent.200") ||
(isHovered && "blue_accent.100")
}
: {})
}))<{
isDisabled: boolean;
hasDividerLine: boolean;
}>`
width: 100%;
flex-direction: row;
justify-content: space-between;
${({ theme }) => css`
padding: ${theme.space["space-5"]} ${theme.space["space-4"]};
background-color: ${theme.colors.white["900"]};
`};
${styledComponentUtils};
${({ isDisabled, hasDividerLine }) =>
(isDisabled &&
(Platform.OS === "web"
? css`
opacity: 0.5;
cursor: default;
`
: css`
opacity: 0.5;
`)) || // visual fix for focus when using tab navigation
(hasDividerLine &&
Platform.OS === "web" &&
css`
outline-offset: -2px;
`)};
`;
export const ContentWrapper = styled(View)`
flex: 1;
flex-direction: row;
align-items: center;
`;
export const StyledContent = styled(View)`
flex: 1;
justify-content: space-between;
`;
export const StyledHeader = styled(Header).attrs({ tag: "h3" })`
${({ theme }) => css`
font-size: ${theme.fontSizes.s};
line-height: ${theme.lineHeights.s};
`}
`;
export const StyledDivider = styled(View)`
${({ theme }) => css`
position: absolute;
left: ${theme.space["space-4"]};
right: 0;
bottom: 0;
height: 1px;
background: ${theme.colors.blue[100]};
`}
`;
export const IconContainer = styled(View)<{ iconSize?: string }>`
height: ${({ iconSize }) => (iconSize && iconSize !== "s" ? "50%" : "100%")};
justify-content: ${({ iconSize }) =>
iconSize && iconSize !== "s" ? "center" : "flex-start"};
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/linkItem/linkItemList/styled-components.ts
import styled from "styled-components/native";
import { View } from "react-native";
import { compose, space, border } from "../../../theming/styledSystem";
const StyledItemListUtils = compose(space, border);
export const StyledItemList = styled(View)(StyledItemListUtils);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/linkItem/index.tsx
import React, { forwardRef } from "react";
import { TouchableHighlight, GestureResponderEvent } from "react-native";
import { useQaLabel } from "../../hooks/useQaLabel";
import { useEvents } from "../../hooks/useEvents";
import { Paragraph } from "../typography";
import { LinkItemProps, LinkItemCompoundComponent } from "./types";
import {
StyledComponent,
ContentWrapper,
StyledContent,
StyledHeader,
StyledDivider,
IconContainer
} from "./styled-components";
import { Icon } from "../icon";
import { LinkItemList } from "./linkItemList";
export const LinkItem = forwardRef<typeof TouchableHighlight, LinkItemProps>(
(
{
title,
description,
isDisabled = false,
start,
end,
onPress,
qaLabel,
hasDividerLine = false,
hasArrowRight = true,
...rest
},
ref
) => {
const { events, eventsHandlers } = useEvents({}, !isDisabled);
const marginByIconSize = (iconSize: string) => {
switch (iconSize) {
case "l":
return { mt: 6 };
case "m":
return { mt: 8 };
default:
return { mt: 2 };
}
};
const handleMargin = () =>
typeof title?.render === "object" && title?.iconSize
? marginByIconSize(title.iconSize)
: { mt: 0 };
return (
<StyledComponent
// @ts-ignore
ref={ref}
accessibilityRole="button"
isDisabled={isDisabled}
hasDividerLine={hasDividerLine}
onPress={(event: GestureResponderEvent) => {
if (typeof onPress === "function" && !isDisabled) onPress(event);
}}
{...events}
{...eventsHandlers}
{...rest}
{...useQaLabel(qaLabel)}
>
<>
<ContentWrapper>
{start}
<StyledContent>
{!!title &&
(React.isValidElement(title.render) ? (
title.render
) : (
<StyledHeader qaLabel={`${qaLabel}-title`} tag="h3">
{title.render}
</StyledHeader>
))}
{description && (
<Paragraph
color="grey.800"
qaLabel={`${qaLabel}-description`}
{...handleMargin()}
>
{description}
</Paragraph>
)}
</StyledContent>
{end}
</ContentWrapper>
{!isDisabled && onPress && hasArrowRight && (
<IconContainer iconSize={title?.iconSize}>
<Icon
name="chevronRight"
size="s"
lineColor="grey.800"
// @ts-ignore - avoid keyboard tab flow
focusable={false}
/>
</IconContainer>
)}
{hasDividerLine && <StyledDivider />}
</>
</StyledComponent>
);
}
) as LinkItemCompoundComponent<typeof LinkItemList>;
export type { LinkItemProps };
export { StyledHeader as LinkItemTitle };
LinkItem.List = LinkItemList;
export default LinkItem;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/linkItem/linkItemList/index.tsx
import React, { cloneElement } from "react";
import { useQaLabel } from "../../../hooks/useQaLabel";
import { StyledItemList } from "./styled-components";
import { LinkItemListProps } from "../types";
export const LinkItemList = ({
children,
qaLabel,
...rest
}: LinkItemListProps) => {
const listElements = React.Children.toArray(children);
const lastElemIndex = listElements.length - 1;
return (
<StyledItemList accessibilityRole="menu" {...useQaLabel(qaLabel)} {...rest}>
{listElements.map(
(elem, index) =>
React.isValidElement(elem) &&
cloneElement(elem, {
key: `list-${index}`,
accessibilityRole: "menuitem",
hasDividerLine: index !== lastElemIndex
} as Partial<unknown>)
)}
</StyledItemList>
);
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/loading/components/spinner/index.tsx
import React from "react";
import { Circle, G } from "react-native-svg";
import { animated, useSpring } from "@react-spring/native";
import { easeExpInOut } from "d3-ease";
import { useQaLabel } from "../../../../hooks";
import { SpinnerProps } from "../../types";
const AnimatedCircle = animated(G);
export const Spinner = ({ strokeWidth, color }: SpinnerProps) => {
const circleTestProps = useQaLabel("circle");
const { strokeDashoffset } = useSpring({
from: { strokeDashoffset: 68 },
to: { strokeDashoffset: 5 },
config: { easing: easeExpInOut, duration: 1800 },
loop: { reverse: true },
reset: true
});
return (
<AnimatedCircle
strokeDasharray="68.7"
strokeDashoffset={strokeDashoffset}
stroke={color}
strokeWidth={strokeWidth}
strokeLinecap="round"
strokeLinejoin="round"
transform="rotate(-90 12 12)"
{...circleTestProps}
>
<Circle fill="transparent" cx="12" cy="12" r="11" />
</AnimatedCircle>
);
};
export default Spinner;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/loading/styled-components.ts
import styled from "styled-components/native";
import { View } from "react-native";
export const Container = styled(View)<{ iconSize: string }>`
display: flex;
flex-flow: row wrap;
align-content: center;
height: ${(props) => props.iconSize}px;
width: ${(props) => props.iconSize}px;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/loading/index.tsx
import React, { forwardRef, memo, useEffect } from "react";
import { Animated, View } from "react-native";
import { Svg, Circle } from "react-native-svg";
import { easeExpInOut } from "d3-ease";
import { get } from "lodash";
import { useTheme } from "../../theming";
import { useIconSize, useQaLabel } from "../../hooks";
import { Spinner } from "./components";
import { Container } from "./styled-components";
import { LoadingProps } from "./types";
const LoadingSpinner = forwardRef<View, LoadingProps>(
(
{
size = "l",
color = "blue_accent.500",
bgColor = "blue_accent.200",
qaLabel = "loading-spinner"
}: LoadingProps,
ref
) => {
const testProps = useQaLabel(qaLabel);
const { colors } = useTheme();
const { iconSize, strokeWidth } = useIconSize(size);
const rotationAnim = new Animated.Value(0);
const interpolateRotation = rotationAnim.interpolate({
inputRange: [0, 1],
outputRange: ["0deg", "360deg"]
});
useEffect(() => {
const animation = Animated.loop(
Animated.timing(rotationAnim, {
useNativeDriver: false,
toValue: 1,
duration: 1800,
easing: easeExpInOut
}),
{
iterations: -1
}
);
animation.start();
return () => {
if (animation) {
animation.stop();
}
};
}, []);
return (
<Container {...testProps} iconSize={iconSize} ref={ref}>
<Animated.View style={{ transform: [{ rotate: interpolateRotation }] }}>
<Svg viewBox="0 0 24 24" height={iconSize} width={iconSize}>
<Circle
fill="transparent"
cx="12"
cy="12"
r="11"
stroke={get(colors, bgColor, bgColor)}
strokeWidth="2"
strokeDasharray="68.7"
/>
<Spinner
color={get(colors, color, color)}
strokeWidth={strokeWidth}
/>
</Svg>
</Animated.View>
</Container>
);
}
);
export const Loading = LoadingSpinner;
export type { LoadingProps };
export default memo(LoadingSpinner);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/loadingMaskAnimation/styled-components.ts
import { animated } from "@react-spring/native";
import styled from "styled-components/native";
import { margin } from "styled-system";
export const StyledAnimatedContainer = styled(animated.View)`
${margin}
width: 100%;
height: 100%;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/logo/types.ts
import { MarginProps } from "styled-system";
export type Brand = "4njbets" | "iowa" | "tvg" | "fdr" | "fdr-iowa";
export interface LogoProps extends MarginProps {
/**
* Set custom height
*/
height?: number;
/**
* Set TVG lettering to white
*/
isDarkMode?: boolean;
/**
* Brand
*/
brand?: Brand;
/**
* Show only illustration
*/
isOnlyIllustration?: boolean;
/**
* Set aria-label
*/
accessibilityLabel?: string;
/**
* Custom data-qa-label
*/
qaLabel?: string;
}
export enum DEFAULTS {
height = 18,
widthComplete = 103,
widthIllustration = 33
}
export enum TYPE_LOGO {
illustration = "illustration",
complete = "complete"
}
export type Dimension = {
dimension: {
viewBox: string;
height: number;
width: number;
};
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/logo/utils.ts
import { Brand, DEFAULTS, TYPE_LOGO, Dimension } from "./types";
const defaultDimensions = {
[TYPE_LOGO.complete]: [DEFAULTS.widthComplete, DEFAULTS.height],
[TYPE_LOGO.illustration]: [DEFAULTS.widthIllustration, DEFAULTS.height]
};
export const getDimensions = (
brand: Brand,
height: number,
typeLogo: TYPE_LOGO
): Dimension => {
const [defaultWidth, defaultHeight] = defaultDimensions[`${typeLogo}`];
switch (brand) {
case "iowa":
return {
dimension: {
viewBox: `0 0 103 30`,
height,
width: (height * 103) / 30
}
};
case "fdr":
return {
dimension: {
viewBox: `0 0 123 36`,
height: 36,
width: 126
}
};
case "4njbets":
return {
dimension: {
viewBox: `0 0 ${defaultWidth} ${defaultHeight}`,
height: height * 1.5,
width: (defaultWidth / defaultHeight) * (height * 1.5)
}
};
case "fdr-iowa":
return {
dimension: {
viewBox: `0 0 172 36`,
height: 36,
width: 172
}
};
default:
return {
dimension: {
viewBox: `0 0 112 34`,
height: 34,
width: 112
}
};
}
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/logo/styled-components.ts
import styled from "styled-components/native";
import { margin } from "styled-system";
import SVG from "react-native-svg";
export const StyledSVG = styled(SVG)(margin);
webpack://frontend-mybets/../../node_modules/react-native-safe-area-context/lib/module/SafeAreaView.js
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); }
import * as React from 'react';
import { View, StyleSheet } from 'react-native';
import { useSafeAreaInsets } from './SafeAreaContext';
// prettier-ignore
const TOP = 0b1000,
RIGHT = 0b0100,
BOTTOM = 0b0010,
LEFT = 0b0001,
ALL = 0b1111;
/* eslint-disable no-bitwise */
const edgeBitmaskMap = {
top: TOP,
right: RIGHT,
bottom: BOTTOM,
left: LEFT
};
export function SafeAreaView({
style = {},
mode,
edges,
...rest
}) {
const insets = useSafeAreaInsets();
const edgeBitmask = edges != null ? edges.reduce((accum, edge) => accum | edgeBitmaskMap[edge], 0) : ALL;
const appliedStyle = React.useMemo(() => {
const insetTop = edgeBitmask & TOP ? insets.top : 0;
const insetRight = edgeBitmask & RIGHT ? insets.right : 0;
const insetBottom = edgeBitmask & BOTTOM ? insets.bottom : 0;
const insetLeft = edgeBitmask & LEFT ? insets.left : 0;
const flatStyle = StyleSheet.flatten(style);
if (mode === 'margin') {
const {
margin = 0,
marginVertical = margin,
marginHorizontal = margin,
marginTop = marginVertical,
marginRight = marginHorizontal,
marginBottom = marginVertical,
marginLeft = marginHorizontal
} = flatStyle;
const marginStyle = {
marginTop: marginTop + insetTop,
marginRight: marginRight + insetRight,
marginBottom: marginBottom + insetBottom,
marginLeft: marginLeft + insetLeft
};
return [style, marginStyle];
} else {
const {
padding = 0,
paddingVertical = padding,
paddingHorizontal = padding,
paddingTop = paddingVertical,
paddingRight = paddingHorizontal,
paddingBottom = paddingVertical,
paddingLeft = paddingHorizontal
} = flatStyle;
const paddingStyle = {
paddingTop: paddingTop + insetTop,
paddingRight: paddingRight + insetRight,
paddingBottom: paddingBottom + insetBottom,
paddingLeft: paddingLeft + insetLeft
};
return [style, paddingStyle];
}
}, [style, insets, mode, edgeBitmask]);
return /*#__PURE__*/React.createElement(View, _extends({
style: appliedStyle
}, rest));
}
//# sourceMappingURL=SafeAreaView.js.map
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/modal/styled-components.ts
import { RefAttributes } from "react";
import styled, { css } from "styled-components/native";
import { initialWindowMetrics } from "react-native-safe-area-context";
import { ThemedStyledProps } from "styled-components";
import {
View,
ViewProps,
Modal,
TouchableWithoutFeedback,
Platform
} from "react-native";
import {
maxHeight,
MaxHeightProps,
maxWidth,
MaxWidthProps,
padding,
PaddingProps
} from "../../theming/styledSystem";
import { IsMobileProp, IsNativeProp, ModalTypeProp } from "./types";
import { Theme } from "../../theming/types";
export const INSET_VERTICAL = initialWindowMetrics
? initialWindowMetrics?.insets?.bottom + initialWindowMetrics?.insets?.top
: 0;
export const INSET_BOTTOM = initialWindowMetrics?.insets?.bottom || 0;
const PADDING_PROPS = [
"p",
"padding",
"pt",
"paddingTop",
"pb",
"paddingBottom",
"pl",
"paddingLeft",
"pr",
"paddingRight",
"py",
"paddingY",
"px",
"paddingX"
];
export const StyledModal = styled(Modal)`
background: ${({ theme }) => theme.colorTokens.background.surface};
`;
export const TouchableOverlayContainer = styled(TouchableWithoutFeedback)``;
export const TouchableContainer = styled(View)`
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
`;
export const OverlayContainer = styled(View)<ModalTypeProp>`
${({ theme, type }) => {
if (type === "full-width-page") {
return css`
background-color: ${theme.colorTokens.background.surface};
`;
}
if (type === "modal-custom-height") {
return "";
}
return css`
/* José asked to use this one by now */
background-color: ${theme.colors.black["700"]};
`;
}}
bottom: 0;
top: 0;
width: 100%;
position: absolute;
`;
export const ContentContainerFullscreen = styled(View)<{ topPosition: number }>`
border-top-right-radius: 4px;
border-top-left-radius: 4px;
position: absolute;
top: ${({ theme, topPosition }) => topPosition ?? theme.space["space-5"]};
bottom: 0;
background: ${({ theme }) => theme.colorTokens.background.surface};
width: 100%;
height: 100%;
padding-bottom: ${INSET_VERTICAL}px;
`;
export const ContentContainerCustomHeight = styled(View)<MaxHeightProps>`
border-top-right-radius: 4px;
border-top-left-radius: 4px;
position: absolute;
bottom: 0;
background: ${({ theme }) => theme.colorTokens.background.surface};
width: 100%;
height: 100%;
padding-bottom: ${INSET_VERTICAL}px;
${maxHeight}
`;
export const ContentContainerFullWidthPage = styled(View)`
position: absolute;
top: 0;
bottom: 0;
background: ${({ theme }) => theme.colorTokens.background.surface};
width: 100%;
padding-bottom: ${INSET_VERTICAL}px;
`;
const LIGHTBOX_DESKTOP_AND_TABLET_WIDTH = 391;
export const LIGHTBOX_MARGIN_SIDE = 12;
export const LIGHTBOX_MARGIN = LIGHTBOX_MARGIN_SIDE * 2;
export const ContentContainerLightbox = styled(View)<
{
height: number;
width: number;
contentHeight: number;
} & IsNativeProp
>`
position: absolute;
width: ${(props) => props.width - LIGHTBOX_MARGIN}px;
height: ${(props) => props.height - LIGHTBOX_MARGIN - INSET_VERTICAL}px;
display: flex;
margin: ${(props) => props.theme.space["space-4"]};
${(props) =>
props.contentHeight < props.height
? css`
justify-content: center;
`
: `justify-content: flex-start`};
align-items: center;
`;
export const ContentInnerLightbox = styled(View)<
{
height: number;
contentHeight?: number;
} & IsNativeProp &
IsMobileProp &
MaxWidthProps
>`
border-radius: ${(props) => props.theme.radii.s};
background: ${({ theme }) => theme.colors.white["900"]};
width: 100%;
max-width: ${(props) =>
props.isMobile ? "100%" : `${LIGHTBOX_DESKTOP_AND_TABLET_WIDTH}px`};
overflow: hidden;
${(props) => {
if (!props.isNative) return `height: auto;`;
return props?.contentHeight &&
props.contentHeight < props.height - LIGHTBOX_MARGIN
? css`
height: ${props.contentHeight}px;
`
: css`
height: ${props.height - INSET_VERTICAL}px;
`;
}};
max-height: ${(props) => props.height - LIGHTBOX_MARGIN}px;
${maxWidth}
`;
// We should consider using the safe area insets from react-native-safe-area-context
// The initialWindowMetrics for inset vertical is not returning the expected value
const insetVertical =
Platform.OS === "web" ? "env(safe-area-inset-top, 0)" : "0";
export const ContentContainerFlexible = styled(View)<{
contentHeight: number;
height: number;
}>`
position: absolute;
margin-top: ${LIGHTBOX_MARGIN_SIDE}px;
bottom: 0;
left: 0;
width: 100%;
height: ${(props) =>
props.contentHeight < props.height
? props.contentHeight + insetVertical
: props.height - LIGHTBOX_MARGIN_SIDE}px;
`;
export const ContentInnerFlexible = styled(View)`
position: relative;
border-top-right-radius: ${(props) => props.theme.radii.s};
border-top-left-radius: ${(props) => props.theme.radii.s};
background: ${({ theme }) => theme.colorTokens.background.surface};
bottom: 0;
width: 100%;
height: 100%;
/* stylelint-disable-next-line */
padding-bottom: constant(safe-area-inset-bottom);
padding-bottom: env(safe-area-inset-bottom);
`;
export const childrenSpacing = (
props: ThemedStyledProps<
ViewProps & RefAttributes<View> & IsMobileProp & ModalTypeProp,
Theme
>
) =>
`padding: ${
props.type === "lightbox" && !props.isMobile
? props.theme.space["space-6"]
: props.theme.space["space-4"]
}`;
export const ChildrenContainer = styled(View)<
IsMobileProp &
ModalTypeProp & {
hasPages: boolean;
pageHeight: number;
isDarkMode: boolean;
} & PaddingProps
>`
background-color: ${({ theme, isDarkMode }) =>
isDarkMode
? theme.colorTokens.background.promotional
: theme.colorTokens.background.surface};
${(props) => (!props.hasPages ? childrenSpacing(props) : ``)};
${(props) =>
!props.hasPages &&
// check if has any padding prop
Object.keys(props).some((prop) => PADDING_PROPS.includes(prop))
? padding(props)
: ``};
${(props) =>
props.type === "full-width-page" ||
props.type === "fullscreen" ||
props.type === "modal-custom-height"
? css`
height: ${props.pageHeight}px;
`
: ``};
`;
export const StickyAreaContainer = styled(View)<IsMobileProp & ModalTypeProp>`
${childrenSpacing};
box-shadow: 0 -2px 4px rgb(17 43 68 / 14%);
background-color: ${({ theme }) => theme.colorTokens.background.surface};
`;
export const TopStickyAreaContainer = styled(View)<
ModalTypeProp & {
isScrolling: boolean;
}
>`
z-index: 1;
background-color: ${(props) => props.theme.colors.white[900]};
${({ isScrolling }) =>
isScrolling &&
css`
box-shadow: 0 2px 4px rgb(17 43 68 / 14%);
`}
`;
webpack://frontend-mybets/../../node_modules/d3-ease/src/back.js
var overshoot = 1.70158;
export var backIn = (function custom(s) {
s = +s;
function backIn(t) {
return (t = +t) * t * (s * (t - 1) + t);
}
backIn.overshoot = custom;
return backIn;
})(overshoot);
export var backOut = (function custom(s) {
s = +s;
function backOut(t) {
return --t * t * ((t + 1) * s + t) + 1;
}
backOut.overshoot = custom;
return backOut;
})(overshoot);
export var backInOut = (function custom(s) {
s = +s;
function backInOut(t) {
return ((t *= 2) < 1 ? t * t * ((s + 1) * t - s) : (t -= 2) * t * ((s + 1) * t + s) + 2) / 2;
}
backInOut.overshoot = custom;
return backInOut;
})(overshoot);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/modal/hooks/useModalAnimations.tsx
import { useEffect, useState, useRef, Dispatch, SetStateAction } from "react";
import { Animated, Platform } from "react-native";
import { easeBackOut, easeBackInOut } from "d3-ease";
import { ModalBaseProps, ModalCloseType } from "../types";
interface UseModalAnimationsProps
extends Pick<
ModalBaseProps,
"onBack" | "onAfterClose" | "onClose" | "onOverlayClick" | "type"
> {
isModalOpen: boolean;
setModalIsOpen: Dispatch<SetStateAction<boolean>>;
closeType: ModalCloseType;
setCloseType: Dispatch<SetStateAction<ModalCloseType>>;
}
const useNativeDriver = Platform.OS !== "web";
export const useModalAnimations = ({
isModalOpen,
setModalIsOpen,
onClose,
closeType,
setCloseType,
onBack,
onOverlayClick,
type,
onAfterClose
}: UseModalAnimationsProps) => {
const [isClosing, setIsClosing] = useState(false);
const [isAnimating, setIsAnimating] = useState(false);
const overlayOpacityAnimation = useRef(new Animated.Value(0)).current;
const contentOpacityAnimation = useRef(new Animated.Value(0)).current;
const lightboxContentAnimation = useRef(new Animated.Value(0.5)).current;
const lightboxScaleAnimation = useRef(new Animated.Value(0.5)).current;
const flexibleContentAnimation = useRef(new Animated.Value(0)).current;
const fullscreenContentAnimation = useRef(new Animated.Value(0)).current;
const fullWidthPageContentAnimation = useRef(new Animated.Value(0)).current;
const animationController = useRef<Animated.CompositeAnimation | null>(null);
const animationCallback = () => {
setIsAnimating(false);
animationController.current = null;
if (isClosing) {
setModalIsOpen(false);
setIsClosing(false);
if (typeof onAfterClose === "function") {
onAfterClose(closeType);
}
switch (closeType) {
case "onBack":
if (typeof onBack === "function") {
onBack();
}
break;
case "onClose":
if (typeof onClose === "function") {
onClose();
}
break;
case "onOverlayClick":
if (typeof onOverlayClick === "function") {
onOverlayClick();
}
break;
default:
}
setCloseType("none");
}
};
const getModalAnimation = (
contentSequence: Array<Animated.CompositeAnimation> = []
): Animated.CompositeAnimation => {
setIsAnimating(true);
animationController.current = Animated.sequence(
isClosing
? [
...contentSequence,
Animated.timing(overlayOpacityAnimation, {
toValue: isClosing ? 0 : 0.6,
duration: 300,
useNativeDriver
})
]
: [
Animated.timing(overlayOpacityAnimation, {
toValue: isClosing ? 0 : 0.6,
duration: 300,
useNativeDriver
}),
...contentSequence
]
);
animationController.current.start(animationCallback);
return animationController.current;
};
const getContentOpacityAnimation = ({
duration,
delay = 0
}: {
duration: number;
delay?: number;
}) =>
Animated.timing(contentOpacityAnimation, {
toValue: isClosing ? 0 : 1,
duration,
delay,
useNativeDriver
});
// handle open and close with animations
useEffect(() => {
if (animationController.current) {
animationController.current.stop();
}
if ((!isClosing && isModalOpen) || isClosing) {
switch (type) {
case "lightbox": {
getModalAnimation([
Animated.parallel([
getContentOpacityAnimation({ duration: isClosing ? 200 : 300 }),
Animated.timing(lightboxContentAnimation, {
toValue: isClosing ? 0.5 : 1,
duration: 300,
delay: isClosing ? 100 : 0,
useNativeDriver,
easing: easeBackOut?.overshoot(0.8)
}),
Animated.timing(lightboxScaleAnimation, {
toValue: isClosing ? 0 : 1,
duration: 300,
useNativeDriver,
easing: easeBackInOut
})
])
]);
break;
}
case "fullscreen": {
getModalAnimation([
Animated.parallel(
[
getContentOpacityAnimation({
duration: 250,
delay: isClosing ? 0 : 150
}),
Animated.timing(fullscreenContentAnimation, {
toValue: isClosing ? 0 : 1,
duration: isClosing ? 500 : 400,
useNativeDriver,
easing: easeBackInOut?.overshoot(0.8)
})
],
{ stopTogether: false }
)
]);
break;
}
case "modal-custom-height": {
getModalAnimation([
Animated.parallel(
[
Animated.timing(fullscreenContentAnimation, {
toValue: isClosing ? 0 : 1,
duration: isClosing ? 500 : 400,
useNativeDriver,
easing: easeBackInOut?.overshoot(0.8)
})
],
{ stopTogether: false }
)
]);
break;
}
case "flexible": {
getModalAnimation([
Animated.parallel([
getContentOpacityAnimation({ duration: 300 }),
Animated.timing(flexibleContentAnimation, {
toValue: isClosing ? 0 : 1,
duration: 300,
useNativeDriver,
easing: easeBackInOut
})
])
]);
break;
}
case "full-width-page": {
getModalAnimation([
Animated.parallel(
[
getContentOpacityAnimation({
duration: 250,
delay: isClosing ? 0 : 150
}),
Animated.timing(fullWidthPageContentAnimation, {
toValue: isClosing ? 0 : 1,
duration: isClosing ? 500 : 400,
useNativeDriver,
easing: easeBackInOut?.overshoot(0.8)
})
],
{ stopTogether: false }
)
]);
break;
}
default:
}
}
}, [isClosing, isModalOpen]);
return {
isAnimating,
isClosing,
setIsClosing,
overlayOpacityAnimation,
contentOpacityAnimation,
lightboxContentAnimation,
lightboxScaleAnimation,
flexibleContentAnimation,
fullscreenContentAnimation,
fullWidthPageContentAnimation
};
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/modal/components/page/styled-components.ts
import styled from "styled-components/native";
import { View } from "react-native";
import { childrenSpacing } from "../../styled-components";
export const Page = styled(View)`
width: 100%;
position: absolute;
top: 0;
left: 0;
background-color: ${(props) => props.theme.colors.white[900]};
${childrenSpacing}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/modal/context/modalPagesReducer.ts
import { State, ReducerActions, ReducerActionTypes } from "./types";
export const INITIAL_STATE: State = {
activePage: undefined,
totalPages: undefined,
nextPage: undefined,
pageHeight: 0,
isFlexible: false,
isAnimating: false,
isFirstRender: true
};
export const ACTIONS: ReducerActionTypes = {
INIT: "INIT",
SET_STATE: "SET_STATE",
START_ANIMATION: "START_ANIMATION",
START_CHANGE_PAGE: "START_CHANGE_PAGE",
END_CHANGE_PAGE: "END_CHANGE_PAGE"
};
export const modalPagesReducer = (
state: State = INITIAL_STATE,
action: ReducerActions
) => {
switch (action.type) {
case ACTIONS.INIT:
return {
...state,
totalPages: action.payload.totalPages
};
case ACTIONS.SET_STATE:
return {
...state,
...action.payload
};
case ACTIONS.START_ANIMATION:
return {
...state,
isAnimating: true
};
case ACTIONS.START_CHANGE_PAGE:
return {
...state,
nextPage: action.payload.nextPage
};
case ACTIONS.END_CHANGE_PAGE:
return {
...state,
isAnimating: false,
activePage: state.nextPage
};
default:
return state;
}
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/modal/context/modalPagesContext.tsx
import { createContext, useContext, useReducer, useMemo } from "react";
import { Context, State } from "./types";
import { modalPagesReducer, INITIAL_STATE } from "./modalPagesReducer";
export const ModalPagesContext = createContext<Context>([
INITIAL_STATE,
() => {}
]);
ModalPagesContext.displayName = "ModalPagesContext";
export const useModalPagesReducer = (initialState?: Partial<State>) => {
const [state, dispatch] = useReducer(
modalPagesReducer,
{ ...INITIAL_STATE, ...initialState } ?? INITIAL_STATE
);
const context: Context = useMemo(() => [state, dispatch], [state, dispatch]);
return context;
};
export const useModalPagesContext = () => useContext(ModalPagesContext);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/modal/components/page/index.tsx
import React, { useRef, useEffect, useCallback } from "react";
import {
Animated,
Platform,
Dimensions,
LayoutChangeEvent
} from "react-native";
import { easeBackInOut } from "d3-ease";
import { useQaLabel } from "../../../../hooks/useQaLabel";
import { ModalPageProps } from "./types";
import { Page } from "./styled-components";
import { useModalPagesContext } from "../../context/modalPagesContext";
import { ACTIONS } from "../../context/modalPagesReducer";
const useNativeDriver = Platform.OS !== "web";
type AnimationDirection = "IN" | "OUT";
const AnimatedPage = Animated.createAnimatedComponent(Page);
export const ModalPage = ({ children, page, qaLabel }: ModalPageProps) => {
const [{ activePage, nextPage, isAnimating }, dispatch] =
useModalPagesContext();
const viewTestProps = useQaLabel(qaLabel ?? "modalPage" + page);
const sideAnimation = useRef(
new Animated.Value(page === activePage ? 1 : 0)
).current;
const opacityAnimation = useRef(
new Animated.Value(page === activePage ? 1 : 0)
).current;
useEffect(() => {
// skip animation
if (
page === activePage ||
(nextPage && activePage && nextPage < activePage && page === nextPage)
) {
sideAnimation.setValue(1);
opacityAnimation.setValue(1);
}
// wait for animations to end until re-running
if (isAnimating || activePage === nextPage) return;
if (typeof page === "number" && page === nextPage) {
runChangePageAnimated("IN");
} else if (
typeof page === "number" &&
page === activePage &&
nextPage &&
page > nextPage
) {
runChangePageAnimated("OUT");
}
}, [activePage, nextPage, page]);
const runChangePageAnimated = useCallback((direction: AnimationDirection) => {
dispatch({ type: ACTIONS.START_ANIMATION });
const animatedConfig = {
toValue: direction === "IN" ? 1 : 0,
duration: 300,
useNativeDriver
};
Animated.parallel([
Animated.timing(sideAnimation, {
...animatedConfig,
easing: easeBackInOut?.overshoot(0.8)
}),
Animated.timing(opacityAnimation, animatedConfig)
]).start(() => {
dispatch({
type: ACTIONS.END_CHANGE_PAGE
});
});
}, []);
const handleLayoutChange = useCallback((event: LayoutChangeEvent) => {
dispatch({
type: ACTIONS.SET_STATE,
payload: {
pageHeight: event.nativeEvent.layout.height
}
});
}, []);
return page === activePage || page === nextPage ? (
<AnimatedPage
{...viewTestProps}
onLayout={handleLayoutChange}
style={{
opacity: opacityAnimation,
transform: [
{
translateX: sideAnimation.interpolate({
inputRange: [0, 1],
outputRange: [Dimensions.get("window").width / 2, 0]
})
}
]
}}
>
{children}
</AnimatedPage>
) : null;
};
export type { ModalPageProps };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/modal/components/pageContainer/styled-components.ts
import styled from "styled-components/native";
import { View } from "react-native";
import { PageHeight } from "../../context/types";
export const StyledView = styled(View)<PageHeight>`
background-color: ${(props) => props.theme.colors.white[900]};
width: 100%;
height: ${({ isFlexible, pageHeight }) => (isFlexible ? pageHeight : "100%")};
top: 0;
left: 0;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/modal/index.tsx
import React, {
useState,
useLayoutEffect,
useEffect,
useMemo,
isValidElement,
forwardRef,
useRef
} from "react";
import {
View,
Animated,
LayoutRectangle,
Platform,
NativeSyntheticEvent,
NativeScrollEvent,
ScrollView,
KeyboardAvoidingView,
StyleSheet,
LayoutChangeEvent
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { useQaLabel } from "../../hooks/useQaLabel";
import { useTvgConfContext } from "../../utils/tvgConfProvider";
import {
ModalProps,
ModalCloseType,
ModalType,
ModalCompoundComponent
} from "./types";
import { ModalHeader, PageHeader } from "../headers";
import {
StyledModal,
OverlayContainer,
ContentContainerFullscreen,
ContentContainerLightbox,
ContentInnerLightbox,
ContentContainerFlexible,
ContentInnerFlexible,
ContentContainerFullWidthPage,
ChildrenContainer,
TouchableContainer,
TouchableOverlayContainer,
StickyAreaContainer,
LIGHTBOX_MARGIN_SIDE,
INSET_VERTICAL,
INSET_BOTTOM,
TopStickyAreaContainer,
ContentContainerCustomHeight
} from "./styled-components";
import { getAccessibilityRole } from "../../utils/accessibility";
import { useWebKeyPress } from "../../hooks";
import { useModalAnimations } from "./hooks/useModalAnimations";
import { useScreenSize } from "./hooks/useScreenSize";
import { ModalPage, ModalPageContainer } from "./components";
import {
useModalPagesReducer,
ModalPagesContext
} from "./context/modalPagesContext";
import { Fading } from "../scrollViewFading/fading";
const AnimatedOverlayContainer =
Animated.createAnimatedComponent(OverlayContainer);
const AnimatedContentContainerFullscreen = Animated.createAnimatedComponent(
ContentContainerFullscreen
);
const AnimatedContentContainerCustomHeight = Animated.createAnimatedComponent(
ContentContainerCustomHeight
);
const AnimatedContentContainerLightbox = Animated.createAnimatedComponent(
ContentContainerLightbox
);
const AnimatedContentContainerFlexible = Animated.createAnimatedComponent(
ContentContainerFlexible
);
const AnimatedContentContainerFullWidth = Animated.createAnimatedComponent(
ContentContainerFullWidthPage
);
const isNative = Platform.OS !== "web";
const getPageHeight = ({
type,
height,
headerHeight = 0,
childrenHeight = 0,
modalHeight = 0
}: {
type: ModalType;
height: number;
headerHeight?: number;
childrenHeight?: number;
modalHeight?: number;
}) => {
switch (type) {
case "fullscreen":
return height - INSET_VERTICAL - headerHeight - LIGHTBOX_MARGIN_SIDE;
case "full-width-page":
return height - INSET_VERTICAL - headerHeight;
case "modal-custom-height":
return modalHeight;
default:
return childrenHeight;
}
};
export const modalTypesWithFade = ["full-width-page", "flexible", "fullscreen"];
const styles = StyleSheet.create({
keyboardView: {
flex: 1
}
});
export const Modal = forwardRef<View, ModalProps>(
(
{
type = "lightbox",
children,
isOpen: isOpenFromProps = true,
onOpen,
onClose,
onBack,
onOverlayClick,
onAfterClose,
onAfterOpen,
qaLabel = "modal-label",
topStickyArea,
stickyArea,
alwaysBounceVertical = true,
shouldCloseOnEsc = true,
maxWidth,
isDarkMode = false,
titlePosition = "center",
isTrackRulesModal = false,
maxHeight,
onScroll,
onRender,
hasBackgroundModal = false,
hasHeader = true,
topPosition,
hideBack,
...modalHeaderProps
},
ref
) => {
const [isModalOpen, setModalIsOpen] = useState(isOpenFromProps);
const [closeType, setCloseType] = useState<ModalCloseType>("none");
// handle open and close with animations per type
const {
isAnimating,
isClosing,
setIsClosing,
contentOpacityAnimation,
overlayOpacityAnimation,
lightboxContentAnimation,
lightboxScaleAnimation,
flexibleContentAnimation,
fullscreenContentAnimation,
fullWidthPageContentAnimation
} = useModalAnimations({
isModalOpen,
setModalIsOpen,
onClose,
closeType,
setCloseType,
onBack,
onOverlayClick,
type,
onAfterClose
});
useEffect(() => {
if (
typeof onAfterOpen === "function" &&
!isAnimating &&
isOpenFromProps &&
isModalOpen
) {
onAfterOpen();
}
}, [isAnimating]);
const { height, width } = useScreenSize();
const [childrenLayout, setChildrenLayout] = useState<
Partial<LayoutRectangle>
>({});
const [headerLayout, setHeaderLayout] = useState<Partial<LayoutRectangle>>(
{}
);
const [stickyAreaLayout, setStickyAreaLayout] = useState<
Partial<LayoutRectangle>
>({});
const [customModalLayout, setCustomModalLayout] = useState<
Partial<LayoutRectangle>
>({});
const [topStickyAreaLayout, setTopStickyAreaLayout] = useState<
Partial<LayoutRectangle>
>({});
const [isScrolling, setIsScrolling] = useState(false);
const { device } = useTvgConfContext();
const isMobile = device === "mobile";
const isEscPressed = useWebKeyPress("Escape");
const viewTestProps = useQaLabel(qaLabel);
const modalViewTestProps = useQaLabel(`${qaLabel}-safe-area`);
const overlayTestProps = useQaLabel("overlay");
const stickyAreaTestProps = useQaLabel("sticky-area");
const topStickyAreaTestProps = useQaLabel("sticky-area");
const [state, dispatch] = useModalPagesReducer({
isFlexible: type === "flexible" || type === "lightbox"
});
const scrollRef = useRef<ScrollView | null>(null);
const hasPages = useMemo(
() =>
isValidElement(children) &&
(children as JSX.Element)?.type.name === "ModalPageContainer",
[children, type]
);
// set initial render before animation
useLayoutEffect(
() => () => {
setModalIsOpen(false);
},
[]
);
useEffect(() => {
if (onRender) {
onRender({ scrollRef });
}
}, [scrollRef.current]);
// close on escape press
useEffect(() => {
if (shouldCloseOnEsc && isModalOpen && !isClosing && isEscPressed) {
setIsClosing(true);
onClose?.();
}
}, [isEscPressed]);
// Prevents background from scrolling while modal is opened
useEffect(() => {
if (!isNative && isModalOpen) {
document.body.style.overflow = "hidden";
}
return () => {
if (!isNative && !hasBackgroundModal) {
document.body.style.overflow = "initial";
}
};
}, [isModalOpen]);
// handle initial open/close animation from isOpen prop
useEffect(() => {
if (isOpenFromProps) {
// open up modal with animation
setModalIsOpen(true);
// if open is false from props but the state is open, begin closing animation
} else if (isModalOpen) {
setIsClosing(true);
}
if (isOpenFromProps && typeof onOpen === "function") {
onOpen();
}
}, [isOpenFromProps]);
// set is scrolling for header shadow
const handleOnScroll = (e: NativeSyntheticEvent<NativeScrollEvent>) => {
const {
contentOffset: { y }
} = e.nativeEvent;
setIsScrolling(y > 0);
if (typeof onScroll === "function") {
onScroll({
ref: scrollRef.current,
event: e
});
}
};
// scroll to top on page change
useEffect(() => {
if (hasPages && state.nextPage === state.activePage) {
scrollRef.current?.scrollTo({ y: 0, animated: true });
}
}, [hasPages, state.nextPage, state.activePage]);
// height of header and children
const childrenHeight =
typeof childrenLayout?.height === "number"
? childrenLayout.height + 1
: undefined;
const stickyAreaLayoutHeight =
React.isValidElement(stickyArea) &&
typeof stickyAreaLayout?.height === "number"
? stickyAreaLayout.height
: 0;
const topStickyAreaLayoutHeight =
React.isValidElement(topStickyArea) &&
typeof topStickyAreaLayout?.height === "number"
? topStickyAreaLayout.height
: 0;
const childrenWithStickyHeight = childrenHeight
? stickyAreaLayoutHeight + topStickyAreaLayoutHeight + childrenHeight
: childrenHeight;
const contentHeight =
typeof headerLayout?.height === "number" &&
typeof childrenWithStickyHeight === "number"
? headerLayout.height + childrenWithStickyHeight
: undefined;
const pageHeight = useMemo(
() =>
getPageHeight({
type,
height,
headerHeight: headerLayout?.height,
childrenHeight: childrenWithStickyHeight,
modalHeight: customModalLayout?.height
}),
[childrenWithStickyHeight, height, headerLayout, customModalLayout]
);
const renderOverlay = () => (
<TouchableOverlayContainer
onPress={() => {
if (!isAnimating) {
setIsClosing(true);
setCloseType("onOverlayClick");
onClose?.();
}
}}
>
<TouchableContainer
style={{
height,
width
}}
{...overlayTestProps}
/>
</TouchableOverlayContainer>
);
const showBack =
(typeof onBack === "function" ||
(state.activePage && state.activePage > 1)) &&
!hideBack;
const handleOnClose = () => {
setCloseType("onClose");
setIsClosing(true);
};
const renderContent = () => (
<>
<View
onLayout={(event) => setHeaderLayout(event?.nativeEvent?.layout)}
ref={ref}
>
{
// render header depending on type
type === "full-width-page" ? (
<PageHeader
{...modalHeaderProps}
{...(showBack
? {
onBack: () => {
setCloseType("onBack");
setIsClosing(true);
}
}
: {})}
hasShadow={isScrolling}
qaLabel="pageHeader"
titlePosition={titlePosition}
isTrackRulesModal={isTrackRulesModal}
/>
) : (
hasHeader && (
<ModalHeader
{...modalHeaderProps}
onClose={handleOnClose}
{...(showBack
? {
onBack: () => {
setCloseType("onBack");
setIsClosing(false);
if (onBack) onBack();
}
}
: {})}
hasRoundedCorners
hasShadow={isScrolling}
isDarkMode={isDarkMode}
qaLabel="modalHeader"
titlePosition={titlePosition}
isTrackRulesModal={isTrackRulesModal}
/>
)
)
}
</View>
{React.isValidElement(topStickyArea) && (
<TopStickyAreaContainer
isScrolling={isScrolling}
type={type}
onLayout={(event) =>
setTopStickyAreaLayout(event?.nativeEvent?.layout)
}
{...topStickyAreaTestProps}
>
{topStickyArea}
</TopStickyAreaContainer>
)}
<ScrollView
onScroll={handleOnScroll}
scrollEventThrottle={500}
alwaysBounceVertical={alwaysBounceVertical}
ref={scrollRef}
>
<ChildrenContainer
hasPages={hasPages}
pageHeight={pageHeight}
isMobile={isMobile}
type={type}
isDarkMode={isDarkMode}
onLayout={(event) => setChildrenLayout(event?.nativeEvent?.layout)}
{...modalHeaderProps}
>
<ModalPagesContext.Provider value={[state, dispatch]}>
{children}
</ModalPagesContext.Provider>
</ChildrenContainer>
</ScrollView>
{modalTypesWithFade.includes(type) && isMobile && hasHeader && (
<Fading
position="bottom"
height="10px"
width="100%"
viewBox="0 0 10 45"
preserveAspectRatio="none"
isVisible
gradientPosition={{
x1: 24,
y1: 44,
x2: 24,
y2: 0
}}
qaLabel="fading-effect"
/>
)}
{React.isValidElement(stickyArea) && (
<StickyAreaContainer
isMobile={isMobile}
type={type}
onLayout={(event) =>
setStickyAreaLayout(event?.nativeEvent?.layout)
}
{...stickyAreaTestProps}
>
{stickyArea}
</StickyAreaContainer>
)}
</>
);
// render container dependending on modal type
const renderContainer = () => {
switch (type) {
case "fullscreen": {
return (
<AnimatedContentContainerFullscreen
topPosition={topPosition}
style={{
height: hasHeader ? height - LIGHTBOX_MARGIN_SIDE : height,
opacity: contentOpacityAnimation,
transform: [
{
translateY: fullscreenContentAnimation.interpolate({
inputRange: [0, 1],
outputRange: ["100%", "0%"]
})
}
]
}}
>
{renderOverlay()}
<KeyboardAvoidingView
behavior="height"
keyboardVerticalOffset={INSET_VERTICAL}
style={styles.keyboardView}
{...viewTestProps}
>
{renderContent()}
</KeyboardAvoidingView>
</AnimatedContentContainerFullscreen>
);
}
case "modal-custom-height": {
return (
<AnimatedContentContainerCustomHeight
style={{
height: height - LIGHTBOX_MARGIN_SIDE,
transform: [
{
translateY: fullscreenContentAnimation.interpolate({
inputRange: [0, 1],
outputRange: ["100%", "0%"]
})
}
]
}}
maxHeight={maxHeight}
onLayout={(event: LayoutChangeEvent) =>
setCustomModalLayout(event?.nativeEvent?.layout)
}
>
{renderOverlay()}
<KeyboardAvoidingView
behavior="height"
keyboardVerticalOffset={INSET_VERTICAL}
style={styles.keyboardView}
{...viewTestProps}
>
{renderContent()}
</KeyboardAvoidingView>
</AnimatedContentContainerCustomHeight>
);
}
case "lightbox": {
return (
<AnimatedContentContainerLightbox
width={width}
height={height}
contentHeight={contentHeight || 0}
isNative={isNative}
style={{
opacity: contentOpacityAnimation,
transform: [
{
translateY: lightboxContentAnimation.interpolate({
inputRange: [0, 1],
outputRange: [50, 0]
})
},
{
scale: lightboxScaleAnimation.interpolate({
inputRange: [0.5, 1],
outputRange: [0.5, 1]
})
}
]
}}
>
{renderOverlay()}
<ContentInnerLightbox
height={height}
contentHeight={contentHeight}
isNative={isNative}
isMobile={isMobile}
maxWidth={maxWidth}
>
<KeyboardAvoidingView
behavior="height"
keyboardVerticalOffset={INSET_VERTICAL}
style={styles.keyboardView}
{...viewTestProps}
>
{renderContent()}
</KeyboardAvoidingView>
</ContentInnerLightbox>
</AnimatedContentContainerLightbox>
);
}
case "flexible": {
return (
<KeyboardAvoidingView
behavior="height"
keyboardVerticalOffset={-INSET_BOTTOM}
style={styles.keyboardView}
>
<AnimatedContentContainerFlexible
contentHeight={contentHeight || 0}
height={height}
style={{
opacity: contentOpacityAnimation,
transform: [
{
translateY: flexibleContentAnimation.interpolate({
inputRange: [0, 1],
outputRange: ["100%", "0%"]
})
}
]
}}
>
{renderOverlay()}
<ContentInnerFlexible {...viewTestProps}>
{renderContent()}
</ContentInnerFlexible>
</AnimatedContentContainerFlexible>
</KeyboardAvoidingView>
);
}
case "full-width-page": {
return (
<KeyboardAvoidingView
behavior="height"
keyboardVerticalOffset={-INSET_BOTTOM}
style={styles.keyboardView}
>
<AnimatedContentContainerFullWidth
style={{
opacity: contentOpacityAnimation,
transform: [
{
translateX: fullWidthPageContentAnimation.interpolate({
inputRange: [0, 1],
outputRange: ["100%", "0%"]
})
}
]
}}
{...viewTestProps}
>
{renderContent()}
</AnimatedContentContainerFullWidth>
</KeyboardAvoidingView>
);
}
default:
}
return null;
};
return (
<StyledModal
visible={isModalOpen}
onDismiss={() => {
if (isModalOpen && !isClosing) {
setIsClosing(true);
}
}}
presentationStyle="overFullScreen"
animationType="none"
transparent
// accessibility props
accessibilityRole={getAccessibilityRole("dialog")}
{...(!isNative
? {
"aria-modal": true
}
: {})}
{...viewTestProps}
>
<AnimatedOverlayContainer
type={type}
style={
type !== "modal-custom-height"
? {
opacity: overlayOpacityAnimation
}
: undefined
}
/>
<SafeAreaView>
<View
style={{
height,
width
}}
{...modalViewTestProps}
>
{renderOverlay()}
{renderContainer()}
</View>
</SafeAreaView>
</StyledModal>
);
}
) as ModalCompoundComponent<typeof ModalPageContainer, typeof ModalPage>;
Modal.PageGroup = ModalPageContainer;
Modal.Page = ModalPage;
export default Modal;
export type { ModalProps, ModalType };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/modal/hooks/useScreenSize.ts
import { useEffect, useState } from "react";
import { useWindowDimensions, Platform } from "react-native";
interface ScreenInfo {
width: number;
height: number;
}
export const useScreenSize = (): ScreenInfo => {
const [screenInfo, setScreenInfo] = useState<ScreenInfo>(
useWindowDimensions()
);
useEffect(() => {
const isNative = Platform.OS !== "web";
if (!isNative && typeof window !== undefined) {
setScreenInfo({ height: window.innerHeight, width: window.innerWidth });
}
}, []);
return screenInfo;
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/modal/components/pageContainer/index.tsx
import React, { useEffect } from "react";
import { useQaLabel } from "../../../../hooks/useQaLabel";
import { useFirstRender } from "../../hooks/useFirstRender";
import { ModalPageContainerProps } from "./types";
import { StyledView } from "./styled-components";
import { useModalPagesContext } from "../../context/modalPagesContext";
export const ModalPageContainer = ({
children,
page: pageFromProps
}: ModalPageContainerProps) => {
const isFirstRender = useFirstRender();
const [
{ totalPages, activePage, nextPage, pageHeight, isFlexible },
dispatch
] = useModalPagesContext();
const viewTestProps = useQaLabel("modalContainer");
const renderPages = () =>
children.map((pageElement, index) =>
// eslint-disable-next-line react/no-array-index-key
React.cloneElement(pageElement, { page: index + 1, key: index + 1 })
);
useEffect(() => {
dispatch({
type: "INIT",
payload: {
totalPages: React.Children.count(children)
}
});
}, [children]);
useEffect(() => {
dispatch({
type: "SET_STATE",
payload: {
// set page without animation
activePage:
isFirstRender && pageFromProps ? pageFromProps : activePage || 1,
isFirstRender
}
});
// handle animations
if (
pageFromProps &&
totalPages &&
pageFromProps <= totalPages &&
(pageFromProps !== activePage || pageFromProps !== nextPage)
) {
dispatch({
type: "START_CHANGE_PAGE",
payload: {
nextPage: pageFromProps
}
});
}
}, [pageFromProps, isFirstRender, totalPages]);
return (
<StyledView
{...viewTestProps}
pageHeight={pageHeight}
isFlexible={isFlexible}
>
{renderPages()}
</StyledView>
);
};
export { ModalPageContainerProps };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/modal/hooks/useFirstRender.tsx
import { useRef, useEffect } from "react";
export const useFirstRender = () => {
const firstRender = useRef(true);
useEffect(() => {
firstRender.current = false;
}, []);
return firstRender.current;
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/mtp/styled-components.ts
import styled, { css } from "styled-components/native";
import { Text } from "react-native";
import {
space,
compose,
typography,
system,
color
} from "../../theming/styledSystem";
import { MtpProps } from "./types";
const transformText = system({
whiteSpace: {
property: "whiteSpace"
}
});
const styledComponentUtils = compose(space, color, typography, transformText);
const baseTextStyle = css<Pick<MtpProps, "isCollapsed">>`
font-size: ${({ theme, isCollapsed }) =>
theme.fontSizes[isCollapsed ? "s" : "3xl"]};
line-height: ${({ theme, isCollapsed }) =>
theme.lineHeights[isCollapsed ? "s" : "3xl"]};
${typography};
`;
export const RaceOff = styled(Text)<
Pick<MtpProps, "isCollapsed" | "hasFullText">
>`
color: ${({ theme }) => theme.colorTokens.lhnHeader.content.positive};
font-weight: ${({ theme, isCollapsed, hasFullText }) =>
theme.fontWeights[isCollapsed && !hasFullText ? "normal" : "bold"]};
${baseTextStyle};
${styledComponentUtils};
`;
export const Resulted = styled(Text)<
Pick<MtpProps, "isCollapsed" | "hasFullText"> & { defaultColor: string }
>`
color: ${({ defaultColor }) => defaultColor};
font-weight: ${({ theme, isCollapsed, hasFullText }) =>
theme.fontWeights[isCollapsed && !hasFullText ? "normal" : "bold"]};
${baseTextStyle};
${styledComponentUtils};
`;
export const RaceTime = styled(Text)<
Pick<MtpProps, "isCollapsed" | "hasFullText"> & { defaultColor: string }
>`
color: ${({ defaultColor }) => defaultColor};
${({ theme, isCollapsed, hasFullText }) => {
if (isCollapsed) {
return css`
${!hasFullText &&
css`
width: min-content;
text-align: center;
`};
font-size: ${theme.fontSizes.s};
`;
}
return css`
font-size: ${theme.fontSizes["3xl"]};
`;
}}
font-weight: ${({ theme, hasFullText }) =>
hasFullText ? theme.fontWeights.bold : theme.fontWeights.normal};
line-height: ${({ theme, isCollapsed }) =>
theme.lineHeights[isCollapsed ? "s" : "3xl"]};
${styledComponentUtils};
`;
export const MinutesText = styled(Text)<
Pick<MtpProps, "mtp" | "isCollapsed"> & { defaultColor: string }
>`
color: ${({ theme, mtp, defaultColor }) =>
mtp > 5 ? defaultColor : theme.colorTokens.lhnHeader.content.negative};
font-weight: ${({ theme }) => theme.fontWeights.bold};
${baseTextStyle};
${styledComponentUtils};
`;
export const TextDescription = styled(Text)<
Pick<MtpProps, "mtp"> & { defaultColor: string }
>`
color: ${({ theme, mtp, defaultColor }) =>
mtp > 5 ? defaultColor : theme.colorTokens.lhnHeader.content.negative};
font-family: ${({ theme }) => theme.fonts.condensedRegular};
font-size: ${({ theme }) => theme.fontSizes.m};
line-height: 16px;
margin-bottom: 5px;
text-transform: uppercase;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/mtpCell/styled-components.ts
import styled, { css } from "styled-components/native";
import { margin } from "styled-system";
import { View } from "react-native";
import { MtpCellProps } from "./types";
export const Container = styled(View)<
Pick<MtpCellProps, "withBackground" | "align"> & {
bgColor: string;
lineColor: string;
}
>`
background-color: ${({ withBackground, bgColor }) =>
withBackground ? bgColor : "transparent"};
border-style: solid;
border-top-left-radius: 4px;
display: flex;
flex-direction: column;
height: 60px;
max-width: 102px;
width: max-content;
padding: 10px 11px 10px 12px;
${({ align, lineColor, withBackground }) =>
align === "left"
? css`
border-right-color: ${lineColor};
border-right-width: ${withBackground ? "1px" : 0};
`
: css`
border-left-color: ${lineColor};
border-left-width: ${withBackground ? "1px" : 0};
`};
${margin}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/mtpPro/styled-components.ts
import styled, { css } from "styled-components/native";
import { Text } from "react-native";
import { space, compose } from "../../theming/styledSystem";
import { MtpProps } from "./types";
const styledComponentUtils = compose(space);
const baseTextStyle = css<Pick<MtpProps, "isCollapsed">>`
font-size: ${({ theme, isCollapsed }) =>
theme.fontSizes[isCollapsed ? "s" : "2xl"]};
line-height: ${({ theme, isCollapsed }) =>
theme.lineHeights[isCollapsed ? "l" : "2xl"]};
`;
export const RaceOff = styled(Text)<
Pick<MtpProps, "isCollapsed" | "hasFullText">
>`
display: flex;
align-items: center;
color: ${({ theme }) => theme.colorTokens.lhnHeader.content.positive};
font-weight: ${({ theme, isCollapsed, hasFullText }) =>
theme.fontWeights[isCollapsed && !hasFullText ? "normal" : "bold"]};
${baseTextStyle};
${styledComponentUtils};
`;
export const Resulted = styled(Text)<
Pick<MtpProps, "isCollapsed" | "hasFullText">
>`
display: flex;
align-items: center;
color: ${({ theme }) => theme.colorTokens.lhnHeader.content.brandSecondary};
font-weight: ${({ theme, isCollapsed, hasFullText }) =>
theme.fontWeights[isCollapsed && !hasFullText ? "normal" : "bold"]};
${baseTextStyle};
${styledComponentUtils};
`;
export const RaceTime = styled(Text)<
Pick<MtpProps, "isCollapsed" | "hasFullText">
>`
display: flex;
align-items: center;
color: ${({ theme }) => theme.colorTokens.lhnHeader.content.brandSecondary};
${({ theme, isCollapsed, hasFullText }) => {
if (isCollapsed) {
return css`
${!hasFullText &&
css`
width: min-content;
text-align: center;
`};
font-size: ${theme.fontSizes.s};
`;
}
return css`
font-size: ${theme.fontSizes["2xl"]};
`;
}}
font-weight: ${({ theme, hasFullText }) =>
hasFullText ? theme.fontWeights.bold : theme.fontWeights.normal};
line-height: ${({ theme, isCollapsed }) =>
theme.lineHeights[isCollapsed ? "s" : "2xl"]};
${styledComponentUtils};
`;
export const MinutesText = styled(Text)<Pick<MtpProps, "mtp" | "isCollapsed">>`
display: flex;
align-items: center;
color: ${({ theme, mtp }) =>
mtp > 5
? theme.colorTokens.lhnHeader.content.brandSecondary
: theme.colorTokens.lhnHeader.content.negative};
font-weight: ${({ theme }) => theme.fontWeights.bold};
${baseTextStyle};
${styledComponentUtils};
font-size: ${({ theme }) => theme.fontSizes["4xl"]};
`;
export const TextDescription = styled(Text)<Pick<MtpProps, "mtp">>`
display: block;
color: ${({ theme, mtp }) =>
mtp > 5
? theme.colorTokens.lhnHeader.content.brandSecondary
: theme.colorTokens.lhnHeader.content.negative};
font-family: ${({ theme }) => theme.fonts.condensedRegular};
font-size: 14px;
text-transform: uppercase;
margin-bottom: 0;
line-height: 125%;
width: 65px;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/pebble/pebbleGroup/styled-components.ts
import styled from "styled-components/native";
import { margin } from "styled-system";
export const StyledViewContainer = styled.View`
${margin}
flex-direction: row;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/pebble/pebbleGroup/index.tsx
import React, { createContext, forwardRef } from "react";
import { View } from "react-native";
import { useQaLabel } from "../../../hooks/useQaLabel";
import { PebbleGroupProps, PebbleGroupContextProps } from "./types";
import { StyledViewContainer } from "./styled-components";
const initialState = { selectedValue: "", onChange: () => {} };
export const GroupContext =
createContext<PebbleGroupContextProps>(initialState);
export const PebbleGroup = forwardRef<View, PebbleGroupProps>(
({ children, selectedValue, onChange, qaLabel, ...rest }, ref) => {
const viewTestProps = useQaLabel(qaLabel);
return (
// @ts-ignore
<StyledViewContainer ref={ref} {...rest} {...viewTestProps}>
<GroupContext.Provider value={{ selectedValue, onChange }}>
{children}
</GroupContext.Provider>
</StyledViewContainer>
);
}
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/pebble/styled-components.ts
import styled from "styled-components/native";
import { margin, compose, variant } from "styled-system";
import { rgba } from "polished";
import { TouchableHighlight, View, Text } from "react-native";
import { RefAttributes } from "react";
import { Icon } from "../icon";
import {
StatesProps,
TransientStatesProps,
StyledStatesProps,
Theme
} from "./types";
export const colorStates = {
prop: "state",
variants: {
normal: {
backgroundColor: "blue_accent.000",
color: "grey.800",
borderColor: "blue.100"
},
hovered: {
backgroundColor: "blue_accent.100",
color: "blue_accent.600",
borderColor: "blue_accent.500"
},
pressed: {
backgroundColor: "blue_accent.200",
color: "blue_accent.600",
borderColor: "blue_accent.500",
boxShadow: "none"
}
}
};
export const stylesColorStates = compose(variant(colorStates));
const getState = (
isHovered: boolean,
isPressed: boolean,
isSelected: boolean
) => {
if (isPressed) return "pressed";
if (isHovered || isSelected) return "hovered";
return "normal";
};
const getColorIconCircle = (
isHovered: boolean,
isPressed: boolean,
isSelected: boolean,
theme: Theme
) => {
if (isPressed) return theme?.colors.blue_accent[300];
if (isHovered || isSelected) return theme?.colors.blue_accent[200];
return theme?.colors.blue_accent[100];
};
const getColorIconLine = (
isHovered: boolean,
isPressed: boolean,
isSelected: boolean,
theme: Theme
) => {
if (isPressed) return theme?.colors.blue_accent[600];
if (isHovered || isSelected) return theme?.colors.blue_accent[600];
return theme?.colors.blue[400];
};
export const StyledViewTagContainer = styled(View)`
position: absolute;
top: -9px;
right: -9px;
`;
export const StyledTouchableHighlight = styled(
TouchableHighlight
).attrs<StatesProps>(({ isHovered, isPressed, isSelected }) => ({
state: getState(isHovered, isPressed, isSelected)
}))<StyledStatesProps & RefAttributes<typeof TouchableHighlight>>`
${margin}
`;
export const StyledViewContainer = styled(View).attrs<StatesProps>(
({ isHovered, isPressed, isSelected }) => ({
state: getState(isHovered, isPressed, isSelected)
})
)<StyledStatesProps>`
${margin};
border-width: 1px;
${({ theme, isHovered, isSelected }) =>
(isHovered || isSelected
? "box-shadow: 0 2px 4px "
: "box-shadow: 0 1px 3px ") +
rgba(theme.colors.blue[900], isHovered || isSelected ? 0.18 : 0.12)};
width: 104px;
border-radius: ${({ theme }) => theme.radii.s};
padding: ${({ theme }) => theme.space["space-4"]};
align-items: center;
${stylesColorStates}
`;
export const StyledViewIconCircle = styled(View)<StatesProps>`
background-color: ${({ theme, isHovered, isPressed, isSelected }) =>
getColorIconCircle(isHovered, isPressed, isSelected, theme)};
width: 40px;
height: 40px;
border-radius: 99px;
align-items: center;
justify-content: center;
margin-bottom: ${({ theme }) => theme.space["space-4"]};
`;
// transient props here avoid error on svg because the camel case prop names
// https://styled-components.com/docs/api (Styled System 5.1)
export const StyledIcon = styled(Icon).attrs<TransientStatesProps>(
({ theme, $isHovered, $isPressed, $isSelected }) => ({
lineColor: getColorIconLine($isHovered, $isPressed, $isSelected, theme),
backgroundColor: "transparent"
})
)<TransientStatesProps>``;
export const StyledTextTitle = styled(Text).attrs<StatesProps>(
({ isHovered, isPressed, isSelected }) => ({
state: getState(isHovered, isPressed, isSelected)
})
)`
font-family: ${({ theme }) => theme.fonts.medium};
font-size: ${({ theme }) => theme.fontSizes.s};
margin-bottom: ${({ theme }) => theme.space["space-2"]};
${stylesColorStates}
`;
export const StyledTextDescription = styled(Text).attrs<StatesProps>(
({ isHovered, isPressed, isSelected }) => ({
state: getState(isHovered, isPressed, isSelected)
})
)<StatesProps>`
font-family: ${({ theme }) => theme.fonts.regular};
font-size: ${({ theme }) => theme.fontSizes.s};
color: ${({ theme }) => theme.colors.grey[800]};
${stylesColorStates}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/pebble/index.tsx
import React, { useContext, useEffect, forwardRef } from "react";
import { TouchableHighlight } from "react-native";
import { useQaLabel } from "../../hooks/useQaLabel";
import { type PebbleProps, PebbleCompoundComponent } from "./types";
import { Tag } from "../tag";
import { PebbleGroup, GroupContext } from "./pebbleGroup";
import { useEvents } from "../../hooks/useEvents";
import {
StyledViewTagContainer,
StyledTouchableHighlight,
StyledViewContainer,
StyledViewIconCircle,
StyledIcon,
StyledTextTitle,
StyledTextDescription
} from "./styled-components";
export const Pebble = forwardRef<typeof TouchableHighlight, PebbleProps>(
(
{
iconName,
title,
description,
tag,
isSelected = false,
qaLabel,
value,
...rest
},
ref
) => {
const viewTestProps = useQaLabel(qaLabel);
const { events, setEvents, eventsHandlers } = useEvents({});
const { selectedValue, onChange = () => {} } = useContext(GroupContext);
useEffect(() => {
setEvents({ ...events, isSelected });
}, [isSelected]);
useEffect(() => {
setEvents({
...events,
isSelected: isSelected || selectedValue === value
});
}, [selectedValue]);
const pressHandler = () => {
onChange(value);
};
const RenderTag = () => (
<StyledViewTagContainer {...events}>
{typeof tag === "string" ? (
<Tag label={tag} variant="promo" size="s" />
) : (
tag
)}
</StyledViewTagContainer>
);
return (
<StyledTouchableHighlight
// @ts-ignore
ref={ref}
{...rest}
{...viewTestProps}
{...eventsHandlers}
{...events}
onPress={pressHandler}
accessibilityRole="button"
underlayColor="none"
onLongPress={pressHandler}
>
<StyledViewContainer {...events}>
{!!tag && <RenderTag />}
<StyledViewIconCircle {...events}>
<StyledIcon
name={iconName}
size="m"
$isHovered={events.isHovered}
$isPressed={events.isPressed}
$isSelected={events.isSelected}
/>
</StyledViewIconCircle>
<StyledTextTitle {...events}>{title}</StyledTextTitle>
{description && (
<StyledTextDescription {...events}>
{description}
</StyledTextDescription>
)}
</StyledViewContainer>
</StyledTouchableHighlight>
);
}
) as PebbleCompoundComponent<typeof PebbleGroup>;
export type { PebbleProps };
Pebble.Group = PebbleGroup;
export default Pebble;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/popper/context/popperReducer.ts
import { State, ReducerActions, ReducerActionTypes } from "../types";
export const INITIAL_STATE: State = {
isOpen: false,
triggerLayout: {
x: 0,
y: 0,
width: 0,
height: 0
}
};
export const ACTIONS: ReducerActionTypes = {
OPEN_POPPER: "OPEN_POPPER",
CLOSE_POPPER: "CLOSE_POPPER"
};
const popperReducer = (
state: State = INITIAL_STATE,
action: ReducerActions
) => {
switch (action.type) {
case ACTIONS.OPEN_POPPER:
return {
...state,
isOpen: true,
triggerLayout: action.payload
};
case ACTIONS.CLOSE_POPPER:
return {
...state,
isOpen: false
};
default:
return state;
}
};
export default popperReducer;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/popper/context/popperProvider.tsx
import React, {
createContext,
useContext,
useReducer,
useMemo,
FC
} from "react";
import { Context } from "../types";
import popperReducer, { INITIAL_STATE } from "./popperReducer";
const PopperContext = createContext<Context>([INITIAL_STATE, () => {}]);
const PopperProvider: FC = ({ children }) => {
const [state, dispatch] = useReducer(popperReducer, INITIAL_STATE);
const context: Context = useMemo(() => [state, dispatch], [state, dispatch]);
return (
<PopperContext.Provider value={context}>{children}</PopperContext.Provider>
);
};
export const usePopperContext = () => useContext(PopperContext);
export default PopperProvider;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/popper/hooks/usePopper.ts
import { useCallback, useMemo, useEffect } from "react";
import { Platform } from "react-native";
import { usePopperContext } from "../context/popperProvider";
import { ACTIONS } from "../context/popperReducer";
import { EventTypes, Layout } from "../types";
const isWeb = Platform.OS === "web";
const usePopper = () => {
const [state, dispatch] = usePopperContext();
useEffect(() => {
if (Platform.OS === "web" && typeof window !== "undefined") {
window.addEventListener("scroll", closeContent);
}
return () => {
if (Platform.OS === "web" && typeof window !== "undefined") {
window.removeEventListener("scroll", closeContent);
}
};
}, []);
const openContent = useCallback(
(triggerLayout: Layout) => {
dispatch({ type: ACTIONS.OPEN_POPPER, payload: triggerLayout });
},
[dispatch]
);
const closeContent = useCallback(() => {
dispatch({ type: ACTIONS.CLOSE_POPPER });
}, [dispatch]);
const getHandlers = useCallback(
(
on: EventTypes = "press",
callback: (fn: (layout: Layout) => void) => void
) => {
const openCallback = () => callback(openContent);
if (on === "hover" && !isWeb) return null;
if (on === "hover" && isWeb) {
return {
onMouseEnter: openCallback,
onMouseLeave: closeContent,
onFocus: openCallback,
onBlur: closeContent
};
}
return { onPress: state.isOpen ? closeContent : openCallback };
},
[state.isOpen]
);
return useMemo(
() => ({
isWeb,
isOpen: state.isOpen,
triggerLayout: state.triggerLayout,
openContent,
closeContent,
getHandlers
}),
[isWeb, state.isOpen, openContent, closeContent, getHandlers]
);
};
export default usePopper;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/popper/hooks/useCloseOnClickOutside.ts
/* TODO: move to a global hooks folder */
import { useEffect, RefObject } from "react";
import { View } from "react-native";
export interface CloseOnClickOutside {
isWeb: boolean;
refs: RefObject<View>[];
onPress: () => void;
}
const isTouchDevice =
typeof window !== "undefined" &&
typeof navigator !== "undefined" &&
("ontouchstart" in window || navigator.maxTouchPoints > 0);
const useCloseOnClickOutside = ({
isWeb,
refs,
onPress
}: CloseOnClickOutside) => {
useEffect(() => {
const listener = (e: MouseEvent | TouchEvent) => {
let clickedInRefs = false;
if (refs) {
refs.forEach((ref) => {
if (
ref &&
ref.current &&
ref.current instanceof HTMLElement &&
ref.current.contains(e.target as HTMLElement)
) {
clickedInRefs = true;
}
});
}
if (!clickedInRefs) onPress();
};
const eventName = isTouchDevice ? "touchstart" : "click";
if (isWeb) {
document.addEventListener(eventName, listener);
}
return () => {
if (isWeb) {
document.removeEventListener(eventName, listener);
}
};
}, []);
};
export default useCloseOnClickOutside;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/popper/hooks/useGetCoordinates.ts
import { Dispatch, SetStateAction, useEffect, useState } from "react";
import { useDebounce } from "../../../hooks";
import { Layout, Placement } from "../types";
export interface GetCoordinates {
triggerLayout: Layout;
placement: Placement;
windowWidth: number;
windowHeight: number;
}
interface Coordinates {
top: number;
left?: number;
right?: number;
}
const DEFAULT_COORDINATES: Coordinates = {
left: 0,
top: 0
};
const useGetCoordinates = ({
triggerLayout,
placement,
windowWidth,
windowHeight
}: GetCoordinates) => {
const {
x: triggerX = 0,
y: triggerY = 0,
width: triggerWidth,
height: triggerHeight
} = triggerLayout;
const [coordinates, setCoordinates]: [
Coordinates,
Dispatch<SetStateAction<Coordinates>>
] = useState(DEFAULT_COORDINATES);
const [isReady, setIsReady]: [boolean, Dispatch<SetStateAction<boolean>>] =
useState(false as boolean);
const debounce = useDebounce();
const getHorizontalCoordinates = (contentWidth: number) => {
if (triggerWidth >= contentWidth) {
return triggerX + (triggerWidth - contentWidth) / 2;
}
return triggerX - contentWidth / 2 + triggerWidth / 2;
};
const getVerticalCoordinates = (contentHeight: number) => {
if (triggerHeight >= contentHeight) {
return triggerY + (triggerHeight - contentHeight) / 2;
}
return triggerY - contentHeight / 2 + triggerHeight / 2;
};
const updateCoordinates = (contentWidth: number, contentHeight: number) => {
const newCoordinates: Coordinates = { top: triggerY };
// Calculates the initial position based on placement
switch (placement) {
case "top-left":
newCoordinates.top -= contentHeight;
newCoordinates.left = triggerX;
break;
case "top-mid":
newCoordinates.top -= contentHeight;
newCoordinates.left = getHorizontalCoordinates(contentWidth);
break;
case "top-right":
newCoordinates.top -= contentHeight;
newCoordinates.left = triggerX + triggerWidth - contentWidth;
break;
case "left":
newCoordinates.top = getVerticalCoordinates(contentHeight);
newCoordinates.left = triggerX - contentWidth;
break;
case "right":
newCoordinates.top = getVerticalCoordinates(contentHeight);
newCoordinates.left = triggerX + triggerWidth;
break;
case "bottom-left":
newCoordinates.top += triggerHeight;
newCoordinates.left = triggerX;
break;
case "bottom-mid":
newCoordinates.top += triggerHeight;
newCoordinates.left = getHorizontalCoordinates(contentWidth);
break;
case "bottom-right":
newCoordinates.top += triggerHeight;
newCoordinates.left = triggerX + triggerWidth - contentWidth;
break;
case "drop-down":
newCoordinates.top += triggerHeight;
newCoordinates.left = triggerX;
break;
default:
break;
}
// It verifies if the tooltip is going out of viewport
// Adjusts the min margin to the left to avoid leaking on the left side
if (newCoordinates.left && newCoordinates.left < 0) {
newCoordinates.left = 10; // minimum margin on the left
}
// adjusts to not allow going further viewport width (cannot go out on the right side)
if (
newCoordinates.left &&
newCoordinates.left + contentWidth > windowWidth
) {
newCoordinates.left = windowWidth - contentWidth - 10; // minimum margin on the right
}
// Adjusts the min margin to the top to avoid leaking on the top
if (newCoordinates.top < 0) {
newCoordinates.top = 10; // minimum margin on the top
}
// adjusts to not allow going further viewport height (cannot go out on the bottom)
if (newCoordinates.top + contentHeight > windowHeight) {
newCoordinates.top = windowHeight - contentHeight - 10; // minimum margin at the bottom
}
setCoordinates(newCoordinates);
};
// use debounce since onLayout is triggered as the Content changes position
// and we only want to set ready on the last position update
useEffect(
debounce(() => setIsReady(true), 32),
[coordinates.left, coordinates.top]
);
useEffect(
() => () => {
setIsReady(false);
},
[]
);
return {
style: { ...coordinates },
isReady,
updateCoordinates
};
};
export default useGetCoordinates;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/popper/components/content/styled-components.ts
import styled from "styled-components/native";
import { View } from "react-native";
export const StyledView = styled(View)`
position: absolute;
max-width: fill-available;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/popper/components/content/index.tsx
import React, { forwardRef, ReactNode } from "react";
import {
View,
StyleSheet,
AccessibilityRole,
LayoutChangeEvent,
useWindowDimensions
} from "react-native";
import { EventTypes, Placement } from "../../types";
import { useGetCoordinates, usePopper } from "../../hooks";
import { StyledView } from "./styled-components";
export interface Props {
placement: Placement;
children: ReactNode;
on?: EventTypes;
}
const Content = forwardRef<View, Props>(
({ children, placement, on = "hover" }, ref) => {
const { isWeb, triggerLayout } = usePopper();
const { width: windowWidth, height: windowHeight } = useWindowDimensions();
const { style, isReady, updateCoordinates } = useGetCoordinates({
triggerLayout,
placement,
windowWidth,
windowHeight
});
const handleOnLayout = ({
nativeEvent: {
layout: { width, height }
}
}: LayoutChangeEvent) => {
updateCoordinates(width, height);
};
return (
<StyledView
accessibilityRole={isWeb ? ("dialog" as AccessibilityRole) : "none"}
pointerEvents={on === "hover" ? "none" : "auto"}
ref={ref}
style={[styles.box, { ...style, opacity: +isReady }]}
onLayout={handleOnLayout}
>
{children}
</StyledView>
);
}
);
const styles = StyleSheet.create({
box: {
position: "absolute",
zIndex: 1
}
});
export default Content;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/popper/components/overlay/styled-components.ts
import { Animated, View, TouchableOpacity, Pressable } from "react-native";
import styled, { css } from "styled-components/native";
import { zIndex, ZIndexProps } from "../../../../theming/styledSystem";
const Overlay = (isFixed: boolean) => css`
${zIndex};
position: ${isFixed ? "fixed" : "absolute"};
cursor: default;
left: 0;
right: 0;
top: 0;
bottom: 0;
`;
export const StyledView = styled(Animated.View)<ZIndexProps>`
${Overlay(false)};
`;
export const StyledPressable = styled(Pressable)<ZIndexProps>`
${Overlay(true)};
`;
export const StyledContent = styled(View)<ZIndexProps>`
${Overlay(false)};
`;
export const StyledTouchableOpacity = styled(TouchableOpacity)<ZIndexProps>`
${zIndex};
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/popper/components/overlay/index.tsx
import React, { useEffect, useRef, useState } from "react";
import ReactDOM from "react-dom";
import { StyleSheet, Animated, Platform, Easing } from "react-native";
import { usePopper, useCloseOnClickOutside } from "../../hooks";
import {
StyledView,
StyledPressable,
StyledContent
} from "./styled-components";
import { OverlayProps } from "./types";
/**
* The overlay component will render the Popper content
* it will have extra features for web such as clicking outside and closing
* TODO: keyboard events
*
*/
const Overlay = ({
children,
triggerRef,
contentRef,
on = "hover",
zIndex = 1999
}: OverlayProps) => {
const { isWeb, isOpen, closeContent } = usePopper();
useCloseOnClickOutside({
isWeb,
refs: [contentRef, triggerRef],
onPress: closeContent
});
const fadeAnim = useRef(new Animated.Value(0)).current;
const scaleAnim = useRef(new Animated.Value(0.95)).current;
const [showOpacity, setShowOpacity] = useState(false);
useEffect(() => {
if (isOpen) setShowOpacity(isOpen);
Animated.parallel([
Animated.timing(fadeAnim, {
toValue: isOpen ? 1 : 0,
duration: 200,
useNativeDriver: Platform.OS !== "web",
easing: Easing.inOut(Easing.ease)
}),
Animated.timing(scaleAnim, {
toValue: isOpen ? 1 : 0.95,
duration: 200,
useNativeDriver: Platform.OS !== "web",
easing: Easing.inOut(Easing.ease)
})
]).start(() => {
setShowOpacity(isOpen);
});
}, [isOpen]);
const styles = StyleSheet.create({
toolTip: {
position: "absolute",
// @ts-ignore
cursor: "default",
left: 0,
right: 0,
top: 0,
bottom: 0
}
});
return showOpacity
? ReactDOM.createPortal(
on === "press" ? (
<StyledView
zIndex={zIndex}
pointerEvents="none"
style={[
styles.toolTip,
{
opacity: fadeAnim,
transform: [{ scale: scaleAnim }]
}
]}
>
<StyledPressable onPress={closeContent} zIndex={zIndex} />
<StyledContent zIndex={zIndex}>{children}</StyledContent>
</StyledView>
) : (
<StyledView
zIndex={zIndex}
pointerEvents="none"
style={[
styles.toolTip,
{
opacity: fadeAnim,
transform: [{ scale: scaleAnim }]
}
]}
>
{children}
</StyledView>
),
document.body
)
: null;
};
export default Overlay;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/popper/utils/measureLayout.ts
import { RefObject } from "react";
import { View } from "react-native";
import { Layout } from "../types";
const measureLayout = (ref: RefObject<View>, isWeb?: boolean) =>
new Promise<Layout>((resolve) => {
if (ref.current) {
if (isWeb) {
// @ts-ignore
const { x, y, width, height } = ref.current.getBoundingClientRect();
resolve({ x, y, width, height });
} else {
ref.current.measureInWindow(
(x: number, y: number, width: number, height: number) => {
resolve({ x, y, width, height });
}
);
}
}
});
export default measureLayout;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/popper/components/trigger/index.tsx
import React, { forwardRef, isValidElement, RefObject } from "react";
import { Pressable, View } from "react-native";
import { useQaLabel } from "../../../../hooks/useQaLabel";
import { EventTypes, Layout } from "../../types";
import usePopper from "../../hooks/usePopper";
import measureLayout from "../../utils/measureLayout";
export interface Props {
on: EventTypes;
isDisabled?: boolean;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
children?: any;
}
const Trigger = forwardRef<View, Props>(
({ children, on, isDisabled = false }, ref) => {
const { getHandlers, isWeb } = usePopper();
const popperQaLabel = useQaLabel("popper-trigger");
const hasValidChildren = isValidElement(children);
const getTriggerLayout = async (callback: (layout: Layout) => void) => {
let scrollXOffset = 0;
let scrollYOffset = 0;
let topPosition = 0;
if (isWeb) {
scrollXOffset = document.documentElement.scrollLeft;
scrollYOffset = document.documentElement.scrollTop;
// @ts-ignore
topPosition = ref.current ? ref.current.getBoundingClientRect().top : 0;
}
const triggerLayout = await measureLayout(ref as RefObject<View>, isWeb);
callback({
...triggerLayout,
x: Number(triggerLayout.x) + scrollXOffset,
y: Number(topPosition || triggerLayout.y) + scrollYOffset
});
};
if (!hasValidChildren) return null;
if (isDisabled) return children;
return on === "press" ? (
<Pressable
ref={ref}
{...getHandlers(on, getTriggerLayout)}
{...popperQaLabel}
>
{children}
</Pressable>
) : (
<View ref={ref} {...getHandlers(on, getTriggerLayout)} {...popperQaLabel}>
{children}
</View>
);
}
);
export default Trigger;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/popper/index.tsx
import React, { RefObject, useRef } from "react";
import { View } from "react-native";
import { PopperProps } from "./types";
import PopperProvider from "./context/popperProvider";
import { Content, Overlay, Trigger } from "./components";
const Popper = ({
children,
on,
content,
placement = "top-mid",
isDisabled = false,
layer = 1999,
...rest
}: PopperProps) => {
const triggerRef: RefObject<View> = useRef(null);
const contentRef: RefObject<View> = useRef(null);
return (
<PopperProvider>
<Trigger ref={triggerRef} isDisabled={isDisabled} on={on}>
{children}
</Trigger>
<Overlay
triggerRef={triggerRef}
contentRef={contentRef}
on={on}
zIndex={layer}
>
<Content ref={contentRef} on={on} placement={placement} {...rest}>
{content}
</Content>
</Overlay>
</PopperProvider>
);
};
Popper.defaultProps = {
placement: "top-mid"
};
export default Popper;
export { usePopper } from "./hooks";
export * from "./types";
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/progressBar/styled-components.ts
import styled from "styled-components/native";
import { space, width } from "styled-system";
import { View } from "react-native";
export const StyledContainer = styled(View)`
width: auto;
flex-direction: row;
${width}
${space}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/progressBar/context/index.ts
import { createContext } from "react";
import { PBContextProps } from "../types";
const initialState: PBContextProps = {
completedSteps: 0
};
export const PBContext = createContext<PBContextProps>(initialState);
PBContext.displayName = "PBContext";
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/progressBar/components/styles.ts
import { compose, variant } from "../../../theming/styledSystem";
export const stylesStepBarUncompleted = compose(
variant({
prop: "variant",
variants: {
dark: {
backgroundColor: "blue.400"
},
light: {
backgroundColor: "blue.100"
}
}
})
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/progressBar/components/step/styled-components.ts
import styled, { css } from "styled-components/native";
import { View, Text } from "react-native";
import {
compose,
variant,
space,
SpaceProps
} from "../../../../theming/styledSystem";
import { stylesStepBarUncompleted } from "../styles";
import { ProgressBarVariant } from "../../types";
export const stylesStepBarDescription = compose(
variant({
prop: "variant",
variants: {
dark: {
color: "white.900"
},
light: {
color: "grey.900"
}
}
})
);
export const StyledStepBarContainer = styled(View)`
flex: 1;
`;
export const StyledStepBar = styled(View)<{
isCompleted?: boolean;
variant: ProgressBarVariant;
}>`
height: 4px;
${({ theme, isCompleted }) =>
isCompleted
? css`
background-color: ${theme.colors.green[500]};
`
: stylesStepBarUncompleted}
`;
export const StyledStepBarDescription = styled(Text)<
{
variant: ProgressBarVariant;
} & SpaceProps
>`
text-align: center;
${space}
${stylesStepBarDescription}
${({ theme }) => css`
font-family: ${theme.fonts.regular};
font-size: ${theme.fontSizes.xs};
font-weight: ${theme.fontWeights.normal};
`}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/progressBar/components/step/index.tsx
import React, { forwardRef, useContext } from "react";
import { View } from "react-native";
import { useQaLabel } from "../../../../hooks/useQaLabel";
import { ProgressBarStepProps } from "../../types";
import { PBContext } from "../../context";
import {
StyledStepBarContainer,
StyledStepBar,
StyledStepBarDescription
} from "./styled-components";
export const ProgressBarStep = forwardRef<View, ProgressBarStepProps>(
(
{
qaLabel = "progress-bar-step",
stepNumber = 1,
stepDescription = null,
isDarkMode = false,
...rest
},
ref
) => {
const viewTestProps = useQaLabel(qaLabel);
const { completedSteps } = useContext(PBContext);
return (
<StyledStepBarContainer ref={ref} {...rest} {...viewTestProps}>
<StyledStepBar
variant={isDarkMode ? "dark" : "light"}
isCompleted={stepNumber <= completedSteps}
/>
{stepDescription ? (
<StyledStepBarDescription
variant={isDarkMode ? "dark" : "light"}
mt="space-1"
>
{stepDescription}
</StyledStepBarDescription>
) : null}
</StyledStepBarContainer>
);
}
);
export default ProgressBarStep;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/progressBar/components/achievementStep/styles.ts
import styled, { css } from "styled-components/native";
import { compose, variant } from "../../../../theming/styledSystem";
import { stylesStepBarUncompleted } from "../styles";
import { ProgressBarVariant } from "../../types";
import { Theme } from "../../../../theming/types";
const stylesStepBarUncompletedText = compose(
variant({
prop: "variant",
variants: {
dark: {
color: "blue.800"
},
light: {
color: "blue.300"
}
}
})
);
export const StyledAchievementStepContainer = styled.View<{
isCompleted?: boolean;
variant: ProgressBarVariant;
isMobile: boolean;
theme: Theme;
}>`
display: flex;
height: ${({ isMobile }) => (isMobile ? "24px" : "32px")};
width: ${({ isMobile }) => (isMobile ? "24px" : "32px")};
border-radius: ${({ isMobile }) => (isMobile ? "24px" : "32px")};
justify-content: center;
align-items: center;
margin-left: 1px;
${({ theme, isCompleted }) =>
isCompleted
? css`
background-color: ${theme.colors.green[500]};
color: ${theme.colors.white[900]};
`
: css`
background-color: ${theme.colors.blue[100]};
${stylesStepBarUncompleted}
`}
`;
export const StyledAchievementStepText = styled.Text<{
isCompleted?: boolean;
variant: ProgressBarVariant;
isMobile: boolean;
theme: Theme;
children?: React.ReactNode;
}>`
${({ theme, isMobile }) => css`
font-family: ${theme.fonts.regular};
font-size: ${isMobile ? theme.fontSizes.s : theme.fontSizes.l};
font-weight: ${theme.fontWeights.bold};
`}
${({ theme, isCompleted }) =>
isCompleted
? css`
color: ${theme.colors.white[900]};
`
: stylesStepBarUncompletedText}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/progressBar/components/achievementStep/index.tsx
import React, { forwardRef, useContext } from "react";
import { View } from "react-native";
import { TvgConfContext } from "../../../../utils/tvgConfProvider";
import { ProgressBarAchievementStepProps } from "../../types";
import { useQaLabel } from "../../../../hooks";
import { PBContext } from "../../context";
import {
StyledAchievementStepContainer,
StyledAchievementStepText
} from "./styles";
export const AchievementStep = forwardRef<
View,
ProgressBarAchievementStepProps
>(
(
{
qaLabel = "progress-bar-achievement-step",
icon,
totalSteps = 0,
isDarkMode = false,
...rest
},
ref
) => {
const viewTestProps = useQaLabel(qaLabel);
const { completedSteps } = useContext(PBContext);
const { device } = useContext(TvgConfContext);
const isAchievementStep = completedSteps > totalSteps;
return (
<StyledAchievementStepContainer
isCompleted={isAchievementStep}
variant={isDarkMode ? "dark" : "light"}
isMobile={device === "mobile"}
// @ts-ignore
ref={ref}
{...rest}
{...viewTestProps}
>
{typeof icon === "string" ? (
<StyledAchievementStepText
variant={isDarkMode ? "dark" : "light"}
isCompleted={isAchievementStep}
isMobile={device === "mobile"}
>
{icon}
</StyledAchievementStepText>
) : (
icon
)}
</StyledAchievementStepContainer>
);
}
);
export default AchievementStep;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/progressBar/index.tsx
import React, { forwardRef, memo, useContext } from "react";
import { View } from "react-native";
import { TvgConfContext } from "../../utils/tvgConfProvider";
import { Devices } from "../../theming/types";
import { useQaLabel } from "../../hooks/useQaLabel";
import { StyledContainer } from "./styled-components";
import {
Step as ProgressBarStep,
AchievementStep as ProgressAchievementStep
} from "./components";
import { PBContext } from "./context";
import {
ProgressBarProps,
ProgressBarStepProps,
ProgressBarAchievementStepProps,
ProgressBarCompoundComponent
} from "./types";
export const stylesFn = (device: Devices) => ({
base: {
marginLeft: 1,
marginRight: 1
},
firstStep: {
marginLeft: 0,
borderBottomLeftRadius: 4,
borderTopLeftRadius: 4
},
lastStep: {
marginRight: 0,
borderBottomRightRadius: 4,
borderTopRightRadius: 4
},
withIcon: {
marginTop: device === "mobile" ? 10 : 14
}
});
export const ProgressBar = memo(
forwardRef<View, ProgressBarProps>(
(
{
qaLabel = "progress-bar",
completedSteps = 0,
icon = null,
isDarkMode = false,
children,
...rest
},
ref
) => {
const viewTestProps = useQaLabel(qaLabel);
const { device } = useContext(TvgConfContext);
const styles = stylesFn(device);
const renderSteps = () =>
children.map((stepElement, index) => {
let style = {};
if (index === 0) {
style = styles.firstStep;
} else if (index === children.length - 1 && !icon) {
style = styles.lastStep;
}
if (icon) {
style = {
...style,
...styles.withIcon
};
}
const stepNumber = index + 1;
return React.cloneElement(stepElement, {
key: stepNumber,
stepNumber,
style: [styles.base, style],
isDarkMode
});
});
return (
<StyledContainer ref={ref} {...rest} {...viewTestProps}>
<PBContext.Provider value={{ completedSteps }}>
{renderSteps()}
{icon ? (
<ProgressAchievementStep
icon={icon}
totalSteps={children.length}
isDarkMode={isDarkMode}
/>
) : null}
</PBContext.Provider>
</StyledContainer>
);
}
)
) as ProgressBarCompoundComponent<
typeof ProgressBarStep,
typeof ProgressAchievementStep
>;
ProgressBar.Step = ProgressBarStep;
ProgressBar.AchievementStep = ProgressAchievementStep;
export type {
ProgressBarProps,
ProgressBarStepProps,
ProgressBarAchievementStepProps
};
export default ProgressBar;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/radio/radioGroup/styled-components.ts
import styled from "styled-components/native";
import { margin } from "styled-system";
import { Theme } from "../../../theming/types";
export const StyledViewContainer = styled.View`
${margin}
border-width: 1px;
border-color: transparent;
`;
export const StyledTextLabel = styled.Text<{
theme: Theme;
children?: React.ReactNode;
}>`
font-family: ${({ theme }) => theme.fonts.medium};
color: ${({ theme }) => theme.colors.grey[900]};
margin-bottom: ${({ theme }) => theme.space["space-4"]};
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/radio/radioGroup/index.tsx
import { View } from "react-native";
import React, { createContext, forwardRef } from "react";
import { useQaLabel } from "../../../hooks/useQaLabel";
import { RadioGroupProps, RadioGroupContextProps } from "./types";
import { StyledViewContainer, StyledTextLabel } from "./styled-components";
const initialState = { selectedValue: "", onChange: () => {} };
export const GroupContext = createContext<RadioGroupContextProps>(initialState);
export const RadioGroup = forwardRef<View, RadioGroupProps>(
(
{
label,
children,
selectedValue,
qaLabel,
onChange,
isDisabled = false,
...rest
},
ref
) => {
const viewTestProps = useQaLabel(qaLabel);
return (
<StyledViewContainer
// @ts-ignore
ref={ref}
{...rest}
{...viewTestProps}
accessibilityRole="radiogroup"
>
<GroupContext.Provider value={{ selectedValue, onChange, isDisabled }}>
{label && (
<View>
<StyledTextLabel accessibilityLabel={label}>
{label}
</StyledTextLabel>
</View>
)}
<View>{children}</View>
</GroupContext.Provider>
</StyledViewContainer>
);
}
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/radio/styled-components.ts
import styled from "styled-components/native";
import { Platform, View, Text, Pressable } from "react-native";
import { margin } from "styled-system";
const setDefaultCursor = Platform.OS === "web" && `cursor: default;`;
export const StyledPressableContainer = styled(Pressable)<{
isHovered: boolean;
isDisabled: boolean;
isInvalid: boolean;
isChecked: boolean;
isPressed: boolean;
}>`
${margin};
height: 24px;
width: 24px;
background-color: ${({ theme }) => theme.colors.white[900]};
border-radius: 99px;
border: 1px solid ${({ theme }) => theme.colors.blue[200]};
justify-content: center;
align-items: center;
box-shadow: ${({ theme }) => theme.elevations.low};
${setDefaultCursor}
${({ isHovered, isDisabled, theme }) =>
isHovered &&
`
border: 2px solid ${
isDisabled ? theme.colors.blue[100] : theme.colors.blue_accent[500]
};
box-shadow: ${theme.elevations.medium};
`}
${({ isInvalid, isDisabled, theme }) =>
isInvalid &&
`
border: 2px solid ${
isDisabled ? theme.colors.blue[100] : theme.colors.orange[600]
};
`}
${({ isChecked, theme }) =>
isChecked &&
`
background-color: ${theme.colors.blue_accent[500]};
border: 2px solid ${theme.colors.blue_accent[500]};
box-shadow: none;
`}
${({ isPressed, theme }) =>
isPressed &&
`
background-color: ${theme.colors.blue_accent[500]};
border: 2px solid ${theme.colors.blue_accent[500]};
box-shadow: none;
`}
${({ isDisabled, theme }) =>
isDisabled &&
`
background-color: ${theme.colors.blue["000"]};
border: 1px solid ${theme.colors.blue[100]};
box-shadow: none;
${setDefaultCursor}
`}
`;
export const StyledViewChecker = styled(View)<{
isChecked: boolean;
isDisabled: boolean;
}>`
height: 8px;
width: 8px;
border-radius: 99px;
background-color: ${({ theme }) => theme.colors.white[900]};
${({ isChecked, isDisabled, theme }) =>
isChecked &&
`
background-color: ${
isDisabled ? theme.colors.blue[200] : theme.colors.white[900]
};
`}
${({ isDisabled, isChecked, theme }) =>
isDisabled &&
`
background-color: ${
isChecked ? theme.colors.blue[200] : theme.colors.blue["000"]
};
`}
`;
export const StyledLabelContainer = styled(Text)`
display: flex;
justify-content: center;
padding-left: ${({ theme }) => theme.space["space-3"]};
padding-right: ${({ theme }) => theme.space["space-6"]};
`;
export const StyledLabel = styled(Text)<{ isDisabled: boolean }>`
${setDefaultCursor};
font-family: ${({ theme }) => theme.fonts.regular};
color: ${({ theme }) => theme.colors.grey[900]};
${({ isDisabled, theme }) =>
isDisabled &&
`
color: ${theme.colors.grey[600]};
`}
`;
export const StyledViewContainer = styled(View)`
flex-direction: row;
align-items: center;
margin-bottom: ${({ theme }) => theme.space["space-4"]};
`;
export const StyledView = styled(View)`
flex-shrink: 1;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/radio/index.tsx
import React, { useContext, forwardRef } from "react";
import { View } from "react-native";
import { useQaLabel } from "../../hooks/useQaLabel";
import { RadioGroup, GroupContext } from "./radioGroup";
import { RadioProps, RadioCompoundComponent } from "./types";
import { useEvents } from "../../hooks/useEvents";
import {
StyledPressableContainer,
StyledViewChecker,
StyledLabelContainer,
StyledViewContainer,
StyledLabel
} from "./styled-components";
export const Radio = forwardRef<View, RadioProps>(
({ value, label, isInvalid = false, qaLabel = value, ...rest }, ref) => {
const {
onChange,
selectedValue,
isDisabled = false
} = useContext(GroupContext);
const { events, eventsHandlers } = useEvents({});
const pressHandler = () => {
if (isDisabled) return;
onChange(value);
};
return (
<StyledViewContainer {...useQaLabel(qaLabel)}>
<StyledPressableContainer
{...rest}
{...useQaLabel(`${qaLabel}-input`)}
{...events}
{...eventsHandlers}
onPress={pressHandler}
ref={ref}
focusable
accessibilityRole="radio"
accessibilityState={{ selected: selectedValue === value }}
accessibilityLabel={label}
isInvalid={isInvalid}
isChecked={selectedValue === value}
isDisabled={isDisabled}
>
<StyledViewChecker
isChecked={selectedValue === value}
isDisabled={isDisabled}
/>
</StyledPressableContainer>
<StyledLabelContainer
{...events}
{...eventsHandlers}
onPress={pressHandler}
>
<StyledLabel
isDisabled={isDisabled}
{...useQaLabel(`${qaLabel}-label`)}
>
{label}
</StyledLabel>
</StyledLabelContainer>
</StyledViewContainer>
);
}
) as RadioCompoundComponent<typeof RadioGroup>;
export type { RadioProps };
Radio.Group = RadioGroup;
export default Radio;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/saddle/styled-components.ts
import styled, { css } from "styled-components/native";
import { space } from "styled-system";
import { View } from "react-native";
import { Paragraph } from "../typography";
import { SaddleProps } from "./types";
import Icon from "../icon";
export const StyledSaddle = styled(View)<
Pick<
SaddleProps,
| "all"
| "saddleColor"
| "fullHeight"
| "isScratched"
| "size"
| "raceFinished"
| "enableMyBetsBehavior"
>
>`
align-items: center;
background-color: ${({ saddleColor }) => saddleColor};
border-radius: 2px;
display: flex;
position: relative;
justify-content: center;
opacity: ${({ isScratched }) => (isScratched ? 0.4 : 1)};
${({ size, fullHeight, all }) => {
if (fullHeight && size !== "s") {
return css`
flex-grow: 1;
height: 100%;
width: 32px;
`;
}
if (all === true && size === "s") {
return css`
width: 44px;
height: 20px;
`;
}
return css`
height: ${size === "s" ? "20px" : "44px"};
width: ${size === "s" ? "20px" : "32px"};
`;
}}
${space};
${({ enableMyBetsBehavior, raceFinished }) =>
enableMyBetsBehavior && `opacity: ${raceFinished ? 0.2 : 1}`}
`;
export const Scratcher = styled(View)<{ size: string }>`
position: absolute;
height: 20px;
width: 20px;
border: 2px solid ${({ theme }) => theme.colorTokens.content.default};
overflow: hidden;
z-index: 2;
`;
export const DiagonalLine = styled(View)`
position: absolute;
width: 141.42%;
height: 2px;
background-color: ${({ theme }) => theme.colorTokens.content.default};
top: 50%;
left: -22.85%;
transform: rotate(135deg);
opacity: 1;
`;
export const StyledParagraph = styled(Paragraph)<Pick<SaddleProps, "size">>`
font-family: ${({ size, theme }) =>
size === "s" ? theme.fonts.medium : theme.fonts.bold};
font-size: ${({ size }) => (size === "s" ? "12px" : "18px")};
text-align: center;
line-height: ${({ size }) => (size === "s" ? "15px" : "22px")};
`;
export const WinnerIconWrapper = styled(View)`
position: absolute;
bottom: -4px;
right: -4px;
width: 12px;
height: 12px;
background: ${({ theme }) => theme.colors.green["500"]};
border-radius: 50%;
border: 1px solid ${({ theme }) => theme.colors.green["000"]};
z-index: 2;
`;
export const WinnerIcon = styled(Icon)`
position: absolute;
top: 0.5px;
left: 0.5px;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/saddle/consts.ts
import { SaddleColors } from "./types";
export const SADDLE_COLORS: SaddleColors = {
thoroughbred: {
"1": { numberColor: "#FFFFFF", saddleColor: "#C20E0E" },
"2": { numberColor: "#000000", saddleColor: "#BCC8C8" },
"3": { numberColor: "#FFFFFF", saddleColor: "#3B4E8C" },
"4": { numberColor: "#000000", saddleColor: "#D3B13C" },
"5": { numberColor: "#FFFFFF", saddleColor: "#116410" },
"6": { numberColor: "#FFFFFF", saddleColor: "#303030" },
"7": { numberColor: "#000000", saddleColor: "#D65A2F" },
"8": { numberColor: "#000000", saddleColor: "#E095AA" },
"9": { numberColor: "#000000", saddleColor: "#2AAAA5" },
"10": { numberColor: "#FFFFFF", saddleColor: "#713A98" },
"11": { numberColor: "#FFFFFF", saddleColor: "#6B6B6B" },
"12": { numberColor: "#000000", saddleColor: "#4EA958" },
"13": { numberColor: "#FFFFFF", saddleColor: "#58514D" },
"14": { numberColor: "#FFFFFF", saddleColor: "#94335A" },
"15": { numberColor: "#FFFFFF", saddleColor: "#69522F" },
"16": { numberColor: "#FFFFFF", saddleColor: "#4C6E9F" },
"17": { numberColor: "#FFFFFF", saddleColor: "#373786" },
"18": { numberColor: "#FFFFFF", saddleColor: "#285F23" },
"19": { numberColor: "#FFFFFF", saddleColor: "#32496D" },
"20": { numberColor: "#FFFFFF", saddleColor: "#671334" }
},
harness: {
"1": { numberColor: "#FFFFFF", saddleColor: "#AF0000" },
"2": { numberColor: "#FFFFFF", saddleColor: "#253C85" },
"3": { numberColor: "#000000", saddleColor: "#B2B4B1" },
"4": { numberColor: "#FFFFFF", saddleColor: "#1C5B1B" },
"5": { numberColor: "#FFFFFF", saddleColor: "#252525" },
"6": { numberColor: "#000000", saddleColor: "#B69E00" },
"7": { numberColor: "#000000", saddleColor: "#B27492" },
"8": { numberColor: "#FFFFFF", saddleColor: "#6B6B6B" },
"9": { numberColor: "#FFFFFF", saddleColor: "#610F9A" },
"10": { numberColor: "#FFFFFF", saddleColor: "#263D88" },
"11": { numberColor: "#FFFFFF", saddleColor: "#3B5E90" },
"12": { numberColor: "#FFFFFF", saddleColor: "#A90000" },
"13": { numberColor: "#FFFFFF", saddleColor: "#1D5E1C" },
"14": { numberColor: "#FFFFFF", saddleColor: "#725933" },
"15": { numberColor: "#FFFFFF", saddleColor: "#C0C0C0" }
}
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/saddle/index.tsx
import React, { FC, memo } from "react";
import { get } from "lodash";
import { useColorTokens } from "@tvg/design-system/web/hooks";
import { useQaLabel } from "../../hooks";
import {
StyledSaddle,
StyledParagraph,
WinnerIconWrapper,
WinnerIcon,
Scratcher,
DiagonalLine
} from "./styled-components";
import {
SaddleProps,
Breed,
HarnessVariation,
ThoroughbredVariation,
SaddleColor
} from "./types";
import { SADDLE_COLORS } from "./consts";
const getRunnerColors = (
runnerNumber: number | string,
breed: Breed = "thoroughbred"
): SaddleColor => {
const runnerNumberInt =
typeof runnerNumber === "string"
? parseInt(runnerNumber, 10)
: runnerNumber;
const breedFilter = get(SADDLE_COLORS, `[${breed}]`) ? breed : "thoroughbred";
const { numberColor, saddleColor } = get(
SADDLE_COLORS,
`[${breedFilter}][${runnerNumberInt}]`,
get(
SADDLE_COLORS,
breedFilter === "harness"
? `[${breedFilter}][15]`
: `[${breedFilter}][20]`
)
);
return {
numberColor,
saddleColor
};
};
export const Saddle: FC<SaddleProps> = memo(
({
all,
number,
qaLabel,
numberColor,
saddleColor,
fullHeight,
size,
isWinner = false,
breed = "thoroughbred",
isScratched = false,
raceFinished = false,
enableMyBetsBehavior = false,
...rest
}) => {
const colorTokens = useColorTokens();
const viewTestProps = useQaLabel(qaLabel || `saddle-container-${number}`);
const saddleNumber =
typeof number === "number" ? number.toString() : number;
const defaultColors = getRunnerColors(number, breed);
const runnerColors: SaddleColor = {
numberColor: numberColor || defaultColors.numberColor,
saddleColor: saddleColor || defaultColors.saddleColor
};
return (
<StyledSaddle
{...viewTestProps}
all={all}
saddleColor={
all ? colorTokens.component.input.base : runnerColors.saddleColor
}
fullHeight={fullHeight}
size={size}
isScratched={isScratched}
raceFinished={raceFinished}
enableMyBetsBehavior={enableMyBetsBehavior}
{...rest}
>
{isScratched && size === "s" && enableMyBetsBehavior && (
<Scratcher size={size}>
<DiagonalLine />
</Scratcher>
)}
{isWinner && (
<WinnerIconWrapper>
<WinnerIcon
size="xs"
name="tick"
lineColor="myBets.win.dotColor"
backgroundColor="myBets.win.dotColor"
shouldUseColorTokens
/>
</WinnerIconWrapper>
)}
<StyledParagraph
fontFamily="bold"
fontSize="s"
color={all ? colorTokens.content.default : runnerColors.numberColor}
textTransform={all ? "capitalize" : "none"}
qaLabel="saddle-number"
size={size}
>
{all ? saddleNumber.toLowerCase() : saddleNumber}
</StyledParagraph>
</StyledSaddle>
);
}
);
export default Saddle;
export { SADDLE_COLORS, getRunnerColors };
export type { SaddleProps, Breed, HarnessVariation, ThoroughbredVariation };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/saddleSelections/styled-components.ts
import styled from "styled-components/native";
import { View } from "react-native";
import { css } from "styled-components";
import { useQaLabel } from "../../hooks";
import { Paragraph } from "../typography";
export const Selections = styled(View)`
flex-flow: row wrap;
row-gap: ${({ theme }) => theme.space["space-1"]};
`;
export const IconContainer = styled(View)`
align-items: center;
flex-direction: row;
height: ${({ theme }) => theme.space["space-6"]};
margin-right: ${({ theme }) => theme.space["space-1"]};
width: ${({ theme }) => theme.space["space-6"]};
`;
export const SaddleSelectionContainer = styled(View)<{
isDetailView: boolean;
hasThirdColumn: boolean;
}>`
${({ isDetailView }) =>
isDetailView ? "flex-direction: column" : "flex-direction: row"};
flex-wrap: wrap;
row-gap: 6px;
width: 100%;
`;
export const RowContainer = styled(View)<{
isDetailView: boolean;
showReplacedRunners?: boolean;
}>`
${({ isDetailView, theme }) =>
isDetailView
? `display: grid;
column-gap: ${theme.space["space-3"]};
row-gap: ${theme.space["space-4"]};
grid-template-columns: min-content 1fr min-content;`
: "display: flex; flex-direction: row;"}
${({ isDetailView, showReplacedRunners }) =>
isDetailView &&
showReplacedRunners &&
css`
display: flex;
flex-direction: row;
column-gap: 0;
`}
`;
export const SaddleDetailsParagraph = styled(Paragraph)<{ scratched: boolean }>`
${({ scratched }) => scratched && "text-decoration: line-through;"}
font-size: 14px;
color: ${({ theme }) => theme.colorTokens.content.default};
`;
export const WillPaysContainer = styled(View)`
font-size: 14px;
`;
export const AlternateContainer = styled(View)`
display: flex;
align-items: center;
flex-direction: row;
`;
export const AlternateDivider = styled(View)<{ isDark: boolean }>`
height: 12px;
width: 1px;
background-color: ${({ theme, isDark }) =>
isDark
? theme.colorTokens.content.onLight
: theme.colorTokens.content.onDark};
margin-right: 4px;
`;
export const IconContainerAlternate = styled.View.attrs<{ qaLabel: string }>(
(props) => ({
...useQaLabel(props.qaLabel)
})
)<{
qaLabel: string;
}>`
align-items: center;
flex-direction: row;
height: 20px;
margin-right: 4px;
width: 20px;
position: relative;
`;
export const IconWrapper = styled(View)`
position: absolute;
top: -8px;
right: -8px;
z-index: 99;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/saddleSelections/saddleNumbers.tsx
import React, { useCallback, useMemo } from "react";
import formatCurrency from "@tvg/formatter/currency";
import { useColorTokens } from "@tvg/design-system/web/hooks";
import { get } from "lodash";
import { Saddle } from "../saddle";
import {
IconContainer,
SaddleDetailsParagraph,
SaddleSelectionContainer,
RowContainer,
WillPaysContainer,
AlternateContainer,
AlternateDivider,
IconContainerAlternate,
IconWrapper
} from "./styled-components";
import { rangeSelections } from "./utils";
import { ShowSelectionsProps } from "./types";
import { Paragraph } from "../typography";
import { Tag } from "../tag";
import { ParagraphFonts } from "../typography/paragraph/types";
import Icon from "../icon";
const SaddleNumbers = ({
numWagerableRunners,
selections,
isDark,
showBetType,
scratches,
wagerDetails = false,
shouldShowRefundTag,
breed = "thoroughbred",
onHandicaping,
hideWillPaysTag = false,
enableMyBetsBehavior = false,
showOdds,
favoriteRunner,
showReplacedRunners,
raceStatus,
isAlternateView,
showAlternatePlaceholder = true
}: ShowSelectionsProps) => {
const colorTokens = useColorTokens();
const saddleSelections =
selections?.length > 0
? selections
.filter((selection) => wagerDetails || !selection.isAlternate)
.sort(
(a, b) =>
parseInt(a.number.toString(), 10) -
parseInt(b.number.toString(), 10)
)
: [];
const hasScratch = scratches ? scratches?.length > 0 : false;
const hasWinner = saddleSelections.some((selection) => selection.winner);
const hasWillPays = saddleSelections.some((selection) => selection.willPay);
const checkSaddleSelection = useCallback(
(runnerNumber: string) =>
saddleSelections.filter(
(saddleSelection) => saddleSelection.number === runnerNumber
),
[saddleSelections, hasWinner, hasScratch, hasWillPays]
);
const alternateSelections = useMemo(
() =>
selections.filter((selection) => selection.isAlternate && !wagerDetails),
[selections]
);
const isAllSelections =
numWagerableRunners &&
Number(numWagerableRunners) === saddleSelections.length &&
!wagerDetails;
const isSaddleNumber = !isAllSelections && saddleSelections.length > 0;
const rangedSelections: string[] = useMemo(
() =>
rangeSelections(
saddleSelections,
scratches,
wagerDetails,
enableMyBetsBehavior
)
.join()
.split(/(-)/)
.join()
.split(","),
[wagerDetails, saddleSelections, scratches]
);
const renderAllSelections = () =>
isAllSelections ? (
<Saddle all={isAllSelections} number="All" size="s" breed={breed} />
) : (
// empty Selections
<Saddle
number="?"
size="s"
saddleColor={colorTokens.content.default}
numberColor={colorTokens.component.input.base}
mr="space-1"
enableMyBetsBehavior={enableMyBetsBehavior}
/>
);
return (
<>
{!isSaddleNumber &&
!hasScratch &&
!onHandicaping &&
!wagerDetails &&
!hasWinner ? (
renderAllSelections()
) : (
<SaddleSelectionContainer
isDetailView={wagerDetails}
hasThirdColumn={!!shouldShowRefundTag || hasWillPays}
>
{rangedSelections.map((item, index) => {
const currentSaddleSelection = checkSaddleSelection(item)[0];
const runnerDetailsStyle = {
fontFamily: (currentSaddleSelection?.winner &&
!currentSaddleSelection?.scratched
? "bold"
: "medium") as ParagraphFonts,
opacity: currentSaddleSelection?.isSettled ? "0.3" : "1"
};
return (
<RowContainer
isDetailView={wagerDetails}
showReplacedRunners={
showReplacedRunners && scratches?.includes(item)
}
key={`sanddle-arrow-${index.toString()}`}
>
{item.includes("-") ? (
<IconContainer>
<Icon
size="m"
name="arrowRight"
lineColor={
isDark && showBetType
? "content.onDark"
: "content.subtle"
}
qaLabel="runner-number-range-arrow"
mr="space-1"
shouldUseColorTokens
/>
</IconContainer>
) : (
currentSaddleSelection && (
<>
<Saddle
isScratched={
scratches?.includes(item) ||
(!enableMyBetsBehavior &&
hasWinner &&
currentSaddleSelection.winner === false)
}
raceFinished={
saddleSelections.length === scratches?.length ||
(hasWinner &&
currentSaddleSelection.winner === false) ||
(enableMyBetsBehavior &&
["lost", "won", "attention"].includes(
raceStatus ?? ""
))
}
key={`Saddle-num-${currentSaddleSelection.number}`}
number={currentSaddleSelection.number}
numberColor={currentSaddleSelection.numberColor}
saddleColor={currentSaddleSelection.saddleColor}
all={currentSaddleSelection.number === "ALL"}
isWinner={currentSaddleSelection.winner}
breed={breed}
enableMyBetsBehavior={enableMyBetsBehavior}
size="s"
mr={
!showBetType && index === rangedSelections.length
? 0
: "space-1"
}
/>
{showReplacedRunners &&
scratches?.includes(item) &&
enableMyBetsBehavior && (
<>
<IconContainer
key={`sanddle-arrow-${index.toString()}`}
>
<Icon
size="m"
name="arrowRight"
lineColor="background.warning"
qaLabel="runner-number-range-arrow"
mr="space-1"
shouldUseColorTokens
/>
</IconContainer>
<Saddle
isScratched={
scratches?.includes(item) ||
(!enableMyBetsBehavior &&
hasWinner &&
currentSaddleSelection.winner === false)
}
breed={breed}
raceFinished={
saddleSelections.length === scratches?.length ||
(hasWinner &&
currentSaddleSelection.winner === false) ||
(enableMyBetsBehavior &&
["lost", "won", "attention"].includes(
raceStatus ?? ""
))
}
key={`Saddle-num-${currentSaddleSelection.number}`}
number={
(
favoriteRunner as unknown as Record<
string,
string
>
)?.runnerNumber
}
size="s"
mr={
!showBetType &&
index === rangedSelections.length
? 0
: "space-1"
}
/>
</>
)}
{wagerDetails && (
<SaddleDetailsParagraph
qaLabel="details-runner-name"
scratched={
!!currentSaddleSelection.scratched &&
!showReplacedRunners &&
!scratches?.includes(item)
}
{...runnerDetailsStyle}
>
{showReplacedRunners && scratches?.includes(item)
? (
favoriteRunner as unknown as Record<
string,
string
>
)?.runnerName
: (currentSaddleSelection.runnerName as string)}
</SaddleDetailsParagraph>
)}
{wagerDetails &&
!!currentSaddleSelection.willPay &&
!hideWillPaysTag && (
<WillPaysContainer>
<Paragraph
qaLabel="details-will-pay-amount"
textAlign="center"
{...runnerDetailsStyle}
>
{formatCurrency(currentSaddleSelection.willPay)}
</Paragraph>
</WillPaysContainer>
)}
{wagerDetails &&
!!shouldShowRefundTag &&
!!currentSaddleSelection.scratched && (
<Tag label="REFUND" size="s" variant="warning" />
)}
{wagerDetails &&
currentSaddleSelection.winner &&
currentSaddleSelection.currentOdds &&
showOdds && (
<WillPaysContainer>
<Paragraph
qaLabel="details-will-pay-amount"
textAlign="center"
fontWeight={
currentSaddleSelection.winner
? "bold"
: undefined
}
>
<>
{get(
currentSaddleSelection,
"currentOdds.numerator"
)}
{get(
currentSaddleSelection,
"currentOdds.denominator"
)
? `/${get(
currentSaddleSelection,
"currentOdds.denominator"
)}`
: ""}
</>
</Paragraph>
</WillPaysContainer>
)}
</>
)
)}
</RowContainer>
);
})}
{(showAlternatePlaceholder || alternateSelections?.length > 0) &&
isAlternateView &&
!wagerDetails && (
<AlternateContainer>
<AlternateDivider isDark={isDark} />
{alternateSelections?.length > 0 ? (
alternateSelections.map((item) => (
// @ts-ignore
<IconContainerAlternate
qaLabel="alternate-saddle-row"
key={`alternate-container-${item.number}`}
>
<IconWrapper>
<Icon
name="doubleChevronLeftRight"
backgroundColor="#fff"
size="s"
lineColor="#05285A"
/>
</IconWrapper>
<Saddle
isScratched={scratches?.includes(
item.number.replace("B", "")
)}
raceFinished={false}
number={item.number}
breed={breed}
numberColor={item.numberColor}
saddleColor={item.saddleColor}
size="s"
/>
</IconContainerAlternate>
))
) : (
<>
{showAlternatePlaceholder && (
// @ts-ignore
<IconContainerAlternate qaLabel="alternate-saddle-row">
<IconWrapper>
<Icon
name="doubleChevronLeftRight"
backgroundColor="#fff"
size="s"
lineColor="#05285A"
/>
</IconWrapper>
<Saddle
number="?"
size="s"
numberColor="var(--fd-colors-core-white)"
saddleColor="#fff3"
qaLabel="saddle-question-mark"
/>
</IconContainerAlternate>
)}
</>
)}
</AlternateContainer>
)}
</SaddleSelectionContainer>
)}
</>
);
};
export default SaddleNumbers;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/saddleSelections/utils/rangeSelections/index.ts
import { SaddleSelectionsProps } from "../../types";
export const rangeSelections = (
selections: SaddleSelectionsProps[],
scratches?: string[] | undefined,
wagerDetails?: boolean,
enableMyBetsBehavior?: boolean
) =>
selections
.reduce((ranges: string[][], curr: SaddleSelectionsProps) => {
const lastSubArray: string[] = ranges[ranges.length - 1];
const prevCurr = (+curr.number - 1).toString();
const nextCurr = +curr.number + 1;
const lastSubArrayChar = lastSubArray?.[lastSubArray?.length - 1]; // 4A or 4
const prevArr = lastSubArrayChar?.match(/[a-zA-Z]+|[0-9]+/g); // ["4","A"] or ["4"]
const isPrevCoupledRunner = prevArr && prevArr?.length > 1;
if (
(curr.winner && enableMyBetsBehavior) ||
!lastSubArray ||
scratches?.includes(curr.number) ||
scratches?.includes(prevCurr) ||
(isPrevCoupledRunner &&
(+curr.number - 1).toString() !== prevArr?.[0]) ||
(!isPrevCoupledRunner &&
lastSubArray[lastSubArray.length - 1] !== prevCurr &&
!Number.isNaN(+curr.number)) ||
Number.isNaN(nextCurr)
) {
ranges.push([]);
}
ranges[ranges.length - 1].push(curr.number);
return ranges;
}, [])
.map((range: string[]) => {
if (range.length > 2 && !wagerDetails) {
return [range[0], range[range.length - 1]].join("-");
}
return range;
});
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/saddleSelections/index.tsx
import React from "react";
import { Selections } from "./styled-components";
import { ShowSelectionsProps, SaddleSelectionsProps } from "./types";
import SaddleNumbers from "./saddleNumbers";
import { useQaLabel } from "../../hooks";
export const SaddleSelections = ({
numWagerableRunners,
selections,
isDark,
showBetType,
scratches,
wagerDetails,
shouldShowRefundTag,
breed = "thoroughbred",
qaLabel = "saddle-selections-container",
onHandicaping,
hideWillPaysTag,
enableMyBetsBehavior,
showOdds,
favoriteRunner,
showReplacedRunners,
raceStatus,
isAlternateView,
showAlternatePlaceholder
}: ShowSelectionsProps) => {
const viewTestProps = useQaLabel(qaLabel || "saddle-selections-container");
return (
<Selections {...viewTestProps}>
<SaddleNumbers
scratches={scratches}
numWagerableRunners={numWagerableRunners}
selections={selections}
isDark={isDark}
showBetType={showBetType}
breed={breed}
wagerDetails={wagerDetails}
onHandicaping={onHandicaping}
shouldShowRefundTag={shouldShowRefundTag}
hideWillPaysTag={hideWillPaysTag}
enableMyBetsBehavior={enableMyBetsBehavior}
showOdds={showOdds}
favoriteRunner={favoriteRunner}
showReplacedRunners={showReplacedRunners}
raceStatus={raceStatus}
isAlternateView={isAlternateView}
showAlternatePlaceholder={showAlternatePlaceholder}
/>
</Selections>
);
};
export default SaddleSelections;
export type { SaddleSelectionsProps };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/scrollViewFading/fading/styled-components.ts
import styled from "styled-components/native";
import { View } from "react-native";
import { useQaLabel } from "../../../hooks";
export const StyledViewContainer = styled(View).attrs<{
qaLabel?: string;
}>((props) => ({
...useQaLabel(props.qaLabel || "StyledViewContainer")
}))<{
position: string;
height: string;
width: string;
qaLabel?: string;
}>`
position: absolute;
z-index: 1;
width: ${({ width }) => width || `44px`};
height: ${({ height }) => height || `48px`};
${({ position }) =>
position === "end" ? `right: 0` : position === "bottom" && `top: 99%`};
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/scrollViewFading/fading/index.tsx
import React from "react";
import { v4 as generateUUID } from "uuid";
import Svg, { Path, LinearGradient, Defs, Stop } from "react-native-svg";
import { colors } from "../../../theming/themes/common/colors";
import { ScrollFadeProps } from "./types";
import { StyledViewContainer } from "./styled-components";
const defaultGradientPosition = {
x1: 44,
y1: 24,
x2: 0,
y2: 24
};
export const Fading = ({
position,
isVisible,
height = "48",
width = "44",
viewBox,
preserveAspectRatio,
gradientPosition = defaultGradientPosition,
qaLabel
}: ScrollFadeProps) => {
const gradientID = generateUUID();
const pathId = `paint0_linear_${gradientID}`;
return isVisible ? (
<StyledViewContainer
position={position}
width={width}
height={height}
qaLabel={qaLabel}
>
<Svg
height={height}
width={width}
style={position === "start" && { transform: [{ rotate: "180deg" }] }}
viewBox={viewBox}
preserveAspectRatio={preserveAspectRatio}
>
<Path d="M44 0H0V48H44V0Z" fill={`url(#${pathId})`} />
<Defs>
<LinearGradient
id={pathId}
{...gradientPosition}
gradientUnits="userSpaceOnUse"
>
<Stop stopColor="white" />
<Stop offset="1" stopColor={colors.white[900]} stopOpacity="0" />
</LinearGradient>
</Defs>
</Svg>
</StyledViewContainer>
) : null;
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/scrollViewFading/styled-components.ts
import styled from "styled-components/native";
import { ScrollView } from "react-native";
export const StyledScrollView = styled(ScrollView)<{ paddingAround: boolean }>`
flex-grow: 0;
${({ paddingAround }) => paddingAround && "padding: 2px 0;"}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/scrollViewFading/index.tsx
import React, { useState, useEffect } from "react";
import { LayoutChangeEvent, Dimensions } from "react-native";
import { ScrollViewFadingProps, ScrollEventType } from "./types";
import { StyledScrollView } from "./styled-components";
import { Fading } from "./fading";
import { useQaLabel } from "../../hooks";
export const ScrollViewFading = ({
children,
showScrollBars = true,
paddingAround = false
}: ScrollViewFadingProps) => {
const [showFadeStart, setShowFadeStart] = useState(false);
const [showFadeEnd, setShowFadeEnd] = useState(false);
const [componentWidth, setComponentWidth] = useState(0);
const [screenWidth, setScreenWidth] = useState(0);
const scrollPadding = 20;
const windowResizeHandler = () => {
setScreenWidth(Dimensions.get("window").width);
};
useEffect(() => {
setScreenWidth(Dimensions.get("window").width);
Dimensions.addEventListener("change", windowResizeHandler);
return () => {
// @ts-ignore
Dimensions.removeEventListener("change", windowResizeHandler);
};
}, []);
useEffect(() => {
setShowFadeEnd(componentWidth === screenWidth);
}, [componentWidth, screenWidth]);
const scrollIsCloseToEnd = ({
layoutMeasurement,
contentOffset,
contentSize
}: ScrollEventType) =>
layoutMeasurement.width + contentOffset.x >=
contentSize.width - scrollPadding;
const scrollIsCloseToStart = (nativeEvent: ScrollEventType) =>
nativeEvent.contentOffset.x <= scrollPadding;
const scrollHandler = ({ nativeEvent }: { nativeEvent: ScrollEventType }) => {
setShowFadeEnd(!scrollIsCloseToEnd(nativeEvent));
setShowFadeStart(!scrollIsCloseToStart(nativeEvent));
};
const onLayoutHandler = (event: LayoutChangeEvent) => {
setComponentWidth(event.nativeEvent.layout.width);
};
return (
<>
<Fading position="start" isVisible={showFadeStart} />
<StyledScrollView
onLayout={onLayoutHandler}
{...useQaLabel("scrollview")}
horizontal
onScroll={scrollHandler}
showsVerticalScrollIndicator={showScrollBars}
showsHorizontalScrollIndicator={showScrollBars}
scrollEventThrottle={200}
paddingAround={paddingAround}
>
{children}
</StyledScrollView>
<Fading position="end" isVisible={showFadeEnd} />
</>
);
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/segmentedControl/styled-components.ts
import styled, { css } from "styled-components/native";
import { View, Text, Pressable, Platform, Animated } from "react-native";
import { space, width } from "../../theming/styledSystem";
import { SegmentSize } from "./types";
export const sizesMap = {
s: {
height: 32
},
m: {
height: 40
},
l: {
height: 52
}
};
export const StyledComponent = styled(View)<{
isDisabled: boolean;
size: SegmentSize;
}>`
overflow: hidden;
position: relative;
height: ${({ size }) => sizesMap[size]?.height}px;
border-radius: 68px;
${({ theme }) => css`
background-color: ${theme.colorTokens.background.base};
padding: ${theme.space["space-1"]};
`};
${({ isDisabled }) =>
isDisabled &&
css`
opacity: 0.4;
`}
${space};
${width};
`;
export const SegmentsContainer = styled(View)`
flex: 1;
flex-direction: row;
justify-content: space-evenly;
align-items: center;
elevation: 5;
background-color: ${({ theme }) => theme.colorTokens.background.default};
`;
export const SegmentTab = styled(Pressable)<{ isFocused: boolean }>`
height: 100%;
flex: 1;
${({ isFocused }) =>
Platform.OS !== "web" &&
isFocused &&
css`
outline-style: solid;
outline-width: 1px;
`}
`;
export const SegmentTabContent = styled(Animated.View)`
flex: 1;
flex-direction: row;
justify-content: center;
align-items: center;
margin: 1px;
`;
export const SegmentText = styled(Text)<{ isSelected?: boolean }>`
${({ theme, isSelected }) => css`
font-family: ${theme.fonts.medium};
font-size: ${theme.fontSizes.s};
line-height: ${theme.lineHeights.s};
color: ${isSelected
? theme.colorTokens.content.default
: theme.colorTokens.content.subtle};
`}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/segmentedControl/segmentedControl.tsx
import React, { createContext, useEffect, useState } from "react";
import { LayoutChangeEvent } from "react-native";
import { getAccessibilityRole } from "../../utils/accessibility";
import { useQaLabel } from "../../hooks/useQaLabel";
import {
SegmentedControlProps,
SCContextProps,
SCTabSelectedProps
} from "./types";
import { StyledComponent, SegmentsContainer } from "./styled-components";
import { SegmentedControlPill } from "./segmentedControlPill";
const initialState: SCContextProps = {
selectedValue: "",
onSelect: () => {},
isDisabled: false
};
export const SCContext = createContext<SCContextProps>(initialState);
SCContext.displayName = "SCContext";
export const SegmentedControl = ({
style,
onChange,
selectedValue,
size,
isDisabled = false,
children,
qaLabel,
...rest
}: SegmentedControlProps): JSX.Element => {
const [segmentWidth, setSegmentWidth] = useState(0);
const [tabsNbr, setTabsNbr] = useState(
React.Children.toArray(children).length
);
const [selectedTab, setSelectedTab] = useState<SCTabSelectedProps>({
index: 0,
children: ""
});
useEffect(() => {
let selectedTabChildren;
let selectedTabEnd;
const childrenElements = React.Children.toArray(children);
const selectedTabIndex = childrenElements.findIndex((elem) => {
if (
React.isValidElement<{
value: string;
children: string | JSX.Element;
end?: JSX.Element;
}>(elem) &&
elem.props.value === selectedValue
) {
selectedTabChildren = elem.props.children;
selectedTabEnd = elem.props.end;
return true;
}
return false;
});
if (selectedTabIndex !== -1) {
setSelectedTab({
index: selectedTabIndex,
children: selectedTabChildren || "",
end: selectedTabEnd
});
}
if (childrenElements.length !== tabsNbr) {
setTabsNbr(childrenElements.length);
}
}, [children, selectedValue]);
const handleChange = (value: string | number) => {
// mocks iOS's nativeEvent
const event = {
nativeEvent: {
value
}
};
// @ts-ignore
if (typeof onChange === "function") onChange(event);
};
const handleLayoutChange = (event: LayoutChangeEvent) => {
const { width } = event.nativeEvent.layout;
const newSegmentWidth = tabsNbr ? width / tabsNbr : 0;
if (newSegmentWidth !== segmentWidth) {
setSegmentWidth(newSegmentWidth);
}
};
return (
<StyledComponent
{...useQaLabel(qaLabel)}
accessibilityRole={getAccessibilityRole("tablist")}
style={style}
size={size}
isDisabled={isDisabled}
onLayout={handleLayoutChange}
{...rest}
>
<SegmentsContainer>
<SCContext.Provider
value={{ selectedValue, onSelect: handleChange, isDisabled }}
>
{children}
</SCContext.Provider>
</SegmentsContainer>
{segmentWidth ? (
<SegmentedControlPill
segmentWidth={segmentWidth}
selectedIndex={selectedTab.index}
end={selectedTab.end}
qaLabel={`${qaLabel}-pill`}
>
{selectedTab.children}
</SegmentedControlPill>
) : null}
</StyledComponent>
);
};
export type { SegmentedControlProps };
export default SegmentedControl;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/segmentedControl/segmentedControlPill.tsx
import React, { isValidElement } from "react";
import { Animated, StyleSheet } from "react-native";
import { easeSinInOut } from "d3-ease";
import { useColorTokens } from "@tvg/design-system/web/hooks";
import { getAccessibilityRole } from "../../utils/accessibility";
import { useQaLabel } from "../../hooks/useQaLabel";
import { SCPillProps } from "./types";
import { SegmentTabContent, SegmentText } from "./styled-components";
const sliderMargin = 4;
export const SegmentedControlPill = ({
segmentWidth,
selectedIndex,
children,
end,
qaLabel = "segmented-control-pill"
}: SCPillProps) => {
const animation = React.useRef(
new Animated.Value(segmentWidth * selectedIndex)
).current;
const colorTokens = useColorTokens();
React.useEffect(() => {
if (animation && segmentWidth) {
Animated.timing(animation, {
toValue: segmentWidth * selectedIndex,
duration: 300,
easing: easeSinInOut,
useNativeDriver: true
}).start();
}
}, [animation, segmentWidth, selectedIndex]);
const opacity = animation.interpolate({
inputRange: [
segmentWidth * (selectedIndex - 1),
segmentWidth * selectedIndex - segmentWidth / 2,
segmentWidth * selectedIndex - segmentWidth / 4,
segmentWidth * selectedIndex,
segmentWidth * selectedIndex + segmentWidth / 4,
segmentWidth * selectedIndex + segmentWidth / 2,
segmentWidth * (selectedIndex + 1)
],
outputRange: [0, 0.1, 0.2, 1, 0.2, 0.1, 0],
extrapolate: "clamp",
easing: easeSinInOut
});
return selectedIndex != null && segmentWidth ? (
<Animated.View
{...useQaLabel(qaLabel)}
style={[
styles.slider,
{
transform: [{ translateX: animation }],
width: segmentWidth - 2 * sliderMargin,
backgroundColor: colorTokens.background.surface,
shadowColor: colorTokens.background.secundary
}
]}
>
<SegmentTabContent
style={{
opacity
}}
>
{isValidElement(children) ? (
children
) : (
<SegmentText
accessibilityRole={getAccessibilityRole("span")}
isSelected
>
<Animated.Text>{children}</Animated.Text>
</SegmentText>
)}
{end}
</SegmentTabContent>
</Animated.View>
) : null;
};
const styles = StyleSheet.create({
slider: {
position: "absolute",
alignItems: "center",
justifyContent: "center",
borderRadius: 68,
top: sliderMargin,
bottom: sliderMargin,
right: sliderMargin,
left: sliderMargin,
shadowOffset: {
width: 0,
height: 1
},
shadowOpacity: 0.12,
shadowRadius: 3,
elevation: 3
}
});
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/seoArea/styled-components.ts
import styled from "styled-components";
import { Theme } from "../../theming/types";
export const SeoContainer = styled.div<{ theme: Theme }>`
background-color: ${({ theme }) => theme.colors.white[900]};
padding: 15px 12px 20px;
box-shadow: inset 0 0 0 1px ${({ theme }) => theme.colors.blue[100]};
a {
vertical-align: baseline;
color: ${({ theme }) => theme.colors.blue_accent[800]};
cursor: pointer;
}
p {
padding-top: 12px;
}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/sort/styled-components.ts
import styled, { css } from "styled-components/native";
import { StyledButton } from "../button";
import {
color,
background,
space,
borderRadius,
width,
compose
} from "../../theming/styledSystem";
const styles = compose(color, background, space, borderRadius, width);
export const SortButton = styled(StyledButton)<{ justifyContent: string }>`
flex-direction: row;
justify-content: ${({ justifyContent }) => justifyContent};
${styles};
`;
export const Container = styled.View<{
hasBorder: boolean;
children?: React.ReactNode;
}>`
position: relative;
${({ hasBorder }) =>
hasBorder &&
css`
border: 1px solid ${({ theme }) => theme.colorTokens.border.default};
box-shadow: 0 2px 4px #112b4424;
`}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/sort/context.ts
import { createContext } from "react";
import { noop } from "lodash";
import { SortContextProps } from "./types";
const initialState: SortContextProps = {
isDropdownOpen: false,
onChange: noop,
selectedValue: "",
layer: 999
};
export const SortContext = createContext<SortContextProps>(initialState);
SortContext.displayName = "SortContext";
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/sort/components/animatedDropdown/styled-components.ts
import styled, { css } from "styled-components/native";
import { rgba } from "polished";
import {
color,
background,
space,
borderRadius,
width,
compose
} from "../../../../theming/styledSystem";
import { Theme } from "../../../../theming/types";
const styleFns = compose(color, background, borderRadius, width);
export const Container = styled.View`
display: flex;
`;
export const ContentContainer = styled.View<{
layer: number;
width: string;
children?: React.ReactNode;
}>`
position: absolute;
z-index: ${({ layer }) => layer};
display: flex;
flex-direction: column;
${space}
${styleFns}
`;
export const Dropdown = styled.View<{
isDarkMode: boolean;
theme: Theme;
children?: React.ReactNode;
}>`
border-width: 1px;
${({ theme, isDarkMode }) => css`
background-color: ${isDarkMode
? theme.colors.blue["900"]
: theme.colors.white["900"]};
border-color: ${theme.colors.blue["100"]};
border-radius: ${theme.radii.s};
filter: drop-shadow(0 1px 3px ${rgba(theme.colors.blue[900], 0.14)});
will-change: filter;
`}
${styleFns}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/sort/components/option/styled-components.ts
import styled, { css } from "styled-components/native";
import { TouchableHighlight, Text } from "react-native";
import { StyledProps, DisabledProps } from "./types";
export const StyledPressable = styled(TouchableHighlight)<
StyledProps & DisabledProps
>`
min-height: 42px;
background-color: ${({ theme }) => theme.colors.white[900]};
padding: ${({ theme }) => theme.space["space-4"]};
justify-content: center;
align-items: left;
${({ isHovered, isDisabled, theme }) =>
isHovered &&
css`
background-color: ${theme.colors.blue_accent["000"]};
cursor: ${isDisabled ? "default" : "pointer"};
`}
${({ isPressed, theme }) =>
isPressed &&
css`
background-color: ${theme.colors.blue_accent[100]};
`}
${({ isDisabled, theme }) =>
isDisabled &&
css`
background-color: ${theme.colors.white[500]};
`};
${({ isSelected, theme }) =>
isSelected &&
css`
background-color: ${theme.colors.blue_accent["000"]};
border-bottom-color: ${theme.colors.blue["000"]};
border-bottom-width: 1px;
border-left-color: ${theme.colors.blue_accent[500]};
border-left-width: 2px;
`}
`;
export const StyledTextTitle = styled(Text)<StyledProps & DisabledProps>`
${({ theme, isSelected, isPressed, isDisabled }) => css`
font-family: ${isSelected || isPressed
? theme.fonts.medium
: theme.fonts.regular};
font-size: ${theme.fontSizes.s};
color: ${((isSelected || isPressed) && theme.colors.blue_accent[500]) ||
(isDisabled && theme.colors.grey[600]) ||
theme.colors.grey[900]};
`}
`;
export const StyledTextDescription = styled(Text)<StyledProps>`
${({ theme, isSelected, isPressed }) => css`
font-family: ${isSelected || isPressed
? theme.fonts.medium
: theme.fonts.regular};
font-size: ${theme.fontSizes.xs};
color: ${theme.colors.grey[700]};
`}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/switch/styled-components.ts
import { Platform, View, Text } from "react-native";
import styled, { css } from "styled-components/native";
import { getAccessibilityRole } from "../../utils/accessibility";
const setDefaultCursor = Platform.OS === "web" && `cursor: default;`;
export const Toggle = styled(View)<{ on: boolean; isDisabled: boolean }>`
height: 24px;
align-items: center;
justify-content: center;
border-radius: ${({ theme }) => theme.radii.l};
${({ on, isDisabled, theme }) =>
on
? css`
background-color: ${isDisabled
? theme.colors.blue["000"]
: theme.colors.blue_accent[500]};
`
: css`
background-color: ${isDisabled
? theme.colors.blue["000"]
: theme.colors.grey[300]};
`};
${({ isDisabled }) => isDisabled && setDefaultCursor}
`;
export const Slider = styled(View)`
width: 18px;
height: 18px;
border-radius: ${({ theme }) => theme.radii.m};
background-color: ${({ theme }) => theme.colors.white[900]};
`;
export const TextArea = styled(Text).attrs(() => ({
accessibilityRole: getAccessibilityRole("span")
}))<{ on: boolean; isDisabled: boolean }>`
color: ${({ theme, isDisabled }) =>
isDisabled ? theme.colors.blue[200] : theme.colors.white[900]};
font-size: ${({ theme }) => theme.fontSizes.xs};
font-family: ${({ theme }) => theme.fonts.medium};
${(props) =>
props.on
? css`
margin-right: ${props.theme.space["space-6"]};
`
: css`
margin-left: ${props.theme.space["space-6"]};
`};
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/switch/index.tsx
import React, { useCallback, useRef, useEffect } from "react";
import { Animated, Pressable } from "react-native";
import useQaLabel from "../../hooks/useQaLabel";
import { Toggle, Slider, TextArea } from "./styled-components";
import { SwitchProps } from "./types";
const AnimatedSlider = Animated.createAnimatedComponent(Slider);
export const Switch = ({
isOn,
onPress,
qaLabel,
isDisabled = false
}: SwitchProps) => {
const testProps = useQaLabel(qaLabel);
const leftAnimatedValue = useRef(new Animated.Value(isOn ? 1 : 0)).current;
const turnOnOff = (on: boolean) =>
Animated.timing(leftAnimatedValue, {
toValue: on ? 0 : 1,
duration: 200,
useNativeDriver: false
}).start();
useEffect(() => {
requestAnimationFrame(() => {
turnOnOff(!isOn);
});
}, [isOn]);
const onPressSwitch = useCallback(() => {
onPress();
requestAnimationFrame(() => {
turnOnOff(!!isOn);
});
}, [isOn, onPress]);
const leftValue = leftAnimatedValue.interpolate({
inputRange: [0, 1],
outputRange: [4, 30]
});
return (
<Pressable
accessibilityRole="switch"
accessibilityState={{ checked: isOn, disabled: isDisabled }}
onPress={onPressSwitch}
disabled={isDisabled}
// eslint-disable-next-line
style={{ width: 52 }}
>
<Toggle {...testProps} on={isOn} isDisabled={isDisabled}>
<TextArea on={isOn} isDisabled={isDisabled}>
{isOn ? "ON" : "OFF"}
</TextArea>
<AnimatedSlider
// eslint-disable-next-line
style={{
position: "absolute",
left: leftValue
}}
/>
</Toggle>
</Pressable>
);
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/tabs/tabs.tsx
import React, { createContext, useState, useMemo } from "react";
import { View, ScrollView } from "react-native";
import { useQaLabel } from "../../hooks/useQaLabel";
import { TabsProps, TabsContextProps, TabsLayout } from "./types";
import {
StyledViewContainer,
ContentView,
TabHeaderContainer
} from "./styled-components";
const initialState: TabsContextProps = {
selectedValue: "",
onChange: () => {},
isStretched: false,
tabsLayout: {},
setTabsLayout: () => {},
isFullHeight: false
};
export const TabsContext = createContext<TabsContextProps>(initialState);
TabsContext.displayName = "TabsContext";
export const Tabs = ({
qaLabel,
children,
selectedValue,
onChange,
isFullHeight = false,
useViewComponent = false,
headerPadding,
headerWidth,
...rest
}: TabsProps) => {
const content = useMemo(() => {
const childrenElements = React.Children.toArray(children);
return childrenElements.filter((val) => {
if (React.isValidElement<{ value: string }>(val)) {
return val.props.value === selectedValue;
}
return val;
});
}, [selectedValue, children]);
const viewTestProps = useQaLabel(qaLabel);
const [tabsLayout, setTabsLayout] = useState<TabsLayout>({});
let tabList;
if (children[0]?.props.qaLabel === "tabList") {
tabList = children[0];
} else {
throw new Error(
"TabList child element is required to be used at first place"
);
}
return (
<StyledViewContainer
isFullHeight={isFullHeight}
{...rest}
{...viewTestProps}
>
<TabsContext.Provider
value={{
selectedValue,
onChange,
tabsLayout,
setTabsLayout,
isFullHeight
}}
>
<TabHeaderContainer
headerPadding={headerPadding}
headerWidth={headerWidth}
>
{tabList}
</TabHeaderContainer>
<ContentView
as={useViewComponent ? View : ScrollView}
isFullHeight={isFullHeight}
>
{content}
</ContentView>
</TabsContext.Provider>
</StyledViewContainer>
);
};
export type { TabsProps };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/tabs/styled-components.ts
import styled, { css } from "styled-components/native";
import { margin } from "styled-system";
import { View, ScrollView } from "react-native";
export const StyledViewContainer = styled(View)<{ isFullHeight: boolean }>`
position: relative;
${({ isFullHeight }) => isFullHeight && "flex-grow:1"};
${margin}
`;
export const ContentView = styled(ScrollView)<{ isFullHeight: boolean }>`
${({ isFullHeight }) => isFullHeight && "flex-grow:1"};
`;
export const TabHeaderContainer = styled(View)<{
headerPadding?: string;
headerWidth?: string;
}>`
border-bottom-color: ${({ theme }) => theme.colors.blue[100]};
border-bottom-width: 1px;
width: ${({ headerWidth }) => headerWidth || `100%`};
background-color: ${({ theme }) => theme.colors.white[900]};
z-index: 1;
${({ headerPadding }) =>
headerPadding &&
css`
padding: ${headerPadding};
`}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/tabs/components/tab/styled-components.ts
import styled from "styled-components/native";
import { TouchableHighlight, Text, View } from "react-native";
import { StrechedProps, StyledProps, DisabledProps } from "./types";
export const StyledPressable = styled(TouchableHighlight)<
StyledProps & StrechedProps & DisabledProps
>`
height: 48px;
background-color: ${({ theme }) => theme.colors.white[900]};
border-bottom-color: ${({ theme }) => theme.colors.blue[100]};
border-bottom-width: ${({ noBorder }) => (noBorder ? "0" : "1px")};
padding-left: ${({ theme }) => theme.space["space-4"]};
padding-right: ${({ theme }) => theme.space["space-4"]};
justify-content: center;
align-items: center;
${({ isStretched }) =>
isStretched &&
`
flex-grow: 1;
`}
${({ isHovered, isDisabled, theme, hoverColor }) =>
isHovered &&
`background-color: ${hoverColor || theme.colors.blue_accent["000"]};
cursor: ${isDisabled ? "default" : "pointer"}
`}
${({ isPressed, theme, hasPressedColor }) =>
isPressed &&
hasPressedColor &&
`
background-color: ${theme.colors.blue_accent[100]};
`}
${({ isDisabled, theme }) =>
isDisabled &&
`
background-color: ${theme.colors.white[500]};
`};
`;
export const StyledTextTitle = styled(Text)<StyledProps & DisabledProps>`
color: ${({ theme, textTitleColor }) =>
textTitleColor || theme.colors.grey[900]};
font-size: ${({ theme }) => theme.fontSizes.s};
font-family: ${({ theme }) => theme.fonts.medium};
${({ isSelected, theme, textTitleSelectedColor }) =>
isSelected &&
`
color: ${textTitleSelectedColor || theme.colors.blue_accent[500]}
`}
${({ isPressed, theme, hasPressedColor }) =>
isPressed &&
hasPressedColor &&
`
color: ${theme.colors.blue_accent[500]}
`}
${({ isDisabled, theme }) =>
isDisabled &&
`
color: ${theme.colors.grey[600]};
`}
${({ isTitleUppercase }) => isTitleUppercase && `text-transform: uppercase;`}
`;
export const StyledViewIconContainer = styled(View)`
margin-left: ${({ theme }) => theme.space["space-1"]};
`;
export const StyledTextDescription = styled(Text)<StyledProps & DisabledProps>`
font-size: ${({ theme }) => theme.fontSizes.xs};
font-family: ${({ theme }) => theme.fonts.regular};
color: ${({ theme }) => theme.colors.grey[800]};
margin-top: 2px;
${({ isSelected, theme }) =>
isSelected &&
`
color: ${theme.colors.blue_accent[400]}
`}
${({ isPressed, theme }) =>
isPressed &&
`
color: ${theme.colors.blue_accent[400]}
`}
${({ isDisabled, theme }) =>
isDisabled &&
`
color: ${theme.colors.grey[500]};
`}
`;
export const StyledViewTitleContainer = styled(View)`
flex-direction: row;
margin-bottom: 2px;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/tabs/components/tab/index.tsx
import React, { useContext, useEffect } from "react";
import { LayoutChangeEvent } from "react-native";
import { useEvents } from "../../../../hooks/useEvents";
import { useQaLabel } from "../../../../hooks/useQaLabel";
import { useTheme } from "../../../../theming";
import { TabsContext } from "../../tabs";
import {
StyledPressable,
StyledTextTitle,
StyledViewIconContainer,
StyledViewTitleContainer,
StyledTextDescription
} from "./styled-components";
import { TabProps } from "./types";
export type { TabProps };
export const Tab = ({
value,
title,
description,
counter,
isSelected = false,
isDisabled = false,
noBorder = false,
isStretched,
qaLabel = value,
isTitleUppercase = false,
hoverColor,
textTitleColor,
textTitleSelectedColor,
hasPressedColor = true
}: TabProps) => {
const viewTestProps = useQaLabel(qaLabel);
const { colors } = useTheme();
const {
selectedValue,
onChange = () => {},
setTabsLayout
} = useContext(TabsContext);
const { events, setEvents, eventsHandlers } = useEvents({
isSelected: selectedValue === value
});
useEffect(() => {
setEvents({ ...events, isSelected });
}, [isSelected]);
useEffect(() => {
setEvents({
...events,
isSelected: isSelected || selectedValue === value
});
}, [selectedValue]);
const pressHandler = () => {
onChange(value);
};
const onLayoutHandler = (event: LayoutChangeEvent, tab: string) => {
const { width, x } = event.nativeEvent.layout;
const newState = {
[tab]: { width, x }
};
setTabsLayout((state: {}) => ({ ...state, ...newState }));
};
return (
<StyledPressable
accessibilityRole="tab"
onPress={pressHandler}
isStretched={isStretched}
isDisabled={isDisabled}
noBorder={noBorder}
disabled={isDisabled}
onLayout={(event) => onLayoutHandler(event, value)}
onLongPress={pressHandler}
underlayColor={colors.blue_accent[100]}
hoverColor={hoverColor}
hasPressedColor={hasPressedColor}
{...eventsHandlers}
{...events}
{...viewTestProps}
>
<>
<StyledViewTitleContainer>
<StyledTextTitle
{...events}
isDisabled={isDisabled}
isTitleUppercase={isTitleUppercase}
textTitleColor={textTitleColor}
textTitleSelectedColor={textTitleSelectedColor}
>
{title}
</StyledTextTitle>
{!isDisabled && counter && (
<StyledViewIconContainer>{counter}</StyledViewIconContainer>
)}
</StyledViewTitleContainer>
{description && (
<StyledTextDescription {...events} isDisabled={isDisabled}>
{description}
</StyledTextDescription>
)}
</>
</StyledPressable>
);
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/tabs/components/tabSelectionIndicator/index.tsx
import React, { useContext, useEffect, useRef } from "react";
import { Animated, Platform, StyleSheet } from "react-native";
import { tvgColorPalette as colors } from "../../../../theming/themes/common";
import { TabsContext } from "../../tabs";
import { TabSelectionIndicatorProps } from "./types";
const isWeb = Platform.OS === "web";
export const TabSelectionIndicator = ({
width,
x,
tabSelectionIndicatorColor
}: TabSelectionIndicatorProps) => {
const { selectedValue, tabsLayout } = useContext(TabsContext);
const translation = useRef(new Animated.Value(x)).current;
useEffect(() => {
Animated.timing(translation, {
toValue: x,
useNativeDriver: !isWeb,
duration: 200
}).start();
}, [selectedValue, tabsLayout]);
return (
<Animated.View
style={[
styles.slider,
{
width,
backgroundColor:
tabSelectionIndicatorColor || colors.blue_accent[500],
transform: [{ translateX: translation }]
}
]}
/>
);
};
const styles = StyleSheet.create({
slider: {
position: "absolute",
top: 46,
height: 2
}
});
export { TabSelectionIndicatorProps };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/tabs/components/tabList/styled-components.ts
import styled from "styled-components/native";
import { View } from "react-native";
export const StyledViewContainer = styled(View)`
flex-direction: row;
height: 48px;
border: none;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/tabs/components/tabPanel/styled-components.ts
import styled from "styled-components/native";
import { View } from "react-native";
import { padding } from "styled-system";
export const StyledView = styled(View)<{ isFullHeight?: boolean }>`
${({ isFullHeight }) => isFullHeight && "flex-grow:1"};
${padding};
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/tag/styled-components.ts
import styled, { css } from "styled-components/native";
import { Platform, View, Text } from "react-native";
import { compose, variant, margin } from "../../theming/styledSystem";
import { Paragraph } from "../typography";
import { TagVariant } from "./types";
const isWeb = Platform.OS === "web";
export const tagVariants = {
info: {
backgroundColor: "background.base",
color: "content.neutral"
},
optedin: {
backgroundColor: "background.positiveSubtle",
color: "content.positive"
},
promo: {
backgroundColor: "background.alertSubtle",
color: "content.alert"
},
warning: {
backgroundColor: "background.warningSubtle",
color: "content.warning"
},
highlight: {
backgroundColor: "background.infoSubtle",
color: "content.info"
},
fav: {
backgroundColor: "component.notification.promo.background",
color: "content.strong"
}
};
export const tagSizes = {
prop: "size",
variants: {
s: {
paddingX: "space-2",
height: "16px"
},
m: {
paddingX: "space-2",
height: "20px"
},
l: {
paddingX: "space-2",
height: "24px"
}
}
};
const stylesTagSizes = compose(variant(tagSizes));
export const styleFitContent =
isWeb &&
css`
width: fit-content;
`;
export const TagContainer = styled(View)<{
backgroundColor: string;
variant: TagVariant;
}>`
${margin}
${stylesTagSizes}
align-items: center;
align-self: flex-start;
background-color: ${({ backgroundColor }) => backgroundColor};
border-radius: 99px;
flex-direction: row;
justify-content: center;
`;
export const StyledParagraph = styled(Paragraph)`
text-transform: uppercase;
`;
export const StyledText = styled(Text)<{ color: string }>`
text-transform: uppercase;
font-family: ${({ theme }) => theme.fonts.condensedRegular};
color: ${({ color }) => color};
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/tag/tagIcon/styled-components.ts
import styled from "styled-components/native";
import { margin } from "styled-system";
import { View } from "react-native";
import { styleFitContent } from "../styled-components";
export const TagCircleContainer = styled(View)<{
backgroundColor: string;
}>`
${margin}
${styleFitContent}
border-radius: 99px;
padding: ${({ theme }) => theme.space["space-1"]};
align-self: flex-start;
background-color: ${({ backgroundColor }) => backgroundColor};
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/tag/index.tsx
import React from "react";
import { useColorTokens } from "../../theming/hooks/useColorTokens";
import { useQaLabel } from "../../hooks/useQaLabel";
import { Icon } from "../icon";
import { StyledText, TagContainer, tagVariants } from "./styled-components";
import { TagIcon } from "./tagIcon";
import { TagProps, TagVariant } from "./types";
export const Tag = ({
qaLabel = "tag",
label,
icon,
variant,
...props
}: TagProps) => {
const viewTestProps = useQaLabel(qaLabel);
const bgColor = useColorTokens(
tagVariants[variant as TagVariant].backgroundColor
);
const color = useColorTokens(
tagVariants[variant as TagVariant].color
) as string;
return (
<TagContainer
backgroundColor={bgColor}
variant={variant}
{...props}
{...viewTestProps}
>
{icon && (
<Icon
name={icon}
size="s"
backgroundColor="transparent"
lineColor={color}
mr="space-1"
/>
)}
<StyledText color={color}>{label}</StyledText>
</TagContainer>
);
};
Tag.Icon = TagIcon;
export type { TagProps, TagVariant };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/tag/tagIcon/index.tsx
import React from "react";
import { useQaLabel } from "../../../hooks";
import { Icon } from "../../icon";
import { TagIconProps } from "./types";
import { TagVariant } from "../types";
import { tagVariants } from "../styled-components";
import { TagCircleContainer } from "./styled-components";
import { useColorTokens } from "../../../theming/hooks/useColorTokens";
export const TagIcon = ({
qaLabel = "tag-icon",
label,
icon,
variant,
...props
}: TagIconProps) => {
const viewTestProps = useQaLabel(qaLabel);
const bgColor = useColorTokens(
tagVariants[variant as TagVariant].backgroundColor
);
const color = useColorTokens(
tagVariants[variant as TagVariant].color
) as string;
return (
<>
<TagCircleContainer
accessibilityLabel={label}
backgroundColor={bgColor}
{...props}
{...viewTestProps}
>
<Icon
size="s"
name={icon}
backgroundColor="transparent"
lineColor={color}
/>
</TagCircleContainer>
</>
);
};
export type { TagIconProps };
export default TagIcon;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/toastMessage/hooks/useToastAnimation.ts
import { useState, useEffect, useRef, Ref } from "react";
import { Animated, View, Platform } from "react-native";
import { easeExpInOut } from "d3-ease";
const useNativeDriver = Platform.OS !== "web";
const useToastAnimation = (
toastRef: Ref<View>,
duration: number,
autoHide: boolean,
onHide?: () => void
) => {
const opacity = useRef(new Animated.Value(0)).current;
const [isAnimating, setIsAnimating] = useState(false);
const [showTimeout, setShowTimeout] = useState(0);
const [hideTimeout, setHideTimeout] = useState(0);
useEffect(
() => () => {
clearTimeout(showTimeout);
clearTimeout(hideTimeout);
},
[showTimeout, hideTimeout]
);
const show = () => {
clearTimeout(showTimeout);
if (isAnimating) return;
clearTimeout(hideTimeout);
setIsAnimating(true);
if (
typeof toastRef !== "function" &&
typeof toastRef?.current?.setNativeProps === "function"
) {
toastRef?.current?.setNativeProps({
pointerEvents: "auto"
});
}
Animated.timing(opacity, {
useNativeDriver,
toValue: 1,
duration: 300,
easing: easeExpInOut
}).start(({ finished }) => {
if (finished) {
setIsAnimating(false);
// @ts-ignore
if (autoHide) setHideTimeout(setTimeout(() => hide(), duration));
}
});
};
const hide = () => {
clearTimeout(showTimeout);
clearTimeout(hideTimeout);
if (isAnimating) return;
if (
typeof toastRef !== "function" &&
typeof toastRef?.current?.setNativeProps === "function"
) {
toastRef?.current?.setNativeProps({
pointerEvents: "none"
});
}
Animated.timing(opacity, {
useNativeDriver,
toValue: 0,
duration: 500,
easing: easeExpInOut
}).start(({ finished }) => {
if (finished) {
setIsAnimating(false);
if (typeof onHide === "function") onHide();
}
});
};
return {
opacity,
show,
hide,
isAnimating,
setIsAnimating,
setShowTimeout,
setHideTimeout
};
};
export default useToastAnimation;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/toastMessage/messageContainer.tsx
import React, { useState, useEffect, useRef, useContext } from "react";
import {
Platform,
Keyboard,
Animated,
LayoutChangeEvent,
StyleSheet,
View,
EmitterSubscription,
GestureResponderEvent
} from "react-native";
import { useQaLabel } from "../../hooks/useQaLabel";
import { ToastMessageProps } from "./types";
import useToastAnimation from "./hooks/useToastAnimation";
import AlertInline from "../alertInline";
import { TvgConfContext } from "../../utils/tvgConfProvider";
export const durations = {
SHORT: 5000,
LONG: 10000
};
export const bottomOffsets = {
SHORT: 20,
TALL: 68
};
export const ToastMessage = ({
isVisible = true,
autoHide = true,
onHide,
delay = 0,
duration,
topOffset = 76,
bottomOffset = bottomOffsets.SHORT,
keyboardOffset = 15,
position = "bottom",
hasDismissButton = false,
qaLabel = "toastMessage",
isFromDSManager = false,
isFullWidth = true,
icon,
onClick,
...rest
}: ToastMessageProps) => {
const { device } = useContext(TvgConfContext);
const toastDuration =
duration ?? ((rest.title && durations.LONG) || durations.SHORT);
const toastRef = useRef<View>(null);
const { opacity, show, hide, setShowTimeout } = useToastAnimation(
toastRef,
toastDuration,
autoHide,
onHide
);
const [height, setHeight] = useState(60);
const [keyboardHeight, setKeyboardHeight] = useState(0);
const [isKeyboardVisible, setIsKeyboardVisible] = useState(false);
useEffect(() => {
let keyboardDidShowListener: EmitterSubscription;
let keyboardDidHideListener: EmitterSubscription;
if (Platform.OS === "ios") {
keyboardDidShowListener = Keyboard.addListener(
"keyboardDidShow",
keyboardDidShow
);
keyboardDidHideListener = Keyboard.addListener(
"keyboardDidHide",
keyboardDidHide
);
}
return () => {
if (keyboardDidShowListener || keyboardDidHideListener) {
keyboardDidShowListener.remove();
keyboardDidHideListener.remove();
}
};
}, []);
useEffect(() => {
if (isVisible) {
// @ts-ignore
setShowTimeout(setTimeout(() => show(), delay));
} else {
hide();
}
}, [isVisible, isKeyboardVisible]);
// @ts-ignore
const keyboardDidShow = (event) => {
setIsKeyboardVisible(true);
setKeyboardHeight(event.endCoordinates?.height);
};
const keyboardDidHide = () => {
setIsKeyboardVisible(false);
setKeyboardHeight(0);
};
const onLayout = (e: LayoutChangeEvent) => {
setHeight(e.nativeEvent.layout.height);
};
const offset =
position === "bottom"
? (isKeyboardVisible && keyboardOffset + keyboardHeight) || bottomOffset
: topOffset;
const range = [height, -offset];
const outputRange =
position === "bottom" ? range : range.map((value) => -value);
const translateY = opacity.interpolate({
inputRange: [0, 1],
outputRange
});
const dismissPressHandler = (e: GestureResponderEvent) => {
hide();
if (rest.onDismissPress) {
rest.onDismissPress(e);
}
};
const deviceStyles = StyleSheet.create({
mobile: {
justifyContent: "center",
flex: 1,
left: 0,
right: 0,
marginRight: 12,
marginLeft: 12
},
tablet:
Platform.OS === "web"
? {
justifyContent: "center",
left: 0,
right: 0,
margin: "auto",
width: 351
}
: {
width: 351,
flex: 1,
alignSelf: "center",
justifyContent: "center"
},
desktop: {
justifyContent: "center",
left: 0,
right: 0,
margin: "auto",
width: 351
}
} as const);
const messagePosition = position === "bottom" ? { bottom: 0 } : { top: 0 };
return (
<Animated.View
style={[
{ opacity, transform: [{ translateY }] },
isFromDSManager ? styleForDsToastManager.base : style.base,
deviceStyles[device],
messagePosition
]}
pointerEvents={isVisible ? "auto" : "none"}
onLayout={onLayout}
ref={toastRef}
{...useQaLabel(qaLabel)}
>
<AlertInline
type="toast"
variant={rest.variant}
title={rest.title}
message={rest.message}
actionLink={rest.actionLink}
hasRoundedStyle={rest.hasRoundedStyle}
onDismissPress={hasDismissButton ? dismissPressHandler : undefined}
hasDismissAnimation={false}
qaLabel={`${qaLabel}-message`}
isFullWidth={isFullWidth}
icon={icon}
onClick={onClick}
/>
</Animated.View>
);
};
const style = StyleSheet.create({
base: {
// @ts-ignore
position: Platform.OS === "web" ? "relative" : "absolute",
zIndex: 99999
}
});
const styleForDsToastManager = StyleSheet.create({
base: {
// @ts-ignore
position: Platform.OS === "web" ? "fixed" : "absolute",
zIndex: 99999
}
});
export default ToastMessage;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/toastMessage/toastManager.tsx
import React, { Component } from "react";
import ReactDOM from "react-dom";
import { isEqual } from "lodash";
import ToastMessage from "./messageContainer";
import { ToastMessageProps, ToastOptions } from "./types";
export interface ToastState extends ToastOptions {
/** If toast message is visible */
isVisible: boolean;
}
class ToastManager extends Component<ToastMessageProps, ToastState> {
static displayName = "ToastManager";
static ref: ToastManager | null = null;
static setRef(ref: ToastManager | null) {
ToastManager.ref = ref;
}
static getRef() {
return ToastManager.ref;
}
static clearRef() {
ToastManager.ref = null;
}
static show(options: ToastMessageProps) {
ToastManager.ref?.show(options);
}
static hide() {
ToastManager.ref?.hide();
}
root: Element | null = null;
el: Element | null = null;
constructor(props: ToastMessageProps) {
super(props);
this.state = {
variant: props.variant,
message: props.message,
isVisible: props.isVisible !== undefined ?? false
};
this.hide = this.hide.bind(this);
}
componentDidMount() {
if (typeof window !== "undefined") {
this.el = document.createElement("div");
this.root = document.body;
this.root.appendChild(this.el);
}
}
shouldComponentUpdate(nextProps: ToastMessageProps, nextState: ToastState) {
return !isEqual(nextProps, this.props) || !isEqual(nextState, this.state);
}
componentWillUnmount = () => {
if (this.el && this.state.isVisible) this.root?.removeChild(this.el);
};
show = (options: ToastOptions) => {
this.setState({
...options,
isVisible: true
});
};
hide = () => {
if (this.state.isVisible) {
this.setState({ isVisible: false });
}
};
render() {
if (typeof window === undefined || !this.el) return null;
return ReactDOM.createPortal(
<ToastMessage
{...this.props}
{...this.state}
onHide={this.hide}
qaLabel="toast-portal"
isFromDSManager
/>,
this.el
);
}
}
export { ToastManager };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/toastMessage/index.tsx
import React from "react";
import { ToastMessage, bottomOffsets, durations } from "./messageContainer";
import { ToastManager } from "./toastManager";
import { ToastMessageProps, ToastMessageLinkProps } from "./types";
import { AlertInline } from "../alertInline";
const ToastMessageLink = (props: ToastMessageLinkProps) => (
<AlertInline.Link type="toast" {...props} />
);
export default ToastMessage;
export {
ToastMessage,
ToastMessageLink,
ToastManager,
bottomOffsets,
durations
};
export type { ToastMessageProps };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/tooltip/index.tsx
import React, { FC } from "react";
import { TooltipProps } from "./types";
import Popper from "../popper";
import Paragraph from "../typography/paragraph";
import { Content as StyledContent } from "./styled-components";
export const Tooltip: FC<TooltipProps> = ({
children,
content,
placement = "top-mid",
isDarkMode = false,
isDisabled = false,
qaLabel,
layer = 1999,
...rest
}) => (
<Popper
on="hover"
placement={placement}
isDisabled={isDisabled}
layer={layer}
content={
<StyledContent
qaLabel={qaLabel}
variant={isDarkMode ? "light" : "dark"}
placement={placement}
{...rest}
>
<Paragraph
color={isDarkMode ? "blue.900" : "white.900"}
qaLabel="tooltip-text"
fontSize="xs"
>
{content}
</Paragraph>
</StyledContent>
}
>
{children}
</Popper>
);
export * from "./types";
export default Tooltip;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/tooltip/styled-components.ts
import styled from "styled-components/native";
import { View } from "react-native";
import { compose, variant } from "../../theming/styledSystem";
import { TooltipContentProps } from "./types";
import { useQaLabel } from "../../hooks/useQaLabel";
const styles = compose(
variant({
prop: "variant",
variants: {
dark: {
backgroundColor: "blue_accent.900"
},
light: {
backgroundColor: "white.900"
}
}
})
);
export const Content = styled(View).attrs<TooltipContentProps>((props) => ({
...(props.qaLabel && useQaLabel(props.qaLabel))
}))<TooltipContentProps>`
${styles};
border-radius: ${({ theme }) => theme.radii.s};
padding: ${({ theme }) => theme.space["space-3"]};
margin: ${({ theme }) => theme.space["space-1"]};
box-shadow: ${({ theme }) => theme.elevations.medium};
justify-content: center;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/tooltipDescriptive/styled-components.ts
import styled from "styled-components/native";
import { rgba } from "polished";
import { View } from "react-native";
import {
color,
background,
space,
borderRadius,
width,
compose,
variant
} from "../../theming/styledSystem";
import { TooltipDescriptiveWrapperProps } from "./types";
const OFFSET_SPACE: string = "space-3";
const styles = compose(
color,
background,
space,
borderRadius,
width,
variant({
prop: "placement",
variants: {
top: { marginBottom: OFFSET_SPACE },
bottom: { marginTop: OFFSET_SPACE },
left: { marginRight: OFFSET_SPACE },
right: { marginLeft: OFFSET_SPACE }
}
})
);
export const Wrapper = styled(View)<
TooltipDescriptiveWrapperProps & { isSmall: boolean }
>`
${styles};
box-shadow: 0 4px 4px ${({ theme }) => rgba(theme.colors.black[900], 0.14)};
margin: ${({ theme }) => theme.space["space-1"]};
${({ isSmall }) => isSmall && "margin-right: 48px"};
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/tvBrand/styled-components.ts
import styled from "styled-components/native";
import { space } from "styled-system";
import { Svg } from "react-native-svg";
export const StyledSvg = styled(Svg)`
${space}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/typography/header/styled-components.ts
import styled from "styled-components/native";
import { Text } from "react-native";
import {
color,
space,
variant,
compose,
layout,
system,
typography
} from "styled-system";
import { HeaderProps } from "./types";
const systemProps = system({
textTransform: {
property: "textTransform"
},
whiteSpace: {
property: "whiteSpace"
},
textOverflow: {
property: "textOverflow"
}
});
const styles = compose(
color,
space,
systemProps,
typography,
layout,
variant({
prop: "tag",
scale: "headingSizes"
})
);
export const StyledHeader = styled(Text).attrs<HeaderProps>(
({ tag, textOverflow }) => ({
accessibilityLevel: tag && tag.replace("h", ""),
overflow: textOverflow === "ellipsis" ? "hidden" : "visible"
})
)<HeaderProps>`
${styles}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/typography/header/index.tsx
import React, { FC, memo } from "react";
import { useQaLabel } from "../../../hooks";
import { StyledHeader } from "./styled-components";
import { HeaderProps } from "./types";
const Header: FC<HeaderProps> = memo(
({
children,
fontFamily = "medium",
textOverflow = "clip",
whiteSpace = "normal",
color = "grey.900",
tag = "h1",
qaLabel = "header",
...rest
}) => (
<StyledHeader
accessibilityRole="header"
fontFamily={fontFamily}
color={color}
tag={tag}
textOverflow={textOverflow}
whiteSpace={whiteSpace}
{...useQaLabel(qaLabel)}
{...rest}
>
{children}
</StyledHeader>
)
);
export { Header };
export type { HeaderProps };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/typography/paragraph/styled-components.ts
import styled from "styled-components/native";
import { Text } from "react-native";
import {
space,
color,
system,
compose,
fontFamily,
fontSize,
flex,
layout,
typography
} from "../../../theming/styledSystem";
import { useQaLabel } from "../../../hooks/useQaLabel";
import { getAccessibilityRole } from "../../../utils/accessibility";
import { ParagraphProps } from "./types";
const lineHeightNormal = system({
fontSize: {
property: "lineHeight",
scale: "lineHeights"
}
});
const lineHeightTaller = system({
fontSize: {
property: "lineHeight",
scale: "lineHeightsTaller"
}
});
const transformText = system({
textTransform: {
property: "textTransform"
},
whiteSpace: {
property: "whiteSpace"
},
textOverflow: {
property: "textOverflow"
}
});
const styles = compose(
space,
color,
fontFamily,
fontSize,
transformText,
typography,
layout
);
export const Paragraph = styled(Text).attrs<ParagraphProps>((props) => ({
ref: props.ref,
accessibilityRole: getAccessibilityRole("paragraph"),
overflow: props.textOverflow === "ellipsis" ? "hidden" : "visible",
width: props.textOverflow === "ellipsis" ? "100%" : "auto",
...useQaLabel(props.qaLabel)
}))<ParagraphProps>`
${(props) => (props.isLineHigher ? lineHeightTaller : lineHeightNormal)}
${styles};
${flex}
`;
Paragraph.defaultProps = {
fontFamily: "regular",
fontSize: "s",
isLineHigher: false,
color: "grey.900"
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/typography/paragraph/index.tsx
import { ParagraphProps } from "./types";
import { Paragraph } from "./styled-components";
export { Paragraph };
export type { ParagraphProps };
export default Paragraph;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/components/webScrollbar/styled-components.ts
import styled, { css } from "styled-components";
import { layout, position, space } from "styled-system";
import {
WebScrollbarProps,
OverflowProps,
ScrollOrientation,
ScrollContainerProps,
ShadowWrapperProps
} from "./types";
const scrollStyle = ({ scrollOrientation, overflow }: OverflowProps) => {
const orientation = {
horizontal: css`
overflow-x: ${overflow};
overflow-y: hidden;
`,
vertical: css`
overflow-y: ${overflow};
overflow-x: hidden;
`,
both: css`
overflow-x: ${overflow};
overflow-y: ${overflow};
`
};
return orientation[scrollOrientation as ScrollOrientation];
};
export const ScrollWrapper = styled.div`
position: relative;
width: 100%;
height: 100%;
margin-left: auto;
margin-right: auto;
overflow: auto;
`;
export const ScrollbarContainer = styled.div<
Pick<
WebScrollbarProps,
| "width"
| "height"
| "isDark"
| "scrollOrientation"
| "overflow"
| "bg"
| "scrollInternalPadding"
> &
ScrollContainerProps
>`
background-color: ${({ bg }) => bg};
${space}
padding-bottom:${({ scrollX, scrollInternalPadding }) =>
scrollX ? `${scrollInternalPadding}px` : "0"};
padding-right: ${({ scrollY, scrollInternalPadding }) =>
scrollY ? `${scrollInternalPadding}px` : "0"};
${layout}
${({ scrollOrientation = "vertical", overflow = "auto" }) =>
scrollStyle({ scrollOrientation, overflow })}
${position}
/* width */
::-webkit-scrollbar {
width: 7px;
}
/* Track */
::-webkit-scrollbar-track {
background: transparent;
box-shadow: none;
}
/* Handle */
::-webkit-scrollbar-thumb {
background: ${({ isDark }) =>
isDark ? "rgba(255, 255, 255, 0.5)" : "rgba(56, 64, 72, 0.5)"};
border-radius: 12px;
}
/* Handle on hover */
::-webkit-scrollbar-thumb:hover {
background: ${({ isDark }) =>
isDark ? "rgba(255, 255, 255, 0.8)" : "rgba(56, 64, 72, 0.8)"};
}
`;
const shadowTop = css<ShadowWrapperProps>`
&::before {
content: "";
box-shadow: inset 0 3px 3px rgba(17, 43, 68, 0.25);
display: flex;
height: 16px;
left: -2px;
pointer-events: none;
position: absolute;
width: calc(${({ width }) => width || "100%"} + 4px);
z-index: 1000;
overflow: hidden;
}
`;
const shadowBottom = css<ShadowWrapperProps>`
&::after {
content: "";
box-shadow: inset 0 -3px 3px rgba(17, 43, 68, 0.25);
display: flex;
height: 16px;
left: -2px;
margin-top: -16px;
pointer-events: none;
position: absolute;
width: calc(${({ width }) => width || "100%"} + 4px);
z-index: 999;
}
`;
export const ShadowWrapper = styled.div<ShadowWrapperProps>`
${space}
${layout}
max-height: ${({ maxHeight }) => maxHeight};
${({ scrollPosition, scrollY }) =>
(scrollPosition === "bottom" || scrollPosition === "mid") && scrollY
? shadowTop
: ""}
${({ scrollPosition, scrollY }) =>
(scrollPosition === "top" || scrollPosition === "mid") && scrollY
? shadowBottom
: ""}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/hooks/useDebounce.ts
import { MutableRefObject, useCallback, useEffect, useRef } from "react";
const useDebounce = () => {
const timeoutRef: MutableRefObject<number> = useRef(0);
const debounce = useCallback(
(fn: () => void, delay: number = 100) =>
() => {
clearTimeout(timeoutRef.current);
// @ts-ignore
timeoutRef.current = setTimeout(() => {
fn();
}, delay);
},
[]
);
useEffect(
() => () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
},
[]
);
return debounce;
};
export default useDebounce;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/hooks/useIconSize.ts
import { iconSizes } from "../theming/themes/common/iconSizes";
import { IconSizeVariants, IconSizeProps } from "../theming/types";
const useIconSize = (size: IconSizeVariants): IconSizeProps =>
iconSizes[size as IconSizeVariants];
export default useIconSize;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/hooks/useMediaQuery.ts
import { useEffect, useState } from "react";
const useMediaQuery = (query: string): boolean => {
const getMatches = (mediaQuery: string): boolean => {
// Prevents SSR issues
if (typeof window !== "undefined") {
return window.matchMedia(mediaQuery).matches;
}
return false;
};
const [matches, setMatches] = useState<boolean>(getMatches(query));
const handleChange = () => {
setMatches(getMatches(query));
};
useEffect(() => {
const matchMedia = window.matchMedia(query);
// Triggered at the first client-side load and if query changes
handleChange();
matchMedia.addEventListener("change", handleChange);
return () => matchMedia.removeEventListener("change", handleChange);
}, [query]);
return matches;
};
export default useMediaQuery;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/hooks/useWebKeyPress.ts
/*
Used to check if a key is being pressed or not on the web.
Usage:
const escPress = useWebKeyPress("Escape");
*/
import { useState, useEffect } from "react";
import { Platform } from "react-native";
export function useWebKeyPress(targetKey: string): boolean {
if (
// only work in browser
Platform.OS !== "web"
) {
return false;
}
const [keyPressed, setKeyPressed] = useState(false);
function downHandler({ key }: { key: string }): void {
if (key === targetKey) {
setKeyPressed(true);
}
}
const upHandler = ({ key }: { key: string }): void => {
if (key === targetKey) {
setKeyPressed(false);
}
};
// Add event listeners
// eslint-disable-next-line consistent-return
useEffect(() => {
if (document) {
document.addEventListener("keydown", downHandler);
document.addEventListener("keyup", upHandler);
// Remove event listeners on cleanup
return () => {
document.removeEventListener("keydown", downHandler);
document.removeEventListener("keyup", upHandler);
};
}
}, []);
return keyPressed;
}
export default useWebKeyPress;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/hooks/useEvents.ts
import { useState } from "react";
import { GestureResponderEvent, NativeSyntheticEvent } from "react-native";
export interface EventsState {
isHovered?: boolean;
isPressed?: boolean;
isFocused?: boolean;
isSelected?: boolean;
}
export const useEvents = <T>(
{
isHovered = false,
isPressed = false,
isFocused = false,
isSelected = false
}: EventsState,
enable = true
) => {
const [events, setEvents] = useState<Required<EventsState>>({
isHovered,
isPressed,
isFocused,
isSelected
});
const mouseEnterHandler = (event: GestureResponderEvent) => {
event.persist();
if (enable) setEvents({ ...events, isHovered: true });
};
const mouseLeaveHandler = (event: GestureResponderEvent) => {
event.persist();
if (enable) setEvents({ ...events, isHovered: false, isPressed: false });
};
const pressInHandler = (event: GestureResponderEvent) => {
event.persist();
if (enable) setEvents({ ...events, isPressed: true });
};
const pressOutHandler = () => {
if (enable) setEvents({ ...events, isPressed: false });
};
const focusHandler = (
event: GestureResponderEvent | NativeSyntheticEvent<T>
) => {
event.persist();
if (enable) setEvents({ ...events, isFocused: true });
};
const blurHandler = (event: NativeSyntheticEvent<T>) => {
event.persist();
if (enable) setEvents({ ...events, isFocused: false });
};
const hoverHandlers = {
onMouseEnter: mouseEnterHandler,
onMouseLeave: mouseLeaveHandler
};
const pressHandlers = {
onMouseDown: pressInHandler,
onMouseUp: pressOutHandler,
onPressIn: pressInHandler,
onPressOut: pressOutHandler,
onTouchStart: pressInHandler,
onTouchEnd: pressOutHandler
};
const focusHandlers = {
onFocus: focusHandler,
onBlur: blurHandler
};
const eventsHandlers = {
...hoverHandlers,
...pressHandlers,
...focusHandlers
};
return {
events,
setEvents,
eventsHandlers,
hoverHandlers,
pressHandlers,
focusHandlers
};
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/hooks/useQaLabel.ts
import { Platform } from "react-native";
type QaLabelWeb = { dataSet: { "qa-label": string } };
type QaLabelNative = { "data-qa-label": string };
/**
* Web and Native require different implementations of the data-qa-label this hook encapsulates that logic
*
* Usage:
* const elementTestProps = useQaLabel('element-label-goes-here')
* <Element {...elementTestProps} />
*/
export const useQaLabel = (label: string): QaLabelWeb | QaLabelNative =>
Platform.OS === "web"
? { dataSet: { "qa-label": label } }
: { "data-qa-label": label };
export default useQaLabel;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/hooks/useQaLabelActive.ts
import { Platform } from "react-native";
type QaLabelActiveWeb = {
dataSet: { "qa-label": string; "qa-active": string };
};
type QaLabelActiveNative = {
"data-qa-label": string;
"data-qa-active": string;
};
/**
* Web and Native require different implementations of the data-qal-label and data-qa-active, this hook encapsulates that logic
*
* Usage:
* const elementTestProps = useQaLabelActive('qa-label-goes-here', 'active-label-goes-here')
* <Element {...elementTestProps} />
*/
export const useQaLabelActive = (
qaLabel: string,
activeLabel: string
): QaLabelActiveWeb | QaLabelActiveNative =>
Platform.OS === "web"
? { dataSet: { "qa-label": qaLabel, "qa-active": activeLabel } }
: { "data-qa-label": qaLabel, "data-qa-active": activeLabel };
export default useQaLabelActive;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/theming/components/constants.ts
import { DESKTOP_THEME, MOBILE_THEME } from "../themes";
import { DeviceTheme } from "./types";
export const DEFAULT_THEME_KEY: "mobile" = "mobile";
export const THEME_MAP: DeviceTheme = {
desktop: DESKTOP_THEME,
mobile: MOBILE_THEME,
tablet: MOBILE_THEME
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/theming/components/themeProvider.tsx
import React, { useContext } from "react";
import { ThemeProvider } from "styled-components/native";
import { TvgConfContext } from "../../utils/tvgConfProvider";
import { Theme } from "../types";
import { DEFAULT_THEME_KEY, THEME_MAP } from "./constants";
import { TVGThemeProviderProps } from "./types";
export const TVGThemeProvider: React.FC<TVGThemeProviderProps> = ({
children,
device
}) => {
const { device: deviceInContext } = useContext(TvgConfContext);
const theme =
(device && THEME_MAP[device]) ||
(deviceInContext && THEME_MAP[deviceInContext]) ||
THEME_MAP[DEFAULT_THEME_KEY];
return <ThemeProvider theme={theme as Theme}>{children}</ThemeProvider>;
};
export default TVGThemeProvider;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/theming/hooks/useColorTokens.ts
import { useContext } from "react";
import { get } from "lodash";
import { ThemeContext } from "styled-components/native";
export const useColorTokens = (value?: string) => {
const useTheme = () => useContext(ThemeContext);
const { colorTokens } = useTheme();
if (value) {
const tokenValue = get(colorTokens, value);
if (!tokenValue && process.env.NODE_ENV !== "production") {
throw new Error(`Invalid color token: ${value}`);
}
return tokenValue;
}
return colorTokens;
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/theming/components/themeProviderWeb.tsx
import React, { useContext } from "react";
import { ThemeProvider as ThemeProviderWeb } from "styled-components";
import { ThemeProvider } from "styled-components/native";
import { TvgConfContext } from "../../utils/tvgConfProvider";
import { fanduelColorTokens, tvgColorTokens } from "../themes/tokens";
import { DEFAULT_THEME_KEY, THEME_MAP } from "./constants";
import { Theme } from "../types";
import { TVGThemeProviderProps } from "./types";
/**
* Until we remove react-native-web, we need to wrap the ThemeProvider from
* styled-components with the ThemeProvider from styled-components/native
* to pass the theme to the web components.
*/
export const TVGThemeProviderWeb: React.FC<TVGThemeProviderProps> = ({
children,
device,
isFanduelTheme
}) => {
const { device: deviceInContext } = useContext(TvgConfContext);
const colorTokens = isFanduelTheme ? fanduelColorTokens : tvgColorTokens;
const theme =
(device && THEME_MAP[device]) ||
(deviceInContext && THEME_MAP[deviceInContext]) ||
THEME_MAP[DEFAULT_THEME_KEY];
return (
<ThemeProviderWeb theme={{ ...theme, colorTokens } as Theme}>
<ThemeProvider theme={{ ...theme, colorTokens } as Theme}>
{children}
</ThemeProvider>
</ThemeProviderWeb>
);
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/theming/hooks/useTheme.ts
import { useContext } from "react";
import { ThemeContext } from "styled-components/native";
import { Theme } from "../types";
const useTheme = (): Theme => useContext(ThemeContext);
export default useTheme;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/theming/hooks/useColor.ts
import useTheme from "./useTheme";
import { Colors } from "../types";
/**
* Get hexadecimal color from theme based on the token
* @param token - e.g., "green.500"
* @returns hexadecimal color - e.g., "#38AB4F"
*/
export const useColor = (token: string): string => {
const { colors } = useTheme();
const [color, variation] = token.split(".");
const [, codeColor] = Object.entries(colors[color as keyof Colors]).filter(
(val) => val[0] === variation
)[0];
return codeColor;
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/theming/themes/common/colors.ts
import { Colors } from "../../types";
export const colors: Colors = {
blue_accent: {
"000": "#FAFCFF",
"100": "#EBF5FF",
"200": "#CDDFFA",
"300": "#AFCCFA",
"400": "#87B2F5",
"500": "#5390ED",
"600": "#3574D4",
"700": "#2F67BD",
"800": "#2959A3",
"900": "#1C3D70"
},
green: {
"000": "#F5FFF7",
"100": "#CEEBD4",
"200": "#B1DEBA",
"300": "#90D19D",
"400": "#69BF7A",
"500": "#38AB4F",
"600": "#329A47",
"700": "#2D873F",
"800": "#246F33",
"900": "#195024"
},
yellow: {
"000": "#FFF6E0",
"100": "#FFECBF",
"200": "#FFE099",
"300": "#FFD470",
"400": "#FFC642",
"500": "#FFB80C",
"600": "#E6A40A",
"700": "#CA9008",
"800": "#A87707",
"900": "#795605"
},
blue: {
"000": "#E9EFF5",
"100": "#D6E3F0",
"200": "#B7CCE1",
"300": "#92B0CE",
"400": "#668FB8",
"500": "#27619B",
"600": "#23568A",
"700": "#1E4B79",
"800": "#193D62",
"900": "#112B44"
},
orange: {
"000": "#FFF3E6",
"100": "#FFE6CC",
"200": "#FAD5AF",
"300": "#F5C089",
"400": "#F0A556",
"500": "#ED850C",
"600": "#D67A11",
"700": "#BD6909",
"800": "#AD6008",
"900": "#854A06"
},
red: {
"000": "#FCEBEB",
"100": "#F7D5D5",
"200": "#F5BCBC",
"300": "#F09E9E",
"400": "#E87676",
"500": "#DE3131",
"600": "#C92C2C",
"700": "#B02727",
"800": "#912020",
"900": "#661616"
},
grey: {
"000": "#F8F8F9",
"100": "#ECEDEE",
"200": "#DEE1E3",
"300": "#CFD2D6",
"400": "#BFC4C8",
"500": "#ADB3B9",
"600": "#99A0A7",
"700": "#818A92",
"800": "#626D78",
"900": "#384048"
},
black: {
"000": "rgba(0, 0, 0, 0.1)",
"100": "rgba(0, 0, 0, 0.2)",
"200": "rgba(0, 0, 0, 0.3)",
"300": "rgba(0, 0, 0, 0.4)",
"400": "rgba(0, 0, 0, 0.5)",
"500": "rgba(0, 0, 0, 0.6)",
"600": "rgba(0, 0, 0, 0.7)",
"700": "rgba(0, 0, 0, 0.8)",
"800": "rgba(0, 0, 0, 0.9)",
"900": "#000000"
},
white: {
"000": "rgba(255, 255, 255, 0.1)",
"100": "rgba(255, 255, 255, 0.2)",
"200": "rgba(255, 255, 255, 0.3)",
"300": "rgba(255, 255, 255, 0.4)",
"400": "rgba(255, 255, 255, 0.5)",
"500": "rgba(255, 255, 255, 0.6)",
"600": "rgba(255, 255, 255, 0.7)",
"700": "rgba(255, 255, 255, 0.8)",
"800": "rgba(255, 255, 255, 0.9)",
"900": "#FFFFFF"
},
tint: {
blue_tint: "#1A4066",
green_tint: "#194546",
yellow_tint: "#414739"
}
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/theming/themes/common/fonts.ts
import { FontWeights, Fonts, FontSizes, LineHeights } from "../../types";
export const fonts: Fonts = {
condensedRegular: "RobotoCondensed-Regular",
regular: "Roboto-Regular",
medium: "Roboto-Medium",
bold: "Roboto-Bold"
};
export const fontSizes: FontSizes = {
xs: "12px",
s: "14px",
m: "16px",
l: "18px",
xl: "20px",
"2xl": "24px",
"3xl": "28px",
"4xl": "32px"
};
export const lineHeights: LineHeights = {
xs: "15px",
s: "18px",
m: "20px",
l: "22px",
xl: "25px",
"2xl": "30px",
"3xl": "35px",
"4xl": "40px"
};
export const lineHeightsShorter = {
xs: "13px",
s: "15px"
};
export const lineHeightsTaller = {
xs: "18px",
s: "21px"
};
export const fontWeights: FontWeights = {
normal: 400,
medium: 500,
bold: 700
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/theming/themes/common/iconSizes.ts
import { IconSizes } from "../../types";
export const iconSizes: IconSizes = {
xs: {
iconSize: "8",
strokeWidth: "2.4"
},
s: {
iconSize: "16",
strokeWidth: "2.3"
},
m: {
iconSize: "20",
strokeWidth: "2.2"
},
l: {
iconSize: "24",
strokeWidth: "2"
},
xl: {
iconSize: "32",
strokeWidth: "1.6"
}
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/theming/themes/common/space.ts
import { Space } from "../../types";
export const space: Space = {
"space-1": "4px",
"space-2": "6px",
"space-3": "8px",
"space-4": "12px",
"space-5": "16px",
"space-6": "20px",
"space-7": "24px",
"space-8": "32px"
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/theming/themes/common/elevations.ts
import { rgba } from "polished";
import { colors } from "./colors";
import { Elevations } from "../../types";
export const elevations: Elevations = {
low: `0px 1px 3px ${rgba(colors.blue["900"], 0.12)}`,
medium: `0px 2px 4px ${rgba(colors.blue["900"], 0.14)}`,
high: `0px 1px 16px ${rgba(colors.blue["900"], 0.25)}`
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/theming/themes/common/buttons.ts
import { Buttons, IconButtons } from "../../types";
import { colors } from "./colors";
import { elevations } from "./elevations";
export const buttons: Buttons = {
primary: {
default: {
background: colors.blue_accent["500"],
border: "none",
boxShadow: elevations.medium,
color: colors.white["900"]
},
hovered: {
background: colors.blue_accent["600"],
boxShadow: elevations.high
},
focused: { background: colors.blue_accent["700"], boxShadow: "0 0 0" },
pressed: { background: colors.blue_accent["700"], boxShadow: "0 0 0" },
loading: { background: colors.white["200"] }
},
secondary: {
default: {
background: colors.white["900"],
border: `1px solid ${colors.blue["100"]}`,
boxShadow: elevations.low,
color: colors.grey["900"]
},
hovered: {
background: colors.blue_accent["000"],
boxShadow: elevations.medium
},
focused: { background: colors.blue_accent["100"], boxShadow: "0 0 0" },
pressed: { background: colors.blue_accent["100"], boxShadow: "0 0 0" },
loading: { background: colors.grey["200"] }
},
secondary_dark: {
default: {
background: colors.white["000"],
border: "none",
color: colors.white["900"]
},
hovered: { background: colors.white["100"] },
focused: { background: colors.white["200"] },
pressed: { background: colors.white["200"] },
loading: { background: colors.white["200"] }
},
tertiary: {
default: {
background: "transparent",
border: "none",
color: colors.blue_accent["500"]
},
hovered: {
background: colors.blue_accent["100"]
},
focused: { background: colors.blue_accent["200"] },
pressed: { background: colors.blue_accent["200"] },
loading: { background: colors.blue_accent["200"] }
},
tertiary_dark: {
default: {
background: "transparent",
border: "none",
color: colors.white["900"]
},
hovered: {
background: colors.white["000"]
},
focused: { background: colors.white["200"] },
pressed: { background: colors.white["200"] },
loading: { background: colors.white["200"] }
},
betting: {
default: {
background: colors.green["500"],
border: "none",
boxShadow: elevations.medium,
color: colors.white["900"]
},
hovered: {
background: colors.green["600"],
boxShadow: elevations.high
},
focused: { background: colors.green["700"], boxShadow: "0 0 0" },
pressed: { background: colors.green["700"], boxShadow: "0 0 0" },
loading: { background: colors.white["200"] }
},
marketing: {
default: {
background: colors.yellow["500"],
border: "none",
boxShadow: elevations.medium,
color: colors.grey["900"]
},
hovered: {
background: colors.yellow["600"],
boxShadow: elevations.high
},
focused: { background: colors.yellow["700"], boxShadow: "0 0 0" },
pressed: { background: colors.yellow["700"], boxShadow: "0 0 0" },
loading: { background: colors.grey["200"] }
},
danger: {
default: {
background: colors.red["500"],
border: "none",
boxShadow: elevations.medium,
color: colors.white["900"]
},
hovered: {
background: colors.red["600"],
boxShadow: elevations.high
},
focused: { background: colors.red["700"], boxShadow: "0 0 0" },
pressed: { background: colors.red["700"], boxShadow: "0 0 0" },
loading: { background: colors.white["200"] }
}
};
export const iconButtons: IconButtons = {
primary: {
...buttons.primary
},
secondary: {
...buttons.secondary
},
secondary_dark: {
...buttons.secondary_dark
},
tertiary: {
default: {
background: "transparent",
border: "none",
color: colors.grey["900"]
},
hovered: {
background: colors.grey["100"]
},
focused: { background: colors.grey["200"] },
pressed: { background: colors.grey["200"] }
},
tertiary_dark: {
...buttons.tertiary_dark
},
betting: {
...buttons.betting
},
danger: {
...buttons.danger
}
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/theming/themes/common/fanduelColorPalette.ts
const core = {
greenL5: "#E9F8EF",
greenL4: "#BCEBCE",
greenL3: "#7FD9A1",
greenL2: "#31C268",
greenL1: "#1BB152",
green: "#128000",
greenD1: "#00732C",
greenD2: "#005D23",
greenD3: "#00491C",
greenD4: "#002E11",
blueL5: "#EAF4FF",
blueL4: "#C8E2FF",
blueL3: "#99CAFF",
blueL2: "#64AEFF",
blueL1: "#2B90FF",
blue: "#0070EB",
blueD1: "#005FC8",
blueD2: "#004EA3",
blueD3: "#003D81",
blueD4: "#002650",
navyL5: "#EDEFF2",
navyL4: "#C6D3E1",
navyL3: "#9CB1CB",
navyL2: "#819CBB",
navyL1: "#6682A2",
navy: "#184C8B",
navyD1: "#14417A",
navyD2: "#103469",
navyD3: "#05285A",
navyD4: "#011638",
redL5: "#FDECED",
redL4: "#F9C9CE",
redL3: "#F198A1",
redL2: "#EA6875",
redL1: "#EB4758",
red: "#D22839",
redD1: "#C8002B",
redD2: "#A40023",
redD3: "#83001C",
redD4: "#40020D",
orangeL5: "#FFF1E6",
orangeL4: "#FFD8B9",
orangeL3: "#FFB77E",
orangeL2: "#FF8C31",
orangeL1: "#F87A1E",
orange: "#C15400",
orangeD1: "#A44800",
orangeD2: "#843B00",
orangeD3: "#692E00",
orangeD4: "#401D00",
yellowL5: "#FFF6BD",
yellowL4: "#FFDC2E",
yellowL3: "#EAC300",
yellowL2: "#C9A800",
yellowL1: "#A98E00",
yellow: "#8A7000",
yellowD1: "#756100",
yellowD2: "#5F4F00",
yellowD3: "#4B3F00",
yellowD4: "#2E2600",
purpleL5: "#F6F1FE",
purpleL4: "#E6D6FE",
purpleL3: "#D4B6FE",
purpleL2: "#C18FFE",
purpleL1: "#B265FE",
purple: "#A530F3",
purpleD1: "#8F02E1",
purpleD2: "#7401B7",
purpleD3: "#61019B",
purpleD4: "#36005B",
tealL5: "#CAFDFF",
tealL4: "#2AF8FF",
tealL3: "#00DCE3",
tealL2: "#00BDC3",
tealL1: "#00A0A5",
teal: "#008085",
tealD1: "#006E72",
tealD2: "#005A5C",
tealD3: "#004649",
tealD4: "#002C2E",
white: "#FFFFFF",
greyL5: "#F7FBFF",
greyL4: "#EAF0F6",
greyL3: "#C9D1DB",
greyL2: "#B0B7BF",
greyL1: "#969DA3",
grey: "#7F848A",
greyD1: "#6A6F73",
greyD2: "#2D2F30",
greyD3: "#1D1E1F",
greyD4: "#131314",
black: "#0A0A0A",
transparentBlack: "rgba(10, 10, 10, 0)",
blackTint005: "rgba(10, 10, 10, 0.05)",
blackTint010: "rgba(10, 10, 10, 0.10)",
blackTint020: "rgba(10, 10, 10, 0.20)",
blackTint030: "rgba(10, 10, 10, 0.30)",
blackTint040: "rgba(10, 10, 10, 0.40)",
blackTint050: "rgba(10, 10, 10, 0.50)",
blackTint060: "rgba(10, 10, 10, 0.60)",
blackTint070: "rgba(10, 10, 10, 0.70)",
blackTint080: "rgba(10, 10, 10, 0.80)",
blackTint090: "rgba(10, 10, 10, 0.90)",
transparentWhite: "rgba(255, 255, 255, 0)",
whiteTint005: "rgba(255, 255, 255, 0.05)",
whiteTint010: "rgba(255, 255, 255, 0.10)",
whiteTint020: "rgba(255, 255, 255, 0.20)",
whiteTint030: "rgba(255, 255, 255, 0.30)",
whiteTint040: "rgba(255, 255, 255, 0.40)",
whiteTint050: "rgba(255, 255, 255, 0.50)",
whiteTint060: "rgba(255, 255, 255, 0.60)",
whiteTint070: "rgba(255, 255, 255, 0.70)",
whiteTint080: "rgba(255, 255, 255, 0.80)",
whiteTint090: "rgba(255, 255, 255, 0.90)"
} as const;
const brand = {
primary: {
default: core.blue,
tint: core.blueL4,
shade: core.blueD2
},
secondary: {
default: core.navyD3,
tint: core.navyL4,
shade: core.navyD4
},
tertiary: {
default: core.yellowL4,
tint: core.yellowL5,
shade: core.yellow
},
decorative: {
sgp: core.yellowL4,
bonus: core.navyD3
},
gradient: {
sports: "linear-gradient(125deg, #005FC8 0%, #003D81 100%)",
gaming: "linear-gradient(125deg, #61019B 0%, #005FC8 100%)"
}
};
export const fanduelColorPalette = {
core,
brand
} as const;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/theming/themes/common/index.ts
import { Radii } from "../../types";
export const breakpoints: Array<string> = [];
export const radii: Radii = {
xs: "2px",
s: "4px",
m: "10px",
l: "12px",
xl: "24px",
"2xl": "48px"
};
export * from "./iconSizes";
export * from "./space";
export * from "./fonts";
export * from "./buttons";
export * from "./elevations";
export * from "./tvgColorPalette";
export * from "./fanduelColorPalette";
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/theming/themes/common/tvgColorPalette.ts
export const tvgColorPalette = {
blue_accent: {
"000": "#FAFCFF",
"100": "#EBF5FF",
"200": "#CDDFFA",
"300": "#AFCCFA",
"400": "#87B2F5",
"500": "#5390ED",
"600": "#3574D4",
"700": "#2F67BD",
"800": "#2959A3",
"900": "#1C3D70"
},
green: {
"000": "#F5FFF7",
"100": "#CEEBD4",
"200": "#B1DEBA",
"300": "#90D19D",
"400": "#69BF7A",
"500": "#38AB4F",
"600": "#329A47",
"700": "#2D873F",
"800": "#246F33",
"900": "#195024"
},
yellow: {
"000": "#FFF6E0",
"100": "#FFECBF",
"200": "#FFE099",
"300": "#FFD470",
"400": "#FFC642",
"500": "#FFB80C",
"600": "#E6A40A",
"700": "#CA9008",
"800": "#A87707",
"900": "#795605"
},
blue: {
"000": "#E9EFF5",
"100": "#D6E3F0",
"200": "#B7CCE1",
"300": "#92B0CE",
"400": "#668FB8",
"500": "#27619B",
"600": "#23568A",
"700": "#1E4B79",
"800": "#193D62",
"900": "#112B44"
},
orange: {
"000": "#FFF3E6",
"100": "#FFE6CC",
"200": "#FAD5AF",
"300": "#F5C089",
"400": "#F0A556",
"500": "#ED850C",
"600": "#D67A11",
"700": "#BD6909",
"800": "#AD6008",
"900": "#854A06"
},
red: {
"000": "#FCEBEB",
"100": "#F7D5D5",
"200": "#F5BCBC",
"300": "#F09E9E",
"400": "#E87676",
"500": "#DE3131",
"600": "#C92C2C",
"700": "#B02727",
"800": "#912020",
"900": "#661616"
},
grey: {
"000": "#F8F8F9",
"100": "#ECEDEE",
"200": "#DEE1E3",
"300": "#CFD2D6",
"400": "#BFC4C8",
"500": "#ADB3B9",
"600": "#99A0A7",
"700": "#818A92",
"800": "#626D78",
"900": "#384048"
},
black: {
"005": "rgba(0, 0, 0, 0.05)",
"000": "rgba(0, 0, 0, 0.1)",
"100": "rgba(0, 0, 0, 0.2)",
"200": "rgba(0, 0, 0, 0.3)",
"300": "rgba(0, 0, 0, 0.4)",
"400": "rgba(0, 0, 0, 0.5)",
"500": "rgba(0, 0, 0, 0.6)",
"600": "rgba(0, 0, 0, 0.7)",
"700": "rgba(0, 0, 0, 0.8)",
"800": "rgba(0, 0, 0, 0.9)",
"900": "#000000"
},
white: {
"005": "rgba(255, 255, 255, 0.05)",
"000": "rgba(255, 255, 255, 0.1)",
"100": "rgba(255, 255, 255, 0.2)",
"200": "rgba(255, 255, 255, 0.3)",
"300": "rgba(255, 255, 255, 0.4)",
"400": "rgba(255, 255, 255, 0.5)",
"500": "rgba(255, 255, 255, 0.6)",
"600": "rgba(255, 255, 255, 0.7)",
"700": "rgba(255, 255, 255, 0.8)",
"800": "rgba(255, 255, 255, 0.9)",
"900": "#FFFFFF"
},
tint: {
transparentBlack: "rgba(0, 0, 0, 0)",
transparentWhite: "rgba(255, 255, 255, 0)",
blue_tint: "#1A4066",
green_tint: "#194546",
yellow_tint: "#414739"
}
} as const;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/theming/themes/desktop.ts
import {
fonts,
fontSizes,
fontWeights,
lineHeights,
lineHeightsShorter,
lineHeightsTaller,
tvgColorPalette as colors,
space,
breakpoints,
radii,
buttons,
iconButtons,
elevations,
iconSizes
} from "./common";
import { tvgColorTokens as colorTokens } from "./tokens";
import { Theme, HeadingSizes } from "../types";
const name = "Desktop";
const headingSizes: HeadingSizes = {
h1: { fontSize: fontSizes["3xl"], lineHeight: lineHeights["3xl"] },
h2: { fontSize: fontSizes.l, lineHeight: lineHeights.l },
h3: { fontSize: fontSizes.m, lineHeight: lineHeights.m }
};
export default {
name,
breakpoints,
colors,
colorTokens,
space,
fonts,
fontSizes,
lineHeights,
lineHeightsShorter,
lineHeightsTaller,
fontWeights,
headingSizes,
radii,
buttons,
iconButtons,
elevations,
iconSizes
} as Theme;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/theming/themes/mobile.ts
import {
fonts,
fontSizes,
fontWeights,
lineHeights,
lineHeightsShorter,
lineHeightsTaller,
tvgColorPalette as colors,
space,
breakpoints,
radii,
buttons,
iconButtons,
elevations,
iconSizes
} from "./common";
import { tvgColorTokens as colorTokens } from "./tokens";
import { Theme, HeadingSizes } from "../types";
const name = "Mobile/Tablet";
const headingSizes: HeadingSizes = {
h1: { fontSize: fontSizes.l, lineHeight: lineHeights.l },
h2: { fontSize: fontSizes.m, lineHeight: lineHeights.m },
h3: { fontSize: fontSizes.m, lineHeight: lineHeights.m }
};
export default {
name,
breakpoints,
colors,
colorTokens,
space,
fonts,
fontSizes,
fontWeights,
lineHeights,
lineHeightsShorter,
lineHeightsTaller,
headingSizes,
radii,
buttons,
iconButtons,
elevations,
iconSizes
} as Theme;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/theming/themes/tokens/fanduelColorTokens.ts
import { fanduelColorPalette } from "../common";
import { ColorTokens } from "./types";
const core = {
transparentBlack: fanduelColorPalette.core.transparentBlack,
blackTint005: fanduelColorPalette.core.blackTint005,
blackTint010: fanduelColorPalette.core.blackTint010,
blackTint020: fanduelColorPalette.core.blackTint020,
blackTint030: fanduelColorPalette.core.blackTint030,
blackTint040: fanduelColorPalette.core.blackTint040,
blackTint050: fanduelColorPalette.core.blackTint050,
blackTint060: fanduelColorPalette.core.blackTint060,
blackTint070: fanduelColorPalette.core.blackTint070,
blackTint080: fanduelColorPalette.core.blackTint080,
blackTint090: fanduelColorPalette.core.blackTint090,
transparentWhite: fanduelColorPalette.core.transparentWhite,
whiteTint005: fanduelColorPalette.core.whiteTint005,
whiteTint010: fanduelColorPalette.core.whiteTint010,
whiteTint020: fanduelColorPalette.core.whiteTint020,
whiteTint030: fanduelColorPalette.core.whiteTint030,
whiteTint040: fanduelColorPalette.core.whiteTint040,
whiteTint050: fanduelColorPalette.core.whiteTint050,
whiteTint060: fanduelColorPalette.core.whiteTint060,
whiteTint070: fanduelColorPalette.core.whiteTint070,
whiteTint080: fanduelColorPalette.core.whiteTint080,
whiteTint090: fanduelColorPalette.core.whiteTint090
};
const content = {
strong: fanduelColorPalette.core.navyD3,
default: fanduelColorPalette.core.greyD4,
subtle: fanduelColorPalette.core.greyD1,
subtle2: fanduelColorPalette.core.grey,
subtle3: fanduelColorPalette.core.greyL2,
disabled: fanduelColorPalette.core.greyL3,
onLight: fanduelColorPalette.core.navyD3,
onDark: fanduelColorPalette.core.white,
link: fanduelColorPalette.core.blueD1,
linkActive: fanduelColorPalette.core.blueD3,
brandPrimary: fanduelColorPalette.brand.primary.default,
brandSecondary: fanduelColorPalette.brand.secondary.default,
info: fanduelColorPalette.core.blueD1,
positive: fanduelColorPalette.core.green,
negative: fanduelColorPalette.core.redD1,
warning: fanduelColorPalette.core.orangeD1,
alert: fanduelColorPalette.core.yellowD1,
neutral: fanduelColorPalette.core.greyD1,
mtp: fanduelColorPalette.core.navyL1,
loadingDefault: fanduelColorPalette.core.blackTint005,
loadingInverse: fanduelColorPalette.core.whiteTint010
};
const component = {
// TODO: REVISION TAGS
tag: {
offer: {
background: fanduelColorPalette.core.yellowL4,
content: fanduelColorPalette.core.navyD3
},
offer_subtle: {
background: fanduelColorPalette.core.yellowL4,
content: fanduelColorPalette.core.navyD3
},
"1stpick": {
background: fanduelColorPalette.core.greenL4,
content: fanduelColorPalette.core.greenD3
},
"2ndpick": {
background: fanduelColorPalette.core.blueL4,
content: fanduelColorPalette.core.blueD3
},
"3rdpick": {
background: fanduelColorPalette.core.orangeL4,
content: fanduelColorPalette.core.orangeD3
},
regular_subtle: {
background: fanduelColorPalette.core.greyL4,
content: fanduelColorPalette.core.greyD1
}
},
button: {
primary: {
content: {
base: fanduelColorPalette.core.white,
hover: fanduelColorPalette.core.white,
active: fanduelColorPalette.core.white,
disabled: fanduelColorPalette.core.greyL2
},
background: {
base: fanduelColorPalette.core.green,
hover: fanduelColorPalette.core.greenD1,
active: fanduelColorPalette.core.greenD2,
disabled: fanduelColorPalette.core.greyL4
}
},
secondary: {
content: {
base: fanduelColorPalette.core.white,
hover: fanduelColorPalette.core.white,
active: fanduelColorPalette.core.white,
disabled: fanduelColorPalette.core.greyL2
},
background: {
base: fanduelColorPalette.core.blue,
hover: fanduelColorPalette.core.blueD1,
active: fanduelColorPalette.core.blueD2,
disabled: fanduelColorPalette.core.greyL4
}
},
tertiary: {
content: {
base: fanduelColorPalette.core.blue,
hover: fanduelColorPalette.core.blue,
active: fanduelColorPalette.core.white,
disabled: fanduelColorPalette.core.greyL2
},
background: {
base: fanduelColorPalette.core.transparentWhite,
hover: fanduelColorPalette.core.blueL5,
active: fanduelColorPalette.core.blue,
disabled: fanduelColorPalette.core.transparentWhite
},
border: {
base: fanduelColorPalette.core.blue,
hover: fanduelColorPalette.core.blue,
active: fanduelColorPalette.core.blue,
disabled: fanduelColorPalette.core.greyL2
}
},
destructive: {
content: {
base: fanduelColorPalette.core.white,
hover: fanduelColorPalette.core.white,
active: fanduelColorPalette.core.white,
disabled: fanduelColorPalette.core.greyL2
},
background: {
base: fanduelColorPalette.core.red,
hover: fanduelColorPalette.core.redD1,
active: fanduelColorPalette.core.redD2,
disabled: fanduelColorPalette.core.greyL4
}
},
buttonLink: {
content: {
base: fanduelColorPalette.core.blue,
hover: fanduelColorPalette.core.blueD1,
active: fanduelColorPalette.core.white,
disabled: fanduelColorPalette.core.greyL2
},
background: {
base: fanduelColorPalette.core.transparentWhite,
hover: fanduelColorPalette.core.blueL5,
active: fanduelColorPalette.core.blueD1,
disabled: "transparent"
},
border: {
disabled: fanduelColorPalette.core.greyL2
}
},
betting: {
content: {
base: fanduelColorPalette.core.white,
hover: fanduelColorPalette.core.white,
active: fanduelColorPalette.core.white,
disabled: fanduelColorPalette.core.greyL2
},
background: {
base: fanduelColorPalette.core.greenL1,
hover: fanduelColorPalette.core.green,
active: fanduelColorPalette.core.greenD1,
disabled: fanduelColorPalette.core.greyL4
}
},
promo: {
content: {
base: fanduelColorPalette.core.navyD3,
hover: fanduelColorPalette.core.navyD3,
active: fanduelColorPalette.core.navyD3,
disabled: fanduelColorPalette.core.greyL2
},
background: {
base: fanduelColorPalette.core.yellowL4,
hover: fanduelColorPalette.core.yellowL3,
active: fanduelColorPalette.core.yellowL2,
disabled: fanduelColorPalette.core.greyL4
}
},
secondaryDark: {
content: {
base: fanduelColorPalette.core.white,
hover: fanduelColorPalette.core.white,
active: fanduelColorPalette.core.white,
disabled: fanduelColorPalette.core.whiteTint030
},
background: {
base: fanduelColorPalette.core.whiteTint010,
hover: fanduelColorPalette.core.whiteTint020,
active: fanduelColorPalette.core.whiteTint030,
disabled: fanduelColorPalette.core.whiteTint010
}
},
transparent: {
content: {
base: fanduelColorPalette.core.white,
hover: fanduelColorPalette.core.white,
active: fanduelColorPalette.core.white,
disabled: fanduelColorPalette.core.navy
},
background: {
base: fanduelColorPalette.core.transparentWhite,
hover: fanduelColorPalette.core.whiteTint010,
active: fanduelColorPalette.core.blue,
disabled: fanduelColorPalette.core.transparentWhite
},
border: {
base: fanduelColorPalette.core.white,
hover: fanduelColorPalette.core.white,
active: fanduelColorPalette.core.transparentWhite,
disabled: fanduelColorPalette.core.navy
}
}
},
notification: {
info: {
background: fanduelColorPalette.core.blueD1,
backgroundSubtle: fanduelColorPalette.core.blueL5,
border: fanduelColorPalette.core.blueD1,
content: fanduelColorPalette.core.navyD3
},
positive: {
background: fanduelColorPalette.core.green,
backgroundSubtle: fanduelColorPalette.core.greenL5,
border: fanduelColorPalette.core.green,
content: fanduelColorPalette.core.navyD3
},
negative: {
background: fanduelColorPalette.core.red,
backgroundSubtle: fanduelColorPalette.core.redL5,
border: fanduelColorPalette.core.red,
content: fanduelColorPalette.core.navyD3
},
warning: {
background: fanduelColorPalette.core.orangeL2,
backgroundSubtle: fanduelColorPalette.core.orangeL5,
border: fanduelColorPalette.core.orangeL1,
content: fanduelColorPalette.core.navyD3
},
promo: {
background: fanduelColorPalette.core.yellowL4,
backgroundSubtle: fanduelColorPalette.core.yellowL5,
border: fanduelColorPalette.core.orangeL3,
content: fanduelColorPalette.core.navyD3
},
geocomply: {
backgroundVerification: fanduelColorPalette.core.purpleD2,
backgroundSuccess: fanduelColorPalette.core.green
}
},
betslip: {
background: fanduelColorPalette.core.navyD2,
backgroundExpanded: fanduelColorPalette.core.navyD4
},
activeGroupedFilterCell: {
content: fanduelColorPalette.core.white,
background: fanduelColorPalette.core.blueD1,
border: fanduelColorPalette.core.blueD1
},
input: {
base: fanduelColorPalette.core.greyL3,
surface: fanduelColorPalette.core.white,
hover: fanduelColorPalette.core.blueL5,
pressed: fanduelColorPalette.core.blueL4,
active: fanduelColorPalette.core.blue,
selected: fanduelColorPalette.core.blueD1,
disabled: fanduelColorPalette.core.greyL4,
border: fanduelColorPalette.core.greyL1
}
};
const background = {
base: fanduelColorPalette.core.greyL4,
surface: fanduelColorPalette.core.white,
layer: fanduelColorPalette.core.greyL5,
accent: fanduelColorPalette.core.blackTint005,
hover: fanduelColorPalette.core.blueL5,
fadeEnd: "linear-gradient(90deg, rgba(255, 255, 255, 0.00) 0%, #FFF 100%)",
fadeBottom:
"linear-gradient(180deg, rgba(255, 255, 255, 0.00) 0%, #FFF 100%)",
primary: fanduelColorPalette.brand.primary.default,
secondary: fanduelColorPalette.brand.secondary.default,
promotional: fanduelColorPalette.core.navyD3,
info: fanduelColorPalette.core.blueD1,
infoSubtle: fanduelColorPalette.core.blueL5,
positive: fanduelColorPalette.core.green,
positiveSubtle: fanduelColorPalette.core.greenL5,
negative: fanduelColorPalette.core.red,
negativeSubtle: fanduelColorPalette.core.redL5,
warning: fanduelColorPalette.core.orangeL1,
warningSubtle: fanduelColorPalette.core.orangeL5,
alert: fanduelColorPalette.core.yellowL4,
alertSubtle: fanduelColorPalette.core.yellowL5,
neutral: fanduelColorPalette.core.greyL2,
neutralSubtle: fanduelColorPalette.core.greyL5
};
const lhnHeader = {
content: {
strong: fanduelColorPalette.core.white,
default: fanduelColorPalette.core.greyL3,
subtle: fanduelColorPalette.core.greyL1,
brandSecondary: fanduelColorPalette.brand.secondary.tint,
positive: fanduelColorPalette.core.greenL2,
negative: fanduelColorPalette.core.redL1
},
border: {
default: fanduelColorPalette.core.whiteTint020,
inverse: fanduelColorPalette.core.greyL4
},
selectedcell: {
border: fanduelColorPalette.core.blue,
background: fanduelColorPalette.core.blueD2
}
};
const border = {
default: fanduelColorPalette.core.greyL3,
subtle: fanduelColorPalette.core.greyL4,
inverse: fanduelColorPalette.core.white,
brand: fanduelColorPalette.brand.primary.default,
info: fanduelColorPalette.core.blueD1,
positive: fanduelColorPalette.core.greenL1,
negative: fanduelColorPalette.core.red,
warning: fanduelColorPalette.core.orangeL1,
alert: fanduelColorPalette.core.yellowL3
};
export const fanduelColorTokens: ColorTokens = {
core,
component,
content,
background,
lhnHeader,
border,
groupedfiltercell: {
background: {
default: fanduelColorPalette.core.transparentWhite,
hover: fanduelColorPalette.core.transparentWhite,
pressed: fanduelColorPalette.core.transparentWhite,
active: fanduelColorPalette.core.blueD1
},
border: {
default: fanduelColorPalette.core.transparentWhite,
hover: fanduelColorPalette.core.greyL3,
pressed: fanduelColorPalette.core.greyL3,
active: fanduelColorPalette.core.greyL3
},
content: {
default: fanduelColorPalette.core.greyD4,
hover: fanduelColorPalette.core.greyD4,
pressed: fanduelColorPalette.core.greyD4,
active: fanduelColorPalette.core.white
}
},
notification: {
info: {
background: fanduelColorPalette.core.blueD1,
backgroundSubtle: fanduelColorPalette.core.blueL5,
border: fanduelColorPalette.core.blueD1
},
positive: {
background: fanduelColorPalette.core.green,
backgroundSubtle: fanduelColorPalette.core.greenL5,
border: fanduelColorPalette.core.green
},
negative: {
background: fanduelColorPalette.core.red,
backgroundSubtle: fanduelColorPalette.core.redL5,
border: fanduelColorPalette.core.red
},
warning: {
background: fanduelColorPalette.core.orangeL2,
backgroundSubtle: fanduelColorPalette.core.orangeL5,
border: fanduelColorPalette.core.orangeL1
}
}
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/theming/themes/tokens/tvgColorTokens.ts
import { tvgColorPalette } from "../common";
import { ColorTokens } from "./types";
const core = {
transparentBlack: tvgColorPalette.tint.transparentBlack,
blackTint005: tvgColorPalette.black["005"],
blackTint010: tvgColorPalette.black["000"],
blackTint020: tvgColorPalette.black["100"],
blackTint030: tvgColorPalette.black["200"],
blackTint040: tvgColorPalette.black["300"],
blackTint050: tvgColorPalette.black["400"],
blackTint060: tvgColorPalette.black["500"],
blackTint070: tvgColorPalette.black["600"],
blackTint080: tvgColorPalette.black["700"],
blackTint090: tvgColorPalette.black["800"],
transparentWhite: tvgColorPalette.tint.transparentWhite,
whiteTint005: tvgColorPalette.white["005"],
whiteTint010: tvgColorPalette.white["000"],
whiteTint020: tvgColorPalette.white["100"],
whiteTint030: tvgColorPalette.white["200"],
whiteTint040: tvgColorPalette.white["300"],
whiteTint050: tvgColorPalette.white["400"],
whiteTint060: tvgColorPalette.white["500"],
whiteTint070: tvgColorPalette.white["600"],
whiteTint080: tvgColorPalette.white["700"],
whiteTint090: tvgColorPalette.white["800"]
};
const content = {
strong: tvgColorPalette.grey["900"],
default: tvgColorPalette.grey["900"],
subtle: tvgColorPalette.grey["800"],
subtle2: tvgColorPalette.grey["700"],
subtle3: tvgColorPalette.grey["500"],
disabled: tvgColorPalette.black["100"],
onLight: tvgColorPalette.grey["900"],
onDark: tvgColorPalette.white["900"],
link: tvgColorPalette.blue_accent["500"],
linkActive: tvgColorPalette.blue_accent["700"],
brandPrimary: tvgColorPalette.blue_accent["500"],
brandSecondary: tvgColorPalette.grey["900"],
info: tvgColorPalette.blue_accent["700"],
positive: tvgColorPalette.green["800"],
negative: tvgColorPalette.red["700"],
warning: tvgColorPalette.orange["900"],
alert: tvgColorPalette.yellow["900"],
neutral: tvgColorPalette.grey["800"],
mtp: tvgColorPalette.blue["400"],
loadingDefault: tvgColorPalette.blue["000"],
loadingInverse: tvgColorPalette.white["000"]
};
const component = {
// TODO: REVISION TAGS
tag: {
offer: {
background: tvgColorPalette.yellow["500"],
content: tvgColorPalette.black["800"]
},
offer_subtle: {
background: tvgColorPalette.yellow["100"],
content: tvgColorPalette.black["900"]
},
"1stpick": {
background: tvgColorPalette.green["100"],
content: tvgColorPalette.green["800"]
},
"2ndpick": {
background: tvgColorPalette.blue["000"],
content: tvgColorPalette.grey["800"]
},
"3rdpick": {
background: tvgColorPalette.orange["100"],
content: tvgColorPalette.orange["900"]
},
regular_subtle: {
background: tvgColorPalette.blue["000"],
content: tvgColorPalette.grey["800"]
}
},
button: {
primary: {
content: {
base: tvgColorPalette.white["900"],
hover: tvgColorPalette.white["900"],
active: tvgColorPalette.white["900"],
disabled: tvgColorPalette.black["200"]
},
background: {
base: tvgColorPalette.green["500"],
hover: tvgColorPalette.green["600"],
active: tvgColorPalette.green["700"],
disabled: tvgColorPalette.blue["000"]
}
},
secondary: {
content: {
base: tvgColorPalette.white["900"],
hover: tvgColorPalette.white["900"],
active: tvgColorPalette.white["900"],
disabled: tvgColorPalette.black["200"]
},
background: {
base: tvgColorPalette.blue_accent["500"],
hover: tvgColorPalette.blue_accent["600"],
active: tvgColorPalette.blue_accent["700"],
disabled: tvgColorPalette.blue["000"]
}
},
tertiary: {
content: {
base: tvgColorPalette.grey["900"],
hover: tvgColorPalette.grey["900"],
active: tvgColorPalette.grey["900"],
disabled: tvgColorPalette.black["200"]
},
background: {
base: tvgColorPalette.white["900"],
hover: tvgColorPalette.blue_accent["000"],
active: tvgColorPalette.blue_accent["100"],
disabled: tvgColorPalette.blue["000"]
},
border: {
base: tvgColorPalette.blue["100"],
hover: tvgColorPalette.blue["100"],
active: tvgColorPalette.blue["100"],
disabled: tvgColorPalette.black["100"]
}
},
destructive: {
content: {
base: tvgColorPalette.white["900"],
hover: tvgColorPalette.white["900"],
active: tvgColorPalette.white["900"],
disabled: tvgColorPalette.black["200"]
},
background: {
base: tvgColorPalette.red["500"],
hover: tvgColorPalette.red["600"],
active: tvgColorPalette.red["700"],
disabled: tvgColorPalette.blue["000"]
}
},
buttonLink: {
content: {
base: tvgColorPalette.blue_accent["500"],
hover: tvgColorPalette.blue_accent["500"],
active: tvgColorPalette.blue_accent["500"],
disabled: tvgColorPalette.black["200"]
},
background: {
base: "transparent",
hover: tvgColorPalette.blue_accent["100"],
active: tvgColorPalette.blue_accent["200"],
disabled: tvgColorPalette.blue["000"]
},
border: {
disabled: "transparent"
}
},
betting: {
content: {
base: tvgColorPalette.white["900"],
hover: tvgColorPalette.white["900"],
active: tvgColorPalette.white["900"],
disabled: tvgColorPalette.black["200"]
},
background: {
base: tvgColorPalette.green["500"],
hover: tvgColorPalette.green["600"],
active: tvgColorPalette.green["700"],
disabled: tvgColorPalette.blue["000"]
}
},
promo: {
content: {
base: tvgColorPalette.grey["900"],
hover: tvgColorPalette.grey["900"],
active: tvgColorPalette.grey["900"],
disabled: tvgColorPalette.black["200"]
},
background: {
base: tvgColorPalette.yellow["500"],
hover: tvgColorPalette.yellow["600"],
active: tvgColorPalette.yellow["700"],
disabled: tvgColorPalette.blue["000"]
}
},
secondaryDark: {
content: {
base: tvgColorPalette.white["900"],
hover: tvgColorPalette.white["900"],
active: tvgColorPalette.white["900"],
disabled: tvgColorPalette.white["200"]
},
background: {
base: tvgColorPalette.white["000"],
hover: tvgColorPalette.white["100"],
active: tvgColorPalette.white["200"],
disabled: tvgColorPalette.white["000"]
}
},
transparent: {
content: {
base: tvgColorPalette.white["900"],
hover: tvgColorPalette.white["900"],
active: tvgColorPalette.white["900"],
disabled: tvgColorPalette.white["200"]
},
background: {
base: tvgColorPalette.white["000"],
hover: tvgColorPalette.white["100"],
active: tvgColorPalette.white["200"],
disabled: tvgColorPalette.white["000"]
},
border: {
base: "transparent",
hover: "transparent",
active: "transparent",
disabled: "transparent"
}
}
},
notification: {
info: {
background: tvgColorPalette.blue_accent["600"],
backgroundSubtle: tvgColorPalette.blue_accent["000"],
border: tvgColorPalette.blue_accent["200"],
content: tvgColorPalette.blue_accent["700"]
},
positive: {
background: tvgColorPalette.green["600"],
backgroundSubtle: tvgColorPalette.green["100"],
border: tvgColorPalette.green["300"],
content: tvgColorPalette.green["800"]
},
negative: {
background: tvgColorPalette.red["500"],
backgroundSubtle: tvgColorPalette.red["000"],
border: tvgColorPalette.red["200"],
content: tvgColorPalette.red["700"]
},
warning: {
background: tvgColorPalette.orange["500"],
backgroundSubtle: tvgColorPalette.orange["000"],
border: tvgColorPalette.orange["200"],
content: tvgColorPalette.orange["900"]
},
promo: {
background: tvgColorPalette.yellow["500"],
backgroundSubtle: tvgColorPalette.yellow["000"],
border: tvgColorPalette.yellow["200"],
content: tvgColorPalette.yellow["900"]
},
geocomply: {
backgroundVerification: tvgColorPalette.blue_accent["600"],
backgroundSuccess: tvgColorPalette.green["600"]
}
},
betslip: {
background: tvgColorPalette.blue["800"],
backgroundExpanded: tvgColorPalette.blue["900"]
},
activeGroupedFilterCell: {
content: tvgColorPalette.blue_accent["700"],
background: tvgColorPalette.blue_accent["100"],
border: tvgColorPalette.blue_accent["500"]
},
input: {
base: tvgColorPalette.grey["300"],
surface: tvgColorPalette.white["900"],
hover: tvgColorPalette.blue_accent["100"],
pressed: tvgColorPalette.blue_accent["200"],
active: tvgColorPalette.blue_accent["500"],
selected: tvgColorPalette.blue_accent["700"],
disabled: tvgColorPalette.blue["000"],
border: tvgColorPalette.blue["100"]
}
};
const background = {
base: tvgColorPalette.blue["000"],
surface: tvgColorPalette.white["900"],
layer: tvgColorPalette.blue_accent["000"],
accent: tvgColorPalette.grey["000"],
hover: tvgColorPalette.blue_accent["100"],
fadeEnd: "linear-gradient(90deg, rgba(255, 255, 255, 0.00) 0%, #FFF 100%)",
fadeBottom:
"linear-gradient(180deg, rgba(255, 255, 255, 0.00) 0%, #FFF 100%)",
primary: tvgColorPalette.blue_accent["500"],
secondary: tvgColorPalette.blue["900"],
promotional: tvgColorPalette.blue["900"],
info: tvgColorPalette.blue_accent["600"],
infoSubtle: tvgColorPalette.blue_accent["100"],
positive: tvgColorPalette.green["600"],
positiveSubtle: tvgColorPalette.green["100"],
negative: tvgColorPalette.red["500"],
negativeSubtle: tvgColorPalette.red["000"],
warning: tvgColorPalette.orange["500"],
warningSubtle: tvgColorPalette.orange["000"],
alert: tvgColorPalette.yellow["500"],
alertSubtle: tvgColorPalette.yellow["000"],
neutral: tvgColorPalette.grey["600"],
neutralSubtle: tvgColorPalette.grey["000"]
};
const lhnHeader = {
content: {
strong: tvgColorPalette.blue["000"],
default: tvgColorPalette.blue["200"],
subtle: tvgColorPalette.white["500"],
brandSecondary: tvgColorPalette.blue["300"],
positive: tvgColorPalette.green["400"],
negative: tvgColorPalette.red["400"]
},
border: {
default: tvgColorPalette.blue["800"],
inverse: tvgColorPalette.blue["600"]
},
selectedcell: {
border: tvgColorPalette.blue["600"],
background: tvgColorPalette.blue["800"]
}
};
const border = {
default: tvgColorPalette.blue["100"],
subtle: tvgColorPalette.blue["000"],
inverse: tvgColorPalette.white["900"],
brand: tvgColorPalette.blue["100"],
info: tvgColorPalette.blue_accent["200"],
positive: tvgColorPalette.green["300"],
negative: tvgColorPalette.red["200"],
warning: tvgColorPalette.orange["200"],
alert: tvgColorPalette.yellow["200"]
};
export const myBets = {
open: {
border: "transparent",
background: "transparent",
dotColor: tvgColorPalette.grey["600"],
textColor: tvgColorPalette.grey["800"],
iconColor: tvgColorPalette.grey["600"],
trackingColor: tvgColorPalette.grey["300"]
},
raceOff: {
border: tvgColorPalette.grey["800"],
background: tvgColorPalette.white["100"],
textColor: tvgColorPalette.grey["900"],
iconColor: tvgColorPalette.grey["800"],
dotColor: tvgColorPalette.grey["800"],
trackingColor: tvgColorPalette.grey["300"]
},
unknown: {
border: tvgColorPalette.grey["800"],
background: tvgColorPalette.white["100"],
textColor: tvgColorPalette.grey["900"],
iconColor: tvgColorPalette.grey["800"],
dotColor: tvgColorPalette.grey["800"],
trackingColor: tvgColorPalette.grey["300"]
},
win: {
border: tvgColorPalette.green["700"],
background: tvgColorPalette.green["100"],
textColor: tvgColorPalette.green["700"],
iconColor: tvgColorPalette.green["700"],
dotColor: tvgColorPalette.green["000"],
trackingColor: tvgColorPalette.green["300"]
},
lost: {
border: tvgColorPalette.red["700"],
background: tvgColorPalette.red["100"],
textColor: tvgColorPalette.red["700"],
iconColor: tvgColorPalette.red["700"],
trackingColor: tvgColorPalette.red["300"]
},
attention: {
border: tvgColorPalette.grey["900"],
background: tvgColorPalette.orange["400"],
textColor: tvgColorPalette.orange["700"],
iconColor: tvgColorPalette.orange["700"],
trackingColor: tvgColorPalette.orange["300"]
}
};
export const tvgColorTokens: ColorTokens = {
core,
component,
content,
background,
lhnHeader,
border,
myBets,
groupedfiltercell: {
background: {
default: "transparent",
hover: tvgColorPalette.blue_accent["000"],
pressed: tvgColorPalette.blue_accent["100"],
active: tvgColorPalette.blue_accent["100"]
},
border: {
default: "transparent",
hover: tvgColorPalette.blue["100"],
pressed: tvgColorPalette.blue["100"],
active: tvgColorPalette.blue_accent["500"]
},
content: {
default: tvgColorPalette.grey["900"],
hover: tvgColorPalette.grey["900"],
pressed: tvgColorPalette.grey["900"],
active: tvgColorPalette.blue_accent["700"]
}
},
notification: {
info: {
background: tvgColorPalette.blue_accent["600"],
backgroundSubtle: tvgColorPalette.blue_accent["000"],
subtle: tvgColorPalette.blue_accent["700"],
content: tvgColorPalette.white["900"],
border: tvgColorPalette.blue_accent["200"]
},
positive: {
background: tvgColorPalette.green["600"],
backgroundSubtle: tvgColorPalette.green["100"],
subtle: tvgColorPalette.green["800"],
content: tvgColorPalette.white["900"],
border: tvgColorPalette.green["300"]
},
negative: {
background: tvgColorPalette.red["500"],
backgroundSubtle: tvgColorPalette.red["000"],
subtle: tvgColorPalette.red["700"],
content: tvgColorPalette.white["900"],
border: tvgColorPalette.red["200"]
},
warning: {
background: tvgColorPalette.orange["500"],
backgroundSubtle: tvgColorPalette.orange["000"],
subtle: tvgColorPalette.orange["900"],
content: tvgColorPalette.white["900"],
border: tvgColorPalette.orange["200"]
},
promo: {
background: tvgColorPalette.yellow["500"],
backgroundSubtle: tvgColorPalette.yellow["000"],
subtle: tvgColorPalette.yellow["900"],
content: tvgColorPalette.grey["900"],
border: tvgColorPalette.yellow["200"]
}
}
} as const;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/theming/utils/themeGet.ts
import React from "react";
import { get } from "styled-system";
import { Theme } from "../types";
interface IProps extends React.HTMLProps<HTMLElement> {
theme: Theme;
}
const themeGet =
(path: string, fallback?: string | number) =>
({ theme }: IProps) =>
get(theme, path, fallback!);
export default themeGet;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/utils/accessibility.tsx
import {
Platform,
AccessibilityRole as NativeAccessibilityRole
} from "react-native";
export type WebOnlyAccessibilityRole =
| "paragraph"
| "span"
| "list"
| "listitem"
| "dialog";
export type AccessibilityRole =
| NativeAccessibilityRole
| WebOnlyAccessibilityRole;
const accessibilityRoleToNativeRole: {
[key in WebOnlyAccessibilityRole]: NativeAccessibilityRole;
} = {
paragraph: "text",
span: "text",
list: "menu",
listitem: "menuitem",
dialog: "alert"
};
export const getAccessibilityRole = (accessibilityRole: AccessibilityRole) =>
// @ts-ignore
(Platform.OS !== "web" && accessibilityRoleToNativeRole[accessibilityRole]) ||
accessibilityRole;
export default getAccessibilityRole;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/utils/breakpoints.tsx
import tvgConf from "@tvg/conf";
const breakpoints = {
desktop: {
min: {
sm: "(min-width: 920px)",
md: "(min-width: 1024px)",
lg: "(min-width: 1152px)",
xl: "(min-width: 1255px)",
xxl: "(min-width: 1364px)"
},
max: {
sm: "(max-width: 919.98px)",
md: "(max-width: 1023.98px)",
lg: "(max-width: 1151.98px)",
xl: "(max-width: 1254.98px)",
xxl: "(max-width: 1363.98px)"
}
},
tablet: {
min: {
sm:
tvgConf().product === "tvg5" // preventing responsive components on desktop
? "(min-width: 1px)"
: "(min-width: 768px)",
md: "(min-width: 1194px)",
lg: "(min-width: 1366px)"
},
max: {
sm:
tvgConf().product === "tvg5" // preventing responsive components on desktop
? "(max-width: 1px)"
: "(max-width: 767.98px)",
md: "(max-width: 1193.98px)",
lg: "(max-width: 1365.98px)"
}
}
};
export default breakpoints;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/utils/tvgConfProvider.tsx
import React, { createContext, useContext } from "react";
import tvgConf from "@tvg/conf";
import { Devices } from "../theming/types";
export interface TvgConfProps {
device: Devices;
brand: string;
product: string;
}
export interface TvgConfProviderProps extends Partial<TvgConfProps> {
children: JSX.Element;
}
const initialState: TvgConfProps = {
device: "mobile",
brand: "tvg",
product: "touch3"
};
export const TvgConfContext = createContext<TvgConfProps>(initialState);
export const TvgConfProvider = ({
children,
...overrides
}: TvgConfProviderProps) => (
<TvgConfContext.Provider
value={{
device: tvgConf().device,
brand: tvgConf().brand,
product: tvgConf().product,
...overrides
}}
>
{children}
</TvgConfContext.Provider>
);
export const useTvgConfContext = () => useContext(TvgConfContext);
export default TvgConfProvider;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/src/utils/tvgSafeAreaProvider.tsx
import React, { useContext } from "react";
import { SafeAreaProvider, Metrics } from "react-native-safe-area-context";
import { TvgConfContext } from "./tvgConfProvider";
const FRAME_DEFAULT = {
width: 1280,
height: 720,
x: 0,
y: 0
};
const MOBILE_FRAME_DEFAULT = {
width: 320,
height: 640,
x: 0,
y: 0
};
const INSETS_DEFAULT = {
left: 0,
right: 0,
bottom: 0,
top: 0
};
interface TvgSafeAreaProviderProps {
/** Children element to be rendered. Normally the TvgSafeAreaProvider should be added at the top level of an application. */
children: JSX.Element;
initialMetrics?: Metrics;
}
export const TvgSafeAreaProvider = (props: TvgSafeAreaProviderProps) => {
const { device } = useContext(TvgConfContext);
const initialMetrics = props.initialMetrics ?? {
frame: device === "mobile" ? MOBILE_FRAME_DEFAULT : FRAME_DEFAULT,
insets: INSETS_DEFAULT
};
return (
<SafeAreaProvider initialMetrics={initialMetrics}>
{props.children}
</SafeAreaProvider>
);
};
export default TvgSafeAreaProvider;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/AlertInLine/styled-components.ts
import styled, { css } from "styled-components";
import { space } from "styled-system";
import { animated } from "@react-spring/web";
import type {
AlertInlineProps,
AlertInlineVariants,
AlertInlineTypes
} from "./types";
const alertInlineVariants = {
success: css`
background-color: var(--fd-colors-system-positive-background-subtle);
border-color: var(--fd-colors-system-positive-border-default);
`,
informational: css`
background-color: var(--fd-colors-system-info-background-subtle);
border-color: var(--fd-colors-system-info-border-default);
`,
error: css`
background-color: var(--fd-colors-system-important-background-subtle);
border-color: var(--fd-colors-system-important-border-default);
`,
warning: css`
background-color: var(--fd-colors-system-warning-background-subtle);
border-color: var(--fd-colors-system-warning-border-default);
`,
promo: css`
background-color: var(--fd-colors-system-alert-background-subtle);
border-color: var(--fd-colors-system-alert-border-default);
`
};
const alertInlineTypes = {
floating: css`
border-radius: 4px;
border-style: solid;
border-width: 1px;
`,
fixed: css`
border-radius: 0;
border-style: solid;
border-width: 1px 0;
`
};
export const AnimatedWrapper = styled(animated.div)`
width: 100%;
height: max-content;
`;
export const AlertInlineContainer = styled.div<
Pick<AlertInlineProps, "variant" | "type">
>`
box-sizing: content-box;
display: flex;
gap: 12px;
padding: 12px;
${({ type }) => alertInlineTypes[type as AlertInlineTypes]}
${({ variant }) => alertInlineVariants[variant as AlertInlineVariants]}
${space}
`;
export const AlertInlineInfo = styled.div<{ flexDirection: string }>`
display: flex;
flex-direction: ${({ flexDirection }) => flexDirection};
flex: 1;
gap: 4px;
justify-content: space-between;
`;
export const IconContainer = styled.div`
display: inline-flex;
align-items: center;
justify-content: center;
height: 18px;
flex-shrink: 0;
`;
export const AlertInlineCloseButton = styled.button`
background: transparent;
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
width: 18px;
height: 18px;
padding: 0;
cursor: pointer;
border: 0;
`;
export const Link = styled.a<{ color: string }>`
color: ${({ color }) => `var(${color})`};
cursor: pointer;
font-family: Roboto, sans-serif;
font-size: 14px;
font-style: normal;
font-weight: 500;
line-height: 125%;
text-decoration: none;
display: flex;
flex-direction: row;
`;
export const LinkWrapper = styled.span`
display: flex;
flex-direction: row;
`;
export const TitleWrapper = styled.div`
display: flex;
flex-direction: row;
justify-content: space-between;
width: 100%;
gap: 12px;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/AlertInLine/constants.ts
export const alertInlineContentMap = {
success: {
icon: {
name: "success",
lineColor: "--fd-colors-system-positive-content-accent",
backgroundColor: "transparent"
},
text: "--fd-colors-system-positive-content-on-subtle",
link: "--fd-colors-system-positive-link-on-subtle"
},
informational: {
icon: {
name: "info",
lineColor: "--fd-colors-system-info-content-accent",
backgroundColor: "transparent"
},
text: "--fd-colors-system-info-content-on-subtle",
link: "--fd-colors-system-info-link-on-subtle"
},
error: {
icon: {
name: "exclamation",
lineColor: "--fd-colors-system-important-content-accent",
backgroundColor: "transparent"
},
text: "--fd-colors-system-important-content-on-subtle",
link: "--fd-colors-system-important-link-on-subtle"
},
warning: {
icon: {
name: "warning",
lineColor: "--fd-colors-system-warning-content-accent",
backgroundColor: "transparent"
},
text: "--fd-colors-system-warning-content-on-subtle",
link: "--fd-colors-system-warning-link-on-subtle"
},
promo: {
icon: {
name: "promo",
lineColor: "--fd-colors-system-alert-content-accent",
backgroundColor: "transparent"
},
text: "--fd-colors-system-alert-content-on-subtle",
link: "--fd-colors-system-alert-link-on-subtle"
}
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/AlertInLine/index.tsx
/* eslint-disable react/no-danger */
import React, { memo, FC, useState, useCallback } from "react";
import { useSpring } from "@react-spring/web";
import { Icon } from "../Icon";
import {
AnimatedWrapper,
AlertInlineContainer,
AlertInlineInfo,
AlertInlineCloseButton,
Link,
LinkWrapper,
TitleWrapper,
IconContainer
} from "./styled-components";
import { IconNames } from "../Icon/types";
import type { AlertInlineProps, AlertInlineVariants } from "./types";
import { alertInlineContentMap } from "./constants";
import { Paragraph } from "../Typography";
export const AlertInLine: FC<AlertInlineProps> = memo(
({
variant,
title,
message = "",
hasDismissButton,
hasDismissAnimation,
onDismissPress,
type = "floating",
linkLabel,
onLinkClick,
linkExtraInfo = "",
qaLabel,
children,
...rest
}) => {
const [isVisible, setIsVisible] = useState(true);
const { name, lineColor, backgroundColor } =
alertInlineContentMap[variant as AlertInlineVariants].icon;
const [animatedStyle, api] = useSpring(() => ({
from: {
opacity: 1
}
}));
const handleDismiss = useCallback((e) => {
onDismissPress?.(e);
// We need to maintain this with js since it has interaction
// depending on the animation
if (hasDismissAnimation) {
api.start({
from: { opacity: 1 },
to: {
opacity: 0
},
onRest: () => {
setIsVisible(false);
}
});
} else {
setIsVisible(false);
}
}, []);
return isVisible ? (
<AnimatedWrapper style={{ ...animatedStyle }}>
<AlertInlineContainer
variant={variant}
type={type}
data-qa-label={qaLabel}
data-status={isVisible ? "visible" : "hidden"}
{...rest}
>
<IconContainer>
<Icon
name={name as IconNames}
lineColor={lineColor}
backgroundColor={backgroundColor}
size="s"
qaLabel={`alert-inline-icon-${name}`}
/>
</IconContainer>
<AlertInlineInfo flexDirection={title ? "column" : "row"}>
{title || message ? (
<TitleWrapper>
<Paragraph
qaLabel={
title ? "alert-inline-title" : "alert-inline-message"
}
color={
alertInlineContentMap[variant as AlertInlineVariants].text
}
fontSize="14px"
fontWeight={!title ? 400 : 500}
lineHeight="125%"
margin={0}
fontFamily={!title ? "regular" : "medium"}
>
<span
dangerouslySetInnerHTML={{
__html: title || message || ""
}}
/>
</Paragraph>
{(!message || !title) && linkLabel && (
<LinkWrapper>
<Link
role="link"
data-qa-label="alert-inline-link"
onClick={(e) => {
onLinkClick?.(e);
}}
color={
alertInlineContentMap[variant as AlertInlineVariants]
.link
}
>
{linkLabel}
</Link>
{linkExtraInfo.length ? (
<Paragraph
color={
alertInlineContentMap[variant as AlertInlineVariants]
.link
}
fontSize="14px"
fontWeight={400}
lineHeight="135%"
fontFamily="regular"
margin={0}
>
{linkExtraInfo}
</Paragraph>
) : (
<></>
)}
</LinkWrapper>
)}
</TitleWrapper>
) : null}
{((title && message) || children) && (
<Paragraph
qaLabel="alert-inline-message"
color={
alertInlineContentMap[variant as AlertInlineVariants].text
}
fontSize="14px"
fontWeight={400}
lineHeight="125%"
fontFamily="regular"
margin={0}
>
{children}
<span
dangerouslySetInnerHTML={{
__html: message
}}
/>
</Paragraph>
)}
{linkLabel && title && message && (
<LinkWrapper>
<Link
role="link"
data-qa-label="alert-inline-link"
onClick={(e) => {
onLinkClick?.(e);
}}
color={
alertInlineContentMap[variant as AlertInlineVariants].link
}
>
{linkLabel}
</Link>
{linkExtraInfo.length ? (
<Paragraph
color={
alertInlineContentMap[variant as AlertInlineVariants].link
}
fontSize="14px"
fontWeight={400}
lineHeight="135%"
fontFamily="regular"
margin={0}
>
{linkExtraInfo}
</Paragraph>
) : (
<></>
)}
</LinkWrapper>
)}
</AlertInlineInfo>
{hasDismissButton && (
<AlertInlineCloseButton
onClick={handleDismiss}
data-qa-label="alert-inline-close-button"
>
<Icon
name="close"
lineColor={
alertInlineContentMap[variant as AlertInlineVariants].text
}
backgroundColor="transparent"
size="s"
qaLabel="alert-inline-icon-close"
/>
</AlertInlineCloseButton>
)}
</AlertInlineContainer>
</AnimatedWrapper>
) : null;
}
);
export type { AlertInlineProps, AlertInlineVariants };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Counter/styled-components.ts
import styled from "styled-components";
import { space, position } from "styled-system";
import type { CounterProps } from "./types";
export const CounterWrapper = styled.div<
Pick<CounterProps, "variant" | "value">
>`
align-items: center;
border-radius: 12px;
display: flex;
height: 16px;
justify-content: center;
max-height: 16px;
min-width: 16px;
padding: 0 ${({ value }) => (value > 9 ? "5px" : "")};
width: max-content;
&.primary {
background-color: var(--fd-colors-system-important-background-default);
}
&.secondary {
background-color: var(--fd-colors-system-info-background-default);
}
${space}
${position}
`;
export const CounterValue = styled.span`
color: var(--fd-colors-system-info-content-on-default);
font-family: "RobotoCondensed-Regular", sans-serif;
font-size: 12px;
font-style: normal;
text-transform: uppercase;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Counter/index.tsx
import React, { type FC } from "react";
import { CounterWrapper, CounterValue } from "./styled-components";
import type { CounterProps } from "./types";
export const Counter: FC<CounterProps> = ({
value,
variant = "primary",
qaLabel = "counter",
...rest
}) => (
<CounterWrapper
className={variant}
value={value}
data-qa-label={qaLabel}
{...rest}
>
<CounterValue data-qa-label={`${qaLabel}-value`}>
{value > 99 ? "99+" : value}
</CounterValue>
</CounterWrapper>
);
export type { CounterProps };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/AccountHistory.tsx
import React, { FC } from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const AccountHistory: FC<IconPathWithBackgroundProps> = ({
backgroundColor,
lineColor,
strokeWidth
}) => (
<>
<path
d="M14.4589 2.625H3.36956C2.1274 2.625 1.12042 3.63236 1.12042
4.875V11.25V19.125C1.12042 20.3676 2.1274 21.375 3.36956
21.375H8.8718L8.67757 21.375H16.8588C13.8867 21.375 10.8809 18.9785
10.8809 15.3721C10.8809 12.1055 13.541 9.36914 16.8588
9.36914V4.875C16.8588 3.63236 15.7011 2.625 14.4589 2.625Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M5.36488 21.375H8.67757H9.62781M16.8588 6.43361V4.875C16.8588 3.63236
15.7011 2.625 14.4589 2.625H3.36956C2.1274 2.625 1.12042 3.63236 1.12042
4.875V11.25V19.125C1.12042 20.3676 2.1274 21.375 3.36956 21.375H8.8718"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
<path
d="M4.49277 13.121L7.49277 13.121"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
<path
d="M4.49277 8.62573L10.4905 8.62573"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
<circle
cx="16.8588"
cy="15.375"
r="6"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
<path
d="M16.6661 13.5043V16.2445L18.9205 17.2551"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
strokeLinecap="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Add.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const Add = ({ lineColor, strokeWidth }: IconPathProps) => (
<path
d="M12 4.5V19.5M4.5 12H19.5"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Alert.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Alert = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M15 15.75H9.00004H4.43728L5.26194 13.7711C5.74689 12.6074 5.92322
11.3428 6.01799 10.0856C6.21719 7.44307 7.25731 3 12 3C16.8143 3 17.8134
7.57825 17.9905 10.2041C18.0701 11.3854 18.2201 12.5741 18.6438
13.6797L19.4373 15.75H15Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M15 15.75H19.4373L18.6438 13.6797C18.2201 12.5741 18.0701 11.3854
17.9905 10.2041C17.8134 7.57825 16.8143 3 12 3C7.25731 3 6.21719 7.44307
6.01799 10.0856C5.92322 11.3428 5.74689 12.6074 5.26194 13.7711L4.43728
15.75H9.00004M15 15.75V16.5C15 18.1569 13.6569 19.5 12 19.5C10.3432 19.5
9.00004 18.1569 9.00004 16.5V15.75M15 15.75H9.00004"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/AlertOff.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const AlertOff = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M4.56276 15.75H19.5628L18.7381 13.7711C18.2532 12.6074 18.0768 11.3428
17.9821 10.0856C17.7829 7.44307 16.7427 3 12 3C7.18575 3 6.18667 7.57825
6.00957 10.2041C5.9299 11.3854 5.77999 12.5741 5.35625 13.6797L4.56276
15.75Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M1.5 1.5L22.5 22.5M18.7186 13.875L18.6438 13.6797C18.2201 12.5741
18.0702 11.3854 17.9905 10.2041C17.8134 7.57826 16.8143 3 12 3C10.7662 3
9.78302 3.30068 9 3.79213M6.72136 6.75C6.27862 7.89743 6.09156 9.11181
6.01817 10.0833C5.9232 11.3404 5.74689 12.6074 5.26195 13.7711L4.43729
15.75H9M9 15.75V16.5C9 18.1569 10.3431 19.5 12 19.5C13.6569 19.5 15
18.1569 15 16.5L15 15.75H9Z"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Announcements.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Announcements = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M2.625 10.8194V13.1806C2.625 14.2984 3.44554 15.2467 4.55169
15.4073L5.625 15.5631L13.875 16.761L21.375 17.85V6.15001L4.55169
8.59275C3.44554 8.75337 2.625 9.70165 2.625 10.8194Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M21.375 6.15001V17.85M21.375 6.15001V3M21.375 6.15001L4.55169
8.59275C3.44554 8.75337 2.625 9.70165 2.625 10.8194V13.1806C2.625
14.2984 3.44554 15.2467 4.55169 15.4073M21.375 17.85V21M21.375
17.85L13.875 16.761M21.375 17.85L4.55169 15.4073M5.625
15.5631V19.875H13.875V16.761M5.625 15.5631L4.55169 15.4073M5.625
15.5631L13.875 16.761"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/ArrowBottom.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const ArrowBottom = ({ lineColor, strokeWidth }: IconPathProps) => (
<path
d="M12 2.25V20.1797M4.5 12.75L12 20.25L19.5 12.75"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/ArrowCollapseLeft.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const ArrowCollapseLeft = ({
lineColor,
strokeWidth
}: IconPathProps) => (
<path
d="M2.625 1.5L2.63081 11.9976L2.625 22.5M13.8903 4.5L6.39034 12L13.8903
19.5M6.46651 12H24"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/ArrowCollapseRight.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const ArrowCollapseRight = ({
lineColor,
strokeWidth
}: IconPathProps) => (
<path
d="M21.375 22.5L21.3692 12.0024L21.375 1.5M10.1097 19.5L17.6097 12L10.1097
4.5M17.5335 12L9.17939e-07 12"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/ArrowLeft.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const ArrowLeft = ({ lineColor, strokeWidth }: IconPathProps) => (
<path
d="M12 4.5L4.5 12L12 19.5M21.75 12H4.57617"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/ArrowRight.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const ArrowRight = ({ lineColor, strokeWidth }: IconPathProps) => (
<path
d="M2.25 12H20.9177M13.5 4.5L21 12L13.5 19.5"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/ArrowUp.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const ArrowUp = ({ lineColor, strokeWidth }: IconPathProps) => (
<path
d="M12 21.75V3.82723M4.5 11.25L12 3.75L19.5 11.25"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Badge.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const Badge = ({ lineColor }: IconPathProps) => (
<path
fillRule="evenodd"
clipRule="evenodd"
d="M4.92624 1.66197C4.78969 1.42195 4.48443 1.33806 4.2444 1.47461L3.15791
2.0927C2.91789 2.22924 2.834 2.53451 2.97055 2.77453L6.7395 9.3997C7.31637
8.9217 7.95938 8.52073 8.65277 8.21257L4.92624 1.66197ZM13.906
7.72655C13.2941 7.58186 12.656 7.50529 12 7.50529C11.8092 7.50529 11.6199
7.51177 11.4323 7.52451L14.7674 1.66197C14.9039 1.42195 15.2092 1.33806
15.4492 1.47461L16.5357 2.0927C16.7757 2.22924 16.8596 2.53451 16.7231
2.77453L13.906 7.72655ZM17.2576 9.39732C16.6805 8.91959 16.0374 8.51892
15.3438 8.21107L19.0695 1.66197C19.2061 1.42195 19.5113 1.33806 19.7513
1.47461L20.8378 2.0927C21.0779 2.22924 21.1617 2.53451 21.0252
2.77453L17.2576 9.39732ZM5.24999 15.7553C5.24999 19.4832 8.27206 22.5053 12
22.5053C12.233 22.5053 12.4632 22.4935 12.6901 22.4704C16.0939 22.1248 18.75
19.2502 18.75 15.7553C18.75 12.0274 15.7279 9.00529 12 9.00529C8.27206
9.00529 5.24999 12.0274 5.24999 15.7553ZM16.5 15.7553C16.5 18.2406 14.4853
20.2553 12 20.2553C9.5147 20.2553 7.49999 18.2406 7.49999 15.7553C7.49999
13.27 9.5147 11.2553 12 11.2553C14.4853 11.2553 16.5 13.27 16.5
15.7553ZM10.875 13.2553C10.875 12.9791 11.0988 12.7553 11.375
12.7553H12.625C12.9011 12.7553 13.125 12.9791 13.125 13.2553V18.2553C13.125
18.5314 12.9011 18.7553 12.625 18.7553H11.375C11.0988 18.7553 10.875 18.5314
10.875 18.2553V13.2553ZM9.24076 1.67456C9.1047 1.43352 8.7987 1.34889
8.55812 1.48576L7.47458 2.10216C7.23397 2.23904 7.15037 2.54538 7.28809
2.78551L9.85452 7.26043L11.1476 5.0523L9.24076 1.67456Z"
fill={lineColor}
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Bank.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Bank = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M2.625 21.375H21.375"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinecap="round"
/>
<path
d="M6 12.3939V21.3676"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinecap="round"
/>
<path
d="M11.9972 12.4056V21.3793"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinecap="round"
/>
<path
d="M18 12.3939V21.3676"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinecap="round"
/>
<path
d="M2.62768 8.62402L2.625 7.41016L11.998 2.625L21.375 7.41016L21.3711 8.625L2.62768 8.62402Z"
fill={backgroundColor}
fillOpacity="1"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinecap="round"
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/BetaProgram.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const BetaProgram = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M7.02039 21L20.37 21C20.9223 21 21.37 20.5523 21.37 20L21.37
9.55244C21.37 8.7189 20.4102 8.25122 19.7537 8.76494L6.40408
19.2125C5.65545 19.7984 6.06975 21 7.02039 21Z"
fill={backgroundColor}
stroke={lineColor}
strokeWidth={strokeWidth}
/>
<path
d="M16.9796 3H3.62998C3.0777 3 2.62998 3.44772 2.62998 4V14.4476C2.62998
15.2811 3.58988 15.7488 4.24629 15.2351L17.5959 4.78751C18.3446 4.20161
17.9303 3 16.9796 3Z"
fill={backgroundColor}
stroke={lineColor}
strokeWidth={strokeWidth}
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Bets.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Bets = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M18.375 2.625H5.625C4.79657 2.625 4.125 3.29657 4.125 4.125V21.75L7.5
20.25L9.75 21.75L12 20.25L14.25 21.75L16.5 20.25L19.875 21.75V4.125C19.875
3.29657 19.2034 2.625 18.375 2.625Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M7.5 8.625H12M7.5 13.125H16.5M5.625 2.625H18.375C19.2034 2.625 19.875
3.29657 19.875 4.125V21.75L16.5 20.25L14.25 21.75L12 20.25L9.75 21.75L7.5
20.25L4.125 21.75V4.125C4.125 3.29657 4.79657 2.625 5.625 2.625Z"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/BetsCancel.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const BetsCancel = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M18.375 2.625H5.625C4.79657 2.625 4.125 3.29657 4.125 4.125V21.75L7.5
20.25L9.75 21.75L12 20.25L14.25 21.75L16.5 20.25L19.875 21.75V4.125C19.875
3.29657 19.2034 2.625 18.375 2.625Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M12 20.25L9.75 21.75L7.5 20.25L4.125 21.75V4.125C4.125 3.29657 4.79657
2.625 5.625 2.625H18.375C19.2034 2.625 19.875 3.29657 19.875 4.125V12M7.5
8.625H12M7.5 13.125H13.5M15.75 14.25L19.5 18M19.5 18L23.25 21.75M19.5
18L15.75 21.75M19.5 18L23.25 14.25"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/BetsRefund.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const BetsRefund = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M18.375 2.625H5.625C4.79657 2.625 4.125 3.29657 4.125 4.125V21.75L7.5
20.25L9.75 21.75L12 20.25L14.25 21.75L16.5 20.25L19.875 21.75V4.125C19.875
3.29657 19.2034 2.625 18.375 2.625Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M12 20.25L9.75 21.75L7.5 20.25L4.125 21.75V4.125C4.125 3.29657 4.79657
2.625 5.625 2.625H18.375C19.2034 2.625 19.875 3.29657 19.875
4.125V11.9585M7.5 8.625H12M7.5 13.125H13.5M18.375 14.25L14.625 18L18.375
21.75M22.875 18H14.6953"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/BetsSuccess.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const BetsSuccess = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M18.375 2.625H5.625C4.79657 2.625 4.125 3.29657 4.125 4.125V21.75L7.5
20.25L9.75 21.75L12 20.25L14.25 21.75L16.5 20.25L19.875 21.75V4.125C19.875
3.29657 19.2034 2.625 18.375 2.625Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M12 20.25L9.75 21.75L7.5 20.25L4.125 21.75V4.125C4.125 3.29657 4.79657
2.625 5.625 2.625H18.375C19.2034 2.625 19.875 3.29657 19.875 4.125V12M7.5
8.625H12M7.5 13.125H13.5M14.25 18L17.25 21L23.25 15"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Calendar.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Calendar = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M2.625 4.875V8.625H21.375V4.875C21.375 3.63236 20.3676 2.625 19.125
2.625H15.375H8.625H4.875C3.63236 2.625 2.625 3.63236 2.625 4.875Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M6 13.125H9M10.5 13.125H13.5M15 13.125H18M6 16.875H9M10.5
16.875H13.5M8.625 0V2.625M8.625 6L8.625 2.625M15.375
3.57628e-07V2.625M15.375 6V2.625M2.625 8.625V19.875C2.625 20.7034 3.29657
21.375 4.125 21.375H19.875C20.7034 21.375 21.375 20.7034 21.375
19.875V8.625M2.625 8.625V4.875C2.625 3.63236 3.63236 2.625 4.875
2.625H8.625M2.625 8.625H21.375M21.375 8.625V4.875C21.375 3.63236 20.3676
2.625 19.125 2.625H15.375M8.625 2.625H15.375"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Card.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Card = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M22.875 5.625H1.125V10.1693L22.875 10.1693V5.625Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M4.15997 14.2534H13.5867M1.125 10.1693L22.875 10.1693M1.125
5.625H22.875V18.375H1.125V5.625Z"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/CardPlus.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const CardPlus = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M11.625 5.625H1.125V10.1693L11.625 10.1693V5.625Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M1.125 10.1708V18.3765H22.875V12.0015M1.125
10.1708V5.62647H11.625M1.125 10.1708H11.625M4.15997 14.2549H11.625M18
4.5V9M18 9V13.5M18 9H22.5M18 9H13.5"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Changes.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Changes = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M10.9393 1.81583C11.5251 1.23004 12.4749 1.23005 13.0607
1.81583L22.1842 10.9393C22.77 11.5251 22.77 12.4749 22.1842
13.0607L13.0607 22.1842C12.4749 22.77 11.5251 22.77 10.9393
22.1842L1.81583 13.0607C1.23004 12.4749 1.23004 11.5251 1.81583
10.9393L10.9393 1.81583Z"
fill={backgroundColor}
/>
<path
d="M12 13.5L12 6.75M12 17.25L12 15M1.81583 13.0607L10.9393
22.1842C11.5251 22.77 12.4749 22.77 13.0607 22.1842L22.1842 13.0607C22.77
12.4749 22.77 11.5251 22.1842 10.9393L13.0607 1.81583C12.4749 1.23005
11.5251 1.23004 10.9393 1.81583L1.81583 10.9393C1.23004 11.5251 1.23004
12.4749 1.81583 13.0607Z"
stroke={lineColor}
strokeWidth={strokeWidth}
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/ChevronDown.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const ChevronDown = ({ lineColor, strokeWidth }: IconPathProps) => (
<path
d="M19.5 9L12 16.5L4.5 9"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/ChevronLeft.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const ChevronLeft = ({ lineColor, strokeWidth }: IconPathProps) => (
<path
d="M15 4.5L7.5 12L15 19.5"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/ChevronRight.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const ChevronRight = ({ lineColor, strokeWidth }: IconPathProps) => (
<path
d="M7.5 4.5L15 12L7.5 19.5"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/ChevronUp.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const ChevronUp = ({ lineColor, strokeWidth }: IconPathProps) => (
<path
d="M4.5 15L12 7.5L19.5 15"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Close.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const Close = ({ lineColor, strokeWidth }: IconPathProps) => (
<path
d="M5.25 5.25L18.75 18.75M18.75 5.25L5.25 18.75"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Cup.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Cup = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M6.37499 2.625H17.625L17.625 5.25C17.625 5.25 17.625 5.38466 17.618
5.625C17.5889 6.62136 17.4393 9.43394 16.6695 11.9974C15.8997 14.5608
14.5097 16.875 12 16.875C9.49024 16.875 8.10028 14.5608 7.33048
11.9974C6.56066 9.43394 6.41105 6.62136 6.38197 5.625C6.37495 5.38466
6.37495 5.25 6.37495 5.25L6.37499 2.625Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M12 16.875L12 21.375M12 16.875C9.49024 16.875 8.10028 14.5608 7.33048
11.9974M12 16.875C14.5097 16.875 15.8997 14.5608 16.6695 11.9974M6.37495
5.25L6.37499 2.625H17.625L17.625 5.25C17.625 5.25 17.625 5.38466 17.618
5.625M6.37495 5.25C6.37495 5.25 6.37497 8.8156 7.33048 11.9974M6.37495
5.25C6.37495 5.25 6.37495 5.38466 6.38197 5.625M12 21.375H7.49995M12
21.375H16.5M6.38197 5.625H2.62495C2.62495 5.625 2.62495 11.8514 7.33048
11.9974M6.38197 5.625C6.41105 6.62136 6.56066 9.43394 7.33048
11.9974M16.6695 11.9974C21.375 11.8513 21.375 5.625 21.375
5.625H17.618M16.6695 11.9974C17.4393 9.43394 17.5889 6.62136 17.618 5.625"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/CustomerSupport.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const CustomerSupport = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M3 11.3269L3.75 18L8.25 17.25V12L3 11.3269Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M20.254 17.9646L20.9966 11.3571L15.75 12V17.25L20.254 17.9646Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M3 11.3269C3 6.52099 7.02944 2.625 12 2.625C16.9706 2.625 21 6.52099
21 11.3269L20.25 18L18.75 21L11.625 21.375M3 11.3269L3.75 18L8.25
17.25V12L3 11.3269ZM15.75 17.25V12L20.9966 11.3571L20.254 17.9646L15.75
17.25Z"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Cvv.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Cvv = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M21.375 5.625H1.125V10.8806H10.7656C10.7656 10.8806 12.5078 8.25
16.1914 8.25C19.875 8.25 21.375 10.7674 21.375 10.7674V10.7617V5.625Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M13.4351 16.9782H12.5152V14.0534L11.6117 14.3171V13.6212L13.3507
13.0205H13.4351V16.9782Z"
fill={lineColor}
/>
<path
d="M17.3947 16.9782H14.6298V16.3802L15.9034 15.0428C16.2173 14.6859
16.3742 14.4022 16.3742 14.192C16.3742 14.0217 16.337 13.8921 16.2626
13.8033C16.1882 13.7145 16.0803 13.6701 15.9388 13.6701C15.7991 13.6701
15.6857 13.7299 15.5986 13.8495C15.5115 13.9673 15.468 14.115 15.468
14.2926H14.5481C14.5481 14.0498 14.6089 13.826 14.7305 13.6212C14.852
13.4146 15.0208 13.2534 15.2367 13.1374C15.4526 13.0214 15.6939 12.9634
15.9606 12.9634C16.3887 12.9634 16.718 13.0622 16.9484 13.2597C17.1807
13.4572 17.2968 13.7408 17.2968 14.1105C17.2968 14.2663 17.2677 14.4186
17.2097 14.5672C17.1516 14.7139 17.0609 14.8689 16.9375 15.032C16.816
15.1932 16.6191 15.4098 16.347 15.6816L15.8354 16.2715H17.3947V16.9782Z"
fill={lineColor}
/>
<path
d="M18.6956 14.6161H19.1283C19.4712 14.6161 19.6426 14.4485 19.6426
14.1132C19.6426 13.9827 19.6018 13.8767 19.5202 13.7952C19.4385 13.7118
19.3233 13.6701 19.1745 13.6701C19.053 13.6701 18.9469 13.7055 18.8561
13.7762C18.7672 13.8468 18.7228 13.9347 18.7228 14.0398H17.8057C17.8057
13.8314 17.8637 13.6457 17.9798 13.4826C18.096 13.3195 18.2565 13.1926
18.4615 13.102C18.6684 13.0096 18.8952 12.9634 19.1419 12.9634C19.5828
12.9634 19.9293 13.064 20.1815 13.2651C20.4337 13.4663 20.5598 13.7426
20.5598 14.0942C20.5598 14.2645 20.5071 14.4258 20.4019 14.578C20.2985
14.7284 20.147 14.8508 19.9474 14.945C20.1579 15.0211 20.323 15.1371
20.4427 15.2929C20.5625 15.4469 20.6223 15.6381 20.6223 15.8665C20.6223
16.2198 20.4863 16.5025 20.2141 16.7145C19.942 16.9266 19.5846 17.0326
19.1419 17.0326C18.8825 17.0326 18.6412 16.9836 18.418 16.8858C18.1967
16.7861 18.0288 16.6493 17.9145 16.4753C17.8002 16.2996 17.7431 16.1002
17.7431 15.8773H18.6656C18.6656 15.9987 18.7146 16.1039 18.8126
16.1926C18.9106 16.2814 19.0312 16.3258 19.1745 16.3258C19.336 16.3258
19.4648 16.2814 19.561 16.1926C19.6571 16.102 19.7052 15.987 19.7052
15.8474C19.7052 15.6481 19.6553 15.5068 19.5555 15.4234C19.4558 15.34
19.3179 15.2984 19.1419 15.2984H18.6956V14.6161Z"
fill={lineColor}
/>
<circle
cx="16.125"
cy="14.9999"
r="6.75"
stroke={lineColor}
strokeWidth={strokeWidth}
/>
<path
d="M10.244 18.3739H1.125V5.62392H21.375V10.7078"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinecap="round"
strokeLinejoin="round"
/>
<path
d="M1.13259 10.8836L10.7547 10.8836"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinecap="round"
strokeLinejoin="round"
/>
<path
d="M4.88782 14.6246L9.37891 14.6246"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Deposit.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const Deposit = ({ lineColor, strokeWidth }: IconPathProps) => (
<>
<path
d="M18 7.5V12M18 12V16.5M18 12H22.5M18 12H13.5"
stroke={lineColor}
strokeWidth={strokeWidth}
/>
<path
d="M12 8.40001C12 8.40001 12 4.80002 7.5 4.80002M7.5 4.80002C3 4.80002 3
8.40001 3 8.40001C3 9.60001 3 10.8 7.5 12C12 13.2 12 14.4 12 15.6C12 15.6
12 19.2 7.5 19.2M7.5 4.80002V1.5M7.5 19.2C3 19.2 3 15.6 3 15.6M7.5
19.2V22.5M18 7.5V12M18 12V16.5M18 12H22.5M18 12H13.5"
stroke={lineColor}
strokeWidth={strokeWidth}
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/DoubleChevronDown.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const DoubleChevronDown = ({
lineColor,
strokeWidth
}: IconPathProps) => (
<path
d="M19.5 12L12 19.5L4.5 12M19.5 4.5L12 12L4.5 4.5"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/DoubleChevronLeft.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const DoubleChevronLeft = ({
lineColor,
strokeWidth
}: IconPathProps) => (
<path
d="M12 4.5L4.5 12L12 19.5M19.5 4.5L12 12L19.5 19.5"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/DoubleChevronRight.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const DoubleChevronRight = ({
lineColor,
strokeWidth
}: IconPathProps) => (
<path
d="M12 4.5L19.5 12L12 19.5M4.5 4.5L12 12L4.5 19.5"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/DoubleChevronUp.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const DoubleChevronUp = ({ lineColor, strokeWidth }: IconPathProps) => (
<path
d="M4.5 12L12 4.5L19.5 12M4.5 19.5L12 12L19.5 19.5"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/ECheck.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const ECheck = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M1.125 4.125H22.875V19.875H1.125V4.125Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M5.2826 14.2631H12.4064M5.2826 9.72643L15.3517 9.72643M1.125
4.125H22.875V19.875H1.125V4.125Z"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinecap="square"
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Edit.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Edit = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M2.625 16.875V21.375H7.125L19.125 9.375L14.625 4.875L2.625 16.875Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M14.625 4.875L2.625 16.875V21.375H7.125L19.125 9.375M14.625
4.875L19.125 9.375M14.625 4.875L16.409 3.09099C17.2877 2.21231 18.7123
2.21231 19.591 3.09099L20.909 4.40901C21.7877 5.28769 21.7877 6.71231
20.909 7.59099L19.125 9.375"
stroke={lineColor}
strokeWidth={strokeWidth}
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Email.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Email = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M21.375 5.625H2.625V18.375H21.375V5.625Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M2.69998 5.69998L12 13.5L21.3 5.69998M2.625
5.625H21.375V18.375H2.625V5.625Z"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Error.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Error = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M22.8755 12.0042C22.8755 18.0105 18.0063 22.8797 12 22.8797C5.99362
22.8797 1.1245 18.0105 1.1245 12.0042C1.1245 5.99782 5.99362 1.12871 12
1.12871C18.0063 1.12871 22.8755 5.99782 22.8755 12.0042Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M7.50005 7.5L12.0001 12M12.0001 12L16.5001 16.5M12.0001 12L7.50005
16.5M12.0001 12L16.5001 7.5M22.8755 12.0042C22.8755 18.0105 18.0063
22.8797 12 22.8797C5.99362 22.8797 1.1245 18.0105 1.1245 12.0042C1.1245
5.99782 5.99362 1.12871 12 1.12871C18.0063 1.12871 22.8755 5.99782
22.8755 12.0042Z"
stroke={lineColor}
strokeWidth={strokeWidth}
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Exclamation.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Exclamation = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M22.8755 12.0042C22.8755 18.0105 18.0064 22.8797 12 22.8797C5.99363
22.8797 1.12451 18.0105 1.12451 12.0042C1.12451 5.99782 5.99363 1.12871
12 1.12871C18.0064 1.12871 22.8755 5.99782 22.8755 12.0042Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M12 13.5V6M12 18V15.75M22.8755 12.0042C22.8755 18.0105 18.0064 22.8797
12 22.8797C5.99363 22.8797 1.12451 18.0105 1.12451 12.0042C1.12451 5.99782
5.99363 1.12871 12 1.12871C18.0064 1.12871 22.8755 5.99782 22.8755
12.0042Z"
stroke={lineColor}
strokeWidth={strokeWidth}
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/EyeHide.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const EyeHide = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M12 4.125C5 4.125 1.5 12 1.5 12C1.5 12 5 19.875 12 19.875C19 19.875
22.5 12 22.5 12C22.5 12 19 4.125 12 4.125ZM12 15.3807C13.8671 15.3807
15.3806 13.8671 15.3806 12C15.3806 10.1329 13.8671 8.61937 12
8.61937C10.1329 8.61937 8.61932 10.1329 8.61932 12C8.61932 13.8671
10.1329 15.3807 12 15.3807Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M3.86012 15.6319C2.28671 13.7701 1.125 12 1.125 12C1.125 12 4.99997
4.125 12 4.125C13.0424 4.125 14.0072 4.29964 14.8944 4.5969M6.16037
17.8286C7.71696 18.9976 9.66349 19.875 12 19.875C19 19.875 22.875 12
22.875 12C22.875 12 20.9409 8.49212 17.8228 6.1588M22.5 1.5L14.3905
9.60954M1.5 22.5L14.3905 9.60954M8.61932 12C8.61932 10.1329 10.1329
8.61937 12 8.61937M9.60744 14.3884C10.2194 15.0014 11.0654 15.3807 12
15.3807C13.867 15.3807 15.3806 13.8671 15.3806 12C15.3806 11.0665 15.0022
10.2213 14.3905 9.60954"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/EyeShow.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const EyeShow = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<path
fillRule="evenodd"
clipRule="evenodd"
d="M12 4.125C5 4.125 1.125 12 1.125 12C1.125 12 5 19.875 12 19.875C19
19.875 22.875 12 22.875 12C22.875 12 19 4.125 12 4.125ZM12 15.3807C13.8671
15.3807 15.3806 13.8671 15.3806 12C15.3806 10.1329 13.8671 8.61937 12
8.61937C10.1329 8.61937 8.61932 10.1329 8.61932 12C8.61932 13.8671 10.1329
15.3807 12 15.3807Z"
fill={backgroundColor}
fillOpacity="1"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Featured.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const Featured = ({ lineColor, strokeWidth }: IconPathProps) => (
<>
<path
d="M18.1216 2.62585H5.87842C5.74035 2.62585 5.62842 2.73778 5.62842
2.87585V20.9922C5.62842 21.1729 5.81412 21.2939 5.97937 21.2209L11.899
18.6079C11.9634 18.5795 12.0366 18.5795 12.101 18.6079L18.0206
21.2209C18.1859 21.2939 18.3716 21.1729 18.3716 20.9922V2.87585C18.3716
2.73778 18.2596 2.62585 18.1216 2.62585Z"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinecap="round"
/>
<path
d="M11.7622 8.23173C11.8371 8.0014 12.1629 8.0014 12.2378 8.23173L12.9542
10.4366C12.9877 10.5397 13.0836 10.6094 13.1919 10.6094H15.5103C15.7525
10.6094 15.8532 10.9193 15.6573 11.0616L13.7817 12.4244C13.694 12.488
13.6574 12.6009 13.6908 12.7039L14.4073 14.9088C14.4821 15.1391 14.2185
15.3306 14.0226 15.1883L12.1469 13.8256C12.0593 13.7619 11.9407 13.7619
11.8531 13.8256L9.97744 15.1883C9.78151 15.3306 9.51789 15.1391 9.59273
14.9088L10.3092 12.7039C10.3426 12.6009 10.306 12.488 10.2183
12.4244L8.34272 11.0616C8.14679 10.9193 8.24749 10.6094 8.48967
10.6094H10.8081C10.9164 10.6094 11.0123 10.5397 11.0458 10.4366L11.7622
8.23173Z"
fill={lineColor}
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Feedback.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Feedback = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M6 7.875H3.625C3.07272 7.875 2.625 8.32272 2.625 8.875L2.625
16.4118C2.625 16.96 3.06942 17.4044 3.61765 17.4044V17.4044C4.16587
17.4044 4.61029 17.8488 4.61029 18.3971V21.375L8.28799 17.6973C8.47553
17.5098 8.72988 17.4044 8.9951 17.4044H15.125C15.6773 17.4044 16.125
16.9567 16.125 16.4044V14.775"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
<path
d="M6.375 3.625C6.375 3.07272 6.82272 2.625 7.375 2.625L20.375
2.625C20.9273 2.625 21.375 3.07272 21.375 3.625V12.2132C21.375 12.7655
20.9273 13.2132 20.375 13.2132H20.1691C19.6168 13.2132 19.1691 13.661
19.1691 14.2132V17.625L15.0502 13.5061C14.8627 13.3186 14.6084 13.2132
14.3431 13.2132L7.375 13.2132C6.82272 13.2132 6.375 12.7655 6.375
12.2132L6.375 3.625Z"
fill={backgroundColor}
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
<path
d="M9.85217 6.93798C9.90606 6.77214 10.1407 6.77214 10.1946
6.93798L10.3371 7.37654C10.3612 7.45071 10.4303 7.50092 10.5082
7.50092H10.9694C11.1438 7.50092 11.2163 7.72405 11.0752 7.82654L10.7021
8.09759C10.639 8.14343 10.6126 8.22467 10.6367 8.29884L10.7792
8.73741C10.8331 8.90324 10.6433 9.04114 10.5022 8.93865L10.1292
8.6676C10.0661 8.62177 9.98065 8.62177 9.91756 8.6676L9.5445
8.93865C9.40343 9.04114 9.21362 8.90324 9.2675 8.73741L9.41 8.29884C9.4341
8.22467 9.4077 8.14343 9.34461 8.09759L8.97155 7.82654C8.83048 7.72405
8.90298 7.50092 9.07735 7.50092H9.53849C9.61647 7.50092 9.68558 7.45071
9.70968 7.37654L9.85217 6.93798Z"
fill="#5390ED"
/>
<path
d="M13.7031 6.93798C13.7569 6.77214 13.9916 6.77214 14.0454
6.93798L14.1879 7.37654C14.212 7.45071 14.2812 7.50092 14.3591
7.50092H14.8203C14.9946 7.50092 15.0671 7.72405 14.9261 7.82654L14.553
8.09759C14.4899 8.14343 14.4635 8.22467 14.4876 8.29884L14.6301
8.73741C14.684 8.90324 14.4942 9.04114 14.3531 8.93865L13.9801
8.6676C13.917 8.62177 13.8315 8.62177 13.7685 8.6676L13.3954
8.93865C13.2543 9.04114 13.0645 8.90324 13.1184 8.73741L13.2609
8.29884C13.285 8.22467 13.2586 8.14343 13.1955 8.09759L12.8224
7.82654C12.6814 7.72405 12.7539 7.50092 12.9282 7.50092H13.3894C13.4674
7.50092 13.5365 7.45071 13.5606 7.37654L13.7031 6.93798Z"
fill="#5390ED"
/>
<path
d="M17.5539 6.93798C17.6078 6.77214 17.8424 6.77214 17.8963
6.93798L18.0388 7.37654C18.0629 7.45071 18.132 7.50092 18.21
7.50092H18.6711C18.8455 7.50092 18.918 7.72405 18.7769 7.82654L18.4039
8.09759C18.3408 8.14343 18.3144 8.22467 18.3385 8.29884L18.481
8.73741C18.5348 8.90324 18.345 9.04114 18.204 8.93865L17.8309
8.6676C17.7678 8.62177 17.6824 8.62177 17.6193 8.6676L17.2462
8.93865C17.1052 9.04114 16.9154 8.90324 16.9692 8.73741L17.1117
8.29884C17.1358 8.22467 17.1094 8.14343 17.0464 8.09759L16.6733
7.82654C16.5322 7.72405 16.6047 7.50092 16.7791 7.50092H17.2402C17.3182
7.50092 17.3873 7.45071 17.4114 7.37654L17.5539 6.93798Z"
fill="#5390ED"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/File.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const File = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M4.125 4.125V19.875C4.125 20.7034 4.79657 21.375 5.625
21.375H18.375C19.2034 21.375 19.875 20.7034 19.875
19.875V7.875H14.625V2.625H5.625C4.79657 2.625 4.125 3.29657 4.125 4.125Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M14.625 2.70509V7.875H19.7969M14.625 2.625H5.625C4.79657 2.625 4.125
3.29657 4.125 4.125L4.125 19.875C4.125 20.7034 4.79657 21.375 5.625
21.375H18.375C19.2034 21.375 19.875 20.7034 19.875 19.875V7.875L14.625
2.625Z"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/FileDownload.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const FileDownload = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M4.125 4.125V19.875C4.125 20.7034 4.79657 21.375 5.625
21.375H18.375C19.2034 21.375 19.875 20.7034 19.875
19.875V7.875H14.625V2.625H5.625C4.79657 2.625 4.125 3.29657 4.125 4.125Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M19.5 14.25V22.0538M23.2031 18.4219L19.5 22.125L15.7969 18.4219M19.875
12V7.875L14.625 2.625H5.625C4.79657 2.625 4.125 3.29657 4.125
4.125V19.875C4.125 20.7034 4.79657 21.375 5.625 21.375H12M14.625
2.70509V7.875H19.8018"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Filters.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Filters = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M7.875 19.875C9.53185 19.875 10.875 18.5319 10.875 16.875C10.875
15.2181 9.53185 13.875 7.875 13.875C6.21815 13.875 4.87613 15.2181
4.87613 16.875C4.87613 18.5319 6.21815 19.875 7.875 19.875Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M14.625 10.125C16.2819 10.125 17.625 8.78185 17.625 7.125C17.625
5.46815 16.2819 4.125 14.625 4.125C12.9681 4.125 11.625 5.46815 11.625
7.125C11.625 8.78185 12.9681 10.125 14.625 10.125Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M4.87613 16.875H1.5M4.87613 16.875C4.87613 18.5319 6.21815 19.875 7.875
19.875C9.53185 19.875 10.875 18.5319 10.875 16.875M4.87613 16.875C4.87613
15.2181 6.21815 13.875 7.875 13.875C9.53185 13.875 10.875 15.2181 10.875
16.875M10.875 16.875H22.5M11.625 7.125H1.5M11.625 7.125C11.625 8.78185
12.9681 10.125 14.625 10.125C16.2819 10.125 17.625 8.78185 17.625
7.125M11.625 7.125C11.625 5.46815 12.9681 4.125 14.625 4.125C16.2819
4.125 17.625 5.46815 17.625 7.125M17.625 7.125H22.5"
stroke={lineColor}
strokeWidth={strokeWidth}
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Greyhounds.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Greyhounds = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<path
d="M8.875 9.22224C6.09722 10.6111 2.625 14.0833 2.625 14.0833L8.18056
18.25L11.6528 14.0833C11.6528 14.0833 15.8757 14.4587 17.9028
15.4722C19.0139 14.9167 21.375 15.4722 21.375 13.3889C17.2083 12
15.9321 8.52779 13.7361 8.52779C12.3472 8.52779 10.9583 5.75002 9.56944
5.75002L6.79167 9.22224H8.875Z"
fill={backgroundColor}
fillOpacity="1"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Hamburger.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const Hamburger = ({ lineColor, strokeWidth }: IconPathProps) => (
<path
d="M1.5 12H22.5M22.5 4.875H1.5M22.5 19.125H1.5"
stroke={lineColor}
strokeWidth={strokeWidth}
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Home.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Home = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M21.375 9L12 3L2.625 9V21.375H9.375V13.5H14.625V21.375H21.375V9Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M9.375 21.375H2.625V9L12 3L21.375 9V21.375H14.625M9.375
21.375V13.5H14.625V21.375M9.375 21.375H14.625"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/HomeCustomize.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const HomeCustomize = ({ lineColor, strokeWidth }: IconPathProps) => (
<>
<path
d="M18.18972 6.431532L16.06848 4.310208 13.86528 5.633916 12.62172 5.11854 12 2.625H9L8.378244 5.118576 7.134732 5.633988 4.931532 4.310256 2.810208 6.43158 4.133964 8.634768 3.618564 9.878256 1.125 10.5V13.5L3.61854 14.12172 4.133916 15.36528 2.810172 17.56848 4.931484 19.68984 7.134672 18.36612 8.37822 18.88152M12.11364 9.470472C11.647692 9.172632 11.094 9 10.5 9 8.843148 9 7.5 10.343148 7.5 12 7.5 12.4746 7.61022 12.92352 7.806444 13.3224 7.924788 13.563 8.074404 13.78548 8.25 13.98432"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
<path
d="M15.195 21.375H10.875V13.29336L16.875 9.375 22.875 13.29336V21.375H18.555M15.195 21.375V16.23216H18.555V21.375M15.195 21.375H18.555"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Horse.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Horse = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<path
d="M12.75 6C9 6.75 3.75 10.5 3.75 17.25L12.75 21.75L12 12.75C12.6 15.75 16
16 17.25 15.75L19.5 17.25C20.7 16.65 20.5 15 20.25 14.25C19.5 14 18.75 12
18 9.75C17.5257 8.32697 16 6.5 15 5.25V3L12.75 6Z"
fill={backgroundColor}
fillOpacity="1"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Info.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Info = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M22.8755 12.0042C22.8755 18.0105 18.0064 22.8797 12 22.8797C5.99363
22.8797 1.12451 18.0105 1.12451 12.0042C1.12451 5.99782 5.99363 1.12871
12 1.12871C18.0064 1.12871 22.8755 5.99782 22.8755 12.0042Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M12 18V10.5M12 8.25V6M22.8755 12.0042C22.8755 18.0105 18.0064 22.8797
12 22.8797C5.99363 22.8797 1.12451 18.0105 1.12451 12.0042C1.12451 5.99782
5.99363 1.12871 12 1.12871C18.0064 1.12871 22.8755 5.99782 22.8755
12.0042Z"
stroke={lineColor}
strokeWidth={strokeWidth}
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Key.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Key = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M4.30499 19.695C6.64674 22.0368 10.4383 22.0368 12.78 19.695C14.4622
18.0128 14.9396 15.5901 14.205 13.485L21.375 6.31501L21.375
2.62499L17.6937 2.62499L10.515 9.79501C8.41336 9.06793 5.98317 9.54184
4.305 11.22C1.96325 13.5618 1.96324 17.3533 4.30499 19.695ZM8.53498
16.59C9.15554 16.59 9.65998 16.0855 9.65998 15.465C9.65998 14.8444
9.15554 14.34 8.53498 14.34C7.91443 14.34 7.40999 14.8444 7.40999
15.465C7.40999 16.0855 7.91443 16.59 8.53498 16.59Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M16.021 8.99144L16.021 11.3793M18.5011 6.69585L18.5011 8.99144M4.305
11.22C1.96325 13.5618 1.96324 17.3533 4.30499 19.695C6.64674 22.0368
10.4383 22.0368 12.78 19.695C14.4622 18.0128 14.9396 15.5901 14.205
13.485L21.375 6.31501L21.375 2.62499L17.6937 2.62499L10.515
9.79501C8.41336 9.06793 5.98317 9.54184 4.305 11.22ZM9.65998
15.465C9.65998 16.0855 9.15554 16.59 8.53498 16.59C7.91443 16.59
7.40999 16.0855 7.40999 15.465C7.40999 14.8444 7.91443 14.34 8.53498
14.34C9.15554 14.34 9.65998 14.8444 9.65998 15.465Z"
stroke={lineColor}
strokeWidth={strokeWidth}
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/LiveVideo.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const LiveVideo = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M12 19.875H6.5625H3.375C2.13236 19.875 1.125 18.8676 1.125
17.625V6.375C1.125 5.13236 2.13236 4.125 3.375 4.125H20.625C21.8676 4.125
22.875 5.13236 22.875 6.375V17.625C22.875 18.8676 21.8676 19.875 20.625
19.875H17.4375H12ZM9 16.5V7.5L16.5 12L9 16.5Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M6.5625 19.875H12H17.4375M6.5625 19.875L3 23.25M6.5625
19.875H3.375C2.13236 19.875 1.125 18.8676 1.125 17.625V6.375C1.125
5.13236 2.13236 4.125 3.375 4.125H20.625C21.8676 4.125 22.875 5.13236
22.875 6.375V17.625C22.875 18.8676 21.8676 19.875 20.625
19.875H17.4375M17.4375 19.875L21 23.25M9 7.5V16.5L16.5 12L9 7.5Z"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Location.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Location = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<path
d="M21.375 2.625L2.625 8.875L10.9583 13.0417L15.125 21.375L21.375 2.625Z"
fill={backgroundColor}
fillOpacity="1"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Lock.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Lock = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<rect
x="4.125"
y="11.6043"
width="15.75"
height="9.77069"
rx="1"
fill={backgroundColor}
fillOpacity="1"
stroke={lineColor}
strokeWidth={strokeWidth}
/>
<path d="M12 15V18" stroke={lineColor} strokeWidth={strokeWidth} />
<path
d="M16.875 11.6043V7.11465C16.875 7.11465 16.875 2.625 12 2.625C7.125
2.625 7.125 7.11465 7.125 7.11465V11.6043"
stroke={lineColor}
strokeWidth={strokeWidth}
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/NoVideo.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const NoVideo = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M22.8797 12C22.8797 18.0087 18.0087 22.8797 12 22.8797C5.99133 22.8797
1.12033 18.0087 1.12033 12C1.12033 5.99133 5.99133 1.12033 12
1.12033C18.0087 1.12033 22.8797 5.99133 22.8797 12ZM9.00064
16.5018V7.5L16.4992 12L9.00064 16.5018Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M1.5 1.5L6.75 6.75M15.9375 15.9375L22.5 22.5M22.8797 12C22.8797 18.0087
18.0087 22.8797 12 22.8797C5.99133 22.8797 1.12033 18.0087 1.12033
12C1.12033 5.99133 5.99133 1.12033 12 1.12033C18.0087 1.12033 22.8797
5.99133 22.8797 12ZM9.00064 7.5V16.5018L16.4992 12L9.00064 7.5Z"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/NumberFire.tsx
import React from "react";
export const NumberFire = () => (
<>
<g clipPath="url(#clip0_20346_7102)">
<path
d="M4.7619 20.7286C3.37143 19.1762 2.51428 17.1857 2.51428
14.9952C2.51428 11.5 4.50476 8.00476 7.00952 7.00476C7.50476
8.50952 8.26667 10.519 11.4952 10.5C8 3.50952 13.4952 0.0142822
14.4952 0.0142822C14.4952 3.28095 16.5714 5.5 18.4571 7.9L13.1238
17.4619L9.02857 13.0809L4.7619 20.7286ZM13.4952 20.4905L9.4
16.1095L6.12381 21.9857C7.81376 23.2721 9.87619 23.9741 12
23.9857C16.9905 23.9857 21.4857 19.9857 21.4857 14.9952C21.4857
12.8048 20.6857 11.0619 19.6286 9.49047L13.4952 20.4905Z"
fill="url(#paint0_linear_20346_7102)"
/>
<path
d="M4.7619 20.7286C3.37143 19.1762 2.51428 17.1857 2.51428
14.9952C2.51428 11.5 4.50476 8.00476 7.00952 7.00476C7.50476
8.50952 8.26667 10.519 11.4952 10.5C8 3.50952 13.4952 0.0142822
14.4952 0.0142822C14.4952 3.28095 16.5714 5.5 18.4571 7.9L13.1238
17.4619L9.02857 13.0809L4.7619 20.7286ZM13.4952 20.4905L9.4
16.1095L6.12381 21.9857C7.81376 23.2721 9.87619 23.9741 12
23.9857C16.9905 23.9857 21.4857 19.9857 21.4857 14.9952C21.4857
12.8048 20.6857 11.0619 19.6286 9.49047L13.4952 20.4905Z"
fill="url(#paint1_linear_20346_7102)"
/>
<path
d="M8.15238 14.6429L4.7619 20.7286C3.37143 19.1762 2.51428
17.1857 2.51428 14.9952C2.51428 11.5 4.50476 8.00476 7.00952
7.00476C5.71428 9.15714 5.91428 11.6714 8.15238 14.6429ZM9.4
16.1095L6.12381 21.9857L6.35238 22.1571C10.6095 25.1381 13.419
20.4143 9.4 16.1095V16.1095Z"
fill="url(#paint2_linear_20346_7102)"
/>
<path
d="M19.6286 9.49047C20.6857 11.0619 21.4857 12.8048 21.4857
14.9952C21.4857 19.9857 16.9905 23.9857 12 23.9857C10.6329 23.9805
9.28249 23.6851 8.03809 23.119C11.4667 24.6238 13.0857 23.1095
13.5048 20.4714L19.6286 9.49047ZM18.4571 7.9C16.5714 5.5 14.4952
3.28095 14.4952 0.0142822C13.4952 0.0142822 7.99999 3.50952 11.4952
10.5C12.4846 12.4997 13.15 14.6439 13.4667 16.8524L18.4571 7.9Z"
fill="url(#paint3_linear_20346_7102)"
/>
<path
d="M19.6286 9.49047C20.6857 11.0619 21.4857 12.8048 21.4857
14.9952C21.4857 19.0048 18.581 22.3762 14.8571 23.5476C18.2857 22.4048
20.6095 17.8429 17.5333 13.2429L19.6286 9.49047ZM16.3524 11.6714L18.4571
7.9C16.5714 5.5 14.4952 3.28095 14.4952 0.0142822C13.0571 1.92857 11.7619
5.5 16.3524 11.6714V11.6714Z"
fill="url(#paint4_linear_20346_7102)"
/>
<path
d="M8.15238 14.6429L4.7619 20.7286C3.37143 19.1762 2.51428 17.1857
2.51428 14.9952C2.51428 11.5 4.50476 8.00476 7.00952 7.00476C5.71428
9.15714 5.91428 11.6714 8.15238 14.6429ZM9.4 16.1095L6.12381 21.9857L6.35238
22.1571C10.6095 25.1381 13.419 20.4143 9.4 16.1095V16.1095Z"
fill="url(#paint5_linear_20346_7102)"
/>
<path
d="M19.6286 9.49047C20.6857 11.0619 21.4857 12.8048 21.4857
14.9952C21.4857 19.9857 16.9905 23.9857 12 23.9857C10.6329 23.9805 9.28249
23.6851 8.03809 23.119C11.4667 24.6238 13.0857 23.1095 13.5048 20.4714L19.6286
9.49047ZM18.4571 7.9C16.5714 5.5 14.4952 3.28095 14.4952 0.0142822C13.4952
0.0142822 7.99999 3.50952 11.4952 10.5C12.4846 12.4997 13.15 14.6439
13.4667 16.8524L18.4571 7.9Z"
fill="url(#paint6_linear_20346_7102)"
/>
<path
d="M19.6286 9.49047C20.6857 11.0619 21.4857 12.8048 21.4857 14.9952C21.4857
19.0048 18.581 22.3762 14.8571 23.5476C18.2857 22.4048 20.6095 17.8429 17.5333
13.2429L19.6286 9.49047ZM16.3524 11.6714L18.4571 7.9C16.5714 5.5 14.4952
3.28095 14.4952 0.0142822C13.0571 1.92857 11.7619 5.5 16.3524 11.6714V11.6714Z"
fill="url(#paint7_linear_20346_7102)"
/>
<path
d="M21.4857 6.48096C21.4857 6.85226 21.3382 7.20835 21.0757 7.4709C20.8131
7.73346 20.457 7.88096 20.0857 7.88096C19.7144 7.88096 19.3583 7.73346 19.0958
7.4709C18.8332 7.20835 18.6857 6.85226 18.6857 6.48096C18.6857 5.48096 19.5905
5.48096 19.0857 3.98572C21.0857 4.49048 21.4857 5.7381 21.4857 6.48096Z"
fill="url(#paint8_linear_20346_7102)"
/>
</g>
<defs>
<linearGradient
id="paint0_linear_20346_7102"
x1="14.3971"
y1="11.979"
x2="4.91809"
y2="17.339"
gradientUnits="userSpaceOnUse"
>
<stop offset="0.18" stopColor="#FFE187" />
<stop offset="0.24" stopColor="#FFD986" />
<stop offset="0.33" stopColor="#FFC384" />
<stop offset="0.44" stopColor="#FFA081" />
<stop offset="0.55" stopColor="#FF737D" />
</linearGradient>
<linearGradient
id="paint1_linear_20346_7102"
x1="20.2667"
y1="13.3105"
x2="9.55333"
y2="11.4219"
gradientUnits="userSpaceOnUse"
>
<stop offset="0.24" stopColor="#FFE187" />
<stop offset="0.28" stopColor="#FFE187" stopOpacity="0.95" />
<stop offset="0.36" stopColor="#FFE187" stopOpacity="0.83" />
<stop offset="0.46" stopColor="#FFE187" stopOpacity="0.62" />
<stop offset="0.58" stopColor="#FFE187" stopOpacity="0.34" />
<stop offset="0.72" stopColor="#FFE187" stopOpacity="0" />
</linearGradient>
<linearGradient
id="paint2_linear_20346_7102"
x1="6.92666"
y1="7.00667"
x2="6.92666"
y2="23.0914"
gradientUnits="userSpaceOnUse"
>
<stop offset="0.14" stopColor="#FFE187" />
<stop offset="0.35" stopColor="#FFC084" />
<stop offset="0.78" stopColor="#FF737D" />
</linearGradient>
<linearGradient
id="paint3_linear_20346_7102"
x1="13.1248"
y1="0.13333"
x2="15.1905"
y2="23.7419"
gradientUnits="userSpaceOnUse"
>
<stop offset="0.25" stopColor="#FFE187" />
<stop offset="0.33" stopColor="#FFD286" />
<stop offset="0.67" stopColor="#FF8E7F" />
<stop offset="0.83" stopColor="#FF737D" />
</linearGradient>
<linearGradient
id="paint4_linear_20346_7102"
x1="20.44"
y1="10.1286"
x2="11.3733"
y2="12.7286"
gradientUnits="userSpaceOnUse"
>
<stop offset="0.04" stopColor="#FFE187" />
<stop offset="13%" stopColor="#FFD686" />
<stop offset="0.29" stopColor="#FFBA83" />
<stop offset="0.49" stopColor="#FF8B7F" />
<stop offset="0.59" stopColor="#FF737D" />
</linearGradient>
<linearGradient
id="paint5_linear_20346_7102"
x1="10.4086"
y1="13.9848"
x2="2.87524"
y2="17.659"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#FFE187" />
<stop offset="0.03" stopColor="#FFE187" stopOpacity="0.92" />
<stop offset="0.12" stopColor="#FFE187" stopOpacity="0.71" />
<stop offset="0.21" stopColor="#FFE187" stopOpacity="0.52" />
<stop offset="0.31" stopColor="#FFE187" stopOpacity="0.36" />
<stop offset="0.4" stopColor="#FFE187" stopOpacity="0.23" />
<stop offset="0.5" stopColor="#FFE187" stopOpacity="0.13" />
<stop offset="0.6" stopColor="#FFE187" stopOpacity="0.06" />
<stop offset="0.71" stopColor="#FFE187" stopOpacity="0.01" />
<stop offset="0.83" stopColor="#FFE187" stopOpacity="0" />
</linearGradient>
<linearGradient
id="paint6_linear_20346_7102"
x1="20.8686"
y1="10.7248"
x2="6.30666"
y2="13.2924"
gradientUnits="userSpaceOnUse"
>
<stop offset="0.11" stopColor="#FFE187" />
<stop offset="0.15" stopColor="#FFE187" stopOpacity="0.8" />
<stop offset="0.19" stopColor="#FFE187" stopOpacity="0.62" />
<stop offset="0.23" stopColor="#FFE187" stopOpacity="0.45" />
<stop offset="0.27" stopColor="#FFE187" stopOpacity="0.31" />
<stop offset="0.32" stopColor="#FFE187" stopOpacity="0.2" />
<stop offset="0.37" stopColor="#FFE187" stopOpacity="0.11" />
<stop offset="0.42" stopColor="#FFE187" stopOpacity="0.05" />
<stop offset="0.48" stopColor="#FFE187" stopOpacity="0.01" />
<stop offset="0.57" stopColor="#FFE187" stopOpacity="0" />
</linearGradient>
<linearGradient
id="paint7_linear_20346_7102"
x1="19.5819"
y1="21.6152"
x2="14.5743"
y2="10.099"
gradientUnits="userSpaceOnUse"
>
<stop offset="0.41" stopColor="#FF737D" />
<stop offset="0.46" stopColor="#FF737D" stopOpacity="0.95" />
<stop offset="0.54" stopColor="#FF737D" stopOpacity="0.83" />
<stop offset="0.65" stopColor="#FF737D" stopOpacity="0.62" />
<stop offset="0.79" stopColor="#FF737D" stopOpacity="0.34" />
<stop offset="0.93" stopColor="#FF737D" stopOpacity="0" />
</linearGradient>
<linearGradient
id="paint8_linear_20346_7102"
x1="18.4324"
y1="4.64477"
x2="21.9419"
y2="8.15429"
gradientUnits="userSpaceOnUse"
>
<stop offset="0.11" stopColor="#FFE187" />
<stop offset="0.35" stopColor="#FFC084" />
<stop offset="0.84" stopColor="#FF737D" />
</linearGradient>
<clipPath id="clip0_20346_7102">
<rect
width="18.9714"
height="23.9714"
fill="white"
transform="translate(2.51428 0.0142822)"
/>
</clipPath>
</defs>
</>
);
export default NumberFire;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/OptedIn.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const OptedIn = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M12.6518 2.62793H19.8728C20.7012 2.62793 21.3728 3.2995 21.3728
4.12793V11.3489C21.3728 11.7664 21.1988 12.165 20.8927 12.4488L11.6956
20.9766C11.1042 21.5249 10.1852 21.5076 9.61501 20.9374L3.06336
14.3857C2.49314 13.8155 2.4758 12.8965 3.02409 12.3051L11.5519
3.10805C11.8358 2.80192 12.2343 2.62793 12.6518 2.62793Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M9 10.5L12 13.5L18 7.5M19.8728 2.62793H12.6518C12.2343 2.62793 11.8358
2.80192 11.5519 3.10805L3.02409 12.3051C2.4758 12.8965 2.49314 13.8155
3.06336 14.3857L9.61501 20.9374C10.1852 21.5076 11.1042 21.5249 11.6956
20.9766L20.8927 12.4488C21.1988 12.165 21.3728 11.7664 21.3728
11.3489V4.12793C21.3728 3.2995 20.7012 2.62793 19.8728 2.62793Z"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Plus.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Plus = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M22.8755 12.0042C22.8755 18.0105 18.0064 22.8797 12 22.8797C5.99363
22.8797 1.12451 18.0105 1.12451 12.0042C1.12451 5.99782 5.99363 1.12871
12 1.12871C18.0064 1.12871 22.8755 5.99782 22.8755 12.0042Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M12.0001 6V12M12.0001 12V18M12.0001 12H18.0001M12.0001
12H6.00006M22.8755 12.0042C22.8755 18.0105 18.0064 22.8797 12
22.8797C5.99363 22.8797 1.12451 18.0105 1.12451 12.0042C1.12451
5.99782 5.99363 1.12871 12 1.12871C18.0064 1.12871 22.8755 5.99782
22.8755 12.0042Z"
stroke={lineColor}
strokeWidth={strokeWidth}
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Popout.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Popout = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M4.125 17.625V6.375C4.125 5.13236 5.13236 4.125 6.375
4.125H17.625C18.8676 4.125 19.875 5.13236 19.875 6.375V17.625C19.875
18.8676 18.8676 19.875 17.625 19.875H6.375C5.13236 19.875 4.125 18.8676
4.125 17.625Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M14.25 4.125H6.375C5.13236 4.125 4.125 5.13236 4.125 6.375V17.625C4.125
18.8676 5.13236 19.875 6.375 19.875H17.625C18.8676 19.875 19.875 18.8676
19.875 17.625V9.75M13.5 10.5L22.4971 1.50293M16.5 1.125L22.8751
1.12491L22.875 7.5"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Promo.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Promo = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<path
fillRule="evenodd"
clipRule="evenodd"
d="M19.8728 2.62793H12.6518C12.2343 2.62793 11.8358 2.80192 11.5519
3.10805L3.02409 12.3051C2.4758 12.8965 2.49314 13.8155 3.06336
14.3857L9.61501 20.9374C10.1852 21.5076 11.1042 21.5249 11.6956
20.9766L20.8927 12.4488C21.1988 12.165 21.3728 11.7664 21.3728
11.3489V4.12793C21.3728 3.2995 20.7012 2.62793 19.8728 2.62793ZM15.749
9.37308C16.3698 9.37308 16.8731 8.86983 16.8731 8.24904C16.8731 7.62825
16.3698 7.125 15.749 7.125C15.1282 7.125 14.625 7.62825 14.625
8.24904C14.625 8.86983 15.1282 9.37308 15.749 9.37308Z"
fill={backgroundColor}
fillOpacity="1"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/ReferFriend.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const ReferFriend = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M7.27024 13.4973H16.7295C17.7442 13.4973 18.6334 14.1765 18.9003
15.1555L20.0811 19.4867C20.3413 20.4409 19.6229 21.3813 18.6339
21.3813H5.3658C4.37679 21.3813 3.65848 20.4409 3.91862 19.4867L5.09947
15.1555C5.36637 14.1765 6.25552 13.4973 7.27024 13.4973Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M15.7522 6.37019C15.7522 8.44241 14.0723 10.1223 12.0001 10.1223C9.9279
10.1223 8.24803 8.44241 8.24803 6.37019C8.24803 4.29797 9.9279 2.6181
12.0001 2.6181C14.0723 2.6181 15.7522 4.29797 15.7522 6.37019Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M12.75 21.3813H5.36602C4.37702 21.3813 3.6587 20.4409 3.91884
19.4867L5.09969 15.1555C5.36659 14.1765 6.25575 13.4973 7.27046
13.4973H12.75M14.625 18H22.8047M19.125 14.25L22.875 18L19.125
21.75M15.7522 6.37019C15.7522 8.44241 14.0723 10.1223 12.0001
10.1223C9.9279 10.1223 8.24803 8.44241 8.24803 6.37019C8.24803 4.29797
9.9279 2.6181 12.0001 2.6181C14.0723 2.6181 15.7522 4.29797 15.7522
6.37019Z"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Refresh.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Refresh = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<circle
cx="11.9999"
cy="12.0042"
r="9.37333"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M11.9606 21.375C6.80467 21.375 2.62494 17.1953 2.62494 12.0393C2.62494
9.54156 3.60584 7.27292 5.20343 5.59758L8.09741 2.70361M12.0393
2.63086C17.1953 2.63086 21.375 6.81059 21.375 11.9666C21.375 14.4607
20.3969 16.7265 18.8033 18.4011L15.9022 21.3022M22.1249
21.3825H15.5806V15.1601M1.87494 2.6299H8.41933V8.625"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Repeat.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Repeat = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M13.741 4.1212C17.1373 4.1212 21.375 6.74509 21.375 12C21.375 17.2549
17.1373 19.8788 13.741 19.8788H10.2592C6.97951 19.8788 2.625 17.2549 2.625
12C2.625 6.74509 6.86288 4.1212 10.2592 4.1212H13.741Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M6 4.12119L9.31742 0.803741M6 4.12119L9.31742 7.43861M6
4.12119H13.7408C17.1371 4.12119 21.375 6.74508 21.375 12C21.375 13.1214
21.1767 14.1231 20.8328 15.0049M18 19.8788L14.6826 16.5614M18
19.8788L14.6826 23.1963M18 19.8788H10.259C6.8627 19.8788 2.625 17.2549
2.625 12C2.625 10.8842 2.81608 9.88694 3.1496 9.00828"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Replay.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Replay = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M22.8755 12.0042C22.8755 18.0105 18.0064 22.8797 12 22.8797C5.99366
22.8797 1.12454 18.0105 1.12454 12.0042C1.12454 5.99782 5.99366 1.12871
12 1.12871C18.0064 1.12871 22.8755 5.99782 22.8755 12.0042ZM16.5 12L9
16.5V7.5L16.5 12Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M1.12033 12C1.12033 18.0087 5.99132 22.8797 12 22.8797C18.0087 22.8797
22.8797 18.0087 22.8797 12C22.8797 5.99132 18.0087 1.12033 12
1.12033C9.00162 1.12033 6.28654 2.33325 4.31864 4.29519L1.16629
7.44754M1.11914 2.61914V7.5H6M9.00064 7.5V16.5019L16.4992 12L9.00064 7.5Z"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Result.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Result = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M18.3743 8.99929C18.3743 12.5197 15.5204 15.3736 12 15.3736C8.47958
15.3736 5.62571 12.5197 5.62571 8.99929C5.62571 5.47887 8.47958 2.625 12
2.625C15.5204 2.625 18.3743 5.47887 18.3743 8.99929ZM12.0014
10.9912C13.1007 10.9912 13.9919 10.1001 13.9919 9.00078C13.9919 7.90149
13.1007 7.01033 12.0014 7.01033C10.9021 7.01033 10.011 7.90149 10.011
9.00078C10.011 10.1001 10.9021 10.9912 12.0014 10.9912Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M10.125 15.0933V21.3667H13.875V15.0934M18.3743 8.99929C18.3743 12.5197
15.5204 15.3736 12 15.3736C8.47958 15.3736 5.62571 12.5197 5.62571
8.99929C5.62571 5.47887 8.47958 2.625 12 2.625C15.5204 2.625 18.3743
5.47887 18.3743 8.99929ZM13.9919 9.00078C13.9919 10.1001 13.1007 10.9912
12.0014 10.9912C10.9021 10.9912 10.011 10.1001 10.011 9.00078C10.011
7.90149 10.9021 7.01033 12.0014 7.01033C13.1007 7.01033 13.9919 7.90149
13.9919 9.00078Z"
stroke={lineColor}
strokeWidth={strokeWidth}
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Rs.tsx
import React from "react";
export const Rs = () => (
<>
<path
d="M20.8979 10.5487C20.8746 10.3853 20.8279 10.2687 20.7346 10.152C20.6646
10.0587 20.5713 9.96536 20.4546 9.91869C20.2446 9.80203 19.988 9.75537
19.6847 9.75537C19.358 9.75537 19.1014 9.80203 18.9614 9.89536C18.8214
9.98869 18.7281 10.1053 18.7281 10.292C18.7281 10.4553 18.7981 10.5953
18.9614 10.712C19.1247 10.8286 19.3114 10.922 19.568 11.0153C19.8247
11.1086 20.1046 11.1786 20.408 11.2486C20.7113 11.3186 21.0379 11.4119
21.3646 11.5053C21.6912 11.5986 22.0179 11.7152 22.3212 11.8319C22.6245
11.9719 22.9045 12.1352 23.1611 12.3452C23.4178 12.5552 23.6044 12.8118
23.7677 13.0918C23.9311 13.3951 24.0011 13.7451 24.0011 14.1651C24.0011
14.7017 23.8844 15.1684 23.6744 15.565C23.4644 15.9616 23.1611 16.2883
22.7878 16.5449C22.4145 16.8016 21.9479 16.9882 21.4346 17.1282C20.8979
17.2682 20.338 17.3149 19.708 17.3149C19.078 17.3149 18.5647 17.2216
18.0748 17.0582C17.5848 16.8949 17.1648 16.6616 16.8148 16.3816C16.4649
16.1016 16.1849 15.775 15.9982 15.4017C15.7882 15.0284 15.6949 14.6317
15.6716 14.2351H18.5403C18.6103 14.5617 18.7737 14.7951 19.0303
14.9584C19.147 15.0284 19.287 15.0984 19.427 15.1217C19.5903 15.1684
19.7303 15.1684 19.8703 15.1684C20.2436 15.1684 20.5469 15.1217 20.7802
15.005C21.0135 14.8884 21.1068 14.7251 21.1068 14.4917C21.1068 14.2584
20.9669 14.0951 20.7102 13.9551C20.4536 13.8384 20.1269 13.7218 19.7303
13.6285C19.3336 13.5351 18.9137 13.4185 18.447 13.3018C17.9804 13.1852
17.5604 13.0218 17.1638 12.8118C16.7671 12.6019 16.4405 12.3219 16.1838
11.9486C15.9272 11.5986 15.7872 11.1319 15.7872 10.5253C15.7872 10.0354
15.8805 9.61538 16.0905 9.24207C16.3005 8.86876 16.5571 8.56544 16.9071
8.33213C17.2571 8.09881 17.6771 7.91215 18.167 7.79549C18.657 7.67883
19.1703 7.60884 19.7536 7.60884C20.3836 7.60884 20.9435 7.67883 21.4102
7.84216C21.8768 8.00548 22.2734 8.19213 22.5768 8.47212C22.9034 8.72877
23.1367 9.03208 23.3234 9.40539C23.51 9.75537 23.6267 10.1287 23.6734
10.5253H20.8979V10.5487Z"
fill="#B1B235"
/>
<path
d="M10.2798 10.8286V11.9708H11.9597L10.2798
13.3241V14.5373H13.9652V13.3241H12.3086L13.9652 11.9942V10.8286H10.2798Z"
fill="#B1B235"
/>
<path
d="M10.2798 15.1206V17.0561C10.2798 17.0561 10.3731 18.7127 12.123
18.7127C13.8729 18.7127 13.9662 17.0561 13.9662
17.0561V15.1206H10.2798ZM12.9152 16.8239C12.9152 16.8239 12.8453 17.5471
12.122 17.5471C11.3987 17.5471 11.3287 16.8239 11.3287
16.8239V16.3339H12.9152V16.8239Z"
fill="#B1B235"
/>
<path
d="M10.2798 6V7.39991L10.6998 7.58657V8.98648L10.2798
9.19646V10.503L13.9652 8.96315V7.65656L10.2798 6ZM11.6331
8.58878V7.88882L12.683 8.2388L11.6331 8.58878Z"
fill="#B1B235"
/>
<path
d="M8.81732 10.7586C8.86399 8.77649 6.81184 8.19319 5.87857
8.19319H1.44658L0 17.2661H2.49545L3.05541 13.954H3.8487L5.24861
17.2661H8.02404L6.36748 13.7907C6.36748 13.7907 8.77066 12.9041 8.81732
10.7586ZM5.80857 11.8552C5.57525 12.0652 5.3886 12.1586 5.08528
12.1586H3.3354L3.66204 10.1531H4.8753C5.17861 10.1531 5.52859 10.0831
5.80857 10.2697C6.06522 10.4331 6.18188 10.7597 6.18188 11.0397C6.18188
11.3897 6.04189 11.6686 5.80857 11.8552Z"
fill="#004693"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/ScheduledRaces.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const ScheduledRaces = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M16.8732 21.375C20.1856 21.375 22.8709 18.6887 22.8709 15.375C22.8709
12.0613 20.1856 9.375 16.8732 9.375C13.5607 9.375 10.8755 12.0613 10.8755
15.375C10.8755 18.6887 13.5607 21.375 16.8732 21.375Z"
fill={backgroundColor}
/>
<path d="M16.6651 13.5V16.2512L18.9142 17.25" fill={backgroundColor} />
<path
d="M17.6651 13.5C17.6651 12.9477 17.2173 12.5 16.6651 12.5C16.1128 12.5
15.6651 12.9477 15.6651 13.5H17.6651ZM16.6651 16.2512H15.6651C15.6651
16.6465 15.8979 17.0047 16.2592 17.1651L16.6651 16.2512ZM18.5083
18.1639C19.0131 18.3881 19.604 18.1606 19.8281 17.6559C20.0523 17.1511
19.8248 16.5602 19.3201 16.3361L18.5083 18.1639ZM3.625
19.875V8.625H1.625V19.875H3.625ZM3.625
8.625V4.875H1.625V8.625H3.625ZM20.375
4.875V7.50586H22.375V4.875H20.375ZM4.125 20.375C3.84886 20.375
3.625 20.1511 3.625 19.875H1.625C1.625 21.2557 2.74429 22.375 4.125
22.375V20.375ZM19.125 3.625C19.8154 3.625 20.375 4.18464 20.375
4.875H22.375C22.375 3.08007 20.9199 1.625 19.125 1.625V3.625ZM4.875
1.625C3.08007 1.625 1.625 3.08007 1.625 4.875H3.625C3.625 4.18464
4.18464 3.625 4.875 3.625V1.625ZM4.875
3.625H8.625V1.625H4.875V3.625ZM8.625
3.625H15.375V1.625H8.625V3.625ZM15.375
3.625H19.125V1.625H15.375V3.625ZM14.375 0V2.625H16.375V0H14.375ZM14.375
2.625V6H16.375V2.625H14.375ZM7.625 0V2.625H9.625V0H7.625ZM7.625
2.625L7.625 6L9.625 6L9.625 2.625L7.625 2.625ZM2.625
9.625H9.75V7.625H2.625V9.625ZM9.75
20.375H4.125V22.375H9.75V20.375ZM21.8709 15.375C21.8709 18.1368 19.633
20.375 16.8732 20.375V22.375C20.7383 22.375 23.8709 19.2406 23.8709
15.375H21.8709ZM16.8732 20.375C14.1134 20.375 11.8755 18.1368 11.8755
15.375H9.87546C9.87546 19.2406 13.0081 22.375 16.8732
22.375V20.375ZM11.8755 15.375C11.8755 12.6132 14.1134 10.375 16.8732
10.375V8.375C13.0081 8.375 9.87546 11.5094 9.87546 15.375H11.8755ZM16.8732
10.375C19.633 10.375 21.8709 12.6132 21.8709 15.375H23.8709C23.8709
11.5094 20.7383 8.375 16.8732 8.375V10.375ZM15.6651
13.5V16.2512H17.6651V13.5H15.6651ZM16.2592 17.1651L18.5083
18.1639L19.3201 16.3361L17.0709 15.3372L16.2592 17.1651Z"
fill={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Search.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Search = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M17.625 10.125C17.625 14.2671 14.2671 17.625 10.125 17.625C5.98286
17.625 2.625 14.2671 2.625 10.125C2.625 5.98286 5.98286 2.625 10.125
2.625C14.2671 2.625 17.625 5.98286 17.625 10.125Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M15.4283 15.4283L21 21M17.625 10.125C17.625 14.2671 14.2671 17.625
10.125 17.625C5.98286 17.625 2.625 14.2671 2.625 10.125C2.625 5.98286
5.98286 2.625 10.125 2.625C14.2671 2.625 17.625 5.98286 17.625 10.125Z"
stroke={lineColor}
strokeWidth={strokeWidth}
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Settings.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Settings = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<path
fillRule="evenodd"
clipRule="evenodd"
d="M10.5 2.625H13.5L14.1218 5.11853L15.3653 5.63392L17.5684 4.31021L19.6897
6.43153L18.3661 8.63467L18.8815 9.87823L21.375 10.5V13.5L18.8816
14.1218L18.3661 15.3654L19.6898 17.5685L17.5685 19.6898L15.3653
18.3662L14.1218 18.8816L13.5 21.375H10.5L9.87822 18.8815L8.63467
18.3661L6.43149 19.6898L4.31017 17.5685L5.63392 15.3653L5.11853
14.1218L2.625 13.5V10.5L5.11857 9.87826L5.63396 8.63477L4.31021
6.43158L6.43153 4.31026L8.63473 5.63399L9.87824 5.11857L10.5 2.625ZM12
15C13.6569 15 15 13.6569 15 12C15 10.3431 13.6569 9 12 9C10.3431 9 9 10.3431
9 12C9 13.6569 10.3431 15 12 15Z"
fill={backgroundColor}
fillOpacity="1"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Share.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const Share = ({ lineColor, strokeWidth }: IconPathProps) => (
<path
d="M7.50414 7.87555H6.38028C5.13764 7.87555 4.13028 8.88348 4.13028
10.1268V17.6311C4.13028 18.8745 5.13764 19.8824 6.38028
19.8824H17.625C18.8676 19.8824 19.875 18.8745 19.875 17.6311V10.1268C19.875
8.88348 18.8676 7.87555 17.625 7.87555H16.5011M8.33356 4.80098L12
1.13242L15.6665 4.80098M12 13.5747L12 1.66733"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/SortAscending.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const SortAscending = ({ lineColor, strokeWidth }: IconPathProps) => (
<path
d="M6 21V4.57031M1.5 9L6 4.5L10.5 9M13.5 18.375H22.5M13.5 12H19.5M13.5
5.625H16.5"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/SortDescending.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const SortDescending = ({ lineColor, strokeWidth }: IconPathProps) => (
<path
d="M6 3V19.4297M1.5 15L6 19.5L10.5 15M13.5 5.625H22.5M13.5 12H19.5M13.5
18.375H16.5"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Stable.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Stable = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M21.375 21.375V11.9819L19.41 6.27321L12 3L4.56661 6.27321L2.625
11.9819V21.375H6.375V13.5H17.625V21.375H21.375Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M6.375 21.375H2.625V11.9819L4.56661 6.27321L12 3L19.41 6.27321L21.375
11.9819V21.375H17.625M6.375 21.375V13.5H17.625V21.375M6.375
21.375H17.625M17.625 21.375L6.4043 13.5293"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Star.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Star = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<path
d="M12 2.92539L14.9438 8.8901L21.5262 9.84659L16.7631 14.4895L17.8875
21.0453L12 17.9501L6.11248 21.0453L7.23689 14.4895L2.47379 9.84659L9.05624
8.8901L12 2.92539Z"
fill={backgroundColor}
fillOpacity="1"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Store.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Store = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M2.71301 8.59024L4.01412 2.62555H19.9859L21.287 8.59024C21.6573 10.5681
20.8475 11.7774 19.8363 12.0697C18.4347 12.4748 15.3822 12.3755 15.3822
9.31671H14.9849C14.9849 10.3736 14.693 12.3755 12.0297
12.3755H11.9703C9.30696 12.3755 9.0025 10.3736 9.0025
9.31671H8.61782C8.61782 12.3755 5.56532 12.4748 4.16368 12.0697C3.15253
11.7774 2.34266 10.5681 2.71301 8.59024Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M4.125 16.1245V21.3745H19.875V16.1245M4.01412 2.62555L2.71301
8.59024C2.34266 10.5681 3.15253 11.7774 4.16368 12.0697C5.56532 12.4748
8.61782 12.3755 8.61782 9.31671H9.0025C9.0025 10.3736 9.30696 12.3755
11.9703 12.3755H12.0297C14.693 12.3755 14.9849 10.3736 14.9849
9.31671H15.3822C15.3822 12.3755 18.4347 12.4748 19.8363 12.0697C20.8475
11.7774 21.6573 10.5681 21.287 8.59024L19.9859 2.62555H4.01412Z"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinecap="round"
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Success.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Success = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M22.8755 12.0042C22.8755 18.0105 18.0063 22.8797 12 22.8797C5.99363
22.8797 1.12451 18.0105 1.12451 12.0042C1.12451 5.99782 5.99363 1.12871
12 1.12871C18.0063 1.12871 22.8755 5.99782 22.8755 12.0042Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M6.75006 12L10.5001 15.75L18.0001 8.25M22.8755 12.0042C22.8755 18.0105
18.0063 22.8797 12 22.8797C5.99363 22.8797 1.12451 18.0105 1.12451
12.0042C1.12451 5.99782 5.99363 1.12871 12 1.12871C18.0063 1.12871 22.8755
5.99782 22.8755 12.0042Z"
stroke={lineColor}
strokeWidth={strokeWidth}
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Support.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Support = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M22.8755 12.0042C22.8755 18.0105 18.0064 22.8797 12 22.8797C5.99363
22.8797 1.12451 18.0105 1.12451 12.0042C1.12451 5.99782 5.99363 1.12871
12 1.12871C18.0064 1.12871 22.8755 5.99782 22.8755 12.0042Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M12 18V15.75M8.99997 9C8.99997 9 8.99997 6 12 6C15 6 15 9 15 9C15 12
12 11.25 12 14.25M22.8755 12.0042C22.8755 18.0105 18.0064 22.8797 12
22.8797C5.99363 22.8797 1.12451 18.0105 1.12451 12.0042C1.12451 5.99782
5.99363 1.12871 12 1.12871C18.0064 1.12871 22.8755 5.99782 22.8755
12.0042Z"
stroke={lineColor}
strokeWidth={strokeWidth}
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Tick.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const Tick = ({ lineColor, strokeWidth }: IconPathProps) => (
<path
d="M3.75 12L9 17.25L20.25 6"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/TimeForm.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const TimeForm = ({ lineColor }: IconPathProps) => (
<path
fillRule="evenodd"
clipRule="evenodd"
d="M2 0C0.895431 0 0 0.89543 0 2V22C0 23.1046 0.89543 24 2
24H22C23.1046 24 24 23.1046 24 22V2C24 0.895431 23.1046 0 22 0H2ZM8.71289
9.11572H11.9795V7.33594H3.29297V9.11572H6.51562V18H8.71289V9.11572ZM15.4365
13.6421H19.6553V11.8696H15.4365V9.11572H20.1826V7.33594H13.2393V18H15.4365V13.6421Z"
fill={lineColor}
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/TrackMaster.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const TrackMaster = ({ lineColor }: IconPathProps) => (
<>
<path
d="M12.7552 20.9722C18.6253 20.9722 23.2604 16.8559 23.2604 11.959C23.2604
7.06213 18.6253 2.9458 12.7552 2.9458C6.88509 2.9458 2.25 7.06213 2.25
11.959C2.25 16.8559 6.88509 20.9722 12.7552 20.9722ZM12 22.494C5.37258
22.494 0 17.7942 0 11.9968C0 6.19936 5.37258 1.4996 12 1.4996C18.6274
1.4996 24 6.19936 24 11.9968C24 17.7942 18.6274 22.494 12 22.494Z"
fill={lineColor}
/>
<path
d="M10.9636 9.11258H8.66371L7.27981 17.0931H5.38188L6.76578
9.11258H4.49881L4.78218 7.49802H11.247L10.9636 9.11258ZM14.069 7.49802L14.6292
14.3978L17.5749 7.49802H20.0659L18.3987 17.0931H16.5007L16.962 14.4373L17.7924
10.6481L14.8532 17.0931H13.5682L12.8433 10.4306L12.2963 14.5625L11.8613
17.0931H9.97001L11.6307 7.49802H14.069Z"
fill={lineColor}
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Tracks.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Tracks = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M13.741 4.12118C17.1373 4.12118 21.375 6.74507 21.375 12C21.375 17.2549
17.1373 19.8788 13.741 19.8788H10.2592C6.97951 19.8788 2.625 17.2549 2.625
12C2.625 6.74507 6.86288 4.12118 10.2592 4.12118H13.741ZM13.5
8.62653H10.5C9 8.62653 7.1283 9.75 7.1283 12C7.1283 14.25 9.05151 15.3735
10.5 15.3735H13.5C15 15.3735 16.8716 14.25 16.8716 12C16.8716 9.75 15
8.62653 13.5 8.62653Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M13.741 4.12118C17.1373 4.12118 21.375 6.74507 21.375 12C21.375 17.2549
17.1373 19.8788 13.741 19.8788H10.2592M13.741 4.12118H10.2592C6.86288
4.12118 2.625 6.74507 2.625 12C2.625 17.2549 6.97951 19.8788 10.2592
19.8788M13.741 4.12118H22.5M10.2592 19.8788H1.5M10.5 8.62653H13.5C15
8.62653 16.8716 9.75 16.8716 12C16.8716 14.25 15 15.3735 13.5
15.3735H10.5C9.05151 15.3735 7.1283 14.25 7.1283 12C7.1283 9.75 9
8.62653 10.5 8.62653Z"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Trash.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Trash = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M4.5 6.375L5.86185 20.028C5.94033 20.7932 6.58486 21.375 7.35403
21.375H16.646C17.4152 21.375 18.0597 20.7932 18.1382 20.028L19.5
6.375H15.75H8.25H4.5Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M9.75 9V18.375M14.25 9V18.375M4.5 6.375H8.25M4.5 6.375H1.50008M4.5
6.375L5.86185 20.028C5.94033 20.7932 6.58486 21.375 7.35403
21.375H16.646C17.4152 21.375 18.0597 20.7932 18.1382 20.028L19.5
6.375M19.5 6.375H15.75M19.5 6.375H22.5001M15.75 6.375H8.25M15.75
6.375V4.125C15.75 3.29657 15.0784 2.625 14.25 2.625H9.75C8.92158 2.625
8.25 3.29657 8.25 4.125V6.375"
stroke={lineColor}
strokeWidth={strokeWidth}
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/TvgPicks.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const TvgPicks = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M3.93367 19.4495L4.77323 16.6117C5.05601 15.6558 5.93399 15 6.93078
15H14.0664C15.0646 15 15.9434 15.6576 16.225 16.6151L17.0593
19.4518C17.3419 20.4125 16.6217 21.375 15.6203 21.375H5.37204C4.36963
21.375 3.64929 20.4107 3.93367 19.4495Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M13.1297 9C13.1297 10.4523 11.9523 11.6297 10.5 11.6297C9.04768 11.6297
7.87034 10.4523 7.87034 9C7.87034 7.54768 9.04768 6.37034 10.5
6.37034C11.9523 6.37034 13.1297 7.54768 13.1297 9Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M12.0004 21.3747H5.37252C4.37011 21.3747 3.64977 20.4104 3.93415
19.4492L4.77371 16.6114C5.05649 15.6556 5.93447 14.9997 6.93126
14.9997H12.0005M14.2512 17.9997L17.2512 20.9997L23.2512 14.9997M22.8764
11.9997V4.87473C22.8764 3.63209 21.8691 2.62473 20.6264
2.62473H3.37644C2.1338 2.62473 1.12644 3.63209 1.12644
4.87473V11.2497V19.1247C1.12644 20.3674 2.1338 21.3747 3.37644
21.3747H10.5014M13.1297 9C13.1297 10.4523 11.9523 11.6297 10.5
11.6297C9.04768 11.6297 7.87034 10.4523 7.87034 9C7.87034 7.54768
9.04768 6.37034 10.5 6.37034C11.9523 6.37034 13.1297 7.54768 13.1297 9Z"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/User.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const User = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M15.7521 6.37018C15.7521 8.4424 14.0723 10.1223 12 10.1223C9.92781
10.1223 8.24794 8.4424 8.24794 6.37018C8.24794 4.29796 9.92781 2.61809 12
2.61809C14.0723 2.61809 15.7521 4.29796 15.7521 6.37018Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M18.8997 15.1584C18.6327 14.1795 17.7436 13.5004 16.729
13.5004H7.27011C6.25547 13.5004 5.36636 14.1795 5.09939 15.1584L3.91897
19.4866C3.65873 20.4408 4.37706 21.3813 5.36612 21.3813H18.633C19.622
21.3813 20.3404 20.4408 20.0801 19.4866L18.8997 15.1584Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M15.7521 6.37018C15.7521 8.4424 14.0723 10.1223 12 10.1223C9.92781
10.1223 8.24794 8.4424 8.24794 6.37018C8.24794 4.29796 9.92781 2.61809 12
2.61809C14.0723 2.61809 15.7521 4.29796 15.7521 6.37018Z"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
<path
d="M18.8997 15.1584C18.6327 14.1795 17.7436 13.5004 16.729
13.5004H7.27011C6.25547 13.5004 5.36636 14.1795 5.09939 15.1584L3.91897
19.4866C3.65873 20.4408 4.37706 21.3813 5.36612 21.3813H18.633C19.622
21.3813 20.3404 20.4408 20.0801 19.4866L18.8997 15.1584Z"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/UserCross.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const UserCross = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M7.27023 13.4973H16.7295C17.7442 13.4973 18.6334 14.1765 18.9003
15.1555L20.0811 19.4867C20.3412 20.4409 19.6229 21.3813 18.6339
21.3813H5.36579C4.37679 21.3813 3.65847 20.4409 3.91861 19.4867L5.09946
15.1555C5.36636 14.1765 6.25552 13.4973 7.27023 13.4973Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M15.7522 6.37019C15.7522 8.44241 14.0723 10.1223 12.0001 10.1223C9.9279
10.1223 8.24803 8.44241 8.24803 6.37019C8.24803 4.29797 9.9279 2.6181
12.0001 2.6181C14.0723 2.6181 15.7522 4.29797 15.7522 6.37019Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M12.75 21.3813H5.36602C4.37702 21.3813 3.6587 20.4409 3.91884
19.4867L5.09969 15.1555C5.36659 14.1765 6.25575 13.4973 7.27046
13.4973H12.75M15.75 14.25L19.5 18M19.5 18L23.25 21.75M19.5 18L15.75
21.75M19.5 18L23.25 14.25M15.7522 6.37019C15.7522 8.44241 14.0723 10.1223
12.0001 10.1223C9.9279 10.1223 8.24803 8.44241 8.24803 6.37019C8.24803
4.29797 9.9279 2.6181 12.0001 2.6181C14.0723 2.6181 15.7522 4.29797
15.7522 6.37019Z"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/UserPlus.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const UserPlus = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M7.27033 13.4973H16.7296C17.7443 13.4973 18.6334 14.1765 18.9004
15.1555L20.0812 19.4867C20.3413 20.4409 19.623 21.3813 18.634
21.3813H5.36589C4.37688 21.3813 3.65857 20.4409 3.91871 19.4867L5.09956
15.1555C5.36646 14.1765 6.25561 13.4973 7.27033 13.4973Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M15.7521 6.37019C15.7521 8.44241 14.0723 10.1223 12 10.1223C9.92781
10.1223 8.24794 8.44241 8.24794 6.37019C8.24794 4.29797 9.92781 2.6181 12
2.6181C14.0723 2.6181 15.7521 4.29797 15.7521 6.37019Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M12.75 21.3813H5.36594C4.37693 21.3813 3.65862 20.4409 3.91876
19.4867L5.09961 15.1555C5.36651 14.1765 6.25567 13.4973 7.27038
13.4973H12.75M19.4999 13.5V18M19.4999 18V22.5M19.4999 18H23.9999M19.4999
18H14.9999M15.7521 6.37019C15.7521 8.44241 14.0723 10.1223 12
10.1223C9.92781 10.1223 8.24794 8.44241 8.24794 6.37019C8.24794 4.29797
9.92781 2.6181 12 2.6181C14.0723 2.6181 15.7521 4.29797 15.7521 6.37019Z"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/UserTick.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const UserTick = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M7.27024 13.4973H16.7295C17.7442 13.4973 18.6334 14.1765 18.9003
15.1555L20.0811 19.4867C20.3413 20.4409 19.6229 21.3813 18.6339
21.3813H5.3658C4.37679 21.3813 3.65848 20.4409 3.91862 19.4867L5.09947
15.1555C5.36637 14.1765 6.25552 13.4973 7.27024 13.4973Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M15.7522 6.37019C15.7522 8.44241 14.0723 10.1223 12.0001 10.1223C9.9279
10.1223 8.24803 8.44241 8.24803 6.37019C8.24803 4.29797 9.9279 2.6181
12.0001 2.6181C14.0723 2.6181 15.7522 4.29797 15.7522 6.37019Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M12.75 21.3813H5.36602C4.37702 21.3813 3.6587 20.4409 3.91884
19.4867L5.09969 15.1555C5.36659 14.1765 6.25575 13.4973 7.27046
13.4973H12.75M14.25 18L17.25 21L23.25 15M15.7522 6.37019C15.7522 8.44241
14.0723 10.1223 12.0001 10.1223C9.9279 10.1223 8.24803 8.44241 8.24803
6.37019C8.24803 4.29797 9.9279 2.6181 12.0001 2.6181C14.0723 2.6181
15.7522 4.29797 15.7522 6.37019Z"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Video.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Video = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<path
fillRule="evenodd"
clipRule="evenodd"
d="M12 22.8797C18.0087 22.8797 22.8797 18.0087 22.8797 12C22.8797 5.99133
18.0087 1.12034 12 1.12034C5.99133 1.12034 1.12034 5.99133 1.12034
12C1.12034 18.0087 5.99133 22.8797 12 22.8797ZM8.62501 17.2318V6.755L16.89
12.0078L8.62501 17.2318Z"
fill={backgroundColor}
fillOpacity="1"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Wallet.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Wallet = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M21.375 8.62683H2.625V19.875H21.375V8.62683Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M21 4.125H2.625V8.85142M2.625 8.62683H21.375V19.875H2.625V8.62683Z"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
<path
d="M18.0002 15.3694C18.0002 15.9907 17.4965 16.4944 16.8752
16.4944C16.2539 16.4944 15.7502 15.9907 15.7502 15.3694C15.7502 14.7481
16.2539 14.2444 16.8752 14.2444C17.4965 14.2444 18.0002 14.7481 18.0002
15.3694Z"
fill={lineColor}
fillOpacity="1"
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Warning.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Warning = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<>
<path
d="M2.32142 21.375H21.6775C22.0524 21.375 22.294 20.9777 22.1214
20.6448L12.4439 1.981C12.2573 1.62122 11.7427 1.62121 11.5561
1.98099L1.87755 20.6448C1.70496 20.9777 1.9465 21.375 2.32142 21.375Z"
fill={backgroundColor}
fillOpacity="1"
/>
<path
d="M12 9V15M12 16.5V18.75M11.5561 1.98099L1.87755 20.6448C1.70496 20.9777
1.9465 21.375 2.32142 21.375H21.6775C22.0524 21.375 22.294 20.9777 22.1214
20.6448L12.4439 1.981C12.2573 1.62122 11.7427 1.62121 11.5561 1.98099Z"
stroke={lineColor}
strokeWidth={strokeWidth}
/>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Withdraw.tsx
import React from "react";
import { IconPathProps } from "../../types";
export const Withdraw = ({ lineColor, strokeWidth }: IconPathProps) => (
<path
d="M12 8.40001C12 8.40001 12 4.80002 7.5 4.80002M7.5 4.80002C3 4.80002 3
8.40001 3 8.40001C3 9.60001 3 10.8 7.5 12C12 13.2 12 14.4 12 15.6C12 15.6 12
19.2 7.5 19.2M7.5 4.80002V1.5M7.5 19.2C3 19.2 3 15.6 3 15.6M7.5
19.2V22.5M21.75 11.625L18 15.375L14.25 11.625M18 7.5V15.293"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/Pin.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const Pin = ({
backgroundColor,
lineColor,
strokeWidth
}: IconPathWithBackgroundProps) => (
<path
fillRule="evenodd"
clipRule="evenodd"
d="M9 0C12.3137 0 15 2.66867 15 5.96065C15 7.1848 14.6285 8.32277 13.9915
9.26937L9.39371 16.7796C9.26127 16.996 8.97736 17.0648 8.75956
16.9332C8.6965 16.8951 8.64355 16.8425 8.60516 16.7799L3.94032
9.17023C3.34643 8.24464 3 7.14284 3 5.96065C3 2.66867 5.68629 0 9 0ZM9
0.917023C6.19609 0.917023 3.92308 3.17513 3.92308 5.96065C3.92308 6.84849
4.15368 7.70185 4.59125 8.46656L8.99908 15.6591L13.2241 8.75969C13.7313
8.00606 14.0252 7.13229 14.0707 6.21257L14.0769 5.96065C14.0769 3.17513
11.8039 0.917023 9 0.917023ZM9 2.75107C10.7843 2.75107 12.2308 4.18805
12.2308 5.96065C12.2308 7.73325 10.7843 9.17023 9 9.17023C7.2157 9.17023
5.76923 7.73325 5.76923 5.96065C5.76923 4.18805 7.2157 2.75107 9 2.75107ZM9
3.66809C7.7255 3.66809 6.69231 4.69451 6.69231 5.96065C6.69231 7.22679
7.7255 8.25321 9 8.25321C10.2745 8.25321 11.3077 7.22679 11.3077
5.96065C11.3077 4.69451 10.2745 3.66809 9 3.66809Z"
stroke={lineColor}
strokeWidth={strokeWidth}
strokeLinejoin="round"
fill={backgroundColor}
/>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/components/IconPaths/DoubleChevronLeftRight.tsx
import React from "react";
import { IconPathWithBackgroundProps } from "../../types";
export const DoubleChevronLeftRight = ({
backgroundColor = "#fff",
lineColor
}: IconPathWithBackgroundProps) => (
<>
<g id="Alternate" clipPath="url(#clip0_34418_4688)">
<path
d="M8.25 8.24985C8.25 8.66406 8.58579 8.99985 9 8.99985L17.5 8.99985L15.6281 10.9654C15.3424 11.2653 15.354 11.7401 15.654 12.0257L16.7401 13.0602C16.8842 13.1974 17.0768 13.2717 17.2757 13.2669C17.4746 13.262 17.6632 13.1784 17.8005 13.0343L22.0862 8.5343C22.638 7.95502 22.638 7.04478 22.0862 6.4655L17.8005 1.9655C17.6632 1.82141 17.4746 1.73781 17.2757 1.73294C17.0768 1.72807 16.8842 1.80235 16.7401 1.93957L15.654 2.97406C15.354 3.25972 15.3424 3.7345 15.6281 4.03446L17.5 5.99985L9 5.99985C8.80109 5.99985 8.61032 6.07887 8.46968 6.21951C8.32904 6.36015 8.25 6.55092 8.25 6.74985L8.25 8.24985Z"
fill={backgroundColor}
stroke={lineColor}
strokeLinejoin="round"
/>
<path
d="M15.75 15.7501C15.75 15.5512 15.671 15.3604 15.5303 15.2198C15.3897 15.0792 15.1989 15.0001 15 15.0001L6.5 15.0001L8.37193 13.0346C8.51596 12.8974 8.59024 12.7048 8.58537 12.5059C8.58049 12.307 8.49689 12.1184 8.3528 11.9829L7.2601 10.9397C6.96013 10.6541 6.48535 10.6657 6.1997 10.9657L1.91399 15.4657C1.36223 16.045 1.36223 16.9553 1.91399 17.5346L6.1997 22.0346C6.33702 22.1787 6.5256 22.2623 6.72446 22.2671C6.92333 22.2719 7.11595 22.1976 7.2601 22.0604L8.3528 21.0171C8.65277 20.7314 8.66438 20.2567 8.37193 19.9657L6.5 18.0001L15 18.0001C15.4142 18.0001 15.75 17.6643 15.75 17.2501L15.75 15.7501Z"
fill={backgroundColor}
stroke={lineColor}
strokeLinejoin="round"
/>
</g>
<defs>
<clipPath id="clip0_34418_4688">
<rect width="24" height="24" fill={backgroundColor} />
</clipPath>
</defs>
</>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/styled-components.ts
import styled from "styled-components";
import { space } from "styled-system";
export const Svg = styled.svg`
${space}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Icon/index.tsx
import React, { FC, memo } from "react";
import type { IconSizeVariants } from "../../theme";
import { useColorTokens, useTheme } from "../../hooks";
import * as Icons from "./components/IconPaths";
import { Svg } from "./styled-components";
import type { IconNames, IconProps } from "./types";
export const Icon: FC<IconProps> = memo(
({
name,
lineColor = "content.link",
size,
backgroundColor = "transparent",
qaLabel,
...rest
}) => {
const { iconSizes } = useTheme();
const { iconSize, strokeWidth } = iconSizes[size as IconSizeVariants];
const IconContent = Icons[name as IconNames];
// TODO: delete when color tokens for every use case are implemented
// Checking if color has # or rgba, so we use the color instead of token
const filterColor = (color: string | undefined) =>
color && (color.includes("#") || color.includes("rgba"))
? color
: useColorTokens(color);
const checkIsTransparent = (color: string) =>
backgroundColor === "transparent" ? "transparent" : filterColor(color);
const selectedLineColor = lineColor.startsWith("--")
? `var(${lineColor})`
: filterColor(lineColor);
const selectedBackgroundColor = backgroundColor.startsWith("--")
? `var(${backgroundColor})`
: checkIsTransparent(backgroundColor);
return (
<Svg
width={iconSize}
height={iconSize}
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
data-qa-label={qaLabel || name}
{...rest}
>
<IconContent
lineColor={selectedLineColor}
backgroundColor={selectedBackgroundColor}
strokeWidth={strokeWidth}
/>
</Svg>
);
}
);
export type { IconProps, IconNames };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Typography/Header/styled-components.ts
import { createElement } from "react";
import styled from "styled-components";
import {
space,
system,
compose,
fontFamily,
fontSize,
flex,
layout,
typography,
variant,
color
} from "styled-system";
import { HeaderProps } from "./types";
const systemProps = system({
textTransform: {
property: "textTransform"
},
whiteSpace: {
property: "whiteSpace"
},
textOverflow: {
property: "textOverflow"
}
});
const styles = compose(
color,
space,
systemProps,
typography,
fontFamily,
fontSize,
layout,
variant({
prop: "tag",
scale: "headingSizes"
})
);
export const StyledHeader = styled(
({ tag, gap, textOverflow, whiteSpace, accessibilityLevel, ...props }) =>
createElement(tag || "p", props)
).attrs<HeaderProps>(({ tag, textOverflow }) => ({
accessibilityLevel: tag && tag.replace("h", ""),
overflow: textOverflow === "ellipsis" ? "hidden" : "visible"
}))<HeaderProps>`
${styles}
${flex}
${({ gap }) => gap && `gap: ${gap};`} /* Conditionally apply gap */
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Typography/Header/index.tsx
import React, { FC, memo } from "react";
import { StyledHeader } from "./styled-components";
import type { HeaderProps } from "./types";
import { getColor } from "../utils";
export const Header: FC<HeaderProps> = memo(
({
children,
fontFamily = "medium",
textOverflow = "clip",
whiteSpace = "normal",
color = "--fd-colors-content-default",
tag = "h1",
qaLabel = "header",
...rest
}) => {
const selectedColor = getColor(color);
return (
<StyledHeader
role="heading"
fontFamily={fontFamily}
color={selectedColor}
tag={tag}
textOverflow={textOverflow}
whiteSpace={whiteSpace}
data-qa-label={qaLabel}
{...rest}
>
{children}
</StyledHeader>
);
}
);
export type { HeaderProps };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Typography/Paragraph/styled-components.ts
import styled from "styled-components";
import {
space,
system,
compose,
fontFamily,
fontSize,
flex,
layout,
typography,
color
} from "styled-system";
import type { ParagraphProps } from "./types";
const lineHeightNormal = system({
fontSize: {
property: "lineHeight",
scale: "lineHeights"
}
});
const lineHeightTaller = system({
fontSize: {
property: "lineHeight",
scale: "lineHeightsTaller"
}
});
const transformText = system({
textTransform: {
property: "textTransform"
},
whiteSpace: {
property: "whiteSpace"
},
textOverflow: {
property: "textOverflow"
}
});
const styles = compose(
space,
fontFamily,
fontSize,
transformText,
typography,
layout,
color
);
export const StyledParagraph = styled.p<ParagraphProps>`
${({ isLineHigher }) => (isLineHigher ? lineHeightTaller : lineHeightNormal)}
overflow: ${({ textOverflow }) =>
textOverflow === "ellipsis" ? "hidden" : "visible"};
${styles};
${flex}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Typography/Paragraph/index.tsx
import React, { FC } from "react";
import type { ParagraphProps, ParagraphFonts } from "./types";
import { StyledParagraph } from "./styled-components";
import { getColor } from "../utils";
export const Paragraph: FC<ParagraphProps> = ({
children,
qaLabel,
color = "--fd-colors-content-default",
textOverflow,
...rest
}) => {
const selectedColor = getColor(color);
return (
<StyledParagraph
role="paragraph"
textOverflow={textOverflow}
color={selectedColor}
data-qa-label={qaLabel}
{...rest}
>
{children}
</StyledParagraph>
);
};
export type { ParagraphProps, ParagraphFonts };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Typography/utils.ts
export function getColor(color: string): string {
return color.startsWith("--") ? `var(${color})` : color;
}
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/hooks/useColorTokens/index.ts
import { useContext } from "react";
import { get } from "lodash";
import { ThemeContext } from "styled-components";
export const useColorTokens = (value?: string) => {
const useTheme = () => useContext(ThemeContext);
const { colorTokens } = useTheme();
if (value) {
const tokenValue = get(colorTokens, value);
if (!tokenValue && process.env.NODE_ENV !== "production") {
throw new Error(`Invalid color token: ${value}`);
}
return tokenValue;
}
return colorTokens;
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/theme/tokens/colors.ts
import { Colors } from "../types";
export const colors: Colors = {
blue_accent: {
"000": "#FAFCFF",
"100": "#EBF5FF",
"200": "#CDDFFA",
"300": "#AFCCFA",
"400": "#87B2F5",
"500": "#5390ED",
"600": "#3574D4",
"700": "#2F67BD",
"800": "#2959A3",
"900": "#1C3D70"
},
green: {
"000": "#F5FFF7",
"100": "#CEEBD4",
"200": "#B1DEBA",
"300": "#90D19D",
"400": "#69BF7A",
"500": "#38AB4F",
"600": "#329A47",
"700": "#2D873F",
"800": "#246F33",
"900": "#195024"
},
yellow: {
"000": "#FFF6E0",
"100": "#FFECBF",
"200": "#FFE099",
"300": "#FFD470",
"400": "#FFC642",
"500": "#FFB80C",
"600": "#E6A40A",
"700": "#CA9008",
"800": "#A87707",
"900": "#795605"
},
blue: {
"000": "#E9EFF5",
"100": "#D6E3F0",
"200": "#B7CCE1",
"300": "#92B0CE",
"400": "#668FB8",
"500": "#27619B",
"600": "#23568A",
"700": "#1E4B79",
"800": "#193D62",
"900": "#112B44"
},
orange: {
"000": "#FFF3E6",
"100": "#FFE6CC",
"200": "#FAD5AF",
"300": "#F5C089",
"400": "#F0A556",
"500": "#ED850C",
"600": "#D67A11",
"700": "#BD6909",
"800": "#AD6008",
"900": "#854A06"
},
red: {
"000": "#FCEBEB",
"100": "#F7D5D5",
"200": "#F5BCBC",
"300": "#F09E9E",
"400": "#E87676",
"500": "#DE3131",
"600": "#C92C2C",
"700": "#B02727",
"800": "#912020",
"900": "#661616"
},
grey: {
"000": "#F8F8F9",
"100": "#ECEDEE",
"200": "#DEE1E3",
"300": "#CFD2D6",
"400": "#BFC4C8",
"500": "#ADB3B9",
"600": "#99A0A7",
"700": "#818A92",
"800": "#626D78",
"900": "#384048"
},
black: {
"000": "rgba(0, 0, 0, 0.1)",
"100": "rgba(0, 0, 0, 0.2)",
"200": "rgba(0, 0, 0, 0.3)",
"300": "rgba(0, 0, 0, 0.4)",
"400": "rgba(0, 0, 0, 0.5)",
"500": "rgba(0, 0, 0, 0.6)",
"600": "rgba(0, 0, 0, 0.7)",
"700": "rgba(0, 0, 0, 0.8)",
"800": "rgba(0, 0, 0, 0.9)",
"900": "#000000"
},
white: {
"000": "rgba(255, 255, 255, 0.1)",
"100": "rgba(255, 255, 255, 0.2)",
"200": "rgba(255, 255, 255, 0.3)",
"300": "rgba(255, 255, 255, 0.4)",
"400": "rgba(255, 255, 255, 0.5)",
"500": "rgba(255, 255, 255, 0.6)",
"600": "rgba(255, 255, 255, 0.7)",
"700": "rgba(255, 255, 255, 0.8)",
"800": "rgba(255, 255, 255, 0.9)",
"900": "#FFFFFF"
},
tint: {
blue_tint: "#1A4066",
green_tint: "#194546",
yellow_tint: "#414739"
}
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/theme/ThemeProvider.tsx
import React, { FC } from "react";
import { ThemeProvider } from "styled-components";
import {
fanduelColorTokens,
tvgColorTokens
} from "../../src/theming/themes/tokens";
import { ThemeProps } from "./types";
import {
colors,
elevations,
space,
iconSizes,
fonts,
fontSizes,
lineHeights,
lineHeightsShorter,
lineHeightsTaller,
fontWeights
} from "./tokens";
interface TVGThemeProviderProps {
children: React.ReactNode;
isFanduelTheme?: boolean;
}
const TVG_THEME = {
name: "tvg",
colors,
elevations,
space,
iconSizes,
colorTokens: tvgColorTokens,
fonts,
fontSizes,
lineHeights,
lineHeightsShorter,
lineHeightsTaller,
fontWeights
};
const TVGThemeProvider: FC<TVGThemeProviderProps> = ({
children,
isFanduelTheme
}) => {
const colorTokens = isFanduelTheme ? fanduelColorTokens : tvgColorTokens;
return (
<ThemeProvider theme={{ ...TVG_THEME, colorTokens } as ThemeProps}>
{children}
</ThemeProvider>
);
};
export { TVG_THEME, TVGThemeProvider, iconSizes };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/theme/tokens/elevations.ts
import { rgba } from "polished";
import { colors } from "./colors";
import { Elevations } from "../types";
export const elevations: Elevations = {
low: `0px 1px 3px ${rgba(colors.blue["900"], 0.12)}`,
medium: `0px 2px 4px ${rgba(colors.blue["900"], 0.14)}`,
high: `0px 1px 16px ${rgba(colors.blue["900"], 0.25)}`
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/theme/tokens/space.ts
import { Space } from "../types";
export const space: Space = {
"space-1": "4px",
"space-2": "6px",
"space-3": "8px",
"space-4": "12px",
"space-5": "16px",
"space-6": "20px",
"space-7": "24px",
"space-8": "32px"
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/theme/tokens/iconSizes.ts
import { IconSizes } from "../types";
export const iconSizes: IconSizes = {
s: {
iconSize: "16",
strokeWidth: "2.3"
},
m: {
iconSize: "20",
strokeWidth: "2.2"
},
l: {
iconSize: "24",
strokeWidth: "2"
},
xl: {
iconSize: "32",
strokeWidth: "1.6"
}
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/theme/tokens/fonts.ts
import { FontWeights, Fonts, FontSizes, LineHeights } from "../types";
export const fonts: Fonts = {
condensedRegular: "RobotoCondensed-Regular",
regular: "Roboto-Regular",
medium: "Roboto-Medium",
bold: "Roboto-Bold"
};
export const fontSizes: FontSizes = {
xs: "12px",
s: "14px",
m: "16px",
l: "18px",
xl: "20px",
"2xl": "24px",
"3xl": "28px",
"4xl": "32px"
};
export const lineHeights: LineHeights = {
xs: "15px",
s: "18px",
m: "20px",
l: "22px",
xl: "25px",
"2xl": "30px",
"3xl": "35px",
"4xl": "40px"
};
export const lineHeightsShorter = {
xs: "13px",
s: "15px"
};
export const lineHeightsTaller = {
xs: "18px",
s: "21px"
};
export const fontWeights: FontWeights = {
normal: 400,
medium: 500,
bold: 700
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/hooks/useTheme/index.ts
import { TVG_THEME, ThemeProps } from "../../theme";
export const useTheme = (): ThemeProps => TVG_THEME;
webpack://frontend-mybets/../../packages/tvg-lib-formatter/currency/index.ts
import currencyFormatter from "currency-formatter";
import numeral from "numeral";
const formatCurrency = (
value: number,
code: string = "USD",
precision: number = 2
): string => currencyFormatter.format(value, { code, precision });
export const formatCurrencyShortened = (
value: number,
code: string = "USD",
precision: number = 0
): string => currencyFormatter.format(value, { code, precision });
export const formatNumber = (value: number | string): string =>
numeral(value).format("0.00");
export const formatPurse = (value: number): string =>
numeral(value).format(value >= 1000 ? "$0.0a" : "$0");
export const formatPurseWithoutCurrency = (value: number): string =>
numeral(value).format(value >= 1000 ? "0.0a" : "0.00a");
export const formatCurrencyToNumber = (value: string): number =>
+value.replace(/\$|,/g, "");
export default formatCurrency;
webpack://frontend-mybets/../../packages/tvg-lib-formatter/dates/index.ts
import { format, addMilliseconds, parseISO } from "date-fns";
const generateNewDate = (value: string) =>
parseISO(value).toString() === "Invalid Date"
? new Date(value)
: parseISO(value);
export const parseDate = (value: string | Date) =>
typeof value === "string" ? generateNewDate(value) : value;
export const formatPostTime = (
postTime: string | Date,
showDate: boolean = false
): string =>
postTime
? format(parseDate(postTime), showDate ? "MMM d h:mma" : "hh:mm")
: postTime;
export const formatPeriod = (postTime: string | Date): string =>
postTime ? format(parseDate(postTime), "a") : postTime;
export const formatRaceDate = (raceDate: string | Date): string =>
raceDate ? format(parseDate(raceDate), "dd MMM yyyy") : raceDate;
export const formatDateWithText = (postTime: string | Date): string =>
postTime ? format(parseDate(postTime), "MMM d ''yy") : postTime;
export const formatDateWithTextDayFirst = (postTime: string | Date): string =>
postTime ? format(parseDate(postTime), "d MMM ''yy") : postTime;
export const formatPastRaceDate = (raceDate: string | Date): string =>
raceDate ? format(parseDate(raceDate), "yyyy-MM-dd") : raceDate;
export const formatMonthDayDate = (postTime: string | Date): string =>
postTime ? format(parseDate(postTime), "MMMM d") : postTime;
export const formatThreeLetterMonthDayDate = (
postTime: string | Date
): string =>
postTime ? format(parseDate(postTime), "MMMM").substr(0, 3) : postTime;
export const formatDayDate = (postTime: string | Date): string =>
postTime ? format(parseDate(postTime), "d") : postTime;
export const formatSecondsToDuration = (seconds: number): string =>
format(addMilliseconds(new Date(0), seconds * 1000), "mm:ss.SSS");
export const formatDateToMMDDYYYYhhmm = (date: string | Date): string =>
date ? format(parseDate(date), "MM/dd/yyyy hh:mm a").toUpperCase() : date;
export const formatDateToMMDDYYYYSlashhhmm = (date: string | Date): string =>
date ? format(parseDate(date), "MM/dd/yyyy - hh:mm a").toUpperCase() : date;
export const formatDateToMMDDYYYY = (date: string | Date): string =>
date ? format(parseDate(date), "MM/dd/yyyy") : date;
export const formatDateTohhmm = (date: string | Date): string =>
date ? format(parseDate(date), "hh:mm a").toUpperCase() : date;
webpack://frontend-mybets/../../packages/tvg-lib-formatter/numeric/index.ts
import numeral from "numeral";
const formatSequencial = (value: number): string => numeral(value).format("0o");
export const formatPoints = (value: number): string =>
numeral(value).format("0,0");
export default formatSequencial;
webpack://frontend-mybets/../../packages/tvg-lib-formatter/url/index.ts
import { without } from "lodash";
import type {
TalentPickDataRunners,
TalentPickData
} from "@tvg/ts-types/TalentPicks";
type FromByToBetSlip = "rebetBet" | "repeatBet" | "runnerClick";
/*
This method aims to check if an url in internal, relative or external
according to a whitelist
If an element of a white list is not included in an url, this url is tested
to find if it's either relative or external
*/
export const inspectURL = (url: string, whiteList: string[]): string => {
let returnValue = "isInternal";
const localProcessUrl = (localUrl: string) =>
localUrl.replace("www.", "").replace("www-", "");
const processedUrl = localProcessUrl(url);
if (
!whiteList.some((element) =>
processedUrl.includes(localProcessUrl(element))
) ||
whiteList.some((element) =>
processedUrl
.split(".")
.slice(1)
.join(".")
.includes(localProcessUrl(element))
)
) {
returnValue = processedUrl.indexOf("/") === 0 ? "isRelative" : "isExternal";
}
return url.includes("www") && url.includes("/promos")
? "isExternal"
: returnValue;
};
const getBetSlipFromUrl = (type: FromByToBetSlip) => {
switch (type) {
case "rebetBet":
return "&fromRebetBetClick=true";
case "repeatBet":
return "&fromRepeatBetClick=true";
default:
return "&fromRunnerClick=true";
}
};
export const buildBetSlipUrl = (
trackCode: string,
raceNumber: string,
selectedRunner: number,
isGreyhound: boolean = false,
betType: number = 10,
betAmount?: number,
fromOf: FromByToBetSlip = "runnerClick"
): string => {
const betamountSearch = betAmount ? `&betamount=${betAmount}` : "";
const greyhoundsSearch = isGreyhound ? "&greyhounds" : "";
const fromBy = getBetSlipFromUrl(fromOf);
return `/betslip/${trackCode}/Day/${raceNumber}?betselections=${selectedRunner}${fromBy}${betamountSearch}&bettype=${betType}${greyhoundsSearch}`;
};
export const buildPoolBetSlipUrl = (
trackCode: string,
raceNumber: string,
isGreyhound: boolean = false,
betId: number | string = "10"
) =>
`/betslip/${trackCode}/Day/${raceNumber}?bettype=${betId}${
isGreyhound ? "&greyhounds" : ""
}`;
export const buildBetSlipTalentPick = (pick: TalentPickData) => {
const { track, race, amount } = pick;
const betSelections = pick.selections.reduce(
(accumulator: string, currentValue: Array<string>) => {
const raceSelections = currentValue.reduce(
(selections, value) =>
selections !== "" ? `${selections},${value}` : value,
""
);
return accumulator !== ""
? `${accumulator};${raceSelections}`
: raceSelections;
},
""
);
return `/betslip/${track}/Day/${race}?bettype=${pick.wagerType.id}&betamount=${amount}&betselections=${betSelections}&talentPickId=${track}_${race}&talentPickName=${pick.talent.name}`;
};
export const formatTrackName = (trackName: string = ""): string =>
trackName
? trackName
.trim()
.replace(/[/]/g, "")
.replace(/\s/g, "-")
.replace(/-+/g, "-")
.toLowerCase()
: "";
export const addParamToURL = (
currentUrl: string,
paramName: string,
paramValue: string
) =>
currentUrl.includes("?")
? `${currentUrl}&${paramName}=${paramValue}`
: `${currentUrl || "/"}?${paramName}=${paramValue}`;
export const buildTalentPicksTVG5Url = (pick: TalentPickData) => {
const { track, trackName, race, amount, wagerType } = pick;
const betSelections = pick.selections.reduce(
(accumulator, currentValue, index) => {
const raceSelections = currentValue.reduce(
(selections, value) =>
selections !== "" ? `${selections},${value}` : `s${index}=${value}`,
""
);
return accumulator !== ""
? `${accumulator}&${raceSelections}`
: raceSelections;
},
""
);
return `/racetracks/${track}/${formatTrackName(
trackName
)}?race=${race}&${betSelections}&bet=${amount}&wt=${
wagerType.abbreviation || wagerType.id
}`;
};
// TODO: remove greyhounds variation since its only used sometimes.
// and inconsistencies might create navigation issues like Program Page duplication
const buildRaceUrl = (
trackAbbr: string,
trackName: string,
raceNumber: number | string,
isGreyhound: boolean = false
): string =>
`/${isGreyhound ? "greyhounds" : "racetracks"}/${trackAbbr}/${formatTrackName(
trackName
)}?race=${raceNumber}`;
export const buildTalentPickRaceUrl = (
trackAbbr: string,
trackName: string,
raceNumber: number | string
): string =>
`/talent-picks/program/${trackAbbr}/${formatTrackName(
trackName
)}/race-${raceNumber}`;
export const parseSelectionsToString = (
selections: TalentPickDataRunners[][]
): string =>
selections
.map((selection: TalentPickDataRunners[]): string =>
selection
.map((sel: TalentPickDataRunners): string => `${sel.order}`)
.join(",")
)
.join("-");
export const parseSelectionsToObject = (selections: string): number[][] => {
const multiLeg = selections.indexOf("-") > -1;
const legs = multiLeg ? selections.split("-") : [selections];
return legs.map((legSelections) => {
const selectionsSplit = legSelections.split(",");
return selectionsSplit.map((selection: string): number => +selection);
});
};
export const buildLiveUrl = (
trackAbbr: string,
trackName: string,
raceNumber: number | string,
channel: string = "TVG"
): string =>
`/live/${channel}/${trackAbbr}/${formatTrackName(
trackName
)}?race=${raceNumber}`;
export const isFullURL = (url: string): boolean => {
const pattern = /^https?:\/\//;
const isFullUrl = pattern.test(url);
return isFullUrl;
};
export const buildPromoBadgeURL = (
promoPath: string,
raceNumber: string | null = null,
hasStoryblok: boolean = false
): string => {
const promosSlug = without(
promoPath.replace(/^(\/promos|promos)/, "").split("/"),
""
).join("/");
return promoPath
? `?${raceNumber ? `race=${raceNumber}&` : ""}promo=${
hasStoryblok
? `promos/${
promosSlug.charAt(0) === "/" ? promosSlug.substr(1) : promosSlug
}`
: promosSlug
}/#promos`
: `${raceNumber ? `race=${raceNumber}&` : ""}?promo=/#promos`;
};
export const processURL = (url: string): string => {
const pattern = /^https?:\/\//;
const isRelativePath = /^\/.+/.test(url);
const isFullUrl = pattern.test(url);
return !isFullUrl && !isRelativePath ? `http://${url}` : url;
};
export default buildRaceUrl;
webpack://frontend-mybets/../../packages/tvg-lib-login-service/cjs/requests/idRequest.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.onError = void 0;
var _conf = _interopRequireDefault(require("@tvg/conf"));
var _requester = _interopRequireDefault(require("@tvg/api/requester"));
var _helper = require("../services/helper");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const onError = () => ({
error: {
status: "error",
message: "Id request fail"
},
success: null
});
exports.onError = onError;
const onSuccess = response => ({
error: null,
success: {
status: "success",
wagerProfile: response.data.wagerProfile,
accountNumber: response.data.accountNumber
}
});
var _default = () => (0, _requester.default)()({
method: "get",
url: `${(0, _conf.default)().config("service.usa")}/session/context`,
headers: (0, _helper.tvgHeaders)(),
withCredentials: true
}).then(onSuccess).catch(onError);
exports.default = _default;
webpack://frontend-mybets/../../packages/tvg-lib-login-service/cjs/requests/login.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.loginAction = exports.onLoginError = exports.onLoginSuccess = void 0;
var _axios = _interopRequireDefault(require("axios"));
var _conf = _interopRequireDefault(require("@tvg/conf"));
var _protocolSetter = _interopRequireDefault(require("@tvg/api/protocolSetter"));
var _helper = require("../services/helper");
var _geocomply = _interopRequireDefault(require("../services/middleware/geocomply"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const onLoginSuccess = response => ({
success: {
status: "success",
data: response.data
},
error: null
});
exports.onLoginSuccess = onLoginSuccess;
const onLoginError = error => {
if (!error.response || !error.response.data || error.response.status >= 500) {
return {
error: {
status: "error",
message: "An error occurred and we could not log you in at this time. Please <a target='_blank' href='https://support.tvg.com/s/'>contact our customer service</a> for assistance."
},
success: null
};
}
const redirect = error.response.data.redirectUrl ? {
redirectUrl: error.response.data.redirectUrl
} : {};
const responsibleGamingExclusion = error.response.data.responsibleGamingExclusion ? {
responsibleGamingExclusion: error.response.data.responsibleGamingExclusion
} : {};
const remainingTries = {
remainingTries: error.response.data.remainingTries
};
return {
error: {
status: "error",
...{
message: (0, _helper.errorParser)(error.response.data.exception)
},
...redirect,
...responsibleGamingExclusion,
...remainingTries
},
success: null
};
};
exports.onLoginError = onLoginError;
const loginRequest = (payload, geo) => {
if (typeof window !== "undefined" && window.grecaptcha && window.grecaptcha.enterprise && (0, _conf.default)().config("recaptchaID")) {
return new Promise(resolve => {
window.grecaptcha.enterprise.ready(() => {
window.grecaptcha.enterprise.execute((0, _conf.default)().config("recaptchaID"), {
action: "LOGIN"
}).then(token => {
return (0, _axios.default)({
method: "post",
url: `${(0, _protocolSetter.default)()}${(0, _conf.default)().config().service.usa}/login`,
data: {
account: payload.account,
pin: payload.pin,
stateAbbr: payload.stateAbbr,
...geo
},
headers: {
...(0, _helper.tvgHeaders)(),
"X-Recaptcha-Token": token
},
withCredentials: true
}).then(onLoginSuccess).catch(onLoginError).then(resolve);
}).catch(e => {
resolve(e);
});
});
});
}
return (0, _axios.default)({
method: "post",
url: `${(0, _protocolSetter.default)()}${(0, _conf.default)().config().service.usa}/login`,
data: {
account: payload.account,
pin: payload.pin,
stateAbbr: payload.stateAbbr,
...geo
},
headers: {
...(0, _helper.tvgHeaders)()
},
withCredentials: true
}).then(onLoginSuccess).catch(onLoginError);
};
const loginAction = payload => (0, _geocomply.default)(payload, loginRequest, ((0, _conf.default)().device === "desktop" || (0, _conf.default)().product === "tvg4") && (0, _conf.default)().brand === "4njbets");
exports.loginAction = loginAction;
webpack://frontend-mybets/../../packages/tvg-lib-login-service/cjs/requests/logout.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.onLogoutError = exports.onLogoutSuccess = void 0;
var _axios = _interopRequireDefault(require("axios"));
var _conf = _interopRequireDefault(require("@tvg/conf"));
var _protocolSetter = _interopRequireDefault(require("@tvg/api/protocolSetter"));
var _helper = require("../services/helper");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const onLogoutSuccess = () => ({
success: {
status: "success"
},
error: null
});
exports.onLogoutSuccess = onLogoutSuccess;
const onLogoutError = error => {
if (!error.response || !error.response.data || error.response.status >= 500) {
return {
error: {
status: "error",
message: "Logout request fail"
},
success: null
};
}
return {
error: {
...{
status: "error"
},
...{
message: error.response.data.message || "Fail to logout"
}
},
success: null
};
};
exports.onLogoutError = onLogoutError;
var _default = () => (0, _axios.default)({
method: "post",
url: `${(0, _protocolSetter.default)()}${(0, _conf.default)().config().service.usa}/logout`,
headers: (0, _helper.tvgHeaders)(),
withCredentials: true
}).then(onLogoutSuccess).catch(onLogoutError);
exports.default = _default;
webpack://frontend-mybets/../../packages/tvg-lib-login-service/cjs/requests/profile.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.onError = void 0;
var _axios = _interopRequireDefault(require("axios"));
var _conf = _interopRequireDefault(require("@tvg/conf"));
var _helper = require("../services/helper");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const onError = () => ({
error: {
status: "error",
message: "Profile request fail"
},
success: null
});
exports.onError = onError;
const onSuccess = response => {
const user = {
accountNumber: response.data.accountNumber,
accountRoles: response.data.accountRoles,
firstName: response.data.firstName,
lastName: response.data.lastName,
primaryPhone: response.data.primaryPhone,
wagerStatus: response.data.wagerStatus,
emailAddress: response.data.emailAddress,
homeAddress: response.data.homeAddress,
mailingAddress: response.data.mailingAddress,
signalProviderId: response.data.signalProviderId,
userName: response.data.userName,
profile: response.data.profile,
pin: ""
};
return {
error: null,
success: {
status: "success",
data: {
user
}
}
};
};
var _default = userId => (0, _axios.default)({
method: "get",
url: `${(0, _conf.default)().config().service.uam}/users/${userId}/profile`,
headers: (0, _helper.tvgHeaders)(),
withCredentials: true
}).then(onSuccess).catch(onError);
exports.default = _default;
webpack://frontend-mybets/../../packages/tvg-lib-login-service/cjs/services/geoComply/index.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _axios = _interopRequireDefault(require("axios"));
var _lodash = require("lodash");
var _conf = _interopRequireDefault(require("@tvg/conf"));
var _errorMessages = _interopRequireDefault(require("./errorMessages.json"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const validateGeoPacket = (userId, geo) => {
const tvg = (0, _conf.default)();
return (0, _axios.default)({
method: "POST",
url: `${tvg.config().service.geo}/geopacket`,
headers: {
Accept: "application/json",
"x-tvg-context": tvg.context()
},
data: {
geo,
userId
}
});
};
class GeoComplySvc {
constructor() {
this.geoClient = null;
this.geoLicenseExpiration = null;
this.geoLicense = null;
this.hasChecked = false;
this.getPack = this.getPack.bind(this);
this.getLicence = this.getLicence.bind(this);
this.getGeoPacket = this.getGeoPacket.bind(this);
this.clientEmitMessage = this.clientEmitMessage.bind(this);
this.validateGeoPacket = validateGeoPacket;
this.softErrorMessage = "geocomply browser error";
if (typeof window !== "undefined") {
this.geoComplyIsPresent = window.GcHtml5;
if (!this.geoComplyIsPresent) {
console.log(_errorMessages.default.missingGeo);
} else {
this.geoClient = window.GcHtml5.createClient(null, null);
this.geoClient.setReason("GeoComply login for TVG");
this.geoClient.events.on("engine.success", (text, xml) => {
this.clientEmitMessage({
success: {
text,
xml
}
});
});
this.geoClient.events.on("browser.failed", code => {
this.clientEmitMessage({
error: {
code,
message: this.softErrorMessage
}
});
});
this.geoClient.events.on("revised.failed", code => {
this.clientEmitMessage({
error: {
code,
message: this.softErrorMessage
}
});
});
this.geoClient.events.on("config.failed", (code, message) => {
this.clientEmitMessage({
error: {
code,
message
}
});
});
this.geoClient.events.on("engine.failed", (code, message) => {
this.clientEmitMessage({
error: {
code,
message
}
});
});
}
}
}
clientEmitMessage(answer) {
this.geoClient.events.emit("geoPacketAvailable", answer);
}
getGeoPacket(userId, type = "login") {
if (!this.geoComplyIsPresent || (0, _conf.default)().brand !== "4njbets") {
return Promise.reject({});
}
if (!this.geoClient) {
this.geoClient = window.GcHtml5.createClient(null, null);
}
if (type === "revalidate") {
this.geoClient.setReason("GeoComply revalidate for TVG");
} else {
this.geoClient.setReason("GeoComply login for TVG");
}
if (!this.geoLicense) {
return this.getLicence(userId).then(() => this.getPack(userId));
}
return this.getPack(userId).then(res => {
this.hasChecked = false;
return res;
}).catch(err => {
this.hasChecked = false;
return err;
});
}
getLicence(userId) {
const tvg = (0, _conf.default)();
return (0, _axios.default)({
method: "get",
url: `${tvg.config().service.geo}/license${this.geoLicenseExpiration ? `?currentLicenseTimestamp=${this.geoLicenseExpiration}` : ""}`,
headers: {
Accept: "application/json",
"x-tvg-context": tvg.context()
}
}).then(response => {
this.geoLicenseExpiration = response.data.expiration;
this.geoLicense = response.data.license;
return userId;
}).catch(() => {
this.geoLicenseExpiration = null;
this.geoLicense = null;
return undefined;
});
}
getPack(userId) {
if (!this.geoClient || !this.geoLicense) {
return Promise.reject(_errorMessages.default.missingGeo);
}
if (!userId) {
return Promise.reject(_errorMessages.default.missingUserID);
}
return new Promise((resolve, reject) => {
this.geoClient.events.on("geoPacketAvailable", data => {
if (data.success) {
return resolve({
geo: data.success.text
});
}
return reject(data.error);
});
this.geoClient.setUserId(userId.trim().toLowerCase());
this.geoClient.setLicense(this.geoLicense);
this.geoClient.request();
});
}
}
exports.default = GeoComplySvc;
module.exports = exports.default;
webpack://frontend-mybets/../../packages/tvg-lib-login-service/cjs/services/helper.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.buildRedirectMessage = exports.errorParser = exports.TimeDiffService = exports.tvgHeaders = void 0;
var _conf = _interopRequireDefault(require("@tvg/conf"));
var _reactCookie = _interopRequireDefault(require("react-cookie"));
var _static = require("./static");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const tvgHeaders = () => ({
"content-type": "application/json",
"x-tvg-context": (0, _conf.default)().context(),
"x-requested-with": "XMLHttpRequest"
});
exports.tvgHeaders = tvgHeaders;
const timeDiff = [];
const TimeDiffService = {
markStart: mark => {
timeDiff[mark] = Date.now();
},
markEnd: mark => Date.now() - timeDiff[mark],
getMark: mark => timeDiff[mark]
};
exports.TimeDiffService = TimeDiffService;
const errorParser = error => error in _static.errors ? _static.errors[error] : "Fail to login.";
exports.errorParser = errorParser;
const buildRedirectMessage = (redirectUrl, capiRedirectMessage) => {
const capiMessage = JSON.parse(capiRedirectMessage);
const {
loginRedirectionTitle = "<brand> CUSTOMER",
loginRedirectionMessage = "Looks like you’re from <state>! Due to state regulation, we need to redirect you to <brand>"
} = capiMessage;
let brand = "tvg";
if (redirectUrl.indexOf("4njbets") > -1) {
brand = "4njbets";
} else if (redirectUrl.indexOf("ia-") > -1 || redirectUrl.indexOf("ia.tvg") > -1) {
brand = "iowa";
} else if (redirectUrl.indexOf("pabets") > -1) {
brand = "pabets";
}
const stateMap = {
"4njbets": {
brand: "4NJBets",
state: "New Jersey"
},
iowa: {
brand: "TVG - IA",
state: "Iowa"
},
pabets: {
brand: "PABets",
state: "Pennsylvania"
},
tvg: {
brand: "TVG",
state: "TVG"
}
};
return {
redirectMessage: loginRedirectionMessage.replace(/<state>/g, stateMap[brand].state).replace(/<brand>/g, stateMap[brand].brand),
redirectTitle: loginRedirectionTitle.replace(/<brand>/g, stateMap[brand].brand)
};
};
exports.buildRedirectMessage = buildRedirectMessage;
webpack://frontend-mybets/../../packages/tvg-lib-login-service/cjs/services/middleware/geocomply.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _index = _interopRequireDefault(require("../geoComply/index"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const geoComply = new _index.default();
var _default = (payload, fn, useGeocomply) => {
const newfn = geo => fn(payload, geo);
if (useGeocomply) {
return geoComply.getGeoPacket(payload.account).then(newfn).catch(newfn);
}
return fn(payload, {});
};
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../packages/tvg-lib-login-service/cjs/services/static.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.CONSTANTS = exports.errors = void 0;
const errors = {
ACCOUNT_DISABLED: "loginFailureAccountDisabled",
ACCOUNT_LOCKED: "loginFailureAccountLocked",
ACCOUNT_UPDATE_REQUIRED: "loginFailureAccountUpdateRequired",
BLACK_LISTED_LOCATION: "blackListedLocation",
BLOCKED_SERVICE: "geoLocationBlockedService",
BLOCKED_SOFTWARE: "geoLocationBlockedSoftware",
GEO_SERVICE_FAILURE: "loginFailureGeneric",
INVALID_CREDENTIALS: "loginFailureInvalidCredentials",
INVALID_GEO: "geoLocationUnconfirmedOrInvalid",
INVALID_GEOPACKET: "geoLocationUnconfirmedOrInvalid",
INVALID_WAGERING_STATE: "loginFailureNonLegalState",
LOGIN_FAILED: "loginFailureGeneric",
LOGIN_REDIRECT: "loginSiteRedirect",
MISSING_TOKEN: "apiMissingUserSessionToken",
NON_LEGAL_STATE: "loginFailureNonLegalState",
OUT_OF_BOUNDARY: "geoLocationOutOfBoundary",
SESSION_NOT_FOUND: "apiUserSessionNotFound",
SESSION_TIMEOUT: "apiUserSessionTimedOut",
UNCONFIRMED_BOUNDARY: "geoLocationUnconfirmedOrInvalid",
USER_SESSION_LIMIT_REACHED: "loginFailureUserSessionLimitReached",
ACCOUNT_IN_TIMEOUT: "loginFailureRGTimeout",
ACCOUNT_SUSPENDED: "loginFailureRGSuspendedOrClose",
ACCOUNT_SELF_EXCLUDED: "loginFailureRGSuspendedOrClose",
InvalidPinException: "invalidPinException",
"com.tvg.pxp.exceptions.UserCompromisedCredentialsException": "userCompromisedCredentials"
};
exports.errors = errors;
const CONSTANTS = {
SET_SESSION_SUCCESS: "SET_SESSION_SUCCESS",
SET_SESSION_ERROR: "SET_SESSION_ERROR",
CLEAR_SESSION: "CLEAR_SESSION",
SET_USER: "SET_USER",
CMS_LOGIN_MESSAGES: "CMS_LOGIN_MESSAGES",
"TVG_LOGIN:DO_LOGIN": "TVG_LOGIN:DO_LOGIN",
"TVG_LOGIN:DO_LOGIN_FORM": "TVG_LOGIN:DO_LOGIN_FORM",
"TVG_LOGIN:DO_LOGOUT": "TVG_LOGIN:DO_LOGOUT",
"TVG_LOGIN:USER_SESSION_UPDATE": "TVG_LOGIN:USER_SESSION_UPDATE",
"TVG_LOGIN:OPEN_LOGIN_MODAL": "TVG_LOGIN:OPEN_LOGIN_MODAL",
"TVG_LOGIN:CLOSE_LOGIN_MODAL": "TVG_LOGIN:CLOSE_LOGIN_MODAL",
"TVG_LOGIN:VALIDATE_SESSION": "TVG_LOGIN:VALIDATE_SESSION",
"TVG_LOGIN:TOUCH_ID_ERROR": "TVG_LOGIN:TOUCH_ID_ERROR",
UPDATE_USER_DATA: "UPDATE_USER_DATA",
METRIC_USER_LOGIN: "user_login"
};
exports.CONSTANTS = CONSTANTS;
webpack://frontend-mybets/../../packages/tvg-lib-login-service/cjs/src/index.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _lodash = require("lodash");
var _cookies = require("@tvg/utils/cookies");
var _login = require("../requests/login");
var _logout = _interopRequireDefault(require("../requests/logout"));
var _idRequest = _interopRequireDefault(require("../requests/idRequest"));
var _profile = _interopRequireDefault(require("../requests/profile"));
var _helper = require("../services/helper");
var _static = require("../services/static");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class LoginService {
static doLogin(payload) {
_helper.TimeDiffService.markStart(_static.CONSTANTS.METRIC_USER_LOGIN);
return (0, _login.loginAction)(payload).then(response => {
if (response.success) {
response.success.data.userDetails.pin = payload.pin;
(0, _cookies.cookieService)("wp", true, (0, _lodash.get)(response, "success.data.userDetails.profile"));
(0, _cookies.cookieService)("hasLoginOnce", true, "true", 31622400);
(0, _lodash.attempt)(() => {
sessionStorage.setItem("userId", (0, _lodash.get)(response, "success.data.userDetails.accountNumber"));
localStorage.setItem("userAuthenticationState", (0, _lodash.get)(payload, "stateAbbr"));
});
}
if (payload && payload.callback && typeof payload.callback === "function") {
payload.callback(response.error, response.success);
}
return response;
}).catch(() => {});
}
static doLogout(payload) {
return (0, _logout.default)().then(response => {
if (payload && payload.callback && typeof payload.callback === "function") {
payload.callback(response.error, response.success);
}
if (response && response.success && typeof window !== "undefined") {
(0, _cookies.cookieService)("wp", false);
(0, _lodash.attempt)(() => {
sessionStorage.removeItem("userId");
localStorage.removeItem("isFirstTouch");
localStorage.removeItem("userAuthenticationState");
});
}
return response;
}).catch(() => {});
}
static requestProfile(userId) {
return (0, _profile.default)(userId).then(response => {
if (response.success) {
(0, _cookies.cookieService)("wp", true, (0, _lodash.get)(response, "success.data.user.profile"));
(0, _cookies.cookieService)("hasLoginOnce", true, "true", 31622400);
}
return response;
}).catch(() => {});
}
static isIOSWebView() {
if (typeof navigator === "undefined") return false;
const ua = navigator.userAgent || "";
return /iPhone|iPad|iPod/i.test(ua) && !/Safari/i.test(ua);
}
static isSessionReady() {
try {
return !!sessionStorage.getItem("userId") || document.cookie.includes("wp=") || document.cookie.includes("hasLoginOnce");
} catch {
return false;
}
}
static validateSession() {
if (this.isIOSWebView() && !this.isSessionReady()) {
return Promise.resolve(undefined);
}
return (0, _idRequest.default)().then(response => {
if (response?.success) {
(0, _lodash.attempt)(() => {
sessionStorage.setItem("userId", (0, _lodash.get)(response, "success.accountNumber"));
(0, _cookies.cookieService)("wp", true, (0, _lodash.get)(response, "success.wagerProfile"));
(0, _cookies.cookieService)("hasLoginOnce", true, "true", 31622400);
});
return this.requestProfile((0, _lodash.get)(response, "success.accountNumber"));
}
return response;
}).catch(() => undefined);
}
}
exports.default = LoginService;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/get.js
import superPropBase from "./superPropBase.js";
export default function _get(target, property, receiver) {
if (typeof Reflect !== "undefined" && Reflect.get) {
_get = Reflect.get;
} else {
_get = function _get(target, property, receiver) {
var base = superPropBase(target, property);
if (!base) return;
var desc = Object.getOwnPropertyDescriptor(base, property);
if (desc.get) {
return desc.get.call(receiver);
}
return desc.value;
};
}
return _get(target, property, receiver || target);
}
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/superPropBase.js
import getPrototypeOf from "./getPrototypeOf.js";
export default function _superPropBase(object, property) {
while (!Object.prototype.hasOwnProperty.call(object, property)) {
object = getPrototypeOf(object);
if (object === null) break;
}
return object;
}
webpack://frontend-mybets/../../packages/tvg-lib-mediator/src/MediatorUtils.ts
import { get } from "lodash";
export const isBrowser = () =>
typeof window !== "undefined" &&
Object.prototype.toString.call(window) === "[object Window]";
export const isNativeApp = () =>
isBrowser() &&
["iosnative", "androidnative"].includes(
get(window, "__TVG_GLOBALS__.PRODUCT")
);
webpack://frontend-mybets/../../packages/tvg-lib-mediator/src/EventEmitters/Base.ts
/**
* BaseEventEmitter
*
* Pure JavaScript EventEmitter. This is used as base to keep track of dispatch
* events. Other event emitters can then extend this and just care about their
* implementation details
*/
import { get as lodashGet } from "lodash";
import { get, set } from "lodash/fp";
import tvgConf from "@tvg/conf";
import type {
EventEmitterInterface,
EventName,
EventListener,
FSA
} from "../Types";
import { isBrowser } from "../MediatorUtils";
const MEDIATOR_LOG_EVENTS_COOKIE = "useMediatorLogEvents";
type EventHandler = {
payload?: FSA;
subscribers: Array<EventListener>;
};
class BaseEventEmitter implements EventEmitterInterface {
events: {
[key in EventName]: EventHandler;
};
constructor() {
this.events = {};
}
dispatch(payload: FSA) {
if (
lodashGet(tvgConf(), "environment") === "qa" &&
typeof window !== "undefined" &&
document.cookie.includes(`${MEDIATOR_LOG_EVENTS_COOKIE}=true`)
) {
console.log("mediator.dispatch - payload:", payload);
}
const event = get(payload.type, this.events);
if (event) {
event.payload = payload;
if (
isBrowser() &&
lodashGet(window, "rnEvents", []).indexOf(payload.type) === -1
) {
event.subscribers.forEach((subscriber) => {
if (subscriber) {
subscriber(payload);
}
});
} else if (typeof window !== "undefined") {
// @ts-ignore
window.ReactNativeWebView.postMessage(
JSON.stringify({
type: payload.type,
body: payload.payload
})
);
}
return this;
}
this.events = set(
payload.type,
{
payload,
subscribers: []
},
this.events
);
return this;
}
subscribe(name: EventName, subscriber: EventListener) {
const event = get(name, this.events);
if (!event) {
this.events = set(
name,
{
payload: null,
subscribers: [subscriber]
},
this.events
);
} else {
event.subscribers = event.subscribers.concat(subscriber);
}
// Not proud of this but I need it
const self = this;
return {
replay() {
if (event?.payload) {
subscriber(event.payload);
}
return this;
},
unsubscribe() {
self.unsubscribe(name, subscriber);
return this;
}
};
}
unsubscribe(name: EventName, subscriber: EventListener) {
const event = get(name, this.events);
if (event) {
event.subscribers = event.subscribers.filter((fn) => fn !== subscriber);
}
return this;
}
}
export default BaseEventEmitter;
webpack://frontend-mybets/../../packages/tvg-lib-mediator/src/EventEmitters/APP.ts
import { get } from "lodash/fp";
import { attempt } from "@tvg/conf/src/utils";
import { PRODUCTS_ANDROID, PRODUCTS_FDR_X_SELL } from "@tvg/conf/src/product";
import BaseEventEmitter from "./Base";
import type { FSA, EventName, EventListener } from "../Types";
type WebkitEvent = {
[key in EventName]: {
postMessage: EventListener;
};
};
type Options = {
webkitEvents?: WebkitEvent;
};
const FD_BRIDGE_MESSAGE_EVT = "BRIDGE_MESSAGE";
const FD_BRIDGE_EVENT_PREFIX = "x-sell/bridge/to-react/";
export const isAndroid = (product: string) =>
PRODUCTS_ANDROID.includes(product);
export const isXSell = (product: string) =>
PRODUCTS_FDR_X_SELL.includes(product);
export const checkSBBridgeEvents = (eventName: String) =>
typeof eventName === "string" && eventName.startsWith(FD_BRIDGE_EVENT_PREFIX);
export default class APPEventEmitter extends BaseEventEmitter {
// @ts-ignore
webkit: WebkitEvent;
// @ts-ignore
androidAppPostMessage: null;
constructor(options: Options = {}) {
super();
// android app flow
if (isAndroid(get("__TVG_GLOBALS__.PRODUCT", window))) {
this.androidAppPostMessage = get("androidBridge.postMessage", window);
if (!this.androidAppPostMessage) {
throw new Error("EventEmitterAPP requires android bridge");
}
// ios app flow
} else {
this.webkit =
options.webkitEvents || get("webkit.messageHandlers", window);
if (!this.webkit) {
throw new Error("EventEmitterAPP requires webkit events to exist");
}
}
}
dispatch = (message: FSA) => {
const product = get("__TVG_GLOBALS__.PRODUCT", window);
const webkitEvent =
get(FD_BRIDGE_MESSAGE_EVT, this.webkit) || get(message.type, this.webkit);
// iOS doesn't show any error message if we simply pass an error instance,
// so we transform the error into a plain object with message and stack
const errorObj = message.payload instanceof Error && {
...message,
payload: APPEventEmitter.encodeError(message.payload)
};
// We need to avoid send invalid events to xsell
if (!isXSell(product) || checkSBBridgeEvents(message.type)) {
if (window && get("androidBridge", window)) {
attempt(() => {
get("androidBridge", window).postMessage(
JSON.stringify(errorObj || message)
);
});
} else if (webkitEvent) {
webkitEvent.postMessage(errorObj || message);
}
}
return super.dispatch(message);
};
static encodeError(error: Error) {
return {
message: error.message,
stack: error.stack
};
}
}
webpack://frontend-mybets/../../packages/tvg-lib-mediator/src/EventEmitters/DOM.ts
import { get, set } from "lodash/fp";
import BaseEventEmitter from "./Base";
import type { FSA, EventName, EventListener } from "../Types";
type Options = {
element?: HTMLElement;
};
type WrapperSubscriber = EventListener & {
originalHandler: EventListener;
};
export default class DOMEventEmitter extends BaseEventEmitter {
element: HTMLElement;
subscribers: WrapperSubscriber[];
constructor(options: Options = {}) {
super();
const element = options.element || document.body;
if (!element) {
throw new Error("DOMEventEmitter requires document.body to exist");
}
this.element = element;
this.subscribers = [];
}
dispatch(payload: FSA) {
const event = get(payload.type, this.events);
if (event) {
const customEvent = new CustomEvent(payload.type, {
detail: payload,
bubbles: false
});
this.element.dispatchEvent(customEvent);
event.payload = payload;
return this;
}
this.events = set(
payload.type,
{
payload,
subscribers: []
},
this.events
);
return this;
}
subscribe(name: string, subscriber: EventListener) {
// @ts-ignore
const handler: WrapperSubscriber = (evt) => subscriber(evt.detail);
handler.originalHandler = subscriber;
this.element.addEventListener(name, handler);
this.subscribers = this.subscribers.concat(handler);
return super.subscribe(name, subscriber);
}
unsubscribe(name: EventName, subscriber: EventListener) {
const event = get(name, this.events);
if (event) {
const handler = this.subscribers.filter(
(fn) => fn.originalHandler === subscriber
)[0];
event.subscribers = event.subscribers.filter((fn) => fn !== handler);
this.element.removeEventListener(name, handler);
return super.unsubscribe(name, handler.originalHandler);
}
return this;
}
}
webpack://frontend-mybets/../../packages/tvg-lib-mediator/src/EventEmitters/Node.ts
import BaseEventEmitter from "./Base";
class NodeEventEmitter extends BaseEventEmitter {}
export default NodeEventEmitter;
webpack://frontend-mybets/../../packages/tvg-lib-mediator/src/Mediator.ts
import { get } from "lodash/fp";
import APPEventEmitter, { isAndroid } from "./EventEmitters/APP";
import DOMEventEmitter from "./EventEmitters/DOM";
import NodeEventEmitter from "./EventEmitters/Node";
import BaseEventEmitter from "./EventEmitters/Base";
import type { EventEmitterInterface } from "./Types";
import { isBrowser } from "./MediatorUtils";
type Channels = {
ios: EventEmitterInterface;
browser: EventEmitterInterface;
node: EventEmitterInterface;
base: EventEmitterInterface;
};
export default class Mediator {
channels: Channels;
constructor() {
this.channels = {
ios:
(Mediator.isAPP() && new APPEventEmitter()) || new BaseEventEmitter(),
browser:
(Mediator.isBrowser() && new DOMEventEmitter()) ||
new BaseEventEmitter(),
node:
(Mediator.isNode() && new NodeEventEmitter()) || new BaseEventEmitter(),
base: new BaseEventEmitter()
};
}
static isNode() {
return (
typeof process !== "undefined" && get("release.name", process) === "node"
);
}
// This function is duplicated in ./EventEmitters/Base.js
static isBrowser() {
// Not perfect
return isBrowser();
}
static isAPP() {
return (
(Mediator.isBrowser() &&
isAndroid(get("__TVG_GLOBALS__.PRODUCT", window))) ||
(Mediator.isBrowser() &&
!!get("webkit.messageHandlers", window) &&
!window.navigator.userAgent.match("CriOS"))
);
}
}
webpack://frontend-mybets/../../packages/tvg-lib-mediator/src/index.ts
import Mediator from "./Mediator";
let mediator = new Mediator();
// Attach mediator channels to the window to allow cross app communication
if (Mediator.isBrowser()) {
// @ts-ignore
if (!window.mediatorChannels) {
// @ts-ignore
window.mediatorChannels = mediator.channels;
} else {
// @ts-ignore
mediator = { channels: window.mediatorChannels };
}
}
export default mediator.channels;
webpack://frontend-mybets/../../packages/tvg-lib-metrics-collector/src/metricsConfigurations.js
const counterDefaultTags = {
type: "counter",
value: "1"
};
module.exports = {
place_bets_error: {
...counterDefaultTags,
name: "place_bets_error"
},
open_video_error: {
...counterDefaultTags,
name: "open_video_error"
},
login_error: {
...counterDefaultTags,
name: "login_error"
},
bets_number: {
...counterDefaultTags,
name: "bets_number"
},
cancel_bets_number: {
...counterDefaultTags,
name: "cancel_bets_number"
},
bet_placement_time: {
name: "bet_placement_time",
type: "timer"
}
};
webpack://frontend-mybets/../../packages/tvg-lib-ts-types/Wager.ts
export enum WagerTypeCodesEnum {
WIN = "WN",
WIN_PLACE = "WP",
WIN_SHOW = "WS",
WIN_PLACE_SHOW = "WPS",
TRIFECTA = "TR",
TRIFECTA_BOX = "TRB",
TRIFECTA_WHEEL = "TRW",
TRIFECTA_KEY = "TRK",
TRIFECTA_KEY_BOX = "TKB",
DAILY_DOUBLE = "DB",
EXACTA = "EX",
EXACTA_BOX = "EXB",
EXACTA_WHEEL = "EXW",
EXACTA_KEY = "EXK",
EXACTA_KEY_BOX = "EKB",
GRAND_SLAM = "GS",
EXACT_12 = "E12",
SURVIVOR = "SV",
V_4 = "V4",
V_5 = "V5",
V_64 = "V64",
V_65 = "V65",
V_75 = "V75",
V_86 = "V86",
GS_75 = "GS75",
PICK_3 = "P3",
PICK_4 = "P4",
PICK_5 = "P5",
PICK_6 = "P6",
PICK_7 = "P7",
PICK_8 = "P8",
PICK_9 = "P9",
PICK_10 = "P10",
PICK_11 = "P11",
PICK_12 = "P12",
PICK_ALL_3 = "A3",
PICK_ALL_4 = "A4",
PICK_ALL_5 = "A5",
PICK_ALL_6 = "A6",
PICK_ALL_7 = "A7",
PICK_ALL_8 = "A8",
PICK_ALL_9 = "A9",
PICK_ALL_10 = "A10",
PICK_ALL_11 = "A11",
PICK_ALL_12 = "A12",
PLACE = "PL",
PLACE_PICK_ALL_3 = "L3",
PLACE_PICK_ALL_4 = "L4",
PLACE_PICK_ALL_5 = "L5",
PLACE_PICK_ALL_6 = "L6",
PLACE_PICK_ALL_7 = "L7",
PLACE_PICK_ALL_8 = "L8",
PLACE_PICK_ALL_9 = "L9",
PLACE_PICK_ALL_10 = "L10",
PLACE_SHOW = "PS",
QUINELLA = "QN",
QUINELLA_BOX = "QNB",
QUINELLA_WHEEL = "QNW",
SHOW = "SH",
SUPERFECTA = "SU",
SUPERFECTA_BOX = "SUB",
SUPERFECTA_WHEEL = "SUW",
SUPERFECTA_KEY = "SUK",
SUPERFECTA_KEY_BOX = "SKB",
SUPERHIGHFIVE = "SH5",
SUPERHIGHFIVE_BOX = "H5B",
SUPERHIGHFIVE_WHEEL = "H5W",
SUPERHIGHFIVE_KEY = "S5K",
SUPERHIGHFIVE_KEY_BOX = "5KB",
OMNI = "OM",
OMNI_BOX = "OMB",
OMNI_WHEEL = "OMW",
TRIO = "TI",
TRIO_BOX = "TIB",
TRIO_WHEEL = "TIW",
UNKNOWN = ""
}
export enum WagerTypeWpsCodesEnum {
WIN = "WN",
WIN_PLACE = "WP",
WIN_SHOW = "WS",
WIN_PLACE_SHOW = "WPS",
PLACE = "PL",
PLACE_SHOW = "PS",
SHOW = "SH"
}
export enum WagerTypeCodesInvertedEnum {
WN = "WIN",
WP = "WIN_PLACE",
WS = "WIN_SHOW",
WPS = "WIN_PLACE_SHOW",
TR = "TRIFECTA",
TRB = "TRIFECTA_BOX",
TRW = "TRIFECTA_WHEEL",
TRK = "TRIFECTA_KEY",
TKB = "TRIFECTA_KEY_BOX",
DB = "DAILY_DOUBLE",
EX = "EXACTA",
EXB = "EXACTA_BOX",
EXW = "EXACTA_WHEEL",
EXK = "EXACTA_KEY",
EKB = "EXACTA_KEY_BOX",
GS = "GRAND_SLAM",
E12 = "EXACT_12",
SV = "SURVIVOR",
V4 = "V_4",
V5 = "V_5",
V64 = "V_64",
V65 = "V_65",
V75 = "V_75",
V86 = "V_86",
GS75 = "GS_75",
P3 = "PICK_3",
P4 = "PICK_4",
P5 = "PICK_5",
P6 = "PICK_6",
P7 = "PICK_7",
P8 = "PICK_8",
P9 = "PICK_9",
P10 = "PICK_10",
P11 = "PICK_11",
P12 = "PICK_12",
A3 = "PICK_ALL_3",
A4 = "PICK_ALL_4",
A5 = "PICK_ALL_5",
A6 = "PICK_ALL_6",
A7 = "PICK_ALL_7",
A8 = "PICK_ALL_8",
A9 = "PICK_ALL_9",
A10 = "PICK_ALL_10",
A11 = "PICK_ALL_11",
A12 = "PICK_ALL_12",
PL = "PLACE",
L3 = "PLACE_PICK_ALL_3",
L4 = "PLACE_PICK_ALL_4",
L5 = "PLACE_PICK_ALL_5",
L6 = "PLACE_PICK_ALL_6",
L7 = "PLACE_PICK_ALL_7",
L8 = "PLACE_PICK_ALL_8",
L9 = "PLACE_PICK_ALL_9",
L10 = "PLACE_PICK_ALL_10",
PS = "PLACE_SHOW",
QN = "QUINELLA",
QNB = "QUINELLA_BOX",
QNW = "QUINELLA_WHEEL",
SH = "SHOW",
SU = "SUPERFECTA",
SUB = "SUPERFECTA_BOX",
SUW = "SUPERFECTA_WHEEL",
SUK = "SUPERFECTA_KEY",
SKB = "SUPERFECTA_KEY_BOX",
SH5 = "SUPERHIGHFIVE",
H5B = "SUPERHIGHFIVE_BOX",
H5W = "SUPERHIGHFIVE_WHEEL",
S5K = "SUPERHIGHFIVE_KEY",
"5KB" = "SUPERHIGHFIVE_KEY_BOX",
OM = "OMNI",
OMB = "OMNI_BOX",
OMW = "OMNI_WHEEL",
TI = "TRIO",
TIB = "TRIO_BOX",
TIW = "TRIO_WHEEL"
}
export interface WagerType {
id: number;
code: WagerTypeCodesEnum;
name: string;
description?: string;
descriptionInternational?: string;
abbreviation?: string;
unitedWagerTypeCode?: string;
}
export enum WagerTypesPos {
Win,
Place,
Show
}
export enum WagerTypes {
WIN = 10,
PLACE = 20,
SHOW = 30,
WIN_PLACE = 40,
WIN_SHOW = 50,
PLACE_SHOW = 60,
WIN_PLACE_SHOW = 70,
QUINELLA = 80,
EXACTA = 110,
DAILY_DOUBLE = 310
}
export const WagerTypesGroup = {
WIN_PLACE_SHOW: [
WagerTypes.WIN,
WagerTypes.PLACE_SHOW,
WagerTypes.WIN_PLACE,
WagerTypes.WIN_SHOW,
WagerTypes.WIN_PLACE_SHOW,
WagerTypes.SHOW,
WagerTypes.PLACE
],
WIN: [
WagerTypes.WIN,
WagerTypes.WIN_PLACE,
WagerTypes.WIN_SHOW,
WagerTypes.WIN_PLACE_SHOW
]
};
export interface WagerGroupsItem {
errorMessage: string;
group: string;
title: string;
value: string;
}
export interface WagerTypeDetails {
group: WagerType;
isBox: boolean;
isKey: boolean;
isWheel: boolean;
legCount: number;
type: WagerType;
}
webpack://frontend-mybets/../../packages/tvg-lib-utils/betSelection.ts
import { get, find, has } from "lodash";
import {
RaceProgram,
RaceWagerType,
BettingInterest,
RaceInfoMyBets
} from "@tvg/ts-types/Race";
import {
BIRunner,
BettingInterests,
VisualSelections
} from "@tvg/ts-types/Selections";
import { BetRunnerDetails, BetSelection } from "@tvg/ts-types/Bet";
import formatSequential from "@tvg/formatter/numeric";
import {
WagerTypeCodesEnum,
WagerTypes,
WagerTypesGroup
} from "@tvg/ts-types/Wager";
export const simpleBetTypes = [
WagerTypeCodesEnum.WIN,
WagerTypeCodesEnum.PLACE,
WagerTypeCodesEnum.SHOW,
WagerTypeCodesEnum.WIN_PLACE,
WagerTypeCodesEnum.WIN_SHOW,
WagerTypeCodesEnum.PLACE_SHOW,
WagerTypeCodesEnum.WIN_PLACE_SHOW
];
const setMatrixSizeByColumnCount = (columnCount: number): string[][] =>
columnCount >= 1 ? Array(columnCount).fill([]) : [[]];
const hasBetType = (
betTypeID: number | null | undefined,
currentRace: RaceProgram
): boolean => {
const wagerTypes = get(currentRace, "wagerTypes", []);
return !!find(
wagerTypes,
(wagerType) => `${wagerType.type.id}` === `${betTypeID}`
);
};
const getDefaultBetType = (
currentRace: RaceProgram,
defaultBetTypeID: string = "",
logged: boolean = false
): RaceWagerType | null => {
const wagerTypes = get(currentRace, "wagerTypes", []);
const defaultType = get(wagerTypes, "[0]");
if (logged) {
const findWagerType = find(
wagerTypes,
(wagerType) => `${wagerType.type.id}` === `${defaultBetTypeID}`
);
const isSpecialGroup = WagerTypesGroup.WIN_PLACE_SHOW.includes(
Number(defaultBetTypeID)
);
const isSpecialGroupAvailableOnRace = wagerTypes.some(
(wagerType) => wagerType.type.id === WagerTypes.WIN_PLACE_SHOW
);
const WPSDefaultBetType = wagerTypes.find(
(wagerType) => wagerType.type.id === WagerTypes.WIN_PLACE_SHOW
);
const handleDefaultBetType =
isSpecialGroup && isSpecialGroupAvailableOnRace
? WPSDefaultBetType
: defaultType;
return findWagerType || (handleDefaultBetType as RaceWagerType);
}
return defaultType;
};
const isValidBetType = (
currentRace: RaceProgram,
betType: number | null | undefined
) => hasBetType(betType, currentRace);
const isValidBetAmount = (
wager: RaceWagerType | null | undefined,
betAmount = 0
) => betAmount >= get(wager, "minWagerAmount", 100000);
const isValidBetSelection = (
wager: RaceWagerType | null | undefined,
betSelections: string[][]
) => betSelections.length === get(wager, "columnCount", 1);
export const getVisualSelections = ({
selections,
bettingInterests,
isLegSelections,
shouldShowAlternates
}: {
selections: Array<Array<string>>;
bettingInterests?: BettingInterest[];
isLegSelections?: boolean;
shouldShowAlternates?: boolean;
}): VisualSelections[] =>
(selections || []).map((selection, selectionIndex) =>
(selection || []).flatMap((singleSelection) => {
const isCurrentRaceSelections = selectionIndex === 0 || !isLegSelections;
const biRunners: VisualSelections = [];
// Remove 'B' from alternate selection for matching purposes
const cleanedSelection = singleSelection.replace("B", "");
const isAlternate = singleSelection.includes("B");
if (
typeof shouldShowAlternates !== "undefined" &&
!shouldShowAlternates &&
isAlternate
) {
return [];
}
const selectedBI = (bettingInterests || []).find(
(bi) => +bi.biNumber === +cleanedSelection
);
if (selectedBI && isCurrentRaceSelections) {
(selectedBI.runners || []).forEach((runner) => {
biRunners.push({
number: runner.runnerId,
numberColor: selectedBI.numberColor,
saddleColor: selectedBI.saddleColor,
isAlternate,
...(isCurrentRaceSelections
? { scratched: !!runner.scratched }
: {})
});
});
} else {
biRunners.push({
number: cleanedSelection,
numberColor: "",
saddleColor: "",
isAlternate
});
}
return biRunners;
})
);
export const getVisualSelectionsWithRaces = (
selections: Array<Array<string>>,
races: Array<RaceProgram>,
isPick: boolean = false
): VisualSelections[] =>
(selections || []).map((raceSelections, index) => {
const currentRace = get(races, isPick ? index : 0, []);
const biRunners: VisualSelections = [];
(raceSelections || []).forEach((runnerSelection) => {
const bettingInterests: Array<BettingInterest> = get(
currentRace,
"bettingInterests",
[]
);
const selectedBI = bettingInterests.find(
(bi) => +bi.biNumber === +runnerSelection
);
const runners = get(selectedBI, "runners", []);
if (!runners.length) {
biRunners.push({
number: runnerSelection,
numberColor: "",
saddleColor: "",
scratched: false
});
} else {
runners.forEach((runner) => {
biRunners.push({
number: runner.runnerId,
numberColor: selectedBI?.numberColor || "",
saddleColor: selectedBI?.saddleColor || "",
scratched: !!runner.scratched
});
});
}
});
return biRunners;
});
export const getSelectionsRunnerNbrScratched = (
selections: Array<VisualSelections>
): Array<Array<string>> =>
selections.map((fullSelection) =>
fullSelection
.filter((selection) => selection.scratched)
.map((scratched) => scratched.number)
);
export const getValidRunnerId = (
selection: Array<BetSelection | BettingInterests>
) =>
selection.reduce((accSelection: string[], selectionRunner) => {
const validSelection = (
selectionRunner.runners as Array<BetRunnerDetails | BIRunner>
).reduce((accRunner: string[], runner) => {
const isScrached = has(runner, "isScratched")
? get(runner, "isScratched", false)
: get(runner, "scratched", false);
if (!isScrached) {
accRunner.push(runner?.runnerId?.toString());
}
return accRunner;
}, [] as string[]);
const isAlternate = get(selectionRunner, "isAlternate", false);
if (validSelection.length && !isAlternate) {
accSelection.push(...validSelection);
}
return accSelection;
}, []);
const getBetAmount = (
wager: RaceWagerType | null,
userAccountNumber: string,
MinimalValues: boolean,
BetAmountPreference: Record<string, number>
) => {
const picksDefault = [310, 330, 340, 350, 360, 370, 380, 390, 400];
if (!!userAccountNumber && !MinimalValues) {
const betTypeId = +get(wager, "type.id", "");
let defaultValue = 0;
// Identify picks and daily doubles
if (picksDefault.includes(betTypeId)) {
defaultValue = +get(BetAmountPreference, "P", 0);
} else {
defaultValue = +get(BetAmountPreference, betTypeId, 0);
}
return defaultValue >= get(wager, "minWagerAmount", 100000)
? defaultValue
: get(wager, "wagerAmounts[0]", 0);
}
return get(wager, "wagerAmounts[0]", 0);
};
const getBetAmountWPSBetSelections = (
wager: RaceWagerType | undefined,
BetAmountPreference: Record<string, number>
) => {
const betTypeId = +get(wager, "type.id", "");
const defaultValue = +get(BetAmountPreference, betTypeId, 0);
return defaultValue >= get(wager, "minWagerAmount", 100000)
? defaultValue
: get(wager, "wagerAmounts[0]", 0);
};
const filterBetTypeFromRaceCallback =
(betTypeID: number | null | undefined) => (wagerType: RaceWagerType) =>
`${wagerType.type.id}` === `${betTypeID}`;
const getBetTypeFromRace = (
currentRace: RaceProgram,
betTypeID: number | null | undefined,
useSubTypes: boolean = false
): RaceWagerType => {
const wagerTypes: Array<RaceWagerType> = get(currentRace, "wagerTypes", []);
const findWagerType = find(
wagerTypes,
filterBetTypeFromRaceCallback(betTypeID)
);
if (useSubTypes) {
const subWagerTypes = wagerTypes.reduce((acc, wagerType) => {
if (wagerType?.types?.length) {
acc.push(...wagerType.types);
}
return acc;
}, [] as RaceWagerType[]);
const findSubWagerType = find(
subWagerTypes,
filterBetTypeFromRaceCallback(betTypeID)
);
return findSubWagerType || findWagerType || wagerTypes[0];
}
return findWagerType || wagerTypes[0];
};
const getOriginalBetTypeFromRace = (
currentRace: RaceProgram | RaceInfoMyBets,
betTypeID?: WagerTypeCodesEnum
): RaceWagerType | undefined => {
let originalWagerType: RaceWagerType | undefined;
const searchWagerType = get(currentRace, "wagerTypes", []).find(
(wt: RaceWagerType) => {
if (
wt.type.code !== betTypeID &&
wt.type.id !== parseInt(`${betTypeID}`, 10)
) {
// original bet type from url ( not grouped)
originalWagerType = wt.types?.find(
(wtIn: RaceWagerType) =>
wtIn.type.code === betTypeID ||
wtIn.type.id === parseInt(`${betTypeID}`, 10)
);
return !!originalWagerType;
}
return true;
}
);
return originalWagerType || searchWagerType;
};
export const getWagerTypesNames = (
wagerType?: RaceWagerType,
enableAlternateSelection?: boolean
) => {
if (!wagerType) {
return [];
}
const {
isBox,
columnCount,
isKey,
isWheel,
legCount,
type: { code }
} = wagerType;
if (enableAlternateSelection) {
return ["Select", "Alternate"];
}
if (isKey && isBox) {
return ["Key", "Box"];
}
if (isKey) {
return ["Key", "Select"];
}
if (isBox) {
return ["Box"];
}
if (isWheel) {
return ["Primary", "Others"];
}
if (simpleBetTypes.includes(code) && legCount === 1) {
return wagerType?.type.name.split("/") || [];
}
if ((columnCount === 1 && !isBox) || legCount > 1) {
return ["Select"];
}
return Array.from({ length: columnCount }, (_, i) => formatSequential(i + 1));
};
const betSelections = {
getDefaultBetType,
setMatrixSizeByColumnCount,
hasBetType,
getBetTypeFromRace,
getBetAmount,
getBetAmountWPSBetSelections,
isValidBetType,
isValidBetAmount,
isValidBetSelection,
getVisualSelections,
getVisualSelectionsWithRaces,
getSelectionsRunnerNbrScratched,
getWagerTypesNames,
getOriginalBetTypeFromRace
};
export default betSelections;
webpack://frontend-mybets/../../packages/tvg-lib-utils/capiUtils.js
import { attempt, get, isError, replace, toPairs, escapeRegExp } from "lodash";
export const TOKEN_DELIMITER = "(?:~|#)";
export const replaceCAPIVariables = (message, variables) => {
let modifiedMessage = message;
toPairs(variables).forEach(([key, value]) => {
// eslint-disable-next-line security/detect-non-literal-regexp
modifiedMessage = replace(
modifiedMessage,
new RegExp(TOKEN_DELIMITER + escapeRegExp(key) + TOKEN_DELIMITER, "g"),
value || value === 0 ? value : ""
);
});
return modifiedMessage;
};
/*
* Use this method to parse from CAPI a stringified JSON
*/
export const parseCAPIMessage = (store, capi, defaultValue = {}) => {
const messagesJSON = get(store, `${capi}`, "");
const messages = attempt(JSON.parse, [messagesJSON]);
return isError(messages) ? defaultValue : messages;
};
export default parseCAPIMessage;
webpack://frontend-mybets/../../packages/tvg-lib-utils/cookies.ts
// @ts-ignore
import cookie from "react-cookie";
const REGEX_PREFIX_TO_REMOVE = new RegExp("^(www|local)");
export const cookieService = (
cookieName: string,
actionType: boolean,
cookieValue?: string,
maxAge?: number
): void => {
if (typeof window !== "undefined") {
const domain = window.location.hostname;
const domainForCookie = REGEX_PREFIX_TO_REMOVE.test(domain)
? domain.substring(domain.indexOf("."))
: `.${domain}`;
if (cookie.load(cookieName, { domain: domainForCookie })) {
cookie.remove(cookieName, { domain: domainForCookie });
}
// add cookies with time
if (actionType) {
cookie.save(
cookieName,
cookieValue,
maxAge
? { domain: domainForCookie, maxAge }
: { domain: domainForCookie }
);
}
}
};
webpack://frontend-mybets/../../packages/tvg-lib-ts-types/User.ts
export enum WagerProfile {
PORT_GENERIC = "PORT-Generic",
FDR_GENERIC = "FDR-Generic",
PORT_FL = "PORT-FL",
PORT_NJ = "PORT-NJ",
PORT_PA = "PORT-PA",
PORT_IA = "PORT-IA"
}
export interface Address {
streetNumber: string;
address1: string;
address2: string;
city: string;
stateAbbr: string;
state: string;
zipCode: string;
country: string;
type: AddressSelection;
}
export type AddressSelection = "RESIDENTIAL" | "MAILING";
export enum AccountRolesEnum {
USER = "USER",
TALENT = "TALENT",
WAGEROPS = "WAGEROPS",
ADMIN = "ADMIN"
}
export enum RolesMap {
TALENT = "TALENT",
WAGEROPS = "WAGEROPS",
ADMIN = "ADMIN"
}
export interface UserInfo {
accountNumber: string;
emailAddress: string;
firstName: string;
homeAddress: Address;
lastName: string;
mailingAddress: Address;
primaryPhone: string;
profile: string;
signalProviderId: string;
status: string;
transportId: string;
userName: string;
wagerStatus: number;
accountRoles: Array<AccountRolesEnum>;
currentLocationByState?: string;
hasMadePreviousWager?: boolean | null;
}
export interface User {
logged: boolean;
user: UserInfo;
}
export interface UserPromo {
id: number;
optedIn: boolean;
path: string;
}
export type UserOptedInPromos = Record<string, boolean>;
export type FavoriteTrackWithId = Record<string, string>;
export interface BrazeCardNumber {
unviewed: number;
totalCards: number;
/* eslint-disable @typescript-eslint/no-explicit-any */
cards: Array<any>; // Array<BrazeContentCard>;
}
export interface SSNObject {
firstName: string;
lastName: string;
yearOfBirth: number;
monthOfBirth: number;
dayOfBirth: number;
address: string;
zipCode: string;
lastFourSSN: string;
}
export interface AddressParam {
streetNumber: string;
address1: string;
address2: string;
zipCode: string;
city: string;
state: string;
country: string;
}
export type UserDetailsSubscription = Record<"email", boolean>;
export interface UserDetailsSignalProvider {
name: string;
providerId: string;
}
export interface UserDetails {
username: string;
password: string;
email: string;
firstName: string;
lastName: string;
dateOfBirth: string;
homeAddress: AddressParam;
mailAddress: AddressParam;
sameMailingAddress: boolean;
socialSecurityNumber: string;
phone: string;
subscriptions: UserDetailsSubscription;
signalProvider: UserDetailsSignalProvider;
}
export interface SignupDetails {
promoCode: string;
campaignCode: string;
rfr: string;
}
webpack://frontend-mybets/../../packages/tvg-lib-utils/generalUtils.ts
import axios from "axios";
import { isUndefined } from "lodash";
import tvgConf from "@tvg/conf";
import mediator from "@tvg/mediator";
import type { UnaryFn } from "@tvg/ts-types/Functional";
import type { TabItem } from "@tvg/ts-types/Common";
import type { Entry } from "@tvg/ts-types/ListItem";
import { WagerProfile } from "@tvg/ts-types/User";
import { isMobile, isXSell } from "@tvg/sh-utils/mobileUtils";
export const pluralize = (
count: number,
word: string,
showCount: boolean = true,
suffix: string = "s",
countPrefix: string = ""
) => {
const hasOnlyOne = count === 1;
const wordPluralized = !hasOnlyOne ? `${word}${suffix}` : word;
return showCount
? `${countPrefix}${count} ${wordPluralized}`
: wordPluralized;
};
export const buildTabs = (
options: Array<Entry>,
selected: string,
onSwitch: UnaryFn<string, void>,
isLoading: boolean,
className: string = ""
): TabItem[] =>
options.map((option) => ({
title: option.value,
isTitleUppercase: false,
isActive: selected === option.key,
isDisabled: isLoading,
onClick: () => onSwitch(option.key),
className,
qaLabel: `tab-item-${option.key}`
}));
export const downloadBlob = (blob: Blob, fileName: string) => {
const blobURL =
window.URL && window.URL.createObjectURL
? window.URL.createObjectURL(blob)
: window.webkitURL.createObjectURL(blob);
const tempLink = document.createElement("a");
tempLink.style.display = "none";
tempLink.href = blobURL;
tempLink.setAttribute("download", fileName);
// Safari thinks _blank anchor are pop ups. We only want to set _blank
// target if the browser does not support the HTML5 download attribute.
// This allows you to download files in desktop safari if pop up blocking
// is enabled.
if (typeof tempLink.download === "undefined") {
tempLink.setAttribute("target", "_blank");
}
if (document.body) document.body.appendChild(tempLink);
tempLink.click();
// Fixes "webkit blob resource error 1"
setTimeout(() => {
if (document.body) document.body.removeChild(tempLink);
if (window.URL) {
window.URL.revokeObjectURL(blobURL);
} else {
window.webkitURL.revokeObjectURL(blobURL);
}
}, 200);
};
export const downloadUrl = (url: string, filename: string, fileType: string) =>
isMobile(tvgConf().product)
? mediator.ios.dispatch({
type: "DOWNLOAD_FILE",
payload: {
url,
fileType,
filename
}
})
: axios(url, {
responseType: "blob",
withCredentials: true
}).then((response) => {
downloadBlob(response.data, filename);
});
export const replaceAll = (str: string, find: string, replace: string) => {
const escapedFind = find.replace(/([.*+?^=!:${}()|[\]/\\])/g, "\\$1");
return str.replace(new RegExp(escapedFind, "g"), replace);
};
export const capitalizeFirstLetter = (string: string = ""): string =>
string.charAt(0).toUpperCase() + string.slice(1);
export const validateRcnLoad = () => {
if (typeof window !== "undefined") {
// @ts-ignore
window.hasLoadedRobertStream = !!document.getElementById("rcnScript");
}
};
// TODO: Update this later when we have tvg5 context from BE
export const isTvg5 = () => tvgConf().product === "tvg5";
const SHOULD_REFETCH_LIMIT = 15 * 60 * 1000; // 15 minutes
let lastRefetch = 0;
export const recoverQueriesFromBackground = (
// eslint-disable-next-line @typescript-eslint/no-explicit-any
clients: any[]
) => {
let hidden;
let visibilityChange = "";
if (!isUndefined(document.hidden)) {
hidden = "hidden";
visibilityChange = "visibilitychange";
// @ts-ignore
} else if (!isUndefined(document.msHidden)) {
hidden = "msHidden";
visibilityChange = "msvisibilitychange";
// @ts-ignore
} else if (!isUndefined(document.webkitHidden)) {
hidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
}
if (!isUndefined(document.addEventListener) && !isUndefined(hidden)) {
document.addEventListener(
visibilityChange,
() => {
if (document.visibilityState === "visible") {
(clients || []).forEach((client) => {
if (client && client.reFetchObservableQueries) {
const now = Date.now();
const shouldRefetch = now - lastRefetch > SHOULD_REFETCH_LIMIT;
if (shouldRefetch) {
client.reFetchObservableQueries(false);
lastRefetch = now;
}
}
});
}
},
false
);
}
};
export const getNumberSuffix = (number: number) => {
const suffix =
{
"1": "st",
"2": "nd",
"3": "rd"
}[number.toString()] || "th";
return suffix;
};
// URP is now enabled by default except for Xsell
// Cookie changed because we still need ATs to be able to perform tasks within non-URP
export const isURP = !(
isXSell() ||
(typeof document !== "undefined" &&
document.cookie.includes("disableURP=true"))
);
export const isFDR = () => tvgConf().brand === "fdr";
export const isFdrDesk =
tvgConf().product === "tvg5" && tvgConf().brand === "fdr";
export const getPortByBrand = (): WagerProfile =>
isFDR() ? WagerProfile.FDR_GENERIC : WagerProfile.PORT_GENERIC;
/**
* Checks if a string represents a zero value (e.g., "0", "0.00", "$0.00").
* Strips all non-numeric and non-decimal characters, then parses as float.
* Returns true if the parsed value is zero or the string is empty/undefined.
*/
export function isZeroLike(value: string): boolean {
if (!value) return true;
const normalized = value.replace(/[^\d.]/g, "");
return parseFloat(normalized) === 0;
}
export default pluralize;
webpack://frontend-mybets/../../packages/urp-comp-location-splash/src/actions.ts
import {
AllowLocationAction,
ErrorLocationAction,
LocationStatusTypes,
LocationStatusAction,
Action,
ErrorTypes,
LocationRequiredAction,
LocationBehindScenesAction,
LocationUnderLoginFlowAction,
RGExclusionAction,
SetBlockedCountry,
SetAndroidBlockedState,
SetEmptyErrorState,
AppVersionOutdatedAction,
LocationUnderFlow,
GhostAccountExceptionAction,
WalkthroughNotFoundAction,
ActionSetStatusLocationUnderFlow,
StatusLocationUnderFlow
} from "./types";
export const setAndroidBlockedState = (): SetAndroidBlockedState => ({
type: "ANDROID_BLOCKED_STATE"
});
export const clearSplashErrors = (): SetEmptyErrorState => ({
type: "CLEAR_ERROR_SPLASH"
});
export const loadingLocationSplashAction = (): Action => ({
type: "SET_LOADING_LOCATION_SPLASH"
});
export const setBlockedCountry = (
isLocationRequired: boolean
): SetBlockedCountry => ({
type: "SET_BLOCKED_COUNTRY",
payload: isLocationRequired
});
export const allowLocationSplashAction = (
isOpen: boolean = false
): AllowLocationAction => ({
type: "ALLOW_LOCATION_SPLASH",
payload: {
isOpen
}
});
export const setLocationSplashOutdatedAppVersionAction =
(): AppVersionOutdatedAction => ({
type: "SET_APP_VERSION_OUTDATED"
});
export const errorLocationSplashAction = (
error: ErrorTypes
): ErrorLocationAction => ({
type: "ERROR_LOCATION_SPLASH",
payload: {
error
}
});
export const fdrGhostAccountExceptionAction =
(): GhostAccountExceptionAction => ({
type: "FDR_GHOST_ACCOUNT_EXCEPTION"
});
export const walkthroughNotFoundAction = (): WalkthroughNotFoundAction => ({
type: "WALKTHROUGH_NOT_FOUND"
});
export const invalidWageringStateLocationSplashAction = (): Action => ({
type: "INVALID_WAGERING_STATE_LOCATION_SPLASH"
});
export const setLocationStatusAction = (
status: LocationStatusTypes
): LocationStatusAction => ({
type: "SET_LOCATION_STATUS",
payload: {
status
}
});
export const setLocationBehindScenesAction = (
isLocationBehindTheScenes: boolean
): LocationBehindScenesAction => ({
type: "SET_LOCATION_BEHIND_SCENES",
payload: {
isLocationBehindTheScenes
}
});
export const setLocationRequiredAction = (
isLocationRequired: boolean
): LocationRequiredAction => ({
type: "SET_LOCATION_REQUIRED",
payload: {
isLocationRequired
}
});
export const setLocationUnderFlowAction = (
locationUnderFlow: LocationUnderFlow
): LocationUnderLoginFlowAction => ({
type: "SET_LOCATION_UNDER_FLOW",
payload: {
locationUnderFlow
}
});
export const rgExclusionSplashAction = (
exclusionType: string,
exclusionEndDate: string
): RGExclusionAction => ({
type: "RG_EXCLUSION_SPLASH",
payload: {
exclusionType,
exclusionEndDate
}
});
export const resetStateLocationSplashAction = (): Action => ({
type: "RESET_STATE"
});
export const setStatusLocationUnderFlow = (
status: StatusLocationUnderFlow
): ActionSetStatusLocationUnderFlow => ({
type: "STATUS_LOCATION_UNDER_FLOW",
payload: {
status
}
});
webpack://frontend-mybets/../../packages/urp-lib-amplitude/src/modules/geolocation/types.ts
import { BaseEventProps } from "../../types";
export type EventProps = BaseEventProps;
export enum MediatorEventType {
SET_USER_STATE = "SET_USER_STATE",
GEOCOMPLY_STATUS = "GEOCOMPLY_STATUS",
REMOVE_GEO_TOKEN = "REMOVE_GEO_TOKEN"
}
export interface EventData {
type: MediatorEventType;
payload: {
region: string;
status: string;
removedBy: string;
};
}
webpack://frontend-mybets/../../packages/urp-lib-amplitude/src/modules/geolocation/utils.ts
import mediator from "@tvg/mediator";
import { MediatorEventType } from "./types";
export const amplitudeSetUserState = (region: string) => {
mediator.base.dispatch({
type: MediatorEventType.SET_USER_STATE,
payload: {
region
}
});
};
export const amplitudeSetGeoComplyStatus = (status: string) => {
mediator.base.dispatch({
type: MediatorEventType.GEOCOMPLY_STATUS,
payload: {
status
}
});
};
export const amplitudeRemovedGeoToken = (removedBy: string) => {
mediator.base.dispatch({
type: MediatorEventType.REMOVE_GEO_TOKEN,
payload: {
removedBy
}
});
};
webpack://frontend-mybets/../../packages/tvg-lib-ts-types/Preferences.ts
export enum CONFIRM_MODAL_PREFERENCE {
ALWAYS = "1",
NEVER = "0"
}
webpack://frontend-mybets/../../packages/urp-lib-selectors/users/index.ts
import { get } from "lodash";
import { Store } from "redux";
import { WagerProfile, UserOptedInPromos } from "@tvg/ts-types/User";
import { SeoTrack } from "@tvg/ts-types/Track";
import { CONFIRM_MODAL_PREFERENCE } from "@tvg/ts-types/Preferences";
import { getPortByBrand } from "@tvg/utils/generalUtils";
import { ToggleStateEnum } from "@tvg/sh-lib-preferences/utils/types";
import {
OptInPromotion,
Promo,
UserEligiblePromotion
} from "@tvg/ts-types/Promos";
import parseJSONCapiMessage from "@tvg/utils/capiUtils";
export const getIsLogged = (store: Store): boolean =>
get(store, "userData.logged", undefined);
export const getAccountNumber = (store: Store): string =>
get(store, "userData.user.accountNumber", "");
export const getFdUserId = (store: Store): string =>
get(store, "userData.user.fdUserId", "");
export const getWagerProfile = (store: Store): WagerProfile =>
get(store, "userData.user.profile") || getPortByBrand();
export const getTracksData = (store: Store): Array<SeoTrack> =>
get(store, "app.seoTrackList", []);
export const getOptedInPromos = (store: Store): UserOptedInPromos =>
get(store, "userData.optedInPromos", {});
export const getCPPPromos = (store: Store) =>
get(store, "cppPromos.promotions", []);
export const getBalance = (store: Store): number =>
get(store, "userData.balance", 0);
export const getBonus = (store: Store): number =>
get(store, "userData.bonus", 0);
export const getBalancePreference = (store: Store): ToggleStateEnum =>
get(store, "userData.preferences.balance_is_shown", ToggleStateEnum.OFF);
export const getShowBetConfirmPref = (store: Store): string =>
get(
store,
"userData.preferences.show_bet_confirm",
CONFIRM_MODAL_PREFERENCE.ALWAYS
);
export const getResidenceState = (store: Store): string =>
get(store, "userData.user.homeAddress.state", "");
export const getFirstName = (store: Store): string =>
get(store, "userData.user.firstName", "");
export const getLastName = (store: Store): string =>
get(store, "userData.user.lastName", "");
export const getIsVerified = (store: Store): boolean =>
get(store, "userData.isVerified", false);
export const getIsTermsAccepted = (store: Store): boolean =>
get(store, "userData.isTermsAccepted", false);
export const getEmail = (store: Store): string =>
get(store, "userData.user.emailAddress");
export const getUserPromotions = (store: Store): Promo[] =>
get(store, "userPromos.promotions", []);
export const getUserEligiblePromotions = (
store: Store
): UserEligiblePromotion[] => get(store, "userPromos.eligiblePromotions", []);
export const getUserOptedInPromotions = (store: Store): OptInPromotion[] =>
get(store, "userPromos.optedInPromotions", []);
export const getFavoriteTracks = (store: Store): string[] =>
get(store, "userFavorites.tracks");
export const getHasRequestedLogin = (store: Store) =>
get(store, "userData.hasRequested", false);
export const getBonusFundsWagerMessages = (store: Store) =>
parseJSONCapiMessage(store, "capi.messages.bonusFundsWagerMessages", {});
export const getHasPreviousWagered = (store: Store): boolean | null =>
get(store, "userData.user.hasMadePreviousWager", null);
export const getRedirectTVGSignup = (
store: Store
): { url_redirects: string; enabled: boolean } =>
parseJSONCapiMessage(store, "capi.messages.redirectTVGSignup", {
url_redirect: "",
enabled: false
});
export const getEnableSpecialFuture = (store: Store): boolean =>
get(store, "capi.featureToggles.enableSpecialFuture", false);
export const getGotPreferences = (store: Store): boolean =>
get(store, "userData.gotPreferences");
export const getUserPreferences = (
store: Store
): Record<string, string | Record<string, string>> =>
get(store, "userData.preferences");
webpack://frontend-mybets/../../packages/urp-lib-unified-modules/src/utils/account/getUserCompliance/index.ts
import mediator from "@tvg/mediator";
export const getUserCompliance = () => {
setTimeout(() => {
mediator.base.dispatch({
type: "UM_ACCOUNT_COMPLIANCE"
});
}, 1000);
};
webpack://frontend-mybets/../../node_modules/camelize/index.js
module.exports = function(obj) {
if (typeof obj === 'string') return camelCase(obj);
return walk(obj);
};
function walk (obj) {
if (!obj || typeof obj !== 'object') return obj;
if (isDate(obj) || isRegex(obj)) return obj;
if (isArray(obj)) return map(obj, walk);
return reduce(objectKeys(obj), function (acc, key) {
var camel = camelCase(key);
acc[camel] = walk(obj[key]);
return acc;
}, {});
}
function camelCase(str) {
return str.replace(/[_.-](\w|$)/g, function (_,x) {
return x.toUpperCase();
});
}
var isArray = Array.isArray || function (obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
};
var isDate = function (obj) {
return Object.prototype.toString.call(obj) === '[object Date]';
};
var isRegex = function (obj) {
return Object.prototype.toString.call(obj) === '[object RegExp]';
};
var has = Object.prototype.hasOwnProperty;
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) {
if (has.call(obj, key)) keys.push(key);
}
return keys;
};
function map (xs, f) {
if (xs.map) return xs.map(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
res.push(f(xs[i], i));
}
return res;
}
function reduce (xs, f, acc) {
if (xs.reduce) return xs.reduce(f, acc);
for (var i = 0; i < xs.length; i++) {
acc = f(acc, xs[i], i);
}
return acc;
}
webpack://frontend-mybets/../../node_modules/cookie/index.js
/*!
* cookie
* Copyright(c) 2012-2014 Roman Shtylman
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module exports.
* @public
*/
exports.parse = parse;
exports.serialize = serialize;
/**
* Module variables.
* @private
*/
var __toString = Object.prototype.toString
var __hasOwnProperty = Object.prototype.hasOwnProperty
/**
* RegExp to match cookie-name in RFC 6265 sec 4.1.1
* This refers out to the obsoleted definition of token in RFC 2616 sec 2.2
* which has been replaced by the token definition in RFC 7230 appendix B.
*
* cookie-name = token
* token = 1*tchar
* tchar = "!" / "#" / "$" / "%" / "&" / "'" /
* "*" / "+" / "-" / "." / "^" / "_" /
* "`" / "|" / "~" / DIGIT / ALPHA
*/
var cookieNameRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
/**
* RegExp to match cookie-value in RFC 6265 sec 4.1.1
*
* cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
* cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
* ; US-ASCII characters excluding CTLs,
* ; whitespace DQUOTE, comma, semicolon,
* ; and backslash
*/
var cookieValueRegExp = /^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/;
/**
* RegExp to match domain-value in RFC 6265 sec 4.1.1
*
* domain-value = <subdomain>
* ; defined in [RFC1034], Section 3.5, as
* ; enhanced by [RFC1123], Section 2.1
* <subdomain> = <label> | <subdomain> "." <label>
* <label> = <let-dig> [ [ <ldh-str> ] <let-dig> ]
* Labels must be 63 characters or less.
* 'let-dig' not 'letter' in the first char, per RFC1123
* <ldh-str> = <let-dig-hyp> | <let-dig-hyp> <ldh-str>
* <let-dig-hyp> = <let-dig> | "-"
* <let-dig> = <letter> | <digit>
* <letter> = any one of the 52 alphabetic characters A through Z in
* upper case and a through z in lower case
* <digit> = any one of the ten digits 0 through 9
*
* Keep support for leading dot: https://github.com/jshttp/cookie/issues/173
*
* > (Note that a leading %x2E ("."), if present, is ignored even though that
* character is not permitted, but a trailing %x2E ("."), if present, will
* cause the user agent to ignore the attribute.)
*/
var domainValueRegExp = /^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i;
/**
* RegExp to match path-value in RFC 6265 sec 4.1.1
*
* path-value = <any CHAR except CTLs or ";">
* CHAR = %x01-7F
* ; defined in RFC 5234 appendix B.1
*/
var pathValueRegExp = /^[\u0020-\u003A\u003D-\u007E]*$/;
/**
* Parse a cookie header.
*
* Parse the given cookie header string into an object
* The object has the various cookies as keys(names) => values
*
* @param {string} str
* @param {object} [opt]
* @return {object}
* @public
*/
function parse(str, opt) {
if (typeof str !== 'string') {
throw new TypeError('argument str must be a string');
}
var obj = {};
var len = str.length;
// RFC 6265 sec 4.1.1, RFC 2616 2.2 defines a cookie name consists of one char minimum, plus '='.
if (len < 2) return obj;
var dec = (opt && opt.decode) || decode;
var index = 0;
var eqIdx = 0;
var endIdx = 0;
do {
eqIdx = str.indexOf('=', index);
if (eqIdx === -1) break; // No more cookie pairs.
endIdx = str.indexOf(';', index);
if (endIdx === -1) {
endIdx = len;
} else if (eqIdx > endIdx) {
// backtrack on prior semicolon
index = str.lastIndexOf(';', eqIdx - 1) + 1;
continue;
}
var keyStartIdx = startIndex(str, index, eqIdx);
var keyEndIdx = endIndex(str, eqIdx, keyStartIdx);
var key = str.slice(keyStartIdx, keyEndIdx);
// only assign once
if (!__hasOwnProperty.call(obj, key)) {
var valStartIdx = startIndex(str, eqIdx + 1, endIdx);
var valEndIdx = endIndex(str, endIdx, valStartIdx);
if (str.charCodeAt(valStartIdx) === 0x22 /* " */ && str.charCodeAt(valEndIdx - 1) === 0x22 /* " */) {
valStartIdx++;
valEndIdx--;
}
var val = str.slice(valStartIdx, valEndIdx);
obj[key] = tryDecode(val, dec);
}
index = endIdx + 1
} while (index < len);
return obj;
}
function startIndex(str, index, max) {
do {
var code = str.charCodeAt(index);
if (code !== 0x20 /* */ && code !== 0x09 /* \t */) return index;
} while (++index < max);
return max;
}
function endIndex(str, index, min) {
while (index > min) {
var code = str.charCodeAt(--index);
if (code !== 0x20 /* */ && code !== 0x09 /* \t */) return index + 1;
}
return min;
}
/**
* Serialize data into a cookie header.
*
* Serialize a name value pair into a cookie string suitable for
* http headers. An optional options object specifies cookie parameters.
*
* serialize('foo', 'bar', { httpOnly: true })
* => "foo=bar; httpOnly"
*
* @param {string} name
* @param {string} val
* @param {object} [opt]
* @return {string}
* @public
*/
function serialize(name, val, opt) {
var enc = (opt && opt.encode) || encodeURIComponent;
if (typeof enc !== 'function') {
throw new TypeError('option encode is invalid');
}
if (!cookieNameRegExp.test(name)) {
throw new TypeError('argument name is invalid');
}
var value = enc(val);
if (!cookieValueRegExp.test(value)) {
throw new TypeError('argument val is invalid');
}
var str = name + '=' + value;
if (!opt) return str;
if (null != opt.maxAge) {
var maxAge = Math.floor(opt.maxAge);
if (!isFinite(maxAge)) {
throw new TypeError('option maxAge is invalid')
}
str += '; Max-Age=' + maxAge;
}
if (opt.domain) {
if (!domainValueRegExp.test(opt.domain)) {
throw new TypeError('option domain is invalid');
}
str += '; Domain=' + opt.domain;
}
if (opt.path) {
if (!pathValueRegExp.test(opt.path)) {
throw new TypeError('option path is invalid');
}
str += '; Path=' + opt.path;
}
if (opt.expires) {
var expires = opt.expires
if (!isDate(expires) || isNaN(expires.valueOf())) {
throw new TypeError('option expires is invalid');
}
str += '; Expires=' + expires.toUTCString()
}
if (opt.httpOnly) {
str += '; HttpOnly';
}
if (opt.secure) {
str += '; Secure';
}
if (opt.partitioned) {
str += '; Partitioned'
}
if (opt.priority) {
var priority = typeof opt.priority === 'string'
? opt.priority.toLowerCase() : opt.priority;
switch (priority) {
case 'low':
str += '; Priority=Low'
break
case 'medium':
str += '; Priority=Medium'
break
case 'high':
str += '; Priority=High'
break
default:
throw new TypeError('option priority is invalid')
}
}
if (opt.sameSite) {
var sameSite = typeof opt.sameSite === 'string'
? opt.sameSite.toLowerCase() : opt.sameSite;
switch (sameSite) {
case true:
str += '; SameSite=Strict';
break;
case 'lax':
str += '; SameSite=Lax';
break;
case 'strict':
str += '; SameSite=Strict';
break;
case 'none':
str += '; SameSite=None';
break;
default:
throw new TypeError('option sameSite is invalid');
}
}
return str;
}
/**
* URL-decode string value. Optimized to skip native call when no %.
*
* @param {string} str
* @returns {string}
*/
function decode (str) {
return str.indexOf('%') !== -1
? decodeURIComponent(str)
: str
}
/**
* Determine if value is a Date.
*
* @param {*} val
* @private
*/
function isDate (val) {
return __toString.call(val) === '[object Date]';
}
/**
* Try decoding a string using a decoding function.
*
* @param {string} str
* @param {function} decode
* @private
*/
function tryDecode(str, decode) {
try {
return decode(str);
} catch (e) {
return str;
}
}
webpack://frontend-mybets/../../node_modules/cookies-next/lib/index.js
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __rest = (this && this.__rest) || function (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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.hasCookie = exports.deleteCookie = exports.setCookie = exports.getCookie = exports.getCookies = void 0;
var cookie_1 = require("cookie");
var isClientSide = function () { return typeof window !== 'undefined'; };
var isCookiesFromAppRouterMiddleware = function (cookieStore) {
if (!cookieStore)
return false;
return ('getAll' &&
'set' in cookieStore &&
typeof cookieStore.getAll === 'function' &&
typeof cookieStore.set === 'function');
};
var isContextFromAppRouterMiddleware = function (context) {
return ((!!(context === null || context === void 0 ? void 0 : context.req) && 'cookies' in context.req && isCookiesFromAppRouterMiddleware(context === null || context === void 0 ? void 0 : context.req.cookies)) ||
(!!(context === null || context === void 0 ? void 0 : context.res) && 'cookies' in context.res && isCookiesFromAppRouterMiddleware(context === null || context === void 0 ? void 0 : context.res.cookies)));
};
var transformAppRouterMiddlewareCookies = function (cookies) {
var _cookies = {};
cookies.getAll().forEach(function (_a) {
var name = _a.name, value = _a.value;
_cookies[name] = value;
});
return _cookies;
};
var stringify = function (value) {
if (value === void 0) { value = ''; }
try {
var result = JSON.stringify(value);
return /^[\{\[]/.test(result) ? result : value;
}
catch (e) {
return value;
}
};
var decode = function (str) {
if (!str)
return str;
return str.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent);
};
var getCookies = function (options) {
if (isContextFromAppRouterMiddleware(options) && (options === null || options === void 0 ? void 0 : options.req))
return transformAppRouterMiddlewareCookies(options.req.cookies);
var req;
// DefaultOptions['req] can be casted here because is narrowed by using the fn: isContextFromAppRouterMiddleware
if (options)
req = options.req;
if (!isClientSide()) {
// if cookie-parser is used in project get cookies from ctx.req.cookies
// if cookie-parser isn't used in project get cookies from ctx.req.headers.cookie
if (req && req.cookies)
return req.cookies;
if (req && req.headers.cookie)
return (0, cookie_1.parse)(req.headers.cookie);
return {};
}
var _cookies = {};
var documentCookies = document.cookie ? document.cookie.split('; ') : [];
for (var i = 0, len = documentCookies.length; i < len; i++) {
var cookieParts = documentCookies[i].split('=');
var _cookie = cookieParts.slice(1).join('=');
var name_1 = cookieParts[0];
_cookies[name_1] = _cookie;
}
return _cookies;
};
exports.getCookies = getCookies;
var getCookie = function (key, options) {
var _cookies = (0, exports.getCookies)(options);
var value = _cookies[key];
if (value === undefined)
return undefined;
return decode(value);
};
exports.getCookie = getCookie;
var setCookie = function (key, data, options) {
if (isContextFromAppRouterMiddleware(options)) {
var req = options.req, res = options.res, restOptions = __rest(options, ["req", "res"]);
var payload = __assign({ name: key, value: data }, restOptions);
if (req) {
req.cookies.set(payload);
}
if (res) {
res.cookies.set(payload);
}
return;
}
var _cookieOptions;
var _req;
var _res;
if (options) {
// DefaultOptions can be casted here because the AppRouterMiddlewareOptions is narrowed using the fn: isContextFromAppRouterMiddleware
var _a = options, req = _a.req, res = _a.res, _options = __rest(_a, ["req", "res"]);
_req = req;
_res = res;
_cookieOptions = _options;
}
var cookieStr = (0, cookie_1.serialize)(key, stringify(data), __assign({ path: '/' }, _cookieOptions));
if (!isClientSide()) {
if (_res && _req) {
var currentCookies = _res.getHeader('Set-Cookie');
if (!Array.isArray(currentCookies)) {
currentCookies = !currentCookies ? [] : [String(currentCookies)];
}
_res.setHeader('Set-Cookie', currentCookies.concat(cookieStr));
if (_req && _req.cookies) {
var _cookies = _req.cookies;
data === '' ? delete _cookies[key] : (_cookies[key] = stringify(data));
}
if (_req && _req.headers && _req.headers.cookie) {
var _cookies = (0, cookie_1.parse)(_req.headers.cookie);
data === '' ? delete _cookies[key] : (_cookies[key] = stringify(data));
_req.headers.cookie = Object.entries(_cookies).reduce(function (accum, item) {
return accum.concat("".concat(item[0], "=").concat(item[1], ";"));
}, '');
}
}
}
else {
document.cookie = cookieStr;
}
};
exports.setCookie = setCookie;
var deleteCookie = function (key, options) {
return (0, exports.setCookie)(key, '', __assign(__assign({}, options), { maxAge: -1 }));
};
exports.deleteCookie = deleteCookie;
var hasCookie = function (key, options) {
if (!key)
return false;
var cookie = (0, exports.getCookies)(options);
return cookie.hasOwnProperty(key);
};
exports.hasCookie = hasCookie;
webpack://frontend-mybets/../../node_modules/css-color-keywords/index.js
'use strict'
module.exports = require('./colors.json')
webpack://frontend-mybets/../../node_modules/css-in-js-utils/es/assignStyle.js
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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
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 _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(n); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function filterUniqueArray(arr) {
return arr.filter(function (val, index) {
return arr.lastIndexOf(val) === index;
});
}
export default function assignStyle(base) {
for (var i = 0, len = arguments.length <= 1 ? 0 : arguments.length - 1; i < len; ++i) {
var style = i + 1 < 1 || arguments.length <= i + 1 ? undefined : arguments[i + 1];
for (var property in style) {
var value = style[property];
var baseValue = base[property];
if (baseValue && value) {
if (Array.isArray(baseValue)) {
base[property] = filterUniqueArray(baseValue.concat(value));
continue;
}
if (Array.isArray(value)) {
base[property] = filterUniqueArray([baseValue].concat(_toConsumableArray(value)));
continue;
}
if (_typeof(value) === 'object') {
base[property] = assignStyle({}, baseValue, value);
continue;
}
}
base[property] = value;
}
}
return base;
}
webpack://frontend-mybets/../../node_modules/css-in-js-utils/es/camelCaseProperty.js
var DASH = /-([a-z])/g;
var MS = /^Ms/g;
var cache = {};
function toUpper(match) {
return match[1].toUpperCase();
}
export default function camelCaseProperty(property) {
if (cache.hasOwnProperty(property)) {
return cache[property];
}
var camelProp = property.replace(DASH, toUpper).replace(MS, 'ms');
cache[property] = camelProp;
return camelProp;
}
webpack://frontend-mybets/../../node_modules/css-in-js-utils/es/hyphenateProperty.js
import hyphenateStyleName from 'hyphenate-style-name';
export default function hyphenateProperty(property) {
return hyphenateStyleName(property);
}
webpack://frontend-mybets/../../node_modules/css-in-js-utils/es/cssifyDeclaration.js
import hyphenateProperty from './hyphenateProperty';
export default function cssifyDeclaration(property, value) {
return hyphenateProperty(property) + ':' + value;
}
webpack://frontend-mybets/../../node_modules/css-in-js-utils/es/cssifyObject.js
import cssifyDeclaration from './cssifyDeclaration';
export default function cssifyObject(style) {
var css = '';
for (var property in style) {
var value = style[property];
if (typeof value !== 'string' && typeof value !== 'number') {
continue;
} // prevents the semicolon after
// the last rule declaration
if (css) {
css += ';';
}
css += cssifyDeclaration(property, value);
}
return css;
}
webpack://frontend-mybets/../../node_modules/css-in-js-utils/es/isPrefixedProperty.js
var RE = /^(Webkit|Moz|O|ms)/;
export default function isPrefixedProperty(property) {
return RE.test(property);
}
webpack://frontend-mybets/../../node_modules/css-in-js-utils/es/isPrefixedValue.js
var RE = /-webkit-|-moz-|-ms-/;
export default function isPrefixedValue(value) {
return typeof value === 'string' && RE.test(value);
}
webpack://frontend-mybets/../../node_modules/css-in-js-utils/es/isUnitlessProperty.js
import hyphenateProperty from './hyphenateProperty';
var unitlessProperties = {
borderImageOutset: true,
borderImageSlice: true,
borderImageWidth: true,
fontWeight: true,
lineHeight: true,
opacity: true,
orphans: true,
tabSize: true,
widows: true,
zIndex: true,
zoom: true,
// SVG-related properties
fillOpacity: true,
floodOpacity: true,
stopOpacity: true,
strokeDasharray: true,
strokeDashoffset: true,
strokeMiterlimit: true,
strokeOpacity: true,
strokeWidth: true
};
var prefixedUnitlessProperties = ['animationIterationCount', 'boxFlex', 'boxFlexGroup', 'boxOrdinalGroup', 'columnCount', 'flex', 'flexGrow', 'flexPositive', 'flexShrink', 'flexNegative', 'flexOrder', 'gridColumn', 'gridColumnEnd', 'gridColumnStart', 'gridRow', 'gridRowEnd', 'gridRowStart', 'lineClamp', 'order'];
var prefixes = ['Webkit', 'ms', 'Moz', 'O'];
function getPrefixedProperty(prefix, property) {
return prefix + property.charAt(0).toUpperCase() + property.slice(1);
} // add all prefixed properties to the unitless properties
for (var i = 0, len = prefixedUnitlessProperties.length; i < len; ++i) {
var property = prefixedUnitlessProperties[i];
unitlessProperties[property] = true;
for (var j = 0, jLen = prefixes.length; j < jLen; ++j) {
unitlessProperties[getPrefixedProperty(prefixes[j], property)] = true;
}
} // add all hypenated properties as well
for (var _property in unitlessProperties) {
unitlessProperties[hyphenateProperty(_property)] = true;
}
export default function isUnitlessProperty(property) {
return unitlessProperties.hasOwnProperty(property);
}
webpack://frontend-mybets/../../node_modules/css-in-js-utils/es/unprefixProperty.js
var RE = /^(ms|Webkit|Moz|O)/;
export default function unprefixProperty(property) {
var propertyWithoutPrefix = property.replace(RE, '');
return propertyWithoutPrefix.charAt(0).toLowerCase() + propertyWithoutPrefix.slice(1);
}
webpack://frontend-mybets/../../node_modules/css-in-js-utils/es/normalizeProperty.js
import camelCaseProperty from './camelCaseProperty';
import unprefixProperty from './unprefixProperty';
export default function normalizeProperty(property) {
return unprefixProperty(camelCaseProperty(property));
}
webpack://frontend-mybets/../../node_modules/css-in-js-utils/es/resolveArrayValue.js
import hyphenateProperty from './hyphenateProperty';
export default function resolveArrayValue(property, value) {
return value.join(';' + hyphenateProperty(property) + ':');
}
webpack://frontend-mybets/../../node_modules/css-in-js-utils/es/unprefixValue.js
var RE = /(-ms-|-webkit-|-moz-|-o-)/g;
export default function unprefixValue(value) {
if (typeof value === 'string') {
return value.replace(RE, '');
}
return value;
}
webpack://frontend-mybets/../../node_modules/css-in-js-utils/lib/hyphenateProperty.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = hyphenateProperty;
var _hyphenateStyleName = require("hyphenate-style-name");
var _hyphenateStyleName2 = _interopRequireDefault(_hyphenateStyleName);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function hyphenateProperty(property) {
return (0, _hyphenateStyleName2["default"])(property);
}
webpack://frontend-mybets/../../node_modules/css-in-js-utils/lib/isPrefixedValue.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = isPrefixedValue;
var RE = /-webkit-|-moz-|-ms-/;
function isPrefixedValue(value) {
return typeof value === 'string' && RE.test(value);
}
webpack://frontend-mybets/../../node_modules/css-to-react-native/index.js
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopDefault(ex) {
return ex && typeof ex === 'object' && 'default' in ex ? ex['default'] : ex;
}
var parse = require('postcss-value-parser');
var parse__default = _interopDefault(parse);
var camelizeStyleName = _interopDefault(require('camelize'));
var cssColorKeywords = _interopDefault(require('css-color-keywords'));
var matchString = function matchString(node) {
if (node.type !== 'string') return null;
return node.value.replace(/\\([0-9a-f]{1,6})(?:\s|$)/gi, function (match, charCode) {
return String.fromCharCode(parseInt(charCode, 16));
}).replace(/\\/g, '');
};
var hexColorRe = /^(#(?:[0-9a-f]{3,4}){1,2})$/i;
var cssFunctionNameRe = /^(rgba?|hsla?|hwb|lab|lch|gray|color)$/;
var matchColor = function matchColor(node) {
if (node.type === 'word' && (hexColorRe.test(node.value) || node.value in cssColorKeywords || node.value === 'transparent')) {
return node.value;
} else if (node.type === 'function' && cssFunctionNameRe.test(node.value)) {
return parse.stringify(node);
}
return null;
};
var noneRe = /^(none)$/i;
var autoRe = /^(auto)$/i;
var identRe = /(^-?[_a-z][_a-z0-9-]*$)/i; // Note if these are wrong, you'll need to change index.js too
var numberRe = /^([+-]?(?:\d*\.)?\d+(?:e[+-]?\d+)?)$/i; // Note lengthRe is sneaky: you can omit units for 0
var lengthRe = /^(0$|(?:[+-]?(?:\d*\.)?\d+(?:e[+-]?\d+)?)(?=px$))/i;
var unsupportedUnitRe = /^([+-]?(?:\d*\.)?\d+(?:e[+-]?\d+)?(ch|em|ex|rem|vh|vw|vmin|vmax|cm|mm|in|pc|pt))$/i;
var angleRe = /^([+-]?(?:\d*\.)?\d+(?:e[+-]?\d+)?(?:deg|rad))$/i;
var percentRe = /^([+-]?(?:\d*\.)?\d+(?:e[+-]?\d+)?%)$/i;
var noopToken = function noopToken(predicate) {
return function (node) {
return predicate(node) ? '<token>' : null;
};
};
var valueForTypeToken = function valueForTypeToken(type) {
return function (node) {
return node.type === type ? node.value : null;
};
};
var regExpToken = function regExpToken(regExp, transform) {
if (transform === void 0) {
transform = String;
}
return function (node) {
if (node.type !== 'word') return null;
var match = node.value.match(regExp);
if (match === null) return null;
var value = transform(match[1]);
return value;
};
};
var SPACE = noopToken(function (node) {
return node.type === 'space';
});
var SLASH = noopToken(function (node) {
return node.type === 'div' && node.value === '/';
});
var COMMA = noopToken(function (node) {
return node.type === 'div' && node.value === ',';
});
var WORD = valueForTypeToken('word');
var NONE = regExpToken(noneRe);
var AUTO = regExpToken(autoRe);
var NUMBER = regExpToken(numberRe, Number);
var LENGTH = regExpToken(lengthRe, Number);
var UNSUPPORTED_LENGTH_UNIT = regExpToken(unsupportedUnitRe);
var ANGLE = regExpToken(angleRe, function (angle) {
return angle.toLowerCase();
});
var PERCENT = regExpToken(percentRe);
var IDENT = regExpToken(identRe);
var STRING = matchString;
var COLOR = matchColor;
var LINE = regExpToken(/^(none|underline|line-through)$/i);
var aspectRatio = function aspectRatio(tokenStream) {
var aspectRatio = tokenStream.expect(NUMBER);
if (tokenStream.hasTokens()) {
tokenStream.expect(SLASH);
aspectRatio /= tokenStream.expect(NUMBER);
}
return {
aspectRatio: aspectRatio
};
};
var BORDER_STYLE = regExpToken(/^(solid|dashed|dotted)$/);
var defaultBorderWidth = 1;
var defaultBorderColor = 'black';
var defaultBorderStyle = 'solid';
var border = function border(tokenStream) {
var borderWidth;
var borderColor;
var borderStyle;
if (tokenStream.matches(NONE)) {
tokenStream.expectEmpty();
return {
borderWidth: 0,
borderColor: 'black',
borderStyle: 'solid'
};
}
var partsParsed = 0;
while (partsParsed < 3 && tokenStream.hasTokens()) {
if (partsParsed !== 0) tokenStream.expect(SPACE);
if (borderWidth === undefined && tokenStream.matches(LENGTH, UNSUPPORTED_LENGTH_UNIT)) {
borderWidth = tokenStream.lastValue;
} else if (borderColor === undefined && tokenStream.matches(COLOR)) {
borderColor = tokenStream.lastValue;
} else if (borderStyle === undefined && tokenStream.matches(BORDER_STYLE)) {
borderStyle = tokenStream.lastValue;
} else {
tokenStream["throw"]();
}
partsParsed += 1;
}
tokenStream.expectEmpty();
if (borderWidth === undefined) borderWidth = defaultBorderWidth;
if (borderColor === undefined) borderColor = defaultBorderColor;
if (borderStyle === undefined) borderStyle = defaultBorderStyle;
return {
borderWidth: borderWidth,
borderColor: borderColor,
borderStyle: borderStyle
};
};
var directionFactory = function directionFactory(_ref) {
var _ref$types = _ref.types,
types = _ref$types === void 0 ? [LENGTH, UNSUPPORTED_LENGTH_UNIT, PERCENT] : _ref$types,
_ref$directions = _ref.directions,
directions = _ref$directions === void 0 ? ['Top', 'Right', 'Bottom', 'Left'] : _ref$directions,
_ref$prefix = _ref.prefix,
prefix = _ref$prefix === void 0 ? '' : _ref$prefix,
_ref$suffix = _ref.suffix,
suffix = _ref$suffix === void 0 ? '' : _ref$suffix;
return function (tokenStream) {
var _ref2;
var values = []; // borderWidth doesn't currently allow a percent value, but may do in the future
values.push(tokenStream.expect.apply(tokenStream, types));
while (values.length < 4 && tokenStream.hasTokens()) {
tokenStream.expect(SPACE);
values.push(tokenStream.expect.apply(tokenStream, types));
}
tokenStream.expectEmpty();
var top = values[0],
_values$ = values[1],
right = _values$ === void 0 ? top : _values$,
_values$2 = values[2],
bottom = _values$2 === void 0 ? top : _values$2,
_values$3 = values[3],
left = _values$3 === void 0 ? right : _values$3;
var keyFor = function keyFor(n) {
return "" + prefix + directions[n] + suffix;
};
return _ref2 = {}, _ref2[keyFor(0)] = top, _ref2[keyFor(1)] = right, _ref2[keyFor(2)] = bottom, _ref2[keyFor(3)] = left, _ref2;
};
};
var parseShadowOffset = function parseShadowOffset(tokenStream) {
var width = tokenStream.expect(LENGTH);
var height = tokenStream.matches(SPACE) ? tokenStream.expect(LENGTH) : width;
tokenStream.expectEmpty();
return {
width: width,
height: height
};
};
var parseShadow = function parseShadow(tokenStream) {
var offsetX;
var offsetY;
var radius;
var color;
if (tokenStream.matches(NONE)) {
tokenStream.expectEmpty();
return {
offset: {
width: 0,
height: 0
},
radius: 0,
color: 'black'
};
}
var didParseFirst = false;
while (tokenStream.hasTokens()) {
if (didParseFirst) tokenStream.expect(SPACE);
if (offsetX === undefined && tokenStream.matches(LENGTH, UNSUPPORTED_LENGTH_UNIT)) {
offsetX = tokenStream.lastValue;
tokenStream.expect(SPACE);
offsetY = tokenStream.expect(LENGTH, UNSUPPORTED_LENGTH_UNIT);
tokenStream.saveRewindPoint();
if (tokenStream.matches(SPACE) && tokenStream.matches(LENGTH, UNSUPPORTED_LENGTH_UNIT)) {
radius = tokenStream.lastValue;
} else {
tokenStream.rewind();
}
} else if (color === undefined && tokenStream.matches(COLOR)) {
color = tokenStream.lastValue;
} else {
tokenStream["throw"]();
}
didParseFirst = true;
}
if (offsetX === undefined) tokenStream["throw"]();
return {
offset: {
width: offsetX,
height: offsetY
},
radius: radius !== undefined ? radius : 0,
color: color !== undefined ? color : 'black'
};
};
var boxShadow = function boxShadow(tokenStream) {
var _parseShadow = parseShadow(tokenStream),
offset = _parseShadow.offset,
radius = _parseShadow.radius,
color = _parseShadow.color;
return {
shadowOffset: offset,
shadowRadius: radius,
shadowColor: color,
shadowOpacity: 1
};
};
var defaultFlexGrow = 1;
var defaultFlexShrink = 1;
var defaultFlexBasis = 0;
var flex = function flex(tokenStream) {
var flexGrow;
var flexShrink;
var flexBasis;
if (tokenStream.matches(NONE)) {
tokenStream.expectEmpty();
return {
flexGrow: 0,
flexShrink: 0,
flexBasis: 'auto'
};
}
tokenStream.saveRewindPoint();
if (tokenStream.matches(AUTO) && !tokenStream.hasTokens()) {
return {
flexGrow: 1,
flexShrink: 1,
flexBasis: 'auto'
};
}
tokenStream.rewind();
var partsParsed = 0;
while (partsParsed < 2 && tokenStream.hasTokens()) {
if (partsParsed !== 0) tokenStream.expect(SPACE);
if (flexGrow === undefined && tokenStream.matches(NUMBER)) {
flexGrow = tokenStream.lastValue;
tokenStream.saveRewindPoint();
if (tokenStream.matches(SPACE) && tokenStream.matches(NUMBER)) {
flexShrink = tokenStream.lastValue;
} else {
tokenStream.rewind();
}
} else if (flexBasis === undefined && tokenStream.matches(LENGTH, UNSUPPORTED_LENGTH_UNIT, PERCENT)) {
flexBasis = tokenStream.lastValue;
} else if (flexBasis === undefined && tokenStream.matches(AUTO)) {
flexBasis = 'auto';
} else {
tokenStream["throw"]();
}
partsParsed += 1;
}
tokenStream.expectEmpty();
if (flexGrow === undefined) flexGrow = defaultFlexGrow;
if (flexShrink === undefined) flexShrink = defaultFlexShrink;
if (flexBasis === undefined) flexBasis = defaultFlexBasis;
return {
flexGrow: flexGrow,
flexShrink: flexShrink,
flexBasis: flexBasis
};
};
var FLEX_WRAP = regExpToken(/(nowrap|wrap|wrap-reverse)/);
var FLEX_DIRECTION = regExpToken(/(row|row-reverse|column|column-reverse)/);
var defaultFlexWrap = 'nowrap';
var defaultFlexDirection = 'row';
var flexFlow = function flexFlow(tokenStream) {
var flexWrap;
var flexDirection;
var partsParsed = 0;
while (partsParsed < 2 && tokenStream.hasTokens()) {
if (partsParsed !== 0) tokenStream.expect(SPACE);
if (flexWrap === undefined && tokenStream.matches(FLEX_WRAP)) {
flexWrap = tokenStream.lastValue;
} else if (flexDirection === undefined && tokenStream.matches(FLEX_DIRECTION)) {
flexDirection = tokenStream.lastValue;
} else {
tokenStream["throw"]();
}
partsParsed += 1;
}
tokenStream.expectEmpty();
if (flexWrap === undefined) flexWrap = defaultFlexWrap;
if (flexDirection === undefined) flexDirection = defaultFlexDirection;
return {
flexWrap: flexWrap,
flexDirection: flexDirection
};
};
var fontFamily = function fontFamily(tokenStream) {
var fontFamily;
if (tokenStream.matches(STRING)) {
fontFamily = tokenStream.lastValue;
} else {
fontFamily = tokenStream.expect(IDENT);
while (tokenStream.hasTokens()) {
tokenStream.expect(SPACE);
var nextIdent = tokenStream.expect(IDENT);
fontFamily += " " + nextIdent;
}
}
tokenStream.expectEmpty();
return {
fontFamily: fontFamily
};
};
var NORMAL = regExpToken(/^(normal)$/);
var STYLE = regExpToken(/^(italic)$/);
var WEIGHT = regExpToken(/^([1-9]00|bold)$/);
var VARIANT = regExpToken(/^(small-caps)$/);
var defaultFontStyle = 'normal';
var defaultFontWeight = 'normal';
var defaultFontVariant = [];
var font = function font(tokenStream) {
var fontStyle;
var fontWeight;
var fontVariant; // let fontSize;
var lineHeight; // let fontFamily;
var numStyleWeightVariantMatched = 0;
while (numStyleWeightVariantMatched < 3 && tokenStream.hasTokens()) {
if (tokenStream.matches(NORMAL)) ;else if (fontStyle === undefined && tokenStream.matches(STYLE)) {
fontStyle = tokenStream.lastValue;
} else if (fontWeight === undefined && tokenStream.matches(WEIGHT)) {
fontWeight = tokenStream.lastValue;
} else if (fontVariant === undefined && tokenStream.matches(VARIANT)) {
fontVariant = [tokenStream.lastValue];
} else {
break;
}
tokenStream.expect(SPACE);
numStyleWeightVariantMatched += 1;
}
var fontSize = tokenStream.expect(LENGTH, UNSUPPORTED_LENGTH_UNIT);
if (tokenStream.matches(SLASH)) {
lineHeight = tokenStream.expect(LENGTH, UNSUPPORTED_LENGTH_UNIT);
}
tokenStream.expect(SPACE);
var _fontFamily = fontFamily(tokenStream),
fontFamily$1 = _fontFamily.fontFamily;
if (fontStyle === undefined) fontStyle = defaultFontStyle;
if (fontWeight === undefined) fontWeight = defaultFontWeight;
if (fontVariant === undefined) fontVariant = defaultFontVariant;
var out = {
fontStyle: fontStyle,
fontWeight: fontWeight,
fontVariant: fontVariant,
fontSize: fontSize,
fontFamily: fontFamily$1
};
if (lineHeight !== undefined) out.lineHeight = lineHeight;
return out;
};
var fontVariant = function fontVariant(tokenStream) {
var values = [tokenStream.expect(IDENT)];
while (tokenStream.hasTokens()) {
tokenStream.expect(SPACE);
values.push(tokenStream.expect(IDENT));
}
return {
fontVariant: values
};
};
var ALIGN_CONTENT = regExpToken(/(flex-(?:start|end)|center|stretch|space-(?:between|around))/);
var JUSTIFY_CONTENT = regExpToken(/(flex-(?:start|end)|center|space-(?:between|around|evenly))/);
var placeContent = function placeContent(tokenStream) {
var alignContent = tokenStream.expect(ALIGN_CONTENT);
var justifyContent;
if (tokenStream.hasTokens()) {
tokenStream.expect(SPACE);
justifyContent = tokenStream.expect(JUSTIFY_CONTENT);
} else {
justifyContent = 'stretch';
}
tokenStream.expectEmpty();
return {
alignContent: alignContent,
justifyContent: justifyContent
};
};
var STYLE$1 = regExpToken(/^(solid|double|dotted|dashed)$/);
var defaultTextDecorationLine = 'none';
var defaultTextDecorationStyle = 'solid';
var defaultTextDecorationColor = 'black';
var textDecoration = function textDecoration(tokenStream) {
var line;
var style;
var color;
var didParseFirst = false;
while (tokenStream.hasTokens()) {
if (didParseFirst) tokenStream.expect(SPACE);
if (line === undefined && tokenStream.matches(LINE)) {
var lines = [tokenStream.lastValue.toLowerCase()];
tokenStream.saveRewindPoint();
if (lines[0] !== 'none' && tokenStream.matches(SPACE) && tokenStream.matches(LINE)) {
lines.push(tokenStream.lastValue.toLowerCase()); // Underline comes before line-through
lines.sort().reverse();
} else {
tokenStream.rewind();
}
line = lines.join(' ');
} else if (style === undefined && tokenStream.matches(STYLE$1)) {
style = tokenStream.lastValue;
} else if (color === undefined && tokenStream.matches(COLOR)) {
color = tokenStream.lastValue;
} else {
tokenStream["throw"]();
}
didParseFirst = true;
}
return {
textDecorationLine: line !== undefined ? line : defaultTextDecorationLine,
textDecorationColor: color !== undefined ? color : defaultTextDecorationColor,
textDecorationStyle: style !== undefined ? style : defaultTextDecorationStyle
};
};
var textDecorationLine = function textDecorationLine(tokenStream) {
var lines = [];
var didParseFirst = false;
while (tokenStream.hasTokens()) {
if (didParseFirst) tokenStream.expect(SPACE);
lines.push(tokenStream.expect(LINE).toLowerCase());
didParseFirst = true;
}
lines.sort().reverse();
return {
textDecorationLine: lines.join(' ')
};
};
var textShadow = function textShadow(tokenStream) {
var _parseShadow2 = parseShadow(tokenStream),
offset = _parseShadow2.offset,
radius = _parseShadow2.radius,
color = _parseShadow2.color;
return {
textShadowOffset: offset,
textShadowRadius: radius,
textShadowColor: color
};
};
var oneOfType = function oneOfType(tokenType) {
return function (functionStream) {
var value = functionStream.expect(tokenType);
functionStream.expectEmpty();
return value;
};
};
var singleNumber = oneOfType(NUMBER);
var singleLength = oneOfType(LENGTH);
var singleAngle = oneOfType(ANGLE);
var xyTransformFactory = function xyTransformFactory(tokenType) {
return function (key, valueIfOmitted) {
return function (functionStream) {
var _ref3, _ref4;
var x = functionStream.expect(tokenType);
var y;
if (functionStream.hasTokens()) {
functionStream.expect(COMMA);
y = functionStream.expect(tokenType);
} else if (valueIfOmitted !== undefined) {
y = valueIfOmitted;
} else {
// Assumption, if x === y, then we can omit XY
// I.e. scale(5) => [{ scale: 5 }] rather than [{ scaleX: 5 }, { scaleY: 5 }]
return x;
}
functionStream.expectEmpty();
return [(_ref3 = {}, _ref3[key + "Y"] = y, _ref3), (_ref4 = {}, _ref4[key + "X"] = x, _ref4)];
};
};
};
var xyNumber = xyTransformFactory(NUMBER);
var xyLength = xyTransformFactory(LENGTH);
var xyAngle = xyTransformFactory(ANGLE);
var partTransforms = {
perspective: singleNumber,
scale: xyNumber('scale'),
scaleX: singleNumber,
scaleY: singleNumber,
translate: xyLength('translate', 0),
translateX: singleLength,
translateY: singleLength,
rotate: singleAngle,
rotateX: singleAngle,
rotateY: singleAngle,
rotateZ: singleAngle,
skewX: singleAngle,
skewY: singleAngle,
skew: xyAngle('skew', '0deg')
};
var transform = function transform(tokenStream) {
var transforms = [];
var didParseFirst = false;
while (tokenStream.hasTokens()) {
if (didParseFirst) tokenStream.expect(SPACE);
var functionStream = tokenStream.expectFunction();
var functionName = functionStream.functionName;
var transformedValues = partTransforms[functionName](functionStream);
if (!Array.isArray(transformedValues)) {
var _ref5;
transformedValues = [(_ref5 = {}, _ref5[functionName] = transformedValues, _ref5)];
}
transforms = transformedValues.concat(transforms);
didParseFirst = true;
}
return {
transform: transforms
};
};
var background = function background(tokenStream) {
return {
backgroundColor: tokenStream.expect(COLOR)
};
};
var borderColor = directionFactory({
types: [COLOR],
prefix: 'border',
suffix: 'Color'
});
var borderRadius = directionFactory({
directions: ['TopLeft', 'TopRight', 'BottomRight', 'BottomLeft'],
prefix: 'border',
suffix: 'Radius'
});
var borderWidth = directionFactory({
prefix: 'border',
suffix: 'Width'
});
var margin = directionFactory({
types: [LENGTH, UNSUPPORTED_LENGTH_UNIT, PERCENT, AUTO],
prefix: 'margin'
});
var padding = directionFactory({
prefix: 'padding'
});
var fontWeight = function fontWeight(tokenStream) {
return {
fontWeight: tokenStream.expect(WORD) // Also match numbers as strings
};
};
var shadowOffset = function shadowOffset(tokenStream) {
return {
shadowOffset: parseShadowOffset(tokenStream)
};
};
var textShadowOffset = function textShadowOffset(tokenStream) {
return {
textShadowOffset: parseShadowOffset(tokenStream)
};
};
var transforms = {
aspectRatio: aspectRatio,
background: background,
border: border,
borderColor: borderColor,
borderRadius: borderRadius,
borderWidth: borderWidth,
boxShadow: boxShadow,
flex: flex,
flexFlow: flexFlow,
font: font,
fontFamily: fontFamily,
fontVariant: fontVariant,
fontWeight: fontWeight,
margin: margin,
padding: padding,
placeContent: placeContent,
shadowOffset: shadowOffset,
textShadow: textShadow,
textShadowOffset: textShadowOffset,
textDecoration: textDecoration,
textDecorationLine: textDecorationLine,
transform: transform
};
var propertiesWithoutUnits;
if (process.env.NODE_ENV !== 'production') {
propertiesWithoutUnits = ['aspectRatio', 'elevation', 'flexGrow', 'flexShrink', 'opacity', 'shadowOpacity', 'zIndex'];
}
var devPropertiesWithUnitsRegExp = propertiesWithoutUnits != null ? new RegExp(propertiesWithoutUnits.join('|')) : null;
var SYMBOL_MATCH = 'SYMBOL_MATCH';
var TokenStream =
/*#__PURE__*/
function () {
function TokenStream(nodes, parent) {
this.index = 0;
this.nodes = nodes;
this.functionName = parent != null ? parent.value : null;
this.lastValue = null;
this.rewindIndex = -1;
}
var _proto = TokenStream.prototype;
_proto.hasTokens = function hasTokens() {
return this.index <= this.nodes.length - 1;
};
_proto[SYMBOL_MATCH] = function () {
if (!this.hasTokens()) return null;
var node = this.nodes[this.index];
for (var i = 0; i < arguments.length; i += 1) {
var tokenDescriptor = i < 0 || arguments.length <= i ? undefined : arguments[i];
var value = tokenDescriptor(node);
if (value !== null) {
this.index += 1;
this.lastValue = value;
return value;
}
}
return null;
};
_proto.matches = function matches() {
return this[SYMBOL_MATCH].apply(this, arguments) !== null;
};
_proto.expect = function expect() {
var value = this[SYMBOL_MATCH].apply(this, arguments);
return value !== null ? value : this["throw"]();
};
_proto.matchesFunction = function matchesFunction() {
var node = this.nodes[this.index];
if (node.type !== 'function') return null;
var value = new TokenStream(node.nodes, node);
this.index += 1;
this.lastValue = null;
return value;
};
_proto.expectFunction = function expectFunction() {
var value = this.matchesFunction();
return value !== null ? value : this["throw"]();
};
_proto.expectEmpty = function expectEmpty() {
if (this.hasTokens()) this["throw"]();
};
_proto["throw"] = function _throw() {
throw new Error("Unexpected token type: " + this.nodes[this.index].type);
};
_proto.saveRewindPoint = function saveRewindPoint() {
this.rewindIndex = this.index;
};
_proto.rewind = function rewind() {
if (this.rewindIndex === -1) throw new Error('Internal error');
this.index = this.rewindIndex;
this.lastValue = null;
};
return TokenStream;
}();
/* eslint-disable no-param-reassign */
// Note if this is wrong, you'll need to change tokenTypes.js too
var numberOrLengthRe = /^([+-]?(?:\d*\.)?\d+(?:e[+-]?\d+)?)(?:px)?$/i;
var numberOnlyRe = /^[+-]?(?:\d*\.\d*|[1-9]\d*)(?:e[+-]?\d+)?$/i;
var boolRe = /^true|false$/i;
var nullRe = /^null$/i;
var undefinedRe = /^undefined$/i; // Undocumented export
var transformRawValue = function transformRawValue(propName, value) {
if (process.env.NODE_ENV !== 'production') {
var needsUnit = !devPropertiesWithUnitsRegExp.test(propName);
var isNumberWithoutUnit = numberOnlyRe.test(value);
if (needsUnit && isNumberWithoutUnit) {
// eslint-disable-next-line no-console
console.warn("Expected style \"" + propName + ": " + value + "\" to contain units");
}
if (!needsUnit && value !== '0' && !isNumberWithoutUnit) {
// eslint-disable-next-line no-console
console.warn("Expected style \"" + propName + ": " + value + "\" to be unitless");
}
}
var numberMatch = value.match(numberOrLengthRe);
if (numberMatch !== null) return Number(numberMatch[1]);
var boolMatch = value.match(boolRe);
if (boolMatch !== null) return boolMatch[0].toLowerCase() === 'true';
var nullMatch = value.match(nullRe);
if (nullMatch !== null) return null;
var undefinedMatch = value.match(undefinedRe);
if (undefinedMatch !== null) return undefined;
return value;
};
var baseTransformShorthandValue = function baseTransformShorthandValue(propName, value) {
var ast = parse__default(value);
var tokenStream = new TokenStream(ast.nodes);
return transforms[propName](tokenStream);
};
var transformShorthandValue = process.env.NODE_ENV === 'production' ? baseTransformShorthandValue : function (propName, value) {
try {
return baseTransformShorthandValue(propName, value);
} catch (e) {
throw new Error("Failed to parse declaration \"" + propName + ": " + value + "\"");
}
};
var getStylesForProperty = function getStylesForProperty(propName, inputValue, allowShorthand) {
var _ref6;
var isRawValue = allowShorthand === false || !(propName in transforms);
var value = inputValue.trim();
var propValues = isRawValue ? (_ref6 = {}, _ref6[propName] = transformRawValue(propName, value), _ref6) : transformShorthandValue(propName, value);
return propValues;
};
var getPropertyName = function getPropertyName(propName) {
var isCustomProp = /^--\w+/.test(propName);
if (isCustomProp) {
return propName;
}
return camelizeStyleName(propName);
};
var index = function index(rules, shorthandBlacklist) {
if (shorthandBlacklist === void 0) {
shorthandBlacklist = [];
}
return rules.reduce(function (accum, rule) {
var propertyName = getPropertyName(rule[0]);
var value = rule[1];
var allowShorthand = shorthandBlacklist.indexOf(propertyName) === -1;
return Object.assign(accum, getStylesForProperty(propertyName, value, allowShorthand));
}, {});
};
exports["default"] = index;
exports.getPropertyName = getPropertyName;
exports.getStylesForProperty = getStylesForProperty;
exports.transformRawValue = transformRawValue;
webpack://frontend-mybets/../../node_modules/currency-formatter/index.js
var accounting = require('accounting')
var assign = require('object-assign')
var localeCurrency = require('locale-currency')
var currencies = require('./currencies.json')
var localeFormats = require('./localeFormats.json')
var defaultCurrency = {
symbol: '',
thousandsSeparator: ',',
decimalSeparator: '.',
symbolOnLeft: true,
spaceBetweenAmountAndSymbol: false,
decimalDigits: 2
}
var defaultLocaleFormat = {}
var formatMapping = [
{
symbolOnLeft: true,
spaceBetweenAmountAndSymbol: false,
format: {
pos: '%s%v',
neg: '-%s%v',
zero: '%s%v'
}
},
{
symbolOnLeft: true,
spaceBetweenAmountAndSymbol: true,
format: {
pos: '%s %v',
neg: '-%s %v',
zero: '%s %v'
}
},
{
symbolOnLeft: false,
spaceBetweenAmountAndSymbol: false,
format: {
pos: '%v%s',
neg: '-%v%s',
zero: '%v%s'
}
},
{
symbolOnLeft: false,
spaceBetweenAmountAndSymbol: true,
format: {
pos: '%v %s',
neg: '-%v %s',
zero: '%v %s'
}
}
]
function format(value, options) {
var code = options.code || (options.locale && localeCurrency.getCurrency(options.locale))
var localeMatch = /^([a-z]+)([_-]([a-z]+))?$/i.exec(options.locale) || []
var language = localeMatch[1]
var region = localeMatch[3]
var localeFormat = assign({}, defaultLocaleFormat,
localeFormats[language] || {},
localeFormats[language + '-' + region] || {})
var currency = assign({}, defaultCurrency, findCurrency(code), localeFormat)
var symbolOnLeft = currency.symbolOnLeft
var spaceBetweenAmountAndSymbol = currency.spaceBetweenAmountAndSymbol
var format = formatMapping.filter(function(f) {
return f.symbolOnLeft == symbolOnLeft && f.spaceBetweenAmountAndSymbol == spaceBetweenAmountAndSymbol
})[0].format
return accounting.formatMoney(value, {
symbol: isUndefined(options.symbol)
? currency.symbol
: options.symbol,
decimal: isUndefined(options.decimal)
? currency.decimalSeparator
: options.decimal,
thousand: isUndefined(options.thousand)
? currency.thousandsSeparator
: options.thousand,
precision: typeof options.precision === 'number'
? options.precision
: currency.decimalDigits,
format: ['string', 'object'].indexOf(typeof options.format) > -1
? options.format
: format
})
}
function findCurrency (currencyCode) {
return currencies[currencyCode]
}
function isUndefined (val) {
return typeof val === 'undefined'
}
function unformat(value, options) {
var code = options.code || (options.locale && localeCurrency.getCurrency(options.locale))
var localeFormat = localeFormats[options.locale] || defaultLocaleFormat
var currency = assign({}, defaultCurrency, findCurrency(code), localeFormat)
var decimal = isUndefined(options.decimal) ? currency.decimalSeparator : options.decimal
return accounting.unformat(value, decimal)
}
module.exports = {
defaultCurrency: defaultCurrency,
get currencies() {
// In favor of backwards compatibility, the currencies map is converted to an array here
return Object.keys(currencies).map(function(key) {
return currencies[key]
})
},
findCurrency: findCurrency,
format: format,
unformat: unformat
}
webpack://frontend-mybets/../../node_modules/d3-ease/src/math.js
// tpmt is two power minus ten times t scaled to [0,1]
export function tpmt(x) {
return (Math.pow(2, -10 * x) - 0.0009765625) * 1.0009775171065494;
}
webpack://frontend-mybets/../../node_modules/d3-ease/src/exp.js
import {tpmt} from "./math.js";
export function expIn(t) {
return tpmt(1 - +t);
}
export function expOut(t) {
return 1 - tpmt(t);
}
export function expInOut(t) {
return ((t *= 2) <= 1 ? tpmt(1 - t) : 2 - tpmt(t - 1)) / 2;
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/_lib/getTimezoneOffsetInMilliseconds/index.js
var MILLISECONDS_IN_MINUTE = 60000;
function getDateMillisecondsPart(date) {
return date.getTime() % MILLISECONDS_IN_MINUTE;
}
/**
* Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds.
* They usually appear for dates that denote time before the timezones were introduced
* (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891
* and GMT+01:00:00 after that date)
*
* Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above,
* which would lead to incorrect calculations.
*
* This function returns the timezone offset in milliseconds that takes seconds in account.
*/
export default function getTimezoneOffsetInMilliseconds(dirtyDate) {
var date = new Date(dirtyDate.getTime());
var baseTimezoneOffset = Math.ceil(date.getTimezoneOffset());
date.setSeconds(0, 0);
var hasNegativeUTCOffset = baseTimezoneOffset > 0;
var millisecondsPartOfTimezoneOffset = hasNegativeUTCOffset ? (MILLISECONDS_IN_MINUTE + getDateMillisecondsPart(date)) % MILLISECONDS_IN_MINUTE : getDateMillisecondsPart(date);
return baseTimezoneOffset * MILLISECONDS_IN_MINUTE + millisecondsPartOfTimezoneOffset;
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/_lib/requiredArgs/index.js
export default function requiredArgs(required, args) {
if (args.length < required) {
throw new TypeError(required + ' argument' + (required > 1 ? 's' : '') + ' required, but only ' + args.length + ' present');
}
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/_lib/toInteger/index.js
export default function toInteger(dirtyNumber) {
if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) {
return NaN;
}
var number = Number(dirtyNumber);
if (isNaN(number)) {
return number;
}
return number < 0 ? Math.ceil(number) : Math.floor(number);
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/addMilliseconds/index.js
import toInteger from '../_lib/toInteger/index.js';
import toDate from '../toDate/index.js';
import requiredArgs from '../_lib/requiredArgs/index.js';
/**
* @name addMilliseconds
* @category Millisecond Helpers
* @summary Add the specified number of milliseconds to the given date.
*
* @description
* Add the specified number of milliseconds to the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of milliseconds to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} the new date with the milliseconds added
* @throws {TypeError} 2 arguments required
*
* @example
* // Add 750 milliseconds to 10 July 2014 12:45:30.000:
* var result = addMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750)
* //=> Thu Jul 10 2014 12:45:30.750
*/
export default function addMilliseconds(dirtyDate, dirtyAmount) {
requiredArgs(2, arguments);
var timestamp = toDate(dirtyDate).getTime();
var amount = toInteger(dirtyAmount);
return new Date(timestamp + amount);
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/locale/en-US/_lib/formatDistance/index.js
var formatDistanceLocale = {
lessThanXSeconds: {
one: 'less than a second',
other: 'less than {{count}} seconds'
},
xSeconds: {
one: '1 second',
other: '{{count}} seconds'
},
halfAMinute: 'half a minute',
lessThanXMinutes: {
one: 'less than a minute',
other: 'less than {{count}} minutes'
},
xMinutes: {
one: '1 minute',
other: '{{count}} minutes'
},
aboutXHours: {
one: 'about 1 hour',
other: 'about {{count}} hours'
},
xHours: {
one: '1 hour',
other: '{{count}} hours'
},
xDays: {
one: '1 day',
other: '{{count}} days'
},
aboutXWeeks: {
one: 'about 1 week',
other: 'about {{count}} weeks'
},
xWeeks: {
one: '1 week',
other: '{{count}} weeks'
},
aboutXMonths: {
one: 'about 1 month',
other: 'about {{count}} months'
},
xMonths: {
one: '1 month',
other: '{{count}} months'
},
aboutXYears: {
one: 'about 1 year',
other: 'about {{count}} years'
},
xYears: {
one: '1 year',
other: '{{count}} years'
},
overXYears: {
one: 'over 1 year',
other: 'over {{count}} years'
},
almostXYears: {
one: 'almost 1 year',
other: 'almost {{count}} years'
}
};
export default function formatDistance(token, count, options) {
options = options || {};
var result;
if (typeof formatDistanceLocale[token] === 'string') {
result = formatDistanceLocale[token];
} else if (count === 1) {
result = formatDistanceLocale[token].one;
} else {
result = formatDistanceLocale[token].other.replace('{{count}}', count);
}
if (options.addSuffix) {
if (options.comparison > 0) {
return 'in ' + result;
} else {
return result + ' ago';
}
}
return result;
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/locale/_lib/buildFormatLongFn/index.js
export default function buildFormatLongFn(args) {
return function (dirtyOptions) {
var options = dirtyOptions || {};
var width = options.width ? String(options.width) : args.defaultWidth;
var format = args.formats[width] || args.formats[args.defaultWidth];
return format;
};
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/locale/en-US/_lib/formatLong/index.js
import buildFormatLongFn from '../../../_lib/buildFormatLongFn/index.js';
var dateFormats = {
full: 'EEEE, MMMM do, y',
long: 'MMMM do, y',
medium: 'MMM d, y',
short: 'MM/dd/yyyy'
};
var timeFormats = {
full: 'h:mm:ss a zzzz',
long: 'h:mm:ss a z',
medium: 'h:mm:ss a',
short: 'h:mm a'
};
var dateTimeFormats = {
full: "{{date}} 'at' {{time}}",
long: "{{date}} 'at' {{time}}",
medium: '{{date}}, {{time}}',
short: '{{date}}, {{time}}'
};
var formatLong = {
date: buildFormatLongFn({
formats: dateFormats,
defaultWidth: 'full'
}),
time: buildFormatLongFn({
formats: timeFormats,
defaultWidth: 'full'
}),
dateTime: buildFormatLongFn({
formats: dateTimeFormats,
defaultWidth: 'full'
})
};
export default formatLong;
webpack://frontend-mybets/../../node_modules/date-fns/esm/locale/_lib/buildMatchPatternFn/index.js
export default function buildMatchPatternFn(args) {
return function (dirtyString, dirtyOptions) {
var string = String(dirtyString);
var options = dirtyOptions || {};
var matchResult = string.match(args.matchPattern);
if (!matchResult) {
return null;
}
var matchedString = matchResult[0];
var parseResult = string.match(args.parsePattern);
if (!parseResult) {
return null;
}
var value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0];
value = options.valueCallback ? options.valueCallback(value) : value;
return {
value: value,
rest: string.slice(matchedString.length)
};
};
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/locale/en-US/_lib/formatRelative/index.js
var formatRelativeLocale = {
lastWeek: "'last' eeee 'at' p",
yesterday: "'yesterday at' p",
today: "'today at' p",
tomorrow: "'tomorrow at' p",
nextWeek: "eeee 'at' p",
other: 'P'
};
export default function formatRelative(token, _date, _baseDate, _options) {
return formatRelativeLocale[token];
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/locale/_lib/buildLocalizeFn/index.js
export default function buildLocalizeFn(args) {
return function (dirtyIndex, dirtyOptions) {
var options = dirtyOptions || {};
var context = options.context ? String(options.context) : 'standalone';
var valuesArray;
if (context === 'formatting' && args.formattingValues) {
var defaultWidth = args.defaultFormattingWidth || args.defaultWidth;
var width = options.width ? String(options.width) : defaultWidth;
valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth];
} else {
var _defaultWidth = args.defaultWidth;
var _width = options.width ? String(options.width) : args.defaultWidth;
valuesArray = args.values[_width] || args.values[_defaultWidth];
}
var index = args.argumentCallback ? args.argumentCallback(dirtyIndex) : dirtyIndex;
return valuesArray[index];
};
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/locale/_lib/buildMatchFn/index.js
export default function buildMatchFn(args) {
return function (dirtyString, dirtyOptions) {
var string = String(dirtyString);
var options = dirtyOptions || {};
var width = options.width;
var matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth];
var matchResult = string.match(matchPattern);
if (!matchResult) {
return null;
}
var matchedString = matchResult[0];
var parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth];
var value;
if (Object.prototype.toString.call(parsePatterns) === '[object Array]') {
value = findIndex(parsePatterns, function (pattern) {
return pattern.test(matchedString);
});
} else {
value = findKey(parsePatterns, function (pattern) {
return pattern.test(matchedString);
});
}
value = args.valueCallback ? args.valueCallback(value) : value;
value = options.valueCallback ? options.valueCallback(value) : value;
return {
value: value,
rest: string.slice(matchedString.length)
};
};
}
function findKey(object, predicate) {
for (var key in object) {
if (object.hasOwnProperty(key) && predicate(object[key])) {
return key;
}
}
}
function findIndex(array, predicate) {
for (var key = 0; key < array.length; key++) {
if (predicate(array[key])) {
return key;
}
}
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/locale/en-US/index.js
import formatDistance from './_lib/formatDistance/index.js';
import formatLong from './_lib/formatLong/index.js';
import formatRelative from './_lib/formatRelative/index.js';
import localize from './_lib/localize/index.js';
import match from './_lib/match/index.js';
/**
* @type {Locale}
* @category Locales
* @summary English locale (United States).
* @language English
* @iso-639-2 eng
* @author Sasha Koss [@kossnocorp]{@link https://github.com/kossnocorp}
* @author Lesha Koss [@leshakoss]{@link https://github.com/leshakoss}
*/
var locale = {
code: 'en-US',
formatDistance: formatDistance,
formatLong: formatLong,
formatRelative: formatRelative,
localize: localize,
match: match,
options: {
weekStartsOn: 0
/* Sunday */
,
firstWeekContainsDate: 1
}
};
export default locale;
webpack://frontend-mybets/../../node_modules/date-fns/esm/locale/en-US/_lib/localize/index.js
import buildLocalizeFn from '../../../_lib/buildLocalizeFn/index.js';
var eraValues = {
narrow: ['B', 'A'],
abbreviated: ['BC', 'AD'],
wide: ['Before Christ', 'Anno Domini']
};
var quarterValues = {
narrow: ['1', '2', '3', '4'],
abbreviated: ['Q1', 'Q2', 'Q3', 'Q4'],
wide: ['1st quarter', '2nd quarter', '3rd quarter', '4th quarter'] // Note: in English, the names of days of the week and months are capitalized.
// If you are making a new locale based on this one, check if the same is true for the language you're working on.
// Generally, formatted dates should look like they are in the middle of a sentence,
// e.g. in Spanish language the weekdays and months should be in the lowercase.
};
var monthValues = {
narrow: ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
abbreviated: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
wide: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
};
var dayValues = {
narrow: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
short: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
abbreviated: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
wide: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
};
var dayPeriodValues = {
narrow: {
am: 'a',
pm: 'p',
midnight: 'mi',
noon: 'n',
morning: 'morning',
afternoon: 'afternoon',
evening: 'evening',
night: 'night'
},
abbreviated: {
am: 'AM',
pm: 'PM',
midnight: 'midnight',
noon: 'noon',
morning: 'morning',
afternoon: 'afternoon',
evening: 'evening',
night: 'night'
},
wide: {
am: 'a.m.',
pm: 'p.m.',
midnight: 'midnight',
noon: 'noon',
morning: 'morning',
afternoon: 'afternoon',
evening: 'evening',
night: 'night'
}
};
var formattingDayPeriodValues = {
narrow: {
am: 'a',
pm: 'p',
midnight: 'mi',
noon: 'n',
morning: 'in the morning',
afternoon: 'in the afternoon',
evening: 'in the evening',
night: 'at night'
},
abbreviated: {
am: 'AM',
pm: 'PM',
midnight: 'midnight',
noon: 'noon',
morning: 'in the morning',
afternoon: 'in the afternoon',
evening: 'in the evening',
night: 'at night'
},
wide: {
am: 'a.m.',
pm: 'p.m.',
midnight: 'midnight',
noon: 'noon',
morning: 'in the morning',
afternoon: 'in the afternoon',
evening: 'in the evening',
night: 'at night'
}
};
function ordinalNumber(dirtyNumber, _dirtyOptions) {
var number = Number(dirtyNumber); // If ordinal numbers depend on context, for example,
// if they are different for different grammatical genders,
// use `options.unit`:
//
// var options = dirtyOptions || {}
// var unit = String(options.unit)
//
// where `unit` can be 'year', 'quarter', 'month', 'week', 'date', 'dayOfYear',
// 'day', 'hour', 'minute', 'second'
var rem100 = number % 100;
if (rem100 > 20 || rem100 < 10) {
switch (rem100 % 10) {
case 1:
return number + 'st';
case 2:
return number + 'nd';
case 3:
return number + 'rd';
}
}
return number + 'th';
}
var localize = {
ordinalNumber: ordinalNumber,
era: buildLocalizeFn({
values: eraValues,
defaultWidth: 'wide'
}),
quarter: buildLocalizeFn({
values: quarterValues,
defaultWidth: 'wide',
argumentCallback: function (quarter) {
return Number(quarter) - 1;
}
}),
month: buildLocalizeFn({
values: monthValues,
defaultWidth: 'wide'
}),
day: buildLocalizeFn({
values: dayValues,
defaultWidth: 'wide'
}),
dayPeriod: buildLocalizeFn({
values: dayPeriodValues,
defaultWidth: 'wide',
formattingValues: formattingDayPeriodValues,
defaultFormattingWidth: 'wide'
})
};
export default localize;
webpack://frontend-mybets/../../node_modules/date-fns/esm/locale/en-US/_lib/match/index.js
import buildMatchPatternFn from '../../../_lib/buildMatchPatternFn/index.js';
import buildMatchFn from '../../../_lib/buildMatchFn/index.js';
var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i;
var parseOrdinalNumberPattern = /\d+/i;
var matchEraPatterns = {
narrow: /^(b|a)/i,
abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,
wide: /^(before christ|before common era|anno domini|common era)/i
};
var parseEraPatterns = {
any: [/^b/i, /^(a|c)/i]
};
var matchQuarterPatterns = {
narrow: /^[1234]/i,
abbreviated: /^q[1234]/i,
wide: /^[1234](th|st|nd|rd)? quarter/i
};
var parseQuarterPatterns = {
any: [/1/i, /2/i, /3/i, /4/i]
};
var matchMonthPatterns = {
narrow: /^[jfmasond]/i,
abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,
wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i
};
var parseMonthPatterns = {
narrow: [/^j/i, /^f/i, /^m/i, /^a/i, /^m/i, /^j/i, /^j/i, /^a/i, /^s/i, /^o/i, /^n/i, /^d/i],
any: [/^ja/i, /^f/i, /^mar/i, /^ap/i, /^may/i, /^jun/i, /^jul/i, /^au/i, /^s/i, /^o/i, /^n/i, /^d/i]
};
var matchDayPatterns = {
narrow: /^[smtwf]/i,
short: /^(su|mo|tu|we|th|fr|sa)/i,
abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i,
wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i
};
var parseDayPatterns = {
narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i],
any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i]
};
var matchDayPeriodPatterns = {
narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,
any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i
};
var parseDayPeriodPatterns = {
any: {
am: /^a/i,
pm: /^p/i,
midnight: /^mi/i,
noon: /^no/i,
morning: /morning/i,
afternoon: /afternoon/i,
evening: /evening/i,
night: /night/i
}
};
var match = {
ordinalNumber: buildMatchPatternFn({
matchPattern: matchOrdinalNumberPattern,
parsePattern: parseOrdinalNumberPattern,
valueCallback: function (value) {
return parseInt(value, 10);
}
}),
era: buildMatchFn({
matchPatterns: matchEraPatterns,
defaultMatchWidth: 'wide',
parsePatterns: parseEraPatterns,
defaultParseWidth: 'any'
}),
quarter: buildMatchFn({
matchPatterns: matchQuarterPatterns,
defaultMatchWidth: 'wide',
parsePatterns: parseQuarterPatterns,
defaultParseWidth: 'any',
valueCallback: function (index) {
return index + 1;
}
}),
month: buildMatchFn({
matchPatterns: matchMonthPatterns,
defaultMatchWidth: 'wide',
parsePatterns: parseMonthPatterns,
defaultParseWidth: 'any'
}),
day: buildMatchFn({
matchPatterns: matchDayPatterns,
defaultMatchWidth: 'wide',
parsePatterns: parseDayPatterns,
defaultParseWidth: 'any'
}),
dayPeriod: buildMatchFn({
matchPatterns: matchDayPeriodPatterns,
defaultMatchWidth: 'any',
parsePatterns: parseDayPeriodPatterns,
defaultParseWidth: 'any'
})
};
export default match;
webpack://frontend-mybets/../../node_modules/date-fns/esm/_lib/addLeadingZeros/index.js
export default function addLeadingZeros(number, targetLength) {
var sign = number < 0 ? '-' : '';
var output = Math.abs(number).toString();
while (output.length < targetLength) {
output = '0' + output;
}
return sign + output;
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/_lib/format/lightFormatters/index.js
import addLeadingZeros from '../../addLeadingZeros/index.js';
/*
* | | Unit | | Unit |
* |-----|--------------------------------|-----|--------------------------------|
* | a | AM, PM | A* | |
* | d | Day of month | D | |
* | h | Hour [1-12] | H | Hour [0-23] |
* | m | Minute | M | Month |
* | s | Second | S | Fraction of second |
* | y | Year (abs) | Y | |
*
* Letters marked by * are not implemented but reserved by Unicode standard.
*/
var formatters = {
// Year
y: function (date, token) {
// From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_tokens
// | Year | y | yy | yyy | yyyy | yyyyy |
// |----------|-------|----|-------|-------|-------|
// | AD 1 | 1 | 01 | 001 | 0001 | 00001 |
// | AD 12 | 12 | 12 | 012 | 0012 | 00012 |
// | AD 123 | 123 | 23 | 123 | 0123 | 00123 |
// | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 |
// | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 |
var signedYear = date.getUTCFullYear(); // Returns 1 for 1 BC (which is year 0 in JavaScript)
var year = signedYear > 0 ? signedYear : 1 - signedYear;
return addLeadingZeros(token === 'yy' ? year % 100 : year, token.length);
},
// Month
M: function (date, token) {
var month = date.getUTCMonth();
return token === 'M' ? String(month + 1) : addLeadingZeros(month + 1, 2);
},
// Day of the month
d: function (date, token) {
return addLeadingZeros(date.getUTCDate(), token.length);
},
// AM or PM
a: function (date, token) {
var dayPeriodEnumValue = date.getUTCHours() / 12 >= 1 ? 'pm' : 'am';
switch (token) {
case 'a':
case 'aa':
case 'aaa':
return dayPeriodEnumValue.toUpperCase();
case 'aaaaa':
return dayPeriodEnumValue[0];
case 'aaaa':
default:
return dayPeriodEnumValue === 'am' ? 'a.m.' : 'p.m.';
}
},
// Hour [1-12]
h: function (date, token) {
return addLeadingZeros(date.getUTCHours() % 12 || 12, token.length);
},
// Hour [0-23]
H: function (date, token) {
return addLeadingZeros(date.getUTCHours(), token.length);
},
// Minute
m: function (date, token) {
return addLeadingZeros(date.getUTCMinutes(), token.length);
},
// Second
s: function (date, token) {
return addLeadingZeros(date.getUTCSeconds(), token.length);
},
// Fraction of second
S: function (date, token) {
var numberOfDigits = token.length;
var milliseconds = date.getUTCMilliseconds();
var fractionalSeconds = Math.floor(milliseconds * Math.pow(10, numberOfDigits - 3));
return addLeadingZeros(fractionalSeconds, token.length);
}
};
export default formatters;
webpack://frontend-mybets/../../node_modules/date-fns/esm/_lib/startOfUTCISOWeek/index.js
import toDate from '../../toDate/index.js';
import requiredArgs from '../requiredArgs/index.js'; // This function will be a part of public API when UTC function will be implemented.
// See issue: https://github.com/date-fns/date-fns/issues/376
export default function startOfUTCISOWeek(dirtyDate) {
requiredArgs(1, arguments);
var weekStartsOn = 1;
var date = toDate(dirtyDate);
var day = date.getUTCDay();
var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
date.setUTCDate(date.getUTCDate() - diff);
date.setUTCHours(0, 0, 0, 0);
return date;
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/_lib/getUTCISOWeekYear/index.js
import toDate from '../../toDate/index.js';
import startOfUTCISOWeek from '../startOfUTCISOWeek/index.js';
import requiredArgs from '../requiredArgs/index.js'; // This function will be a part of public API when UTC function will be implemented.
// See issue: https://github.com/date-fns/date-fns/issues/376
export default function getUTCISOWeekYear(dirtyDate) {
requiredArgs(1, arguments);
var date = toDate(dirtyDate);
var year = date.getUTCFullYear();
var fourthOfJanuaryOfNextYear = new Date(0);
fourthOfJanuaryOfNextYear.setUTCFullYear(year + 1, 0, 4);
fourthOfJanuaryOfNextYear.setUTCHours(0, 0, 0, 0);
var startOfNextYear = startOfUTCISOWeek(fourthOfJanuaryOfNextYear);
var fourthOfJanuaryOfThisYear = new Date(0);
fourthOfJanuaryOfThisYear.setUTCFullYear(year, 0, 4);
fourthOfJanuaryOfThisYear.setUTCHours(0, 0, 0, 0);
var startOfThisYear = startOfUTCISOWeek(fourthOfJanuaryOfThisYear);
if (date.getTime() >= startOfNextYear.getTime()) {
return year + 1;
} else if (date.getTime() >= startOfThisYear.getTime()) {
return year;
} else {
return year - 1;
}
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/_lib/startOfUTCWeek/index.js
import toInteger from '../toInteger/index.js';
import toDate from '../../toDate/index.js';
import requiredArgs from '../requiredArgs/index.js'; // This function will be a part of public API when UTC function will be implemented.
// See issue: https://github.com/date-fns/date-fns/issues/376
export default function startOfUTCWeek(dirtyDate, dirtyOptions) {
requiredArgs(1, arguments);
var options = dirtyOptions || {};
var locale = options.locale;
var localeWeekStartsOn = locale && locale.options && locale.options.weekStartsOn;
var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : toInteger(localeWeekStartsOn);
var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : toInteger(options.weekStartsOn); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
}
var date = toDate(dirtyDate);
var day = date.getUTCDay();
var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
date.setUTCDate(date.getUTCDate() - diff);
date.setUTCHours(0, 0, 0, 0);
return date;
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/_lib/getUTCWeekYear/index.js
import toInteger from '../toInteger/index.js';
import toDate from '../../toDate/index.js';
import startOfUTCWeek from '../startOfUTCWeek/index.js';
import requiredArgs from '../requiredArgs/index.js'; // This function will be a part of public API when UTC function will be implemented.
// See issue: https://github.com/date-fns/date-fns/issues/376
export default function getUTCWeekYear(dirtyDate, dirtyOptions) {
requiredArgs(1, arguments);
var date = toDate(dirtyDate, dirtyOptions);
var year = date.getUTCFullYear();
var options = dirtyOptions || {};
var locale = options.locale;
var localeFirstWeekContainsDate = locale && locale.options && locale.options.firstWeekContainsDate;
var defaultFirstWeekContainsDate = localeFirstWeekContainsDate == null ? 1 : toInteger(localeFirstWeekContainsDate);
var firstWeekContainsDate = options.firstWeekContainsDate == null ? defaultFirstWeekContainsDate : toInteger(options.firstWeekContainsDate); // Test if weekStartsOn is between 1 and 7 _and_ is not NaN
if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively');
}
var firstWeekOfNextYear = new Date(0);
firstWeekOfNextYear.setUTCFullYear(year + 1, 0, firstWeekContainsDate);
firstWeekOfNextYear.setUTCHours(0, 0, 0, 0);
var startOfNextYear = startOfUTCWeek(firstWeekOfNextYear, dirtyOptions);
var firstWeekOfThisYear = new Date(0);
firstWeekOfThisYear.setUTCFullYear(year, 0, firstWeekContainsDate);
firstWeekOfThisYear.setUTCHours(0, 0, 0, 0);
var startOfThisYear = startOfUTCWeek(firstWeekOfThisYear, dirtyOptions);
if (date.getTime() >= startOfNextYear.getTime()) {
return year + 1;
} else if (date.getTime() >= startOfThisYear.getTime()) {
return year;
} else {
return year - 1;
}
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/_lib/format/formatters/index.js
import lightFormatters from '../lightFormatters/index.js';
import getUTCDayOfYear from '../../../_lib/getUTCDayOfYear/index.js';
import getUTCISOWeek from '../../../_lib/getUTCISOWeek/index.js';
import getUTCISOWeekYear from '../../../_lib/getUTCISOWeekYear/index.js';
import getUTCWeek from '../../../_lib/getUTCWeek/index.js';
import getUTCWeekYear from '../../../_lib/getUTCWeekYear/index.js';
import addLeadingZeros from '../../addLeadingZeros/index.js';
var dayPeriodEnum = {
am: 'am',
pm: 'pm',
midnight: 'midnight',
noon: 'noon',
morning: 'morning',
afternoon: 'afternoon',
evening: 'evening',
night: 'night'
/*
* | | Unit | | Unit |
* |-----|--------------------------------|-----|--------------------------------|
* | a | AM, PM | A* | Milliseconds in day |
* | b | AM, PM, noon, midnight | B | Flexible day period |
* | c | Stand-alone local day of week | C* | Localized hour w/ day period |
* | d | Day of month | D | Day of year |
* | e | Local day of week | E | Day of week |
* | f | | F* | Day of week in month |
* | g* | Modified Julian day | G | Era |
* | h | Hour [1-12] | H | Hour [0-23] |
* | i! | ISO day of week | I! | ISO week of year |
* | j* | Localized hour w/ day period | J* | Localized hour w/o day period |
* | k | Hour [1-24] | K | Hour [0-11] |
* | l* | (deprecated) | L | Stand-alone month |
* | m | Minute | M | Month |
* | n | | N | |
* | o! | Ordinal number modifier | O | Timezone (GMT) |
* | p! | Long localized time | P! | Long localized date |
* | q | Stand-alone quarter | Q | Quarter |
* | r* | Related Gregorian year | R! | ISO week-numbering year |
* | s | Second | S | Fraction of second |
* | t! | Seconds timestamp | T! | Milliseconds timestamp |
* | u | Extended year | U* | Cyclic year |
* | v* | Timezone (generic non-locat.) | V* | Timezone (location) |
* | w | Local week of year | W* | Week of month |
* | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) |
* | y | Year (abs) | Y | Local week-numbering year |
* | z | Timezone (specific non-locat.) | Z* | Timezone (aliases) |
*
* Letters marked by * are not implemented but reserved by Unicode standard.
*
* Letters marked by ! are non-standard, but implemented by date-fns:
* - `o` modifies the previous token to turn it into an ordinal (see `format` docs)
* - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days,
* i.e. 7 for Sunday, 1 for Monday, etc.
* - `I` is ISO week of year, as opposed to `w` which is local week of year.
* - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year.
* `R` is supposed to be used in conjunction with `I` and `i`
* for universal ISO week-numbering date, whereas
* `Y` is supposed to be used in conjunction with `w` and `e`
* for week-numbering date specific to the locale.
* - `P` is long localized date format
* - `p` is long localized time format
*/
};
var formatters = {
// Era
G: function (date, token, localize) {
var era = date.getUTCFullYear() > 0 ? 1 : 0;
switch (token) {
// AD, BC
case 'G':
case 'GG':
case 'GGG':
return localize.era(era, {
width: 'abbreviated'
});
// A, B
case 'GGGGG':
return localize.era(era, {
width: 'narrow'
});
// Anno Domini, Before Christ
case 'GGGG':
default:
return localize.era(era, {
width: 'wide'
});
}
},
// Year
y: function (date, token, localize) {
// Ordinal number
if (token === 'yo') {
var signedYear = date.getUTCFullYear(); // Returns 1 for 1 BC (which is year 0 in JavaScript)
var year = signedYear > 0 ? signedYear : 1 - signedYear;
return localize.ordinalNumber(year, {
unit: 'year'
});
}
return lightFormatters.y(date, token);
},
// Local week-numbering year
Y: function (date, token, localize, options) {
var signedWeekYear = getUTCWeekYear(date, options); // Returns 1 for 1 BC (which is year 0 in JavaScript)
var weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear; // Two digit year
if (token === 'YY') {
var twoDigitYear = weekYear % 100;
return addLeadingZeros(twoDigitYear, 2);
} // Ordinal number
if (token === 'Yo') {
return localize.ordinalNumber(weekYear, {
unit: 'year'
});
} // Padding
return addLeadingZeros(weekYear, token.length);
},
// ISO week-numbering year
R: function (date, token) {
var isoWeekYear = getUTCISOWeekYear(date); // Padding
return addLeadingZeros(isoWeekYear, token.length);
},
// Extended year. This is a single number designating the year of this calendar system.
// The main difference between `y` and `u` localizers are B.C. years:
// | Year | `y` | `u` |
// |------|-----|-----|
// | AC 1 | 1 | 1 |
// | BC 1 | 1 | 0 |
// | BC 2 | 2 | -1 |
// Also `yy` always returns the last two digits of a year,
// while `uu` pads single digit years to 2 characters and returns other years unchanged.
u: function (date, token) {
var year = date.getUTCFullYear();
return addLeadingZeros(year, token.length);
},
// Quarter
Q: function (date, token, localize) {
var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
switch (token) {
// 1, 2, 3, 4
case 'Q':
return String(quarter);
// 01, 02, 03, 04
case 'QQ':
return addLeadingZeros(quarter, 2);
// 1st, 2nd, 3rd, 4th
case 'Qo':
return localize.ordinalNumber(quarter, {
unit: 'quarter'
});
// Q1, Q2, Q3, Q4
case 'QQQ':
return localize.quarter(quarter, {
width: 'abbreviated',
context: 'formatting'
});
// 1, 2, 3, 4 (narrow quarter; could be not numerical)
case 'QQQQQ':
return localize.quarter(quarter, {
width: 'narrow',
context: 'formatting'
});
// 1st quarter, 2nd quarter, ...
case 'QQQQ':
default:
return localize.quarter(quarter, {
width: 'wide',
context: 'formatting'
});
}
},
// Stand-alone quarter
q: function (date, token, localize) {
var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
switch (token) {
// 1, 2, 3, 4
case 'q':
return String(quarter);
// 01, 02, 03, 04
case 'qq':
return addLeadingZeros(quarter, 2);
// 1st, 2nd, 3rd, 4th
case 'qo':
return localize.ordinalNumber(quarter, {
unit: 'quarter'
});
// Q1, Q2, Q3, Q4
case 'qqq':
return localize.quarter(quarter, {
width: 'abbreviated',
context: 'standalone'
});
// 1, 2, 3, 4 (narrow quarter; could be not numerical)
case 'qqqqq':
return localize.quarter(quarter, {
width: 'narrow',
context: 'standalone'
});
// 1st quarter, 2nd quarter, ...
case 'qqqq':
default:
return localize.quarter(quarter, {
width: 'wide',
context: 'standalone'
});
}
},
// Month
M: function (date, token, localize) {
var month = date.getUTCMonth();
switch (token) {
case 'M':
case 'MM':
return lightFormatters.M(date, token);
// 1st, 2nd, ..., 12th
case 'Mo':
return localize.ordinalNumber(month + 1, {
unit: 'month'
});
// Jan, Feb, ..., Dec
case 'MMM':
return localize.month(month, {
width: 'abbreviated',
context: 'formatting'
});
// J, F, ..., D
case 'MMMMM':
return localize.month(month, {
width: 'narrow',
context: 'formatting'
});
// January, February, ..., December
case 'MMMM':
default:
return localize.month(month, {
width: 'wide',
context: 'formatting'
});
}
},
// Stand-alone month
L: function (date, token, localize) {
var month = date.getUTCMonth();
switch (token) {
// 1, 2, ..., 12
case 'L':
return String(month + 1);
// 01, 02, ..., 12
case 'LL':
return addLeadingZeros(month + 1, 2);
// 1st, 2nd, ..., 12th
case 'Lo':
return localize.ordinalNumber(month + 1, {
unit: 'month'
});
// Jan, Feb, ..., Dec
case 'LLL':
return localize.month(month, {
width: 'abbreviated',
context: 'standalone'
});
// J, F, ..., D
case 'LLLLL':
return localize.month(month, {
width: 'narrow',
context: 'standalone'
});
// January, February, ..., December
case 'LLLL':
default:
return localize.month(month, {
width: 'wide',
context: 'standalone'
});
}
},
// Local week of year
w: function (date, token, localize, options) {
var week = getUTCWeek(date, options);
if (token === 'wo') {
return localize.ordinalNumber(week, {
unit: 'week'
});
}
return addLeadingZeros(week, token.length);
},
// ISO week of year
I: function (date, token, localize) {
var isoWeek = getUTCISOWeek(date);
if (token === 'Io') {
return localize.ordinalNumber(isoWeek, {
unit: 'week'
});
}
return addLeadingZeros(isoWeek, token.length);
},
// Day of the month
d: function (date, token, localize) {
if (token === 'do') {
return localize.ordinalNumber(date.getUTCDate(), {
unit: 'date'
});
}
return lightFormatters.d(date, token);
},
// Day of year
D: function (date, token, localize) {
var dayOfYear = getUTCDayOfYear(date);
if (token === 'Do') {
return localize.ordinalNumber(dayOfYear, {
unit: 'dayOfYear'
});
}
return addLeadingZeros(dayOfYear, token.length);
},
// Day of week
E: function (date, token, localize) {
var dayOfWeek = date.getUTCDay();
switch (token) {
// Tue
case 'E':
case 'EE':
case 'EEE':
return localize.day(dayOfWeek, {
width: 'abbreviated',
context: 'formatting'
});
// T
case 'EEEEE':
return localize.day(dayOfWeek, {
width: 'narrow',
context: 'formatting'
});
// Tu
case 'EEEEEE':
return localize.day(dayOfWeek, {
width: 'short',
context: 'formatting'
});
// Tuesday
case 'EEEE':
default:
return localize.day(dayOfWeek, {
width: 'wide',
context: 'formatting'
});
}
},
// Local day of week
e: function (date, token, localize, options) {
var dayOfWeek = date.getUTCDay();
var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
switch (token) {
// Numerical value (Nth day of week with current locale or weekStartsOn)
case 'e':
return String(localDayOfWeek);
// Padded numerical value
case 'ee':
return addLeadingZeros(localDayOfWeek, 2);
// 1st, 2nd, ..., 7th
case 'eo':
return localize.ordinalNumber(localDayOfWeek, {
unit: 'day'
});
case 'eee':
return localize.day(dayOfWeek, {
width: 'abbreviated',
context: 'formatting'
});
// T
case 'eeeee':
return localize.day(dayOfWeek, {
width: 'narrow',
context: 'formatting'
});
// Tu
case 'eeeeee':
return localize.day(dayOfWeek, {
width: 'short',
context: 'formatting'
});
// Tuesday
case 'eeee':
default:
return localize.day(dayOfWeek, {
width: 'wide',
context: 'formatting'
});
}
},
// Stand-alone local day of week
c: function (date, token, localize, options) {
var dayOfWeek = date.getUTCDay();
var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
switch (token) {
// Numerical value (same as in `e`)
case 'c':
return String(localDayOfWeek);
// Padded numerical value
case 'cc':
return addLeadingZeros(localDayOfWeek, token.length);
// 1st, 2nd, ..., 7th
case 'co':
return localize.ordinalNumber(localDayOfWeek, {
unit: 'day'
});
case 'ccc':
return localize.day(dayOfWeek, {
width: 'abbreviated',
context: 'standalone'
});
// T
case 'ccccc':
return localize.day(dayOfWeek, {
width: 'narrow',
context: 'standalone'
});
// Tu
case 'cccccc':
return localize.day(dayOfWeek, {
width: 'short',
context: 'standalone'
});
// Tuesday
case 'cccc':
default:
return localize.day(dayOfWeek, {
width: 'wide',
context: 'standalone'
});
}
},
// ISO day of week
i: function (date, token, localize) {
var dayOfWeek = date.getUTCDay();
var isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek;
switch (token) {
// 2
case 'i':
return String(isoDayOfWeek);
// 02
case 'ii':
return addLeadingZeros(isoDayOfWeek, token.length);
// 2nd
case 'io':
return localize.ordinalNumber(isoDayOfWeek, {
unit: 'day'
});
// Tue
case 'iii':
return localize.day(dayOfWeek, {
width: 'abbreviated',
context: 'formatting'
});
// T
case 'iiiii':
return localize.day(dayOfWeek, {
width: 'narrow',
context: 'formatting'
});
// Tu
case 'iiiiii':
return localize.day(dayOfWeek, {
width: 'short',
context: 'formatting'
});
// Tuesday
case 'iiii':
default:
return localize.day(dayOfWeek, {
width: 'wide',
context: 'formatting'
});
}
},
// AM or PM
a: function (date, token, localize) {
var hours = date.getUTCHours();
var dayPeriodEnumValue = hours / 12 >= 1 ? 'pm' : 'am';
switch (token) {
case 'a':
case 'aa':
case 'aaa':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'abbreviated',
context: 'formatting'
});
case 'aaaaa':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'narrow',
context: 'formatting'
});
case 'aaaa':
default:
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'wide',
context: 'formatting'
});
}
},
// AM, PM, midnight, noon
b: function (date, token, localize) {
var hours = date.getUTCHours();
var dayPeriodEnumValue;
if (hours === 12) {
dayPeriodEnumValue = dayPeriodEnum.noon;
} else if (hours === 0) {
dayPeriodEnumValue = dayPeriodEnum.midnight;
} else {
dayPeriodEnumValue = hours / 12 >= 1 ? 'pm' : 'am';
}
switch (token) {
case 'b':
case 'bb':
case 'bbb':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'abbreviated',
context: 'formatting'
});
case 'bbbbb':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'narrow',
context: 'formatting'
});
case 'bbbb':
default:
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'wide',
context: 'formatting'
});
}
},
// in the morning, in the afternoon, in the evening, at night
B: function (date, token, localize) {
var hours = date.getUTCHours();
var dayPeriodEnumValue;
if (hours >= 17) {
dayPeriodEnumValue = dayPeriodEnum.evening;
} else if (hours >= 12) {
dayPeriodEnumValue = dayPeriodEnum.afternoon;
} else if (hours >= 4) {
dayPeriodEnumValue = dayPeriodEnum.morning;
} else {
dayPeriodEnumValue = dayPeriodEnum.night;
}
switch (token) {
case 'B':
case 'BB':
case 'BBB':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'abbreviated',
context: 'formatting'
});
case 'BBBBB':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'narrow',
context: 'formatting'
});
case 'BBBB':
default:
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'wide',
context: 'formatting'
});
}
},
// Hour [1-12]
h: function (date, token, localize) {
if (token === 'ho') {
var hours = date.getUTCHours() % 12;
if (hours === 0) hours = 12;
return localize.ordinalNumber(hours, {
unit: 'hour'
});
}
return lightFormatters.h(date, token);
},
// Hour [0-23]
H: function (date, token, localize) {
if (token === 'Ho') {
return localize.ordinalNumber(date.getUTCHours(), {
unit: 'hour'
});
}
return lightFormatters.H(date, token);
},
// Hour [0-11]
K: function (date, token, localize) {
var hours = date.getUTCHours() % 12;
if (token === 'Ko') {
return localize.ordinalNumber(hours, {
unit: 'hour'
});
}
return addLeadingZeros(hours, token.length);
},
// Hour [1-24]
k: function (date, token, localize) {
var hours = date.getUTCHours();
if (hours === 0) hours = 24;
if (token === 'ko') {
return localize.ordinalNumber(hours, {
unit: 'hour'
});
}
return addLeadingZeros(hours, token.length);
},
// Minute
m: function (date, token, localize) {
if (token === 'mo') {
return localize.ordinalNumber(date.getUTCMinutes(), {
unit: 'minute'
});
}
return lightFormatters.m(date, token);
},
// Second
s: function (date, token, localize) {
if (token === 'so') {
return localize.ordinalNumber(date.getUTCSeconds(), {
unit: 'second'
});
}
return lightFormatters.s(date, token);
},
// Fraction of second
S: function (date, token) {
return lightFormatters.S(date, token);
},
// Timezone (ISO-8601. If offset is 0, output is always `'Z'`)
X: function (date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timezoneOffset = originalDate.getTimezoneOffset();
if (timezoneOffset === 0) {
return 'Z';
}
switch (token) {
// Hours and optional minutes
case 'X':
return formatTimezoneWithOptionalMinutes(timezoneOffset);
// Hours, minutes and optional seconds without `:` delimiter
// Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
// so this token always has the same output as `XX`
case 'XXXX':
case 'XX':
// Hours and minutes without `:` delimiter
return formatTimezone(timezoneOffset);
// Hours, minutes and optional seconds with `:` delimiter
// Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
// so this token always has the same output as `XXX`
case 'XXXXX':
case 'XXX': // Hours and minutes with `:` delimiter
default:
return formatTimezone(timezoneOffset, ':');
}
},
// Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent)
x: function (date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timezoneOffset = originalDate.getTimezoneOffset();
switch (token) {
// Hours and optional minutes
case 'x':
return formatTimezoneWithOptionalMinutes(timezoneOffset);
// Hours, minutes and optional seconds without `:` delimiter
// Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
// so this token always has the same output as `xx`
case 'xxxx':
case 'xx':
// Hours and minutes without `:` delimiter
return formatTimezone(timezoneOffset);
// Hours, minutes and optional seconds with `:` delimiter
// Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
// so this token always has the same output as `xxx`
case 'xxxxx':
case 'xxx': // Hours and minutes with `:` delimiter
default:
return formatTimezone(timezoneOffset, ':');
}
},
// Timezone (GMT)
O: function (date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timezoneOffset = originalDate.getTimezoneOffset();
switch (token) {
// Short
case 'O':
case 'OO':
case 'OOO':
return 'GMT' + formatTimezoneShort(timezoneOffset, ':');
// Long
case 'OOOO':
default:
return 'GMT' + formatTimezone(timezoneOffset, ':');
}
},
// Timezone (specific non-location)
z: function (date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timezoneOffset = originalDate.getTimezoneOffset();
switch (token) {
// Short
case 'z':
case 'zz':
case 'zzz':
return 'GMT' + formatTimezoneShort(timezoneOffset, ':');
// Long
case 'zzzz':
default:
return 'GMT' + formatTimezone(timezoneOffset, ':');
}
},
// Seconds timestamp
t: function (date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timestamp = Math.floor(originalDate.getTime() / 1000);
return addLeadingZeros(timestamp, token.length);
},
// Milliseconds timestamp
T: function (date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timestamp = originalDate.getTime();
return addLeadingZeros(timestamp, token.length);
}
};
function formatTimezoneShort(offset, dirtyDelimiter) {
var sign = offset > 0 ? '-' : '+';
var absOffset = Math.abs(offset);
var hours = Math.floor(absOffset / 60);
var minutes = absOffset % 60;
if (minutes === 0) {
return sign + String(hours);
}
var delimiter = dirtyDelimiter || '';
return sign + String(hours) + delimiter + addLeadingZeros(minutes, 2);
}
function formatTimezoneWithOptionalMinutes(offset, dirtyDelimiter) {
if (offset % 60 === 0) {
var sign = offset > 0 ? '-' : '+';
return sign + addLeadingZeros(Math.abs(offset) / 60, 2);
}
return formatTimezone(offset, dirtyDelimiter);
}
function formatTimezone(offset, dirtyDelimiter) {
var delimiter = dirtyDelimiter || '';
var sign = offset > 0 ? '-' : '+';
var absOffset = Math.abs(offset);
var hours = addLeadingZeros(Math.floor(absOffset / 60), 2);
var minutes = addLeadingZeros(absOffset % 60, 2);
return sign + hours + delimiter + minutes;
}
export default formatters;
webpack://frontend-mybets/../../node_modules/date-fns/esm/_lib/getUTCWeek/index.js
import toDate from '../../toDate/index.js';
import startOfUTCWeek from '../startOfUTCWeek/index.js';
import startOfUTCWeekYear from '../startOfUTCWeekYear/index.js';
import requiredArgs from '../requiredArgs/index.js';
var MILLISECONDS_IN_WEEK = 604800000; // This function will be a part of public API when UTC function will be implemented.
// See issue: https://github.com/date-fns/date-fns/issues/376
export default function getUTCWeek(dirtyDate, options) {
requiredArgs(1, arguments);
var date = toDate(dirtyDate);
var diff = startOfUTCWeek(date, options).getTime() - startOfUTCWeekYear(date, options).getTime(); // Round the number of days to the nearest integer
// because the number of milliseconds in a week is not constant
// (e.g. it's different in the week of the daylight saving time clock shift)
return Math.round(diff / MILLISECONDS_IN_WEEK) + 1;
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/_lib/startOfUTCWeekYear/index.js
import toInteger from '../toInteger/index.js';
import getUTCWeekYear from '../getUTCWeekYear/index.js';
import startOfUTCWeek from '../startOfUTCWeek/index.js';
import requiredArgs from '../requiredArgs/index.js'; // This function will be a part of public API when UTC function will be implemented.
// See issue: https://github.com/date-fns/date-fns/issues/376
export default function startOfUTCWeekYear(dirtyDate, dirtyOptions) {
requiredArgs(1, arguments);
var options = dirtyOptions || {};
var locale = options.locale;
var localeFirstWeekContainsDate = locale && locale.options && locale.options.firstWeekContainsDate;
var defaultFirstWeekContainsDate = localeFirstWeekContainsDate == null ? 1 : toInteger(localeFirstWeekContainsDate);
var firstWeekContainsDate = options.firstWeekContainsDate == null ? defaultFirstWeekContainsDate : toInteger(options.firstWeekContainsDate);
var year = getUTCWeekYear(dirtyDate, dirtyOptions);
var firstWeek = new Date(0);
firstWeek.setUTCFullYear(year, 0, firstWeekContainsDate);
firstWeek.setUTCHours(0, 0, 0, 0);
var date = startOfUTCWeek(firstWeek, dirtyOptions);
return date;
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/_lib/getUTCISOWeek/index.js
import toDate from '../../toDate/index.js';
import startOfUTCISOWeek from '../startOfUTCISOWeek/index.js';
import startOfUTCISOWeekYear from '../startOfUTCISOWeekYear/index.js';
import requiredArgs from '../requiredArgs/index.js';
var MILLISECONDS_IN_WEEK = 604800000; // This function will be a part of public API when UTC function will be implemented.
// See issue: https://github.com/date-fns/date-fns/issues/376
export default function getUTCISOWeek(dirtyDate) {
requiredArgs(1, arguments);
var date = toDate(dirtyDate);
var diff = startOfUTCISOWeek(date).getTime() - startOfUTCISOWeekYear(date).getTime(); // Round the number of days to the nearest integer
// because the number of milliseconds in a week is not constant
// (e.g. it's different in the week of the daylight saving time clock shift)
return Math.round(diff / MILLISECONDS_IN_WEEK) + 1;
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/_lib/startOfUTCISOWeekYear/index.js
import getUTCISOWeekYear from '../getUTCISOWeekYear/index.js';
import startOfUTCISOWeek from '../startOfUTCISOWeek/index.js';
import requiredArgs from '../requiredArgs/index.js'; // This function will be a part of public API when UTC function will be implemented.
// See issue: https://github.com/date-fns/date-fns/issues/376
export default function startOfUTCISOWeekYear(dirtyDate) {
requiredArgs(1, arguments);
var year = getUTCISOWeekYear(dirtyDate);
var fourthOfJanuary = new Date(0);
fourthOfJanuary.setUTCFullYear(year, 0, 4);
fourthOfJanuary.setUTCHours(0, 0, 0, 0);
var date = startOfUTCISOWeek(fourthOfJanuary);
return date;
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/_lib/getUTCDayOfYear/index.js
import toDate from '../../toDate/index.js';
import requiredArgs from '../requiredArgs/index.js';
var MILLISECONDS_IN_DAY = 86400000; // This function will be a part of public API when UTC function will be implemented.
// See issue: https://github.com/date-fns/date-fns/issues/376
export default function getUTCDayOfYear(dirtyDate) {
requiredArgs(1, arguments);
var date = toDate(dirtyDate);
var timestamp = date.getTime();
date.setUTCMonth(0, 1);
date.setUTCHours(0, 0, 0, 0);
var startOfYearTimestamp = date.getTime();
var difference = timestamp - startOfYearTimestamp;
return Math.floor(difference / MILLISECONDS_IN_DAY) + 1;
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/_lib/format/longFormatters/index.js
function dateLongFormatter(pattern, formatLong) {
switch (pattern) {
case 'P':
return formatLong.date({
width: 'short'
});
case 'PP':
return formatLong.date({
width: 'medium'
});
case 'PPP':
return formatLong.date({
width: 'long'
});
case 'PPPP':
default:
return formatLong.date({
width: 'full'
});
}
}
function timeLongFormatter(pattern, formatLong) {
switch (pattern) {
case 'p':
return formatLong.time({
width: 'short'
});
case 'pp':
return formatLong.time({
width: 'medium'
});
case 'ppp':
return formatLong.time({
width: 'long'
});
case 'pppp':
default:
return formatLong.time({
width: 'full'
});
}
}
function dateTimeLongFormatter(pattern, formatLong) {
var matchResult = pattern.match(/(P+)(p+)?/);
var datePattern = matchResult[1];
var timePattern = matchResult[2];
if (!timePattern) {
return dateLongFormatter(pattern, formatLong);
}
var dateTimeFormat;
switch (datePattern) {
case 'P':
dateTimeFormat = formatLong.dateTime({
width: 'short'
});
break;
case 'PP':
dateTimeFormat = formatLong.dateTime({
width: 'medium'
});
break;
case 'PPP':
dateTimeFormat = formatLong.dateTime({
width: 'long'
});
break;
case 'PPPP':
default:
dateTimeFormat = formatLong.dateTime({
width: 'full'
});
break;
}
return dateTimeFormat.replace('{{date}}', dateLongFormatter(datePattern, formatLong)).replace('{{time}}', timeLongFormatter(timePattern, formatLong));
}
var longFormatters = {
p: timeLongFormatter,
P: dateTimeLongFormatter
};
export default longFormatters;
webpack://frontend-mybets/../../node_modules/date-fns/esm/_lib/protectedTokens/index.js
var protectedDayOfYearTokens = ['D', 'DD'];
var protectedWeekYearTokens = ['YY', 'YYYY'];
export function isProtectedDayOfYearToken(token) {
return protectedDayOfYearTokens.indexOf(token) !== -1;
}
export function isProtectedWeekYearToken(token) {
return protectedWeekYearTokens.indexOf(token) !== -1;
}
export function throwProtectedError(token, format, input) {
if (token === 'YYYY') {
throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(format, "`) for formatting years to the input `").concat(input, "`; see: https://git.io/fxCyr"));
} else if (token === 'YY') {
throw new RangeError("Use `yy` instead of `YY` (in `".concat(format, "`) for formatting years to the input `").concat(input, "`; see: https://git.io/fxCyr"));
} else if (token === 'D') {
throw new RangeError("Use `d` instead of `D` (in `".concat(format, "`) for formatting days of the month to the input `").concat(input, "`; see: https://git.io/fxCyr"));
} else if (token === 'DD') {
throw new RangeError("Use `dd` instead of `DD` (in `".concat(format, "`) for formatting days of the month to the input `").concat(input, "`; see: https://git.io/fxCyr"));
}
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/format/index.js
import isValid from '../isValid/index.js';
import defaultLocale from '../locale/en-US/index.js';
import subMilliseconds from '../subMilliseconds/index.js';
import toDate from '../toDate/index.js';
import formatters from '../_lib/format/formatters/index.js';
import longFormatters from '../_lib/format/longFormatters/index.js';
import getTimezoneOffsetInMilliseconds from '../_lib/getTimezoneOffsetInMilliseconds/index.js';
import { isProtectedDayOfYearToken, isProtectedWeekYearToken, throwProtectedError } from '../_lib/protectedTokens/index.js';
import toInteger from '../_lib/toInteger/index.js';
import requiredArgs from '../_lib/requiredArgs/index.js'; // This RegExp consists of three parts separated by `|`:
// - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token
// (one of the certain letters followed by `o`)
// - (\w)\1* matches any sequences of the same letter
// - '' matches two quote characters in a row
// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),
// except a single quote symbol, which ends the sequence.
// Two quote characters do not end the sequence.
// If there is no matching single quote
// then the sequence will continue until the end of the string.
// - . matches any single character unmatched by previous parts of the RegExps
var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g; // This RegExp catches symbols escaped by quotes, and also
// sequences of symbols P, p, and the combinations like `PPPPPPPppppp`
var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;
var escapedStringRegExp = /^'([^]*?)'?$/;
var doubleQuoteRegExp = /''/g;
var unescapedLatinCharacterRegExp = /[a-zA-Z]/;
/**
* @name format
* @category Common Helpers
* @summary Format the date.
*
* @description
* Return the formatted date string in the given format. The result may vary by locale.
*
* > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries.
* > See: https://git.io/fxCyr
*
* The characters wrapped between two single quotes characters (') are escaped.
* Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.
* (see the last example)
*
* Format of the string is based on Unicode Technical Standard #35:
* https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
* with a few additions (see note 7 below the table).
*
* Accepted patterns:
* | Unit | Pattern | Result examples | Notes |
* |---------------------------------|---------|-----------------------------------|-------|
* | Era | G..GGG | AD, BC | |
* | | GGGG | Anno Domini, Before Christ | 2 |
* | | GGGGG | A, B | |
* | Calendar year | y | 44, 1, 1900, 2017 | 5 |
* | | yo | 44th, 1st, 0th, 17th | 5,7 |
* | | yy | 44, 01, 00, 17 | 5 |
* | | yyy | 044, 001, 1900, 2017 | 5 |
* | | yyyy | 0044, 0001, 1900, 2017 | 5 |
* | | yyyyy | ... | 3,5 |
* | Local week-numbering year | Y | 44, 1, 1900, 2017 | 5 |
* | | Yo | 44th, 1st, 1900th, 2017th | 5,7 |
* | | YY | 44, 01, 00, 17 | 5,8 |
* | | YYY | 044, 001, 1900, 2017 | 5 |
* | | YYYY | 0044, 0001, 1900, 2017 | 5,8 |
* | | YYYYY | ... | 3,5 |
* | ISO week-numbering year | R | -43, 0, 1, 1900, 2017 | 5,7 |
* | | RR | -43, 00, 01, 1900, 2017 | 5,7 |
* | | RRR | -043, 000, 001, 1900, 2017 | 5,7 |
* | | RRRR | -0043, 0000, 0001, 1900, 2017 | 5,7 |
* | | RRRRR | ... | 3,5,7 |
* | Extended year | u | -43, 0, 1, 1900, 2017 | 5 |
* | | uu | -43, 01, 1900, 2017 | 5 |
* | | uuu | -043, 001, 1900, 2017 | 5 |
* | | uuuu | -0043, 0001, 1900, 2017 | 5 |
* | | uuuuu | ... | 3,5 |
* | Quarter (formatting) | Q | 1, 2, 3, 4 | |
* | | Qo | 1st, 2nd, 3rd, 4th | 7 |
* | | QQ | 01, 02, 03, 04 | |
* | | QQQ | Q1, Q2, Q3, Q4 | |
* | | QQQQ | 1st quarter, 2nd quarter, ... | 2 |
* | | QQQQQ | 1, 2, 3, 4 | 4 |
* | Quarter (stand-alone) | q | 1, 2, 3, 4 | |
* | | qo | 1st, 2nd, 3rd, 4th | 7 |
* | | qq | 01, 02, 03, 04 | |
* | | qqq | Q1, Q2, Q3, Q4 | |
* | | qqqq | 1st quarter, 2nd quarter, ... | 2 |
* | | qqqqq | 1, 2, 3, 4 | 4 |
* | Month (formatting) | M | 1, 2, ..., 12 | |
* | | Mo | 1st, 2nd, ..., 12th | 7 |
* | | MM | 01, 02, ..., 12 | |
* | | MMM | Jan, Feb, ..., Dec | |
* | | MMMM | January, February, ..., December | 2 |
* | | MMMMM | J, F, ..., D | |
* | Month (stand-alone) | L | 1, 2, ..., 12 | |
* | | Lo | 1st, 2nd, ..., 12th | 7 |
* | | LL | 01, 02, ..., 12 | |
* | | LLL | Jan, Feb, ..., Dec | |
* | | LLLL | January, February, ..., December | 2 |
* | | LLLLL | J, F, ..., D | |
* | Local week of year | w | 1, 2, ..., 53 | |
* | | wo | 1st, 2nd, ..., 53th | 7 |
* | | ww | 01, 02, ..., 53 | |
* | ISO week of year | I | 1, 2, ..., 53 | 7 |
* | | Io | 1st, 2nd, ..., 53th | 7 |
* | | II | 01, 02, ..., 53 | 7 |
* | Day of month | d | 1, 2, ..., 31 | |
* | | do | 1st, 2nd, ..., 31st | 7 |
* | | dd | 01, 02, ..., 31 | |
* | Day of year | D | 1, 2, ..., 365, 366 | 9 |
* | | Do | 1st, 2nd, ..., 365th, 366th | 7 |
* | | DD | 01, 02, ..., 365, 366 | 9 |
* | | DDD | 001, 002, ..., 365, 366 | |
* | | DDDD | ... | 3 |
* | Day of week (formatting) | E..EEE | Mon, Tue, Wed, ..., Sun | |
* | | EEEE | Monday, Tuesday, ..., Sunday | 2 |
* | | EEEEE | M, T, W, T, F, S, S | |
* | | EEEEEE | Mo, Tu, We, Th, Fr, Su, Sa | |
* | ISO day of week (formatting) | i | 1, 2, 3, ..., 7 | 7 |
* | | io | 1st, 2nd, ..., 7th | 7 |
* | | ii | 01, 02, ..., 07 | 7 |
* | | iii | Mon, Tue, Wed, ..., Sun | 7 |
* | | iiii | Monday, Tuesday, ..., Sunday | 2,7 |
* | | iiiii | M, T, W, T, F, S, S | 7 |
* | | iiiiii | Mo, Tu, We, Th, Fr, Su, Sa | 7 |
* | Local day of week (formatting) | e | 2, 3, 4, ..., 1 | |
* | | eo | 2nd, 3rd, ..., 1st | 7 |
* | | ee | 02, 03, ..., 01 | |
* | | eee | Mon, Tue, Wed, ..., Sun | |
* | | eeee | Monday, Tuesday, ..., Sunday | 2 |
* | | eeeee | M, T, W, T, F, S, S | |
* | | eeeeee | Mo, Tu, We, Th, Fr, Su, Sa | |
* | Local day of week (stand-alone) | c | 2, 3, 4, ..., 1 | |
* | | co | 2nd, 3rd, ..., 1st | 7 |
* | | cc | 02, 03, ..., 01 | |
* | | ccc | Mon, Tue, Wed, ..., Sun | |
* | | cccc | Monday, Tuesday, ..., Sunday | 2 |
* | | ccccc | M, T, W, T, F, S, S | |
* | | cccccc | Mo, Tu, We, Th, Fr, Su, Sa | |
* | AM, PM | a..aaa | AM, PM | |
* | | aaaa | a.m., p.m. | 2 |
* | | aaaaa | a, p | |
* | AM, PM, noon, midnight | b..bbb | AM, PM, noon, midnight | |
* | | bbbb | a.m., p.m., noon, midnight | 2 |
* | | bbbbb | a, p, n, mi | |
* | Flexible day period | B..BBB | at night, in the morning, ... | |
* | | BBBB | at night, in the morning, ... | 2 |
* | | BBBBB | at night, in the morning, ... | |
* | Hour [1-12] | h | 1, 2, ..., 11, 12 | |
* | | ho | 1st, 2nd, ..., 11th, 12th | 7 |
* | | hh | 01, 02, ..., 11, 12 | |
* | Hour [0-23] | H | 0, 1, 2, ..., 23 | |
* | | Ho | 0th, 1st, 2nd, ..., 23rd | 7 |
* | | HH | 00, 01, 02, ..., 23 | |
* | Hour [0-11] | K | 1, 2, ..., 11, 0 | |
* | | Ko | 1st, 2nd, ..., 11th, 0th | 7 |
* | | KK | 01, 02, ..., 11, 00 | |
* | Hour [1-24] | k | 24, 1, 2, ..., 23 | |
* | | ko | 24th, 1st, 2nd, ..., 23rd | 7 |
* | | kk | 24, 01, 02, ..., 23 | |
* | Minute | m | 0, 1, ..., 59 | |
* | | mo | 0th, 1st, ..., 59th | 7 |
* | | mm | 00, 01, ..., 59 | |
* | Second | s | 0, 1, ..., 59 | |
* | | so | 0th, 1st, ..., 59th | 7 |
* | | ss | 00, 01, ..., 59 | |
* | Fraction of second | S | 0, 1, ..., 9 | |
* | | SS | 00, 01, ..., 99 | |
* | | SSS | 000, 0001, ..., 999 | |
* | | SSSS | ... | 3 |
* | Timezone (ISO-8601 w/ Z) | X | -08, +0530, Z | |
* | | XX | -0800, +0530, Z | |
* | | XXX | -08:00, +05:30, Z | |
* | | XXXX | -0800, +0530, Z, +123456 | 2 |
* | | XXXXX | -08:00, +05:30, Z, +12:34:56 | |
* | Timezone (ISO-8601 w/o Z) | x | -08, +0530, +00 | |
* | | xx | -0800, +0530, +0000 | |
* | | xxx | -08:00, +05:30, +00:00 | 2 |
* | | xxxx | -0800, +0530, +0000, +123456 | |
* | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | |
* | Timezone (GMT) | O...OOO | GMT-8, GMT+5:30, GMT+0 | |
* | | OOOO | GMT-08:00, GMT+05:30, GMT+00:00 | 2 |
* | Timezone (specific non-locat.) | z...zzz | GMT-8, GMT+5:30, GMT+0 | 6 |
* | | zzzz | GMT-08:00, GMT+05:30, GMT+00:00 | 2,6 |
* | Seconds timestamp | t | 512969520 | 7 |
* | | tt | ... | 3,7 |
* | Milliseconds timestamp | T | 512969520900 | 7 |
* | | TT | ... | 3,7 |
* | Long localized date | P | 05/29/1453 | 7 |
* | | PP | May 29, 1453 | 7 |
* | | PPP | May 29th, 1453 | 7 |
* | | PPPP | Sunday, May 29th, 1453 | 2,7 |
* | Long localized time | p | 12:00 AM | 7 |
* | | pp | 12:00:00 AM | 7 |
* | | ppp | 12:00:00 AM GMT+2 | 7 |
* | | pppp | 12:00:00 AM GMT+02:00 | 2,7 |
* | Combination of date and time | Pp | 05/29/1453, 12:00 AM | 7 |
* | | PPpp | May 29, 1453, 12:00:00 AM | 7 |
* | | PPPppp | May 29th, 1453 at ... | 7 |
* | | PPPPpppp| Sunday, May 29th, 1453 at ... | 2,7 |
* Notes:
* 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale
* are the same as "stand-alone" units, but are different in some languages.
* "Formatting" units are declined according to the rules of the language
* in the context of a date. "Stand-alone" units are always nominative singular:
*
* `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`
*
* `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`
*
* 2. Any sequence of the identical letters is a pattern, unless it is escaped by
* the single quote characters (see below).
* If the sequence is longer than listed in table (e.g. `EEEEEEEEEEE`)
* the output will be the same as default pattern for this unit, usually
* the longest one (in case of ISO weekdays, `EEEE`). Default patterns for units
* are marked with "2" in the last column of the table.
*
* `format(new Date(2017, 10, 6), 'MMM') //=> 'Nov'`
*
* `format(new Date(2017, 10, 6), 'MMMM') //=> 'November'`
*
* `format(new Date(2017, 10, 6), 'MMMMM') //=> 'N'`
*
* `format(new Date(2017, 10, 6), 'MMMMMM') //=> 'November'`
*
* `format(new Date(2017, 10, 6), 'MMMMMMM') //=> 'November'`
*
* 3. Some patterns could be unlimited length (such as `yyyyyyyy`).
* The output will be padded with zeros to match the length of the pattern.
*
* `format(new Date(2017, 10, 6), 'yyyyyyyy') //=> '00002017'`
*
* 4. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.
* These tokens represent the shortest form of the quarter.
*
* 5. The main difference between `y` and `u` patterns are B.C. years:
*
* | Year | `y` | `u` |
* |------|-----|-----|
* | AC 1 | 1 | 1 |
* | BC 1 | 1 | 0 |
* | BC 2 | 2 | -1 |
*
* Also `yy` always returns the last two digits of a year,
* while `uu` pads single digit years to 2 characters and returns other years unchanged:
*
* | Year | `yy` | `uu` |
* |------|------|------|
* | 1 | 01 | 01 |
* | 14 | 14 | 14 |
* | 376 | 76 | 376 |
* | 1453 | 53 | 1453 |
*
* The same difference is true for local and ISO week-numbering years (`Y` and `R`),
* except local week-numbering years are dependent on `options.weekStartsOn`
* and `options.firstWeekContainsDate` (compare [getISOWeekYear]{@link https://date-fns.org/docs/getISOWeekYear}
* and [getWeekYear]{@link https://date-fns.org/docs/getWeekYear}).
*
* 6. Specific non-location timezones are currently unavailable in `date-fns`,
* so right now these tokens fall back to GMT timezones.
*
* 7. These patterns are not in the Unicode Technical Standard #35:
* - `i`: ISO day of week
* - `I`: ISO week of year
* - `R`: ISO week-numbering year
* - `t`: seconds timestamp
* - `T`: milliseconds timestamp
* - `o`: ordinal number modifier
* - `P`: long localized date
* - `p`: long localized time
*
* 8. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years.
* You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://git.io/fxCyr
*
* 9. `D` and `DD` tokens represent days of the year but they are ofthen confused with days of the month.
* You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://git.io/fxCyr
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* - The second argument is now required for the sake of explicitness.
*
* ```javascript
* // Before v2.0.0
* format(new Date(2016, 0, 1))
*
* // v2.0.0 onward
* format(new Date(2016, 0, 1), "yyyy-MM-dd'T'HH:mm:ss.SSSxxx")
* ```
*
* - New format string API for `format` function
* which is based on [Unicode Technical Standard #35](https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table).
* See [this post](https://blog.date-fns.org/post/unicode-tokens-in-date-fns-v2-sreatyki91jg) for more details.
*
* - Characters are now escaped using single quote symbols (`'`) instead of square brackets.
*
* @param {Date|Number} date - the original date
* @param {String} format - the string of tokens
* @param {Object} [options] - an object with options.
* @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @param {Number} [options.firstWeekContainsDate=1] - the day of January, which is
* @param {Boolean} [options.useAdditionalWeekYearTokens=false] - if true, allows usage of the week-numbering year tokens `YY` and `YYYY`;
* see: https://git.io/fxCyr
* @param {Boolean} [options.useAdditionalDayOfYearTokens=false] - if true, allows usage of the day of year tokens `D` and `DD`;
* see: https://git.io/fxCyr
* @returns {String} the formatted date string
* @throws {TypeError} 2 arguments required
* @throws {RangeError} `date` must not be Invalid Date
* @throws {RangeError} `options.locale` must contain `localize` property
* @throws {RangeError} `options.locale` must contain `formatLong` property
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
* @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7
* @throws {RangeError} use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://git.io/fxCyr
* @throws {RangeError} use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://git.io/fxCyr
* @throws {RangeError} use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://git.io/fxCyr
* @throws {RangeError} use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://git.io/fxCyr
* @throws {RangeError} format string contains an unescaped latin alphabet character
*
* @example
* // Represent 11 February 2014 in middle-endian format:
* var result = format(new Date(2014, 1, 11), 'MM/dd/yyyy')
* //=> '02/11/2014'
*
* @example
* // Represent 2 July 2014 in Esperanto:
* import { eoLocale } from 'date-fns/locale/eo'
* var result = format(new Date(2014, 6, 2), "do 'de' MMMM yyyy", {
* locale: eoLocale
* })
* //=> '2-a de julio 2014'
*
* @example
* // Escape string by single quote characters:
* var result = format(new Date(2014, 6, 2, 15), "h 'o''clock'")
* //=> "3 o'clock"
*/
export default function format(dirtyDate, dirtyFormatStr, dirtyOptions) {
requiredArgs(2, arguments);
var formatStr = String(dirtyFormatStr);
var options = dirtyOptions || {};
var locale = options.locale || defaultLocale;
var localeFirstWeekContainsDate = locale.options && locale.options.firstWeekContainsDate;
var defaultFirstWeekContainsDate = localeFirstWeekContainsDate == null ? 1 : toInteger(localeFirstWeekContainsDate);
var firstWeekContainsDate = options.firstWeekContainsDate == null ? defaultFirstWeekContainsDate : toInteger(options.firstWeekContainsDate); // Test if weekStartsOn is between 1 and 7 _and_ is not NaN
if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively');
}
var localeWeekStartsOn = locale.options && locale.options.weekStartsOn;
var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : toInteger(localeWeekStartsOn);
var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : toInteger(options.weekStartsOn); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
}
if (!locale.localize) {
throw new RangeError('locale must contain localize property');
}
if (!locale.formatLong) {
throw new RangeError('locale must contain formatLong property');
}
var originalDate = toDate(dirtyDate);
if (!isValid(originalDate)) {
throw new RangeError('Invalid time value');
} // Convert the date in system timezone to the same date in UTC+00:00 timezone.
// This ensures that when UTC functions will be implemented, locales will be compatible with them.
// See an issue about UTC functions: https://github.com/date-fns/date-fns/issues/376
var timezoneOffset = getTimezoneOffsetInMilliseconds(originalDate);
var utcDate = subMilliseconds(originalDate, timezoneOffset);
var formatterOptions = {
firstWeekContainsDate: firstWeekContainsDate,
weekStartsOn: weekStartsOn,
locale: locale,
_originalDate: originalDate
};
var result = formatStr.match(longFormattingTokensRegExp).map(function (substring) {
var firstCharacter = substring[0];
if (firstCharacter === 'p' || firstCharacter === 'P') {
var longFormatter = longFormatters[firstCharacter];
return longFormatter(substring, locale.formatLong, formatterOptions);
}
return substring;
}).join('').match(formattingTokensRegExp).map(function (substring) {
// Replace two single quote characters with one single quote character
if (substring === "''") {
return "'";
}
var firstCharacter = substring[0];
if (firstCharacter === "'") {
return cleanEscapedString(substring);
}
var formatter = formatters[firstCharacter];
if (formatter) {
if (!options.useAdditionalWeekYearTokens && isProtectedWeekYearToken(substring)) {
throwProtectedError(substring, dirtyFormatStr, dirtyDate);
}
if (!options.useAdditionalDayOfYearTokens && isProtectedDayOfYearToken(substring)) {
throwProtectedError(substring, dirtyFormatStr, dirtyDate);
}
return formatter(utcDate, substring, locale.localize, formatterOptions);
}
if (firstCharacter.match(unescapedLatinCharacterRegExp)) {
throw new RangeError('Format string contains an unescaped latin alphabet character `' + firstCharacter + '`');
}
return substring;
}).join('');
return result;
}
function cleanEscapedString(input) {
return input.match(escapedStringRegExp)[1].replace(doubleQuoteRegExp, "'");
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/isValid/index.js
import toDate from '../toDate/index.js';
import requiredArgs from '../_lib/requiredArgs/index.js';
/**
* @name isValid
* @category Common Helpers
* @summary Is the given date valid?
*
* @description
* Returns false if argument is Invalid Date and true otherwise.
* Argument is converted to Date using `toDate`. See [toDate]{@link https://date-fns.org/docs/toDate}
* Invalid Date is a Date, whose time value is NaN.
*
* Time value of Date: http://es5.github.io/#x15.9.1.1
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* - Now `isValid` doesn't throw an exception
* if the first argument is not an instance of Date.
* Instead, argument is converted beforehand using `toDate`.
*
* Examples:
*
* | `isValid` argument | Before v2.0.0 | v2.0.0 onward |
* |---------------------------|---------------|---------------|
* | `new Date()` | `true` | `true` |
* | `new Date('2016-01-01')` | `true` | `true` |
* | `new Date('')` | `false` | `false` |
* | `new Date(1488370835081)` | `true` | `true` |
* | `new Date(NaN)` | `false` | `false` |
* | `'2016-01-01'` | `TypeError` | `false` |
* | `''` | `TypeError` | `false` |
* | `1488370835081` | `TypeError` | `true` |
* | `NaN` | `TypeError` | `false` |
*
* We introduce this change to make *date-fns* consistent with ECMAScript behavior
* that try to coerce arguments to the expected type
* (which is also the case with other *date-fns* functions).
*
* @param {*} date - the date to check
* @returns {Boolean} the date is valid
* @throws {TypeError} 1 argument required
*
* @example
* // For the valid date:
* var result = isValid(new Date(2014, 1, 31))
* //=> true
*
* @example
* // For the value, convertable into a date:
* var result = isValid(1393804800000)
* //=> true
*
* @example
* // For the invalid date:
* var result = isValid(new Date(''))
* //=> false
*/
export default function isValid(dirtyDate) {
requiredArgs(1, arguments);
var date = toDate(dirtyDate);
return !isNaN(date);
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/subMilliseconds/index.js
import toInteger from '../_lib/toInteger/index.js';
import addMilliseconds from '../addMilliseconds/index.js';
import requiredArgs from '../_lib/requiredArgs/index.js';
/**
* @name subMilliseconds
* @category Millisecond Helpers
* @summary Subtract the specified number of milliseconds from the given date.
*
* @description
* Subtract the specified number of milliseconds from the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of milliseconds to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} the new date with the milliseconds subtracted
* @throws {TypeError} 2 arguments required
*
* @example
* // Subtract 750 milliseconds from 10 July 2014 12:45:30.000:
* var result = subMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750)
* //=> Thu Jul 10 2014 12:45:29.250
*/
export default function subMilliseconds(dirtyDate, dirtyAmount) {
requiredArgs(2, arguments);
var amount = toInteger(dirtyAmount);
return addMilliseconds(dirtyDate, -amount);
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/isAfter/index.js
import toDate from '../toDate/index.js';
import requiredArgs from '../_lib/requiredArgs/index.js';
/**
* @name isAfter
* @category Common Helpers
* @summary Is the first date after the second one?
*
* @description
* Is the first date after the second one?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date that should be after the other one to return true
* @param {Date|Number} dateToCompare - the date to compare with
* @returns {Boolean} the first date is after the second date
* @throws {TypeError} 2 arguments required
*
* @example
* // Is 10 July 1989 after 11 February 1987?
* var result = isAfter(new Date(1989, 6, 10), new Date(1987, 1, 11))
* //=> true
*/
export default function isAfter(dirtyDate, dirtyDateToCompare) {
requiredArgs(2, arguments);
var date = toDate(dirtyDate);
var dateToCompare = toDate(dirtyDateToCompare);
return date.getTime() > dateToCompare.getTime();
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/parseISO/index.js
import toInteger from '../_lib/toInteger/index.js';
import requiredArgs from '../_lib/requiredArgs/index.js';
var MILLISECONDS_IN_HOUR = 3600000;
var MILLISECONDS_IN_MINUTE = 60000;
var DEFAULT_ADDITIONAL_DIGITS = 2;
var patterns = {
dateTimeDelimiter: /[T ]/,
timeZoneDelimiter: /[Z ]/i,
timezone: /([Z+-].*)$/
};
var dateRegex = /^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/;
var timeRegex = /^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/;
var timezoneRegex = /^([+-])(\d{2})(?::?(\d{2}))?$/;
/**
* @name parseISO
* @category Common Helpers
* @summary Parse ISO string
*
* @description
* Parse the given string in ISO 8601 format and return an instance of Date.
*
* Function accepts complete ISO 8601 formats as well as partial implementations.
* ISO 8601: http://en.wikipedia.org/wiki/ISO_8601
*
* If the argument isn't a string, the function cannot parse the string or
* the values are invalid, it returns Invalid Date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* - The previous `parse` implementation was renamed to `parseISO`.
*
* ```javascript
* // Before v2.0.0
* parse('2016-01-01')
*
* // v2.0.0 onward
* parseISO('2016-01-01')
* ```
*
* - `parseISO` now validates separate date and time values in ISO-8601 strings
* and returns `Invalid Date` if the date is invalid.
*
* ```javascript
* parseISO('2018-13-32')
* //=> Invalid Date
* ```
*
* - `parseISO` now doesn't fall back to `new Date` constructor
* if it fails to parse a string argument. Instead, it returns `Invalid Date`.
*
* @param {String} argument - the value to convert
* @param {Object} [options] - an object with options.
* @param {0|1|2} [options.additionalDigits=2] - the additional number of digits in the extended year format
* @returns {Date} the parsed date in the local time zone
* @throws {TypeError} 1 argument required
* @throws {RangeError} `options.additionalDigits` must be 0, 1 or 2
*
* @example
* // Convert string '2014-02-11T11:30:30' to date:
* var result = parseISO('2014-02-11T11:30:30')
* //=> Tue Feb 11 2014 11:30:30
*
* @example
* // Convert string '+02014101' to date,
* // if the additional number of digits in the extended year format is 1:
* var result = parseISO('+02014101', { additionalDigits: 1 })
* //=> Fri Apr 11 2014 00:00:00
*/
export default function parseISO(argument, dirtyOptions) {
requiredArgs(1, arguments);
var options = dirtyOptions || {};
var additionalDigits = options.additionalDigits == null ? DEFAULT_ADDITIONAL_DIGITS : toInteger(options.additionalDigits);
if (additionalDigits !== 2 && additionalDigits !== 1 && additionalDigits !== 0) {
throw new RangeError('additionalDigits must be 0, 1 or 2');
}
if (!(typeof argument === 'string' || Object.prototype.toString.call(argument) === '[object String]')) {
return new Date(NaN);
}
var dateStrings = splitDateString(argument);
var date;
if (dateStrings.date) {
var parseYearResult = parseYear(dateStrings.date, additionalDigits);
date = parseDate(parseYearResult.restDateString, parseYearResult.year);
}
if (isNaN(date) || !date) {
return new Date(NaN);
}
var timestamp = date.getTime();
var time = 0;
var offset;
if (dateStrings.time) {
time = parseTime(dateStrings.time);
if (isNaN(time) || time === null) {
return new Date(NaN);
}
}
if (dateStrings.timezone) {
offset = parseTimezone(dateStrings.timezone);
if (isNaN(offset)) {
return new Date(NaN);
}
} else {
var dirtyDate = new Date(timestamp + time); // js parsed string assuming it's in UTC timezone
// but we need it to be parsed in our timezone
// so we use utc values to build date in our timezone.
// Year values from 0 to 99 map to the years 1900 to 1999
// so set year explicitly with setFullYear.
var result = new Date(dirtyDate.getUTCFullYear(), dirtyDate.getUTCMonth(), dirtyDate.getUTCDate(), dirtyDate.getUTCHours(), dirtyDate.getUTCMinutes(), dirtyDate.getUTCSeconds(), dirtyDate.getUTCMilliseconds());
result.setFullYear(dirtyDate.getUTCFullYear());
return result;
}
return new Date(timestamp + time + offset);
}
function splitDateString(dateString) {
var dateStrings = {};
var array = dateString.split(patterns.dateTimeDelimiter);
var timeString; // The regex match should only return at maximum two array elements.
// [date], [time], or [date, time].
if (array.length > 2) {
return dateStrings;
}
if (/:/.test(array[0])) {
dateStrings.date = null;
timeString = array[0];
} else {
dateStrings.date = array[0];
timeString = array[1];
if (patterns.timeZoneDelimiter.test(dateStrings.date)) {
dateStrings.date = dateString.split(patterns.timeZoneDelimiter)[0];
timeString = dateString.substr(dateStrings.date.length, dateString.length);
}
}
if (timeString) {
var token = patterns.timezone.exec(timeString);
if (token) {
dateStrings.time = timeString.replace(token[1], '');
dateStrings.timezone = token[1];
} else {
dateStrings.time = timeString;
}
}
return dateStrings;
}
function parseYear(dateString, additionalDigits) {
var regex = new RegExp('^(?:(\\d{4}|[+-]\\d{' + (4 + additionalDigits) + '})|(\\d{2}|[+-]\\d{' + (2 + additionalDigits) + '})$)');
var captures = dateString.match(regex); // Invalid ISO-formatted year
if (!captures) return {
year: null
};
var year = captures[1] && parseInt(captures[1]);
var century = captures[2] && parseInt(captures[2]);
return {
year: century == null ? year : century * 100,
restDateString: dateString.slice((captures[1] || captures[2]).length)
};
}
function parseDate(dateString, year) {
// Invalid ISO-formatted year
if (year === null) return null;
var captures = dateString.match(dateRegex); // Invalid ISO-formatted string
if (!captures) return null;
var isWeekDate = !!captures[4];
var dayOfYear = parseDateUnit(captures[1]);
var month = parseDateUnit(captures[2]) - 1;
var day = parseDateUnit(captures[3]);
var week = parseDateUnit(captures[4]);
var dayOfWeek = parseDateUnit(captures[5]) - 1;
if (isWeekDate) {
if (!validateWeekDate(year, week, dayOfWeek)) {
return new Date(NaN);
}
return dayOfISOWeekYear(year, week, dayOfWeek);
} else {
var date = new Date(0);
if (!validateDate(year, month, day) || !validateDayOfYearDate(year, dayOfYear)) {
return new Date(NaN);
}
date.setUTCFullYear(year, month, Math.max(dayOfYear, day));
return date;
}
}
function parseDateUnit(value) {
return value ? parseInt(value) : 1;
}
function parseTime(timeString) {
var captures = timeString.match(timeRegex);
if (!captures) return null; // Invalid ISO-formatted time
var hours = parseTimeUnit(captures[1]);
var minutes = parseTimeUnit(captures[2]);
var seconds = parseTimeUnit(captures[3]);
if (!validateTime(hours, minutes, seconds)) {
return NaN;
}
return hours * MILLISECONDS_IN_HOUR + minutes * MILLISECONDS_IN_MINUTE + seconds * 1000;
}
function parseTimeUnit(value) {
return value && parseFloat(value.replace(',', '.')) || 0;
}
function parseTimezone(timezoneString) {
if (timezoneString === 'Z') return 0;
var captures = timezoneString.match(timezoneRegex);
if (!captures) return 0;
var sign = captures[1] === '+' ? -1 : 1;
var hours = parseInt(captures[2]);
var minutes = captures[3] && parseInt(captures[3]) || 0;
if (!validateTimezone(hours, minutes)) {
return NaN;
}
return sign * (hours * MILLISECONDS_IN_HOUR + minutes * MILLISECONDS_IN_MINUTE);
}
function dayOfISOWeekYear(isoWeekYear, week, day) {
var date = new Date(0);
date.setUTCFullYear(isoWeekYear, 0, 4);
var fourthOfJanuaryDay = date.getUTCDay() || 7;
var diff = (week - 1) * 7 + day + 1 - fourthOfJanuaryDay;
date.setUTCDate(date.getUTCDate() + diff);
return date;
} // Validation functions
// February is null to handle the leap year (using ||)
var daysInMonths = [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
function isLeapYearIndex(year) {
return year % 400 === 0 || year % 4 === 0 && year % 100;
}
function validateDate(year, month, date) {
return month >= 0 && month <= 11 && date >= 1 && date <= (daysInMonths[month] || (isLeapYearIndex(year) ? 29 : 28));
}
function validateDayOfYearDate(year, dayOfYear) {
return dayOfYear >= 1 && dayOfYear <= (isLeapYearIndex(year) ? 366 : 365);
}
function validateWeekDate(_year, week, day) {
return week >= 1 && week <= 53 && day >= 0 && day <= 6;
}
function validateTime(hours, minutes, seconds) {
if (hours === 24) {
return minutes === 0 && seconds === 0;
}
return seconds >= 0 && seconds < 60 && minutes >= 0 && minutes < 60 && hours >= 0 && hours < 25;
}
function validateTimezone(_hours, minutes) {
return minutes >= 0 && minutes <= 59;
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/toDate/index.js
import requiredArgs from '../_lib/requiredArgs/index.js';
/**
* @name toDate
* @category Common Helpers
* @summary Convert the given argument to an instance of Date.
*
* @description
* Convert the given argument to an instance of Date.
*
* If the argument is an instance of Date, the function returns its clone.
*
* If the argument is a number, it is treated as a timestamp.
*
* If the argument is none of the above, the function returns Invalid Date.
*
* **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`.
*
* @param {Date|Number} argument - the value to convert
* @returns {Date} the parsed date in the local time zone
* @throws {TypeError} 1 argument required
*
* @example
* // Clone the date:
* const result = toDate(new Date(2014, 1, 11, 11, 30, 30))
* //=> Tue Feb 11 2014 11:30:30
*
* @example
* // Convert the timestamp to date:
* const result = toDate(1392098430000)
* //=> Tue Feb 11 2014 11:30:30
*/
export default function toDate(argument) {
requiredArgs(1, arguments);
var argStr = Object.prototype.toString.call(argument); // Clone the date
if (argument instanceof Date || typeof argument === 'object' && argStr === '[object Date]') {
// Prevent the date to lose the milliseconds when passed to new Date() in IE10
return new Date(argument.getTime());
} else if (typeof argument === 'number' || argStr === '[object Number]') {
return new Date(argument);
} else {
if ((typeof argument === 'string' || argStr === '[object String]') && typeof console !== 'undefined') {
// eslint-disable-next-line no-console
console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as arguments. Please use `parseISO` to parse strings. See: https://git.io/fjule"); // eslint-disable-next-line no-console
console.warn(new Error().stack);
}
return new Date(NaN);
}
}
webpack://frontend-mybets/../../node_modules/decode-uri-component/index.js
'use strict';
var token = '%[a-f0-9]{2}';
var singleMatcher = new RegExp('(' + token + ')|([^%]+?)', 'gi');
var multiMatcher = new RegExp('(' + token + ')+', 'gi');
function decodeComponents(components, split) {
try {
// Try to decode the entire string first
return [decodeURIComponent(components.join(''))];
} catch (err) {
// Do nothing
}
if (components.length === 1) {
return components;
}
split = split || 1;
// Split the array in 2 parts
var left = components.slice(0, split);
var right = components.slice(split);
return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right));
}
function decode(input) {
try {
return decodeURIComponent(input);
} catch (err) {
var tokens = input.match(singleMatcher) || [];
for (var i = 1; i < tokens.length; i++) {
input = decodeComponents(tokens, i).join('');
tokens = input.match(singleMatcher) || [];
}
return input;
}
}
function customDecodeURIComponent(input) {
// Keep track of all the replacements and prefill the map with the `BOM`
var replaceMap = {
'%FE%FF': '\uFFFD\uFFFD',
'%FF%FE': '\uFFFD\uFFFD'
};
var match = multiMatcher.exec(input);
while (match) {
try {
// Decode as big chunks as possible
replaceMap[match[0]] = decodeURIComponent(match[0]);
} catch (err) {
var result = decode(match[0]);
if (result !== match[0]) {
replaceMap[match[0]] = result;
}
}
match = multiMatcher.exec(input);
}
// Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else
replaceMap['%C2'] = '\uFFFD';
var entries = Object.keys(replaceMap);
for (var i = 0; i < entries.length; i++) {
// Replace all decoded components
var key = entries[i];
input = input.replace(new RegExp(key, 'g'), replaceMap[key]);
}
return input;
}
module.exports = function (encodedURI) {
if (typeof encodedURI !== 'string') {
throw new TypeError('Expected `encodedURI` to be of type `string`, got `' + typeof encodedURI + '`');
}
try {
encodedURI = encodedURI.replace(/\+/g, ' ');
// Try the built in decoder first
return decodeURIComponent(encodedURI);
} catch (err) {
// Fallback to a more advanced decoder
return customDecodeURIComponent(encodedURI);
}
};
webpack://frontend-mybets/../../node_modules/fast-json-stable-stringify/index.js
'use strict';
module.exports = function (data, opts) {
if (!opts) opts = {};
if (typeof opts === 'function') opts = { cmp: opts };
var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false;
var cmp = opts.cmp && (function (f) {
return function (node) {
return function (a, b) {
var aobj = { key: a, value: node[a] };
var bobj = { key: b, value: node[b] };
return f(aobj, bobj);
};
};
})(opts.cmp);
var seen = [];
return (function stringify (node) {
if (node && node.toJSON && typeof node.toJSON === 'function') {
node = node.toJSON();
}
if (node === undefined) return;
if (typeof node == 'number') return isFinite(node) ? '' + node : 'null';
if (typeof node !== 'object') return JSON.stringify(node);
var i, out;
if (Array.isArray(node)) {
out = '[';
for (i = 0; i < node.length; i++) {
if (i) out += ',';
out += stringify(node[i]) || 'null';
}
return out + ']';
}
if (node === null) return 'null';
if (seen.indexOf(node) !== -1) {
if (cycles) return JSON.stringify('__cycle__');
throw new TypeError('Converting circular structure to JSON');
}
var seenIndex = seen.push(node) - 1;
var keys = Object.keys(node).sort(cmp && cmp(node));
out = '';
for (i = 0; i < keys.length; i++) {
var key = keys[i];
var value = stringify(node[key]);
if (!value) continue;
if (out) out += ',';
out += JSON.stringify(key) + ':' + value;
}
seen.splice(seenIndex, 1);
return '{' + out + '}';
})(data);
};
webpack://frontend-mybets/../../node_modules/fbjs/lib/emptyFunction.js
"use strict";
/**
* 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;
};
module.exports = emptyFunction;
webpack://frontend-mybets/../../node_modules/fbjs/lib/invariant.js
/**
* 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.
*
*
*/
'use strict';
var validateFormat = process.env.NODE_ENV !== "production" ? function (format) {
if (format === undefined) {
throw new Error('invariant(...): Second argument must be a string.');
}
} : function (format) {};
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments to provide
* information about what broke and what you were expecting.
*
* The invariant message will be stripped in production, but the invariant will
* remain to ensure logic does not differ in production.
*/
function invariant(condition, format) {
for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
validateFormat(format);
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return String(args[argIndex++]);
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // Skip invariant's own stack frame.
throw error;
}
}
module.exports = invariant;
webpack://frontend-mybets/../../node_modules/fbjs/lib/warning.js
/**
* Copyright (c) 2014-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.
*
*/
'use strict';
var emptyFunction = require("./emptyFunction");
/**
* 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.
*/
function printWarning(format) {
for (var _len = arguments.length, args = new 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.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) {}
}
var warning = process.env.NODE_ENV !== "production" ? function (condition, format) {
if (format === undefined) {
throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (!condition) {
for (var _len2 = arguments.length, args = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
printWarning.apply(void 0, [format].concat(args));
}
} : emptyFunction;
module.exports = warning;
webpack://frontend-mybets/../../node_modules/filter-obj/index.js
'use strict';
module.exports = function (obj, predicate) {
var ret = {};
var keys = Object.keys(obj);
var isArr = Array.isArray(predicate);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var val = obj[key];
if (isArr ? predicate.indexOf(key) !== -1 : predicate(key, val, obj)) {
ret[key] = val;
}
}
return ret;
};
webpack://frontend-mybets/../../node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js
'use strict';
var reactIs = require('react-is');
/**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var REACT_STATICS = {
childContextTypes: true,
contextType: true,
contextTypes: true,
defaultProps: true,
displayName: true,
getDefaultProps: true,
getDerivedStateFromError: true,
getDerivedStateFromProps: true,
mixins: true,
propTypes: true,
type: true
};
var KNOWN_STATICS = {
name: true,
length: true,
prototype: true,
caller: true,
callee: true,
arguments: true,
arity: true
};
var FORWARD_REF_STATICS = {
'$$typeof': true,
render: true,
defaultProps: true,
displayName: true,
propTypes: true
};
var MEMO_STATICS = {
'$$typeof': true,
compare: true,
defaultProps: true,
displayName: true,
propTypes: true,
type: true
};
var TYPE_STATICS = {};
TYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS;
TYPE_STATICS[reactIs.Memo] = MEMO_STATICS;
function getStatics(component) {
// React v16.11 and below
if (reactIs.isMemo(component)) {
return MEMO_STATICS;
} // React v16.12 and above
return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;
}
var defineProperty = Object.defineProperty;
var getOwnPropertyNames = Object.getOwnPropertyNames;
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var getPrototypeOf = Object.getPrototypeOf;
var objectPrototype = Object.prototype;
function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {
if (typeof sourceComponent !== 'string') {
// don't hoist over string (html) components
if (objectPrototype) {
var inheritedComponent = getPrototypeOf(sourceComponent);
if (inheritedComponent && inheritedComponent !== objectPrototype) {
hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);
}
}
var keys = getOwnPropertyNames(sourceComponent);
if (getOwnPropertySymbols) {
keys = keys.concat(getOwnPropertySymbols(sourceComponent));
}
var targetStatics = getStatics(targetComponent);
var sourceStatics = getStatics(sourceComponent);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {
var descriptor = getOwnPropertyDescriptor(sourceComponent, key);
try {
// Avoid failures from read-only properties
defineProperty(targetComponent, key, descriptor);
} catch (e) {}
}
}
}
return targetComponent;
}
module.exports = hoistNonReactStatics;
webpack://frontend-mybets/../../node_modules/hoist-non-react-statics/node_modules/react-is/cjs/react-is.production.min.js
/** @license React v16.13.1
* react-is.production.min.js
*
* 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.
*/
'use strict';var b="function"===typeof Symbol&&Symbol.for,c=b?Symbol.for("react.element"):60103,d=b?Symbol.for("react.portal"):60106,e=b?Symbol.for("react.fragment"):60107,f=b?Symbol.for("react.strict_mode"):60108,g=b?Symbol.for("react.profiler"):60114,h=b?Symbol.for("react.provider"):60109,k=b?Symbol.for("react.context"):60110,l=b?Symbol.for("react.async_mode"):60111,m=b?Symbol.for("react.concurrent_mode"):60111,n=b?Symbol.for("react.forward_ref"):60112,p=b?Symbol.for("react.suspense"):60113,q=b?
Symbol.for("react.suspense_list"):60120,r=b?Symbol.for("react.memo"):60115,t=b?Symbol.for("react.lazy"):60116,v=b?Symbol.for("react.block"):60121,w=b?Symbol.for("react.fundamental"):60117,x=b?Symbol.for("react.responder"):60118,y=b?Symbol.for("react.scope"):60119;
function z(a){if("object"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case t:case r:case h:return a;default:return u}}case d:return u}}}function A(a){return z(a)===m}exports.AsyncMode=l;exports.ConcurrentMode=m;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=n;exports.Fragment=e;exports.Lazy=t;exports.Memo=r;exports.Portal=d;
exports.Profiler=g;exports.StrictMode=f;exports.Suspense=p;exports.isAsyncMode=function(a){return A(a)||z(a)===l};exports.isConcurrentMode=A;exports.isContextConsumer=function(a){return z(a)===k};exports.isContextProvider=function(a){return z(a)===h};exports.isElement=function(a){return"object"===typeof a&&null!==a&&a.$$typeof===c};exports.isForwardRef=function(a){return z(a)===n};exports.isFragment=function(a){return z(a)===e};exports.isLazy=function(a){return z(a)===t};
exports.isMemo=function(a){return z(a)===r};exports.isPortal=function(a){return z(a)===d};exports.isProfiler=function(a){return z(a)===g};exports.isStrictMode=function(a){return z(a)===f};exports.isSuspense=function(a){return z(a)===p};
exports.isValidElementType=function(a){return"string"===typeof a||"function"===typeof a||a===e||a===m||a===g||a===f||a===p||a===q||"object"===typeof a&&null!==a&&(a.$$typeof===t||a.$$typeof===r||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n||a.$$typeof===w||a.$$typeof===x||a.$$typeof===y||a.$$typeof===v)};exports.typeOf=z;
webpack://frontend-mybets/../../node_modules/hoist-non-react-statics/node_modules/react-is/index.js
'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/react-is.production.min.js');
} else {
module.exports = require('./cjs/react-is.development.js');
}
webpack://frontend-mybets/../../node_modules/hyphenate-style-name/index.js
/* eslint-disable no-var, prefer-template */
var uppercasePattern = /[A-Z]/g
var msPattern = /^ms-/
var cache = {}
function toHyphenLower(match) {
return '-' + match.toLowerCase()
}
function hyphenateStyleName(name) {
if (cache.hasOwnProperty(name)) {
return cache[name]
}
var hName = name.replace(uppercasePattern, toHyphenLower)
return (cache[name] = msPattern.test(hName) ? '-' + hName : hName)
}
export default hyphenateStyleName
webpack://frontend-mybets/../../node_modules/inline-style-prefixer/lib/createPrefixer.js
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = createPrefixer;
var _prefixProperty = require('./utils/prefixProperty');
var _prefixProperty2 = _interopRequireDefault(_prefixProperty);
var _prefixValue = require('./utils/prefixValue');
var _prefixValue2 = _interopRequireDefault(_prefixValue);
var _addNewValuesOnly = require('./utils/addNewValuesOnly');
var _addNewValuesOnly2 = _interopRequireDefault(_addNewValuesOnly);
var _isObject = require('./utils/isObject');
var _isObject2 = _interopRequireDefault(_isObject);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function createPrefixer(_ref) {
var prefixMap = _ref.prefixMap,
plugins = _ref.plugins;
return function prefix(style) {
for (var property in style) {
var value = style[property];
// handle nested objects
if ((0, _isObject2.default)(value)) {
style[property] = prefix(value);
// handle array values
} else if (Array.isArray(value)) {
var combinedValue = [];
for (var i = 0, len = value.length; i < len; ++i) {
var processedValue = (0, _prefixValue2.default)(plugins, property, value[i], style, prefixMap);
(0, _addNewValuesOnly2.default)(combinedValue, processedValue || value[i]);
}
// only modify the value if it was touched
// by any plugin to prevent unnecessary mutations
if (combinedValue.length > 0) {
style[property] = combinedValue;
}
} else {
var _processedValue = (0, _prefixValue2.default)(plugins, property, value, style, prefixMap);
// only modify the value if it was touched
// by any plugin to prevent unnecessary mutations
if (_processedValue) {
style[property] = _processedValue;
}
style = (0, _prefixProperty2.default)(prefixMap, property, style);
}
}
return style;
};
}
webpack://frontend-mybets/../../node_modules/inline-style-prefixer/lib/plugins/backgroundClip.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = backgroundClip;
function backgroundClip() {
return null;
}
webpack://frontend-mybets/../../node_modules/inline-style-prefixer/lib/plugins/crossFade.js
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = crossFade;
var _cssInJsUtils = require('css-in-js-utils');
var CROSS_FADE_REGEX = /cross-fade\(/g;
// http://caniuse.com/#search=cross-fade
var prefixes = ['-webkit-', ''];
function crossFade(property, value) {
if (typeof value === 'string' && !(0, _cssInJsUtils.isPrefixedValue)(value) && value.indexOf('cross-fade(') !== -1) {
return prefixes.map(function (prefix) {
return value.replace(CROSS_FADE_REGEX, prefix + 'cross-fade(');
});
}
}
webpack://frontend-mybets/../../node_modules/inline-style-prefixer/lib/plugins/cursor.js
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = cursor;
var prefixes = ['-webkit-', '-moz-', ''];
var values = {
'zoom-in': true,
'zoom-out': true,
grab: true,
grabbing: true
};
function cursor(property, value) {
if (property === 'cursor' && values.hasOwnProperty(value)) {
return prefixes.map(function (prefix) {
return prefix + value;
});
}
}
webpack://frontend-mybets/../../node_modules/inline-style-prefixer/lib/plugins/filter.js
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = filter;
var _cssInJsUtils = require('css-in-js-utils');
var FILTER_REGEX = /filter\(/g;
// http://caniuse.com/#feat=css-filter-function
var prefixes = ['-webkit-', ''];
function filter(property, value) {
if (typeof value === 'string' && !(0, _cssInJsUtils.isPrefixedValue)(value) && value.indexOf('filter(') !== -1) {
return prefixes.map(function (prefix) {
return value.replace(FILTER_REGEX, prefix + 'filter(');
});
}
}
webpack://frontend-mybets/../../node_modules/inline-style-prefixer/lib/plugins/imageSet.js
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = imageSet;
var _isPrefixedValue = require('css-in-js-utils/lib/isPrefixedValue');
var _isPrefixedValue2 = _interopRequireDefault(_isPrefixedValue);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// http://caniuse.com/#feat=css-image-set
var prefixes = ['-webkit-', ''];
function imageSet(property, value) {
if (typeof value === 'string' && !(0, _isPrefixedValue2.default)(value) && value.indexOf('image-set(') > -1) {
return prefixes.map(function (prefix) {
return value.replace(/image-set\(/g, prefix + 'image-set(');
});
}
}
webpack://frontend-mybets/../../node_modules/inline-style-prefixer/lib/plugins/logical.js
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = logical;
var alternativeProps = {
marginBlockStart: ['WebkitMarginBefore'],
marginBlockEnd: ['WebkitMarginAfter'],
marginInlineStart: ['WebkitMarginStart', 'MozMarginStart'],
marginInlineEnd: ['WebkitMarginEnd', 'MozMarginEnd'],
paddingBlockStart: ['WebkitPaddingBefore'],
paddingBlockEnd: ['WebkitPaddingAfter'],
paddingInlineStart: ['WebkitPaddingStart', 'MozPaddingStart'],
paddingInlineEnd: ['WebkitPaddingEnd', 'MozPaddingEnd'],
borderBlockStart: ['WebkitBorderBefore'],
borderBlockStartColor: ['WebkitBorderBeforeColor'],
borderBlockStartStyle: ['WebkitBorderBeforeStyle'],
borderBlockStartWidth: ['WebkitBorderBeforeWidth'],
borderBlockEnd: ['WebkitBorderAfter'],
borderBlockEndColor: ['WebkitBorderAfterColor'],
borderBlockEndStyle: ['WebkitBorderAfterStyle'],
borderBlockEndWidth: ['WebkitBorderAfterWidth'],
borderInlineStart: ['WebkitBorderStart', 'MozBorderStart'],
borderInlineStartColor: ['WebkitBorderStartColor', 'MozBorderStartColor'],
borderInlineStartStyle: ['WebkitBorderStartStyle', 'MozBorderStartStyle'],
borderInlineStartWidth: ['WebkitBorderStartWidth', 'MozBorderStartWidth'],
borderInlineEnd: ['WebkitBorderEnd', 'MozBorderEnd'],
borderInlineEndColor: ['WebkitBorderEndColor', 'MozBorderEndColor'],
borderInlineEndStyle: ['WebkitBorderEndStyle', 'MozBorderEndStyle'],
borderInlineEndWidth: ['WebkitBorderEndWidth', 'MozBorderEndWidth']
};
function logical(property, value, style) {
if (Object.prototype.hasOwnProperty.call(alternativeProps, property)) {
var alternativePropList = alternativeProps[property];
for (var i = 0, len = alternativePropList.length; i < len; ++i) {
style[alternativePropList[i]] = value;
}
}
}
webpack://frontend-mybets/../../node_modules/inline-style-prefixer/lib/plugins/position.js
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = position;
function position(property, value) {
if (property === 'position' && value === 'sticky') {
return ['-webkit-sticky', 'sticky'];
}
}
webpack://frontend-mybets/../../node_modules/inline-style-prefixer/lib/plugins/sizing.js
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = sizing;
var prefixes = ['-webkit-', '-moz-', ''];
var properties = {
maxHeight: true,
maxWidth: true,
width: true,
height: true,
columnWidth: true,
minWidth: true,
minHeight: true
};
var values = {
'min-content': true,
'max-content': true,
'fill-available': true,
'fit-content': true,
'contain-floats': true
};
function sizing(property, value) {
if (properties.hasOwnProperty(property) && values.hasOwnProperty(value)) {
return prefixes.map(function (prefix) {
return prefix + value;
});
}
}
webpack://frontend-mybets/../../node_modules/inline-style-prefixer/lib/plugins/transition.js
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = transition;
var _hyphenateProperty = require('css-in-js-utils/lib/hyphenateProperty');
var _hyphenateProperty2 = _interopRequireDefault(_hyphenateProperty);
var _isPrefixedValue = require('css-in-js-utils/lib/isPrefixedValue');
var _isPrefixedValue2 = _interopRequireDefault(_isPrefixedValue);
var _capitalizeString = require('../utils/capitalizeString');
var _capitalizeString2 = _interopRequireDefault(_capitalizeString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var properties = {
transition: true,
transitionProperty: true,
WebkitTransition: true,
WebkitTransitionProperty: true,
MozTransition: true,
MozTransitionProperty: true
};
var prefixMapping = {
Webkit: '-webkit-',
Moz: '-moz-',
ms: '-ms-'
};
function prefixValue(value, propertyPrefixMap) {
if ((0, _isPrefixedValue2.default)(value)) {
return value;
}
// only split multi values, not cubic beziers
var multipleValues = value.split(/,(?![^()]*(?:\([^()]*\))?\))/g);
for (var i = 0, len = multipleValues.length; i < len; ++i) {
var singleValue = multipleValues[i];
var values = [singleValue];
for (var property in propertyPrefixMap) {
var dashCaseProperty = (0, _hyphenateProperty2.default)(property);
if (singleValue.indexOf(dashCaseProperty) > -1 && dashCaseProperty !== 'order') {
var prefixes = propertyPrefixMap[property];
for (var j = 0, pLen = prefixes.length; j < pLen; ++j) {
// join all prefixes and create a new value
values.unshift(singleValue.replace(dashCaseProperty, prefixMapping[prefixes[j]] + dashCaseProperty));
}
}
}
multipleValues[i] = values.join(',');
}
return multipleValues.join(',');
}
function transition(property, value, style, propertyPrefixMap) {
// also check for already prefixed transitions
if (typeof value === 'string' && properties.hasOwnProperty(property)) {
var outputValue = prefixValue(value, propertyPrefixMap);
// if the property is already prefixed
var webkitOutput = outputValue.split(/,(?![^()]*(?:\([^()]*\))?\))/g).filter(function (val) {
return !/-moz-|-ms-/.test(val);
}).join(',');
if (property.indexOf('Webkit') > -1) {
return webkitOutput;
}
var mozOutput = outputValue.split(/,(?![^()]*(?:\([^()]*\))?\))/g).filter(function (val) {
return !/-webkit-|-ms-/.test(val);
}).join(',');
if (property.indexOf('Moz') > -1) {
return mozOutput;
}
style['Webkit' + (0, _capitalizeString2.default)(property)] = webkitOutput;
style['Moz' + (0, _capitalizeString2.default)(property)] = mozOutput;
return outputValue;
}
}
webpack://frontend-mybets/../../node_modules/inline-style-prefixer/lib/utils/addNewValuesOnly.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = addNewValuesOnly;
function addIfNew(list, value) {
if (list.indexOf(value) === -1) {
list.push(value);
}
}
function addNewValuesOnly(list, values) {
if (Array.isArray(values)) {
for (var i = 0, len = values.length; i < len; ++i) {
addIfNew(list, values[i]);
}
} else {
addIfNew(list, values);
}
}
webpack://frontend-mybets/../../node_modules/inline-style-prefixer/lib/utils/capitalizeString.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = capitalizeString;
function capitalizeString(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
webpack://frontend-mybets/../../node_modules/inline-style-prefixer/lib/utils/isObject.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isObject;
function isObject(value) {
return value instanceof Object && !Array.isArray(value);
}
webpack://frontend-mybets/../../node_modules/inline-style-prefixer/lib/utils/prefixProperty.js
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = prefixProperty;
var _capitalizeString = require('./capitalizeString');
var _capitalizeString2 = _interopRequireDefault(_capitalizeString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function prefixProperty(prefixProperties, property, style) {
var requiredPrefixes = prefixProperties[property];
if (requiredPrefixes && style.hasOwnProperty(property)) {
var capitalizedProperty = (0, _capitalizeString2.default)(property);
for (var i = 0; i < requiredPrefixes.length; ++i) {
var prefixedProperty = requiredPrefixes[i] + capitalizedProperty;
if (!style[prefixedProperty]) {
style[prefixedProperty] = style[property];
}
}
}
return style;
}
webpack://frontend-mybets/../../node_modules/inline-style-prefixer/lib/utils/prefixValue.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = prefixValue;
function prefixValue(plugins, property, value, style, metaData) {
for (var i = 0, len = plugins.length; i < len; ++i) {
var processedValue = plugins[i](property, value, style, metaData);
// we can stop processing if a value is returned
// as all plugin criteria are unique
if (processedValue) {
return processedValue;
}
}
}
webpack://frontend-mybets/../../node_modules/is-node/index.js
// Coding standard for this project defined @ https://github.com/MatthewSH/standards/blob/master/JavaScript.md 'use strict'; exports = module.exports = !!(typeof process !== 'undefined' && process.versions && process.versions.node);
webpack://frontend-mybets/../../node_modules/jwt-decode/build/jwt-decode.esm.js
function e(e){this.message=e}e.prototype=new Error,e.prototype.name="InvalidCharacterError";var r="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(r){var t=String(r).replace(/=+$/,"");if(t.length%4==1)throw new e("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,o,a=0,i=0,c="";o=t.charAt(i++);~o&&(n=a%4?64*n+o:o,a++%4)?c+=String.fromCharCode(255&n>>(-2*a&6)):0)o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(o);return c};function t(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(r(e).replace(/(.)/g,(function(e,r){var t=r.charCodeAt(0).toString(16).toUpperCase();return t.length<2&&(t="0"+t),"%"+t})))}(t)}catch(e){return r(t)}}function n(e){this.message=e}function o(e,r){if("string"!=typeof e)throw new n("Invalid token specified");var o=!0===(r=r||{}).header?0:1;try{return JSON.parse(t(e.split(".")[o]))}catch(e){throw new n("Invalid token specified: "+e.message)}}n.prototype=new Error,n.prototype.name="InvalidTokenError";export default o;export{n as InvalidTokenError};
//# sourceMappingURL=jwt-decode.esm.js.map
webpack://frontend-mybets/../../node_modules/locale-currency/index.js
var map = require("./map");
var getCountryCode = function(localeString) {
var components = localeString.split("_");
if (components.length == 2) {
return components.pop();
}
components = localeString.split("-");
if (components.length == 2) {
return components.pop();
}
return localeString;
}
exports.getCurrency = function(locale) {
var countryCode = getCountryCode(locale).toUpperCase();
if (countryCode in map) {
return map[countryCode];
}
return null;
}
exports.getLocales = function(currencyCode) {
currencyCode = currencyCode.toUpperCase();
var locales = [];
for (countryCode in map) {
if (map[countryCode] === currencyCode) {
locales.push(countryCode);
}
}
return locales;
}
webpack://frontend-mybets/../../node_modules/locale-currency/map.js
// Generated using ShowCurrencies.java
var map = {
AD: 'EUR',
AE: 'AED',
AF: 'AFN',
AG: 'XCD',
AI: 'XCD',
AL: 'ALL',
AM: 'AMD',
AN: 'ANG',
AO: 'AOA',
AR: 'ARS',
AS: 'USD',
AT: 'EUR',
AU: 'AUD',
AW: 'AWG',
AX: 'EUR',
AZ: 'AZN',
BA: 'BAM',
BB: 'BBD',
BD: 'BDT',
BE: 'EUR',
BF: 'XOF',
BG: 'BGN',
BH: 'BHD',
BI: 'BIF',
BJ: 'XOF',
BL: 'EUR',
BM: 'BMD',
BN: 'BND',
BO: 'BOB',
BQ: 'USD',
BR: 'BRL',
BS: 'BSD',
BT: 'BTN',
BV: 'NOK',
BW: 'BWP',
BY: 'BYR',
BZ: 'BZD',
CA: 'CAD',
CC: 'AUD',
CD: 'CDF',
CF: 'XAF',
CG: 'XAF',
CH: 'CHF',
CI: 'XOF',
CK: 'NZD',
CL: 'CLP',
CM: 'XAF',
CN: 'CNY',
CO: 'COP',
CR: 'CRC',
CU: 'CUP',
CV: 'CVE',
CW: 'ANG',
CX: 'AUD',
CY: 'EUR',
CZ: 'CZK',
DE: 'EUR',
DJ: 'DJF',
DK: 'DKK',
DM: 'XCD',
DO: 'DOP',
DZ: 'DZD',
EC: 'USD',
EE: 'EUR',
EG: 'EGP',
EH: 'MAD',
ER: 'ERN',
ES: 'EUR',
ET: 'ETB',
FI: 'EUR',
FJ: 'FJD',
FK: 'FKP',
FM: 'USD',
FO: 'DKK',
FR: 'EUR',
GA: 'XAF',
GB: 'GBP',
GD: 'XCD',
GE: 'GEL',
GF: 'EUR',
GG: 'GBP',
GH: 'GHS',
GI: 'GIP',
GL: 'DKK',
GM: 'GMD',
GN: 'GNF',
GP: 'EUR',
GQ: 'XAF',
GR: 'EUR',
GS: 'GBP',
GT: 'GTQ',
GU: 'USD',
GW: 'XOF',
GY: 'GYD',
HK: 'HKD',
HM: 'AUD',
HN: 'HNL',
HR: 'HRK',
HT: 'HTG',
HU: 'HUF',
ID: 'IDR',
IE: 'EUR',
IL: 'ILS',
IM: 'GBP',
IN: 'INR',
IO: 'USD',
IQ: 'IQD',
IR: 'IRR',
IS: 'ISK',
IT: 'EUR',
JE: 'GBP',
JM: 'JMD',
JO: 'JOD',
JP: 'JPY',
KE: 'KES',
KG: 'KGS',
KH: 'KHR',
KI: 'AUD',
KM: 'KMF',
KN: 'XCD',
KP: 'KPW',
KR: 'KRW',
KW: 'KWD',
KY: 'KYD',
KZ: 'KZT',
LA: 'LAK',
LB: 'LBP',
LC: 'XCD',
LI: 'CHF',
LK: 'LKR',
LR: 'LRD',
LS: 'LSL',
LT: 'LTL',
LU: 'EUR',
LV: 'LVL',
LY: 'LYD',
MA: 'MAD',
MC: 'EUR',
MD: 'MDL',
ME: 'EUR',
MF: 'EUR',
MG: 'MGA',
MH: 'USD',
MK: 'MKD',
ML: 'XOF',
MM: 'MMK',
MN: 'MNT',
MO: 'MOP',
MP: 'USD',
MQ: 'EUR',
MR: 'MRO',
MS: 'XCD',
MT: 'EUR',
MU: 'MUR',
MV: 'MVR',
MW: 'MWK',
MX: 'MXN',
MY: 'MYR',
MZ: 'MZN',
NA: 'NAD',
NC: 'XPF',
NE: 'XOF',
NF: 'AUD',
NG: 'NGN',
NI: 'NIO',
NL: 'EUR',
NO: 'NOK',
NP: 'NPR',
NR: 'AUD',
NU: 'NZD',
NZ: 'NZD',
OM: 'OMR',
PA: 'PAB',
PE: 'PEN',
PF: 'XPF',
PG: 'PGK',
PH: 'PHP',
PK: 'PKR',
PL: 'PLN',
PM: 'EUR',
PN: 'NZD',
PR: 'USD',
PS: 'ILS',
PT: 'EUR',
PW: 'USD',
PY: 'PYG',
QA: 'QAR',
RE: 'EUR',
RO: 'RON',
RS: 'RSD',
RU: 'RUB',
RW: 'RWF',
SA: 'SAR',
SB: 'SBD',
SC: 'SCR',
SD: 'SDG',
SE: 'SEK',
SG: 'SGD',
SH: 'SHP',
SI: 'EUR',
SJ: 'NOK',
SK: 'EUR',
SL: 'SLL',
SM: 'EUR',
SN: 'XOF',
SO: 'SOS',
SR: 'SRD',
ST: 'STD',
SV: 'SVC',
SX: 'ANG',
SY: 'SYP',
SZ: 'SZL',
TC: 'USD',
TD: 'XAF',
TF: 'EUR',
TG: 'XOF',
TH: 'THB',
TJ: 'TJS',
TK: 'NZD',
TL: 'USD',
TM: 'TMT',
TN: 'TND',
TO: 'TOP',
TR: 'TRY',
TT: 'TTD',
TV: 'AUD',
TW: 'TWD',
TZ: 'TZS',
UA: 'UAH',
UG: 'UGX',
UM: 'USD',
US: 'USD',
UY: 'UYU',
UZ: 'UZS',
VA: 'EUR',
VC: 'XCD',
VE: 'VEF',
VG: 'USD',
VI: 'USD',
VN: 'VND',
VU: 'VUV',
WF: 'XPF',
WS: 'WST',
YE: 'YER',
YT: 'EUR',
ZA: 'ZAR',
ZM: 'ZMK',
ZW: 'ZWL'
};
module.exports = map;
webpack://frontend-mybets/../../node_modules/lodash/_DataView.js
var getNative = require('./_getNative'),
root = require('./_root');
/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView');
module.exports = DataView;
webpack://frontend-mybets/../../node_modules/lodash/_Hash.js
var hashClear = require('./_hashClear'),
hashDelete = require('./_hashDelete'),
hashGet = require('./_hashGet'),
hashHas = require('./_hashHas'),
hashSet = require('./_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;
module.exports = Hash;
webpack://frontend-mybets/../../node_modules/lodash/_LazyWrapper.js
var baseCreate = require('./_baseCreate'),
baseLodash = require('./_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;
module.exports = LazyWrapper;
webpack://frontend-mybets/../../node_modules/lodash/_ListCache.js
var listCacheClear = require('./_listCacheClear'),
listCacheDelete = require('./_listCacheDelete'),
listCacheGet = require('./_listCacheGet'),
listCacheHas = require('./_listCacheHas'),
listCacheSet = require('./_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;
module.exports = ListCache;
webpack://frontend-mybets/../../node_modules/lodash/_LodashWrapper.js
var baseCreate = require('./_baseCreate'),
baseLodash = require('./_baseLodash');
/**
* The base constructor for creating `lodash` wrapper objects.
*
* @private
* @param {*} value The value to wrap.
* @param {boolean} [chainAll] Enable explicit method chain sequences.
*/
function LodashWrapper(value, chainAll) {
this.__wrapped__ = value;
this.__actions__ = [];
this.__chain__ = !!chainAll;
this.__index__ = 0;
this.__values__ = undefined;
}
LodashWrapper.prototype = baseCreate(baseLodash.prototype);
LodashWrapper.prototype.constructor = LodashWrapper;
module.exports = LodashWrapper;
webpack://frontend-mybets/../../node_modules/lodash/_Map.js
var getNative = require('./_getNative'),
root = require('./_root');
/* Built-in method references that are verified to be native. */
var Map = getNative(root, 'Map');
module.exports = Map;
webpack://frontend-mybets/../../node_modules/lodash/_MapCache.js
var mapCacheClear = require('./_mapCacheClear'),
mapCacheDelete = require('./_mapCacheDelete'),
mapCacheGet = require('./_mapCacheGet'),
mapCacheHas = require('./_mapCacheHas'),
mapCacheSet = require('./_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;
module.exports = MapCache;
webpack://frontend-mybets/../../node_modules/lodash/_Promise.js
var getNative = require('./_getNative'),
root = require('./_root');
/* Built-in method references that are verified to be native. */
var Promise = getNative(root, 'Promise');
module.exports = Promise;
webpack://frontend-mybets/../../node_modules/lodash/_Set.js
var getNative = require('./_getNative'),
root = require('./_root');
/* Built-in method references that are verified to be native. */
var Set = getNative(root, 'Set');
module.exports = Set;
webpack://frontend-mybets/../../node_modules/lodash/_SetCache.js
var MapCache = require('./_MapCache'),
setCacheAdd = require('./_setCacheAdd'),
setCacheHas = require('./_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;
module.exports = SetCache;
webpack://frontend-mybets/../../node_modules/lodash/_Stack.js
var ListCache = require('./_ListCache'),
stackClear = require('./_stackClear'),
stackDelete = require('./_stackDelete'),
stackGet = require('./_stackGet'),
stackHas = require('./_stackHas'),
stackSet = require('./_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;
module.exports = Stack;
webpack://frontend-mybets/../../node_modules/lodash/_Symbol.js
var root = require('./_root');
/** Built-in value references. */
var Symbol = root.Symbol;
module.exports = Symbol;
webpack://frontend-mybets/../../node_modules/lodash/_Uint8Array.js
var root = require('./_root');
/** Built-in value references. */
var Uint8Array = root.Uint8Array;
module.exports = Uint8Array;
webpack://frontend-mybets/../../node_modules/lodash/_WeakMap.js
var getNative = require('./_getNative'),
root = require('./_root');
/* Built-in method references that are verified to be native. */
var WeakMap = getNative(root, 'WeakMap');
module.exports = WeakMap;
webpack://frontend-mybets/../../node_modules/lodash/_apply.js
/**
* A faster alternative to `Function#apply`, this function invokes `func`
* with the `this` binding of `thisArg` and the arguments of `args`.
*
* @private
* @param {Function} func The function to invoke.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} args The arguments to invoke `func` with.
* @returns {*} Returns the result of `func`.
*/
function apply(func, thisArg, args) {
switch (args.length) {
case 0: return func.call(thisArg);
case 1: return func.call(thisArg, args[0]);
case 2: return func.call(thisArg, args[0], args[1]);
case 3: return func.call(thisArg, args[0], args[1], args[2]);
}
return func.apply(thisArg, args);
}
module.exports = apply;
webpack://frontend-mybets/../../node_modules/lodash/_arrayEach.js
/**
* A specialized version of `_.forEach` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
module.exports = arrayEach;
webpack://frontend-mybets/../../node_modules/lodash/_arrayEvery.js
/**
* A specialized version of `_.every` 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 all elements pass the predicate check,
* else `false`.
*/
function arrayEvery(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (!predicate(array[index], index, array)) {
return false;
}
}
return true;
}
module.exports = arrayEvery;
webpack://frontend-mybets/../../node_modules/lodash/_arrayFilter.js
/**
* A specialized version of `_.filter` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function arrayFilter(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result[resIndex++] = value;
}
}
return result;
}
module.exports = arrayFilter;
webpack://frontend-mybets/../../node_modules/lodash/_arrayIncludes.js
var baseIndexOf = require('./_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;
}
module.exports = arrayIncludes;
webpack://frontend-mybets/../../node_modules/lodash/_arrayIncludesWith.js
/**
* This function is like `arrayIncludes` except that it accepts a comparator.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @param {Function} comparator The comparator invoked per element.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/
function arrayIncludesWith(array, value, comparator) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (comparator(value, array[index])) {
return true;
}
}
return false;
}
module.exports = arrayIncludesWith;
webpack://frontend-mybets/../../node_modules/lodash/_arrayLikeKeys.js
var baseTimes = require('./_baseTimes'),
isArguments = require('./isArguments'),
isArray = require('./isArray'),
isBuffer = require('./isBuffer'),
isIndex = require('./_isIndex'),
isTypedArray = require('./isTypedArray');
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
var isArr = isArray(value),
isArg = !isArr && isArguments(value),
isBuff = !isArr && !isArg && isBuffer(value),
isType = !isArr && !isArg && !isBuff && isTypedArray(value),
skipIndexes = isArr || isArg || isBuff || isType,
result = skipIndexes ? baseTimes(value.length, String) : [],
length = result.length;
for (var key in value) {
if ((inherited || hasOwnProperty.call(value, key)) &&
!(skipIndexes && (
// Safari 9 has enumerable `arguments.length` in strict mode.
key == 'length' ||
// Node.js 0.10 has enumerable non-index properties on buffers.
(isBuff && (key == 'offset' || key == 'parent')) ||
// PhantomJS 2 has enumerable non-index properties on typed arrays.
(isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
// Skip index properties.
isIndex(key, length)
))) {
result.push(key);
}
}
return result;
}
module.exports = arrayLikeKeys;
webpack://frontend-mybets/../../node_modules/lodash/_arrayMap.js
/**
* A specialized version of `_.map` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function arrayMap(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length,
result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
module.exports = arrayMap;
webpack://frontend-mybets/../../node_modules/lodash/_arrayPush.js
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/
function arrayPush(array, values) {
var index = -1,
length = values.length,
offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
module.exports = arrayPush;
webpack://frontend-mybets/../../node_modules/lodash/_arrayReduce.js
/**
* A specialized version of `_.reduce` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initAccum] Specify using the first element of `array` as
* the initial value.
* @returns {*} Returns the accumulated value.
*/
function arrayReduce(array, iteratee, accumulator, initAccum) {
var index = -1,
length = array == null ? 0 : array.length;
if (initAccum && length) {
accumulator = array[++index];
}
while (++index < length) {
accumulator = iteratee(accumulator, array[index], index, array);
}
return accumulator;
}
module.exports = arrayReduce;
webpack://frontend-mybets/../../node_modules/lodash/_arraySome.js
/**
* A specialized version of `_.some` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function arraySome(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
module.exports = arraySome;
webpack://frontend-mybets/../../node_modules/lodash/_asciiSize.js
var baseProperty = require('./_baseProperty');
/**
* Gets the size of an ASCII `string`.
*
* @private
* @param {string} string The string inspect.
* @returns {number} Returns the string size.
*/
var asciiSize = baseProperty('length');
module.exports = asciiSize;
webpack://frontend-mybets/../../node_modules/lodash/_asciiToArray.js
/**
* Converts an ASCII `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function asciiToArray(string) {
return string.split('');
}
module.exports = asciiToArray;
webpack://frontend-mybets/../../node_modules/lodash/_asciiWords.js
/** Used to match words composed of alphanumeric characters. */
var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
/**
* Splits an ASCII `string` into an array of its words.
*
* @private
* @param {string} The string to inspect.
* @returns {Array} Returns the words of `string`.
*/
function asciiWords(string) {
return string.match(reAsciiWord) || [];
}
module.exports = asciiWords;
webpack://frontend-mybets/../../node_modules/lodash/_assignMergeValue.js
var baseAssignValue = require('./_baseAssignValue'),
eq = require('./eq');
/**
* This function is like `assignValue` except that it doesn't assign
* `undefined` values.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignMergeValue(object, key, value) {
if ((value !== undefined && !eq(object[key], value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value);
}
}
module.exports = assignMergeValue;
webpack://frontend-mybets/../../node_modules/lodash/_assignValue.js
var baseAssignValue = require('./_baseAssignValue'),
eq = require('./eq');
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignValue(object, key, value) {
var objValue = object[key];
if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value);
}
}
module.exports = assignValue;
webpack://frontend-mybets/../../node_modules/lodash/_assocIndexOf.js
var eq = require('./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(array[length][0], key)) {
return length;
}
}
return -1;
}
module.exports = assocIndexOf;
webpack://frontend-mybets/../../node_modules/lodash/_baseAssign.js
var copyObject = require('./_copyObject'),
keys = require('./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(source), object);
}
module.exports = baseAssign;
webpack://frontend-mybets/../../node_modules/lodash/_baseAssignIn.js
var copyObject = require('./_copyObject'),
keysIn = require('./keysIn');
/**
* The base implementation of `_.assignIn` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssignIn(object, source) {
return object && copyObject(source, keysIn(source), object);
}
module.exports = baseAssignIn;
webpack://frontend-mybets/../../node_modules/lodash/_baseAssignValue.js
var defineProperty = require('./_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;
}
}
module.exports = baseAssignValue;
webpack://frontend-mybets/../../node_modules/lodash/_baseClamp.js
/**
* The base implementation of `_.clamp` which doesn't coerce arguments.
*
* @private
* @param {number} number The number to clamp.
* @param {number} [lower] The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the clamped number.
*/
function baseClamp(number, lower, upper) {
if (number === number) {
if (upper !== undefined) {
number = number <= upper ? number : upper;
}
if (lower !== undefined) {
number = number >= lower ? number : lower;
}
}
return number;
}
module.exports = baseClamp;
webpack://frontend-mybets/../../node_modules/lodash/_baseClone.js
var Stack = require('./_Stack'),
arrayEach = require('./_arrayEach'),
assignValue = require('./_assignValue'),
baseAssign = require('./_baseAssign'),
baseAssignIn = require('./_baseAssignIn'),
cloneBuffer = require('./_cloneBuffer'),
copyArray = require('./_copyArray'),
copySymbols = require('./_copySymbols'),
copySymbolsIn = require('./_copySymbolsIn'),
getAllKeys = require('./_getAllKeys'),
getAllKeysIn = require('./_getAllKeysIn'),
getTag = require('./_getTag'),
initCloneArray = require('./_initCloneArray'),
initCloneByTag = require('./_initCloneByTag'),
initCloneObject = require('./_initCloneObject'),
isArray = require('./isArray'),
isBuffer = require('./isBuffer'),
isMap = require('./isMap'),
isObject = require('./isObject'),
isSet = require('./isSet'),
keys = require('./keys'),
keysIn = require('./keysIn');
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
CLONE_FLAT_FLAG = 2,
CLONE_SYMBOLS_FLAG = 4;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[argsTag] = cloneableTags[arrayTag] =
cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
cloneableTags[boolTag] = cloneableTags[dateTag] =
cloneableTags[float32Tag] = cloneableTags[float64Tag] =
cloneableTags[int8Tag] = cloneableTags[int16Tag] =
cloneableTags[int32Tag] = cloneableTags[mapTag] =
cloneableTags[numberTag] = cloneableTags[objectTag] =
cloneableTags[regexpTag] = cloneableTags[setTag] =
cloneableTags[stringTag] = cloneableTags[symbolTag] =
cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
cloneableTags[errorTag] = cloneableTags[funcTag] =
cloneableTags[weakMapTag] = false;
/**
* The base implementation of `_.clone` and `_.cloneDeep` which tracks
* traversed objects.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} bitmask The bitmask flags.
* 1 - Deep clone
* 2 - Flatten inherited properties
* 4 - Clone symbols
* @param {Function} [customizer] The function to customize cloning.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The parent object of `value`.
* @param {Object} [stack] Tracks traversed objects and their clone counterparts.
* @returns {*} Returns the cloned value.
*/
function baseClone(value, bitmask, customizer, key, object, stack) {
var result,
isDeep = bitmask & CLONE_DEEP_FLAG,
isFlat = bitmask & CLONE_FLAT_FLAG,
isFull = bitmask & CLONE_SYMBOLS_FLAG;
if (customizer) {
result = object ? customizer(value, key, object, stack) : customizer(value);
}
if (result !== undefined) {
return result;
}
if (!isObject(value)) {
return value;
}
var isArr = isArray(value);
if (isArr) {
result = initCloneArray(value);
if (!isDeep) {
return copyArray(value, result);
}
} else {
var tag = getTag(value),
isFunc = tag == funcTag || tag == genTag;
if (isBuffer(value)) {
return cloneBuffer(value, isDeep);
}
if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
result = (isFlat || isFunc) ? {} : initCloneObject(value);
if (!isDeep) {
return isFlat
? copySymbolsIn(value, baseAssignIn(result, value))
: copySymbols(value, baseAssign(result, value));
}
} else {
if (!cloneableTags[tag]) {
return object ? value : {};
}
result = initCloneByTag(value, tag, isDeep);
}
}
// Check for circular references and return its corresponding clone.
stack || (stack = new Stack);
var stacked = stack.get(value);
if (stacked) {
return stacked;
}
stack.set(value, result);
if (isSet(value)) {
value.forEach(function(subValue) {
result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
});
} else if (isMap(value)) {
value.forEach(function(subValue, key) {
result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
}
var keysFunc = isFull
? (isFlat ? getAllKeysIn : getAllKeys)
: (isFlat ? keysIn : keys);
var props = isArr ? undefined : keysFunc(value);
arrayEach(props || value, function(subValue, key) {
if (props) {
key = subValue;
subValue = value[key];
}
// Recursively populate clone (susceptible to call stack limits).
assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
return result;
}
module.exports = baseClone;
webpack://frontend-mybets/../../node_modules/lodash/_baseCreate.js
var isObject = require('./isObject');
/** Built-in value references. */
var objectCreate = Object.create;
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} proto The object to inherit from.
* @returns {Object} Returns the new object.
*/
var baseCreate = (function() {
function object() {}
return function(proto) {
if (!isObject(proto)) {
return {};
}
if (objectCreate) {
return objectCreate(proto);
}
object.prototype = proto;
var result = new object;
object.prototype = undefined;
return result;
};
}());
module.exports = baseCreate;
webpack://frontend-mybets/../../node_modules/lodash/_baseDifference.js
var SetCache = require('./_SetCache'),
arrayIncludes = require('./_arrayIncludes'),
arrayIncludesWith = require('./_arrayIncludesWith'),
arrayMap = require('./_arrayMap'),
baseUnary = require('./_baseUnary'),
cacheHas = require('./_cacheHas');
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/**
* The base implementation of methods like `_.difference` without support
* for excluding multiple arrays or iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Array} values The values to exclude.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
*/
function baseDifference(array, values, iteratee, comparator) {
var index = -1,
includes = arrayIncludes,
isCommon = true,
length = array.length,
result = [],
valuesLength = values.length;
if (!length) {
return result;
}
if (iteratee) {
values = arrayMap(values, baseUnary(iteratee));
}
if (comparator) {
includes = arrayIncludesWith;
isCommon = false;
}
else if (values.length >= LARGE_ARRAY_SIZE) {
includes = cacheHas;
isCommon = false;
values = new SetCache(values);
}
outer:
while (++index < length) {
var value = array[index],
computed = iteratee == null ? value : iteratee(value);
value = (comparator || value !== 0) ? value : 0;
if (isCommon && computed === computed) {
var valuesIndex = valuesLength;
while (valuesIndex--) {
if (values[valuesIndex] === computed) {
continue outer;
}
}
result.push(value);
}
else if (!includes(values, computed, comparator)) {
result.push(value);
}
}
return result;
}
module.exports = baseDifference;
webpack://frontend-mybets/../../node_modules/lodash/_baseEach.js
var baseForOwn = require('./_baseForOwn'),
createBaseEach = require('./_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);
module.exports = baseEach;
webpack://frontend-mybets/../../node_modules/lodash/_baseEvery.js
var baseEach = require('./_baseEach');
/**
* The base implementation of `_.every` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`
*/
function baseEvery(collection, predicate) {
var result = true;
baseEach(collection, function(value, index, collection) {
result = !!predicate(value, index, collection);
return result;
});
return result;
}
module.exports = baseEvery;
webpack://frontend-mybets/../../node_modules/lodash/_baseFilter.js
var baseEach = require('./_baseEach');
/**
* The base implementation of `_.filter` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function baseFilter(collection, predicate) {
var result = [];
baseEach(collection, function(value, index, collection) {
if (predicate(value, index, collection)) {
result.push(value);
}
});
return result;
}
module.exports = baseFilter;
webpack://frontend-mybets/../../node_modules/lodash/_baseFindIndex.js
/**
* The base implementation of `_.findIndex` and `_.findLastIndex` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {number} fromIndex The index to search from.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseFindIndex(array, predicate, fromIndex, fromRight) {
var length = array.length,
index = fromIndex + (fromRight ? 1 : -1);
while ((fromRight ? index-- : ++index < length)) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
module.exports = baseFindIndex;
webpack://frontend-mybets/../../node_modules/lodash/_baseFindKey.js
/**
* The base implementation of methods like `_.findKey` and `_.findLastKey`,
* without support for iteratee shorthands, which iterates over `collection`
* using `eachFunc`.
*
* @private
* @param {Array|Object} collection The collection to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {Function} eachFunc The function to iterate over `collection`.
* @returns {*} Returns the found element or its key, else `undefined`.
*/
function baseFindKey(collection, predicate, eachFunc) {
var result;
eachFunc(collection, function(value, key, collection) {
if (predicate(value, key, collection)) {
result = key;
return false;
}
});
return result;
}
module.exports = baseFindKey;
webpack://frontend-mybets/../../node_modules/lodash/_baseFlatten.js
var arrayPush = require('./_arrayPush'),
isFlattenable = require('./_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;
}
module.exports = baseFlatten;
webpack://frontend-mybets/../../node_modules/lodash/_baseFor.js
var createBaseFor = require('./_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();
module.exports = baseFor;
webpack://frontend-mybets/../../node_modules/lodash/_baseForOwn.js
var baseFor = require('./_baseFor'),
keys = require('./keys');
/**
* The base implementation of `_.forOwn` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwn(object, iteratee) {
return object && baseFor(object, iteratee, keys);
}
module.exports = baseForOwn;
webpack://frontend-mybets/../../node_modules/lodash/_baseGet.js
var castPath = require('./_castPath'),
toKey = require('./_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;
}
module.exports = baseGet;
webpack://frontend-mybets/../../node_modules/lodash/_baseGetAllKeys.js
var arrayPush = require('./_arrayPush'),
isArray = require('./isArray');
/**
* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
* `keysFunc` and `symbolsFunc` to get the enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Function} keysFunc The function to get the keys of `object`.
* @param {Function} symbolsFunc The function to get the symbols of `object`.
* @returns {Array} Returns the array of property names and symbols.
*/
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
}
module.exports = baseGetAllKeys;
webpack://frontend-mybets/../../node_modules/lodash/_baseGetTag.js
var Symbol = require('./_Symbol'),
getRawTag = require('./_getRawTag'),
objectToString = require('./_objectToString');
/** `Object#toString` result references. */
var nullTag = '[object Null]',
undefinedTag = '[object Undefined]';
/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
if (value == null) {
return value === undefined ? undefinedTag : nullTag;
}
return (symToStringTag && symToStringTag in Object(value))
? getRawTag(value)
: objectToString(value);
}
module.exports = baseGetTag;
webpack://frontend-mybets/../../node_modules/lodash/_baseHas.js
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* The base implementation of `_.has` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHas(object, key) {
return object != null && hasOwnProperty.call(object, key);
}
module.exports = baseHas;
webpack://frontend-mybets/../../node_modules/lodash/_baseHasIn.js
/**
* The base implementation of `_.hasIn` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHasIn(object, key) {
return object != null && key in Object(object);
}
module.exports = baseHasIn;
webpack://frontend-mybets/../../node_modules/lodash/_baseIndexOf.js
var baseFindIndex = require('./_baseFindIndex'),
baseIsNaN = require('./_baseIsNaN'),
strictIndexOf = require('./_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);
}
module.exports = baseIndexOf;
webpack://frontend-mybets/../../node_modules/lodash/_baseIsArguments.js
var baseGetTag = require('./_baseGetTag'),
isObjectLike = require('./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(value) && baseGetTag(value) == argsTag;
}
module.exports = baseIsArguments;
webpack://frontend-mybets/../../node_modules/lodash/_baseIsEqual.js
var baseIsEqualDeep = require('./_baseIsEqualDeep'),
isObjectLike = require('./isObjectLike');
/**
* The base implementation of `_.isEqual` which supports partial comparisons
* and tracks traversed objects.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {boolean} bitmask The bitmask flags.
* 1 - Unordered comparison
* 2 - Partial comparison
* @param {Function} [customizer] The function to customize comparisons.
* @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, bitmask, customizer, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}
module.exports = baseIsEqual;
webpack://frontend-mybets/../../node_modules/lodash/_baseIsEqualDeep.js
var Stack = require('./_Stack'),
equalArrays = require('./_equalArrays'),
equalByTag = require('./_equalByTag'),
equalObjects = require('./_equalObjects'),
getTag = require('./_getTag'),
isArray = require('./isArray'),
isBuffer = require('./isBuffer'),
isTypedArray = require('./isTypedArray');
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
objectTag = '[object Object]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = objIsArr ? arrayTag : getTag(object),
othTag = othIsArr ? arrayTag : getTag(other);
objTag = objTag == argsTag ? objectTag : objTag;
othTag = othTag == argsTag ? objectTag : othTag;
var objIsObj = objTag == objectTag,
othIsObj = othTag == objectTag,
isSameTag = objTag == othTag;
if (isSameTag && isBuffer(object)) {
if (!isBuffer(other)) {
return false;
}
objIsArr = true;
objIsObj = false;
}
if (isSameTag && !objIsObj) {
stack || (stack = new Stack);
return (objIsArr || isTypedArray(object))
? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
: equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
}
if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object,
othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new Stack);
return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new Stack);
return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}
module.exports = baseIsEqualDeep;
webpack://frontend-mybets/../../node_modules/lodash/_baseIsMap.js
var getTag = require('./_getTag'),
isObjectLike = require('./isObjectLike');
/** `Object#toString` result references. */
var mapTag = '[object Map]';
/**
* The base implementation of `_.isMap` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
*/
function baseIsMap(value) {
return isObjectLike(value) && getTag(value) == mapTag;
}
module.exports = baseIsMap;
webpack://frontend-mybets/../../node_modules/lodash/_baseIsMatch.js
var Stack = require('./_Stack'),
baseIsEqual = require('./_baseIsEqual');
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/**
* The base implementation of `_.isMatch` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Array} matchData The property names, values, and compare flags to match.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
*/
function baseIsMatch(object, source, matchData, customizer) {
var index = matchData.length,
length = index,
noCustomizer = !customizer;
if (object == null) {
return !length;
}
object = Object(object);
while (index--) {
var data = matchData[index];
if ((noCustomizer && data[2])
? data[1] !== object[data[0]]
: !(data[0] in object)
) {
return false;
}
}
while (++index < length) {
data = matchData[index];
var key = data[0],
objValue = object[key],
srcValue = data[1];
if (noCustomizer && data[2]) {
if (objValue === undefined && !(key in object)) {
return false;
}
} else {
var stack = new Stack;
if (customizer) {
var result = customizer(objValue, srcValue, key, object, source, stack);
}
if (!(result === undefined
? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)
: result
)) {
return false;
}
}
}
return true;
}
module.exports = baseIsMatch;
webpack://frontend-mybets/../../node_modules/lodash/_baseIsNaN.js
/**
* The base implementation of `_.isNaN` without support for number objects.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
*/
function baseIsNaN(value) {
return value !== value;
}
module.exports = baseIsNaN;
webpack://frontend-mybets/../../node_modules/lodash/_baseIsNative.js
var isFunction = require('./isFunction'),
isMasked = require('./_isMasked'),
isObject = require('./isObject'),
toSource = require('./_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,
objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/
function baseIsNative(value) {
if (!isObject(value) || isMasked(value)) {
return false;
}
var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
module.exports = baseIsNative;
webpack://frontend-mybets/../../node_modules/lodash/_baseIsRegExp.js
var baseGetTag = require('./_baseGetTag'),
isObjectLike = require('./isObjectLike');
/** `Object#toString` result references. */
var regexpTag = '[object RegExp]';
/**
* The base implementation of `_.isRegExp` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
*/
function baseIsRegExp(value) {
return isObjectLike(value) && baseGetTag(value) == regexpTag;
}
module.exports = baseIsRegExp;
webpack://frontend-mybets/../../node_modules/lodash/_baseIsSet.js
var getTag = require('./_getTag'),
isObjectLike = require('./isObjectLike');
/** `Object#toString` result references. */
var setTag = '[object Set]';
/**
* The base implementation of `_.isSet` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
*/
function baseIsSet(value) {
return isObjectLike(value) && getTag(value) == setTag;
}
module.exports = baseIsSet;
webpack://frontend-mybets/../../node_modules/lodash/_baseIsTypedArray.js
var baseGetTag = require('./_baseGetTag'),
isLength = require('./isLength'),
isObjectLike = require('./isObjectLike');
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[funcTag] =
typedArrayTags[mapTag] = typedArrayTags[numberTag] =
typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
typedArrayTags[setTag] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag] = false;
/**
* The base implementation of `_.isTypedArray` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
*/
function baseIsTypedArray(value) {
return isObjectLike(value) &&
isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
}
module.exports = baseIsTypedArray;
webpack://frontend-mybets/../../node_modules/lodash/_baseIteratee.js
var baseMatches = require('./_baseMatches'),
baseMatchesProperty = require('./_baseMatchesProperty'),
identity = require('./identity'),
isArray = require('./isArray'),
property = require('./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;
}
if (typeof value == 'object') {
return isArray(value)
? baseMatchesProperty(value[0], value[1])
: baseMatches(value);
}
return property(value);
}
module.exports = baseIteratee;
webpack://frontend-mybets/../../node_modules/lodash/_baseKeys.js
var isPrototype = require('./_isPrototype'),
nativeKeys = require('./_nativeKeys');
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!isPrototype(object)) {
return nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
module.exports = baseKeys;
webpack://frontend-mybets/../../node_modules/lodash/_baseKeysIn.js
var isObject = require('./isObject'),
isPrototype = require('./_isPrototype'),
nativeKeysIn = require('./_nativeKeysIn');
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeysIn(object) {
if (!isObject(object)) {
return nativeKeysIn(object);
}
var isProto = isPrototype(object),
result = [];
for (var key in object) {
if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
result.push(key);
}
}
return result;
}
module.exports = baseKeysIn;
webpack://frontend-mybets/../../node_modules/lodash/_baseLodash.js
/**
* The function whose prototype chain sequence wrappers inherit from.
*
* @private
*/
function baseLodash() {
// No operation performed.
}
module.exports = baseLodash;
webpack://frontend-mybets/../../node_modules/lodash/_baseMap.js
var baseEach = require('./_baseEach'),
isArrayLike = require('./isArrayLike');
/**
* The base implementation of `_.map` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function baseMap(collection, iteratee) {
var index = -1,
result = isArrayLike(collection) ? Array(collection.length) : [];
baseEach(collection, function(value, key, collection) {
result[++index] = iteratee(value, key, collection);
});
return result;
}
module.exports = baseMap;
webpack://frontend-mybets/../../node_modules/lodash/_baseMatches.js
var baseIsMatch = require('./_baseIsMatch'),
getMatchData = require('./_getMatchData'),
matchesStrictComparable = require('./_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);
};
}
module.exports = baseMatches;
webpack://frontend-mybets/../../node_modules/lodash/_baseMatchesProperty.js
var baseIsEqual = require('./_baseIsEqual'),
get = require('./get'),
hasIn = require('./hasIn'),
isKey = require('./_isKey'),
isStrictComparable = require('./_isStrictComparable'),
matchesStrictComparable = require('./_matchesStrictComparable'),
toKey = require('./_toKey');
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/**
* The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
*
* @private
* @param {string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatchesProperty(path, srcValue) {
if (isKey(path) && isStrictComparable(srcValue)) {
return matchesStrictComparable(toKey(path), srcValue);
}
return function(object) {
var objValue = get(object, path);
return (objValue === undefined && objValue === srcValue)
? hasIn(object, path)
: baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
};
}
module.exports = baseMatchesProperty;
webpack://frontend-mybets/../../node_modules/lodash/_baseMerge.js
var Stack = require('./_Stack'),
assignMergeValue = require('./_assignMergeValue'),
baseFor = require('./_baseFor'),
baseMergeDeep = require('./_baseMergeDeep'),
isObject = require('./isObject'),
keysIn = require('./keysIn'),
safeGet = require('./_safeGet');
/**
* 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) {
stack || (stack = new Stack);
if (isObject(srcValue)) {
baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
}
else {
var newValue = customizer
? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)
: undefined;
if (newValue === undefined) {
newValue = srcValue;
}
assignMergeValue(object, key, newValue);
}
}, keysIn);
}
module.exports = baseMerge;
webpack://frontend-mybets/../../node_modules/lodash/_baseMergeDeep.js
var assignMergeValue = require('./_assignMergeValue'),
cloneBuffer = require('./_cloneBuffer'),
cloneTypedArray = require('./_cloneTypedArray'),
copyArray = require('./_copyArray'),
initCloneObject = require('./_initCloneObject'),
isArguments = require('./isArguments'),
isArray = require('./isArray'),
isArrayLikeObject = require('./isArrayLikeObject'),
isBuffer = require('./isBuffer'),
isFunction = require('./isFunction'),
isObject = require('./isObject'),
isPlainObject = require('./isPlainObject'),
isTypedArray = require('./isTypedArray'),
safeGet = require('./_safeGet'),
toPlainObject = require('./toPlainObject');
/**
* A specialized version of `baseMerge` for arrays and objects which performs
* deep merges and tracks traversed objects enabling objects with circular
* references to be merged.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {string} key The key of the value to merge.
* @param {number} srcIndex The index of `source`.
* @param {Function} mergeFunc The function to merge values.
* @param {Function} [customizer] The function to customize assigned values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
var objValue = safeGet(object, key),
srcValue = safeGet(source, key),
stacked = stack.get(srcValue);
if (stacked) {
assignMergeValue(object, key, stacked);
return;
}
var newValue = customizer
? customizer(objValue, srcValue, (key + ''), object, source, stack)
: undefined;
var isCommon = newValue === undefined;
if (isCommon) {
var isArr = isArray(srcValue),
isBuff = !isArr && isBuffer(srcValue),
isTyped = !isArr && !isBuff && isTypedArray(srcValue);
newValue = srcValue;
if (isArr || isBuff || isTyped) {
if (isArray(objValue)) {
newValue = objValue;
}
else if (isArrayLikeObject(objValue)) {
newValue = copyArray(objValue);
}
else if (isBuff) {
isCommon = false;
newValue = cloneBuffer(srcValue, true);
}
else if (isTyped) {
isCommon = false;
newValue = cloneTypedArray(srcValue, true);
}
else {
newValue = [];
}
}
else if (isPlainObject(srcValue) || isArguments(srcValue)) {
newValue = objValue;
if (isArguments(objValue)) {
newValue = toPlainObject(objValue);
}
else if (!isObject(objValue) || isFunction(objValue)) {
newValue = initCloneObject(srcValue);
}
}
else {
isCommon = false;
}
}
if (isCommon) {
// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue, newValue);
mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
stack['delete'](srcValue);
}
assignMergeValue(object, key, newValue);
}
module.exports = baseMergeDeep;
webpack://frontend-mybets/../../node_modules/lodash/_baseOrderBy.js
var arrayMap = require('./_arrayMap'),
baseGet = require('./_baseGet'),
baseIteratee = require('./_baseIteratee'),
baseMap = require('./_baseMap'),
baseSortBy = require('./_baseSortBy'),
baseUnary = require('./_baseUnary'),
compareMultiple = require('./_compareMultiple'),
identity = require('./identity'),
isArray = require('./isArray');
/**
* 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) {
if (iteratees.length) {
iteratees = arrayMap(iteratees, function(iteratee) {
if (isArray(iteratee)) {
return function(value) {
return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);
}
}
return iteratee;
});
} else {
iteratees = [identity];
}
var index = -1;
iteratees = arrayMap(iteratees, baseUnary(baseIteratee));
var result = baseMap(collection, function(value, key, collection) {
var criteria = arrayMap(iteratees, function(iteratee) {
return iteratee(value);
});
return { 'criteria': criteria, 'index': ++index, 'value': value };
});
return baseSortBy(result, function(object, other) {
return compareMultiple(object, other, orders);
});
}
module.exports = baseOrderBy;
webpack://frontend-mybets/../../node_modules/lodash/_basePickBy.js
var baseGet = require('./_baseGet'),
baseSet = require('./_baseSet'),
castPath = require('./_castPath');
/**
* The base implementation of `_.pickBy` without support for iteratee shorthands.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @param {Function} predicate The function invoked per property.
* @returns {Object} Returns the new object.
*/
function basePickBy(object, paths, predicate) {
var index = -1,
length = paths.length,
result = {};
while (++index < length) {
var path = paths[index],
value = baseGet(object, path);
if (predicate(value, path)) {
baseSet(result, castPath(path, object), value);
}
}
return result;
}
module.exports = basePickBy;
webpack://frontend-mybets/../../node_modules/lodash/_baseProperty.js
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
module.exports = baseProperty;
webpack://frontend-mybets/../../node_modules/lodash/_basePropertyDeep.js
var baseGet = require('./_baseGet');
/**
* A specialized version of `baseProperty` which supports deep paths.
*
* @private
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function basePropertyDeep(path) {
return function(object) {
return baseGet(object, path);
};
}
module.exports = basePropertyDeep;
webpack://frontend-mybets/../../node_modules/lodash/_basePropertyOf.js
/**
* The base implementation of `_.propertyOf` without support for deep paths.
*
* @private
* @param {Object} object The object to query.
* @returns {Function} Returns the new accessor function.
*/
function basePropertyOf(object) {
return function(key) {
return object == null ? undefined : object[key];
};
}
module.exports = basePropertyOf;
webpack://frontend-mybets/../../node_modules/lodash/_baseRange.js
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeCeil = Math.ceil,
nativeMax = Math.max;
/**
* The base implementation of `_.range` and `_.rangeRight` which doesn't
* coerce arguments.
*
* @private
* @param {number} start The start of the range.
* @param {number} end The end of the range.
* @param {number} step The value to increment or decrement by.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Array} Returns the range of numbers.
*/
function baseRange(start, end, step, fromRight) {
var index = -1,
length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
result = Array(length);
while (length--) {
result[fromRight ? length : ++index] = start;
start += step;
}
return result;
}
module.exports = baseRange;
webpack://frontend-mybets/../../node_modules/lodash/_baseRest.js
var identity = require('./identity'),
overRest = require('./_overRest'),
setToString = require('./_setToString');
/**
* The base implementation of `_.rest` which doesn't validate or coerce arguments.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
*/
function baseRest(func, start) {
return setToString(overRest(func, start, identity), func + '');
}
module.exports = baseRest;
webpack://frontend-mybets/../../node_modules/lodash/_baseSet.js
var assignValue = require('./_assignValue'),
castPath = require('./_castPath'),
isIndex = require('./_isIndex'),
isObject = require('./isObject'),
toKey = require('./_toKey');
/**
* The base implementation of `_.set`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @param {Function} [customizer] The function to customize path creation.
* @returns {Object} Returns `object`.
*/
function baseSet(object, path, value, customizer) {
if (!isObject(object)) {
return object;
}
path = castPath(path, object);
var index = -1,
length = path.length,
lastIndex = length - 1,
nested = object;
while (nested != null && ++index < length) {
var key = toKey(path[index]),
newValue = value;
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
return object;
}
if (index != lastIndex) {
var objValue = nested[key];
newValue = customizer ? customizer(objValue, key, nested) : undefined;
if (newValue === undefined) {
newValue = isObject(objValue)
? objValue
: (isIndex(path[index + 1]) ? [] : {});
}
}
assignValue(nested, key, newValue);
nested = nested[key];
}
return object;
}
module.exports = baseSet;
webpack://frontend-mybets/../../node_modules/lodash/_baseSetData.js
var identity = require('./identity'),
metaMap = require('./_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 : function(func, data) {
metaMap.set(func, data);
return func;
};
module.exports = baseSetData;
webpack://frontend-mybets/../../node_modules/lodash/_baseSetToString.js
var constant = require('./constant'),
defineProperty = require('./_defineProperty'),
identity = require('./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 : function(func, string) {
return defineProperty(func, 'toString', {
'configurable': true,
'enumerable': false,
'value': constant(string),
'writable': true
});
};
module.exports = baseSetToString;
webpack://frontend-mybets/../../node_modules/lodash/_baseSlice.js
/**
* The base implementation of `_.slice` without an iteratee call guard.
*
* @private
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function baseSlice(array, start, end) {
var index = -1,
length = array.length;
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = end > length ? length : end;
if (end < 0) {
end += length;
}
length = start > end ? 0 : ((end - start) >>> 0);
start >>>= 0;
var result = Array(length);
while (++index < length) {
result[index] = array[index + start];
}
return result;
}
module.exports = baseSlice;
webpack://frontend-mybets/../../node_modules/lodash/_baseSome.js
var baseEach = require('./_baseEach');
/**
* The base implementation of `_.some` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection 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 baseSome(collection, predicate) {
var result;
baseEach(collection, function(value, index, collection) {
result = predicate(value, index, collection);
return !result;
});
return !!result;
}
module.exports = baseSome;
webpack://frontend-mybets/../../node_modules/lodash/_baseSortBy.js
/**
* The base implementation of `_.sortBy` which uses `comparer` to define the
* sort order of `array` and replaces criteria objects with their corresponding
* values.
*
* @private
* @param {Array} array The array to sort.
* @param {Function} comparer The function to define sort order.
* @returns {Array} Returns `array`.
*/
function baseSortBy(array, comparer) {
var length = array.length;
array.sort(comparer);
while (length--) {
array[length] = array[length].value;
}
return array;
}
module.exports = baseSortBy;
webpack://frontend-mybets/../../node_modules/lodash/_baseTimes.js
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
module.exports = baseTimes;
webpack://frontend-mybets/../../node_modules/lodash/_baseToPairs.js
var arrayMap = require('./_arrayMap');
/**
* The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array
* of key-value pairs for `object` 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 key-value pairs.
*/
function baseToPairs(object, props) {
return arrayMap(props, function(key) {
return [key, object[key]];
});
}
module.exports = baseToPairs;
webpack://frontend-mybets/../../node_modules/lodash/_baseToString.js
var Symbol = require('./_Symbol'),
arrayMap = require('./_arrayMap'),
isArray = require('./isArray'),
isSymbol = require('./isSymbol');
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolToString = symbolProto ? symbolProto.toString : undefined;
/**
* The base implementation of `_.toString` which doesn't convert nullish
* values to empty strings.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
// Exit early for strings to avoid a performance hit in some environments.
if (typeof value == 'string') {
return value;
}
if (isArray(value)) {
// Recursively convert values (susceptible to call stack limits).
return arrayMap(value, baseToString) + '';
}
if (isSymbol(value)) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
module.exports = baseToString;
webpack://frontend-mybets/../../node_modules/lodash/_baseTrim.js
var trimmedEndIndex = require('./_trimmedEndIndex');
/** Used to match leading whitespace. */
var reTrimStart = /^\s+/;
/**
* The base implementation of `_.trim`.
*
* @private
* @param {string} string The string to trim.
* @returns {string} Returns the trimmed string.
*/
function baseTrim(string) {
return string
? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')
: string;
}
module.exports = baseTrim;
webpack://frontend-mybets/../../node_modules/lodash/_baseUnary.js
/**
* The base implementation of `_.unary` without support for storing metadata.
*
* @private
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
*/
function baseUnary(func) {
return function(value) {
return func(value);
};
}
module.exports = baseUnary;
webpack://frontend-mybets/../../node_modules/lodash/_baseUniq.js
var SetCache = require('./_SetCache'),
arrayIncludes = require('./_arrayIncludes'),
arrayIncludesWith = require('./_arrayIncludesWith'),
cacheHas = require('./_cacheHas'),
createSet = require('./_createSet'),
setToArray = require('./_setToArray');
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/**
* The base implementation of `_.uniqBy` without support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new duplicate free array.
*/
function baseUniq(array, iteratee, comparator) {
var index = -1,
includes = arrayIncludes,
length = array.length,
isCommon = true,
result = [],
seen = result;
if (comparator) {
isCommon = false;
includes = arrayIncludesWith;
}
else if (length >= LARGE_ARRAY_SIZE) {
var set = iteratee ? null : createSet(array);
if (set) {
return setToArray(set);
}
isCommon = false;
includes = cacheHas;
seen = new SetCache;
}
else {
seen = iteratee ? [] : result;
}
outer:
while (++index < length) {
var value = array[index],
computed = iteratee ? iteratee(value) : value;
value = (comparator || value !== 0) ? value : 0;
if (isCommon && computed === computed) {
var seenIndex = seen.length;
while (seenIndex--) {
if (seen[seenIndex] === computed) {
continue outer;
}
}
if (iteratee) {
seen.push(computed);
}
result.push(value);
}
else if (!includes(seen, computed, comparator)) {
if (seen !== result) {
seen.push(computed);
}
result.push(value);
}
}
return result;
}
module.exports = baseUniq;
webpack://frontend-mybets/../../node_modules/lodash/_baseUnset.js
var castPath = require('./_castPath'),
last = require('./last'),
parent = require('./_parent'),
toKey = require('./_toKey');
/**
* The base implementation of `_.unset`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The property path to unset.
* @returns {boolean} Returns `true` if the property is deleted, else `false`.
*/
function baseUnset(object, path) {
path = castPath(path, object);
object = parent(object, path);
return object == null || delete object[toKey(last(path))];
}
module.exports = baseUnset;
webpack://frontend-mybets/../../node_modules/lodash/_baseValues.js
var arrayMap = require('./_arrayMap');
/**
* The base implementation of `_.values` and `_.valuesIn` which creates an
* array of `object` property values corresponding to the property names
* of `props`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} props The property names to get values for.
* @returns {Object} Returns the array of property values.
*/
function baseValues(object, props) {
return arrayMap(props, function(key) {
return object[key];
});
}
module.exports = baseValues;
webpack://frontend-mybets/../../node_modules/lodash/_cacheHas.js
/**
* Checks if a `cache` value for `key` exists.
*
* @private
* @param {Object} cache The cache to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function cacheHas(cache, key) {
return cache.has(key);
}
module.exports = cacheHas;
webpack://frontend-mybets/../../node_modules/lodash/_castFunction.js
var identity = require('./identity');
/**
* Casts `value` to `identity` if it's not a function.
*
* @private
* @param {*} value The value to inspect.
* @returns {Function} Returns cast function.
*/
function castFunction(value) {
return typeof value == 'function' ? value : identity;
}
module.exports = castFunction;
webpack://frontend-mybets/../../node_modules/lodash/_castPath.js
var isArray = require('./isArray'),
isKey = require('./_isKey'),
stringToPath = require('./_stringToPath'),
toString = require('./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(value)) {
return value;
}
return isKey(value, object) ? [value] : stringToPath(toString(value));
}
module.exports = castPath;
webpack://frontend-mybets/../../node_modules/lodash/_castSlice.js
var baseSlice = require('./_baseSlice');
/**
* Casts `array` to a slice if it's needed.
*
* @private
* @param {Array} array The array to inspect.
* @param {number} start The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the cast slice.
*/
function castSlice(array, start, end) {
var length = array.length;
end = end === undefined ? length : end;
return (!start && end >= length) ? array : baseSlice(array, start, end);
}
module.exports = castSlice;
webpack://frontend-mybets/../../node_modules/lodash/_charsEndIndex.js
var baseIndexOf = require('./_baseIndexOf');
/**
* Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the last unmatched string symbol.
*/
function charsEndIndex(strSymbols, chrSymbols) {
var index = strSymbols.length;
while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
return index;
}
module.exports = charsEndIndex;
webpack://frontend-mybets/../../node_modules/lodash/_charsStartIndex.js
var baseIndexOf = require('./_baseIndexOf');
/**
* Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the first unmatched string symbol.
*/
function charsStartIndex(strSymbols, chrSymbols) {
var index = -1,
length = strSymbols.length;
while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
return index;
}
module.exports = charsStartIndex;
webpack://frontend-mybets/../../node_modules/lodash/_cloneArrayBuffer.js
var Uint8Array = require('./_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;
}
module.exports = cloneArrayBuffer;
webpack://frontend-mybets/../../node_modules/lodash/_cloneBuffer.js
var root = require('./_root');
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined,
allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;
/**
* Creates a clone of `buffer`.
*
* @private
* @param {Buffer} buffer The buffer to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Buffer} Returns the cloned buffer.
*/
function cloneBuffer(buffer, isDeep) {
if (isDeep) {
return buffer.slice();
}
var length = buffer.length,
result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
buffer.copy(result);
return result;
}
module.exports = cloneBuffer;
webpack://frontend-mybets/../../node_modules/lodash/_cloneDataView.js
var cloneArrayBuffer = require('./_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);
}
module.exports = cloneDataView;
webpack://frontend-mybets/../../node_modules/lodash/_cloneRegExp.js
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/**
* Creates a clone of `regexp`.
*
* @private
* @param {Object} regexp The regexp to clone.
* @returns {Object} Returns the cloned regexp.
*/
function cloneRegExp(regexp) {
var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
result.lastIndex = regexp.lastIndex;
return result;
}
module.exports = cloneRegExp;
webpack://frontend-mybets/../../node_modules/lodash/_cloneSymbol.js
var Symbol = require('./_Symbol');
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* Creates a clone of the `symbol` object.
*
* @private
* @param {Object} symbol The symbol object to clone.
* @returns {Object} Returns the cloned symbol object.
*/
function cloneSymbol(symbol) {
return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
module.exports = cloneSymbol;
webpack://frontend-mybets/../../node_modules/lodash/_cloneTypedArray.js
var cloneArrayBuffer = require('./_cloneArrayBuffer');
/**
* Creates a clone of `typedArray`.
*
* @private
* @param {Object} typedArray The typed array to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned typed array.
*/
function cloneTypedArray(typedArray, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
module.exports = cloneTypedArray;
webpack://frontend-mybets/../../node_modules/lodash/_compareAscending.js
var isSymbol = require('./isSymbol');
/**
* Compares values to sort them in ascending order.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {number} Returns the sort order indicator for `value`.
*/
function compareAscending(value, other) {
if (value !== other) {
var valIsDefined = value !== undefined,
valIsNull = value === null,
valIsReflexive = value === value,
valIsSymbol = isSymbol(value);
var othIsDefined = other !== undefined,
othIsNull = other === null,
othIsReflexive = other === other,
othIsSymbol = isSymbol(other);
if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
(valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||
(valIsNull && othIsDefined && othIsReflexive) ||
(!valIsDefined && othIsReflexive) ||
!valIsReflexive) {
return 1;
}
if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
(othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||
(othIsNull && valIsDefined && valIsReflexive) ||
(!othIsDefined && valIsReflexive) ||
!othIsReflexive) {
return -1;
}
}
return 0;
}
module.exports = compareAscending;
webpack://frontend-mybets/../../node_modules/lodash/_compareMultiple.js
var compareAscending = require('./_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;
}
module.exports = compareMultiple;
webpack://frontend-mybets/../../node_modules/lodash/_composeArgs.js
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates an array that is the composition of partially applied arguments,
* placeholders, and provided arguments into a single array of arguments.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to prepend to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgs(args, partials, holders, isCurried) {
var argsIndex = -1,
argsLength = args.length,
holdersLength = holders.length,
leftIndex = -1,
leftLength = partials.length,
rangeLength = nativeMax(argsLength - holdersLength, 0),
result = Array(leftLength + rangeLength),
isUncurried = !isCurried;
while (++leftIndex < leftLength) {
result[leftIndex] = partials[leftIndex];
}
while (++argsIndex < holdersLength) {
if (isUncurried || argsIndex < argsLength) {
result[holders[argsIndex]] = args[argsIndex];
}
}
while (rangeLength--) {
result[leftIndex++] = args[argsIndex++];
}
return result;
}
module.exports = composeArgs;
webpack://frontend-mybets/../../node_modules/lodash/_composeArgsRight.js
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* This function is like `composeArgs` except that the arguments composition
* is tailored for `_.partialRight`.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to append to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgsRight(args, partials, holders, isCurried) {
var argsIndex = -1,
argsLength = args.length,
holdersIndex = -1,
holdersLength = holders.length,
rightIndex = -1,
rightLength = partials.length,
rangeLength = nativeMax(argsLength - holdersLength, 0),
result = Array(rangeLength + rightLength),
isUncurried = !isCurried;
while (++argsIndex < rangeLength) {
result[argsIndex] = args[argsIndex];
}
var offset = argsIndex;
while (++rightIndex < rightLength) {
result[offset + rightIndex] = partials[rightIndex];
}
while (++holdersIndex < holdersLength) {
if (isUncurried || argsIndex < argsLength) {
result[offset + holders[holdersIndex]] = args[argsIndex++];
}
}
return result;
}
module.exports = composeArgsRight;
webpack://frontend-mybets/../../node_modules/lodash/_copyArray.js
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function copyArray(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
module.exports = copyArray;
webpack://frontend-mybets/../../node_modules/lodash/_copyObject.js
var assignValue = require('./_assignValue'),
baseAssignValue = require('./_baseAssignValue');
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property identifiers to copy.
* @param {Object} [object={}] The object to copy properties to.
* @param {Function} [customizer] The function to customize copied values.
* @returns {Object} Returns `object`.
*/
function copyObject(source, props, object, customizer) {
var isNew = !object;
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
var newValue = customizer
? customizer(object[key], source[key], key, object, source)
: undefined;
if (newValue === undefined) {
newValue = source[key];
}
if (isNew) {
baseAssignValue(object, key, newValue);
} else {
assignValue(object, key, newValue);
}
}
return object;
}
module.exports = copyObject;
webpack://frontend-mybets/../../node_modules/lodash/_copySymbols.js
var copyObject = require('./_copyObject'),
getSymbols = require('./_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);
}
module.exports = copySymbols;
webpack://frontend-mybets/../../node_modules/lodash/_copySymbolsIn.js
var copyObject = require('./_copyObject'),
getSymbolsIn = require('./_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);
}
module.exports = copySymbolsIn;
webpack://frontend-mybets/../../node_modules/lodash/_coreJsData.js
var root = require('./_root');
/** Used to detect overreaching core-js shims. */
var coreJsData = root['__core-js_shared__'];
module.exports = coreJsData;
webpack://frontend-mybets/../../node_modules/lodash/_countHolders.js
/**
* Gets the number of `placeholder` occurrences in `array`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} placeholder The placeholder to search for.
* @returns {number} Returns the placeholder count.
*/
function countHolders(array, placeholder) {
var length = array.length,
result = 0;
while (length--) {
if (array[length] === placeholder) {
++result;
}
}
return result;
}
module.exports = countHolders;
webpack://frontend-mybets/../../node_modules/lodash/_createAssigner.js
var baseRest = require('./_baseRest'),
isIterateeCall = require('./_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;
});
}
module.exports = createAssigner;
webpack://frontend-mybets/../../node_modules/lodash/_createBaseEach.js
var isArrayLike = require('./isArrayLike');
/**
* Creates a `baseEach` or `baseEachRight` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
if (collection == null) {
return collection;
}
if (!isArrayLike(collection)) {
return eachFunc(collection, iteratee);
}
var length = collection.length,
index = fromRight ? length : -1,
iterable = Object(collection);
while ((fromRight ? index-- : ++index < length)) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
};
}
module.exports = createBaseEach;
webpack://frontend-mybets/../../node_modules/lodash/_createBaseFor.js
/**
* Creates a base function for methods like `_.forIn` and `_.forOwn`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var index = -1,
iterable = Object(object),
props = keysFunc(object),
length = props.length;
while (length--) {
var key = props[fromRight ? length : ++index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
module.exports = createBaseFor;
webpack://frontend-mybets/../../node_modules/lodash/_createBind.js
var createCtor = require('./_createCtor'),
root = require('./_root');
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1;
/**
* Creates a function that wraps `func` to invoke it with the optional `this`
* binding of `thisArg`.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createBind(func, bitmask, thisArg) {
var isBind = bitmask & WRAP_BIND_FLAG,
Ctor = createCtor(func);
function wrapper() {
var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
return fn.apply(isBind ? thisArg : this, arguments);
}
return wrapper;
}
module.exports = createBind;
webpack://frontend-mybets/../../node_modules/lodash/_createCaseFirst.js
var castSlice = require('./_castSlice'),
hasUnicode = require('./_hasUnicode'),
stringToArray = require('./_stringToArray'),
toString = require('./toString');
/**
* Creates a function like `_.lowerFirst`.
*
* @private
* @param {string} methodName The name of the `String` case method to use.
* @returns {Function} Returns the new case function.
*/
function createCaseFirst(methodName) {
return function(string) {
string = toString(string);
var strSymbols = hasUnicode(string)
? stringToArray(string)
: undefined;
var chr = strSymbols
? strSymbols[0]
: string.charAt(0);
var trailing = strSymbols
? castSlice(strSymbols, 1).join('')
: string.slice(1);
return chr[methodName]() + trailing;
};
}
module.exports = createCaseFirst;
webpack://frontend-mybets/../../node_modules/lodash/_createCompounder.js
var arrayReduce = require('./_arrayReduce'),
deburr = require('./deburr'),
words = require('./words');
/** Used to compose unicode capture groups. */
var rsApos = "['\u2019]";
/** Used to match apostrophes. */
var reApos = RegExp(rsApos, 'g');
/**
* Creates a function like `_.camelCase`.
*
* @private
* @param {Function} callback The function to combine each word.
* @returns {Function} Returns the new compounder function.
*/
function createCompounder(callback) {
return function(string) {
return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
};
}
module.exports = createCompounder;
webpack://frontend-mybets/../../node_modules/lodash/_createCtor.js
var baseCreate = require('./_baseCreate'),
isObject = require('./isObject');
/**
* Creates a function that produces an instance of `Ctor` regardless of
* whether it was invoked as part of a `new` expression or by `call` or `apply`.
*
* @private
* @param {Function} Ctor The constructor to wrap.
* @returns {Function} Returns the new wrapped function.
*/
function createCtor(Ctor) {
return function() {
// Use a `switch` statement to work with class constructors. See
// http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
// for more details.
var args = arguments;
switch (args.length) {
case 0: return new Ctor;
case 1: return new Ctor(args[0]);
case 2: return new Ctor(args[0], args[1]);
case 3: return new Ctor(args[0], args[1], args[2]);
case 4: return new Ctor(args[0], args[1], args[2], args[3]);
case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
}
var thisBinding = baseCreate(Ctor.prototype),
result = Ctor.apply(thisBinding, args);
// Mimic the constructor's `return` behavior.
// See https://es5.github.io/#x13.2.2 for more details.
return isObject(result) ? result : thisBinding;
};
}
module.exports = createCtor;
webpack://frontend-mybets/../../node_modules/lodash/_createCurry.js
var apply = require('./_apply'),
createCtor = require('./_createCtor'),
createHybrid = require('./_createHybrid'),
createRecurry = require('./_createRecurry'),
getHolder = require('./_getHolder'),
replaceHolders = require('./_replaceHolders'),
root = require('./_root');
/**
* Creates a function that wraps `func` to enable currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {number} arity The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createCurry(func, bitmask, arity) {
var Ctor = createCtor(func);
function wrapper() {
var length = arguments.length,
args = Array(length),
index = length,
placeholder = getHolder(wrapper);
while (index--) {
args[index] = arguments[index];
}
var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
? []
: replaceHolders(args, placeholder);
length -= holders.length;
if (length < arity) {
return createRecurry(
func, bitmask, createHybrid, wrapper.placeholder, undefined,
args, holders, undefined, undefined, arity - length);
}
var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
return apply(fn, this, args);
}
return wrapper;
}
module.exports = createCurry;
webpack://frontend-mybets/../../node_modules/lodash/_createFind.js
var baseIteratee = require('./_baseIteratee'),
isArrayLike = require('./isArrayLike'),
keys = require('./keys');
/**
* Creates a `_.find` or `_.findLast` function.
*
* @private
* @param {Function} findIndexFunc The function to find the collection index.
* @returns {Function} Returns the new find function.
*/
function createFind(findIndexFunc) {
return function(collection, predicate, fromIndex) {
var iterable = Object(collection);
if (!isArrayLike(collection)) {
var iteratee = baseIteratee(predicate, 3);
collection = keys(collection);
predicate = function(key) { return iteratee(iterable[key], key, iterable); };
}
var index = findIndexFunc(collection, predicate, fromIndex);
return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
};
}
module.exports = createFind;
webpack://frontend-mybets/../../node_modules/lodash/_createFlow.js
var LodashWrapper = require('./_LodashWrapper'),
flatRest = require('./_flatRest'),
getData = require('./_getData'),
getFuncName = require('./_getFuncName'),
isArray = require('./isArray'),
isLaziable = require('./_isLaziable');
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/** Used to compose bitmasks for function metadata. */
var WRAP_CURRY_FLAG = 8,
WRAP_PARTIAL_FLAG = 32,
WRAP_ARY_FLAG = 128,
WRAP_REARG_FLAG = 256;
/**
* Creates a `_.flow` or `_.flowRight` function.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new flow function.
*/
function createFlow(fromRight) {
return flatRest(function(funcs) {
var length = funcs.length,
index = length,
prereq = LodashWrapper.prototype.thru;
if (fromRight) {
funcs.reverse();
}
while (index--) {
var func = funcs[index];
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
if (prereq && !wrapper && getFuncName(func) == 'wrapper') {
var wrapper = new LodashWrapper([], true);
}
}
index = wrapper ? index : length;
while (++index < length) {
func = funcs[index];
var funcName = getFuncName(func),
data = funcName == 'wrapper' ? getData(func) : undefined;
if (data && isLaziable(data[0]) &&
data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) &&
!data[4].length && data[9] == 1
) {
wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);
} else {
wrapper = (func.length == 1 && isLaziable(func))
? wrapper[funcName]()
: wrapper.thru(func);
}
}
return function() {
var args = arguments,
value = args[0];
if (wrapper && args.length == 1 && isArray(value)) {
return wrapper.plant(value).value();
}
var index = 0,
result = length ? funcs[index].apply(this, args) : value;
while (++index < length) {
result = funcs[index].call(this, result);
}
return result;
};
});
}
module.exports = createFlow;
webpack://frontend-mybets/../../node_modules/lodash/_createHybrid.js
var composeArgs = require('./_composeArgs'),
composeArgsRight = require('./_composeArgsRight'),
countHolders = require('./_countHolders'),
createCtor = require('./_createCtor'),
createRecurry = require('./_createRecurry'),
getHolder = require('./_getHolder'),
reorder = require('./_reorder'),
replaceHolders = require('./_replaceHolders'),
root = require('./_root');
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_FLAG = 8,
WRAP_CURRY_RIGHT_FLAG = 16,
WRAP_ARY_FLAG = 128,
WRAP_FLIP_FLAG = 512;
/**
* Creates a function that wraps `func` to invoke it with optional `this`
* binding of `thisArg`, partial application, and currying.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [partialsRight] The arguments to append to those provided
* to the new function.
* @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
var isAry = bitmask & WRAP_ARY_FLAG,
isBind = bitmask & WRAP_BIND_FLAG,
isBindKey = bitmask & WRAP_BIND_KEY_FLAG,
isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG),
isFlip = bitmask & WRAP_FLIP_FLAG,
Ctor = isBindKey ? undefined : createCtor(func);
function wrapper() {
var length = arguments.length,
args = Array(length),
index = length;
while (index--) {
args[index] = arguments[index];
}
if (isCurried) {
var placeholder = getHolder(wrapper),
holdersCount = countHolders(args, placeholder);
}
if (partials) {
args = composeArgs(args, partials, holders, isCurried);
}
if (partialsRight) {
args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
}
length -= holdersCount;
if (isCurried && length < arity) {
var newHolders = replaceHolders(args, placeholder);
return createRecurry(
func, bitmask, createHybrid, wrapper.placeholder, thisArg,
args, newHolders, argPos, ary, arity - length
);
}
var thisBinding = isBind ? thisArg : this,
fn = isBindKey ? thisBinding[func] : func;
length = args.length;
if (argPos) {
args = reorder(args, argPos);
} else if (isFlip && length > 1) {
args.reverse();
}
if (isAry && ary < length) {
args.length = ary;
}
if (this && this !== root && this instanceof wrapper) {
fn = Ctor || createCtor(fn);
}
return fn.apply(thisBinding, args);
}
return wrapper;
}
module.exports = createHybrid;
webpack://frontend-mybets/../../node_modules/lodash/_createPartial.js
var apply = require('./_apply'),
createCtor = require('./_createCtor'),
root = require('./_root');
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1;
/**
* Creates a function that wraps `func` to invoke it with the `this` binding
* of `thisArg` and `partials` prepended to the arguments it receives.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} partials The arguments to prepend to those provided to
* the new function.
* @returns {Function} Returns the new wrapped function.
*/
function createPartial(func, bitmask, thisArg, partials) {
var isBind = bitmask & WRAP_BIND_FLAG,
Ctor = createCtor(func);
function wrapper() {
var argsIndex = -1,
argsLength = arguments.length,
leftIndex = -1,
leftLength = partials.length,
args = Array(leftLength + argsLength),
fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
while (++leftIndex < leftLength) {
args[leftIndex] = partials[leftIndex];
}
while (argsLength--) {
args[leftIndex++] = arguments[++argsIndex];
}
return apply(fn, isBind ? thisArg : this, args);
}
return wrapper;
}
module.exports = createPartial;
webpack://frontend-mybets/../../node_modules/lodash/_createRange.js
var baseRange = require('./_baseRange'),
isIterateeCall = require('./_isIterateeCall'),
toFinite = require('./toFinite');
/**
* Creates a `_.range` or `_.rangeRight` function.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new range function.
*/
function createRange(fromRight) {
return function(start, end, step) {
if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {
end = step = undefined;
}
// Ensure the sign of `-0` is preserved.
start = toFinite(start);
if (end === undefined) {
end = start;
start = 0;
} else {
end = toFinite(end);
}
step = step === undefined ? (start < end ? 1 : -1) : toFinite(step);
return baseRange(start, end, step, fromRight);
};
}
module.exports = createRange;
webpack://frontend-mybets/../../node_modules/lodash/_createRecurry.js
var isLaziable = require('./_isLaziable'),
setData = require('./_setData'),
setWrapToString = require('./_setWrapToString');
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_BOUND_FLAG = 4,
WRAP_CURRY_FLAG = 8,
WRAP_PARTIAL_FLAG = 32,
WRAP_PARTIAL_RIGHT_FLAG = 64;
/**
* Creates a function that wraps `func` to continue currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {Function} wrapFunc The function to create the `func` wrapper.
* @param {*} placeholder The placeholder value.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
var isCurry = bitmask & WRAP_CURRY_FLAG,
newHolders = isCurry ? holders : undefined,
newHoldersRight = isCurry ? undefined : holders,
newPartials = isCurry ? partials : undefined,
newPartialsRight = isCurry ? undefined : partials;
bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG);
bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);
if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {
bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);
}
var newData = [
func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
newHoldersRight, argPos, ary, arity
];
var result = wrapFunc.apply(undefined, newData);
if (isLaziable(func)) {
setData(result, newData);
}
result.placeholder = placeholder;
return setWrapToString(result, func, bitmask);
}
module.exports = createRecurry;
webpack://frontend-mybets/../../node_modules/lodash/_createSet.js
var Set = require('./_Set'),
noop = require('./noop'),
setToArray = require('./_setToArray');
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/**
* Creates a set object of `values`.
*
* @private
* @param {Array} values The values to add to the set.
* @returns {Object} Returns the new set.
*/
var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {
return new Set(values);
};
module.exports = createSet;
webpack://frontend-mybets/../../node_modules/lodash/_createToPairs.js
var baseToPairs = require('./_baseToPairs'),
getTag = require('./_getTag'),
mapToArray = require('./_mapToArray'),
setToPairs = require('./_setToPairs');
/** `Object#toString` result references. */
var mapTag = '[object Map]',
setTag = '[object Set]';
/**
* Creates a `_.toPairs` or `_.toPairsIn` function.
*
* @private
* @param {Function} keysFunc The function to get the keys of a given object.
* @returns {Function} Returns the new pairs function.
*/
function createToPairs(keysFunc) {
return function(object) {
var tag = getTag(object);
if (tag == mapTag) {
return mapToArray(object);
}
if (tag == setTag) {
return setToPairs(object);
}
return baseToPairs(object, keysFunc(object));
};
}
module.exports = createToPairs;
webpack://frontend-mybets/../../node_modules/lodash/_createWrap.js
var baseSetData = require('./_baseSetData'),
createBind = require('./_createBind'),
createCurry = require('./_createCurry'),
createHybrid = require('./_createHybrid'),
createPartial = require('./_createPartial'),
getData = require('./_getData'),
mergeData = require('./_mergeData'),
setData = require('./_setData'),
setWrapToString = require('./_setWrapToString'),
toInteger = require('./toInteger');
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_FLAG = 8,
WRAP_CURRY_RIGHT_FLAG = 16,
WRAP_PARTIAL_FLAG = 32,
WRAP_PARTIAL_RIGHT_FLAG = 64;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates a function that either curries or invokes `func` with optional
* `this` binding and partially applied arguments.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags.
* 1 - `_.bind`
* 2 - `_.bindKey`
* 4 - `_.curry` or `_.curryRight` of a bound function
* 8 - `_.curry`
* 16 - `_.curryRight`
* 32 - `_.partial`
* 64 - `_.partialRight`
* 128 - `_.rearg`
* 256 - `_.ary`
* 512 - `_.flip`
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to be partially applied.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;
if (!isBindKey && typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
var length = partials ? partials.length : 0;
if (!length) {
bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);
partials = holders = undefined;
}
ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);
arity = arity === undefined ? arity : toInteger(arity);
length -= holders ? holders.length : 0;
if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
var partialsRight = partials,
holdersRight = holders;
partials = holders = undefined;
}
var data = isBindKey ? undefined : getData(func);
var newData = [
func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
argPos, ary, arity
];
if (data) {
mergeData(newData, data);
}
func = newData[0];
bitmask = newData[1];
thisArg = newData[2];
partials = newData[3];
holders = newData[4];
arity = newData[9] = newData[9] === undefined
? (isBindKey ? 0 : func.length)
: nativeMax(newData[9] - length, 0);
if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
}
if (!bitmask || bitmask == WRAP_BIND_FLAG) {
var result = createBind(func, bitmask, thisArg);
} else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
result = createCurry(func, bitmask, arity);
} else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {
result = createPartial(func, bitmask, thisArg, partials);
} else {
result = createHybrid.apply(undefined, newData);
}
var setter = data ? baseSetData : setData;
return setWrapToString(setter(result, newData), func, bitmask);
}
module.exports = createWrap;
webpack://frontend-mybets/../../node_modules/lodash/_customOmitClone.js
var isPlainObject = require('./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(value) ? undefined : value;
}
module.exports = customOmitClone;
webpack://frontend-mybets/../../node_modules/lodash/_deburrLetter.js
var basePropertyOf = require('./_basePropertyOf');
/** Used to map Latin Unicode letters to basic Latin letters. */
var deburredLetters = {
// Latin-1 Supplement block.
'\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
'\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
'\xc7': 'C', '\xe7': 'c',
'\xd0': 'D', '\xf0': 'd',
'\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
'\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
'\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
'\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
'\xd1': 'N', '\xf1': 'n',
'\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
'\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
'\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
'\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
'\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
'\xc6': 'Ae', '\xe6': 'ae',
'\xde': 'Th', '\xfe': 'th',
'\xdf': 'ss',
// Latin Extended-A block.
'\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
'\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
'\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
'\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
'\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
'\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
'\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
'\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
'\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
'\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
'\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
'\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
'\u0134': 'J', '\u0135': 'j',
'\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
'\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
'\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
'\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
'\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
'\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
'\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
'\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
'\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
'\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
'\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
'\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
'\u0163': 't', '\u0165': 't', '\u0167': 't',
'\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
'\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
'\u0174': 'W', '\u0175': 'w',
'\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
'\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
'\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
'\u0132': 'IJ', '\u0133': 'ij',
'\u0152': 'Oe', '\u0153': 'oe',
'\u0149': "'n", '\u017f': 's'
};
/**
* Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
* letters to basic Latin letters.
*
* @private
* @param {string} letter The matched letter to deburr.
* @returns {string} Returns the deburred letter.
*/
var deburrLetter = basePropertyOf(deburredLetters);
module.exports = deburrLetter;
webpack://frontend-mybets/../../node_modules/lodash/_defineProperty.js
var getNative = require('./_getNative');
var defineProperty = (function() {
try {
var func = getNative(Object, 'defineProperty');
func({}, '', {});
return func;
} catch (e) {}
}());
module.exports = defineProperty;
webpack://frontend-mybets/../../node_modules/lodash/_equalArrays.js
var SetCache = require('./_SetCache'),
arraySome = require('./_arraySome'),
cacheHas = require('./_cacheHas');
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `array` and `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
arrLength = array.length,
othLength = other.length;
if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
return false;
}
// Check that cyclic values are equal.
var arrStacked = stack.get(array);
var othStacked = stack.get(other);
if (arrStacked && othStacked) {
return arrStacked == other && othStacked == array;
}
var index = -1,
result = true,
seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;
stack.set(array, other);
stack.set(other, array);
// Ignore non-index properties.
while (++index < arrLength) {
var arrValue = array[index],
othValue = other[index];
if (customizer) {
var compared = isPartial
? customizer(othValue, arrValue, index, other, array, stack)
: customizer(arrValue, othValue, index, array, other, stack);
}
if (compared !== undefined) {
if (compared) {
continue;
}
result = false;
break;
}
// Recursively compare arrays (susceptible to call stack limits).
if (seen) {
if (!arraySome(other, function(othValue, othIndex) {
if (!cacheHas(seen, othIndex) &&
(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
return seen.push(othIndex);
}
})) {
result = false;
break;
}
} else if (!(
arrValue === othValue ||
equalFunc(arrValue, othValue, bitmask, customizer, stack)
)) {
result = false;
break;
}
}
stack['delete'](array);
stack['delete'](other);
return result;
}
module.exports = equalArrays;
webpack://frontend-mybets/../../node_modules/lodash/_equalByTag.js
var Symbol = require('./_Symbol'),
Uint8Array = require('./_Uint8Array'),
eq = require('./eq'),
equalArrays = require('./_equalArrays'),
mapToArray = require('./_mapToArray'),
setToArray = require('./_setToArray');
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/** `Object#toString` result references. */
var boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
mapTag = '[object Map]',
numberTag = '[object Number]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]';
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
switch (tag) {
case dataViewTag:
if ((object.byteLength != other.byteLength) ||
(object.byteOffset != other.byteOffset)) {
return false;
}
object = object.buffer;
other = other.buffer;
case arrayBufferTag:
if ((object.byteLength != other.byteLength) ||
!equalFunc(new Uint8Array(object), new Uint8Array(other))) {
return false;
}
return true;
case boolTag:
case dateTag:
case numberTag:
// Coerce booleans to `1` or `0` and dates to milliseconds.
// Invalid dates are coerced to `NaN`.
return eq(+object, +other);
case errorTag:
return object.name == other.name && object.message == other.message;
case regexpTag:
case stringTag:
// Coerce regexes to strings and treat strings, primitives and objects,
// as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
// for more details.
return object == (other + '');
case mapTag:
var convert = mapToArray;
case setTag:
var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
convert || (convert = setToArray);
if (object.size != other.size && !isPartial) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
bitmask |= COMPARE_UNORDERED_FLAG;
// Recursively compare objects (susceptible to call stack limits).
stack.set(object, other);
var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
stack['delete'](object);
return result;
case symbolTag:
if (symbolValueOf) {
return symbolValueOf.call(object) == symbolValueOf.call(other);
}
}
return false;
}
module.exports = equalByTag;
webpack://frontend-mybets/../../node_modules/lodash/_equalObjects.js
var getAllKeys = require('./_getAllKeys');
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1;
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
objProps = getAllKeys(object),
objLength = objProps.length,
othProps = getAllKeys(other),
othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
return false;
}
}
// Check that cyclic values are equal.
var objStacked = stack.get(object);
var othStacked = stack.get(other);
if (objStacked && othStacked) {
return objStacked == other && othStacked == object;
}
var result = true;
stack.set(object, other);
stack.set(other, object);
var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
othValue = other[key];
if (customizer) {
var compared = isPartial
? customizer(othValue, objValue, key, other, object, stack)
: customizer(objValue, othValue, key, object, other, stack);
}
// Recursively compare objects (susceptible to call stack limits).
if (!(compared === undefined
? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
: compared
)) {
result = false;
break;
}
skipCtor || (skipCtor = key == 'constructor');
}
if (result && !skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
result = false;
}
}
stack['delete'](object);
stack['delete'](other);
return result;
}
module.exports = equalObjects;
webpack://frontend-mybets/../../node_modules/lodash/_flatRest.js
var flatten = require('./flatten'),
overRest = require('./_overRest'),
setToString = require('./_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), func + '');
}
module.exports = flatRest;
webpack://frontend-mybets/../../node_modules/lodash/_freeGlobal.js
/** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; module.exports = freeGlobal;
webpack://frontend-mybets/../../node_modules/lodash/_getAllKeys.js
var baseGetAllKeys = require('./_baseGetAllKeys'),
getSymbols = require('./_getSymbols'),
keys = require('./keys');
/**
* Creates an array of own enumerable property names and symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeys(object) {
return baseGetAllKeys(object, keys, getSymbols);
}
module.exports = getAllKeys;
webpack://frontend-mybets/../../node_modules/lodash/_getAllKeysIn.js
var baseGetAllKeys = require('./_baseGetAllKeys'),
getSymbolsIn = require('./_getSymbolsIn'),
keysIn = require('./keysIn');
/**
* Creates an array of own and inherited enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeysIn(object) {
return baseGetAllKeys(object, keysIn, getSymbolsIn);
}
module.exports = getAllKeysIn;
webpack://frontend-mybets/../../node_modules/lodash/_getData.js
var metaMap = require('./_metaMap'),
noop = require('./noop');
/**
* Gets metadata for `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {*} Returns the metadata for `func`.
*/
var getData = !metaMap ? noop : function(func) {
return metaMap.get(func);
};
module.exports = getData;
webpack://frontend-mybets/../../node_modules/lodash/_getFuncName.js
var realNames = require('./_realNames');
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Gets the name of `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {string} Returns the function name.
*/
function getFuncName(func) {
var result = (func.name + ''),
array = realNames[result],
length = hasOwnProperty.call(realNames, result) ? array.length : 0;
while (length--) {
var data = array[length],
otherFunc = data.func;
if (otherFunc == null || otherFunc == func) {
return data.name;
}
}
return result;
}
module.exports = getFuncName;
webpack://frontend-mybets/../../node_modules/lodash/_getHolder.js
/**
* Gets the argument placeholder value for `func`.
*
* @private
* @param {Function} func The function to inspect.
* @returns {*} Returns the placeholder value.
*/
function getHolder(func) {
var object = func;
return object.placeholder;
}
module.exports = getHolder;
webpack://frontend-mybets/../../node_modules/lodash/_getMapData.js
var isKeyable = require('./_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;
}
module.exports = getMapData;
webpack://frontend-mybets/../../node_modules/lodash/_getMatchData.js
var isStrictComparable = require('./_isStrictComparable'),
keys = require('./keys');
/**
* Gets the property names, values, and compare flags of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the match data of `object`.
*/
function getMatchData(object) {
var result = keys(object),
length = result.length;
while (length--) {
var key = result[length],
value = object[key];
result[length] = [key, value, isStrictComparable(value)];
}
return result;
}
module.exports = getMatchData;
webpack://frontend-mybets/../../node_modules/lodash/_getNative.js
var baseIsNative = require('./_baseIsNative'),
getValue = require('./_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;
}
module.exports = getNative;
webpack://frontend-mybets/../../node_modules/lodash/_getPrototype.js
var overArg = require('./_overArg');
/** Built-in value references. */
var getPrototype = overArg(Object.getPrototypeOf, Object);
module.exports = getPrototype;
webpack://frontend-mybets/../../node_modules/lodash/_getRawTag.js
var Symbol = require('./_Symbol');
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag),
tag = value[symToStringTag];
try {
value[symToStringTag] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
module.exports = getRawTag;
webpack://frontend-mybets/../../node_modules/lodash/_getSymbols.js
var arrayFilter = require('./_arrayFilter'),
stubArray = require('./stubArray');
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;
/**
* Creates an array of the own enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
if (object == null) {
return [];
}
object = Object(object);
return arrayFilter(nativeGetSymbols(object), function(symbol) {
return propertyIsEnumerable.call(object, symbol);
});
};
module.exports = getSymbols;
webpack://frontend-mybets/../../node_modules/lodash/_getSymbolsIn.js
var arrayPush = require('./_arrayPush'),
getPrototype = require('./_getPrototype'),
getSymbols = require('./_getSymbols'),
stubArray = require('./stubArray');
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;
/**
* Creates an array of the own and inherited enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {
var result = [];
while (object) {
arrayPush(result, getSymbols(object));
object = getPrototype(object);
}
return result;
};
module.exports = getSymbolsIn;
webpack://frontend-mybets/../../node_modules/lodash/_getTag.js
var DataView = require('./_DataView'),
Map = require('./_Map'),
Promise = require('./_Promise'),
Set = require('./_Set'),
WeakMap = require('./_WeakMap'),
baseGetTag = require('./_baseGetTag'),
toSource = require('./_toSource');
/** `Object#toString` result references. */
var mapTag = '[object Map]',
objectTag = '[object Object]',
promiseTag = '[object Promise]',
setTag = '[object Set]',
weakMapTag = '[object WeakMap]';
var dataViewTag = '[object DataView]';
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
mapCtorString = toSource(Map),
promiseCtorString = toSource(Promise),
setCtorString = toSource(Set),
weakMapCtorString = toSource(WeakMap);
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
var getTag = baseGetTag;
// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
(Map && getTag(new Map) != mapTag) ||
(Promise && getTag(Promise.resolve()) != promiseTag) ||
(Set && getTag(new Set) != setTag) ||
(WeakMap && getTag(new WeakMap) != weakMapTag)) {
getTag = function(value) {
var result = baseGetTag(value),
Ctor = result == objectTag ? value.constructor : undefined,
ctorString = Ctor ? toSource(Ctor) : '';
if (ctorString) {
switch (ctorString) {
case dataViewCtorString: return dataViewTag;
case mapCtorString: return mapTag;
case promiseCtorString: return promiseTag;
case setCtorString: return setTag;
case weakMapCtorString: return weakMapTag;
}
}
return result;
};
}
module.exports = getTag;
webpack://frontend-mybets/../../node_modules/lodash/_getValue.js
/**
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function getValue(object, key) {
return object == null ? undefined : object[key];
}
module.exports = getValue;
webpack://frontend-mybets/../../node_modules/lodash/_getWrapDetails.js
/** Used to match wrap detail comments. */
var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
reSplitDetails = /,? & /;
/**
* Extracts wrapper details from the `source` body comment.
*
* @private
* @param {string} source The source to inspect.
* @returns {Array} Returns the wrapper details.
*/
function getWrapDetails(source) {
var match = source.match(reWrapDetails);
return match ? match[1].split(reSplitDetails) : [];
}
module.exports = getWrapDetails;
webpack://frontend-mybets/../../node_modules/lodash/_hasPath.js
var castPath = require('./_castPath'),
isArguments = require('./isArguments'),
isArray = require('./isArray'),
isIndex = require('./_isIndex'),
isLength = require('./isLength'),
toKey = require('./_toKey');
/**
* Checks if `path` exists on `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @param {Function} hasFunc The function to check properties.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
*/
function hasPath(object, path, hasFunc) {
path = castPath(path, object);
var index = -1,
length = path.length,
result = false;
while (++index < length) {
var key = toKey(path[index]);
if (!(result = object != null && hasFunc(object, key))) {
break;
}
object = object[key];
}
if (result || ++index != length) {
return result;
}
length = object == null ? 0 : object.length;
return !!length && isLength(length) && isIndex(key, length) &&
(isArray(object) || isArguments(object));
}
module.exports = hasPath;
webpack://frontend-mybets/../../node_modules/lodash/_hasUnicode.js
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
rsComboMarksRange = '\\u0300-\\u036f',
reComboHalfMarksRange = '\\ufe20-\\ufe2f',
rsComboSymbolsRange = '\\u20d0-\\u20ff',
rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
rsVarRange = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */
var rsZWJ = '\\u200d';
/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');
/**
* Checks if `string` contains Unicode symbols.
*
* @private
* @param {string} string The string to inspect.
* @returns {boolean} Returns `true` if a symbol is found, else `false`.
*/
function hasUnicode(string) {
return reHasUnicode.test(string);
}
module.exports = hasUnicode;
webpack://frontend-mybets/../../node_modules/lodash/_hasUnicodeWord.js
/** Used to detect strings that need a more robust regexp to match words. */
var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
/**
* Checks if `string` contains a word composed of Unicode symbols.
*
* @private
* @param {string} string The string to inspect.
* @returns {boolean} Returns `true` if a word is found, else `false`.
*/
function hasUnicodeWord(string) {
return reHasUnicodeWord.test(string);
}
module.exports = hasUnicodeWord;
webpack://frontend-mybets/../../node_modules/lodash/_hashClear.js
var nativeCreate = require('./_nativeCreate');
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear() {
this.__data__ = nativeCreate ? nativeCreate(null) : {};
this.size = 0;
}
module.exports = hashClear;
webpack://frontend-mybets/../../node_modules/lodash/_hashDelete.js
/**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
this.size -= result ? 1 : 0;
return result;
}
module.exports = hashDelete;
webpack://frontend-mybets/../../node_modules/lodash/_hashGet.js
var nativeCreate = require('./_nativeCreate');
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(key) {
var data = this.__data__;
if (nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty.call(data, key) ? data[key] : undefined;
}
module.exports = hashGet;
webpack://frontend-mybets/../../node_modules/lodash/_hashHas.js
var nativeCreate = require('./_nativeCreate');
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(key) {
var data = this.__data__;
return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
}
module.exports = hashHas;
webpack://frontend-mybets/../../node_modules/lodash/_hashSet.js
var nativeCreate = require('./_nativeCreate');
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/
function hashSet(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
return this;
}
module.exports = hashSet;
webpack://frontend-mybets/../../node_modules/lodash/_initCloneArray.js
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Initializes an array clone.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the initialized clone.
*/
function initCloneArray(array) {
var length = array.length,
result = new array.constructor(length);
// Add properties assigned by `RegExp#exec`.
if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
result.index = array.index;
result.input = array.input;
}
return result;
}
module.exports = initCloneArray;
webpack://frontend-mybets/../../node_modules/lodash/_initCloneByTag.js
var cloneArrayBuffer = require('./_cloneArrayBuffer'),
cloneDataView = require('./_cloneDataView'),
cloneRegExp = require('./_cloneRegExp'),
cloneSymbol = require('./_cloneSymbol'),
cloneTypedArray = require('./_cloneTypedArray');
/** `Object#toString` result references. */
var boolTag = '[object Boolean]',
dateTag = '[object Date]',
mapTag = '[object Map]',
numberTag = '[object Number]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/**
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
*
* @private
* @param {Object} object The object to clone.
* @param {string} tag The `toStringTag` of the object to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneByTag(object, tag, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag:
return cloneArrayBuffer(object);
case boolTag:
case dateTag:
return new Ctor(+object);
case dataViewTag:
return cloneDataView(object, isDeep);
case float32Tag: case float64Tag:
case int8Tag: case int16Tag: case int32Tag:
case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
return cloneTypedArray(object, isDeep);
case mapTag:
return new Ctor;
case numberTag:
case stringTag:
return new Ctor(object);
case regexpTag:
return cloneRegExp(object);
case setTag:
return new Ctor;
case symbolTag:
return cloneSymbol(object);
}
}
module.exports = initCloneByTag;
webpack://frontend-mybets/../../node_modules/lodash/_initCloneObject.js
var baseCreate = require('./_baseCreate'),
getPrototype = require('./_getPrototype'),
isPrototype = require('./_isPrototype');
/**
* Initializes an object clone.
*
* @private
* @param {Object} object The object to clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneObject(object) {
return (typeof object.constructor == 'function' && !isPrototype(object))
? baseCreate(getPrototype(object))
: {};
}
module.exports = initCloneObject;
webpack://frontend-mybets/../../node_modules/lodash/_insertWrapDetails.js
/** Used to match wrap detail comments. */
var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/;
/**
* Inserts wrapper `details` in a comment at the top of the `source` body.
*
* @private
* @param {string} source The source to modify.
* @returns {Array} details The details to insert.
* @returns {string} Returns the modified source.
*/
function insertWrapDetails(source, details) {
var length = details.length;
if (!length) {
return source;
}
var lastIndex = length - 1;
details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
details = details.join(length > 2 ? ', ' : ' ');
return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
}
module.exports = insertWrapDetails;
webpack://frontend-mybets/../../node_modules/lodash/_isFlattenable.js
var Symbol = require('./_Symbol'),
isArguments = require('./isArguments'),
isArray = require('./isArray');
/** Built-in value references. */
var spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;
/**
* Checks if `value` is a flattenable `arguments` object or array.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
*/
function isFlattenable(value) {
return isArray(value) || isArguments(value) ||
!!(spreadableSymbol && value && value[spreadableSymbol]);
}
module.exports = isFlattenable;
webpack://frontend-mybets/../../node_modules/lodash/_isIndex.js
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
var type = typeof value;
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length &&
(type == 'number' ||
(type != 'symbol' && reIsUint.test(value))) &&
(value > -1 && value % 1 == 0 && value < length);
}
module.exports = isIndex;
webpack://frontend-mybets/../../node_modules/lodash/_isIterateeCall.js
var eq = require('./eq'),
isArrayLike = require('./isArrayLike'),
isIndex = require('./_isIndex'),
isObject = require('./isObject');
/**
* Checks if the given arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call,
* else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject(object)) {
return false;
}
var type = typeof index;
if (type == 'number'
? (isArrayLike(object) && isIndex(index, object.length))
: (type == 'string' && index in object)
) {
return eq(object[index], value);
}
return false;
}
module.exports = isIterateeCall;
webpack://frontend-mybets/../../node_modules/lodash/_isKey.js
var isArray = require('./isArray'),
isSymbol = require('./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(value)) {
return false;
}
var type = typeof value;
if (type == 'number' || type == 'symbol' || type == 'boolean' ||
value == null || isSymbol(value)) {
return true;
}
return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
(object != null && value in Object(object));
}
module.exports = isKey;
webpack://frontend-mybets/../../node_modules/lodash/_isKeyable.js
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
? (value !== '__proto__')
: (value === null);
}
module.exports = isKeyable;
webpack://frontend-mybets/../../node_modules/lodash/_isLaziable.js
var LazyWrapper = require('./_LazyWrapper'),
getData = require('./_getData'),
getFuncName = require('./_getFuncName'),
lodash = require('./wrapperLodash');
/**
* Checks if `func` has a lazy counterpart.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` has a lazy counterpart,
* else `false`.
*/
function isLaziable(func) {
var funcName = getFuncName(func),
other = lodash[funcName];
if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {
return false;
}
if (func === other) {
return true;
}
var data = getData(other);
return !!data && func === data[0];
}
module.exports = isLaziable;
webpack://frontend-mybets/../../node_modules/lodash/_isMasked.js
var coreJsData = require('./_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);
}
module.exports = isMasked;
webpack://frontend-mybets/../../node_modules/lodash/_isPrototype.js
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
return value === proto;
}
module.exports = isPrototype;
webpack://frontend-mybets/../../node_modules/lodash/_isStrictComparable.js
var isObject = require('./isObject');
/**
* Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` if suitable for strict
* equality comparisons, else `false`.
*/
function isStrictComparable(value) {
return value === value && !isObject(value);
}
module.exports = isStrictComparable;
webpack://frontend-mybets/../../node_modules/lodash/_listCacheClear.js
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
module.exports = listCacheClear;
webpack://frontend-mybets/../../node_modules/lodash/_listCacheDelete.js
var assocIndexOf = require('./_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;
}
module.exports = listCacheDelete;
webpack://frontend-mybets/../../node_modules/lodash/_listCacheGet.js
var assocIndexOf = require('./_assocIndexOf');
/**
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function listCacheGet(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
return index < 0 ? undefined : data[index][1];
}
module.exports = listCacheGet;
webpack://frontend-mybets/../../node_modules/lodash/_listCacheHas.js
var assocIndexOf = require('./_assocIndexOf');
/**
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function listCacheHas(key) {
return assocIndexOf(this.__data__, key) > -1;
}
module.exports = listCacheHas;
webpack://frontend-mybets/../../node_modules/lodash/_listCacheSet.js
var assocIndexOf = require('./_assocIndexOf');
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/
function listCacheSet(key, value) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
module.exports = listCacheSet;
webpack://frontend-mybets/../../node_modules/lodash/_mapCacheClear.js
var Hash = require('./_Hash'),
ListCache = require('./_ListCache'),
Map = require('./_Map');
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapCacheClear() {
this.size = 0;
this.__data__ = {
'hash': new Hash,
'map': new (Map || ListCache),
'string': new Hash
};
}
module.exports = mapCacheClear;
webpack://frontend-mybets/../../node_modules/lodash/_mapCacheDelete.js
var getMapData = require('./_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;
}
module.exports = mapCacheDelete;
webpack://frontend-mybets/../../node_modules/lodash/_mapCacheGet.js
var getMapData = require('./_getMapData');
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapCacheGet(key) {
return getMapData(this, key).get(key);
}
module.exports = mapCacheGet;
webpack://frontend-mybets/../../node_modules/lodash/_mapCacheHas.js
var getMapData = require('./_getMapData');
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapCacheHas(key) {
return getMapData(this, key).has(key);
}
module.exports = mapCacheHas;
webpack://frontend-mybets/../../node_modules/lodash/_mapCacheSet.js
var getMapData = require('./_getMapData');
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapCacheSet(key, value) {
var data = getMapData(this, key),
size = data.size;
data.set(key, value);
this.size += data.size == size ? 0 : 1;
return this;
}
module.exports = mapCacheSet;
webpack://frontend-mybets/../../node_modules/lodash/_mapToArray.js
/**
* Converts `map` to its key-value pairs.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the key-value pairs.
*/
function mapToArray(map) {
var index = -1,
result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
module.exports = mapToArray;
webpack://frontend-mybets/../../node_modules/lodash/_matchesStrictComparable.js
/**
* A specialized version of `matchesProperty` for source values suitable
* for strict equality comparisons, i.e. `===`.
*
* @private
* @param {string} key The key of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function matchesStrictComparable(key, srcValue) {
return function(object) {
if (object == null) {
return false;
}
return object[key] === srcValue &&
(srcValue !== undefined || (key in Object(object)));
};
}
module.exports = matchesStrictComparable;
webpack://frontend-mybets/../../node_modules/lodash/_memoizeCapped.js
var memoize = require('./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(func, function(key) {
if (cache.size === MAX_MEMOIZE_SIZE) {
cache.clear();
}
return key;
});
var cache = result.cache;
return result;
}
module.exports = memoizeCapped;
webpack://frontend-mybets/../../node_modules/lodash/_mergeData.js
var composeArgs = require('./_composeArgs'),
composeArgsRight = require('./_composeArgsRight'),
replaceHolders = require('./_replaceHolders');
/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_BOUND_FLAG = 4,
WRAP_CURRY_FLAG = 8,
WRAP_ARY_FLAG = 128,
WRAP_REARG_FLAG = 256;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;
/**
* Merges the function metadata of `source` into `data`.
*
* Merging metadata reduces the number of wrappers used to invoke a function.
* This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
* may be applied regardless of execution order. Methods like `_.ary` and
* `_.rearg` modify function arguments, making the order in which they are
* executed important, preventing the merging of metadata. However, we make
* an exception for a safe combined case where curried functions have `_.ary`
* and or `_.rearg` applied.
*
* @private
* @param {Array} data The destination metadata.
* @param {Array} source The source metadata.
* @returns {Array} Returns `data`.
*/
function mergeData(data, source) {
var bitmask = data[1],
srcBitmask = source[1],
newBitmask = bitmask | srcBitmask,
isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);
var isCombo =
((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) ||
((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) ||
((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG));
// Exit early if metadata can't be merged.
if (!(isCommon || isCombo)) {
return data;
}
// Use source `thisArg` if available.
if (srcBitmask & WRAP_BIND_FLAG) {
data[2] = source[2];
// Set when currying a bound function.
newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;
}
// Compose partial arguments.
var value = source[3];
if (value) {
var partials = data[3];
data[3] = partials ? composeArgs(partials, value, source[4]) : value;
data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];
}
// Compose partial right arguments.
value = source[5];
if (value) {
partials = data[5];
data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;
data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];
}
// Use source `argPos` if available.
value = source[7];
if (value) {
data[7] = value;
}
// Use source `ary` if it's smaller.
if (srcBitmask & WRAP_ARY_FLAG) {
data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
}
// Use source `arity` if one is not provided.
if (data[9] == null) {
data[9] = source[9];
}
// Use source `func` and merge bitmasks.
data[0] = source[0];
data[1] = newBitmask;
return data;
}
module.exports = mergeData;
webpack://frontend-mybets/../../node_modules/lodash/_metaMap.js
var WeakMap = require('./_WeakMap');
/** Used to store function metadata. */
var metaMap = WeakMap && new WeakMap;
module.exports = metaMap;
webpack://frontend-mybets/../../node_modules/lodash/_nativeCreate.js
var getNative = require('./_getNative');
/* Built-in method references that are verified to be native. */
var nativeCreate = getNative(Object, 'create');
module.exports = nativeCreate;
webpack://frontend-mybets/../../node_modules/lodash/_nativeKeys.js
var overArg = require('./_overArg');
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = overArg(Object.keys, Object);
module.exports = nativeKeys;
webpack://frontend-mybets/../../node_modules/lodash/_nativeKeysIn.js
/**
* This function is like
* [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* except that it includes inherited enumerable properties.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function nativeKeysIn(object) {
var result = [];
if (object != null) {
for (var key in Object(object)) {
result.push(key);
}
}
return result;
}
module.exports = nativeKeysIn;
webpack://frontend-mybets/../../node_modules/lodash/_nodeUtil.js
var freeGlobal = require('./_freeGlobal');
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports && freeGlobal.process;
/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
try {
// Use `util.types` for Node.js 10+.
var types = freeModule && freeModule.require && freeModule.require('util').types;
if (types) {
return types;
}
// Legacy `process.binding('util')` for Node.js < 10.
return freeProcess && freeProcess.binding && freeProcess.binding('util');
} catch (e) {}
}());
module.exports = nodeUtil;
webpack://frontend-mybets/../../node_modules/lodash/_objectToString.js
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/
function objectToString(value) {
return nativeObjectToString.call(value);
}
module.exports = objectToString;
webpack://frontend-mybets/../../node_modules/lodash/_overArg.js
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
module.exports = overArg;
webpack://frontend-mybets/../../node_modules/lodash/_overRest.js
var apply = require('./_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);
};
}
module.exports = overRest;
webpack://frontend-mybets/../../node_modules/lodash/_parent.js
var baseGet = require('./_baseGet'),
baseSlice = require('./_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));
}
module.exports = parent;
webpack://frontend-mybets/../../node_modules/lodash/_realNames.js
/** Used to lookup unminified function names. */
var realNames = {};
module.exports = realNames;
webpack://frontend-mybets/../../node_modules/lodash/_reorder.js
var copyArray = require('./_copyArray'),
isIndex = require('./_isIndex');
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;
/**
* Reorder `array` according to the specified indexes where the element at
* the first index is assigned as the first element, the element at
* the second index is assigned as the second element, and so on.
*
* @private
* @param {Array} array The array to reorder.
* @param {Array} indexes The arranged array indexes.
* @returns {Array} Returns `array`.
*/
function reorder(array, indexes) {
var arrLength = array.length,
length = nativeMin(indexes.length, arrLength),
oldArray = copyArray(array);
while (length--) {
var index = indexes[length];
array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
}
return array;
}
module.exports = reorder;
webpack://frontend-mybets/../../node_modules/lodash/_replaceHolders.js
/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';
/**
* Replaces all `placeholder` elements in `array` with an internal placeholder
* and returns an array of their indexes.
*
* @private
* @param {Array} array The array to modify.
* @param {*} placeholder The placeholder to replace.
* @returns {Array} Returns the new array of placeholder indexes.
*/
function replaceHolders(array, placeholder) {
var index = -1,
length = array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value === placeholder || value === PLACEHOLDER) {
array[index] = PLACEHOLDER;
result[resIndex++] = index;
}
}
return result;
}
module.exports = replaceHolders;
webpack://frontend-mybets/../../node_modules/lodash/_root.js
var freeGlobal = require('./_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')();
module.exports = root;
webpack://frontend-mybets/../../node_modules/lodash/_safeGet.js
/**
* Gets the value at `key`, unless `key` is "__proto__" or "constructor".
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function safeGet(object, key) {
if (key === 'constructor' && typeof object[key] === 'function') {
return;
}
if (key == '__proto__') {
return;
}
return object[key];
}
module.exports = safeGet;
webpack://frontend-mybets/../../node_modules/lodash/_setCacheAdd.js
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/**
* Adds `value` to the array cache.
*
* @private
* @name add
* @memberOf SetCache
* @alias push
* @param {*} value The value to cache.
* @returns {Object} Returns the cache instance.
*/
function setCacheAdd(value) {
this.__data__.set(value, HASH_UNDEFINED);
return this;
}
module.exports = setCacheAdd;
webpack://frontend-mybets/../../node_modules/lodash/_setCacheHas.js
/**
* Checks if `value` is in the array cache.
*
* @private
* @name has
* @memberOf SetCache
* @param {*} value The value to search for.
* @returns {number} Returns `true` if `value` is found, else `false`.
*/
function setCacheHas(value) {
return this.__data__.has(value);
}
module.exports = setCacheHas;
webpack://frontend-mybets/../../node_modules/lodash/_setData.js
var baseSetData = require('./_baseSetData'),
shortOut = require('./_shortOut');
/**
* Sets metadata for `func`.
*
* **Note:** If this function becomes hot, i.e. is invoked a lot in a short
* period of time, it will trip its breaker and transition to an identity
* function to avoid garbage collection pauses in V8. See
* [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
* for more details.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var setData = shortOut(baseSetData);
module.exports = setData;
webpack://frontend-mybets/../../node_modules/lodash/_setToArray.js
/**
* Converts `set` to an array of its values.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the values.
*/
function setToArray(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
module.exports = setToArray;
webpack://frontend-mybets/../../node_modules/lodash/_setToPairs.js
/**
* Converts `set` to its value-value pairs.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the value-value pairs.
*/
function setToPairs(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = [value, value];
});
return result;
}
module.exports = setToPairs;
webpack://frontend-mybets/../../node_modules/lodash/_setToString.js
var baseSetToString = require('./_baseSetToString'),
shortOut = require('./_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);
module.exports = setToString;
webpack://frontend-mybets/../../node_modules/lodash/_setWrapToString.js
var getWrapDetails = require('./_getWrapDetails'),
insertWrapDetails = require('./_insertWrapDetails'),
setToString = require('./_setToString'),
updateWrapDetails = require('./_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)));
}
module.exports = setWrapToString;
webpack://frontend-mybets/../../node_modules/lodash/_shortOut.js
/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
HOT_SPAN = 16;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeNow = Date.now;
/**
* Creates a function that'll short out and invoke `identity` instead
* of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
* milliseconds.
*
* @private
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new shortable function.
*/
function shortOut(func) {
var count = 0,
lastCalled = 0;
return function() {
var stamp = nativeNow(),
remaining = HOT_SPAN - (stamp - lastCalled);
lastCalled = stamp;
if (remaining > 0) {
if (++count >= HOT_COUNT) {
return arguments[0];
}
} else {
count = 0;
}
return func.apply(undefined, arguments);
};
}
module.exports = shortOut;
webpack://frontend-mybets/../../node_modules/lodash/_stackClear.js
var ListCache = require('./_ListCache');
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = new ListCache;
this.size = 0;
}
module.exports = stackClear;
webpack://frontend-mybets/../../node_modules/lodash/_stackDelete.js
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function stackDelete(key) {
var data = this.__data__,
result = data['delete'](key);
this.size = data.size;
return result;
}
module.exports = stackDelete;
webpack://frontend-mybets/../../node_modules/lodash/_stackGet.js
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function stackGet(key) {
return this.__data__.get(key);
}
module.exports = stackGet;
webpack://frontend-mybets/../../node_modules/lodash/_stackHas.js
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function stackHas(key) {
return this.__data__.has(key);
}
module.exports = stackHas;
webpack://frontend-mybets/../../node_modules/lodash/_stackSet.js
var ListCache = require('./_ListCache'),
Map = require('./_Map'),
MapCache = require('./_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;
}
module.exports = stackSet;
webpack://frontend-mybets/../../node_modules/lodash/_strictIndexOf.js
/**
* A specialized version of `_.indexOf` which performs strict equality
* comparisons of values, i.e. `===`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function strictIndexOf(array, value, fromIndex) {
var index = fromIndex - 1,
length = array.length;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
module.exports = strictIndexOf;
webpack://frontend-mybets/../../node_modules/lodash/_stringSize.js
var asciiSize = require('./_asciiSize'),
hasUnicode = require('./_hasUnicode'),
unicodeSize = require('./_unicodeSize');
/**
* Gets the number of symbols in `string`.
*
* @private
* @param {string} string The string to inspect.
* @returns {number} Returns the string size.
*/
function stringSize(string) {
return hasUnicode(string)
? unicodeSize(string)
: asciiSize(string);
}
module.exports = stringSize;
webpack://frontend-mybets/../../node_modules/lodash/_stringToArray.js
var asciiToArray = require('./_asciiToArray'),
hasUnicode = require('./_hasUnicode'),
unicodeToArray = require('./_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);
}
module.exports = stringToArray;
webpack://frontend-mybets/../../node_modules/lodash/_stringToPath.js
var memoizeCapped = require('./_memoizeCapped');
/** Used to match property names within property paths. */
var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;
/**
* Converts `string` to a property path array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the property path array.
*/
var stringToPath = memoizeCapped(function(string) {
var result = [];
if (string.charCodeAt(0) === 46 /* . */) {
result.push('');
}
string.replace(rePropName, function(match, number, quote, subString) {
result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
});
return result;
});
module.exports = stringToPath;
webpack://frontend-mybets/../../node_modules/lodash/_toKey.js
var isSymbol = require('./isSymbol');
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/**
* Converts `value` to a string key if it's not a string or symbol.
*
* @private
* @param {*} value The value to inspect.
* @returns {string|symbol} Returns the key.
*/
function toKey(value) {
if (typeof value == 'string' || isSymbol(value)) {
return value;
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
module.exports = toKey;
webpack://frontend-mybets/../../node_modules/lodash/_toSource.js
/** Used for built-in method references. */
var funcProto = Function.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to convert.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
module.exports = toSource;
webpack://frontend-mybets/../../node_modules/lodash/_trimmedEndIndex.js
/** Used to match a single whitespace character. */
var reWhitespace = /\s/;
/**
* Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
* character of `string`.
*
* @private
* @param {string} string The string to inspect.
* @returns {number} Returns the index of the last non-whitespace character.
*/
function trimmedEndIndex(string) {
var index = string.length;
while (index-- && reWhitespace.test(string.charAt(index))) {}
return index;
}
module.exports = trimmedEndIndex;
webpack://frontend-mybets/../../node_modules/lodash/_unicodeSize.js
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
rsComboMarksRange = '\\u0300-\\u036f',
reComboHalfMarksRange = '\\ufe20-\\ufe2f',
rsComboSymbolsRange = '\\u20d0-\\u20ff',
rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
rsVarRange = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */
var rsAstral = '[' + rsAstralRange + ']',
rsCombo = '[' + rsComboRange + ']',
rsFitz = '\\ud83c[\\udffb-\\udfff]',
rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
rsNonAstral = '[^' + rsAstralRange + ']',
rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
rsZWJ = '\\u200d';
/** Used to compose unicode regexes. */
var reOptMod = rsModifier + '?',
rsOptVar = '[' + rsVarRange + ']?',
rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
rsSeq = rsOptVar + reOptMod + rsOptJoin,
rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
/**
* Gets the size of a Unicode `string`.
*
* @private
* @param {string} string The string inspect.
* @returns {number} Returns the string size.
*/
function unicodeSize(string) {
var result = reUnicode.lastIndex = 0;
while (reUnicode.test(string)) {
++result;
}
return result;
}
module.exports = unicodeSize;
webpack://frontend-mybets/../../node_modules/lodash/_unicodeToArray.js
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
rsComboMarksRange = '\\u0300-\\u036f',
reComboHalfMarksRange = '\\ufe20-\\ufe2f',
rsComboSymbolsRange = '\\u20d0-\\u20ff',
rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
rsVarRange = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */
var rsAstral = '[' + rsAstralRange + ']',
rsCombo = '[' + rsComboRange + ']',
rsFitz = '\\ud83c[\\udffb-\\udfff]',
rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
rsNonAstral = '[^' + rsAstralRange + ']',
rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
rsZWJ = '\\u200d';
/** Used to compose unicode regexes. */
var reOptMod = rsModifier + '?',
rsOptVar = '[' + rsVarRange + ']?',
rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
rsSeq = rsOptVar + reOptMod + rsOptJoin,
rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
/**
* Converts a Unicode `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function unicodeToArray(string) {
return string.match(reUnicode) || [];
}
module.exports = unicodeToArray;
webpack://frontend-mybets/../../node_modules/lodash/_unicodeWords.js
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
rsComboMarksRange = '\\u0300-\\u036f',
reComboHalfMarksRange = '\\ufe20-\\ufe2f',
rsComboSymbolsRange = '\\u20d0-\\u20ff',
rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
rsDingbatRange = '\\u2700-\\u27bf',
rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
rsPunctuationRange = '\\u2000-\\u206f',
rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000',
rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
rsVarRange = '\\ufe0e\\ufe0f',
rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
/** Used to compose unicode capture groups. */
var rsApos = "['\u2019]",
rsBreak = '[' + rsBreakRange + ']',
rsCombo = '[' + rsComboRange + ']',
rsDigits = '\\d+',
rsDingbat = '[' + rsDingbatRange + ']',
rsLower = '[' + rsLowerRange + ']',
rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
rsFitz = '\\ud83c[\\udffb-\\udfff]',
rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
rsNonAstral = '[^' + rsAstralRange + ']',
rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
rsUpper = '[' + rsUpperRange + ']',
rsZWJ = '\\u200d';
/** Used to compose unicode regexes. */
var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')',
rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')',
rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
reOptMod = rsModifier + '?',
rsOptVar = '[' + rsVarRange + ']?',
rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])',
rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])',
rsSeq = rsOptVar + reOptMod + rsOptJoin,
rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq;
/** Used to match complex or compound words. */
var reUnicodeWord = RegExp([
rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')',
rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower,
rsUpper + '+' + rsOptContrUpper,
rsOrdUpper,
rsOrdLower,
rsDigits,
rsEmoji
].join('|'), 'g');
/**
* Splits a Unicode `string` into an array of its words.
*
* @private
* @param {string} The string to inspect.
* @returns {Array} Returns the words of `string`.
*/
function unicodeWords(string) {
return string.match(reUnicodeWord) || [];
}
module.exports = unicodeWords;
webpack://frontend-mybets/../../node_modules/lodash/_updateWrapDetails.js
var arrayEach = require('./_arrayEach'),
arrayIncludes = require('./_arrayIncludes');
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_FLAG = 8,
WRAP_CURRY_RIGHT_FLAG = 16,
WRAP_PARTIAL_FLAG = 32,
WRAP_PARTIAL_RIGHT_FLAG = 64,
WRAP_ARY_FLAG = 128,
WRAP_REARG_FLAG = 256,
WRAP_FLIP_FLAG = 512;
/** Used to associate wrap methods with their bit flags. */
var wrapFlags = [
['ary', WRAP_ARY_FLAG],
['bind', WRAP_BIND_FLAG],
['bindKey', WRAP_BIND_KEY_FLAG],
['curry', WRAP_CURRY_FLAG],
['curryRight', WRAP_CURRY_RIGHT_FLAG],
['flip', WRAP_FLIP_FLAG],
['partial', WRAP_PARTIAL_FLAG],
['partialRight', WRAP_PARTIAL_RIGHT_FLAG],
['rearg', WRAP_REARG_FLAG]
];
/**
* Updates wrapper `details` based on `bitmask` flags.
*
* @private
* @returns {Array} details The details to modify.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @returns {Array} Returns `details`.
*/
function updateWrapDetails(details, bitmask) {
arrayEach(wrapFlags, function(pair) {
var value = '_.' + pair[0];
if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {
details.push(value);
}
});
return details.sort();
}
module.exports = updateWrapDetails;
webpack://frontend-mybets/../../node_modules/lodash/_wrapperClone.js
var LazyWrapper = require('./_LazyWrapper'),
LodashWrapper = require('./_LodashWrapper'),
copyArray = require('./_copyArray');
/**
* Creates a clone of `wrapper`.
*
* @private
* @param {Object} wrapper The wrapper to clone.
* @returns {Object} Returns the cloned wrapper.
*/
function wrapperClone(wrapper) {
if (wrapper instanceof LazyWrapper) {
return wrapper.clone();
}
var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
result.__actions__ = copyArray(wrapper.__actions__);
result.__index__ = wrapper.__index__;
result.__values__ = wrapper.__values__;
return result;
}
module.exports = wrapperClone;
webpack://frontend-mybets/../../node_modules/lodash/ary.js
var createWrap = require('./_createWrap');
/** Used to compose bitmasks for function metadata. */
var WRAP_ARY_FLAG = 128;
/**
* Creates a function that invokes `func`, with up to `n` arguments,
* ignoring any additional arguments.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} func The function to cap arguments for.
* @param {number} [n=func.length] The arity cap.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the new capped function.
* @example
*
* _.map(['6', '8', '10'], _.ary(parseInt, 1));
* // => [6, 8, 10]
*/
function ary(func, n, guard) {
n = guard ? undefined : n;
n = (func && n == null) ? func.length : n;
return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n);
}
module.exports = ary;
webpack://frontend-mybets/../../node_modules/lodash/attempt.js
var apply = require('./_apply'),
baseRest = require('./_baseRest'),
isError = require('./isError');
/**
* Attempts to invoke `func`, returning either the result or the caught error
* object. Any additional arguments are provided to `func` when it's invoked.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {Function} func The function to attempt.
* @param {...*} [args] The arguments to invoke `func` with.
* @returns {*} Returns the `func` result or error object.
* @example
*
* // Avoid throwing errors for invalid selectors.
* var elements = _.attempt(function(selector) {
* return document.querySelectorAll(selector);
* }, '>_>');
*
* if (_.isError(elements)) {
* elements = [];
* }
*/
var attempt = baseRest(function(func, args) {
try {
return apply(func, undefined, args);
} catch (e) {
return isError(e) ? e : new Error(e);
}
});
module.exports = attempt;
webpack://frontend-mybets/../../node_modules/lodash/bind.js
var baseRest = require('./_baseRest'),
createWrap = require('./_createWrap'),
getHolder = require('./_getHolder'),
replaceHolders = require('./_replaceHolders');
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_PARTIAL_FLAG = 32;
/**
* Creates a function that invokes `func` with the `this` binding of `thisArg`
* and `partials` prepended to the arguments it receives.
*
* The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for partially applied arguments.
*
* **Note:** Unlike native `Function#bind`, this method doesn't set the "length"
* property of bound functions.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* function greet(greeting, punctuation) {
* return greeting + ' ' + this.user + punctuation;
* }
*
* var object = { 'user': 'fred' };
*
* var bound = _.bind(greet, object, 'hi');
* bound('!');
* // => 'hi fred!'
*
* // Bound with placeholders.
* var bound = _.bind(greet, object, _, '!');
* bound('hi');
* // => 'hi fred!'
*/
var bind = baseRest(function(func, thisArg, partials) {
var bitmask = WRAP_BIND_FLAG;
if (partials.length) {
var holders = replaceHolders(partials, getHolder(bind));
bitmask |= WRAP_PARTIAL_FLAG;
}
return createWrap(func, bitmask, thisArg, partials, holders);
});
// Assign default placeholders.
bind.placeholder = {};
module.exports = bind;
webpack://frontend-mybets/../../node_modules/lodash/bindAll.js
var arrayEach = require('./_arrayEach'),
baseAssignValue = require('./_baseAssignValue'),
bind = require('./bind'),
flatRest = require('./_flatRest'),
toKey = require('./_toKey');
/**
* Binds methods of an object to the object itself, overwriting the existing
* method.
*
* **Note:** This method doesn't set the "length" property of bound functions.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {Object} object The object to bind and assign the bound methods to.
* @param {...(string|string[])} methodNames The object method names to bind.
* @returns {Object} Returns `object`.
* @example
*
* var view = {
* 'label': 'docs',
* 'click': function() {
* console.log('clicked ' + this.label);
* }
* };
*
* _.bindAll(view, ['click']);
* jQuery(element).on('click', view.click);
* // => Logs 'clicked docs' when clicked.
*/
var bindAll = flatRest(function(object, methodNames) {
arrayEach(methodNames, function(key) {
key = toKey(key);
baseAssignValue(object, key, bind(object[key], object));
});
return object;
});
module.exports = bindAll;
webpack://frontend-mybets/../../node_modules/lodash/capitalize.js
var toString = require('./toString'),
upperFirst = require('./upperFirst');
/**
* Converts the first character of `string` to upper case and the remaining
* to lower case.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to capitalize.
* @returns {string} Returns the capitalized string.
* @example
*
* _.capitalize('FRED');
* // => 'Fred'
*/
function capitalize(string) {
return upperFirst(toString(string).toLowerCase());
}
module.exports = capitalize;
webpack://frontend-mybets/../../node_modules/lodash/clone.js
var baseClone = require('./_baseClone');
/** Used to compose bitmasks for cloning. */
var CLONE_SYMBOLS_FLAG = 4;
/**
* Creates a shallow clone of `value`.
*
* **Note:** This method is loosely based on the
* [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
* and supports cloning arrays, array buffers, booleans, date objects, maps,
* numbers, `Object` objects, regexes, sets, strings, symbols, and typed
* arrays. The own enumerable properties of `arguments` objects are cloned
* as plain objects. An empty object is returned for uncloneable values such
* as error objects, functions, DOM nodes, and WeakMaps.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to clone.
* @returns {*} Returns the cloned value.
* @see _.cloneDeep
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var shallow = _.clone(objects);
* console.log(shallow[0] === objects[0]);
* // => true
*/
function clone(value) {
return baseClone(value, CLONE_SYMBOLS_FLAG);
}
module.exports = clone;
webpack://frontend-mybets/../../node_modules/lodash/cloneDeep.js
var baseClone = require('./_baseClone');
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
CLONE_SYMBOLS_FLAG = 4;
/**
* This method is like `_.clone` except that it recursively clones `value`.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Lang
* @param {*} value The value to recursively clone.
* @returns {*} Returns the deep cloned value.
* @see _.clone
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var deep = _.cloneDeep(objects);
* console.log(deep[0] === objects[0]);
* // => false
*/
function cloneDeep(value) {
return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);
}
module.exports = cloneDeep;
webpack://frontend-mybets/../../node_modules/lodash/compact.js
/**
* Creates an array with all falsey values removed. The values `false`, `null`,
* `0`, `""`, `undefined`, and `NaN` are falsey.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to compact.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.compact([0, 1, false, 2, '', 3]);
* // => [1, 2, 3]
*/
function compact(array) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value) {
result[resIndex++] = value;
}
}
return result;
}
module.exports = compact;
webpack://frontend-mybets/../../node_modules/lodash/constant.js
/**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new constant function.
* @example
*
* var objects = _.times(2, _.constant({ 'a': 1 }));
*
* console.log(objects);
* // => [{ 'a': 1 }, { 'a': 1 }]
*
* console.log(objects[0] === objects[1]);
* // => true
*/
function constant(value) {
return function() {
return value;
};
}
module.exports = constant;
webpack://frontend-mybets/../../node_modules/lodash/curry.js
var createWrap = require('./_createWrap');
/** Used to compose bitmasks for function metadata. */
var WRAP_CURRY_FLAG = 8;
/**
* Creates a function that accepts arguments of `func` and either invokes
* `func` returning its result, if at least `arity` number of arguments have
* been provided, or returns a function that accepts the remaining `func`
* arguments, and so on. The arity of `func` may be specified if `func.length`
* is not sufficient.
*
* The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for provided arguments.
*
* **Note:** This method doesn't set the "length" property of curried functions.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Function
* @param {Function} func The function to curry.
* @param {number} [arity=func.length] The arity of `func`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the new curried function.
* @example
*
* var abc = function(a, b, c) {
* return [a, b, c];
* };
*
* var curried = _.curry(abc);
*
* curried(1)(2)(3);
* // => [1, 2, 3]
*
* curried(1, 2)(3);
* // => [1, 2, 3]
*
* curried(1, 2, 3);
* // => [1, 2, 3]
*
* // Curried with placeholders.
* curried(1)(_, 3)(2);
* // => [1, 2, 3]
*/
function curry(func, arity, guard) {
arity = guard ? undefined : arity;
var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
result.placeholder = curry.placeholder;
return result;
}
// Assign default placeholders.
curry.placeholder = {};
module.exports = curry;
webpack://frontend-mybets/../../node_modules/lodash/debounce.js
var isObject = require('./isObject'),
now = require('./now'),
toNumber = require('./toNumber');
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max,
nativeMin = Math.min;
/**
* Creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked. The debounced function comes with a `cancel` method to cancel
* delayed `func` invocations and a `flush` method to immediately invoke them.
* Provide `options` to indicate whether `func` should be invoked on the
* leading and/or trailing edge of the `wait` timeout. The `func` is invoked
* with the last arguments provided to the debounced function. Subsequent
* calls to the debounced function return the result of the last `func`
* invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the debounced function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.debounce` and `_.throttle`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to debounce.
* @param {number} [wait=0] The number of milliseconds to delay.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=false]
* Specify invoking on the leading edge of the timeout.
* @param {number} [options.maxWait]
* The maximum time `func` is allowed to be delayed before it's invoked.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // Avoid costly calculations while the window size is in flux.
* jQuery(window).on('resize', _.debounce(calculateLayout, 150));
*
* // Invoke `sendMail` when clicked, debouncing subsequent calls.
* jQuery(element).on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* }));
*
* // Ensure `batchLog` is invoked once after 1 second of debounced calls.
* var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
* var source = new EventSource('/stream');
* jQuery(source).on('message', debounced);
*
* // Cancel the trailing debounced invocation.
* jQuery(window).on('popstate', debounced.cancel);
*/
function debounce(func, wait, options) {
var lastArgs,
lastThis,
maxWait,
result,
timerId,
lastCallTime,
lastInvokeTime = 0,
leading = false,
maxing = false,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
wait = toNumber(wait) || 0;
if (isObject(options)) {
leading = !!options.leading;
maxing = 'maxWait' in options;
maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
function invokeFunc(time) {
var args = lastArgs,
thisArg = lastThis;
lastArgs = lastThis = undefined;
lastInvokeTime = time;
result = func.apply(thisArg, args);
return result;
}
function leadingEdge(time) {
// Reset any `maxWait` timer.
lastInvokeTime = time;
// Start the timer for the trailing edge.
timerId = setTimeout(timerExpired, wait);
// Invoke the leading edge.
return leading ? invokeFunc(time) : result;
}
function remainingWait(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime,
timeWaiting = wait - timeSinceLastCall;
return maxing
? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)
: timeWaiting;
}
function shouldInvoke(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime;
// Either this is the first call, activity has stopped and we're at the
// trailing edge, the system time has gone backwards and we're treating
// it as the trailing edge, or we've hit the `maxWait` limit.
return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
(timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
}
function timerExpired() {
var time = now();
if (shouldInvoke(time)) {
return trailingEdge(time);
}
// Restart the timer.
timerId = setTimeout(timerExpired, remainingWait(time));
}
function trailingEdge(time) {
timerId = undefined;
// Only invoke if we have `lastArgs` which means `func` has been
// debounced at least once.
if (trailing && lastArgs) {
return invokeFunc(time);
}
lastArgs = lastThis = undefined;
return result;
}
function cancel() {
if (timerId !== undefined) {
clearTimeout(timerId);
}
lastInvokeTime = 0;
lastArgs = lastCallTime = lastThis = timerId = undefined;
}
function flush() {
return timerId === undefined ? result : trailingEdge(now());
}
function debounced() {
var time = now(),
isInvoking = shouldInvoke(time);
lastArgs = arguments;
lastThis = this;
lastCallTime = time;
if (isInvoking) {
if (timerId === undefined) {
return leadingEdge(lastCallTime);
}
if (maxing) {
// Handle invocations in a tight loop.
clearTimeout(timerId);
timerId = setTimeout(timerExpired, wait);
return invokeFunc(lastCallTime);
}
}
if (timerId === undefined) {
timerId = setTimeout(timerExpired, wait);
}
return result;
}
debounced.cancel = cancel;
debounced.flush = flush;
return debounced;
}
module.exports = debounce;
webpack://frontend-mybets/../../node_modules/lodash/deburr.js
var deburrLetter = require('./_deburrLetter'),
toString = require('./toString');
/** Used to match Latin Unicode letters (excluding mathematical operators). */
var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
/** Used to compose unicode character classes. */
var rsComboMarksRange = '\\u0300-\\u036f',
reComboHalfMarksRange = '\\ufe20-\\ufe2f',
rsComboSymbolsRange = '\\u20d0-\\u20ff',
rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange;
/** Used to compose unicode capture groups. */
var rsCombo = '[' + rsComboRange + ']';
/**
* Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
* [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
*/
var reComboMark = RegExp(rsCombo, 'g');
/**
* Deburrs `string` by converting
* [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
* and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
* letters to basic Latin letters and removing
* [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to deburr.
* @returns {string} Returns the deburred string.
* @example
*
* _.deburr('déjà vu');
* // => 'deja vu'
*/
function deburr(string) {
string = toString(string);
return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
}
module.exports = deburr;
webpack://frontend-mybets/../../node_modules/lodash/endsWith.js
var baseClamp = require('./_baseClamp'),
baseToString = require('./_baseToString'),
toInteger = require('./toInteger'),
toString = require('./toString');
/**
* Checks if `string` ends 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=string.length] The position to search up to.
* @returns {boolean} Returns `true` if `string` ends with `target`,
* else `false`.
* @example
*
* _.endsWith('abc', 'c');
* // => true
*
* _.endsWith('abc', 'b');
* // => false
*
* _.endsWith('abc', 'b', 2);
* // => true
*/
function endsWith(string, target, position) {
string = toString(string);
target = baseToString(target);
var length = string.length;
position = position === undefined
? length
: baseClamp(toInteger(position), 0, length);
var end = position;
position -= target.length;
return position >= 0 && string.slice(position, end) == target;
}
module.exports = endsWith;
webpack://frontend-mybets/../../node_modules/lodash/eq.js
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
module.exports = eq;
webpack://frontend-mybets/../../node_modules/lodash/escapeRegExp.js
var toString = require('./toString');
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g,
reHasRegExpChar = RegExp(reRegExpChar.source);
/**
* Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+",
* "?", "(", ")", "[", "]", "{", "}", and "|" in `string`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escapeRegExp('[lodash](https://lodash.com/)');
* // => '\[lodash\]\(https://lodash\.com/\)'
*/
function escapeRegExp(string) {
string = toString(string);
return (string && reHasRegExpChar.test(string))
? string.replace(reRegExpChar, '\\$&')
: string;
}
module.exports = escapeRegExp;
webpack://frontend-mybets/../../node_modules/lodash/every.js
var arrayEvery = require('./_arrayEvery'),
baseEvery = require('./_baseEvery'),
baseIteratee = require('./_baseIteratee'),
isArray = require('./isArray'),
isIterateeCall = require('./_isIterateeCall');
/**
* Checks if `predicate` returns truthy for **all** elements of `collection`.
* Iteration is stopped once `predicate` returns falsey. The predicate is
* invoked with three arguments: (value, index|key, collection).
*
* **Note:** This method returns `true` for
* [empty collections](https://en.wikipedia.org/wiki/Empty_set) because
* [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of
* elements of empty collections.
*
* @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.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`.
* @example
*
* _.every([true, 1, null, 'yes'], Boolean);
* // => false
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.every(users, { 'user': 'barney', 'active': false });
* // => false
*
* // The `_.matchesProperty` iteratee shorthand.
* _.every(users, ['active', false]);
* // => true
*
* // The `_.property` iteratee shorthand.
* _.every(users, 'active');
* // => false
*/
function every(collection, predicate, guard) {
var func = isArray(collection) ? arrayEvery : baseEvery;
if (guard && isIterateeCall(collection, predicate, guard)) {
predicate = undefined;
}
return func(collection, baseIteratee(predicate, 3));
}
module.exports = every;
webpack://frontend-mybets/../../node_modules/lodash/filter.js
var arrayFilter = require('./_arrayFilter'),
baseFilter = require('./_baseFilter'),
baseIteratee = require('./_baseIteratee'),
isArray = require('./isArray');
/**
* 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']
*
* // Combining several predicates using `_.overEvery` or `_.overSome`.
* _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]]));
* // => objects for ['fred', 'barney']
*/
function filter(collection, predicate) {
var func = isArray(collection) ? arrayFilter : baseFilter;
return func(collection, baseIteratee(predicate, 3));
}
module.exports = filter;
webpack://frontend-mybets/../../node_modules/lodash/find.js
var createFind = require('./_createFind'),
findIndex = require('./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);
module.exports = find;
webpack://frontend-mybets/../../node_modules/lodash/findIndex.js
var baseFindIndex = require('./_baseFindIndex'),
baseIteratee = require('./_baseIteratee'),
toInteger = require('./toInteger');
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* This method is like `_.find` except that it returns the index of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.findIndex(users, function(o) { return o.user == 'barney'; });
* // => 0
*
* // The `_.matches` iteratee shorthand.
* _.findIndex(users, { 'user': 'fred', 'active': false });
* // => 1
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findIndex(users, ['active', false]);
* // => 0
*
* // The `_.property` iteratee shorthand.
* _.findIndex(users, 'active');
* // => 2
*/
function findIndex(array, predicate, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger(fromIndex);
if (index < 0) {
index = nativeMax(length + index, 0);
}
return baseFindIndex(array, baseIteratee(predicate, 3), index);
}
module.exports = findIndex;
webpack://frontend-mybets/../../node_modules/lodash/findKey.js
var baseFindKey = require('./_baseFindKey'),
baseForOwn = require('./_baseForOwn'),
baseIteratee = require('./_baseIteratee');
/**
* This method is like `_.find` except that it returns the key of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Object
* @param {Object} object The object to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {string|undefined} Returns the key of the matched element,
* else `undefined`.
* @example
*
* var users = {
* 'barney': { 'age': 36, 'active': true },
* 'fred': { 'age': 40, 'active': false },
* 'pebbles': { 'age': 1, 'active': true }
* };
*
* _.findKey(users, function(o) { return o.age < 40; });
* // => 'barney' (iteration order is not guaranteed)
*
* // The `_.matches` iteratee shorthand.
* _.findKey(users, { 'age': 1, 'active': true });
* // => 'pebbles'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findKey(users, ['active', false]);
* // => 'fred'
*
* // The `_.property` iteratee shorthand.
* _.findKey(users, 'active');
* // => 'barney'
*/
function findKey(object, predicate) {
return baseFindKey(object, baseIteratee(predicate, 3), baseForOwn);
}
module.exports = findKey;
webpack://frontend-mybets/../../node_modules/lodash/findLast.js
var createFind = require('./_createFind'),
findLastIndex = require('./findLastIndex');
/**
* This method is like `_.find` except that it iterates over elements of
* `collection` from right to left.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Collection
* @param {Array|Object} collection The collection to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=collection.length-1] The index to search from.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* _.findLast([1, 2, 3, 4], function(n) {
* return n % 2 == 1;
* });
* // => 3
*/
var findLast = createFind(findLastIndex);
module.exports = findLast;
webpack://frontend-mybets/../../node_modules/lodash/findLastIndex.js
var baseFindIndex = require('./_baseFindIndex'),
baseIteratee = require('./_baseIteratee'),
toInteger = require('./toInteger');
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max,
nativeMin = Math.min;
/**
* This method is like `_.findIndex` except that it iterates over elements
* of `collection` from right to left.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=array.length-1] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
* _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });
* // => 2
*
* // The `_.matches` iteratee shorthand.
* _.findLastIndex(users, { 'user': 'barney', 'active': true });
* // => 0
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findLastIndex(users, ['active', false]);
* // => 2
*
* // The `_.property` iteratee shorthand.
* _.findLastIndex(users, 'active');
* // => 0
*/
function findLastIndex(array, predicate, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = length - 1;
if (fromIndex !== undefined) {
index = toInteger(fromIndex);
index = fromIndex < 0
? nativeMax(length + index, 0)
: nativeMin(index, length - 1);
}
return baseFindIndex(array, baseIteratee(predicate, 3), index, true);
}
module.exports = findLastIndex;
webpack://frontend-mybets/../../node_modules/lodash/first.js
module.exports = require('./head');
webpack://frontend-mybets/../../node_modules/lodash/flatMap.js
var baseFlatten = require('./_baseFlatten'),
map = require('./map');
/**
* Creates a flattened array of values by running each element in `collection`
* thru `iteratee` and flattening the mapped results. The iteratee is invoked
* with three arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 4.0.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 flattened array.
* @example
*
* function duplicate(n) {
* return [n, n];
* }
*
* _.flatMap([1, 2], duplicate);
* // => [1, 1, 2, 2]
*/
function flatMap(collection, iteratee) {
return baseFlatten(map(collection, iteratee), 1);
}
module.exports = flatMap;
webpack://frontend-mybets/../../node_modules/lodash/flatten.js
var baseFlatten = require('./_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) : [];
}
module.exports = flatten;
webpack://frontend-mybets/../../node_modules/lodash/flowRight.js
var createFlow = require('./_createFlow');
/**
* This method is like `_.flow` except that it creates a function that
* invokes the given functions from right to left.
*
* @static
* @since 3.0.0
* @memberOf _
* @category Util
* @param {...(Function|Function[])} [funcs] The functions to invoke.
* @returns {Function} Returns the new composite function.
* @see _.flow
* @example
*
* function square(n) {
* return n * n;
* }
*
* var addSquare = _.flowRight([square, _.add]);
* addSquare(1, 2);
* // => 9
*/
var flowRight = createFlow(true);
module.exports = flowRight;
webpack://frontend-mybets/../../node_modules/lodash/forEach.js
var arrayEach = require('./_arrayEach'),
baseEach = require('./_baseEach'),
castFunction = require('./_castFunction'),
isArray = require('./isArray');
/**
* Iterates over elements of `collection` and invokes `iteratee` for each element.
* The iteratee is invoked with three arguments: (value, index|key, collection).
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* **Note:** As with other "Collections" methods, objects with a "length"
* property are iterated like arrays. To avoid this behavior use `_.forIn`
* or `_.forOwn` for object iteration.
*
* @static
* @memberOf _
* @since 0.1.0
* @alias each
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
* @see _.forEachRight
* @example
*
* _.forEach([1, 2], function(value) {
* console.log(value);
* });
* // => Logs `1` then `2`.
*
* _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/
function forEach(collection, iteratee) {
var func = isArray(collection) ? arrayEach : baseEach;
return func(collection, castFunction(iteratee));
}
module.exports = forEach;
webpack://frontend-mybets/../../node_modules/lodash/fp/_baseConvert.js
var mapping = require('./_mapping'),
fallbackHolder = require('./placeholder');
/** Built-in value reference. */
var push = Array.prototype.push;
/**
* Creates a function, with an arity of `n`, that invokes `func` with the
* arguments it receives.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} n The arity of the new function.
* @returns {Function} Returns the new function.
*/
function baseArity(func, n) {
return n == 2
? function(a, b) { return func.apply(undefined, arguments); }
: function(a) { return func.apply(undefined, arguments); };
}
/**
* Creates a function that invokes `func`, with up to `n` arguments, ignoring
* any additional arguments.
*
* @private
* @param {Function} func The function to cap arguments for.
* @param {number} n The arity cap.
* @returns {Function} Returns the new function.
*/
function baseAry(func, n) {
return n == 2
? function(a, b) { return func(a, b); }
: function(a) { return func(a); };
}
/**
* Creates a clone of `array`.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the cloned array.
*/
function cloneArray(array) {
var length = array ? array.length : 0,
result = Array(length);
while (length--) {
result[length] = array[length];
}
return result;
}
/**
* Creates a function that clones a given object using the assignment `func`.
*
* @private
* @param {Function} func The assignment function.
* @returns {Function} Returns the new cloner function.
*/
function createCloner(func) {
return function(object) {
return func({}, object);
};
}
/**
* A specialized version of `_.spread` which flattens the spread array into
* the arguments of the invoked `func`.
*
* @private
* @param {Function} func The function to spread arguments over.
* @param {number} start The start position of the spread.
* @returns {Function} Returns the new function.
*/
function flatSpread(func, start) {
return function() {
var length = arguments.length,
lastIndex = length - 1,
args = Array(length);
while (length--) {
args[length] = arguments[length];
}
var array = args[start],
otherArgs = args.slice(0, start);
if (array) {
push.apply(otherArgs, array);
}
if (start != lastIndex) {
push.apply(otherArgs, args.slice(start + 1));
}
return func.apply(this, otherArgs);
};
}
/**
* Creates a function that wraps `func` and uses `cloner` to clone the first
* argument it receives.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} cloner The function to clone arguments.
* @returns {Function} Returns the new immutable function.
*/
function wrapImmutable(func, cloner) {
return function() {
var length = arguments.length;
if (!length) {
return;
}
var args = Array(length);
while (length--) {
args[length] = arguments[length];
}
var result = args[0] = cloner.apply(undefined, args);
func.apply(undefined, args);
return result;
};
}
/**
* The base implementation of `convert` which accepts a `util` object of methods
* required to perform conversions.
*
* @param {Object} util The util object.
* @param {string} name The name of the function to convert.
* @param {Function} func The function to convert.
* @param {Object} [options] The options object.
* @param {boolean} [options.cap=true] Specify capping iteratee arguments.
* @param {boolean} [options.curry=true] Specify currying.
* @param {boolean} [options.fixed=true] Specify fixed arity.
* @param {boolean} [options.immutable=true] Specify immutable operations.
* @param {boolean} [options.rearg=true] Specify rearranging arguments.
* @returns {Function|Object} Returns the converted function or object.
*/
function baseConvert(util, name, func, options) {
var isLib = typeof name == 'function',
isObj = name === Object(name);
if (isObj) {
options = func;
func = name;
name = undefined;
}
if (func == null) {
throw new TypeError;
}
options || (options = {});
var config = {
'cap': 'cap' in options ? options.cap : true,
'curry': 'curry' in options ? options.curry : true,
'fixed': 'fixed' in options ? options.fixed : true,
'immutable': 'immutable' in options ? options.immutable : true,
'rearg': 'rearg' in options ? options.rearg : true
};
var defaultHolder = isLib ? func : fallbackHolder,
forceCurry = ('curry' in options) && options.curry,
forceFixed = ('fixed' in options) && options.fixed,
forceRearg = ('rearg' in options) && options.rearg,
pristine = isLib ? func.runInContext() : undefined;
var helpers = isLib ? func : {
'ary': util.ary,
'assign': util.assign,
'clone': util.clone,
'curry': util.curry,
'forEach': util.forEach,
'isArray': util.isArray,
'isError': util.isError,
'isFunction': util.isFunction,
'isWeakMap': util.isWeakMap,
'iteratee': util.iteratee,
'keys': util.keys,
'rearg': util.rearg,
'toInteger': util.toInteger,
'toPath': util.toPath
};
var ary = helpers.ary,
assign = helpers.assign,
clone = helpers.clone,
curry = helpers.curry,
each = helpers.forEach,
isArray = helpers.isArray,
isError = helpers.isError,
isFunction = helpers.isFunction,
isWeakMap = helpers.isWeakMap,
keys = helpers.keys,
rearg = helpers.rearg,
toInteger = helpers.toInteger,
toPath = helpers.toPath;
var aryMethodKeys = keys(mapping.aryMethod);
var wrappers = {
'castArray': function(castArray) {
return function() {
var value = arguments[0];
return isArray(value)
? castArray(cloneArray(value))
: castArray.apply(undefined, arguments);
};
},
'iteratee': function(iteratee) {
return function() {
var func = arguments[0],
arity = arguments[1],
result = iteratee(func, arity),
length = result.length;
if (config.cap && typeof arity == 'number') {
arity = arity > 2 ? (arity - 2) : 1;
return (length && length <= arity) ? result : baseAry(result, arity);
}
return result;
};
},
'mixin': function(mixin) {
return function(source) {
var func = this;
if (!isFunction(func)) {
return mixin(func, Object(source));
}
var pairs = [];
each(keys(source), function(key) {
if (isFunction(source[key])) {
pairs.push([key, func.prototype[key]]);
}
});
mixin(func, Object(source));
each(pairs, function(pair) {
var value = pair[1];
if (isFunction(value)) {
func.prototype[pair[0]] = value;
} else {
delete func.prototype[pair[0]];
}
});
return func;
};
},
'nthArg': function(nthArg) {
return function(n) {
var arity = n < 0 ? 1 : (toInteger(n) + 1);
return curry(nthArg(n), arity);
};
},
'rearg': function(rearg) {
return function(func, indexes) {
var arity = indexes ? indexes.length : 0;
return curry(rearg(func, indexes), arity);
};
},
'runInContext': function(runInContext) {
return function(context) {
return baseConvert(util, runInContext(context), options);
};
}
};
/*--------------------------------------------------------------------------*/
/**
* Casts `func` to a function with an arity capped iteratee if needed.
*
* @private
* @param {string} name The name of the function to inspect.
* @param {Function} func The function to inspect.
* @returns {Function} Returns the cast function.
*/
function castCap(name, func) {
if (config.cap) {
var indexes = mapping.iterateeRearg[name];
if (indexes) {
return iterateeRearg(func, indexes);
}
var n = !isLib && mapping.iterateeAry[name];
if (n) {
return iterateeAry(func, n);
}
}
return func;
}
/**
* Casts `func` to a curried function if needed.
*
* @private
* @param {string} name The name of the function to inspect.
* @param {Function} func The function to inspect.
* @param {number} n The arity of `func`.
* @returns {Function} Returns the cast function.
*/
function castCurry(name, func, n) {
return (forceCurry || (config.curry && n > 1))
? curry(func, n)
: func;
}
/**
* Casts `func` to a fixed arity function if needed.
*
* @private
* @param {string} name The name of the function to inspect.
* @param {Function} func The function to inspect.
* @param {number} n The arity cap.
* @returns {Function} Returns the cast function.
*/
function castFixed(name, func, n) {
if (config.fixed && (forceFixed || !mapping.skipFixed[name])) {
var data = mapping.methodSpread[name],
start = data && data.start;
return start === undefined ? ary(func, n) : flatSpread(func, start);
}
return func;
}
/**
* Casts `func` to an rearged function if needed.
*
* @private
* @param {string} name The name of the function to inspect.
* @param {Function} func The function to inspect.
* @param {number} n The arity of `func`.
* @returns {Function} Returns the cast function.
*/
function castRearg(name, func, n) {
return (config.rearg && n > 1 && (forceRearg || !mapping.skipRearg[name]))
? rearg(func, mapping.methodRearg[name] || mapping.aryRearg[n])
: func;
}
/**
* Creates a clone of `object` by `path`.
*
* @private
* @param {Object} object The object to clone.
* @param {Array|string} path The path to clone by.
* @returns {Object} Returns the cloned object.
*/
function cloneByPath(object, path) {
path = toPath(path);
var index = -1,
length = path.length,
lastIndex = length - 1,
result = clone(Object(object)),
nested = result;
while (nested != null && ++index < length) {
var key = path[index],
value = nested[key];
if (value != null &&
!(isFunction(value) || isError(value) || isWeakMap(value))) {
nested[key] = clone(index == lastIndex ? value : Object(value));
}
nested = nested[key];
}
return result;
}
/**
* Converts `lodash` to an immutable auto-curried iteratee-first data-last
* version with conversion `options` applied.
*
* @param {Object} [options] The options object. See `baseConvert` for more details.
* @returns {Function} Returns the converted `lodash`.
*/
function convertLib(options) {
return _.runInContext.convert(options)(undefined);
}
/**
* Create a converter function for `func` of `name`.
*
* @param {string} name The name of the function to convert.
* @param {Function} func The function to convert.
* @returns {Function} Returns the new converter function.
*/
function createConverter(name, func) {
var realName = mapping.aliasToReal[name] || name,
methodName = mapping.remap[realName] || realName,
oldOptions = options;
return function(options) {
var newUtil = isLib ? pristine : helpers,
newFunc = isLib ? pristine[methodName] : func,
newOptions = assign(assign({}, oldOptions), options);
return baseConvert(newUtil, realName, newFunc, newOptions);
};
}
/**
* Creates a function that wraps `func` to invoke its iteratee, with up to `n`
* arguments, ignoring any additional arguments.
*
* @private
* @param {Function} func The function to cap iteratee arguments for.
* @param {number} n The arity cap.
* @returns {Function} Returns the new function.
*/
function iterateeAry(func, n) {
return overArg(func, function(func) {
return typeof func == 'function' ? baseAry(func, n) : func;
});
}
/**
* Creates a function that wraps `func` to invoke its iteratee with arguments
* arranged according to the specified `indexes` where the argument value at
* the first index is provided as the first argument, the argument value at
* the second index is provided as the second argument, and so on.
*
* @private
* @param {Function} func The function to rearrange iteratee arguments for.
* @param {number[]} indexes The arranged argument indexes.
* @returns {Function} Returns the new function.
*/
function iterateeRearg(func, indexes) {
return overArg(func, function(func) {
var n = indexes.length;
return baseArity(rearg(baseAry(func, n), indexes), n);
});
}
/**
* Creates a function that invokes `func` with its first 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() {
var length = arguments.length;
if (!length) {
return func();
}
var args = Array(length);
while (length--) {
args[length] = arguments[length];
}
var index = config.rearg ? 0 : (length - 1);
args[index] = transform(args[index]);
return func.apply(undefined, args);
};
}
/**
* Creates a function that wraps `func` and applys the conversions
* rules by `name`.
*
* @private
* @param {string} name The name of the function to wrap.
* @param {Function} func The function to wrap.
* @returns {Function} Returns the converted function.
*/
function wrap(name, func, placeholder) {
var result,
realName = mapping.aliasToReal[name] || name,
wrapped = func,
wrapper = wrappers[realName];
if (wrapper) {
wrapped = wrapper(func);
}
else if (config.immutable) {
if (mapping.mutate.array[realName]) {
wrapped = wrapImmutable(func, cloneArray);
}
else if (mapping.mutate.object[realName]) {
wrapped = wrapImmutable(func, createCloner(func));
}
else if (mapping.mutate.set[realName]) {
wrapped = wrapImmutable(func, cloneByPath);
}
}
each(aryMethodKeys, function(aryKey) {
each(mapping.aryMethod[aryKey], function(otherName) {
if (realName == otherName) {
var data = mapping.methodSpread[realName],
afterRearg = data && data.afterRearg;
result = afterRearg
? castFixed(realName, castRearg(realName, wrapped, aryKey), aryKey)
: castRearg(realName, castFixed(realName, wrapped, aryKey), aryKey);
result = castCap(realName, result);
result = castCurry(realName, result, aryKey);
return false;
}
});
return !result;
});
result || (result = wrapped);
if (result == func) {
result = forceCurry ? curry(result, 1) : function() {
return func.apply(this, arguments);
};
}
result.convert = createConverter(realName, func);
result.placeholder = func.placeholder = placeholder;
return result;
}
/*--------------------------------------------------------------------------*/
if (!isObj) {
return wrap(name, func, defaultHolder);
}
var _ = func;
// Convert methods by ary cap.
var pairs = [];
each(aryMethodKeys, function(aryKey) {
each(mapping.aryMethod[aryKey], function(key) {
var func = _[mapping.remap[key] || key];
if (func) {
pairs.push([key, wrap(key, func, _)]);
}
});
});
// Convert remaining methods.
each(keys(_), function(key) {
var func = _[key];
if (typeof func == 'function') {
var length = pairs.length;
while (length--) {
if (pairs[length][0] == key) {
return;
}
}
func.convert = createConverter(key, func);
pairs.push([key, func]);
}
});
// Assign to `_` leaving `_.prototype` unchanged to allow chaining.
each(pairs, function(pair) {
_[pair[0]] = pair[1];
});
_.convert = convertLib;
_.placeholder = _;
// Assign aliases.
each(keys(_), function(key) {
each(mapping.realToAlias[key] || [], function(alias) {
_[alias] = _[key];
});
});
return _;
}
module.exports = baseConvert;
webpack://frontend-mybets/../../node_modules/lodash/fp/_mapping.js
/** Used to map aliases to their real names. */
exports.aliasToReal = {
// Lodash aliases.
'each': 'forEach',
'eachRight': 'forEachRight',
'entries': 'toPairs',
'entriesIn': 'toPairsIn',
'extend': 'assignIn',
'extendAll': 'assignInAll',
'extendAllWith': 'assignInAllWith',
'extendWith': 'assignInWith',
'first': 'head',
// Methods that are curried variants of others.
'conforms': 'conformsTo',
'matches': 'isMatch',
'property': 'get',
// Ramda aliases.
'__': 'placeholder',
'F': 'stubFalse',
'T': 'stubTrue',
'all': 'every',
'allPass': 'overEvery',
'always': 'constant',
'any': 'some',
'anyPass': 'overSome',
'apply': 'spread',
'assoc': 'set',
'assocPath': 'set',
'complement': 'negate',
'compose': 'flowRight',
'contains': 'includes',
'dissoc': 'unset',
'dissocPath': 'unset',
'dropLast': 'dropRight',
'dropLastWhile': 'dropRightWhile',
'equals': 'isEqual',
'identical': 'eq',
'indexBy': 'keyBy',
'init': 'initial',
'invertObj': 'invert',
'juxt': 'over',
'omitAll': 'omit',
'nAry': 'ary',
'path': 'get',
'pathEq': 'matchesProperty',
'pathOr': 'getOr',
'paths': 'at',
'pickAll': 'pick',
'pipe': 'flow',
'pluck': 'map',
'prop': 'get',
'propEq': 'matchesProperty',
'propOr': 'getOr',
'props': 'at',
'symmetricDifference': 'xor',
'symmetricDifferenceBy': 'xorBy',
'symmetricDifferenceWith': 'xorWith',
'takeLast': 'takeRight',
'takeLastWhile': 'takeRightWhile',
'unapply': 'rest',
'unnest': 'flatten',
'useWith': 'overArgs',
'where': 'conformsTo',
'whereEq': 'isMatch',
'zipObj': 'zipObject'
};
/** Used to map ary to method names. */
exports.aryMethod = {
'1': [
'assignAll', 'assignInAll', 'attempt', 'castArray', 'ceil', 'create',
'curry', 'curryRight', 'defaultsAll', 'defaultsDeepAll', 'floor', 'flow',
'flowRight', 'fromPairs', 'invert', 'iteratee', 'memoize', 'method', 'mergeAll',
'methodOf', 'mixin', 'nthArg', 'over', 'overEvery', 'overSome','rest', 'reverse',
'round', 'runInContext', 'spread', 'template', 'trim', 'trimEnd', 'trimStart',
'uniqueId', 'words', 'zipAll'
],
'2': [
'add', 'after', 'ary', 'assign', 'assignAllWith', 'assignIn', 'assignInAllWith',
'at', 'before', 'bind', 'bindAll', 'bindKey', 'chunk', 'cloneDeepWith',
'cloneWith', 'concat', 'conformsTo', 'countBy', 'curryN', 'curryRightN',
'debounce', 'defaults', 'defaultsDeep', 'defaultTo', 'delay', 'difference',
'divide', 'drop', 'dropRight', 'dropRightWhile', 'dropWhile', 'endsWith', 'eq',
'every', 'filter', 'find', 'findIndex', 'findKey', 'findLast', 'findLastIndex',
'findLastKey', 'flatMap', 'flatMapDeep', 'flattenDepth', 'forEach',
'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'get',
'groupBy', 'gt', 'gte', 'has', 'hasIn', 'includes', 'indexOf', 'intersection',
'invertBy', 'invoke', 'invokeMap', 'isEqual', 'isMatch', 'join', 'keyBy',
'lastIndexOf', 'lt', 'lte', 'map', 'mapKeys', 'mapValues', 'matchesProperty',
'maxBy', 'meanBy', 'merge', 'mergeAllWith', 'minBy', 'multiply', 'nth', 'omit',
'omitBy', 'overArgs', 'pad', 'padEnd', 'padStart', 'parseInt', 'partial',
'partialRight', 'partition', 'pick', 'pickBy', 'propertyOf', 'pull', 'pullAll',
'pullAt', 'random', 'range', 'rangeRight', 'rearg', 'reject', 'remove',
'repeat', 'restFrom', 'result', 'sampleSize', 'some', 'sortBy', 'sortedIndex',
'sortedIndexOf', 'sortedLastIndex', 'sortedLastIndexOf', 'sortedUniqBy',
'split', 'spreadFrom', 'startsWith', 'subtract', 'sumBy', 'take', 'takeRight',
'takeRightWhile', 'takeWhile', 'tap', 'throttle', 'thru', 'times', 'trimChars',
'trimCharsEnd', 'trimCharsStart', 'truncate', 'union', 'uniqBy', 'uniqWith',
'unset', 'unzipWith', 'without', 'wrap', 'xor', 'zip', 'zipObject',
'zipObjectDeep'
],
'3': [
'assignInWith', 'assignWith', 'clamp', 'differenceBy', 'differenceWith',
'findFrom', 'findIndexFrom', 'findLastFrom', 'findLastIndexFrom', 'getOr',
'includesFrom', 'indexOfFrom', 'inRange', 'intersectionBy', 'intersectionWith',
'invokeArgs', 'invokeArgsMap', 'isEqualWith', 'isMatchWith', 'flatMapDepth',
'lastIndexOfFrom', 'mergeWith', 'orderBy', 'padChars', 'padCharsEnd',
'padCharsStart', 'pullAllBy', 'pullAllWith', 'rangeStep', 'rangeStepRight',
'reduce', 'reduceRight', 'replace', 'set', 'slice', 'sortedIndexBy',
'sortedLastIndexBy', 'transform', 'unionBy', 'unionWith', 'update', 'xorBy',
'xorWith', 'zipWith'
],
'4': [
'fill', 'setWith', 'updateWith'
]
};
/** Used to map ary to rearg configs. */
exports.aryRearg = {
'2': [1, 0],
'3': [2, 0, 1],
'4': [3, 2, 0, 1]
};
/** Used to map method names to their iteratee ary. */
exports.iterateeAry = {
'dropRightWhile': 1,
'dropWhile': 1,
'every': 1,
'filter': 1,
'find': 1,
'findFrom': 1,
'findIndex': 1,
'findIndexFrom': 1,
'findKey': 1,
'findLast': 1,
'findLastFrom': 1,
'findLastIndex': 1,
'findLastIndexFrom': 1,
'findLastKey': 1,
'flatMap': 1,
'flatMapDeep': 1,
'flatMapDepth': 1,
'forEach': 1,
'forEachRight': 1,
'forIn': 1,
'forInRight': 1,
'forOwn': 1,
'forOwnRight': 1,
'map': 1,
'mapKeys': 1,
'mapValues': 1,
'partition': 1,
'reduce': 2,
'reduceRight': 2,
'reject': 1,
'remove': 1,
'some': 1,
'takeRightWhile': 1,
'takeWhile': 1,
'times': 1,
'transform': 2
};
/** Used to map method names to iteratee rearg configs. */
exports.iterateeRearg = {
'mapKeys': [1],
'reduceRight': [1, 0]
};
/** Used to map method names to rearg configs. */
exports.methodRearg = {
'assignInAllWith': [1, 0],
'assignInWith': [1, 2, 0],
'assignAllWith': [1, 0],
'assignWith': [1, 2, 0],
'differenceBy': [1, 2, 0],
'differenceWith': [1, 2, 0],
'getOr': [2, 1, 0],
'intersectionBy': [1, 2, 0],
'intersectionWith': [1, 2, 0],
'isEqualWith': [1, 2, 0],
'isMatchWith': [2, 1, 0],
'mergeAllWith': [1, 0],
'mergeWith': [1, 2, 0],
'padChars': [2, 1, 0],
'padCharsEnd': [2, 1, 0],
'padCharsStart': [2, 1, 0],
'pullAllBy': [2, 1, 0],
'pullAllWith': [2, 1, 0],
'rangeStep': [1, 2, 0],
'rangeStepRight': [1, 2, 0],
'setWith': [3, 1, 2, 0],
'sortedIndexBy': [2, 1, 0],
'sortedLastIndexBy': [2, 1, 0],
'unionBy': [1, 2, 0],
'unionWith': [1, 2, 0],
'updateWith': [3, 1, 2, 0],
'xorBy': [1, 2, 0],
'xorWith': [1, 2, 0],
'zipWith': [1, 2, 0]
};
/** Used to map method names to spread configs. */
exports.methodSpread = {
'assignAll': { 'start': 0 },
'assignAllWith': { 'start': 0 },
'assignInAll': { 'start': 0 },
'assignInAllWith': { 'start': 0 },
'defaultsAll': { 'start': 0 },
'defaultsDeepAll': { 'start': 0 },
'invokeArgs': { 'start': 2 },
'invokeArgsMap': { 'start': 2 },
'mergeAll': { 'start': 0 },
'mergeAllWith': { 'start': 0 },
'partial': { 'start': 1 },
'partialRight': { 'start': 1 },
'without': { 'start': 1 },
'zipAll': { 'start': 0 }
};
/** Used to identify methods which mutate arrays or objects. */
exports.mutate = {
'array': {
'fill': true,
'pull': true,
'pullAll': true,
'pullAllBy': true,
'pullAllWith': true,
'pullAt': true,
'remove': true,
'reverse': true
},
'object': {
'assign': true,
'assignAll': true,
'assignAllWith': true,
'assignIn': true,
'assignInAll': true,
'assignInAllWith': true,
'assignInWith': true,
'assignWith': true,
'defaults': true,
'defaultsAll': true,
'defaultsDeep': true,
'defaultsDeepAll': true,
'merge': true,
'mergeAll': true,
'mergeAllWith': true,
'mergeWith': true,
},
'set': {
'set': true,
'setWith': true,
'unset': true,
'update': true,
'updateWith': true
}
};
/** Used to map real names to their aliases. */
exports.realToAlias = (function() {
var hasOwnProperty = Object.prototype.hasOwnProperty,
object = exports.aliasToReal,
result = {};
for (var key in object) {
var value = object[key];
if (hasOwnProperty.call(result, value)) {
result[value].push(key);
} else {
result[value] = [key];
}
}
return result;
}());
/** Used to map method names to other names. */
exports.remap = {
'assignAll': 'assign',
'assignAllWith': 'assignWith',
'assignInAll': 'assignIn',
'assignInAllWith': 'assignInWith',
'curryN': 'curry',
'curryRightN': 'curryRight',
'defaultsAll': 'defaults',
'defaultsDeepAll': 'defaultsDeep',
'findFrom': 'find',
'findIndexFrom': 'findIndex',
'findLastFrom': 'findLast',
'findLastIndexFrom': 'findLastIndex',
'getOr': 'get',
'includesFrom': 'includes',
'indexOfFrom': 'indexOf',
'invokeArgs': 'invoke',
'invokeArgsMap': 'invokeMap',
'lastIndexOfFrom': 'lastIndexOf',
'mergeAll': 'merge',
'mergeAllWith': 'mergeWith',
'padChars': 'pad',
'padCharsEnd': 'padEnd',
'padCharsStart': 'padStart',
'propertyOf': 'get',
'rangeStep': 'range',
'rangeStepRight': 'rangeRight',
'restFrom': 'rest',
'spreadFrom': 'spread',
'trimChars': 'trim',
'trimCharsEnd': 'trimEnd',
'trimCharsStart': 'trimStart',
'zipAll': 'zip'
};
/** Used to track methods that skip fixing their arity. */
exports.skipFixed = {
'castArray': true,
'flow': true,
'flowRight': true,
'iteratee': true,
'mixin': true,
'rearg': true,
'runInContext': true
};
/** Used to track methods that skip rearranging arguments. */
exports.skipRearg = {
'add': true,
'assign': true,
'assignIn': true,
'bind': true,
'bindKey': true,
'concat': true,
'difference': true,
'divide': true,
'eq': true,
'gt': true,
'gte': true,
'isEqual': true,
'lt': true,
'lte': true,
'matchesProperty': true,
'merge': true,
'multiply': true,
'overArgs': true,
'partial': true,
'partialRight': true,
'propertyOf': true,
'random': true,
'range': true,
'rangeRight': true,
'subtract': true,
'zip': true,
'zipObject': true,
'zipObjectDeep': true
};
webpack://frontend-mybets/../../node_modules/lodash/fp/_util.js
module.exports = {
'ary': require('../ary'),
'assign': require('../_baseAssign'),
'clone': require('../clone'),
'curry': require('../curry'),
'forEach': require('../_arrayEach'),
'isArray': require('../isArray'),
'isError': require('../isError'),
'isFunction': require('../isFunction'),
'isWeakMap': require('../isWeakMap'),
'iteratee': require('../iteratee'),
'keys': require('../_baseKeys'),
'rearg': require('../rearg'),
'toInteger': require('../toInteger'),
'toPath': require('../toPath')
};
webpack://frontend-mybets/../../node_modules/lodash/fp/convert.js
var baseConvert = require('./_baseConvert'),
util = require('./_util');
/**
* Converts `func` of `name` to an immutable auto-curried iteratee-first data-last
* version with conversion `options` applied. If `name` is an object its methods
* will be converted.
*
* @param {string} name The name of the function to wrap.
* @param {Function} [func] The function to wrap.
* @param {Object} [options] The options object. See `baseConvert` for more details.
* @returns {Function|Object} Returns the converted function or object.
*/
function convert(name, func, options) {
return baseConvert(util, name, func, options);
}
module.exports = convert;
webpack://frontend-mybets/../../node_modules/lodash/fp/get.js
var convert = require('./convert'),
func = convert('get', require('../get'));
func.placeholder = require('./placeholder');
module.exports = func;
webpack://frontend-mybets/../../node_modules/lodash/fp/placeholder.js
/**
* The default argument placeholder value for methods.
*
* @type {Object}
*/
module.exports = {};
webpack://frontend-mybets/../../node_modules/lodash/fp/set.js
var convert = require('./convert'),
func = convert('set', require('../set'));
func.placeholder = require('./placeholder');
module.exports = func;
webpack://frontend-mybets/../../node_modules/lodash/get.js
var baseGet = require('./_baseGet');
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/
function get(object, path, defaultValue) {
var result = object == null ? undefined : baseGet(object, path);
return result === undefined ? defaultValue : result;
}
module.exports = get;
webpack://frontend-mybets/../../node_modules/lodash/has.js
var baseHas = require('./_baseHas'),
hasPath = require('./_hasPath');
/**
* Checks if `path` is a direct property of `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = { 'a': { 'b': 2 } };
* var other = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.has(object, 'a');
* // => true
*
* _.has(object, 'a.b');
* // => true
*
* _.has(object, ['a', 'b']);
* // => true
*
* _.has(other, 'a');
* // => false
*/
function has(object, path) {
return object != null && hasPath(object, path, baseHas);
}
module.exports = has;
webpack://frontend-mybets/../../node_modules/lodash/hasIn.js
var baseHasIn = require('./_baseHasIn'),
hasPath = require('./_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);
}
module.exports = hasIn;
webpack://frontend-mybets/../../node_modules/lodash/head.js
/**
* Gets the first element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @alias first
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the first element of `array`.
* @example
*
* _.head([1, 2, 3]);
* // => 1
*
* _.head([]);
* // => undefined
*/
function head(array) {
return (array && array.length) ? array[0] : undefined;
}
module.exports = head;
webpack://frontend-mybets/../../node_modules/lodash/identity.js
/**
* This method returns the first argument it receives.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'a': 1 };
*
* console.log(_.identity(object) === object);
* // => true
*/
function identity(value) {
return value;
}
module.exports = identity;
webpack://frontend-mybets/../../node_modules/lodash/includes.js
var baseIndexOf = require('./_baseIndexOf'),
isArrayLike = require('./isArrayLike'),
isString = require('./isString'),
toInteger = require('./toInteger'),
values = require('./values');
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Checks if `value` is in `collection`. If `collection` is a string, it's
* checked for a substring of `value`, otherwise
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* is used for equality comparisons. If `fromIndex` is negative, it's used as
* the offset from the end of `collection`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {boolean} Returns `true` if `value` is found, else `false`.
* @example
*
* _.includes([1, 2, 3], 1);
* // => true
*
* _.includes([1, 2, 3], 1, 2);
* // => false
*
* _.includes({ 'a': 1, 'b': 2 }, 1);
* // => true
*
* _.includes('abcd', 'bc');
* // => true
*/
function includes(collection, value, fromIndex, guard) {
collection = isArrayLike(collection) ? collection : values(collection);
fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;
var length = collection.length;
if (fromIndex < 0) {
fromIndex = nativeMax(length + fromIndex, 0);
}
return isString(collection)
? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)
: (!!length && baseIndexOf(collection, value, fromIndex) > -1);
}
module.exports = includes;
webpack://frontend-mybets/../../node_modules/lodash/indexOf.js
var baseIndexOf = require('./_baseIndexOf'),
toInteger = require('./toInteger');
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Gets the index at which the first occurrence of `value` is found in `array`
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. If `fromIndex` is negative, it's used as the
* offset from the end of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.indexOf([1, 2, 1, 2], 2);
* // => 1
*
* // Search from the `fromIndex`.
* _.indexOf([1, 2, 1, 2], 2, 2);
* // => 3
*/
function indexOf(array, value, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger(fromIndex);
if (index < 0) {
index = nativeMax(length + index, 0);
}
return baseIndexOf(array, value, index);
}
module.exports = indexOf;
webpack://frontend-mybets/../../node_modules/lodash/isArguments.js
var baseIsArguments = require('./_baseIsArguments'),
isObjectLike = require('./isObjectLike');
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
!propertyIsEnumerable.call(value, 'callee');
};
module.exports = isArguments;
webpack://frontend-mybets/../../node_modules/lodash/isArray.js
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
module.exports = isArray;
webpack://frontend-mybets/../../node_modules/lodash/isArrayLike.js
var isFunction = require('./isFunction'),
isLength = require('./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(value.length) && !isFunction(value);
}
module.exports = isArrayLike;
webpack://frontend-mybets/../../node_modules/lodash/isArrayLikeObject.js
var isArrayLike = require('./isArrayLike'),
isObjectLike = require('./isObjectLike');
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return isObjectLike(value) && isArrayLike(value);
}
module.exports = isArrayLikeObject;
webpack://frontend-mybets/../../node_modules/lodash/isBuffer.js
var root = require('./_root'),
stubFalse = require('./stubFalse');
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/
var isBuffer = nativeIsBuffer || stubFalse;
module.exports = isBuffer;
webpack://frontend-mybets/../../node_modules/lodash/isEmpty.js
var baseKeys = require('./_baseKeys'),
getTag = require('./_getTag'),
isArguments = require('./isArguments'),
isArray = require('./isArray'),
isArrayLike = require('./isArrayLike'),
isBuffer = require('./isBuffer'),
isPrototype = require('./_isPrototype'),
isTypedArray = require('./isTypedArray');
/** `Object#toString` result references. */
var mapTag = '[object Map]',
setTag = '[object Set]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Checks if `value` is an empty object, collection, map, or set.
*
* Objects are considered empty if they have no own enumerable string keyed
* properties.
*
* Array-like values such as `arguments` objects, arrays, buffers, strings, or
* jQuery-like collections are considered empty if they have a `length` of `0`.
* Similarly, maps and sets are considered empty if they have a `size` of `0`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is empty, else `false`.
* @example
*
* _.isEmpty(null);
* // => true
*
* _.isEmpty(true);
* // => true
*
* _.isEmpty(1);
* // => true
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({ 'a': 1 });
* // => false
*/
function isEmpty(value) {
if (value == null) {
return true;
}
if (isArrayLike(value) &&
(isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||
isBuffer(value) || isTypedArray(value) || isArguments(value))) {
return !value.length;
}
var tag = getTag(value);
if (tag == mapTag || tag == setTag) {
return !value.size;
}
if (isPrototype(value)) {
return !baseKeys(value).length;
}
for (var key in value) {
if (hasOwnProperty.call(value, key)) {
return false;
}
}
return true;
}
module.exports = isEmpty;
webpack://frontend-mybets/../../node_modules/lodash/isEqual.js
var baseIsEqual = require('./_baseIsEqual');
/**
* Performs a deep comparison between two values to determine if they are
* equivalent.
*
* **Note:** This method supports comparing arrays, array buffers, booleans,
* date objects, error objects, maps, numbers, `Object` objects, regexes,
* sets, strings, symbols, and typed arrays. `Object` objects are compared
* by their own, not inherited, enumerable properties. Functions and DOM
* nodes are compared by strict equality, i.e. `===`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.isEqual(object, other);
* // => true
*
* object === other;
* // => false
*/
function isEqual(value, other) {
return baseIsEqual(value, other);
}
module.exports = isEqual;
webpack://frontend-mybets/../../node_modules/lodash/isError.js
var baseGetTag = require('./_baseGetTag'),
isObjectLike = require('./isObjectLike'),
isPlainObject = require('./isPlainObject');
/** `Object#toString` result references. */
var domExcTag = '[object DOMException]',
errorTag = '[object Error]';
/**
* Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
* `SyntaxError`, `TypeError`, or `URIError` object.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an error object, else `false`.
* @example
*
* _.isError(new Error);
* // => true
*
* _.isError(Error);
* // => false
*/
function isError(value) {
if (!isObjectLike(value)) {
return false;
}
var tag = baseGetTag(value);
return tag == errorTag || tag == domExcTag ||
(typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value));
}
module.exports = isError;
webpack://frontend-mybets/../../node_modules/lodash/isFinite.js
var root = require('./_root');
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsFinite = root.isFinite;
/**
* Checks if `value` is a finite primitive number.
*
* **Note:** This method is based on
* [`Number.isFinite`](https://mdn.io/Number/isFinite).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
* @example
*
* _.isFinite(3);
* // => true
*
* _.isFinite(Number.MIN_VALUE);
* // => true
*
* _.isFinite(Infinity);
* // => false
*
* _.isFinite('3');
* // => false
*/
function isFinite(value) {
return typeof value == 'number' && nativeIsFinite(value);
}
module.exports = isFinite;
webpack://frontend-mybets/../../node_modules/lodash/isFunction.js
var baseGetTag = require('./_baseGetTag'),
isObject = require('./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(value)) {
return false;
}
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag = baseGetTag(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
module.exports = isFunction;
webpack://frontend-mybets/../../node_modules/lodash/isLength.js
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
module.exports = isLength;
webpack://frontend-mybets/../../node_modules/lodash/isMap.js
var baseIsMap = require('./_baseIsMap'),
baseUnary = require('./_baseUnary'),
nodeUtil = require('./_nodeUtil');
/* Node.js helper references. */
var nodeIsMap = nodeUtil && nodeUtil.isMap;
/**
* Checks if `value` is classified as a `Map` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
* @example
*
* _.isMap(new Map);
* // => true
*
* _.isMap(new WeakMap);
* // => false
*/
var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;
module.exports = isMap;
webpack://frontend-mybets/../../node_modules/lodash/isNaN.js
var isNumber = require('./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(value) {
// An `NaN` primitive is the only value that is not equal to itself.
// Perform the `toStringTag` check first to avoid errors with some
// ActiveX objects in IE.
return isNumber(value) && value != +value;
}
module.exports = isNaN;
webpack://frontend-mybets/../../node_modules/lodash/isNull.js
/**
* Checks if `value` is `null`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `null`, else `false`.
* @example
*
* _.isNull(null);
* // => true
*
* _.isNull(void 0);
* // => false
*/
function isNull(value) {
return value === null;
}
module.exports = isNull;
webpack://frontend-mybets/../../node_modules/lodash/isNumber.js
var baseGetTag = require('./_baseGetTag'),
isObjectLike = require('./isObjectLike');
/** `Object#toString` result references. */
var numberTag = '[object Number]';
/**
* Checks if `value` is classified as a `Number` primitive or object.
*
* **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
* classified as numbers, use the `_.isFinite` method.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a number, else `false`.
* @example
*
* _.isNumber(3);
* // => true
*
* _.isNumber(Number.MIN_VALUE);
* // => true
*
* _.isNumber(Infinity);
* // => true
*
* _.isNumber('3');
* // => false
*/
function isNumber(value) {
return typeof value == 'number' ||
(isObjectLike(value) && baseGetTag(value) == numberTag);
}
module.exports = isNumber;
webpack://frontend-mybets/../../node_modules/lodash/isObject.js
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return value != null && (type == 'object' || type == 'function');
}
module.exports = isObject;
webpack://frontend-mybets/../../node_modules/lodash/isObjectLike.js
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return value != null && typeof value == 'object';
}
module.exports = isObjectLike;
webpack://frontend-mybets/../../node_modules/lodash/isPlainObject.js
var baseGetTag = require('./_baseGetTag'),
getPrototype = require('./_getPrototype'),
isObjectLike = require('./isObjectLike');
/** `Object#toString` result references. */
var objectTag = '[object Object]';
/** Used for built-in method references. */
var funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to infer the `Object` constructor. */
var objectCtorString = funcToString.call(Object);
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @static
* @memberOf _
* @since 0.8.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
return false;
}
var proto = getPrototype(value);
if (proto === null) {
return true;
}
var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
return typeof Ctor == 'function' && Ctor instanceof Ctor &&
funcToString.call(Ctor) == objectCtorString;
}
module.exports = isPlainObject;
webpack://frontend-mybets/../../node_modules/lodash/isRegExp.js
var baseIsRegExp = require('./_baseIsRegExp'),
baseUnary = require('./_baseUnary'),
nodeUtil = require('./_nodeUtil');
/* Node.js helper references. */
var nodeIsRegExp = nodeUtil && nodeUtil.isRegExp;
/**
* Checks if `value` is classified as a `RegExp` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
* @example
*
* _.isRegExp(/abc/);
* // => true
*
* _.isRegExp('/abc/');
* // => false
*/
var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp;
module.exports = isRegExp;
webpack://frontend-mybets/../../node_modules/lodash/isSet.js
var baseIsSet = require('./_baseIsSet'),
baseUnary = require('./_baseUnary'),
nodeUtil = require('./_nodeUtil');
/* Node.js helper references. */
var nodeIsSet = nodeUtil && nodeUtil.isSet;
/**
* Checks if `value` is classified as a `Set` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
* @example
*
* _.isSet(new Set);
* // => true
*
* _.isSet(new WeakSet);
* // => false
*/
var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;
module.exports = isSet;
webpack://frontend-mybets/../../node_modules/lodash/isString.js
var baseGetTag = require('./_baseGetTag'),
isArray = require('./isArray'),
isObjectLike = require('./isObjectLike');
/** `Object#toString` result references. */
var stringTag = '[object String]';
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a string, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' ||
(!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);
}
module.exports = isString;
webpack://frontend-mybets/../../node_modules/lodash/isSymbol.js
var baseGetTag = require('./_baseGetTag'),
isObjectLike = require('./isObjectLike');
/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && baseGetTag(value) == symbolTag);
}
module.exports = isSymbol;
webpack://frontend-mybets/../../node_modules/lodash/isTypedArray.js
var baseIsTypedArray = require('./_baseIsTypedArray'),
baseUnary = require('./_baseUnary'),
nodeUtil = require('./_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;
module.exports = isTypedArray;
webpack://frontend-mybets/../../node_modules/lodash/isUndefined.js
/**
* Checks if `value` is `undefined`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
* @example
*
* _.isUndefined(void 0);
* // => true
*
* _.isUndefined(null);
* // => false
*/
function isUndefined(value) {
return value === undefined;
}
module.exports = isUndefined;
webpack://frontend-mybets/../../node_modules/lodash/isWeakMap.js
var getTag = require('./_getTag'),
isObjectLike = require('./isObjectLike');
/** `Object#toString` result references. */
var weakMapTag = '[object WeakMap]';
/**
* Checks if `value` is classified as a `WeakMap` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a weak map, else `false`.
* @example
*
* _.isWeakMap(new WeakMap);
* // => true
*
* _.isWeakMap(new Map);
* // => false
*/
function isWeakMap(value) {
return isObjectLike(value) && getTag(value) == weakMapTag;
}
module.exports = isWeakMap;
webpack://frontend-mybets/../../node_modules/lodash/iteratee.js
var baseClone = require('./_baseClone'),
baseIteratee = require('./_baseIteratee');
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1;
/**
* Creates a function that invokes `func` with the arguments of the created
* function. If `func` is a property name, the created function returns the
* property value for a given element. If `func` is an array or object, the
* created function returns `true` for elements that contain the equivalent
* source properties, otherwise it returns `false`.
*
* @static
* @since 4.0.0
* @memberOf _
* @category Util
* @param {*} [func=_.identity] The value to convert to a callback.
* @returns {Function} Returns the callback.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
* // => [{ 'user': 'barney', 'age': 36, 'active': true }]
*
* // The `_.matchesProperty` iteratee shorthand.
* _.filter(users, _.iteratee(['user', 'fred']));
* // => [{ 'user': 'fred', 'age': 40 }]
*
* // The `_.property` iteratee shorthand.
* _.map(users, _.iteratee('user'));
* // => ['barney', 'fred']
*
* // Create custom iteratee shorthands.
* _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
* return !_.isRegExp(func) ? iteratee(func) : function(string) {
* return func.test(string);
* };
* });
*
* _.filter(['abc', 'def'], /ef/);
* // => ['def']
*/
function iteratee(func) {
return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG));
}
module.exports = iteratee;
webpack://frontend-mybets/../../node_modules/lodash/join.js
/** Used for built-in method references. */
var arrayProto = Array.prototype;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeJoin = arrayProto.join;
/**
* Converts all elements in `array` into a string separated by `separator`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to convert.
* @param {string} [separator=','] The element separator.
* @returns {string} Returns the joined string.
* @example
*
* _.join(['a', 'b', 'c'], '~');
* // => 'a~b~c'
*/
function join(array, separator) {
return array == null ? '' : nativeJoin.call(array, separator);
}
module.exports = join;
webpack://frontend-mybets/../../node_modules/lodash/keys.js
var arrayLikeKeys = require('./_arrayLikeKeys'),
baseKeys = require('./_baseKeys'),
isArrayLike = require('./isArrayLike');
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
module.exports = keys;
webpack://frontend-mybets/../../node_modules/lodash/keysIn.js
var arrayLikeKeys = require('./_arrayLikeKeys'),
baseKeysIn = require('./_baseKeysIn'),
isArrayLike = require('./isArrayLike');
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn(object) {
return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
}
module.exports = keysIn;
webpack://frontend-mybets/../../node_modules/lodash/last.js
/**
* Gets the last element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the last element of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
*/
function last(array) {
var length = array == null ? 0 : array.length;
return length ? array[length - 1] : undefined;
}
module.exports = last;
webpack://frontend-mybets/../../node_modules/lodash/lodash.js
/**
* @license
* Lodash <https://lodash.com/>
* Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
;(function() {
/** Used as a safe reference for `undefined` in pre-ES5 environments. */
var undefined;
/** Used as the semantic version number. */
var VERSION = '4.17.21';
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/** Error message constants. */
var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.',
FUNC_ERROR_TEXT = 'Expected a function',
INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`';
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used as the maximum memoize cache size. */
var MAX_MEMOIZE_SIZE = 500;
/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
CLONE_FLAT_FLAG = 2,
CLONE_SYMBOLS_FLAG = 4;
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_BOUND_FLAG = 4,
WRAP_CURRY_FLAG = 8,
WRAP_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 as default options for `_.truncate`. */
var DEFAULT_TRUNC_LENGTH = 30,
DEFAULT_TRUNC_OMISSION = '...';
/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
HOT_SPAN = 16;
/** Used to indicate the type of lazy iteratees. */
var LAZY_FILTER_FLAG = 1,
LAZY_MAP_FLAG = 2,
LAZY_WHILE_FLAG = 3;
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0,
MAX_SAFE_INTEGER = 9007199254740991,
MAX_INTEGER = 1.7976931348623157e+308,
NAN = 0 / 0;
/** Used as references for the maximum length and index of an array. */
var MAX_ARRAY_LENGTH = 4294967295,
MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,
HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
/** Used to associate wrap methods with their bit flags. */
var wrapFlags = [
['ary', WRAP_ARY_FLAG],
['bind', WRAP_BIND_FLAG],
['bindKey', WRAP_BIND_KEY_FLAG],
['curry', WRAP_CURRY_FLAG],
['curryRight', WRAP_CURRY_RIGHT_FLAG],
['flip', WRAP_FLIP_FLAG],
['partial', WRAP_PARTIAL_FLAG],
['partialRight', WRAP_PARTIAL_RIGHT_FLAG],
['rearg', WRAP_REARG_FLAG]
];
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
asyncTag = '[object AsyncFunction]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
domExcTag = '[object DOMException]',
errorTag = '[object Error]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
mapTag = '[object Map]',
numberTag = '[object Number]',
nullTag = '[object Null]',
objectTag = '[object Object]',
promiseTag = '[object Promise]',
proxyTag = '[object Proxy]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]',
undefinedTag = '[object Undefined]',
weakMapTag = '[object WeakMap]',
weakSetTag = '[object WeakSet]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to match empty string literals in compiled template source. */
var reEmptyStringLeading = /\b__p \+= '';/g,
reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
/** Used to match HTML entities and HTML characters. */
var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g,
reUnescapedHtml = /[&<>"']/g,
reHasEscapedHtml = RegExp(reEscapedHtml.source),
reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
/** Used to match template delimiters. */
var reEscape = /<%-([\s\S]+?)%>/g,
reEvaluate = /<%([\s\S]+?)%>/g,
reInterpolate = /<%=([\s\S]+?)%>/g;
/** Used to match property names within property paths. */
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
reIsPlainProp = /^\w*$/,
rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g,
reHasRegExpChar = RegExp(reRegExpChar.source);
/** Used to match leading whitespace. */
var reTrimStart = /^\s+/;
/** Used to match a single whitespace character. */
var reWhitespace = /\s/;
/** Used to match wrap detail comments. */
var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,
reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
reSplitDetails = /,? & /;
/** Used to match words composed of alphanumeric characters. */
var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
/**
* Used to validate the `validate` option in `_.template` variable.
*
* Forbids characters which could potentially change the meaning of the function argument definition:
* - "()," (modification of function parameters)
* - "=" (default value)
* - "[]{}" (destructuring of function parameters)
* - "/" (beginning of a comment)
* - whitespace
*/
var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/;
/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;
/**
* Used to match
* [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components).
*/
var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/** 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 host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/** Used to match Latin Unicode letters (excluding mathematical operators). */
var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
/** Used to ensure capturing order of template delimiters. */
var reNoMatch = /($^)/;
/** Used to match unescaped characters in compiled string literals. */
var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
rsComboMarksRange = '\\u0300-\\u036f',
reComboHalfMarksRange = '\\ufe20-\\ufe2f',
rsComboSymbolsRange = '\\u20d0-\\u20ff',
rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
rsDingbatRange = '\\u2700-\\u27bf',
rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
rsPunctuationRange = '\\u2000-\\u206f',
rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000',
rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
rsVarRange = '\\ufe0e\\ufe0f',
rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
/** Used to compose unicode capture groups. */
var rsApos = "['\u2019]",
rsAstral = '[' + rsAstralRange + ']',
rsBreak = '[' + rsBreakRange + ']',
rsCombo = '[' + rsComboRange + ']',
rsDigits = '\\d+',
rsDingbat = '[' + rsDingbatRange + ']',
rsLower = '[' + rsLowerRange + ']',
rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
rsFitz = '\\ud83c[\\udffb-\\udfff]',
rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
rsNonAstral = '[^' + rsAstralRange + ']',
rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
rsUpper = '[' + rsUpperRange + ']',
rsZWJ = '\\u200d';
/** Used to compose unicode regexes. */
var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')',
rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')',
rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
reOptMod = rsModifier + '?',
rsOptVar = '[' + rsVarRange + ']?',
rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])',
rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])',
rsSeq = rsOptVar + reOptMod + rsOptJoin,
rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,
rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
/** Used to match apostrophes. */
var reApos = RegExp(rsApos, 'g');
/**
* Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
* [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
*/
var reComboMark = RegExp(rsCombo, 'g');
/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
/** Used to match complex or compound words. */
var reUnicodeWord = RegExp([
rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')',
rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower,
rsUpper + '+' + rsOptContrUpper,
rsOrdUpper,
rsOrdLower,
rsDigits,
rsEmoji
].join('|'), 'g');
/** 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 + ']');
/** Used to detect strings that need a more robust regexp to match words. */
var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
/** Used to assign default `context` object properties. */
var contextProps = [
'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array',
'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object',
'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array',
'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap',
'_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout'
];
/** Used to make template sourceURLs easier to identify. */
var templateCounter = -1;
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[funcTag] =
typedArrayTags[mapTag] = typedArrayTags[numberTag] =
typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
typedArrayTags[setTag] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag] = false;
/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[argsTag] = cloneableTags[arrayTag] =
cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
cloneableTags[boolTag] = cloneableTags[dateTag] =
cloneableTags[float32Tag] = cloneableTags[float64Tag] =
cloneableTags[int8Tag] = cloneableTags[int16Tag] =
cloneableTags[int32Tag] = cloneableTags[mapTag] =
cloneableTags[numberTag] = cloneableTags[objectTag] =
cloneableTags[regexpTag] = cloneableTags[setTag] =
cloneableTags[stringTag] = cloneableTags[symbolTag] =
cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
cloneableTags[errorTag] = cloneableTags[funcTag] =
cloneableTags[weakMapTag] = false;
/** Used to map Latin Unicode letters to basic Latin letters. */
var deburredLetters = {
// Latin-1 Supplement block.
'\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
'\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
'\xc7': 'C', '\xe7': 'c',
'\xd0': 'D', '\xf0': 'd',
'\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
'\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
'\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
'\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
'\xd1': 'N', '\xf1': 'n',
'\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
'\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
'\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
'\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
'\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
'\xc6': 'Ae', '\xe6': 'ae',
'\xde': 'Th', '\xfe': 'th',
'\xdf': 'ss',
// Latin Extended-A block.
'\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
'\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
'\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
'\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
'\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
'\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
'\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
'\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
'\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
'\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
'\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
'\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
'\u0134': 'J', '\u0135': 'j',
'\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
'\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
'\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
'\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
'\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
'\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
'\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
'\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
'\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
'\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
'\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
'\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
'\u0163': 't', '\u0165': 't', '\u0167': 't',
'\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
'\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
'\u0174': 'W', '\u0175': 'w',
'\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
'\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
'\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
'\u0132': 'IJ', '\u0133': 'ij',
'\u0152': 'Oe', '\u0153': 'oe',
'\u0149': "'n", '\u017f': 's'
};
/** Used to map characters to HTML entities. */
var htmlEscapes = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
/** Used to map HTML entities to characters. */
var htmlUnescapes = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
''': "'"
};
/** Used to escape characters for inclusion in compiled string literals. */
var stringEscapes = {
'\\': '\\',
"'": "'",
'\n': 'n',
'\r': 'r',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
/** Built-in method references without a dependency on `root`. */
var freeParseFloat = parseFloat,
freeParseInt = parseInt;
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
/** 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')();
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports && freeGlobal.process;
/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
try {
// Use `util.types` for Node.js 10+.
var types = freeModule && freeModule.require && freeModule.require('util').types;
if (types) {
return types;
}
// Legacy `process.binding('util')` for Node.js < 10.
return freeProcess && freeProcess.binding && freeProcess.binding('util');
} catch (e) {}
}());
/* Node.js helper references. */
var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer,
nodeIsDate = nodeUtil && nodeUtil.isDate,
nodeIsMap = nodeUtil && nodeUtil.isMap,
nodeIsRegExp = nodeUtil && nodeUtil.isRegExp,
nodeIsSet = nodeUtil && nodeUtil.isSet,
nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
/*--------------------------------------------------------------------------*/
/**
* 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);
}
/**
* A specialized version of `baseAggregator` for arrays.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform keys.
* @param {Object} accumulator The initial aggregated object.
* @returns {Function} Returns `accumulator`.
*/
function arrayAggregator(array, setter, iteratee, accumulator) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
var value = array[index];
setter(accumulator, value, iteratee(value), array);
}
return accumulator;
}
/**
* 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;
}
/**
* A specialized version of `_.forEachRight` 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 arrayEachRight(array, iteratee) {
var length = array == null ? 0 : array.length;
while (length--) {
if (iteratee(array[length], length, array) === false) {
break;
}
}
return array;
}
/**
* A specialized version of `_.every` 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 all elements pass the predicate check,
* else `false`.
*/
function arrayEvery(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (!predicate(array[index], index, array)) {
return false;
}
}
return true;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* A specialized version of `_.reduceRight` 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 last element of `array` as
* the initial value.
* @returns {*} Returns the accumulated value.
*/
function arrayReduceRight(array, iteratee, accumulator, initAccum) {
var length = array == null ? 0 : array.length;
if (initAccum && length) {
accumulator = array[--length];
}
while (length--) {
accumulator = iteratee(accumulator, array[length], length, array);
}
return accumulator;
}
/**
* 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;
}
/**
* Gets the size of an ASCII `string`.
*
* @private
* @param {string} string The string inspect.
* @returns {number} Returns the string size.
*/
var asciiSize = baseProperty('length');
/**
* 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('');
}
/**
* Splits an ASCII `string` into an array of its words.
*
* @private
* @param {string} The string to inspect.
* @returns {Array} Returns the words of `string`.
*/
function asciiWords(string) {
return string.match(reAsciiWord) || [];
}
/**
* The base implementation of methods like `_.findKey` and `_.findLastKey`,
* without support for iteratee shorthands, which iterates over `collection`
* using `eachFunc`.
*
* @private
* @param {Array|Object} collection The collection to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {Function} eachFunc The function to iterate over `collection`.
* @returns {*} Returns the found element or its key, else `undefined`.
*/
function baseFindKey(collection, predicate, eachFunc) {
var result;
eachFunc(collection, function(value, key, collection) {
if (predicate(value, key, collection)) {
result = key;
return false;
}
});
return result;
}
/**
* 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;
}
/**
* 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);
}
/**
* This function is like `baseIndexOf` except that it accepts a comparator.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @param {Function} comparator The comparator invoked per element.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseIndexOfWith(array, value, fromIndex, comparator) {
var index = fromIndex - 1,
length = array.length;
while (++index < length) {
if (comparator(array[index], value)) {
return index;
}
}
return -1;
}
/**
* 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;
}
/**
* The base implementation of `_.mean` and `_.meanBy` 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 mean.
*/
function baseMean(array, iteratee) {
var length = array == null ? 0 : array.length;
return length ? (baseSum(array, iteratee) / length) : NAN;
}
/**
* 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];
};
}
/**
* The base implementation of `_.propertyOf` without support for deep paths.
*
* @private
* @param {Object} object The object to query.
* @returns {Function} Returns the new accessor function.
*/
function basePropertyOf(object) {
return function(key) {
return object == null ? undefined : object[key];
};
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array
* of key-value pairs for `object` 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 key-value pairs.
*/
function baseToPairs(object, props) {
return arrayMap(props, function(key) {
return [key, object[key]];
});
}
/**
* The base implementation of `_.trim`.
*
* @private
* @param {string} string The string to trim.
* @returns {string} Returns the trimmed string.
*/
function baseTrim(string) {
return string
? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')
: string;
}
/**
* 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);
};
}
/**
* 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];
});
}
/**
* 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);
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
* letters to basic Latin letters.
*
* @private
* @param {string} letter The matched letter to deburr.
* @returns {string} Returns the deburred letter.
*/
var deburrLetter = basePropertyOf(deburredLetters);
/**
* Used by `_.escape` to convert characters to HTML entities.
*
* @private
* @param {string} chr The matched character to escape.
* @returns {string} Returns the escaped character.
*/
var escapeHtmlChar = basePropertyOf(htmlEscapes);
/**
* Used by `_.template` to escape characters for inclusion in compiled string literals.
*
* @private
* @param {string} chr The matched character to escape.
* @returns {string} Returns the escaped character.
*/
function escapeStringChar(chr) {
return '\\' + stringEscapes[chr];
}
/**
* 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];
}
/**
* 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);
}
/**
* Checks if `string` contains a word composed of Unicode symbols.
*
* @private
* @param {string} string The string to inspect.
* @returns {boolean} Returns `true` if a word is found, else `false`.
*/
function hasUnicodeWord(string) {
return reHasUnicodeWord.test(string);
}
/**
* Converts `iterator` to an array.
*
* @private
* @param {Object} iterator The iterator to convert.
* @returns {Array} Returns the converted array.
*/
function iteratorToArray(iterator) {
var data,
result = [];
while (!(data = iterator.next()).done) {
result.push(data.value);
}
return result;
}
/**
* 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;
}
/**
* 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));
};
}
/**
* 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;
}
/**
* 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;
}
/**
* Converts `set` to its value-value pairs.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the value-value pairs.
*/
function setToPairs(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = [value, value];
});
return result;
}
/**
* 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;
}
/**
* A specialized version of `_.lastIndexOf` 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 strictLastIndexOf(array, value, fromIndex) {
var index = fromIndex + 1;
while (index--) {
if (array[index] === value) {
return index;
}
}
return index;
}
/**
* Gets the number of symbols in `string`.
*
* @private
* @param {string} string The string to inspect.
* @returns {number} Returns the string size.
*/
function stringSize(string) {
return hasUnicode(string)
? unicodeSize(string)
: asciiSize(string);
}
/**
* 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);
}
/**
* Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
* character of `string`.
*
* @private
* @param {string} string The string to inspect.
* @returns {number} Returns the index of the last non-whitespace character.
*/
function trimmedEndIndex(string) {
var index = string.length;
while (index-- && reWhitespace.test(string.charAt(index))) {}
return index;
}
/**
* Used by `_.unescape` to convert HTML entities to characters.
*
* @private
* @param {string} chr The matched character to unescape.
* @returns {string} Returns the unescaped character.
*/
var unescapeHtmlChar = basePropertyOf(htmlUnescapes);
/**
* Gets the size of a Unicode `string`.
*
* @private
* @param {string} string The string inspect.
* @returns {number} Returns the string size.
*/
function unicodeSize(string) {
var result = reUnicode.lastIndex = 0;
while (reUnicode.test(string)) {
++result;
}
return result;
}
/**
* 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) || [];
}
/**
* Splits a Unicode `string` into an array of its words.
*
* @private
* @param {string} The string to inspect.
* @returns {Array} Returns the words of `string`.
*/
function unicodeWords(string) {
return string.match(reUnicodeWord) || [];
}
/*--------------------------------------------------------------------------*/
/**
* Create a new pristine `lodash` function using the `context` object.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Util
* @param {Object} [context=root] The context object.
* @returns {Function} Returns a new `lodash` function.
* @example
*
* _.mixin({ 'foo': _.constant('foo') });
*
* var lodash = _.runInContext();
* lodash.mixin({ 'bar': lodash.constant('bar') });
*
* _.isFunction(_.foo);
* // => true
* _.isFunction(_.bar);
* // => false
*
* lodash.isFunction(lodash.foo);
* // => false
* lodash.isFunction(lodash.bar);
* // => true
*
* // Create a suped-up `defer` in Node.js.
* var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
*/
var runInContext = (function runInContext(context) {
context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps));
/** Built-in constructor references. */
var Array = context.Array,
Date = context.Date,
Error = context.Error,
Function = context.Function,
Math = context.Math,
Object = context.Object,
RegExp = context.RegExp,
String = context.String,
TypeError = context.TypeError;
/** Used for built-in method references. */
var arrayProto = Array.prototype,
funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to detect overreaching core-js shims. */
var coreJsData = context['__core-js_shared__'];
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to generate unique IDs. */
var idCounter = 0;
/** 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) : '';
}());
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/** Used to infer the `Object` constructor. */
var objectCtorString = funcToString.call(Object);
/** Used to restore the original `_` reference in `_.noConflict`. */
var oldDash = root._;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/** Built-in value references. */
var Buffer = moduleExports ? context.Buffer : undefined,
Symbol = context.Symbol,
Uint8Array = context.Uint8Array,
allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined,
getPrototype = overArg(Object.getPrototypeOf, Object),
objectCreate = Object.create,
propertyIsEnumerable = objectProto.propertyIsEnumerable,
splice = arrayProto.splice,
spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined,
symIterator = Symbol ? Symbol.iterator : undefined,
symToStringTag = Symbol ? Symbol.toStringTag : undefined;
var defineProperty = (function() {
try {
var func = getNative(Object, 'defineProperty');
func({}, '', {});
return func;
} catch (e) {}
}());
/** Mocked built-ins. */
var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout,
ctxNow = Date && Date.now !== root.Date.now && Date.now,
ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeCeil = Math.ceil,
nativeFloor = Math.floor,
nativeGetSymbols = Object.getOwnPropertySymbols,
nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
nativeIsFinite = context.isFinite,
nativeJoin = arrayProto.join,
nativeKeys = overArg(Object.keys, Object),
nativeMax = Math.max,
nativeMin = Math.min,
nativeNow = Date.now,
nativeParseInt = context.parseInt,
nativeRandom = Math.random,
nativeReverse = arrayProto.reverse;
/* Built-in method references that are verified to be native. */
var DataView = getNative(context, 'DataView'),
Map = getNative(context, 'Map'),
Promise = getNative(context, 'Promise'),
Set = getNative(context, 'Set'),
WeakMap = getNative(context, 'WeakMap'),
nativeCreate = getNative(Object, 'create');
/** Used to store function metadata. */
var metaMap = WeakMap && new WeakMap;
/** Used to lookup unminified function names. */
var realNames = {};
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
mapCtorString = toSource(Map),
promiseCtorString = toSource(Promise),
setCtorString = toSource(Set),
weakMapCtorString = toSource(WeakMap);
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,
symbolToString = symbolProto ? symbolProto.toString : undefined;
/*------------------------------------------------------------------------*/
/**
* Creates a `lodash` object which wraps `value` to enable implicit method
* chain sequences. Methods that operate on and return arrays, collections,
* and functions can be chained together. Methods that retrieve a single value
* or may return a primitive value will automatically end the chain sequence
* and return the unwrapped value. Otherwise, the value must be unwrapped
* with `_#value`.
*
* Explicit chain sequences, which must be unwrapped with `_#value`, may be
* enabled using `_.chain`.
*
* The execution of chained methods is lazy, that is, it's deferred until
* `_#value` is implicitly or explicitly called.
*
* Lazy evaluation allows several methods to support shortcut fusion.
* Shortcut fusion is an optimization to merge iteratee calls; this avoids
* the creation of intermediate arrays and can greatly reduce the number of
* iteratee executions. Sections of a chain sequence qualify for shortcut
* fusion if the section is applied to an array and iteratees accept only
* one argument. The heuristic for whether a section qualifies for shortcut
* fusion is subject to change.
*
* Chaining is supported in custom builds as long as the `_#value` method is
* directly or indirectly included in the build.
*
* In addition to lodash methods, wrappers have `Array` and `String` methods.
*
* The wrapper `Array` methods are:
* `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
*
* The wrapper `String` methods are:
* `replace` and `split`
*
* The wrapper methods that support shortcut fusion are:
* `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
* `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
* `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
*
* The chainable wrapper methods are:
* `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
* `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
* `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
* `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
* `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
* `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
* `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
* `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
* `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
* `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
* `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
* `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
* `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
* `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
* `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
* `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
* `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
* `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
* `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
* `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
* `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
* `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
* `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
* `zipObject`, `zipObjectDeep`, and `zipWith`
*
* The wrapper methods that are **not** chainable by default are:
* `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
* `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
* `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
* `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
* `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
* `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
* `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
* `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
* `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
* `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
* `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
* `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
* `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
* `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
* `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
* `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
* `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
* `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
* `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
* `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
* `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
* `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
* `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
* `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
* `upperFirst`, `value`, and `words`
*
* @name _
* @constructor
* @category Seq
* @param {*} value The value to wrap in a `lodash` instance.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* function square(n) {
* return n * n;
* }
*
* var wrapped = _([1, 2, 3]);
*
* // Returns an unwrapped value.
* wrapped.reduce(_.add);
* // => 6
*
* // Returns a wrapped value.
* var squares = wrapped.map(square);
*
* _.isArray(squares);
* // => false
*
* _.isArray(squares.value());
* // => true
*/
function lodash(value) {
if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
if (value instanceof LodashWrapper) {
return value;
}
if (hasOwnProperty.call(value, '__wrapped__')) {
return wrapperClone(value);
}
}
return new LodashWrapper(value);
}
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} proto The object to inherit from.
* @returns {Object} Returns the new object.
*/
var baseCreate = (function() {
function object() {}
return function(proto) {
if (!isObject(proto)) {
return {};
}
if (objectCreate) {
return objectCreate(proto);
}
object.prototype = proto;
var result = new object;
object.prototype = undefined;
return result;
};
}());
/**
* The function whose prototype chain sequence wrappers inherit from.
*
* @private
*/
function baseLodash() {
// No operation performed.
}
/**
* 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;
}
/**
* By default, the template delimiters used by lodash are like those in
* embedded Ruby (ERB) as well as ES2015 template strings. Change the
* following template settings to use alternative delimiters.
*
* @static
* @memberOf _
* @type {Object}
*/
lodash.templateSettings = {
/**
* Used to detect `data` property values to be HTML-escaped.
*
* @memberOf _.templateSettings
* @type {RegExp}
*/
'escape': reEscape,
/**
* Used to detect code to be evaluated.
*
* @memberOf _.templateSettings
* @type {RegExp}
*/
'evaluate': reEvaluate,
/**
* Used to detect `data` property values to inject.
*
* @memberOf _.templateSettings
* @type {RegExp}
*/
'interpolate': reInterpolate,
/**
* Used to reference the data object in the template text.
*
* @memberOf _.templateSettings
* @type {string}
*/
'variable': '',
/**
* Used to import variables into the compiled template.
*
* @memberOf _.templateSettings
* @type {Object}
*/
'imports': {
/**
* A reference to the `lodash` function.
*
* @memberOf _.templateSettings.imports
* @type {Function}
*/
'_': lodash
}
};
// Ensure wrappers are instances of `baseLodash`.
lodash.prototype = baseLodash.prototype;
lodash.prototype.constructor = lodash;
LodashWrapper.prototype = baseCreate(baseLodash.prototype);
LodashWrapper.prototype.constructor = LodashWrapper;
/*------------------------------------------------------------------------*/
/**
* 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__ = [];
}
/**
* Creates a clone of the lazy wrapper object.
*
* @private
* @name clone
* @memberOf LazyWrapper
* @returns {Object} Returns the cloned `LazyWrapper` object.
*/
function lazyClone() {
var result = new LazyWrapper(this.__wrapped__);
result.__actions__ = copyArray(this.__actions__);
result.__dir__ = this.__dir__;
result.__filtered__ = this.__filtered__;
result.__iteratees__ = copyArray(this.__iteratees__);
result.__takeCount__ = this.__takeCount__;
result.__views__ = copyArray(this.__views__);
return result;
}
/**
* Reverses the direction of lazy iteration.
*
* @private
* @name reverse
* @memberOf LazyWrapper
* @returns {Object} Returns the new reversed `LazyWrapper` object.
*/
function lazyReverse() {
if (this.__filtered__) {
var result = new LazyWrapper(this);
result.__dir__ = -1;
result.__filtered__ = true;
} else {
result = this.clone();
result.__dir__ *= -1;
}
return result;
}
/**
* Extracts the unwrapped value from its lazy wrapper.
*
* @private
* @name value
* @memberOf LazyWrapper
* @returns {*} Returns the unwrapped value.
*/
function lazyValue() {
var array = this.__wrapped__.value(),
dir = this.__dir__,
isArr = isArray(array),
isRight = dir < 0,
arrLength = isArr ? array.length : 0,
view = getView(0, arrLength, this.__views__),
start = view.start,
end = view.end,
length = end - start,
index = isRight ? end : (start - 1),
iteratees = this.__iteratees__,
iterLength = iteratees.length,
resIndex = 0,
takeCount = nativeMin(length, this.__takeCount__);
if (!isArr || (!isRight && arrLength == length && takeCount == length)) {
return baseWrapperValue(array, this.__actions__);
}
var result = [];
outer:
while (length-- && resIndex < takeCount) {
index += dir;
var iterIndex = -1,
value = array[index];
while (++iterIndex < iterLength) {
var data = iteratees[iterIndex],
iteratee = data.iteratee,
type = data.type,
computed = iteratee(value);
if (type == LAZY_MAP_FLAG) {
value = computed;
} else if (!computed) {
if (type == LAZY_FILTER_FLAG) {
continue outer;
} else {
break outer;
}
}
}
result[resIndex++] = value;
}
return result;
}
// Ensure `LazyWrapper` is an instance of `baseLodash`.
LazyWrapper.prototype = baseCreate(baseLodash.prototype);
LazyWrapper.prototype.constructor = LazyWrapper;
/*------------------------------------------------------------------------*/
/**
* 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]);
}
}
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear() {
this.__data__ = nativeCreate ? nativeCreate(null) : {};
this.size = 0;
}
/**
* 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;
}
/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(key) {
var data = this.__data__;
if (nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty.call(data, key) ? data[key] : undefined;
}
/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(key) {
var data = this.__data__;
return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
}
/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/
function hashSet(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
return this;
}
// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
/*------------------------------------------------------------------------*/
/**
* 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]);
}
}
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
/**
* 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;
}
/**
* 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];
}
/**
* 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;
}
/**
* 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;
}
// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
/*------------------------------------------------------------------------*/
/**
* 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]);
}
}
/**
* 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
};
}
/**
* 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;
}
/**
* 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);
}
/**
* 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);
}
/**
* 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;
}
// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
/*------------------------------------------------------------------------*/
/**
*
* 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]);
}
}
/**
* Adds `value` to the array cache.
*
* @private
* @name add
* @memberOf SetCache
* @alias push
* @param {*} value The value to cache.
* @returns {Object} Returns the cache instance.
*/
function setCacheAdd(value) {
this.__data__.set(value, HASH_UNDEFINED);
return this;
}
/**
* 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);
}
// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
SetCache.prototype.has = setCacheHas;
/*------------------------------------------------------------------------*/
/**
* 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;
}
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = new ListCache;
this.size = 0;
}
/**
* 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;
}
/**
* 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);
}
/**
* 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);
}
/**
* 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;
}
// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
/*------------------------------------------------------------------------*/
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
var isArr = isArray(value),
isArg = !isArr && isArguments(value),
isBuff = !isArr && !isArg && isBuffer(value),
isType = !isArr && !isArg && !isBuff && isTypedArray(value),
skipIndexes = isArr || isArg || isBuff || isType,
result = skipIndexes ? baseTimes(value.length, String) : [],
length = result.length;
for (var key in value) {
if ((inherited || hasOwnProperty.call(value, key)) &&
!(skipIndexes && (
// Safari 9 has enumerable `arguments.length` in strict mode.
key == 'length' ||
// Node.js 0.10 has enumerable non-index properties on buffers.
(isBuff && (key == 'offset' || key == 'parent')) ||
// PhantomJS 2 has enumerable non-index properties on typed arrays.
(isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
// Skip index properties.
isIndex(key, length)
))) {
result.push(key);
}
}
return result;
}
/**
* A specialized version of `_.sample` for arrays.
*
* @private
* @param {Array} array The array to sample.
* @returns {*} Returns the random element.
*/
function arraySample(array) {
var length = array.length;
return length ? array[baseRandom(0, length - 1)] : undefined;
}
/**
* A specialized version of `_.sampleSize` for arrays.
*
* @private
* @param {Array} array The array to sample.
* @param {number} n The number of elements to sample.
* @returns {Array} Returns the random elements.
*/
function arraySampleSize(array, n) {
return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length));
}
/**
* A specialized version of `_.shuffle` for arrays.
*
* @private
* @param {Array} array The array to shuffle.
* @returns {Array} Returns the new shuffled array.
*/
function arrayShuffle(array) {
return shuffleSelf(copyArray(array));
}
/**
* This function is like `assignValue` except that it doesn't assign
* `undefined` values.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignMergeValue(object, key, value) {
if ((value !== undefined && !eq(object[key], value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value);
}
}
/**
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignValue(object, key, value) {
var objValue = object[key];
if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value);
}
}
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq(array[length][0], key)) {
return length;
}
}
return -1;
}
/**
* Aggregates elements of `collection` on `accumulator` with keys transformed
* by `iteratee` and values set by `setter`.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform keys.
* @param {Object} accumulator The initial aggregated object.
* @returns {Function} Returns `accumulator`.
*/
function baseAggregator(collection, setter, iteratee, accumulator) {
baseEach(collection, function(value, key, collection) {
setter(accumulator, value, iteratee(value), collection);
});
return accumulator;
}
/**
* The base implementation of `_.assign` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssign(object, source) {
return object && copyObject(source, keys(source), object);
}
/**
* The base implementation of `_.assignIn` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssignIn(object, source) {
return object && copyObject(source, keysIn(source), object);
}
/**
* 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;
}
}
/**
* The base implementation of `_.at` without support for individual paths.
*
* @private
* @param {Object} object The object to iterate over.
* @param {string[]} paths The property paths to pick.
* @returns {Array} Returns the picked elements.
*/
function baseAt(object, paths) {
var index = -1,
length = paths.length,
result = Array(length),
skip = object == null;
while (++index < length) {
result[index] = skip ? undefined : get(object, paths[index]);
}
return result;
}
/**
* 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;
}
/**
* The base implementation of `_.clone` and `_.cloneDeep` which tracks
* traversed objects.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} bitmask The bitmask flags.
* 1 - Deep clone
* 2 - Flatten inherited properties
* 4 - Clone symbols
* @param {Function} [customizer] The function to customize cloning.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The parent object of `value`.
* @param {Object} [stack] Tracks traversed objects and their clone counterparts.
* @returns {*} Returns the cloned value.
*/
function baseClone(value, bitmask, customizer, key, object, stack) {
var result,
isDeep = bitmask & CLONE_DEEP_FLAG,
isFlat = bitmask & CLONE_FLAT_FLAG,
isFull = bitmask & CLONE_SYMBOLS_FLAG;
if (customizer) {
result = object ? customizer(value, key, object, stack) : customizer(value);
}
if (result !== undefined) {
return result;
}
if (!isObject(value)) {
return value;
}
var isArr = isArray(value);
if (isArr) {
result = initCloneArray(value);
if (!isDeep) {
return copyArray(value, result);
}
} else {
var tag = getTag(value),
isFunc = tag == funcTag || tag == genTag;
if (isBuffer(value)) {
return cloneBuffer(value, isDeep);
}
if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
result = (isFlat || isFunc) ? {} : initCloneObject(value);
if (!isDeep) {
return isFlat
? copySymbolsIn(value, baseAssignIn(result, value))
: copySymbols(value, baseAssign(result, value));
}
} else {
if (!cloneableTags[tag]) {
return object ? value : {};
}
result = initCloneByTag(value, tag, isDeep);
}
}
// Check for circular references and return its corresponding clone.
stack || (stack = new Stack);
var stacked = stack.get(value);
if (stacked) {
return stacked;
}
stack.set(value, result);
if (isSet(value)) {
value.forEach(function(subValue) {
result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
});
} else if (isMap(value)) {
value.forEach(function(subValue, key) {
result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
}
var keysFunc = isFull
? (isFlat ? getAllKeysIn : getAllKeys)
: (isFlat ? keysIn : keys);
var props = isArr ? undefined : keysFunc(value);
arrayEach(props || value, function(subValue, key) {
if (props) {
key = subValue;
subValue = value[key];
}
// Recursively populate clone (susceptible to call stack limits).
assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
return result;
}
/**
* The base implementation of `_.conforms` which doesn't clone `source`.
*
* @private
* @param {Object} source The object of property predicates to conform to.
* @returns {Function} Returns the new spec function.
*/
function baseConforms(source) {
var props = keys(source);
return function(object) {
return baseConformsTo(object, source, props);
};
}
/**
* The base implementation of `_.conformsTo` which accepts `props` to check.
*
* @private
* @param {Object} object The object to inspect.
* @param {Object} source The object of property predicates to conform to.
* @returns {boolean} Returns `true` if `object` conforms, else `false`.
*/
function baseConformsTo(object, source, props) {
var length = props.length;
if (object == null) {
return !length;
}
object = Object(object);
while (length--) {
var key = props[length],
predicate = source[key],
value = object[key];
if ((value === undefined && !(key in object)) || !predicate(value)) {
return false;
}
}
return true;
}
/**
* The base implementation of `_.delay` and `_.defer` which accepts `args`
* to provide to `func`.
*
* @private
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay invocation.
* @param {Array} args The arguments to provide to `func`.
* @returns {number|Object} Returns the timer id or timeout object.
*/
function baseDelay(func, wait, args) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
return setTimeout(function() { func.apply(undefined, args); }, wait);
}
/**
* The base implementation of methods like `_.difference` without support
* for excluding multiple arrays or iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Array} values The values to exclude.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
*/
function baseDifference(array, values, iteratee, comparator) {
var index = -1,
includes = arrayIncludes,
isCommon = true,
length = array.length,
result = [],
valuesLength = values.length;
if (!length) {
return result;
}
if (iteratee) {
values = arrayMap(values, baseUnary(iteratee));
}
if (comparator) {
includes = arrayIncludesWith;
isCommon = false;
}
else if (values.length >= LARGE_ARRAY_SIZE) {
includes = cacheHas;
isCommon = false;
values = new SetCache(values);
}
outer:
while (++index < length) {
var value = array[index],
computed = iteratee == null ? value : iteratee(value);
value = (comparator || value !== 0) ? value : 0;
if (isCommon && computed === computed) {
var valuesIndex = valuesLength;
while (valuesIndex--) {
if (values[valuesIndex] === computed) {
continue outer;
}
}
result.push(value);
}
else if (!includes(values, computed, comparator)) {
result.push(value);
}
}
return result;
}
/**
* 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);
/**
* The base implementation of `_.forEachRight` 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 baseEachRight = createBaseEach(baseForOwnRight, true);
/**
* The base implementation of `_.every` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`
*/
function baseEvery(collection, predicate) {
var result = true;
baseEach(collection, function(value, index, collection) {
result = !!predicate(value, index, collection);
return result;
});
return result;
}
/**
* The base implementation of methods like `_.max` and `_.min` which accepts a
* `comparator` to determine the extremum value.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The iteratee invoked per iteration.
* @param {Function} comparator The comparator used to compare values.
* @returns {*} Returns the extremum value.
*/
function baseExtremum(array, iteratee, comparator) {
var index = -1,
length = array.length;
while (++index < length) {
var value = array[index],
current = iteratee(value);
if (current != null && (computed === undefined
? (current === current && !isSymbol(current))
: comparator(current, computed)
)) {
var computed = current,
result = value;
}
}
return result;
}
/**
* The base implementation of `_.fill` without an iteratee call guard.
*
* @private
* @param {Array} array The array to fill.
* @param {*} value The value to fill `array` with.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns `array`.
*/
function baseFill(array, value, start, end) {
var length = array.length;
start = toInteger(start);
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = (end === undefined || end > length) ? length : toInteger(end);
if (end < 0) {
end += length;
}
end = start > end ? 0 : toLength(end);
while (start < end) {
array[start++] = value;
}
return array;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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();
/**
* This function is like `baseFor` except that it iterates over properties
* in the opposite order.
*
* @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 baseForRight = createBaseFor(true);
/**
* 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);
}
/**
* The base implementation of `_.forOwnRight` 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 baseForOwnRight(object, iteratee) {
return object && baseForRight(object, iteratee, keys);
}
/**
* The base implementation of `_.functions` which creates an array of
* `object` function property names filtered from `props`.
*
* @private
* @param {Object} object The object to inspect.
* @param {Array} props The property names to filter.
* @returns {Array} Returns the function names.
*/
function baseFunctions(object, props) {
return arrayFilter(props, function(key) {
return isFunction(object[key]);
});
}
/**
* 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;
}
/**
* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
* `keysFunc` and `symbolsFunc` to get the enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Function} keysFunc The function to get the keys of `object`.
* @param {Function} symbolsFunc The function to get the symbols of `object`.
* @returns {Array} Returns the array of property names and symbols.
*/
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
}
/**
* 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);
}
/**
* The base implementation of `_.gt` which doesn't coerce arguments.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is greater than `other`,
* else `false`.
*/
function baseGt(value, other) {
return value > other;
}
/**
* The base implementation of `_.has` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHas(object, key) {
return object != null && hasOwnProperty.call(object, key);
}
/**
* 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);
}
/**
* The base implementation of `_.inRange` which doesn't coerce arguments.
*
* @private
* @param {number} number The number to check.
* @param {number} start The start of the range.
* @param {number} end The end of the range.
* @returns {boolean} Returns `true` if `number` is in the range, else `false`.
*/
function baseInRange(number, start, end) {
return number >= nativeMin(start, end) && number < nativeMax(start, end);
}
/**
* 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;
}
/**
* 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;
}
/**
* The base implementation of `_.invoke` without support for individual
* method arguments.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the method to invoke.
* @param {Array} args The arguments to invoke the method with.
* @returns {*} Returns the result of the invoked method.
*/
function baseInvoke(object, path, args) {
path = castPath(path, object);
object = parent(object, path);
var func = object == null ? object : object[toKey(last(path))];
return func == null ? undefined : apply(func, object, args);
}
/**
* The base implementation of `_.isArguments`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
*/
function baseIsArguments(value) {
return isObjectLike(value) && baseGetTag(value) == argsTag;
}
/**
* The base implementation of `_.isArrayBuffer` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
*/
function baseIsArrayBuffer(value) {
return isObjectLike(value) && baseGetTag(value) == arrayBufferTag;
}
/**
* The base implementation of `_.isDate` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a date object, else `false`.
*/
function baseIsDate(value) {
return isObjectLike(value) && baseGetTag(value) == dateTag;
}
/**
* The base implementation of `_.isEqual` which supports partial comparisons
* and tracks traversed objects.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {boolean} bitmask The bitmask flags.
* 1 - Unordered comparison
* 2 - Partial comparison
* @param {Function} [customizer] The function to customize comparisons.
* @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, bitmask, customizer, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = objIsArr ? arrayTag : getTag(object),
othTag = othIsArr ? arrayTag : getTag(other);
objTag = objTag == argsTag ? objectTag : objTag;
othTag = othTag == argsTag ? objectTag : othTag;
var objIsObj = objTag == objectTag,
othIsObj = othTag == objectTag,
isSameTag = objTag == othTag;
if (isSameTag && isBuffer(object)) {
if (!isBuffer(other)) {
return false;
}
objIsArr = true;
objIsObj = false;
}
if (isSameTag && !objIsObj) {
stack || (stack = new Stack);
return (objIsArr || isTypedArray(object))
? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
: equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
}
if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object,
othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new Stack);
return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new Stack);
return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}
/**
* The base implementation of `_.isMap` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
*/
function baseIsMap(value) {
return isObjectLike(value) && getTag(value) == mapTag;
}
/**
* 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;
}
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/
function baseIsNative(value) {
if (!isObject(value) || isMasked(value)) {
return false;
}
var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
/**
* The base implementation of `_.isRegExp` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
*/
function baseIsRegExp(value) {
return isObjectLike(value) && baseGetTag(value) == regexpTag;
}
/**
* The base implementation of `_.isSet` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
*/
function baseIsSet(value) {
return isObjectLike(value) && getTag(value) == setTag;
}
/**
* The base implementation of `_.isTypedArray` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
*/
function baseIsTypedArray(value) {
return isObjectLike(value) &&
isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
}
/**
* The base implementation of `_.iteratee`.
*
* @private
* @param {*} [value=_.identity] The value to convert to an iteratee.
* @returns {Function} Returns the iteratee.
*/
function baseIteratee(value) {
// Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
// See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
if (typeof value == 'function') {
return value;
}
if (value == null) {
return identity;
}
if (typeof value == 'object') {
return isArray(value)
? baseMatchesProperty(value[0], value[1])
: baseMatches(value);
}
return property(value);
}
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!isPrototype(object)) {
return nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
/**
* The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeysIn(object) {
if (!isObject(object)) {
return nativeKeysIn(object);
}
var isProto = isPrototype(object),
result = [];
for (var key in object) {
if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
result.push(key);
}
}
return result;
}
/**
* The base implementation of `_.lt` which doesn't coerce arguments.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is less than `other`,
* else `false`.
*/
function baseLt(value, other) {
return value < other;
}
/**
* The base implementation of `_.map` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function baseMap(collection, iteratee) {
var index = -1,
result = isArrayLike(collection) ? Array(collection.length) : [];
baseEach(collection, function(value, key, collection) {
result[++index] = iteratee(value, key, collection);
});
return result;
}
/**
* 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);
};
}
/**
* The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
*
* @private
* @param {string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatchesProperty(path, srcValue) {
if (isKey(path) && isStrictComparable(srcValue)) {
return matchesStrictComparable(toKey(path), srcValue);
}
return function(object) {
var objValue = get(object, path);
return (objValue === undefined && objValue === srcValue)
? hasIn(object, path)
: baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
};
}
/**
* 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) {
stack || (stack = new Stack);
if (isObject(srcValue)) {
baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
}
else {
var newValue = customizer
? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)
: undefined;
if (newValue === undefined) {
newValue = srcValue;
}
assignMergeValue(object, key, newValue);
}
}, keysIn);
}
/**
* A specialized version of `baseMerge` for arrays and objects which performs
* deep merges and tracks traversed objects enabling objects with circular
* references to be merged.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {string} key The key of the value to merge.
* @param {number} srcIndex The index of `source`.
* @param {Function} mergeFunc The function to merge values.
* @param {Function} [customizer] The function to customize assigned values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
var objValue = safeGet(object, key),
srcValue = safeGet(source, key),
stacked = stack.get(srcValue);
if (stacked) {
assignMergeValue(object, key, stacked);
return;
}
var newValue = customizer
? customizer(objValue, srcValue, (key + ''), object, source, stack)
: undefined;
var isCommon = newValue === undefined;
if (isCommon) {
var isArr = isArray(srcValue),
isBuff = !isArr && isBuffer(srcValue),
isTyped = !isArr && !isBuff && isTypedArray(srcValue);
newValue = srcValue;
if (isArr || isBuff || isTyped) {
if (isArray(objValue)) {
newValue = objValue;
}
else if (isArrayLikeObject(objValue)) {
newValue = copyArray(objValue);
}
else if (isBuff) {
isCommon = false;
newValue = cloneBuffer(srcValue, true);
}
else if (isTyped) {
isCommon = false;
newValue = cloneTypedArray(srcValue, true);
}
else {
newValue = [];
}
}
else if (isPlainObject(srcValue) || isArguments(srcValue)) {
newValue = objValue;
if (isArguments(objValue)) {
newValue = toPlainObject(objValue);
}
else if (!isObject(objValue) || isFunction(objValue)) {
newValue = initCloneObject(srcValue);
}
}
else {
isCommon = false;
}
}
if (isCommon) {
// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue, newValue);
mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
stack['delete'](srcValue);
}
assignMergeValue(object, key, newValue);
}
/**
* The base implementation of `_.nth` which doesn't coerce arguments.
*
* @private
* @param {Array} array The array to query.
* @param {number} n The index of the element to return.
* @returns {*} Returns the nth element of `array`.
*/
function baseNth(array, n) {
var length = array.length;
if (!length) {
return;
}
n += n < 0 ? length : 0;
return isIndex(n, length) ? array[n] : undefined;
}
/**
* 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) {
if (iteratees.length) {
iteratees = arrayMap(iteratees, function(iteratee) {
if (isArray(iteratee)) {
return function(value) {
return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);
}
}
return iteratee;
});
} else {
iteratees = [identity];
}
var index = -1;
iteratees = arrayMap(iteratees, baseUnary(getIteratee()));
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);
});
}
/**
* The base implementation of `_.pick` without support for individual
* property identifiers.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @returns {Object} Returns the new object.
*/
function basePick(object, paths) {
return basePickBy(object, paths, function(value, path) {
return hasIn(object, path);
});
}
/**
* 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;
}
/**
* 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);
};
}
/**
* The base implementation of `_.pullAllBy` without support for iteratee
* shorthands.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns `array`.
*/
function basePullAll(array, values, iteratee, comparator) {
var indexOf = comparator ? baseIndexOfWith : baseIndexOf,
index = -1,
length = values.length,
seen = array;
if (array === values) {
values = copyArray(values);
}
if (iteratee) {
seen = arrayMap(array, baseUnary(iteratee));
}
while (++index < length) {
var fromIndex = 0,
value = values[index],
computed = iteratee ? iteratee(value) : value;
while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) {
if (seen !== array) {
splice.call(seen, fromIndex, 1);
}
splice.call(array, fromIndex, 1);
}
}
return array;
}
/**
* The base implementation of `_.pullAt` without support for individual
* indexes or capturing the removed elements.
*
* @private
* @param {Array} array The array to modify.
* @param {number[]} indexes The indexes of elements to remove.
* @returns {Array} Returns `array`.
*/
function basePullAt(array, indexes) {
var length = array ? indexes.length : 0,
lastIndex = length - 1;
while (length--) {
var index = indexes[length];
if (length == lastIndex || index !== previous) {
var previous = index;
if (isIndex(index)) {
splice.call(array, index, 1);
} else {
baseUnset(array, index);
}
}
}
return array;
}
/**
* The base implementation of `_.random` without support for returning
* floating-point numbers.
*
* @private
* @param {number} lower The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the random number.
*/
function baseRandom(lower, upper) {
return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
}
/**
* The base implementation of `_.range` and `_.rangeRight` which doesn't
* coerce arguments.
*
* @private
* @param {number} start The start of the range.
* @param {number} end The end of the range.
* @param {number} step The value to increment or decrement by.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Array} Returns the range of numbers.
*/
function baseRange(start, end, step, fromRight) {
var index = -1,
length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
result = Array(length);
while (length--) {
result[fromRight ? length : ++index] = start;
start += step;
}
return result;
}
/**
* The base implementation of `_.repeat` which doesn't coerce arguments.
*
* @private
* @param {string} string The string to repeat.
* @param {number} n The number of times to repeat the string.
* @returns {string} Returns the repeated string.
*/
function baseRepeat(string, n) {
var result = '';
if (!string || n < 1 || n > MAX_SAFE_INTEGER) {
return result;
}
// Leverage the exponentiation by squaring algorithm for a faster repeat.
// See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
do {
if (n % 2) {
result += string;
}
n = nativeFloor(n / 2);
if (n) {
string += string;
}
} while (n);
return result;
}
/**
* The base implementation of `_.rest` which doesn't validate or coerce arguments.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
*/
function baseRest(func, start) {
return setToString(overRest(func, start, identity), func + '');
}
/**
* The base implementation of `_.sample`.
*
* @private
* @param {Array|Object} collection The collection to sample.
* @returns {*} Returns the random element.
*/
function baseSample(collection) {
return arraySample(values(collection));
}
/**
* The base implementation of `_.sampleSize` without param guards.
*
* @private
* @param {Array|Object} collection The collection to sample.
* @param {number} n The number of elements to sample.
* @returns {Array} Returns the random elements.
*/
function baseSampleSize(collection, n) {
var array = values(collection);
return shuffleSelf(array, baseClamp(n, 0, array.length));
}
/**
* The base implementation of `_.set`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @param {Function} [customizer] The function to customize path creation.
* @returns {Object} Returns `object`.
*/
function baseSet(object, path, value, customizer) {
if (!isObject(object)) {
return object;
}
path = castPath(path, object);
var index = -1,
length = path.length,
lastIndex = length - 1,
nested = object;
while (nested != null && ++index < length) {
var key = toKey(path[index]),
newValue = value;
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
return object;
}
if (index != lastIndex) {
var objValue = nested[key];
newValue = customizer ? customizer(objValue, key, nested) : undefined;
if (newValue === undefined) {
newValue = isObject(objValue)
? objValue
: (isIndex(path[index + 1]) ? [] : {});
}
}
assignValue(nested, key, newValue);
nested = nested[key];
}
return object;
}
/**
* The base implementation of `setData` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var baseSetData = !metaMap ? identity : function(func, data) {
metaMap.set(func, data);
return func;
};
/**
* The base implementation of `setToString` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var baseSetToString = !defineProperty ? identity : function(func, string) {
return defineProperty(func, 'toString', {
'configurable': true,
'enumerable': false,
'value': constant(string),
'writable': true
});
};
/**
* The base implementation of `_.shuffle`.
*
* @private
* @param {Array|Object} collection The collection to shuffle.
* @returns {Array} Returns the new shuffled array.
*/
function baseShuffle(collection) {
return shuffleSelf(values(collection));
}
/**
* 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;
}
/**
* The base implementation of `_.some` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection 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 baseSome(collection, predicate) {
var result;
baseEach(collection, function(value, index, collection) {
result = predicate(value, index, collection);
return !result;
});
return !!result;
}
/**
* The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which
* performs a binary search of `array` to determine the index at which `value`
* should be inserted into `array` in order to maintain its sort order.
*
* @private
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {boolean} [retHighest] Specify returning the highest qualified index.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
*/
function baseSortedIndex(array, value, retHighest) {
var low = 0,
high = array == null ? low : array.length;
if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
while (low < high) {
var mid = (low + high) >>> 1,
computed = array[mid];
if (computed !== null && !isSymbol(computed) &&
(retHighest ? (computed <= value) : (computed < value))) {
low = mid + 1;
} else {
high = mid;
}
}
return high;
}
return baseSortedIndexBy(array, value, identity, retHighest);
}
/**
* The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`
* which invokes `iteratee` for `value` and each element of `array` to compute
* their sort ranking. The iteratee is invoked with one argument; (value).
*
* @private
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {Function} iteratee The iteratee invoked per element.
* @param {boolean} [retHighest] Specify returning the highest qualified index.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
*/
function baseSortedIndexBy(array, value, iteratee, retHighest) {
var low = 0,
high = array == null ? 0 : array.length;
if (high === 0) {
return 0;
}
value = iteratee(value);
var valIsNaN = value !== value,
valIsNull = value === null,
valIsSymbol = isSymbol(value),
valIsUndefined = value === undefined;
while (low < high) {
var mid = nativeFloor((low + high) / 2),
computed = iteratee(array[mid]),
othIsDefined = computed !== undefined,
othIsNull = computed === null,
othIsReflexive = computed === computed,
othIsSymbol = isSymbol(computed);
if (valIsNaN) {
var setLow = retHighest || othIsReflexive;
} else if (valIsUndefined) {
setLow = othIsReflexive && (retHighest || othIsDefined);
} else if (valIsNull) {
setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull);
} else if (valIsSymbol) {
setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol);
} else if (othIsNull || othIsSymbol) {
setLow = false;
} else {
setLow = retHighest ? (computed <= value) : (computed < value);
}
if (setLow) {
low = mid + 1;
} else {
high = mid;
}
}
return nativeMin(high, MAX_ARRAY_INDEX);
}
/**
* The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @returns {Array} Returns the new duplicate free array.
*/
function baseSortedUniq(array, iteratee) {
var index = -1,
length = array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index],
computed = iteratee ? iteratee(value) : value;
if (!index || !eq(computed, seen)) {
var seen = computed;
result[resIndex++] = value === 0 ? 0 : value;
}
}
return result;
}
/**
* The base implementation of `_.toNumber` which doesn't ensure correct
* conversions of binary, hexadecimal, or octal string values.
*
* @private
* @param {*} value The value to process.
* @returns {number} Returns the number.
*/
function baseToNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
return +value;
}
/**
* The base implementation of `_.toString` which doesn't convert nullish
* values to empty strings.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
// Exit early for strings to avoid a performance hit in some environments.
if (typeof value == 'string') {
return value;
}
if (isArray(value)) {
// Recursively convert values (susceptible to call stack limits).
return arrayMap(value, baseToString) + '';
}
if (isSymbol(value)) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
/**
* The base implementation of `_.uniqBy` without support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new duplicate free array.
*/
function baseUniq(array, iteratee, comparator) {
var index = -1,
includes = arrayIncludes,
length = array.length,
isCommon = true,
result = [],
seen = result;
if (comparator) {
isCommon = false;
includes = arrayIncludesWith;
}
else if (length >= LARGE_ARRAY_SIZE) {
var set = iteratee ? null : createSet(array);
if (set) {
return setToArray(set);
}
isCommon = false;
includes = cacheHas;
seen = new SetCache;
}
else {
seen = iteratee ? [] : result;
}
outer:
while (++index < length) {
var value = array[index],
computed = iteratee ? iteratee(value) : value;
value = (comparator || value !== 0) ? value : 0;
if (isCommon && computed === computed) {
var seenIndex = seen.length;
while (seenIndex--) {
if (seen[seenIndex] === computed) {
continue outer;
}
}
if (iteratee) {
seen.push(computed);
}
result.push(value);
}
else if (!includes(seen, computed, comparator)) {
if (seen !== result) {
seen.push(computed);
}
result.push(value);
}
}
return result;
}
/**
* The base implementation of `_.unset`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The property path to unset.
* @returns {boolean} Returns `true` if the property is deleted, else `false`.
*/
function baseUnset(object, path) {
path = castPath(path, object);
object = parent(object, path);
return object == null || delete object[toKey(last(path))];
}
/**
* The base implementation of `_.update`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to update.
* @param {Function} updater The function to produce the updated value.
* @param {Function} [customizer] The function to customize path creation.
* @returns {Object} Returns `object`.
*/
function baseUpdate(object, path, updater, customizer) {
return baseSet(object, path, updater(baseGet(object, path)), customizer);
}
/**
* The base implementation of methods like `_.dropWhile` and `_.takeWhile`
* without support for iteratee shorthands.
*
* @private
* @param {Array} array The array to query.
* @param {Function} predicate The function invoked per iteration.
* @param {boolean} [isDrop] Specify dropping elements instead of taking them.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Array} Returns the slice of `array`.
*/
function baseWhile(array, predicate, isDrop, fromRight) {
var length = array.length,
index = fromRight ? length : -1;
while ((fromRight ? index-- : ++index < length) &&
predicate(array[index], index, array)) {}
return isDrop
? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))
: baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));
}
/**
* The base implementation of `wrapperValue` which returns the result of
* performing a sequence of actions on the unwrapped `value`, where each
* successive action is supplied the return value of the previous.
*
* @private
* @param {*} value The unwrapped value.
* @param {Array} actions Actions to perform to resolve the unwrapped value.
* @returns {*} Returns the resolved value.
*/
function baseWrapperValue(value, actions) {
var result = value;
if (result instanceof LazyWrapper) {
result = result.value();
}
return arrayReduce(actions, function(result, action) {
return action.func.apply(action.thisArg, arrayPush([result], action.args));
}, result);
}
/**
* The base implementation of methods like `_.xor`, 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 values.
*/
function baseXor(arrays, iteratee, comparator) {
var length = arrays.length;
if (length < 2) {
return length ? baseUniq(arrays[0]) : [];
}
var index = -1,
result = Array(length);
while (++index < length) {
var array = arrays[index],
othIndex = -1;
while (++othIndex < length) {
if (othIndex != index) {
result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator);
}
}
}
return baseUniq(baseFlatten(result, 1), iteratee, comparator);
}
/**
* This base implementation of `_.zipObject` which assigns values using `assignFunc`.
*
* @private
* @param {Array} props The property identifiers.
* @param {Array} values The property values.
* @param {Function} assignFunc The function to assign values.
* @returns {Object} Returns the new object.
*/
function baseZipObject(props, values, assignFunc) {
var index = -1,
length = props.length,
valsLength = values.length,
result = {};
while (++index < length) {
var value = index < valsLength ? values[index] : undefined;
assignFunc(result, props[index], value);
}
return result;
}
/**
* Casts `value` to an empty array if it's not an array like object.
*
* @private
* @param {*} value The value to inspect.
* @returns {Array|Object} Returns the cast array-like object.
*/
function castArrayLikeObject(value) {
return isArrayLikeObject(value) ? value : [];
}
/**
* 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;
}
/**
* Casts `value` to a path array if it's not one.
*
* @private
* @param {*} value The value to inspect.
* @param {Object} [object] The object to query keys on.
* @returns {Array} Returns the cast property path array.
*/
function castPath(value, object) {
if (isArray(value)) {
return value;
}
return isKey(value, object) ? [value] : stringToPath(toString(value));
}
/**
* A `baseRest` alias which can be replaced with `identity` by module
* replacement plugins.
*
* @private
* @type {Function}
* @param {Function} func The function to apply a rest parameter to.
* @returns {Function} Returns the new function.
*/
var castRest = baseRest;
/**
* 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);
}
/**
* A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout).
*
* @private
* @param {number|Object} id The timer id or timeout object of the timer to clear.
*/
var clearTimeout = ctxClearTimeout || function(id) {
return root.clearTimeout(id);
};
/**
* 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;
}
/**
* 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;
}
/**
* 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);
}
/**
* 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;
}
/**
* 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)) : {};
}
/**
* 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);
}
/**
* Compares values to sort them in ascending order.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {number} Returns the sort order indicator for `value`.
*/
function compareAscending(value, other) {
if (value !== other) {
var valIsDefined = value !== undefined,
valIsNull = value === null,
valIsReflexive = value === value,
valIsSymbol = isSymbol(value);
var othIsDefined = other !== undefined,
othIsNull = other === null,
othIsReflexive = other === other,
othIsSymbol = isSymbol(other);
if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
(valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||
(valIsNull && othIsDefined && othIsReflexive) ||
(!valIsDefined && othIsReflexive) ||
!valIsReflexive) {
return 1;
}
if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
(othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||
(othIsNull && valIsDefined && valIsReflexive) ||
(!othIsDefined && valIsReflexive) ||
!othIsReflexive) {
return -1;
}
}
return 0;
}
/**
* 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;
}
/**
* Creates an array that is the composition of partially applied arguments,
* placeholders, and provided arguments into a single array of arguments.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to prepend to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgs(args, partials, holders, isCurried) {
var argsIndex = -1,
argsLength = args.length,
holdersLength = holders.length,
leftIndex = -1,
leftLength = partials.length,
rangeLength = nativeMax(argsLength - holdersLength, 0),
result = Array(leftLength + rangeLength),
isUncurried = !isCurried;
while (++leftIndex < leftLength) {
result[leftIndex] = partials[leftIndex];
}
while (++argsIndex < holdersLength) {
if (isUncurried || argsIndex < argsLength) {
result[holders[argsIndex]] = args[argsIndex];
}
}
while (rangeLength--) {
result[leftIndex++] = args[argsIndex++];
}
return result;
}
/**
* This function is like `composeArgs` except that the arguments composition
* is tailored for `_.partialRight`.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to append to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgsRight(args, partials, holders, isCurried) {
var argsIndex = -1,
argsLength = args.length,
holdersIndex = -1,
holdersLength = holders.length,
rightIndex = -1,
rightLength = partials.length,
rangeLength = nativeMax(argsLength - holdersLength, 0),
result = Array(rangeLength + rightLength),
isUncurried = !isCurried;
while (++argsIndex < rangeLength) {
result[argsIndex] = args[argsIndex];
}
var offset = argsIndex;
while (++rightIndex < rightLength) {
result[offset + rightIndex] = partials[rightIndex];
}
while (++holdersIndex < holdersLength) {
if (isUncurried || argsIndex < argsLength) {
result[offset + holders[holdersIndex]] = args[argsIndex++];
}
}
return result;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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);
}
/**
* 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);
}
/**
* Creates a function like `_.groupBy`.
*
* @private
* @param {Function} setter The function to set accumulator values.
* @param {Function} [initializer] The accumulator object initializer.
* @returns {Function} Returns the new aggregator function.
*/
function createAggregator(setter, initializer) {
return function(collection, iteratee) {
var func = isArray(collection) ? arrayAggregator : baseAggregator,
accumulator = initializer ? initializer() : {};
return func(collection, setter, getIteratee(iteratee, 2), accumulator);
};
}
/**
* 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;
});
}
/**
* Creates a `baseEach` or `baseEachRight` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
if (collection == null) {
return collection;
}
if (!isArrayLike(collection)) {
return eachFunc(collection, iteratee);
}
var length = collection.length,
index = fromRight ? length : -1,
iterable = Object(collection);
while ((fromRight ? index-- : ++index < length)) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
};
}
/**
* 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;
};
}
/**
* 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;
}
/**
* Creates a function like `_.lowerFirst`.
*
* @private
* @param {string} methodName The name of the `String` case method to use.
* @returns {Function} Returns the new case function.
*/
function createCaseFirst(methodName) {
return function(string) {
string = toString(string);
var strSymbols = hasUnicode(string)
? stringToArray(string)
: undefined;
var chr = strSymbols
? strSymbols[0]
: string.charAt(0);
var trailing = strSymbols
? castSlice(strSymbols, 1).join('')
: string.slice(1);
return chr[methodName]() + trailing;
};
}
/**
* Creates a function like `_.camelCase`.
*
* @private
* @param {Function} callback The function to combine each word.
* @returns {Function} Returns the new compounder function.
*/
function createCompounder(callback) {
return function(string) {
return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
};
}
/**
* Creates a function that produces an instance of `Ctor` regardless of
* whether it was invoked as part of a `new` expression or by `call` or `apply`.
*
* @private
* @param {Function} Ctor The constructor to wrap.
* @returns {Function} Returns the new wrapped function.
*/
function createCtor(Ctor) {
return function() {
// Use a `switch` statement to work with class constructors. See
// http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
// for more details.
var args = arguments;
switch (args.length) {
case 0: return new Ctor;
case 1: return new Ctor(args[0]);
case 2: return new Ctor(args[0], args[1]);
case 3: return new Ctor(args[0], args[1], args[2]);
case 4: return new Ctor(args[0], args[1], args[2], args[3]);
case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
}
var thisBinding = baseCreate(Ctor.prototype),
result = Ctor.apply(thisBinding, args);
// Mimic the constructor's `return` behavior.
// See https://es5.github.io/#x13.2.2 for more details.
return isObject(result) ? result : thisBinding;
};
}
/**
* 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;
}
/**
* Creates a `_.find` or `_.findLast` function.
*
* @private
* @param {Function} findIndexFunc The function to find the collection index.
* @returns {Function} Returns the new find function.
*/
function createFind(findIndexFunc) {
return function(collection, predicate, fromIndex) {
var iterable = Object(collection);
if (!isArrayLike(collection)) {
var iteratee = getIteratee(predicate, 3);
collection = keys(collection);
predicate = function(key) { return iteratee(iterable[key], key, iterable); };
}
var index = findIndexFunc(collection, predicate, fromIndex);
return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
};
}
/**
* Creates a `_.flow` or `_.flowRight` function.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new flow function.
*/
function createFlow(fromRight) {
return flatRest(function(funcs) {
var length = funcs.length,
index = length,
prereq = LodashWrapper.prototype.thru;
if (fromRight) {
funcs.reverse();
}
while (index--) {
var func = funcs[index];
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
if (prereq && !wrapper && getFuncName(func) == 'wrapper') {
var wrapper = new LodashWrapper([], true);
}
}
index = wrapper ? index : length;
while (++index < length) {
func = funcs[index];
var funcName = getFuncName(func),
data = funcName == 'wrapper' ? getData(func) : undefined;
if (data && isLaziable(data[0]) &&
data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) &&
!data[4].length && data[9] == 1
) {
wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);
} else {
wrapper = (func.length == 1 && isLaziable(func))
? wrapper[funcName]()
: wrapper.thru(func);
}
}
return function() {
var args = arguments,
value = args[0];
if (wrapper && args.length == 1 && isArray(value)) {
return wrapper.plant(value).value();
}
var index = 0,
result = length ? funcs[index].apply(this, args) : value;
while (++index < length) {
result = funcs[index].call(this, result);
}
return result;
};
});
}
/**
* Creates a function that wraps `func` to invoke it with optional `this`
* binding of `thisArg`, partial application, and currying.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [partialsRight] The arguments to append to those provided
* to the new function.
* @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
var isAry = bitmask & WRAP_ARY_FLAG,
isBind = bitmask & WRAP_BIND_FLAG,
isBindKey = bitmask & WRAP_BIND_KEY_FLAG,
isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG),
isFlip = bitmask & WRAP_FLIP_FLAG,
Ctor = isBindKey ? undefined : createCtor(func);
function wrapper() {
var length = arguments.length,
args = Array(length),
index = length;
while (index--) {
args[index] = arguments[index];
}
if (isCurried) {
var placeholder = getHolder(wrapper),
holdersCount = countHolders(args, placeholder);
}
if (partials) {
args = composeArgs(args, partials, holders, isCurried);
}
if (partialsRight) {
args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
}
length -= holdersCount;
if (isCurried && length < arity) {
var newHolders = replaceHolders(args, placeholder);
return createRecurry(
func, bitmask, createHybrid, wrapper.placeholder, thisArg,
args, newHolders, argPos, ary, arity - length
);
}
var thisBinding = isBind ? thisArg : this,
fn = isBindKey ? thisBinding[func] : func;
length = args.length;
if (argPos) {
args = reorder(args, argPos);
} else if (isFlip && length > 1) {
args.reverse();
}
if (isAry && ary < length) {
args.length = ary;
}
if (this && this !== root && this instanceof wrapper) {
fn = Ctor || createCtor(fn);
}
return fn.apply(thisBinding, args);
}
return wrapper;
}
/**
* 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), {});
};
}
/**
* Creates a function that performs a mathematical operation on two values.
*
* @private
* @param {Function} operator The function to perform the operation.
* @param {number} [defaultValue] The value used for `undefined` arguments.
* @returns {Function} Returns the new mathematical operation function.
*/
function createMathOperation(operator, defaultValue) {
return function(value, other) {
var result;
if (value === undefined && other === undefined) {
return defaultValue;
}
if (value !== undefined) {
result = value;
}
if (other !== undefined) {
if (result === undefined) {
return other;
}
if (typeof value == 'string' || typeof other == 'string') {
value = baseToString(value);
other = baseToString(other);
} else {
value = baseToNumber(value);
other = baseToNumber(other);
}
result = operator(value, other);
}
return result;
};
}
/**
* Creates a function like `_.over`.
*
* @private
* @param {Function} arrayFunc The function to iterate over iteratees.
* @returns {Function} Returns the new over function.
*/
function createOver(arrayFunc) {
return flatRest(function(iteratees) {
iteratees = arrayMap(iteratees, baseUnary(getIteratee()));
return baseRest(function(args) {
var thisArg = this;
return arrayFunc(iteratees, function(iteratee) {
return apply(iteratee, thisArg, args);
});
});
});
}
/**
* Creates the padding for `string` based on `length`. The `chars` string
* is truncated if the number of characters exceeds `length`.
*
* @private
* @param {number} length The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padding for `string`.
*/
function createPadding(length, chars) {
chars = chars === undefined ? ' ' : baseToString(chars);
var charsLength = chars.length;
if (charsLength < 2) {
return charsLength ? baseRepeat(chars, length) : chars;
}
var result = baseRepeat(chars, nativeCeil(length / stringSize(chars)));
return hasUnicode(chars)
? castSlice(stringToArray(result), 0, length).join('')
: result.slice(0, length);
}
/**
* Creates a function that wraps `func` to invoke it with the `this` binding
* of `thisArg` and `partials` prepended to the arguments it receives.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} partials The arguments to prepend to those provided to
* the new function.
* @returns {Function} Returns the new wrapped function.
*/
function createPartial(func, bitmask, thisArg, partials) {
var isBind = bitmask & WRAP_BIND_FLAG,
Ctor = createCtor(func);
function wrapper() {
var argsIndex = -1,
argsLength = arguments.length,
leftIndex = -1,
leftLength = partials.length,
args = Array(leftLength + argsLength),
fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
while (++leftIndex < leftLength) {
args[leftIndex] = partials[leftIndex];
}
while (argsLength--) {
args[leftIndex++] = arguments[++argsIndex];
}
return apply(fn, isBind ? thisArg : this, args);
}
return wrapper;
}
/**
* Creates a `_.range` or `_.rangeRight` function.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new range function.
*/
function createRange(fromRight) {
return function(start, end, step) {
if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {
end = step = undefined;
}
// Ensure the sign of `-0` is preserved.
start = toFinite(start);
if (end === undefined) {
end = start;
start = 0;
} else {
end = toFinite(end);
}
step = step === undefined ? (start < end ? 1 : -1) : toFinite(step);
return baseRange(start, end, step, fromRight);
};
}
/**
* Creates a function that performs a relational operation on two values.
*
* @private
* @param {Function} operator The function to perform the operation.
* @returns {Function} Returns the new relational operation function.
*/
function createRelationalOperation(operator) {
return function(value, other) {
if (!(typeof value == 'string' && typeof other == 'string')) {
value = toNumber(value);
other = toNumber(other);
}
return operator(value, other);
};
}
/**
* Creates a function that wraps `func` to continue currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {Function} wrapFunc The function to create the `func` wrapper.
* @param {*} placeholder The placeholder value.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
var isCurry = bitmask & WRAP_CURRY_FLAG,
newHolders = isCurry ? holders : undefined,
newHoldersRight = isCurry ? undefined : holders,
newPartials = isCurry ? partials : undefined,
newPartialsRight = isCurry ? undefined : partials;
bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG);
bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);
if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {
bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);
}
var newData = [
func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
newHoldersRight, argPos, ary, arity
];
var result = wrapFunc.apply(undefined, newData);
if (isLaziable(func)) {
setData(result, newData);
}
result.placeholder = placeholder;
return setWrapToString(result, func, bitmask);
}
/**
* Creates a function like `_.round`.
*
* @private
* @param {string} methodName The name of the `Math` method to use when rounding.
* @returns {Function} Returns the new round function.
*/
function createRound(methodName) {
var func = Math[methodName];
return function(number, precision) {
number = toNumber(number);
precision = precision == null ? 0 : nativeMin(toInteger(precision), 292);
if (precision && nativeIsFinite(number)) {
// Shift with exponential notation to avoid floating-point issues.
// See [MDN](https://mdn.io/round#Examples) for more details.
var pair = (toString(number) + 'e').split('e'),
value = func(pair[0] + 'e' + (+pair[1] + precision));
pair = (toString(value) + 'e').split('e');
return +(pair[0] + 'e' + (+pair[1] - precision));
}
return func(number);
};
}
/**
* Creates a set object of `values`.
*
* @private
* @param {Array} values The values to add to the set.
* @returns {Object} Returns the new set.
*/
var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {
return new Set(values);
};
/**
* Creates a `_.toPairs` or `_.toPairsIn` function.
*
* @private
* @param {Function} keysFunc The function to get the keys of a given object.
* @returns {Function} Returns the new pairs function.
*/
function createToPairs(keysFunc) {
return function(object) {
var tag = getTag(object);
if (tag == mapTag) {
return mapToArray(object);
}
if (tag == setTag) {
return setToPairs(object);
}
return baseToPairs(object, keysFunc(object));
};
}
/**
* Creates a function that either curries or invokes `func` with optional
* `this` binding and partially applied arguments.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags.
* 1 - `_.bind`
* 2 - `_.bindKey`
* 4 - `_.curry` or `_.curryRight` of a bound function
* 8 - `_.curry`
* 16 - `_.curryRight`
* 32 - `_.partial`
* 64 - `_.partialRight`
* 128 - `_.rearg`
* 256 - `_.ary`
* 512 - `_.flip`
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to be partially applied.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;
if (!isBindKey && typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
var length = partials ? partials.length : 0;
if (!length) {
bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);
partials = holders = undefined;
}
ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);
arity = arity === undefined ? arity : toInteger(arity);
length -= holders ? holders.length : 0;
if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
var partialsRight = partials,
holdersRight = holders;
partials = holders = undefined;
}
var data = isBindKey ? undefined : getData(func);
var newData = [
func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
argPos, ary, arity
];
if (data) {
mergeData(newData, data);
}
func = newData[0];
bitmask = newData[1];
thisArg = newData[2];
partials = newData[3];
holders = newData[4];
arity = newData[9] = newData[9] === undefined
? (isBindKey ? 0 : func.length)
: nativeMax(newData[9] - length, 0);
if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
}
if (!bitmask || bitmask == WRAP_BIND_FLAG) {
var result = createBind(func, bitmask, thisArg);
} else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
result = createCurry(func, bitmask, arity);
} else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {
result = createPartial(func, bitmask, thisArg, partials);
} else {
result = createHybrid.apply(undefined, newData);
}
var setter = data ? baseSetData : setData;
return setWrapToString(setter(result, newData), func, bitmask);
}
/**
* Used by `_.defaults` to customize its `_.assignIn` use to assign properties
* of source objects to the destination object for all destination properties
* that resolve to `undefined`.
*
* @private
* @param {*} objValue The destination value.
* @param {*} srcValue The source value.
* @param {string} key The key of the property to assign.
* @param {Object} object The parent object of `objValue`.
* @returns {*} Returns the value to assign.
*/
function customDefaultsAssignIn(objValue, srcValue, key, object) {
if (objValue === undefined ||
(eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {
return srcValue;
}
return objValue;
}
/**
* Used by `_.defaultsDeep` to customize its `_.merge` use to merge source
* objects into destination objects that are passed thru.
*
* @private
* @param {*} objValue The destination value.
* @param {*} srcValue The source value.
* @param {string} key The key of the property to merge.
* @param {Object} object The parent object of `objValue`.
* @param {Object} source The parent object of `srcValue`.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
* @returns {*} Returns the value to assign.
*/
function customDefaultsMerge(objValue, srcValue, key, object, source, stack) {
if (isObject(objValue) && isObject(srcValue)) {
// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue, objValue);
baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack);
stack['delete'](srcValue);
}
return objValue;
}
/**
* Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain
* objects.
*
* @private
* @param {*} value The value to inspect.
* @param {string} key The key of the property to inspect.
* @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.
*/
function customOmitClone(value) {
return isPlainObject(value) ? undefined : value;
}
/**
* 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;
}
// Check that cyclic values are equal.
var arrStacked = stack.get(array);
var othStacked = stack.get(other);
if (arrStacked && othStacked) {
return arrStacked == other && othStacked == array;
}
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;
}
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
switch (tag) {
case dataViewTag:
if ((object.byteLength != other.byteLength) ||
(object.byteOffset != other.byteOffset)) {
return false;
}
object = object.buffer;
other = other.buffer;
case arrayBufferTag:
if ((object.byteLength != other.byteLength) ||
!equalFunc(new Uint8Array(object), new Uint8Array(other))) {
return false;
}
return true;
case boolTag:
case dateTag:
case numberTag:
// Coerce booleans to `1` or `0` and dates to milliseconds.
// Invalid dates are coerced to `NaN`.
return eq(+object, +other);
case errorTag:
return object.name == other.name && object.message == other.message;
case regexpTag:
case stringTag:
// Coerce regexes to strings and treat strings, primitives and objects,
// as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
// for more details.
return object == (other + '');
case mapTag:
var convert = mapToArray;
case setTag:
var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
convert || (convert = setToArray);
if (object.size != other.size && !isPartial) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
bitmask |= COMPARE_UNORDERED_FLAG;
// Recursively compare objects (susceptible to call stack limits).
stack.set(object, other);
var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
stack['delete'](object);
return result;
case symbolTag:
if (symbolValueOf) {
return symbolValueOf.call(object) == symbolValueOf.call(other);
}
}
return false;
}
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
objProps = getAllKeys(object),
objLength = objProps.length,
othProps = getAllKeys(other),
othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
return false;
}
}
// Check that cyclic values are equal.
var objStacked = stack.get(object);
var othStacked = stack.get(other);
if (objStacked && othStacked) {
return objStacked == other && othStacked == object;
}
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;
}
/**
* A specialized version of `baseRest` which flattens the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @returns {Function} Returns the new function.
*/
function flatRest(func) {
return setToString(overRest(func, undefined, flatten), func + '');
}
/**
* Creates an array of own enumerable property names and symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeys(object) {
return baseGetAllKeys(object, keys, getSymbols);
}
/**
* Creates an array of own and inherited enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeysIn(object) {
return baseGetAllKeys(object, keysIn, getSymbolsIn);
}
/**
* Gets metadata for `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {*} Returns the metadata for `func`.
*/
var getData = !metaMap ? noop : function(func) {
return metaMap.get(func);
};
/**
* Gets the name of `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {string} Returns the function name.
*/
function getFuncName(func) {
var result = (func.name + ''),
array = realNames[result],
length = hasOwnProperty.call(realNames, result) ? array.length : 0;
while (length--) {
var data = array[length],
otherFunc = data.func;
if (otherFunc == null || otherFunc == func) {
return data.name;
}
}
return result;
}
/**
* 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 = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func;
return object.placeholder;
}
/**
* Gets the appropriate "iteratee" function. If `_.iteratee` is customized,
* this function returns the custom method, otherwise it returns `baseIteratee`.
* If arguments are provided, the chosen function is invoked with them and
* its result is returned.
*
* @private
* @param {*} [value] The value to convert to an iteratee.
* @param {number} [arity] The arity of the created iteratee.
* @returns {Function} Returns the chosen function or its result.
*/
function getIteratee() {
var result = lodash.iteratee || iteratee;
result = result === iteratee ? baseIteratee : result;
return arguments.length ? result(arguments[0], arguments[1]) : result;
}
/**
* 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;
}
/**
* Gets the property names, values, and compare flags of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the match data of `object`.
*/
function getMatchData(object) {
var result = keys(object),
length = result.length;
while (length--) {
var key = result[length],
value = object[key];
result[length] = [key, value, isStrictComparable(value)];
}
return result;
}
/**
* 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;
}
/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag),
tag = value[symToStringTag];
try {
value[symToStringTag] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
/**
* Creates an array of the own enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
if (object == null) {
return [];
}
object = Object(object);
return arrayFilter(nativeGetSymbols(object), function(symbol) {
return propertyIsEnumerable.call(object, symbol);
});
};
/**
* Creates an array of the own and inherited enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {
var result = [];
while (object) {
arrayPush(result, getSymbols(object));
object = getPrototype(object);
}
return result;
};
/**
* 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;
};
}
/**
* Gets the view, applying any `transforms` to the `start` and `end` positions.
*
* @private
* @param {number} start The start of the view.
* @param {number} end The end of the view.
* @param {Array} transforms The transformations to apply to the view.
* @returns {Object} Returns an object containing the `start` and `end`
* positions of the view.
*/
function getView(start, end, transforms) {
var index = -1,
length = transforms.length;
while (++index < length) {
var data = transforms[index],
size = data.size;
switch (data.type) {
case 'drop': start += size; break;
case 'dropRight': end -= size; break;
case 'take': end = nativeMin(end, start + size); break;
case 'takeRight': start = nativeMax(start, end - size); break;
}
}
return { 'start': start, 'end': end };
}
/**
* 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) : [];
}
/**
* Checks if `path` exists on `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @param {Function} hasFunc The function to check properties.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
*/
function hasPath(object, path, hasFunc) {
path = castPath(path, object);
var index = -1,
length = path.length,
result = false;
while (++index < length) {
var key = toKey(path[index]);
if (!(result = object != null && hasFunc(object, key))) {
break;
}
object = object[key];
}
if (result || ++index != length) {
return result;
}
length = object == null ? 0 : object.length;
return !!length && isLength(length) && isIndex(key, length) &&
(isArray(object) || isArguments(object));
}
/**
* Initializes an array clone.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the initialized clone.
*/
function initCloneArray(array) {
var length = array.length,
result = new array.constructor(length);
// Add properties assigned by `RegExp#exec`.
if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
result.index = array.index;
result.input = array.input;
}
return result;
}
/**
* 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))
: {};
}
/**
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
*
* @private
* @param {Object} object The object to clone.
* @param {string} tag The `toStringTag` of the object to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneByTag(object, tag, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag:
return cloneArrayBuffer(object);
case boolTag:
case dateTag:
return new Ctor(+object);
case dataViewTag:
return cloneDataView(object, isDeep);
case float32Tag: case float64Tag:
case int8Tag: case int16Tag: case int32Tag:
case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
return cloneTypedArray(object, isDeep);
case mapTag:
return new Ctor;
case numberTag:
case stringTag:
return new Ctor(object);
case regexpTag:
return cloneRegExp(object);
case setTag:
return new Ctor;
case symbolTag:
return cloneSymbol(object);
}
}
/**
* 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');
}
/**
* Checks if `value` is a flattenable `arguments` object or array.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
*/
function isFlattenable(value) {
return isArray(value) || isArguments(value) ||
!!(spreadableSymbol && value && value[spreadableSymbol]);
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
var type = typeof value;
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length &&
(type == 'number' ||
(type != 'symbol' && reIsUint.test(value))) &&
(value > -1 && value % 1 == 0 && value < length);
}
/**
* Checks if the given arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call,
* else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject(object)) {
return false;
}
var type = typeof index;
if (type == 'number'
? (isArrayLike(object) && isIndex(index, object.length))
: (type == 'string' && index in object)
) {
return eq(object[index], value);
}
return false;
}
/**
* Checks if `value` is a property name and not a property path.
*
* @private
* @param {*} value The value to check.
* @param {Object} [object] The object to query keys on.
* @returns {boolean} Returns `true` if `value` is a property name, else `false`.
*/
function isKey(value, object) {
if (isArray(value)) {
return false;
}
var type = typeof value;
if (type == 'number' || type == 'symbol' || type == 'boolean' ||
value == null || isSymbol(value)) {
return true;
}
return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
(object != null && value in Object(object));
}
/**
* 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);
}
/**
* Checks if `func` has a lazy counterpart.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` has a lazy counterpart,
* else `false`.
*/
function isLaziable(func) {
var funcName = getFuncName(func),
other = lodash[funcName];
if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {
return false;
}
if (func === other) {
return true;
}
var data = getData(other);
return !!data && func === data[0];
}
/**
* 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);
}
/**
* Checks if `func` is capable of being masked.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `func` is maskable, else `false`.
*/
var isMaskable = coreJsData ? isFunction : stubFalse;
/**
* 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;
}
/**
* Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` if suitable for strict
* equality comparisons, else `false`.
*/
function isStrictComparable(value) {
return value === value && !isObject(value);
}
/**
* 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)));
};
}
/**
* A specialized version of `_.memoize` which clears the memoized function's
* cache when it exceeds `MAX_MEMOIZE_SIZE`.
*
* @private
* @param {Function} func The function to have its output memoized.
* @returns {Function} Returns the new memoized function.
*/
function memoizeCapped(func) {
var result = memoize(func, function(key) {
if (cache.size === MAX_MEMOIZE_SIZE) {
cache.clear();
}
return key;
});
var cache = result.cache;
return result;
}
/**
* Merges the function metadata of `source` into `data`.
*
* Merging metadata reduces the number of wrappers used to invoke a function.
* This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
* may be applied regardless of execution order. Methods like `_.ary` and
* `_.rearg` modify function arguments, making the order in which they are
* executed important, preventing the merging of metadata. However, we make
* an exception for a safe combined case where curried functions have `_.ary`
* and or `_.rearg` applied.
*
* @private
* @param {Array} data The destination metadata.
* @param {Array} source The source metadata.
* @returns {Array} Returns `data`.
*/
function mergeData(data, source) {
var bitmask = data[1],
srcBitmask = source[1],
newBitmask = bitmask | srcBitmask,
isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);
var isCombo =
((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) ||
((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) ||
((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG));
// Exit early if metadata can't be merged.
if (!(isCommon || isCombo)) {
return data;
}
// Use source `thisArg` if available.
if (srcBitmask & WRAP_BIND_FLAG) {
data[2] = source[2];
// Set when currying a bound function.
newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;
}
// Compose partial arguments.
var value = source[3];
if (value) {
var partials = data[3];
data[3] = partials ? composeArgs(partials, value, source[4]) : value;
data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];
}
// Compose partial right arguments.
value = source[5];
if (value) {
partials = data[5];
data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;
data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];
}
// Use source `argPos` if available.
value = source[7];
if (value) {
data[7] = value;
}
// Use source `ary` if it's smaller.
if (srcBitmask & WRAP_ARY_FLAG) {
data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
}
// Use source `arity` if one is not provided.
if (data[9] == null) {
data[9] = source[9];
}
// Use source `func` and merge bitmasks.
data[0] = source[0];
data[1] = newBitmask;
return data;
}
/**
* 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;
}
/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/
function objectToString(value) {
return nativeObjectToString.call(value);
}
/**
* 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);
};
}
/**
* 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));
}
/**
* Reorder `array` according to the specified indexes where the element at
* the first index is assigned as the first element, the element at
* the second index is assigned as the second element, and so on.
*
* @private
* @param {Array} array The array to reorder.
* @param {Array} indexes The arranged array indexes.
* @returns {Array} Returns `array`.
*/
function reorder(array, indexes) {
var arrLength = array.length,
length = nativeMin(indexes.length, arrLength),
oldArray = copyArray(array);
while (length--) {
var index = indexes[length];
array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
}
return array;
}
/**
* Gets the value at `key`, unless `key` is "__proto__" or "constructor".
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function safeGet(object, key) {
if (key === 'constructor' && typeof object[key] === 'function') {
return;
}
if (key == '__proto__') {
return;
}
return object[key];
}
/**
* 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);
/**
* A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout).
*
* @private
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay invocation.
* @returns {number|Object} Returns the timer id or timeout object.
*/
var setTimeout = ctxSetTimeout || function(func, wait) {
return root.setTimeout(func, wait);
};
/**
* 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);
/**
* 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)));
}
/**
* 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);
};
}
/**
* A specialized version of `_.shuffle` which mutates and sets the size of `array`.
*
* @private
* @param {Array} array The array to shuffle.
* @param {number} [size=array.length] The size of `array`.
* @returns {Array} Returns `array`.
*/
function shuffleSelf(array, size) {
var index = -1,
length = array.length,
lastIndex = length - 1;
size = size === undefined ? length : size;
while (++index < size) {
var rand = baseRandom(index, lastIndex),
value = array[rand];
array[rand] = array[index];
array[index] = value;
}
array.length = size;
return array;
}
/**
* Converts `string` to a property path array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the property path array.
*/
var stringToPath = memoizeCapped(function(string) {
var result = [];
if (string.charCodeAt(0) === 46 /* . */) {
result.push('');
}
string.replace(rePropName, function(match, number, quote, subString) {
result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
});
return result;
});
/**
* Converts `value` to a string key if it's not a string or symbol.
*
* @private
* @param {*} value The value to inspect.
* @returns {string|symbol} Returns the key.
*/
function toKey(value) {
if (typeof value == 'string' || isSymbol(value)) {
return value;
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
/**
* 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 '';
}
/**
* 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();
}
/**
* 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;
}
/*------------------------------------------------------------------------*/
/**
* Creates an array of elements split into groups the length of `size`.
* If `array` can't be split evenly, the final chunk will be the remaining
* elements.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to process.
* @param {number} [size=1] The length of each chunk
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the new array of chunks.
* @example
*
* _.chunk(['a', 'b', 'c', 'd'], 2);
* // => [['a', 'b'], ['c', 'd']]
*
* _.chunk(['a', 'b', 'c', 'd'], 3);
* // => [['a', 'b', 'c'], ['d']]
*/
function chunk(array, size, guard) {
if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) {
size = 1;
} else {
size = nativeMax(toInteger(size), 0);
}
var length = array == null ? 0 : array.length;
if (!length || size < 1) {
return [];
}
var index = 0,
resIndex = 0,
result = Array(nativeCeil(length / size));
while (index < length) {
result[resIndex++] = baseSlice(array, index, (index += size));
}
return result;
}
/**
* 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;
}
/**
* Creates a new array concatenating `array` with any additional arrays
* and/or values.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to concatenate.
* @param {...*} [values] The values to concatenate.
* @returns {Array} Returns the new concatenated array.
* @example
*
* var array = [1];
* var other = _.concat(array, 2, [3], [[4]]);
*
* console.log(other);
* // => [1, 2, 3, [4]]
*
* console.log(array);
* // => [1]
*/
function concat() {
var length = arguments.length;
if (!length) {
return [];
}
var args = Array(length - 1),
array = arguments[0],
index = length;
while (index--) {
args[index - 1] = arguments[index];
}
return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1));
}
/**
* Creates an array of `array` values not included in the other given arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. The order and references of result values are
* determined by the first array.
*
* **Note:** Unlike `_.pullAll`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @see _.without, _.xor
* @example
*
* _.difference([2, 1], [2, 3]);
* // => [1]
*/
var difference = baseRest(function(array, values) {
return isArrayLikeObject(array)
? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true))
: [];
});
/**
* This method is like `_.difference` except that it accepts `iteratee` which
* is invoked for each element of `array` and `values` to generate the criterion
* by which they're compared. The order and references of result values are
* determined by the first array. The iteratee is invoked with one argument:
* (value).
*
* **Note:** Unlike `_.pullAllBy`, this method returns a new array.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The values to exclude.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);
* // => [1.2]
*
* // The `_.property` iteratee shorthand.
* _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');
* // => [{ 'x': 2 }]
*/
var differenceBy = baseRest(function(array, values) {
var iteratee = last(values);
if (isArrayLikeObject(iteratee)) {
iteratee = undefined;
}
return isArrayLikeObject(array)
? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2))
: [];
});
/**
* This method is like `_.difference` except that it accepts `comparator`
* which is invoked to compare elements of `array` to `values`. The order and
* references of result values are determined by the first array. The comparator
* is invoked with two arguments: (arrVal, othVal).
*
* **Note:** Unlike `_.pullAllWith`, this method returns a new array.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The values to exclude.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
*
* _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);
* // => [{ 'x': 2, 'y': 1 }]
*/
var differenceWith = baseRest(function(array, values) {
var comparator = last(values);
if (isArrayLikeObject(comparator)) {
comparator = undefined;
}
return isArrayLikeObject(array)
? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator)
: [];
});
/**
* Creates a slice of `array` with `n` elements dropped from the beginning.
*
* @static
* @memberOf _
* @since 0.5.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to drop.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.drop([1, 2, 3]);
* // => [2, 3]
*
* _.drop([1, 2, 3], 2);
* // => [3]
*
* _.drop([1, 2, 3], 5);
* // => []
*
* _.drop([1, 2, 3], 0);
* // => [1, 2, 3]
*/
function drop(array, n, guard) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
n = (guard || n === undefined) ? 1 : toInteger(n);
return baseSlice(array, n < 0 ? 0 : n, length);
}
/**
* Creates a slice of `array` with `n` elements dropped from the end.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to drop.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.dropRight([1, 2, 3]);
* // => [1, 2]
*
* _.dropRight([1, 2, 3], 2);
* // => [1]
*
* _.dropRight([1, 2, 3], 5);
* // => []
*
* _.dropRight([1, 2, 3], 0);
* // => [1, 2, 3]
*/
function dropRight(array, n, guard) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
n = (guard || n === undefined) ? 1 : toInteger(n);
n = length - n;
return baseSlice(array, 0, n < 0 ? 0 : n);
}
/**
* Creates a slice of `array` excluding elements dropped from the end.
* Elements are dropped until `predicate` returns falsey. The predicate is
* invoked with three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
* _.dropRightWhile(users, function(o) { return !o.active; });
* // => objects for ['barney']
*
* // The `_.matches` iteratee shorthand.
* _.dropRightWhile(users, { 'user': 'pebbles', 'active': false });
* // => objects for ['barney', 'fred']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.dropRightWhile(users, ['active', false]);
* // => objects for ['barney']
*
* // The `_.property` iteratee shorthand.
* _.dropRightWhile(users, 'active');
* // => objects for ['barney', 'fred', 'pebbles']
*/
function dropRightWhile(array, predicate) {
return (array && array.length)
? baseWhile(array, getIteratee(predicate, 3), true, true)
: [];
}
/**
* Creates a slice of `array` excluding elements dropped from the beginning.
* Elements are dropped until `predicate` returns falsey. The predicate is
* invoked with three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.dropWhile(users, function(o) { return !o.active; });
* // => objects for ['pebbles']
*
* // The `_.matches` iteratee shorthand.
* _.dropWhile(users, { 'user': 'barney', 'active': false });
* // => objects for ['fred', 'pebbles']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.dropWhile(users, ['active', false]);
* // => objects for ['pebbles']
*
* // The `_.property` iteratee shorthand.
* _.dropWhile(users, 'active');
* // => objects for ['barney', 'fred', 'pebbles']
*/
function dropWhile(array, predicate) {
return (array && array.length)
? baseWhile(array, getIteratee(predicate, 3), true)
: [];
}
/**
* Fills elements of `array` with `value` from `start` up to, but not
* including, `end`.
*
* **Note:** This method mutates `array`.
*
* @static
* @memberOf _
* @since 3.2.0
* @category Array
* @param {Array} array The array to fill.
* @param {*} value The value to fill `array` with.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns `array`.
* @example
*
* var array = [1, 2, 3];
*
* _.fill(array, 'a');
* console.log(array);
* // => ['a', 'a', 'a']
*
* _.fill(Array(3), 2);
* // => [2, 2, 2]
*
* _.fill([4, 6, 8, 10], '*', 1, 3);
* // => [4, '*', '*', 10]
*/
function fill(array, value, start, end) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {
start = 0;
end = length;
}
return baseFill(array, value, start, end);
}
/**
* This method is like `_.find` except that it returns the index of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.findIndex(users, function(o) { return o.user == 'barney'; });
* // => 0
*
* // The `_.matches` iteratee shorthand.
* _.findIndex(users, { 'user': 'fred', 'active': false });
* // => 1
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findIndex(users, ['active', false]);
* // => 0
*
* // The `_.property` iteratee shorthand.
* _.findIndex(users, 'active');
* // => 2
*/
function findIndex(array, predicate, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger(fromIndex);
if (index < 0) {
index = nativeMax(length + index, 0);
}
return baseFindIndex(array, getIteratee(predicate, 3), index);
}
/**
* This method is like `_.findIndex` except that it iterates over elements
* of `collection` from right to left.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=array.length-1] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
* _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });
* // => 2
*
* // The `_.matches` iteratee shorthand.
* _.findLastIndex(users, { 'user': 'barney', 'active': true });
* // => 0
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findLastIndex(users, ['active', false]);
* // => 2
*
* // The `_.property` iteratee shorthand.
* _.findLastIndex(users, 'active');
* // => 0
*/
function findLastIndex(array, predicate, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = length - 1;
if (fromIndex !== undefined) {
index = toInteger(fromIndex);
index = fromIndex < 0
? nativeMax(length + index, 0)
: nativeMin(index, length - 1);
}
return baseFindIndex(array, getIteratee(predicate, 3), index, true);
}
/**
* 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) : [];
}
/**
* Recursively flattens `array`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flattenDeep([1, [2, [3, [4]], 5]]);
* // => [1, 2, 3, 4, 5]
*/
function flattenDeep(array) {
var length = array == null ? 0 : array.length;
return length ? baseFlatten(array, INFINITY) : [];
}
/**
* Recursively flatten `array` up to `depth` times.
*
* @static
* @memberOf _
* @since 4.4.0
* @category Array
* @param {Array} array The array to flatten.
* @param {number} [depth=1] The maximum recursion depth.
* @returns {Array} Returns the new flattened array.
* @example
*
* var array = [1, [2, [3, [4]], 5]];
*
* _.flattenDepth(array, 1);
* // => [1, 2, [3, [4]], 5]
*
* _.flattenDepth(array, 2);
* // => [1, 2, 3, [4], 5]
*/
function flattenDepth(array, depth) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
depth = depth === undefined ? 1 : toInteger(depth);
return baseFlatten(array, depth);
}
/**
* The inverse of `_.toPairs`; this method returns an object composed
* from key-value `pairs`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} pairs The key-value pairs.
* @returns {Object} Returns the new object.
* @example
*
* _.fromPairs([['a', 1], ['b', 2]]);
* // => { 'a': 1, 'b': 2 }
*/
function fromPairs(pairs) {
var index = -1,
length = pairs == null ? 0 : pairs.length,
result = {};
while (++index < length) {
var pair = pairs[index];
result[pair[0]] = pair[1];
}
return result;
}
/**
* Gets the first element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @alias first
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the first element of `array`.
* @example
*
* _.head([1, 2, 3]);
* // => 1
*
* _.head([]);
* // => undefined
*/
function head(array) {
return (array && array.length) ? array[0] : undefined;
}
/**
* Gets the index at which the first occurrence of `value` is found in `array`
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. If `fromIndex` is negative, it's used as the
* offset from the end of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.indexOf([1, 2, 1, 2], 2);
* // => 1
*
* // Search from the `fromIndex`.
* _.indexOf([1, 2, 1, 2], 2, 2);
* // => 3
*/
function indexOf(array, value, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger(fromIndex);
if (index < 0) {
index = nativeMax(length + index, 0);
}
return baseIndexOf(array, value, index);
}
/**
* Gets all but the last element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.initial([1, 2, 3]);
* // => [1, 2]
*/
function initial(array) {
var length = array == null ? 0 : array.length;
return length ? baseSlice(array, 0, -1) : [];
}
/**
* 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)
: [];
});
/**
* This method is like `_.intersection` except that it accepts `iteratee`
* which is invoked for each element of each `arrays` to generate the criterion
* by which they're compared. The order and references of result values are
* determined by the first array. The iteratee is invoked with one argument:
* (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new array of intersecting values.
* @example
*
* _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);
* // => [2.1]
*
* // The `_.property` iteratee shorthand.
* _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }]
*/
var intersectionBy = baseRest(function(arrays) {
var iteratee = last(arrays),
mapped = arrayMap(arrays, castArrayLikeObject);
if (iteratee === last(mapped)) {
iteratee = undefined;
} else {
mapped.pop();
}
return (mapped.length && mapped[0] === arrays[0])
? baseIntersection(mapped, getIteratee(iteratee, 2))
: [];
});
/**
* This method is like `_.intersection` except that it accepts `comparator`
* which is invoked to compare elements of `arrays`. The order and references
* of result values are determined by the first array. The comparator is
* invoked with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of intersecting values.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
* var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.intersectionWith(objects, others, _.isEqual);
* // => [{ 'x': 1, 'y': 2 }]
*/
var intersectionWith = baseRest(function(arrays) {
var comparator = last(arrays),
mapped = arrayMap(arrays, castArrayLikeObject);
comparator = typeof comparator == 'function' ? comparator : undefined;
if (comparator) {
mapped.pop();
}
return (mapped.length && mapped[0] === arrays[0])
? baseIntersection(mapped, undefined, comparator)
: [];
});
/**
* Converts all elements in `array` into a string separated by `separator`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to convert.
* @param {string} [separator=','] The element separator.
* @returns {string} Returns the joined string.
* @example
*
* _.join(['a', 'b', 'c'], '~');
* // => 'a~b~c'
*/
function join(array, separator) {
return array == null ? '' : nativeJoin.call(array, separator);
}
/**
* 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;
}
/**
* This method is like `_.indexOf` except that it iterates over elements of
* `array` from right to left.
*
* @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=array.length-1] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.lastIndexOf([1, 2, 1, 2], 2);
* // => 3
*
* // Search from the `fromIndex`.
* _.lastIndexOf([1, 2, 1, 2], 2, 2);
* // => 1
*/
function lastIndexOf(array, value, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = length;
if (fromIndex !== undefined) {
index = toInteger(fromIndex);
index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1);
}
return value === value
? strictLastIndexOf(array, value, index)
: baseFindIndex(array, baseIsNaN, index, true);
}
/**
* Gets the element at index `n` of `array`. If `n` is negative, the nth
* element from the end is returned.
*
* @static
* @memberOf _
* @since 4.11.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=0] The index of the element to return.
* @returns {*} Returns the nth element of `array`.
* @example
*
* var array = ['a', 'b', 'c', 'd'];
*
* _.nth(array, 1);
* // => 'b'
*
* _.nth(array, -2);
* // => 'c';
*/
function nth(array, n) {
return (array && array.length) ? baseNth(array, toInteger(n)) : undefined;
}
/**
* Removes all given values from `array` using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove`
* to remove elements from an array by predicate.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {...*} [values] The values to remove.
* @returns {Array} Returns `array`.
* @example
*
* var array = ['a', 'b', 'c', 'a', 'b', 'c'];
*
* _.pull(array, 'a', 'c');
* console.log(array);
* // => ['b', 'b']
*/
var pull = baseRest(pullAll);
/**
* This method is like `_.pull` except that it accepts an array of values to remove.
*
* **Note:** Unlike `_.difference`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @returns {Array} Returns `array`.
* @example
*
* var array = ['a', 'b', 'c', 'a', 'b', 'c'];
*
* _.pullAll(array, ['a', 'c']);
* console.log(array);
* // => ['b', 'b']
*/
function pullAll(array, values) {
return (array && array.length && values && values.length)
? basePullAll(array, values)
: array;
}
/**
* This method is like `_.pullAll` except that it accepts `iteratee` which is
* invoked for each element of `array` and `values` to generate the criterion
* by which they're compared. The iteratee is invoked with one argument: (value).
*
* **Note:** Unlike `_.differenceBy`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns `array`.
* @example
*
* var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];
*
* _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');
* console.log(array);
* // => [{ 'x': 2 }]
*/
function pullAllBy(array, values, iteratee) {
return (array && array.length && values && values.length)
? basePullAll(array, values, getIteratee(iteratee, 2))
: array;
}
/**
* This method is like `_.pullAll` except that it accepts `comparator` which
* is invoked to compare elements of `array` to `values`. The comparator is
* invoked with two arguments: (arrVal, othVal).
*
* **Note:** Unlike `_.differenceWith`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 4.6.0
* @category Array
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns `array`.
* @example
*
* var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }];
*
* _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual);
* console.log(array);
* // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]
*/
function pullAllWith(array, values, comparator) {
return (array && array.length && values && values.length)
? basePullAll(array, values, undefined, comparator)
: array;
}
/**
* Removes elements from `array` corresponding to `indexes` and returns an
* array of removed elements.
*
* **Note:** Unlike `_.at`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {...(number|number[])} [indexes] The indexes of elements to remove.
* @returns {Array} Returns the new array of removed elements.
* @example
*
* var array = ['a', 'b', 'c', 'd'];
* var pulled = _.pullAt(array, [1, 3]);
*
* console.log(array);
* // => ['a', 'c']
*
* console.log(pulled);
* // => ['b', 'd']
*/
var pullAt = flatRest(function(array, indexes) {
var length = array == null ? 0 : array.length,
result = baseAt(array, indexes);
basePullAt(array, arrayMap(indexes, function(index) {
return isIndex(index, length) ? +index : index;
}).sort(compareAscending));
return result;
});
/**
* Removes all elements from `array` that `predicate` returns truthy for
* and returns an array of the removed elements. The predicate is invoked
* with three arguments: (value, index, array).
*
* **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`
* to pull elements from an array by value.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new array of removed elements.
* @example
*
* var array = [1, 2, 3, 4];
* var evens = _.remove(array, function(n) {
* return n % 2 == 0;
* });
*
* console.log(array);
* // => [1, 3]
*
* console.log(evens);
* // => [2, 4]
*/
function remove(array, predicate) {
var result = [];
if (!(array && array.length)) {
return result;
}
var index = -1,
indexes = [],
length = array.length;
predicate = getIteratee(predicate, 3);
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result.push(value);
indexes.push(index);
}
}
basePullAt(array, indexes);
return result;
}
/**
* Reverses `array` so that the first element becomes the last, the second
* element becomes the second to last, and so on.
*
* **Note:** This method mutates `array` and is based on
* [`Array#reverse`](https://mdn.io/Array/reverse).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to modify.
* @returns {Array} Returns `array`.
* @example
*
* var array = [1, 2, 3];
*
* _.reverse(array);
* // => [3, 2, 1]
*
* console.log(array);
* // => [3, 2, 1]
*/
function reverse(array) {
return array == null ? array : nativeReverse.call(array);
}
/**
* Creates a slice of `array` from `start` up to, but not including, `end`.
*
* **Note:** This method is used instead of
* [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are
* returned.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @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 slice(array, start, end) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {
start = 0;
end = length;
}
else {
start = start == null ? 0 : toInteger(start);
end = end === undefined ? length : toInteger(end);
}
return baseSlice(array, start, end);
}
/**
* Uses a binary search to determine the lowest index at which `value`
* should be inserted into `array` in order to maintain its sort order.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* _.sortedIndex([30, 50], 40);
* // => 1
*/
function sortedIndex(array, value) {
return baseSortedIndex(array, value);
}
/**
* This method is like `_.sortedIndex` except that it accepts `iteratee`
* which is invoked for `value` and each element of `array` to compute their
* sort ranking. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* var objects = [{ 'x': 4 }, { 'x': 5 }];
*
* _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
* // => 0
*
* // The `_.property` iteratee shorthand.
* _.sortedIndexBy(objects, { 'x': 4 }, 'x');
* // => 0
*/
function sortedIndexBy(array, value, iteratee) {
return baseSortedIndexBy(array, value, getIteratee(iteratee, 2));
}
/**
* This method is like `_.indexOf` except that it performs a binary
* search on a sorted `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.sortedIndexOf([4, 5, 5, 5, 6], 5);
* // => 1
*/
function sortedIndexOf(array, value) {
var length = array == null ? 0 : array.length;
if (length) {
var index = baseSortedIndex(array, value);
if (index < length && eq(array[index], value)) {
return index;
}
}
return -1;
}
/**
* This method is like `_.sortedIndex` except that it returns the highest
* index at which `value` should be inserted into `array` in order to
* maintain its sort order.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* _.sortedLastIndex([4, 5, 5, 5, 6], 5);
* // => 4
*/
function sortedLastIndex(array, value) {
return baseSortedIndex(array, value, true);
}
/**
* This method is like `_.sortedLastIndex` except that it accepts `iteratee`
* which is invoked for `value` and each element of `array` to compute their
* sort ranking. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* var objects = [{ 'x': 4 }, { 'x': 5 }];
*
* _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
* // => 1
*
* // The `_.property` iteratee shorthand.
* _.sortedLastIndexBy(objects, { 'x': 4 }, 'x');
* // => 1
*/
function sortedLastIndexBy(array, value, iteratee) {
return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true);
}
/**
* This method is like `_.lastIndexOf` except that it performs a binary
* search on a sorted `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.sortedLastIndexOf([4, 5, 5, 5, 6], 5);
* // => 3
*/
function sortedLastIndexOf(array, value) {
var length = array == null ? 0 : array.length;
if (length) {
var index = baseSortedIndex(array, value, true) - 1;
if (eq(array[index], value)) {
return index;
}
}
return -1;
}
/**
* This method is like `_.uniq` except that it's designed and optimized
* for sorted arrays.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.sortedUniq([1, 1, 2]);
* // => [1, 2]
*/
function sortedUniq(array) {
return (array && array.length)
? baseSortedUniq(array)
: [];
}
/**
* This method is like `_.uniqBy` except that it's designed and optimized
* for sorted arrays.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);
* // => [1.1, 2.3]
*/
function sortedUniqBy(array, iteratee) {
return (array && array.length)
? baseSortedUniq(array, getIteratee(iteratee, 2))
: [];
}
/**
* Gets all but the first element of `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to query.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.tail([1, 2, 3]);
* // => [2, 3]
*/
function tail(array) {
var length = array == null ? 0 : array.length;
return length ? baseSlice(array, 1, length) : [];
}
/**
* Creates a slice of `array` with `n` elements taken from the beginning.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to take.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.take([1, 2, 3]);
* // => [1]
*
* _.take([1, 2, 3], 2);
* // => [1, 2]
*
* _.take([1, 2, 3], 5);
* // => [1, 2, 3]
*
* _.take([1, 2, 3], 0);
* // => []
*/
function take(array, n, guard) {
if (!(array && array.length)) {
return [];
}
n = (guard || n === undefined) ? 1 : toInteger(n);
return baseSlice(array, 0, n < 0 ? 0 : n);
}
/**
* Creates a slice of `array` with `n` elements taken from the end.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to take.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.takeRight([1, 2, 3]);
* // => [3]
*
* _.takeRight([1, 2, 3], 2);
* // => [2, 3]
*
* _.takeRight([1, 2, 3], 5);
* // => [1, 2, 3]
*
* _.takeRight([1, 2, 3], 0);
* // => []
*/
function takeRight(array, n, guard) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
n = (guard || n === undefined) ? 1 : toInteger(n);
n = length - n;
return baseSlice(array, n < 0 ? 0 : n, length);
}
/**
* Creates a slice of `array` with elements taken from the end. Elements are
* taken until `predicate` returns falsey. The predicate is invoked with
* three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
* _.takeRightWhile(users, function(o) { return !o.active; });
* // => objects for ['fred', 'pebbles']
*
* // The `_.matches` iteratee shorthand.
* _.takeRightWhile(users, { 'user': 'pebbles', 'active': false });
* // => objects for ['pebbles']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.takeRightWhile(users, ['active', false]);
* // => objects for ['fred', 'pebbles']
*
* // The `_.property` iteratee shorthand.
* _.takeRightWhile(users, 'active');
* // => []
*/
function takeRightWhile(array, predicate) {
return (array && array.length)
? baseWhile(array, getIteratee(predicate, 3), false, true)
: [];
}
/**
* Creates a slice of `array` with elements taken from the beginning. Elements
* are taken until `predicate` returns falsey. The predicate is invoked with
* three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.takeWhile(users, function(o) { return !o.active; });
* // => objects for ['barney', 'fred']
*
* // The `_.matches` iteratee shorthand.
* _.takeWhile(users, { 'user': 'barney', 'active': false });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.takeWhile(users, ['active', false]);
* // => objects for ['barney', 'fred']
*
* // The `_.property` iteratee shorthand.
* _.takeWhile(users, 'active');
* // => []
*/
function takeWhile(array, predicate) {
return (array && array.length)
? baseWhile(array, getIteratee(predicate, 3))
: [];
}
/**
* Creates an array of unique values, in order, from all given arrays using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of combined values.
* @example
*
* _.union([2], [1, 2]);
* // => [2, 1]
*/
var union = baseRest(function(arrays) {
return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));
});
/**
* This method is like `_.union` except that it accepts `iteratee` which is
* invoked for each element of each `arrays` to generate the criterion by
* which uniqueness is computed. Result values are chosen from the first
* array in which the value occurs. The iteratee is invoked with one argument:
* (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new array of combined values.
* @example
*
* _.unionBy([2.1], [1.2, 2.3], Math.floor);
* // => [2.1, 1.2]
*
* // The `_.property` iteratee shorthand.
* _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }, { 'x': 2 }]
*/
var unionBy = baseRest(function(arrays) {
var iteratee = last(arrays);
if (isArrayLikeObject(iteratee)) {
iteratee = undefined;
}
return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2));
});
/**
* This method is like `_.union` except that it accepts `comparator` which
* is invoked to compare elements of `arrays`. Result values are chosen from
* the first array in which the value occurs. The comparator is invoked
* with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of combined values.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
* var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.unionWith(objects, others, _.isEqual);
* // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
*/
var unionWith = baseRest(function(arrays) {
var comparator = last(arrays);
comparator = typeof comparator == 'function' ? comparator : undefined;
return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator);
});
/**
* Creates a duplicate-free version of an array, using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons, in which only the first occurrence of each element
* is kept. The order of result values is determined by the order they occur
* in the array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.uniq([2, 1, 2]);
* // => [2, 1]
*/
function uniq(array) {
return (array && array.length) ? baseUniq(array) : [];
}
/**
* This method is like `_.uniq` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the criterion by which
* uniqueness is computed. The order of result values is determined by the
* order they occur in the array. The iteratee is invoked with one argument:
* (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.uniqBy([2.1, 1.2, 2.3], Math.floor);
* // => [2.1, 1.2]
*
* // The `_.property` iteratee shorthand.
* _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }, { 'x': 2 }]
*/
function uniqBy(array, iteratee) {
return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : [];
}
/**
* This method is like `_.uniq` except that it accepts `comparator` which
* is invoked to compare elements of `array`. The order of result values is
* determined by the order they occur in the array.The comparator is invoked
* with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.uniqWith(objects, _.isEqual);
* // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
*/
function uniqWith(array, comparator) {
comparator = typeof comparator == 'function' ? comparator : undefined;
return (array && array.length) ? baseUniq(array, undefined, comparator) : [];
}
/**
* This method is like `_.zip` except that it accepts an array of grouped
* elements and creates an array regrouping the elements to their pre-zip
* configuration.
*
* @static
* @memberOf _
* @since 1.2.0
* @category Array
* @param {Array} array The array of grouped elements to process.
* @returns {Array} Returns the new array of regrouped elements.
* @example
*
* var zipped = _.zip(['a', 'b'], [1, 2], [true, false]);
* // => [['a', 1, true], ['b', 2, false]]
*
* _.unzip(zipped);
* // => [['a', 'b'], [1, 2], [true, false]]
*/
function unzip(array) {
if (!(array && array.length)) {
return [];
}
var length = 0;
array = arrayFilter(array, function(group) {
if (isArrayLikeObject(group)) {
length = nativeMax(group.length, length);
return true;
}
});
return baseTimes(length, function(index) {
return arrayMap(array, baseProperty(index));
});
}
/**
* This method is like `_.unzip` except that it accepts `iteratee` to specify
* how regrouped values should be combined. The iteratee is invoked with the
* elements of each group: (...group).
*
* @static
* @memberOf _
* @since 3.8.0
* @category Array
* @param {Array} array The array of grouped elements to process.
* @param {Function} [iteratee=_.identity] The function to combine
* regrouped values.
* @returns {Array} Returns the new array of regrouped elements.
* @example
*
* var zipped = _.zip([1, 2], [10, 20], [100, 200]);
* // => [[1, 10, 100], [2, 20, 200]]
*
* _.unzipWith(zipped, _.add);
* // => [3, 30, 300]
*/
function unzipWith(array, iteratee) {
if (!(array && array.length)) {
return [];
}
var result = unzip(array);
if (iteratee == null) {
return result;
}
return arrayMap(result, function(group) {
return apply(iteratee, undefined, group);
});
}
/**
* Creates an array excluding all given values using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* **Note:** Unlike `_.pull`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...*} [values] The values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @see _.difference, _.xor
* @example
*
* _.without([2, 1, 2, 3], 1, 2);
* // => [3]
*/
var without = baseRest(function(array, values) {
return isArrayLikeObject(array)
? baseDifference(array, values)
: [];
});
/**
* Creates an array of unique values that is the
* [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)
* of the given arrays. The order of result values is determined by the order
* they occur in the arrays.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of filtered values.
* @see _.difference, _.without
* @example
*
* _.xor([2, 1], [2, 3]);
* // => [1, 3]
*/
var xor = baseRest(function(arrays) {
return baseXor(arrayFilter(arrays, isArrayLikeObject));
});
/**
* This method is like `_.xor` except that it accepts `iteratee` which is
* invoked for each element of each `arrays` to generate the criterion by
* which by which they're compared. The order of result values is determined
* by the order they occur in the arrays. The iteratee is invoked with one
* argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);
* // => [1.2, 3.4]
*
* // The `_.property` iteratee shorthand.
* _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 2 }]
*/
var xorBy = baseRest(function(arrays) {
var iteratee = last(arrays);
if (isArrayLikeObject(iteratee)) {
iteratee = undefined;
}
return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2));
});
/**
* This method is like `_.xor` except that it accepts `comparator` which is
* invoked to compare elements of `arrays`. The order of result values is
* determined by the order they occur in the arrays. The comparator is invoked
* with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
* var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.xorWith(objects, others, _.isEqual);
* // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
*/
var xorWith = baseRest(function(arrays) {
var comparator = last(arrays);
comparator = typeof comparator == 'function' ? comparator : undefined;
return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator);
});
/**
* Creates an array of grouped elements, the first of which contains the
* first elements of the given arrays, the second of which contains the
* second elements of the given arrays, and so on.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {...Array} [arrays] The arrays to process.
* @returns {Array} Returns the new array of grouped elements.
* @example
*
* _.zip(['a', 'b'], [1, 2], [true, false]);
* // => [['a', 1, true], ['b', 2, false]]
*/
var zip = baseRest(unzip);
/**
* This method is like `_.fromPairs` except that it accepts two arrays,
* one of property identifiers and one of corresponding values.
*
* @static
* @memberOf _
* @since 0.4.0
* @category Array
* @param {Array} [props=[]] The property identifiers.
* @param {Array} [values=[]] The property values.
* @returns {Object} Returns the new object.
* @example
*
* _.zipObject(['a', 'b'], [1, 2]);
* // => { 'a': 1, 'b': 2 }
*/
function zipObject(props, values) {
return baseZipObject(props || [], values || [], assignValue);
}
/**
* This method is like `_.zipObject` except that it supports property paths.
*
* @static
* @memberOf _
* @since 4.1.0
* @category Array
* @param {Array} [props=[]] The property identifiers.
* @param {Array} [values=[]] The property values.
* @returns {Object} Returns the new object.
* @example
*
* _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);
* // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }
*/
function zipObjectDeep(props, values) {
return baseZipObject(props || [], values || [], baseSet);
}
/**
* This method is like `_.zip` except that it accepts `iteratee` to specify
* how grouped values should be combined. The iteratee is invoked with the
* elements of each group: (...group).
*
* @static
* @memberOf _
* @since 3.8.0
* @category Array
* @param {...Array} [arrays] The arrays to process.
* @param {Function} [iteratee=_.identity] The function to combine
* grouped values.
* @returns {Array} Returns the new array of grouped elements.
* @example
*
* _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {
* return a + b + c;
* });
* // => [111, 222]
*/
var zipWith = baseRest(function(arrays) {
var length = arrays.length,
iteratee = length > 1 ? arrays[length - 1] : undefined;
iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined;
return unzipWith(arrays, iteratee);
});
/*------------------------------------------------------------------------*/
/**
* Creates a `lodash` wrapper instance that wraps `value` with explicit method
* chain sequences enabled. The result of such sequences must be unwrapped
* with `_#value`.
*
* @static
* @memberOf _
* @since 1.3.0
* @category Seq
* @param {*} value The value to wrap.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'pebbles', 'age': 1 }
* ];
*
* var youngest = _
* .chain(users)
* .sortBy('age')
* .map(function(o) {
* return o.user + ' is ' + o.age;
* })
* .head()
* .value();
* // => 'pebbles is 1'
*/
function chain(value) {
var result = lodash(value);
result.__chain__ = true;
return result;
}
/**
* This method invokes `interceptor` and returns `value`. The interceptor
* is invoked with one argument; (value). The purpose of this method is to
* "tap into" a method chain sequence in order to modify intermediate results.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Seq
* @param {*} value The value to provide to `interceptor`.
* @param {Function} interceptor The function to invoke.
* @returns {*} Returns `value`.
* @example
*
* _([1, 2, 3])
* .tap(function(array) {
* // Mutate input array.
* array.pop();
* })
* .reverse()
* .value();
* // => [2, 1]
*/
function tap(value, interceptor) {
interceptor(value);
return value;
}
/**
* This method is like `_.tap` except that it returns the result of `interceptor`.
* The purpose of this method is to "pass thru" values replacing intermediate
* results in a method chain sequence.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Seq
* @param {*} value The value to provide to `interceptor`.
* @param {Function} interceptor The function to invoke.
* @returns {*} Returns the result of `interceptor`.
* @example
*
* _(' abc ')
* .chain()
* .trim()
* .thru(function(value) {
* return [value];
* })
* .value();
* // => ['abc']
*/
function thru(value, interceptor) {
return interceptor(value);
}
/**
* This method is the wrapper version of `_.at`.
*
* @name at
* @memberOf _
* @since 1.0.0
* @category Seq
* @param {...(string|string[])} [paths] The property paths to pick.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
*
* _(object).at(['a[0].b.c', 'a[1]']).value();
* // => [3, 4]
*/
var wrapperAt = flatRest(function(paths) {
var length = paths.length,
start = length ? paths[0] : 0,
value = this.__wrapped__,
interceptor = function(object) { return baseAt(object, paths); };
if (length > 1 || this.__actions__.length ||
!(value instanceof LazyWrapper) || !isIndex(start)) {
return this.thru(interceptor);
}
value = value.slice(start, +start + (length ? 1 : 0));
value.__actions__.push({
'func': thru,
'args': [interceptor],
'thisArg': undefined
});
return new LodashWrapper(value, this.__chain__).thru(function(array) {
if (length && !array.length) {
array.push(undefined);
}
return array;
});
});
/**
* Creates a `lodash` wrapper instance with explicit method chain sequences enabled.
*
* @name chain
* @memberOf _
* @since 0.1.0
* @category Seq
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 }
* ];
*
* // A sequence without explicit chaining.
* _(users).head();
* // => { 'user': 'barney', 'age': 36 }
*
* // A sequence with explicit chaining.
* _(users)
* .chain()
* .head()
* .pick('user')
* .value();
* // => { 'user': 'barney' }
*/
function wrapperChain() {
return chain(this);
}
/**
* Executes the chain sequence and returns the wrapped result.
*
* @name commit
* @memberOf _
* @since 3.2.0
* @category Seq
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var array = [1, 2];
* var wrapped = _(array).push(3);
*
* console.log(array);
* // => [1, 2]
*
* wrapped = wrapped.commit();
* console.log(array);
* // => [1, 2, 3]
*
* wrapped.last();
* // => 3
*
* console.log(array);
* // => [1, 2, 3]
*/
function wrapperCommit() {
return new LodashWrapper(this.value(), this.__chain__);
}
/**
* Gets the next value on a wrapped object following the
* [iterator protocol](https://mdn.io/iteration_protocols#iterator).
*
* @name next
* @memberOf _
* @since 4.0.0
* @category Seq
* @returns {Object} Returns the next iterator value.
* @example
*
* var wrapped = _([1, 2]);
*
* wrapped.next();
* // => { 'done': false, 'value': 1 }
*
* wrapped.next();
* // => { 'done': false, 'value': 2 }
*
* wrapped.next();
* // => { 'done': true, 'value': undefined }
*/
function wrapperNext() {
if (this.__values__ === undefined) {
this.__values__ = toArray(this.value());
}
var done = this.__index__ >= this.__values__.length,
value = done ? undefined : this.__values__[this.__index__++];
return { 'done': done, 'value': value };
}
/**
* Enables the wrapper to be iterable.
*
* @name Symbol.iterator
* @memberOf _
* @since 4.0.0
* @category Seq
* @returns {Object} Returns the wrapper object.
* @example
*
* var wrapped = _([1, 2]);
*
* wrapped[Symbol.iterator]() === wrapped;
* // => true
*
* Array.from(wrapped);
* // => [1, 2]
*/
function wrapperToIterator() {
return this;
}
/**
* Creates a clone of the chain sequence planting `value` as the wrapped value.
*
* @name plant
* @memberOf _
* @since 3.2.0
* @category Seq
* @param {*} value The value to plant.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* function square(n) {
* return n * n;
* }
*
* var wrapped = _([1, 2]).map(square);
* var other = wrapped.plant([3, 4]);
*
* other.value();
* // => [9, 16]
*
* wrapped.value();
* // => [1, 4]
*/
function wrapperPlant(value) {
var result,
parent = this;
while (parent instanceof baseLodash) {
var clone = wrapperClone(parent);
clone.__index__ = 0;
clone.__values__ = undefined;
if (result) {
previous.__wrapped__ = clone;
} else {
result = clone;
}
var previous = clone;
parent = parent.__wrapped__;
}
previous.__wrapped__ = value;
return result;
}
/**
* This method is the wrapper version of `_.reverse`.
*
* **Note:** This method mutates the wrapped array.
*
* @name reverse
* @memberOf _
* @since 0.1.0
* @category Seq
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var array = [1, 2, 3];
*
* _(array).reverse().value()
* // => [3, 2, 1]
*
* console.log(array);
* // => [3, 2, 1]
*/
function wrapperReverse() {
var value = this.__wrapped__;
if (value instanceof LazyWrapper) {
var wrapped = value;
if (this.__actions__.length) {
wrapped = new LazyWrapper(this);
}
wrapped = wrapped.reverse();
wrapped.__actions__.push({
'func': thru,
'args': [reverse],
'thisArg': undefined
});
return new LodashWrapper(wrapped, this.__chain__);
}
return this.thru(reverse);
}
/**
* Executes the chain sequence to resolve the unwrapped value.
*
* @name value
* @memberOf _
* @since 0.1.0
* @alias toJSON, valueOf
* @category Seq
* @returns {*} Returns the resolved unwrapped value.
* @example
*
* _([1, 2, 3]).value();
* // => [1, 2, 3]
*/
function wrapperValue() {
return baseWrapperValue(this.__wrapped__, this.__actions__);
}
/*------------------------------------------------------------------------*/
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` thru `iteratee`. The corresponding value of
* each key is the number of times the key was returned by `iteratee`. The
* iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 0.5.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee to transform keys.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.countBy([6.1, 4.2, 6.3], Math.floor);
* // => { '4': 1, '6': 2 }
*
* // The `_.property` iteratee shorthand.
* _.countBy(['one', 'two', 'three'], 'length');
* // => { '3': 2, '5': 1 }
*/
var countBy = createAggregator(function(result, value, key) {
if (hasOwnProperty.call(result, key)) {
++result[key];
} else {
baseAssignValue(result, key, 1);
}
});
/**
* Checks if `predicate` returns truthy for **all** elements of `collection`.
* Iteration is stopped once `predicate` returns falsey. The predicate is
* invoked with three arguments: (value, index|key, collection).
*
* **Note:** This method returns `true` for
* [empty collections](https://en.wikipedia.org/wiki/Empty_set) because
* [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of
* elements of empty collections.
*
* @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.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`.
* @example
*
* _.every([true, 1, null, 'yes'], Boolean);
* // => false
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.every(users, { 'user': 'barney', 'active': false });
* // => false
*
* // The `_.matchesProperty` iteratee shorthand.
* _.every(users, ['active', false]);
* // => true
*
* // The `_.property` iteratee shorthand.
* _.every(users, 'active');
* // => false
*/
function every(collection, predicate, guard) {
var func = isArray(collection) ? arrayEvery : baseEvery;
if (guard && isIterateeCall(collection, predicate, guard)) {
predicate = undefined;
}
return func(collection, getIteratee(predicate, 3));
}
/**
* 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']
*
* // Combining several predicates using `_.overEvery` or `_.overSome`.
* _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]]));
* // => objects for ['fred', 'barney']
*/
function filter(collection, predicate) {
var func = isArray(collection) ? arrayFilter : baseFilter;
return func(collection, getIteratee(predicate, 3));
}
/**
* 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);
/**
* This method is like `_.find` except that it iterates over elements of
* `collection` from right to left.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Collection
* @param {Array|Object} collection The collection to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=collection.length-1] The index to search from.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* _.findLast([1, 2, 3, 4], function(n) {
* return n % 2 == 1;
* });
* // => 3
*/
var findLast = createFind(findLastIndex);
/**
* Creates a flattened array of values by running each element in `collection`
* thru `iteratee` and flattening the mapped results. The iteratee is invoked
* with three arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 4.0.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 flattened array.
* @example
*
* function duplicate(n) {
* return [n, n];
* }
*
* _.flatMap([1, 2], duplicate);
* // => [1, 1, 2, 2]
*/
function flatMap(collection, iteratee) {
return baseFlatten(map(collection, iteratee), 1);
}
/**
* This method is like `_.flatMap` except that it recursively flattens the
* mapped results.
*
* @static
* @memberOf _
* @since 4.7.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 flattened array.
* @example
*
* function duplicate(n) {
* return [[[n, n]]];
* }
*
* _.flatMapDeep([1, 2], duplicate);
* // => [1, 1, 2, 2]
*/
function flatMapDeep(collection, iteratee) {
return baseFlatten(map(collection, iteratee), INFINITY);
}
/**
* This method is like `_.flatMap` except that it recursively flattens the
* mapped results up to `depth` times.
*
* @static
* @memberOf _
* @since 4.7.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {number} [depth=1] The maximum recursion depth.
* @returns {Array} Returns the new flattened array.
* @example
*
* function duplicate(n) {
* return [[[n, n]]];
* }
*
* _.flatMapDepth([1, 2], duplicate, 2);
* // => [[1, 1], [2, 2]]
*/
function flatMapDepth(collection, iteratee, depth) {
depth = depth === undefined ? 1 : toInteger(depth);
return baseFlatten(map(collection, iteratee), depth);
}
/**
* Iterates over elements of `collection` and invokes `iteratee` for each element.
* The iteratee is invoked with three arguments: (value, index|key, collection).
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* **Note:** As with other "Collections" methods, objects with a "length"
* property are iterated like arrays. To avoid this behavior use `_.forIn`
* or `_.forOwn` for object iteration.
*
* @static
* @memberOf _
* @since 0.1.0
* @alias each
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
* @see _.forEachRight
* @example
*
* _.forEach([1, 2], function(value) {
* console.log(value);
* });
* // => Logs `1` then `2`.
*
* _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/
function forEach(collection, iteratee) {
var func = isArray(collection) ? arrayEach : baseEach;
return func(collection, getIteratee(iteratee, 3));
}
/**
* This method is like `_.forEach` except that it iterates over elements of
* `collection` from right to left.
*
* @static
* @memberOf _
* @since 2.0.0
* @alias eachRight
* @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 _.forEach
* @example
*
* _.forEachRight([1, 2], function(value) {
* console.log(value);
* });
* // => Logs `2` then `1`.
*/
function forEachRight(collection, iteratee) {
var func = isArray(collection) ? arrayEachRight : baseEachRight;
return func(collection, getIteratee(iteratee, 3));
}
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` thru `iteratee`. The order of grouped values
* is determined by the order they occur in `collection`. The corresponding
* value of each key is an array of elements responsible for generating the
* key. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee to transform keys.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.groupBy([6.1, 4.2, 6.3], Math.floor);
* // => { '4': [4.2], '6': [6.1, 6.3] }
*
* // The `_.property` iteratee shorthand.
* _.groupBy(['one', 'two', 'three'], 'length');
* // => { '3': ['one', 'two'], '5': ['three'] }
*/
var groupBy = createAggregator(function(result, value, key) {
if (hasOwnProperty.call(result, key)) {
result[key].push(value);
} else {
baseAssignValue(result, key, [value]);
}
});
/**
* Checks if `value` is in `collection`. If `collection` is a string, it's
* checked for a substring of `value`, otherwise
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* is used for equality comparisons. If `fromIndex` is negative, it's used as
* the offset from the end of `collection`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {boolean} Returns `true` if `value` is found, else `false`.
* @example
*
* _.includes([1, 2, 3], 1);
* // => true
*
* _.includes([1, 2, 3], 1, 2);
* // => false
*
* _.includes({ 'a': 1, 'b': 2 }, 1);
* // => true
*
* _.includes('abcd', 'bc');
* // => true
*/
function includes(collection, value, fromIndex, guard) {
collection = isArrayLike(collection) ? collection : values(collection);
fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;
var length = collection.length;
if (fromIndex < 0) {
fromIndex = nativeMax(length + fromIndex, 0);
}
return isString(collection)
? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)
: (!!length && baseIndexOf(collection, value, fromIndex) > -1);
}
/**
* Invokes the method at `path` of each element in `collection`, returning
* an array of the results of each invoked method. Any additional arguments
* are provided to each invoked method. If `path` is a function, it's invoked
* for, and `this` bound to, each element in `collection`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Array|Function|string} path The path of the method to invoke or
* the function invoked per iteration.
* @param {...*} [args] The arguments to invoke each method with.
* @returns {Array} Returns the array of results.
* @example
*
* _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');
* // => [[1, 5, 7], [1, 2, 3]]
*
* _.invokeMap([123, 456], String.prototype.split, '');
* // => [['1', '2', '3'], ['4', '5', '6']]
*/
var invokeMap = baseRest(function(collection, path, args) {
var index = -1,
isFunc = typeof path == 'function',
result = isArrayLike(collection) ? Array(collection.length) : [];
baseEach(collection, function(value) {
result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args);
});
return result;
});
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` thru `iteratee`. The corresponding value of
* each key is the last element responsible for generating the key. The
* iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee to transform keys.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* var array = [
* { 'dir': 'left', 'code': 97 },
* { 'dir': 'right', 'code': 100 }
* ];
*
* _.keyBy(array, function(o) {
* return String.fromCharCode(o.code);
* });
* // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
*
* _.keyBy(array, 'dir');
* // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
*/
var keyBy = createAggregator(function(result, value, key) {
baseAssignValue(result, key, value);
});
/**
* Creates an array of values by running each element in `collection` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
*
* The guarded methods are:
* `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
* `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
* `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
* `template`, `trim`, `trimEnd`, `trimStart`, and `words`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
* @example
*
* function square(n) {
* return n * n;
* }
*
* _.map([4, 8], square);
* // => [16, 64]
*
* _.map({ 'a': 4, 'b': 8 }, square);
* // => [16, 64] (iteration order is not guaranteed)
*
* var users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
*
* // The `_.property` iteratee shorthand.
* _.map(users, 'user');
* // => ['barney', 'fred']
*/
function map(collection, iteratee) {
var func = isArray(collection) ? arrayMap : baseMap;
return func(collection, getIteratee(iteratee, 3));
}
/**
* This method is like `_.sortBy` except that it allows specifying the sort
* orders of the iteratees to sort by. If `orders` is unspecified, all values
* are sorted in ascending order. Otherwise, specify an order of "desc" for
* descending or "asc" for ascending sort order of corresponding values.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]
* The iteratees to sort by.
* @param {string[]} [orders] The sort orders of `iteratees`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 48 },
* { 'user': 'barney', 'age': 34 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'barney', 'age': 36 }
* ];
*
* // Sort by `user` in ascending order and by `age` in descending order.
* _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
* // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
*/
function orderBy(collection, iteratees, orders, guard) {
if (collection == null) {
return [];
}
if (!isArray(iteratees)) {
iteratees = iteratees == null ? [] : [iteratees];
}
orders = guard ? undefined : orders;
if (!isArray(orders)) {
orders = orders == null ? [] : [orders];
}
return baseOrderBy(collection, iteratees, orders);
}
/**
* Creates an array of elements split into two groups, the first of which
* contains elements `predicate` returns truthy for, the second of which
* contains elements `predicate` returns falsey for. The predicate is
* invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 3.0.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 array of grouped elements.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': true },
* { 'user': 'pebbles', 'age': 1, 'active': false }
* ];
*
* _.partition(users, function(o) { return o.active; });
* // => objects for [['fred'], ['barney', 'pebbles']]
*
* // The `_.matches` iteratee shorthand.
* _.partition(users, { 'age': 1, 'active': false });
* // => objects for [['pebbles'], ['barney', 'fred']]
*
* // The `_.matchesProperty` iteratee shorthand.
* _.partition(users, ['active', false]);
* // => objects for [['barney', 'pebbles'], ['fred']]
*
* // The `_.property` iteratee shorthand.
* _.partition(users, 'active');
* // => objects for [['fred'], ['barney', 'pebbles']]
*/
var partition = createAggregator(function(result, value, key) {
result[key ? 0 : 1].push(value);
}, function() { return [[], []]; });
/**
* Reduces `collection` to a value which is the accumulated result of running
* each element in `collection` thru `iteratee`, where each successive
* invocation is supplied the return value of the previous. If `accumulator`
* is not given, the first element of `collection` is used as the initial
* value. The iteratee is invoked with four arguments:
* (accumulator, value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.reduce`, `_.reduceRight`, and `_.transform`.
*
* The guarded methods are:
* `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
* and `sortBy`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @returns {*} Returns the accumulated value.
* @see _.reduceRight
* @example
*
* _.reduce([1, 2], function(sum, n) {
* return sum + n;
* }, 0);
* // => 3
*
* _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
* (result[value] || (result[value] = [])).push(key);
* return result;
* }, {});
* // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
*/
function reduce(collection, iteratee, accumulator) {
var func = isArray(collection) ? arrayReduce : baseReduce,
initAccum = arguments.length < 3;
return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach);
}
/**
* This method is like `_.reduce` except that it iterates over elements of
* `collection` from right to left.
*
* @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 _.reduce
* @example
*
* var array = [[0, 1], [2, 3], [4, 5]];
*
* _.reduceRight(array, function(flattened, other) {
* return flattened.concat(other);
* }, []);
* // => [4, 5, 2, 3, 0, 1]
*/
function reduceRight(collection, iteratee, accumulator) {
var func = isArray(collection) ? arrayReduceRight : baseReduce,
initAccum = arguments.length < 3;
return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight);
}
/**
* The opposite of `_.filter`; this method returns the elements of `collection`
* that `predicate` does **not** return truthy for.
*
* @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 _.filter
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': true }
* ];
*
* _.reject(users, function(o) { return !o.active; });
* // => objects for ['fred']
*
* // The `_.matches` iteratee shorthand.
* _.reject(users, { 'age': 40, 'active': true });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.reject(users, ['active', false]);
* // => objects for ['fred']
*
* // The `_.property` iteratee shorthand.
* _.reject(users, 'active');
* // => objects for ['barney']
*/
function reject(collection, predicate) {
var func = isArray(collection) ? arrayFilter : baseFilter;
return func(collection, negate(getIteratee(predicate, 3)));
}
/**
* Gets a random element from `collection`.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Collection
* @param {Array|Object} collection The collection to sample.
* @returns {*} Returns the random element.
* @example
*
* _.sample([1, 2, 3, 4]);
* // => 2
*/
function sample(collection) {
var func = isArray(collection) ? arraySample : baseSample;
return func(collection);
}
/**
* Gets `n` random elements at unique keys from `collection` up to the
* size of `collection`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to sample.
* @param {number} [n=1] The number of elements to sample.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the random elements.
* @example
*
* _.sampleSize([1, 2, 3], 2);
* // => [3, 1]
*
* _.sampleSize([1, 2, 3], 4);
* // => [2, 3, 1]
*/
function sampleSize(collection, n, guard) {
if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) {
n = 1;
} else {
n = toInteger(n);
}
var func = isArray(collection) ? arraySampleSize : baseSampleSize;
return func(collection, n);
}
/**
* Creates an array of shuffled values, using a version of the
* [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to shuffle.
* @returns {Array} Returns the new shuffled array.
* @example
*
* _.shuffle([1, 2, 3, 4]);
* // => [4, 1, 3, 2]
*/
function shuffle(collection) {
var func = isArray(collection) ? arrayShuffle : baseShuffle;
return func(collection);
}
/**
* Gets the size of `collection` by returning its length for array-like
* values or the number of own enumerable string keyed properties for objects.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @returns {number} Returns the collection size.
* @example
*
* _.size([1, 2, 3]);
* // => 3
*
* _.size({ 'a': 1, 'b': 2 });
* // => 2
*
* _.size('pebbles');
* // => 7
*/
function size(collection) {
if (collection == null) {
return 0;
}
if (isArrayLike(collection)) {
return isString(collection) ? stringSize(collection) : collection.length;
}
var tag = getTag(collection);
if (tag == mapTag || tag == setTag) {
return collection.size;
}
return baseKeys(collection).length;
}
/**
* Checks if `predicate` returns truthy for **any** element of `collection`.
* Iteration is stopped once `predicate` returns truthy. 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 iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
* @example
*
* _.some([null, 0, 'yes', false], Boolean);
* // => true
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.some(users, { 'user': 'barney', 'active': false });
* // => false
*
* // The `_.matchesProperty` iteratee shorthand.
* _.some(users, ['active', false]);
* // => true
*
* // The `_.property` iteratee shorthand.
* _.some(users, 'active');
* // => true
*/
function some(collection, predicate, guard) {
var func = isArray(collection) ? arraySome : baseSome;
if (guard && isIterateeCall(collection, predicate, guard)) {
predicate = undefined;
}
return func(collection, getIteratee(predicate, 3));
}
/**
* Creates an array of elements, sorted in ascending order by the results of
* running each element in a collection thru each iteratee. This method
* performs a stable sort, that is, it preserves the original sort order of
* equal elements. The iteratees are invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {...(Function|Function[])} [iteratees=[_.identity]]
* The iteratees to sort by.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 48 },
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 30 },
* { 'user': 'barney', 'age': 34 }
* ];
*
* _.sortBy(users, [function(o) { return o.user; }]);
* // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]
*
* _.sortBy(users, ['user', 'age']);
* // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]
*/
var sortBy = baseRest(function(collection, iteratees) {
if (collection == null) {
return [];
}
var length = iteratees.length;
if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {
iteratees = [];
} else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
iteratees = [iteratees[0]];
}
return baseOrderBy(collection, baseFlatten(iteratees, 1), []);
});
/*------------------------------------------------------------------------*/
/**
* Gets the timestamp of the number of milliseconds that have elapsed since
* the Unix epoch (1 January 1970 00:00:00 UTC).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Date
* @returns {number} Returns the timestamp.
* @example
*
* _.defer(function(stamp) {
* console.log(_.now() - stamp);
* }, _.now());
* // => Logs the number of milliseconds it took for the deferred invocation.
*/
var now = ctxNow || function() {
return root.Date.now();
};
/*------------------------------------------------------------------------*/
/**
* The opposite of `_.before`; this method creates a function that invokes
* `func` once it's called `n` or more times.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {number} n The number of calls before `func` is invoked.
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var saves = ['profile', 'settings'];
*
* var done = _.after(saves.length, function() {
* console.log('done saving!');
* });
*
* _.forEach(saves, function(type) {
* asyncSave({ 'type': type, 'complete': done });
* });
* // => Logs 'done saving!' after the two async saves have completed.
*/
function after(n, func) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
n = toInteger(n);
return function() {
if (--n < 1) {
return func.apply(this, arguments);
}
};
}
/**
* Creates a function that invokes `func`, with up to `n` arguments,
* ignoring any additional arguments.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} func The function to cap arguments for.
* @param {number} [n=func.length] The arity cap.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the new capped function.
* @example
*
* _.map(['6', '8', '10'], _.ary(parseInt, 1));
* // => [6, 8, 10]
*/
function ary(func, n, guard) {
n = guard ? undefined : n;
n = (func && n == null) ? func.length : n;
return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n);
}
/**
* Creates a function that invokes `func`, with the `this` binding and arguments
* of the created function, while it's called less than `n` times. Subsequent
* calls to the created function return the result of the last `func` invocation.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {number} n The number of calls at which `func` is no longer invoked.
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* jQuery(element).on('click', _.before(5, addContactToList));
* // => Allows adding up to 4 contacts to the list.
*/
function before(n, func) {
var result;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
n = toInteger(n);
return function() {
if (--n > 0) {
result = func.apply(this, arguments);
}
if (n <= 1) {
func = undefined;
}
return result;
};
}
/**
* Creates a function that invokes `func` with the `this` binding of `thisArg`
* and `partials` prepended to the arguments it receives.
*
* The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for partially applied arguments.
*
* **Note:** Unlike native `Function#bind`, this method doesn't set the "length"
* property of bound functions.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* function greet(greeting, punctuation) {
* return greeting + ' ' + this.user + punctuation;
* }
*
* var object = { 'user': 'fred' };
*
* var bound = _.bind(greet, object, 'hi');
* bound('!');
* // => 'hi fred!'
*
* // Bound with placeholders.
* var bound = _.bind(greet, object, _, '!');
* bound('hi');
* // => 'hi fred!'
*/
var bind = baseRest(function(func, thisArg, partials) {
var bitmask = WRAP_BIND_FLAG;
if (partials.length) {
var holders = replaceHolders(partials, getHolder(bind));
bitmask |= WRAP_PARTIAL_FLAG;
}
return createWrap(func, bitmask, thisArg, partials, holders);
});
/**
* Creates a function that invokes the method at `object[key]` with `partials`
* prepended to the arguments it receives.
*
* This method differs from `_.bind` by allowing bound functions to reference
* methods that may be redefined or don't yet exist. See
* [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)
* for more details.
*
* The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* @static
* @memberOf _
* @since 0.10.0
* @category Function
* @param {Object} object The object to invoke the method on.
* @param {string} key The key of the method.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* var object = {
* 'user': 'fred',
* 'greet': function(greeting, punctuation) {
* return greeting + ' ' + this.user + punctuation;
* }
* };
*
* var bound = _.bindKey(object, 'greet', 'hi');
* bound('!');
* // => 'hi fred!'
*
* object.greet = function(greeting, punctuation) {
* return greeting + 'ya ' + this.user + punctuation;
* };
*
* bound('!');
* // => 'hiya fred!'
*
* // Bound with placeholders.
* var bound = _.bindKey(object, 'greet', _, '!');
* bound('hi');
* // => 'hiya fred!'
*/
var bindKey = baseRest(function(object, key, partials) {
var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG;
if (partials.length) {
var holders = replaceHolders(partials, getHolder(bindKey));
bitmask |= WRAP_PARTIAL_FLAG;
}
return createWrap(key, bitmask, object, partials, holders);
});
/**
* Creates a function that accepts arguments of `func` and either invokes
* `func` returning its result, if at least `arity` number of arguments have
* been provided, or returns a function that accepts the remaining `func`
* arguments, and so on. The arity of `func` may be specified if `func.length`
* is not sufficient.
*
* The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for provided arguments.
*
* **Note:** This method doesn't set the "length" property of curried functions.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Function
* @param {Function} func The function to curry.
* @param {number} [arity=func.length] The arity of `func`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the new curried function.
* @example
*
* var abc = function(a, b, c) {
* return [a, b, c];
* };
*
* var curried = _.curry(abc);
*
* curried(1)(2)(3);
* // => [1, 2, 3]
*
* curried(1, 2)(3);
* // => [1, 2, 3]
*
* curried(1, 2, 3);
* // => [1, 2, 3]
*
* // Curried with placeholders.
* curried(1)(_, 3)(2);
* // => [1, 2, 3]
*/
function curry(func, arity, guard) {
arity = guard ? undefined : arity;
var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
result.placeholder = curry.placeholder;
return result;
}
/**
* This method is like `_.curry` except that arguments are applied to `func`
* in the manner of `_.partialRight` instead of `_.partial`.
*
* The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for provided arguments.
*
* **Note:** This method doesn't set the "length" property of curried functions.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} func The function to curry.
* @param {number} [arity=func.length] The arity of `func`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the new curried function.
* @example
*
* var abc = function(a, b, c) {
* return [a, b, c];
* };
*
* var curried = _.curryRight(abc);
*
* curried(3)(2)(1);
* // => [1, 2, 3]
*
* curried(2, 3)(1);
* // => [1, 2, 3]
*
* curried(1, 2, 3);
* // => [1, 2, 3]
*
* // Curried with placeholders.
* curried(3)(1, _)(2);
* // => [1, 2, 3]
*/
function curryRight(func, arity, guard) {
arity = guard ? undefined : arity;
var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
result.placeholder = curryRight.placeholder;
return result;
}
/**
* Creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked. The debounced function comes with a `cancel` method to cancel
* delayed `func` invocations and a `flush` method to immediately invoke them.
* Provide `options` to indicate whether `func` should be invoked on the
* leading and/or trailing edge of the `wait` timeout. The `func` is invoked
* with the last arguments provided to the debounced function. Subsequent
* calls to the debounced function return the result of the last `func`
* invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the debounced function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.debounce` and `_.throttle`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to debounce.
* @param {number} [wait=0] The number of milliseconds to delay.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=false]
* Specify invoking on the leading edge of the timeout.
* @param {number} [options.maxWait]
* The maximum time `func` is allowed to be delayed before it's invoked.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // Avoid costly calculations while the window size is in flux.
* jQuery(window).on('resize', _.debounce(calculateLayout, 150));
*
* // Invoke `sendMail` when clicked, debouncing subsequent calls.
* jQuery(element).on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* }));
*
* // Ensure `batchLog` is invoked once after 1 second of debounced calls.
* var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
* var source = new EventSource('/stream');
* jQuery(source).on('message', debounced);
*
* // Cancel the trailing debounced invocation.
* jQuery(window).on('popstate', debounced.cancel);
*/
function debounce(func, wait, options) {
var lastArgs,
lastThis,
maxWait,
result,
timerId,
lastCallTime,
lastInvokeTime = 0,
leading = false,
maxing = false,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
wait = toNumber(wait) || 0;
if (isObject(options)) {
leading = !!options.leading;
maxing = 'maxWait' in options;
maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
function invokeFunc(time) {
var args = lastArgs,
thisArg = lastThis;
lastArgs = lastThis = undefined;
lastInvokeTime = time;
result = func.apply(thisArg, args);
return result;
}
function leadingEdge(time) {
// Reset any `maxWait` timer.
lastInvokeTime = time;
// Start the timer for the trailing edge.
timerId = setTimeout(timerExpired, wait);
// Invoke the leading edge.
return leading ? invokeFunc(time) : result;
}
function remainingWait(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime,
timeWaiting = wait - timeSinceLastCall;
return maxing
? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)
: timeWaiting;
}
function shouldInvoke(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime;
// Either this is the first call, activity has stopped and we're at the
// trailing edge, the system time has gone backwards and we're treating
// it as the trailing edge, or we've hit the `maxWait` limit.
return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
(timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
}
function timerExpired() {
var time = now();
if (shouldInvoke(time)) {
return trailingEdge(time);
}
// Restart the timer.
timerId = setTimeout(timerExpired, remainingWait(time));
}
function trailingEdge(time) {
timerId = undefined;
// Only invoke if we have `lastArgs` which means `func` has been
// debounced at least once.
if (trailing && lastArgs) {
return invokeFunc(time);
}
lastArgs = lastThis = undefined;
return result;
}
function cancel() {
if (timerId !== undefined) {
clearTimeout(timerId);
}
lastInvokeTime = 0;
lastArgs = lastCallTime = lastThis = timerId = undefined;
}
function flush() {
return timerId === undefined ? result : trailingEdge(now());
}
function debounced() {
var time = now(),
isInvoking = shouldInvoke(time);
lastArgs = arguments;
lastThis = this;
lastCallTime = time;
if (isInvoking) {
if (timerId === undefined) {
return leadingEdge(lastCallTime);
}
if (maxing) {
// Handle invocations in a tight loop.
clearTimeout(timerId);
timerId = setTimeout(timerExpired, wait);
return invokeFunc(lastCallTime);
}
}
if (timerId === undefined) {
timerId = setTimeout(timerExpired, wait);
}
return result;
}
debounced.cancel = cancel;
debounced.flush = flush;
return debounced;
}
/**
* Defers invoking the `func` until the current call stack has cleared. Any
* additional arguments are provided to `func` when it's invoked.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to defer.
* @param {...*} [args] The arguments to invoke `func` with.
* @returns {number} Returns the timer id.
* @example
*
* _.defer(function(text) {
* console.log(text);
* }, 'deferred');
* // => Logs 'deferred' after one millisecond.
*/
var defer = baseRest(function(func, args) {
return baseDelay(func, 1, args);
});
/**
* Invokes `func` after `wait` milliseconds. Any additional arguments are
* provided to `func` when it's invoked.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay invocation.
* @param {...*} [args] The arguments to invoke `func` with.
* @returns {number} Returns the timer id.
* @example
*
* _.delay(function(text) {
* console.log(text);
* }, 1000, 'later');
* // => Logs 'later' after one second.
*/
var delay = baseRest(function(func, wait, args) {
return baseDelay(func, toNumber(wait) || 0, args);
});
/**
* Creates a function that invokes `func` with arguments reversed.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Function
* @param {Function} func The function to flip arguments for.
* @returns {Function} Returns the new flipped function.
* @example
*
* var flipped = _.flip(function() {
* return _.toArray(arguments);
* });
*
* flipped('a', 'b', 'c', 'd');
* // => ['d', 'c', 'b', 'a']
*/
function flip(func) {
return createWrap(func, WRAP_FLIP_FLAG);
}
/**
* 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;
/**
* Creates a function that negates the result of the predicate `func`. The
* `func` predicate is invoked with the `this` binding and arguments of the
* created function.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} predicate The predicate to negate.
* @returns {Function} Returns the new negated function.
* @example
*
* function isEven(n) {
* return n % 2 == 0;
* }
*
* _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
* // => [1, 3, 5]
*/
function negate(predicate) {
if (typeof predicate != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
return function() {
var args = arguments;
switch (args.length) {
case 0: return !predicate.call(this);
case 1: return !predicate.call(this, args[0]);
case 2: return !predicate.call(this, args[0], args[1]);
case 3: return !predicate.call(this, args[0], args[1], args[2]);
}
return !predicate.apply(this, args);
};
}
/**
* Creates a function that is restricted to invoking `func` once. Repeat calls
* to the function return the value of the first invocation. The `func` is
* invoked with the `this` binding and arguments of the created function.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var initialize = _.once(createApplication);
* initialize();
* initialize();
* // => `createApplication` is invoked once
*/
function once(func) {
return before(2, func);
}
/**
* Creates a function that invokes `func` with its arguments transformed.
*
* @static
* @since 4.0.0
* @memberOf _
* @category Function
* @param {Function} func The function to wrap.
* @param {...(Function|Function[])} [transforms=[_.identity]]
* The argument transforms.
* @returns {Function} Returns the new function.
* @example
*
* function doubled(n) {
* return n * 2;
* }
*
* function square(n) {
* return n * n;
* }
*
* var func = _.overArgs(function(x, y) {
* return [x, y];
* }, [square, doubled]);
*
* func(9, 3);
* // => [81, 6]
*
* func(10, 5);
* // => [100, 10]
*/
var overArgs = castRest(function(func, transforms) {
transforms = (transforms.length == 1 && isArray(transforms[0]))
? arrayMap(transforms[0], baseUnary(getIteratee()))
: arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee()));
var funcsLength = transforms.length;
return baseRest(function(args) {
var index = -1,
length = nativeMin(args.length, funcsLength);
while (++index < length) {
args[index] = transforms[index].call(this, args[index]);
}
return apply(func, this, args);
});
});
/**
* 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);
});
/**
* This method is like `_.partial` except that partially applied arguments
* are appended to the arguments it receives.
*
* The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method doesn't set the "length" property of partially
* applied functions.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* function greet(greeting, name) {
* return greeting + ' ' + name;
* }
*
* var greetFred = _.partialRight(greet, 'fred');
* greetFred('hi');
* // => 'hi fred'
*
* // Partially applied with placeholders.
* var sayHelloTo = _.partialRight(greet, 'hello', _);
* sayHelloTo('fred');
* // => 'hello fred'
*/
var partialRight = baseRest(function(func, partials) {
var holders = replaceHolders(partials, getHolder(partialRight));
return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders);
});
/**
* Creates a function that invokes `func` with arguments arranged according
* to the specified `indexes` where the argument value at the first index is
* provided as the first argument, the argument value at the second index is
* provided as the second argument, and so on.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} func The function to rearrange arguments for.
* @param {...(number|number[])} indexes The arranged argument indexes.
* @returns {Function} Returns the new function.
* @example
*
* var rearged = _.rearg(function(a, b, c) {
* return [a, b, c];
* }, [2, 0, 1]);
*
* rearged('b', 'c', 'a')
* // => ['a', 'b', 'c']
*/
var rearg = flatRest(function(func, indexes) {
return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes);
});
/**
* Creates a function that invokes `func` with the `this` binding of the
* created function and arguments from `start` and beyond provided as
* an array.
*
* **Note:** This method is based on the
* [rest parameter](https://mdn.io/rest_parameters).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Function
* @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.
* @example
*
* var say = _.rest(function(what, names) {
* return what + ' ' + _.initial(names).join(', ') +
* (_.size(names) > 1 ? ', & ' : '') + _.last(names);
* });
*
* say('hello', 'fred', 'barney', 'pebbles');
* // => 'hello fred, barney, & pebbles'
*/
function rest(func, start) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
start = start === undefined ? start : toInteger(start);
return baseRest(func, start);
}
/**
* Creates a function that invokes `func` with the `this` binding of the
* create function and an array of arguments much like
* [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply).
*
* **Note:** This method is based on the
* [spread operator](https://mdn.io/spread_operator).
*
* @static
* @memberOf _
* @since 3.2.0
* @category Function
* @param {Function} func The function to spread arguments over.
* @param {number} [start=0] The start position of the spread.
* @returns {Function} Returns the new function.
* @example
*
* var say = _.spread(function(who, what) {
* return who + ' says ' + what;
* });
*
* say(['fred', 'hello']);
* // => 'fred says hello'
*
* var numbers = Promise.all([
* Promise.resolve(40),
* Promise.resolve(36)
* ]);
*
* numbers.then(_.spread(function(x, y) {
* return x + y;
* }));
* // => a Promise of 76
*/
function spread(func, start) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
start = start == null ? 0 : nativeMax(toInteger(start), 0);
return baseRest(function(args) {
var array = args[start],
otherArgs = castSlice(args, 0, start);
if (array) {
arrayPush(otherArgs, array);
}
return apply(func, this, otherArgs);
});
}
/**
* Creates a throttled function that only invokes `func` at most once per
* every `wait` milliseconds. The throttled function comes with a `cancel`
* method to cancel delayed `func` invocations and a `flush` method to
* immediately invoke them. Provide `options` to indicate whether `func`
* should be invoked on the leading and/or trailing edge of the `wait`
* timeout. The `func` is invoked with the last arguments provided to the
* throttled function. Subsequent calls to the throttled function return the
* result of the last `func` invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the throttled function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.throttle` and `_.debounce`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to throttle.
* @param {number} [wait=0] The number of milliseconds to throttle invocations to.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=true]
* Specify invoking on the leading edge of the timeout.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new throttled function.
* @example
*
* // Avoid excessively updating the position while scrolling.
* jQuery(window).on('scroll', _.throttle(updatePosition, 100));
*
* // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
* var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
* jQuery(element).on('click', throttled);
*
* // Cancel the trailing throttled invocation.
* jQuery(window).on('popstate', throttled.cancel);
*/
function throttle(func, wait, options) {
var leading = true,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
if (isObject(options)) {
leading = 'leading' in options ? !!options.leading : leading;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
return debounce(func, wait, {
'leading': leading,
'maxWait': wait,
'trailing': trailing
});
}
/**
* Creates a function that accepts up to one argument, ignoring any
* additional arguments.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Function
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
* @example
*
* _.map(['6', '8', '10'], _.unary(parseInt));
* // => [6, 8, 10]
*/
function unary(func) {
return ary(func, 1);
}
/**
* Creates a function that provides `value` to `wrapper` as its first
* argument. Any additional arguments provided to the function are appended
* to those provided to the `wrapper`. The wrapper is invoked with the `this`
* binding of the created function.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {*} value The value to wrap.
* @param {Function} [wrapper=identity] The wrapper function.
* @returns {Function} Returns the new function.
* @example
*
* var p = _.wrap(_.escape, function(func, text) {
* return '<p>' + func(text) + '</p>';
* });
*
* p('fred, barney, & pebbles');
* // => '<p>fred, barney, & pebbles</p>'
*/
function wrap(value, wrapper) {
return partial(castFunction(wrapper), value);
}
/*------------------------------------------------------------------------*/
/**
* Casts `value` as an array if it's not one.
*
* @static
* @memberOf _
* @since 4.4.0
* @category Lang
* @param {*} value The value to inspect.
* @returns {Array} Returns the cast array.
* @example
*
* _.castArray(1);
* // => [1]
*
* _.castArray({ 'a': 1 });
* // => [{ 'a': 1 }]
*
* _.castArray('abc');
* // => ['abc']
*
* _.castArray(null);
* // => [null]
*
* _.castArray(undefined);
* // => [undefined]
*
* _.castArray();
* // => []
*
* var array = [1, 2, 3];
* console.log(_.castArray(array) === array);
* // => true
*/
function castArray() {
if (!arguments.length) {
return [];
}
var value = arguments[0];
return isArray(value) ? value : [value];
}
/**
* Creates a shallow clone of `value`.
*
* **Note:** This method is loosely based on the
* [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
* and supports cloning arrays, array buffers, booleans, date objects, maps,
* numbers, `Object` objects, regexes, sets, strings, symbols, and typed
* arrays. The own enumerable properties of `arguments` objects are cloned
* as plain objects. An empty object is returned for uncloneable values such
* as error objects, functions, DOM nodes, and WeakMaps.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to clone.
* @returns {*} Returns the cloned value.
* @see _.cloneDeep
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var shallow = _.clone(objects);
* console.log(shallow[0] === objects[0]);
* // => true
*/
function clone(value) {
return baseClone(value, CLONE_SYMBOLS_FLAG);
}
/**
* This method is like `_.clone` except that it accepts `customizer` which
* is invoked to produce the cloned value. If `customizer` returns `undefined`,
* cloning is handled by the method instead. The `customizer` is invoked with
* up to four arguments; (value [, index|key, object, stack]).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to clone.
* @param {Function} [customizer] The function to customize cloning.
* @returns {*} Returns the cloned value.
* @see _.cloneDeepWith
* @example
*
* function customizer(value) {
* if (_.isElement(value)) {
* return value.cloneNode(false);
* }
* }
*
* var el = _.cloneWith(document.body, customizer);
*
* console.log(el === document.body);
* // => false
* console.log(el.nodeName);
* // => 'BODY'
* console.log(el.childNodes.length);
* // => 0
*/
function cloneWith(value, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return baseClone(value, CLONE_SYMBOLS_FLAG, customizer);
}
/**
* This method is like `_.clone` except that it recursively clones `value`.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Lang
* @param {*} value The value to recursively clone.
* @returns {*} Returns the deep cloned value.
* @see _.clone
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var deep = _.cloneDeep(objects);
* console.log(deep[0] === objects[0]);
* // => false
*/
function cloneDeep(value) {
return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);
}
/**
* This method is like `_.cloneWith` except that it recursively clones `value`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to recursively clone.
* @param {Function} [customizer] The function to customize cloning.
* @returns {*} Returns the deep cloned value.
* @see _.cloneWith
* @example
*
* function customizer(value) {
* if (_.isElement(value)) {
* return value.cloneNode(true);
* }
* }
*
* var el = _.cloneDeepWith(document.body, customizer);
*
* console.log(el === document.body);
* // => false
* console.log(el.nodeName);
* // => 'BODY'
* console.log(el.childNodes.length);
* // => 20
*/
function cloneDeepWith(value, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer);
}
/**
* Checks if `object` conforms to `source` by invoking the predicate
* properties of `source` with the corresponding property values of `object`.
*
* **Note:** This method is equivalent to `_.conforms` when `source` is
* partially applied.
*
* @static
* @memberOf _
* @since 4.14.0
* @category Lang
* @param {Object} object The object to inspect.
* @param {Object} source The object of property predicates to conform to.
* @returns {boolean} Returns `true` if `object` conforms, else `false`.
* @example
*
* var object = { 'a': 1, 'b': 2 };
*
* _.conformsTo(object, { 'b': function(n) { return n > 1; } });
* // => true
*
* _.conformsTo(object, { 'b': function(n) { return n > 2; } });
* // => false
*/
function conformsTo(object, source) {
return source == null || baseConformsTo(object, source, keys(source));
}
/**
* 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);
}
/**
* Checks if `value` is greater than `other`.
*
* @static
* @memberOf _
* @since 3.9.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is greater than `other`,
* else `false`.
* @see _.lt
* @example
*
* _.gt(3, 1);
* // => true
*
* _.gt(3, 3);
* // => false
*
* _.gt(1, 3);
* // => false
*/
var gt = createRelationalOperation(baseGt);
/**
* Checks if `value` is greater than or equal to `other`.
*
* @static
* @memberOf _
* @since 3.9.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is greater than or equal to
* `other`, else `false`.
* @see _.lte
* @example
*
* _.gte(3, 1);
* // => true
*
* _.gte(3, 3);
* // => true
*
* _.gte(1, 3);
* // => false
*/
var gte = createRelationalOperation(function(value, other) {
return value >= other;
});
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
!propertyIsEnumerable.call(value, 'callee');
};
/**
* 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;
/**
* Checks if `value` is classified as an `ArrayBuffer` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
* @example
*
* _.isArrayBuffer(new ArrayBuffer(2));
* // => true
*
* _.isArrayBuffer(new Array(2));
* // => false
*/
var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer;
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return isObjectLike(value) && isArrayLike(value);
}
/**
* Checks if `value` is classified as a boolean primitive or object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a boolean, else `false`.
* @example
*
* _.isBoolean(false);
* // => true
*
* _.isBoolean(null);
* // => false
*/
function isBoolean(value) {
return value === true || value === false ||
(isObjectLike(value) && baseGetTag(value) == boolTag);
}
/**
* 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;
/**
* Checks if `value` is classified as a `Date` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a date object, else `false`.
* @example
*
* _.isDate(new Date);
* // => true
*
* _.isDate('Mon April 23 2012');
* // => false
*/
var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate;
/**
* Checks if `value` is likely a DOM element.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
* @example
*
* _.isElement(document.body);
* // => true
*
* _.isElement('<body>');
* // => false
*/
function isElement(value) {
return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value);
}
/**
* Checks if `value` is an empty object, collection, map, or set.
*
* Objects are considered empty if they have no own enumerable string keyed
* properties.
*
* Array-like values such as `arguments` objects, arrays, buffers, strings, or
* jQuery-like collections are considered empty if they have a `length` of `0`.
* Similarly, maps and sets are considered empty if they have a `size` of `0`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is empty, else `false`.
* @example
*
* _.isEmpty(null);
* // => true
*
* _.isEmpty(true);
* // => true
*
* _.isEmpty(1);
* // => true
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({ 'a': 1 });
* // => false
*/
function isEmpty(value) {
if (value == null) {
return true;
}
if (isArrayLike(value) &&
(isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||
isBuffer(value) || isTypedArray(value) || isArguments(value))) {
return !value.length;
}
var tag = getTag(value);
if (tag == mapTag || tag == setTag) {
return !value.size;
}
if (isPrototype(value)) {
return !baseKeys(value).length;
}
for (var key in value) {
if (hasOwnProperty.call(value, key)) {
return false;
}
}
return true;
}
/**
* 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);
}
/**
* This method is like `_.isEqual` except that it accepts `customizer` which
* is invoked to compare values. If `customizer` returns `undefined`, comparisons
* are handled by the method instead. The `customizer` is invoked with up to
* six arguments: (objValue, othValue [, index|key, object, other, stack]).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* function isGreeting(value) {
* return /^h(?:i|ello)$/.test(value);
* }
*
* function customizer(objValue, othValue) {
* if (isGreeting(objValue) && isGreeting(othValue)) {
* return true;
* }
* }
*
* var array = ['hello', 'goodbye'];
* var other = ['hi', 'goodbye'];
*
* _.isEqualWith(array, other, customizer);
* // => true
*/
function isEqualWith(value, other, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
var result = customizer ? customizer(value, other) : undefined;
return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result;
}
/**
* Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
* `SyntaxError`, `TypeError`, or `URIError` object.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an error object, else `false`.
* @example
*
* _.isError(new Error);
* // => true
*
* _.isError(Error);
* // => false
*/
function isError(value) {
if (!isObjectLike(value)) {
return false;
}
var tag = baseGetTag(value);
return tag == errorTag || tag == domExcTag ||
(typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value));
}
/**
* Checks if `value` is a finite primitive number.
*
* **Note:** This method is based on
* [`Number.isFinite`](https://mdn.io/Number/isFinite).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
* @example
*
* _.isFinite(3);
* // => true
*
* _.isFinite(Number.MIN_VALUE);
* // => true
*
* _.isFinite(Infinity);
* // => false
*
* _.isFinite('3');
* // => false
*/
function isFinite(value) {
return typeof value == 'number' && nativeIsFinite(value);
}
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
if (!isObject(value)) {
return false;
}
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag = baseGetTag(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
/**
* Checks if `value` is an integer.
*
* **Note:** This method is based on
* [`Number.isInteger`](https://mdn.io/Number/isInteger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an integer, else `false`.
* @example
*
* _.isInteger(3);
* // => true
*
* _.isInteger(Number.MIN_VALUE);
* // => false
*
* _.isInteger(Infinity);
* // => false
*
* _.isInteger('3');
* // => false
*/
function isInteger(value) {
return typeof value == 'number' && value == toInteger(value);
}
/**
* 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;
}
/**
* 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');
}
/**
* 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';
}
/**
* Checks if `value` is classified as a `Map` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
* @example
*
* _.isMap(new Map);
* // => true
*
* _.isMap(new WeakMap);
* // => false
*/
var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;
/**
* Performs a partial deep comparison between `object` and `source` to
* determine if `object` contains equivalent property values.
*
* **Note:** This method is equivalent to `_.matches` when `source` is
* partially applied.
*
* Partial comparisons will match empty array and empty object `source`
* values against any array or object value, respectively. See `_.isEqual`
* for a list of supported value comparisons.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
* @example
*
* var object = { 'a': 1, 'b': 2 };
*
* _.isMatch(object, { 'b': 2 });
* // => true
*
* _.isMatch(object, { 'b': 1 });
* // => false
*/
function isMatch(object, source) {
return object === source || baseIsMatch(object, source, getMatchData(source));
}
/**
* This method is like `_.isMatch` except that it accepts `customizer` which
* is invoked to compare values. If `customizer` returns `undefined`, comparisons
* are handled by the method instead. The `customizer` is invoked with five
* arguments: (objValue, srcValue, index|key, object, source).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
* @example
*
* function isGreeting(value) {
* return /^h(?:i|ello)$/.test(value);
* }
*
* function customizer(objValue, srcValue) {
* if (isGreeting(objValue) && isGreeting(srcValue)) {
* return true;
* }
* }
*
* var object = { 'greeting': 'hello' };
* var source = { 'greeting': 'hi' };
*
* _.isMatchWith(object, source, customizer);
* // => true
*/
function isMatchWith(object, source, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return baseIsMatch(object, source, getMatchData(source), customizer);
}
/**
* Checks if `value` is `NaN`.
*
* **Note:** This method is based on
* [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
* global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
* `undefined` and other non-number values.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
* @example
*
* _.isNaN(NaN);
* // => true
*
* _.isNaN(new Number(NaN));
* // => true
*
* isNaN(undefined);
* // => true
*
* _.isNaN(undefined);
* // => false
*/
function isNaN(value) {
// An `NaN` primitive is the only value that is not equal to itself.
// Perform the `toStringTag` check first to avoid errors with some
// ActiveX objects in IE.
return isNumber(value) && value != +value;
}
/**
* Checks if `value` is a pristine native function.
*
* **Note:** This method can't reliably detect native functions in the presence
* of the core-js package because core-js circumvents this kind of detection.
* Despite multiple requests, the core-js maintainer has made it clear: any
* attempt to fix the detection will be obstructed. As a result, we're left
* with little choice but to throw an error. Unfortunately, this also affects
* packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill),
* which rely on core-js.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => false
*/
function isNative(value) {
if (isMaskable(value)) {
throw new Error(CORE_ERROR_TEXT);
}
return baseIsNative(value);
}
/**
* Checks if `value` is `null`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `null`, else `false`.
* @example
*
* _.isNull(null);
* // => true
*
* _.isNull(void 0);
* // => false
*/
function isNull(value) {
return value === null;
}
/**
* Checks if `value` is `null` or `undefined`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is nullish, else `false`.
* @example
*
* _.isNil(null);
* // => true
*
* _.isNil(void 0);
* // => true
*
* _.isNil(NaN);
* // => false
*/
function isNil(value) {
return value == null;
}
/**
* Checks if `value` is classified as a `Number` primitive or object.
*
* **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
* classified as numbers, use the `_.isFinite` method.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a number, else `false`.
* @example
*
* _.isNumber(3);
* // => true
*
* _.isNumber(Number.MIN_VALUE);
* // => true
*
* _.isNumber(Infinity);
* // => true
*
* _.isNumber('3');
* // => false
*/
function isNumber(value) {
return typeof value == 'number' ||
(isObjectLike(value) && baseGetTag(value) == numberTag);
}
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @static
* @memberOf _
* @since 0.8.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
return false;
}
var proto = getPrototype(value);
if (proto === null) {
return true;
}
var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
return typeof Ctor == 'function' && Ctor instanceof Ctor &&
funcToString.call(Ctor) == objectCtorString;
}
/**
* Checks if `value` is classified as a `RegExp` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
* @example
*
* _.isRegExp(/abc/);
* // => true
*
* _.isRegExp('/abc/');
* // => false
*/
var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp;
/**
* Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754
* double precision number which isn't the result of a rounded unsafe integer.
*
* **Note:** This method is based on
* [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a safe integer, else `false`.
* @example
*
* _.isSafeInteger(3);
* // => true
*
* _.isSafeInteger(Number.MIN_VALUE);
* // => false
*
* _.isSafeInteger(Infinity);
* // => false
*
* _.isSafeInteger('3');
* // => false
*/
function isSafeInteger(value) {
return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is classified as a `Set` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
* @example
*
* _.isSet(new Set);
* // => true
*
* _.isSet(new WeakSet);
* // => false
*/
var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a string, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' ||
(!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);
}
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && baseGetTag(value) == symbolTag);
}
/**
* 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;
/**
* 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;
}
/**
* Checks if `value` is classified as a `WeakMap` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a weak map, else `false`.
* @example
*
* _.isWeakMap(new WeakMap);
* // => true
*
* _.isWeakMap(new Map);
* // => false
*/
function isWeakMap(value) {
return isObjectLike(value) && getTag(value) == weakMapTag;
}
/**
* Checks if `value` is classified as a `WeakSet` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a weak set, else `false`.
* @example
*
* _.isWeakSet(new WeakSet);
* // => true
*
* _.isWeakSet(new Set);
* // => false
*/
function isWeakSet(value) {
return isObjectLike(value) && baseGetTag(value) == weakSetTag;
}
/**
* Checks if `value` is less than `other`.
*
* @static
* @memberOf _
* @since 3.9.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is less than `other`,
* else `false`.
* @see _.gt
* @example
*
* _.lt(1, 3);
* // => true
*
* _.lt(3, 3);
* // => false
*
* _.lt(3, 1);
* // => false
*/
var lt = createRelationalOperation(baseLt);
/**
* Checks if `value` is less than or equal to `other`.
*
* @static
* @memberOf _
* @since 3.9.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is less than or equal to
* `other`, else `false`.
* @see _.gte
* @example
*
* _.lte(1, 3);
* // => true
*
* _.lte(3, 3);
* // => true
*
* _.lte(3, 1);
* // => false
*/
var lte = createRelationalOperation(function(value, other) {
return value <= other;
});
/**
* Converts `value` to an array.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to convert.
* @returns {Array} Returns the converted array.
* @example
*
* _.toArray({ 'a': 1, 'b': 2 });
* // => [1, 2]
*
* _.toArray('abc');
* // => ['a', 'b', 'c']
*
* _.toArray(1);
* // => []
*
* _.toArray(null);
* // => []
*/
function toArray(value) {
if (!value) {
return [];
}
if (isArrayLike(value)) {
return isString(value) ? stringToArray(value) : copyArray(value);
}
if (symIterator && value[symIterator]) {
return iteratorToArray(value[symIterator]());
}
var tag = getTag(value),
func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values);
return func(value);
}
/**
* Converts `value` to a finite number.
*
* @static
* @memberOf _
* @since 4.12.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted number.
* @example
*
* _.toFinite(3.2);
* // => 3.2
*
* _.toFinite(Number.MIN_VALUE);
* // => 5e-324
*
* _.toFinite(Infinity);
* // => 1.7976931348623157e+308
*
* _.toFinite('3.2');
* // => 3.2
*/
function toFinite(value) {
if (!value) {
return value === 0 ? value : 0;
}
value = toNumber(value);
if (value === INFINITY || value === -INFINITY) {
var sign = (value < 0 ? -1 : 1);
return sign * MAX_INTEGER;
}
return value === value ? value : 0;
}
/**
* Converts `value` to an integer.
*
* **Note:** This method is loosely based on
* [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toInteger(3.2);
* // => 3
*
* _.toInteger(Number.MIN_VALUE);
* // => 0
*
* _.toInteger(Infinity);
* // => 1.7976931348623157e+308
*
* _.toInteger('3.2');
* // => 3
*/
function toInteger(value) {
var result = toFinite(value),
remainder = result % 1;
return result === result ? (remainder ? result - remainder : result) : 0;
}
/**
* Converts `value` to an integer suitable for use as the length of an
* array-like object.
*
* **Note:** This method is based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toLength(3.2);
* // => 3
*
* _.toLength(Number.MIN_VALUE);
* // => 0
*
* _.toLength(Infinity);
* // => 4294967295
*
* _.toLength('3.2');
* // => 3
*/
function toLength(value) {
return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;
}
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
if (isObject(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = baseTrim(value);
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
/**
* Converts `value` to a plain object flattening inherited enumerable string
* keyed properties of `value` to own properties of the plain object.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {Object} Returns the converted plain object.
* @example
*
* function Foo() {
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.assign({ 'a': 1 }, new Foo);
* // => { 'a': 1, 'b': 2 }
*
* _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
* // => { 'a': 1, 'b': 2, 'c': 3 }
*/
function toPlainObject(value) {
return copyObject(value, keysIn(value));
}
/**
* Converts `value` to a safe integer. A safe integer can be compared and
* represented correctly.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toSafeInteger(3.2);
* // => 3
*
* _.toSafeInteger(Number.MIN_VALUE);
* // => 0
*
* _.toSafeInteger(Infinity);
* // => 9007199254740991
*
* _.toSafeInteger('3.2');
* // => 3
*/
function toSafeInteger(value) {
return value
? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER)
: (value === 0 ? value : 0);
}
/**
* 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);
}
/*------------------------------------------------------------------------*/
/**
* Assigns own enumerable string keyed properties of source objects to the
* destination object. Source objects are applied from left to right.
* Subsequent sources overwrite property assignments of previous sources.
*
* **Note:** This method mutates `object` and is loosely based on
* [`Object.assign`](https://mdn.io/Object/assign).
*
* @static
* @memberOf _
* @since 0.10.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.assignIn
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* function Bar() {
* this.c = 3;
* }
*
* Foo.prototype.b = 2;
* Bar.prototype.d = 4;
*
* _.assign({ 'a': 0 }, new Foo, new Bar);
* // => { 'a': 1, 'c': 3 }
*/
var assign = createAssigner(function(object, source) {
if (isPrototype(source) || isArrayLike(source)) {
copyObject(source, keys(source), object);
return;
}
for (var key in source) {
if (hasOwnProperty.call(source, key)) {
assignValue(object, key, source[key]);
}
}
});
/**
* This method is like `_.assign` except that it iterates over own and
* inherited source properties.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias extend
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.assign
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* function Bar() {
* this.c = 3;
* }
*
* Foo.prototype.b = 2;
* Bar.prototype.d = 4;
*
* _.assignIn({ 'a': 0 }, new Foo, new Bar);
* // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
*/
var assignIn = createAssigner(function(object, source) {
copyObject(source, keysIn(source), object);
});
/**
* This method is like `_.assignIn` except that it accepts `customizer`
* which is invoked to produce the assigned values. If `customizer` returns
* `undefined`, assignment is handled by the method instead. The `customizer`
* is invoked with five arguments: (objValue, srcValue, key, object, source).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias extendWith
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @see _.assignWith
* @example
*
* function customizer(objValue, srcValue) {
* return _.isUndefined(objValue) ? srcValue : objValue;
* }
*
* var defaults = _.partialRight(_.assignInWith, customizer);
*
* defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {
copyObject(source, keysIn(source), object, customizer);
});
/**
* This method is like `_.assign` 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
* @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 _.assignInWith
* @example
*
* function customizer(objValue, srcValue) {
* return _.isUndefined(objValue) ? srcValue : objValue;
* }
*
* var defaults = _.partialRight(_.assignWith, customizer);
*
* defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var assignWith = createAssigner(function(object, source, srcIndex, customizer) {
copyObject(source, keys(source), object, customizer);
});
/**
* Creates an array of values corresponding to `paths` of `object`.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {...(string|string[])} [paths] The property paths to pick.
* @returns {Array} Returns the picked values.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
*
* _.at(object, ['a[0].b.c', 'a[1]']);
* // => [3, 4]
*/
var at = flatRest(baseAt);
/**
* Creates an object that inherits from the `prototype` object. If a
* `properties` object is given, its own enumerable string keyed properties
* are assigned to the created object.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Object
* @param {Object} prototype The object to inherit from.
* @param {Object} [properties] The properties to assign to the object.
* @returns {Object} Returns the new object.
* @example
*
* function Shape() {
* this.x = 0;
* this.y = 0;
* }
*
* function Circle() {
* Shape.call(this);
* }
*
* Circle.prototype = _.create(Shape.prototype, {
* 'constructor': Circle
* });
*
* var circle = new Circle;
* circle instanceof Circle;
* // => true
*
* circle instanceof Shape;
* // => true
*/
function create(prototype, properties) {
var result = baseCreate(prototype);
return properties == null ? result : baseAssign(result, properties);
}
/**
* Assigns own and inherited enumerable string keyed properties of source
* objects to the destination object for all destination properties that
* resolve to `undefined`. Source objects are applied from left to right.
* Once a property is set, additional values of the same property are ignored.
*
* **Note:** This method mutates `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.defaultsDeep
* @example
*
* _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var defaults = baseRest(function(object, sources) {
object = Object(object);
var index = -1;
var length = sources.length;
var guard = length > 2 ? sources[2] : undefined;
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
length = 1;
}
while (++index < length) {
var source = sources[index];
var props = keysIn(source);
var propsIndex = -1;
var propsLength = props.length;
while (++propsIndex < propsLength) {
var key = props[propsIndex];
var value = object[key];
if (value === undefined ||
(eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) {
object[key] = source[key];
}
}
}
return object;
});
/**
* This method is like `_.defaults` except that it recursively assigns
* default properties.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 3.10.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.defaults
* @example
*
* _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });
* // => { 'a': { 'b': 2, 'c': 3 } }
*/
var defaultsDeep = baseRest(function(args) {
args.push(undefined, customDefaultsMerge);
return apply(mergeWith, undefined, args);
});
/**
* This method is like `_.find` except that it returns the key of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Object
* @param {Object} object The object to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {string|undefined} Returns the key of the matched element,
* else `undefined`.
* @example
*
* var users = {
* 'barney': { 'age': 36, 'active': true },
* 'fred': { 'age': 40, 'active': false },
* 'pebbles': { 'age': 1, 'active': true }
* };
*
* _.findKey(users, function(o) { return o.age < 40; });
* // => 'barney' (iteration order is not guaranteed)
*
* // The `_.matches` iteratee shorthand.
* _.findKey(users, { 'age': 1, 'active': true });
* // => 'pebbles'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findKey(users, ['active', false]);
* // => 'fred'
*
* // The `_.property` iteratee shorthand.
* _.findKey(users, 'active');
* // => 'barney'
*/
function findKey(object, predicate) {
return baseFindKey(object, getIteratee(predicate, 3), baseForOwn);
}
/**
* This method is like `_.findKey` except that it iterates over elements of
* a collection in the opposite order.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Object
* @param {Object} object The object to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {string|undefined} Returns the key of the matched element,
* else `undefined`.
* @example
*
* var users = {
* 'barney': { 'age': 36, 'active': true },
* 'fred': { 'age': 40, 'active': false },
* 'pebbles': { 'age': 1, 'active': true }
* };
*
* _.findLastKey(users, function(o) { return o.age < 40; });
* // => returns 'pebbles' assuming `_.findKey` returns 'barney'
*
* // The `_.matches` iteratee shorthand.
* _.findLastKey(users, { 'age': 36, 'active': true });
* // => 'barney'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findLastKey(users, ['active', false]);
* // => 'fred'
*
* // The `_.property` iteratee shorthand.
* _.findLastKey(users, 'active');
* // => 'pebbles'
*/
function findLastKey(object, predicate) {
return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight);
}
/**
* Iterates over own and inherited 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 _.forInRight
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forIn(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).
*/
function forIn(object, iteratee) {
return object == null
? object
: baseFor(object, getIteratee(iteratee, 3), keysIn);
}
/**
* This method is like `_.forIn` except that it iterates over properties of
* `object` in the opposite order.
*
* @static
* @memberOf _
* @since 2.0.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 _.forIn
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forInRight(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.
*/
function forInRight(object, iteratee) {
return object == null
? object
: baseForRight(object, getIteratee(iteratee, 3), keysIn);
}
/**
* 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, getIteratee(iteratee, 3));
}
/**
* This method is like `_.forOwn` except that it iterates over properties of
* `object` in the opposite order.
*
* @static
* @memberOf _
* @since 2.0.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 _.forOwn
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forOwnRight(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.
*/
function forOwnRight(object, iteratee) {
return object && baseForOwnRight(object, getIteratee(iteratee, 3));
}
/**
* Creates an array of function property names from own enumerable properties
* of `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to inspect.
* @returns {Array} Returns the function names.
* @see _.functionsIn
* @example
*
* function Foo() {
* this.a = _.constant('a');
* this.b = _.constant('b');
* }
*
* Foo.prototype.c = _.constant('c');
*
* _.functions(new Foo);
* // => ['a', 'b']
*/
function functions(object) {
return object == null ? [] : baseFunctions(object, keys(object));
}
/**
* Creates an array of function property names from own and inherited
* enumerable properties of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to inspect.
* @returns {Array} Returns the function names.
* @see _.functions
* @example
*
* function Foo() {
* this.a = _.constant('a');
* this.b = _.constant('b');
* }
*
* Foo.prototype.c = _.constant('c');
*
* _.functionsIn(new Foo);
* // => ['a', 'b', 'c']
*/
function functionsIn(object) {
return object == null ? [] : baseFunctions(object, keysIn(object));
}
/**
* 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;
}
/**
* Checks if `path` is a direct property of `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = { 'a': { 'b': 2 } };
* var other = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.has(object, 'a');
* // => true
*
* _.has(object, 'a.b');
* // => true
*
* _.has(object, ['a', 'b']);
* // => true
*
* _.has(other, 'a');
* // => false
*/
function has(object, path) {
return object != null && hasPath(object, path, baseHas);
}
/**
* 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);
}
/**
* Creates an object composed of the inverted keys and values of `object`.
* If `object` contains duplicate values, subsequent values overwrite
* property assignments of previous values.
*
* @static
* @memberOf _
* @since 0.7.0
* @category Object
* @param {Object} object The object to invert.
* @returns {Object} Returns the new inverted object.
* @example
*
* var object = { 'a': 1, 'b': 2, 'c': 1 };
*
* _.invert(object);
* // => { '1': 'c', '2': 'b' }
*/
var invert = createInverter(function(result, value, key) {
if (value != null &&
typeof value.toString != 'function') {
value = nativeObjectToString.call(value);
}
result[value] = key;
}, constant(identity));
/**
* This method is like `_.invert` except that the inverted object is generated
* from the results of running each element of `object` thru `iteratee`. The
* corresponding inverted value of each inverted key is an array of keys
* responsible for generating the inverted value. The iteratee is invoked
* with one argument: (value).
*
* @static
* @memberOf _
* @since 4.1.0
* @category Object
* @param {Object} object The object to invert.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Object} Returns the new inverted object.
* @example
*
* var object = { 'a': 1, 'b': 2, 'c': 1 };
*
* _.invertBy(object);
* // => { '1': ['a', 'c'], '2': ['b'] }
*
* _.invertBy(object, function(value) {
* return 'group' + value;
* });
* // => { 'group1': ['a', 'c'], 'group2': ['b'] }
*/
var invertBy = createInverter(function(result, value, key) {
if (value != null &&
typeof value.toString != 'function') {
value = nativeObjectToString.call(value);
}
if (hasOwnProperty.call(result, value)) {
result[value].push(key);
} else {
result[value] = [key];
}
}, getIteratee);
/**
* Invokes the method at `path` of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the method to invoke.
* @param {...*} [args] The arguments to invoke the method with.
* @returns {*} Returns the result of the invoked method.
* @example
*
* var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };
*
* _.invoke(object, 'a[0].b.c.slice', 1, 3);
* // => [2, 3]
*/
var invoke = baseRest(baseInvoke);
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn(object) {
return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
}
/**
* 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 = getIteratee(iteratee, 3);
baseForOwn(object, function(value, key, object) {
baseAssignValue(result, iteratee(value, key, object), value);
});
return result;
}
/**
* 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 = getIteratee(iteratee, 3);
baseForOwn(object, function(value, key, object) {
baseAssignValue(result, key, iteratee(value, key, object));
});
return result;
}
/**
* 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);
});
/**
* This method is like `_.merge` except that it accepts `customizer` which
* is invoked to produce the merged values of the destination and source
* properties. If `customizer` returns `undefined`, merging is handled by the
* method instead. The `customizer` is invoked with six arguments:
* (objValue, srcValue, key, object, source, stack).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @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`.
* @example
*
* function customizer(objValue, srcValue) {
* if (_.isArray(objValue)) {
* return objValue.concat(srcValue);
* }
* }
*
* var object = { 'a': [1], 'b': [2] };
* var other = { 'a': [3], 'b': [4] };
*
* _.mergeWith(object, other, customizer);
* // => { 'a': [1, 3], 'b': [2, 4] }
*/
var mergeWith = createAssigner(function(object, source, srcIndex, customizer) {
baseMerge(object, source, srcIndex, customizer);
});
/**
* 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;
});
/**
* The opposite of `_.pickBy`; this method creates an object composed of
* the own and inherited enumerable string keyed properties of `object` that
* `predicate` doesn't return 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 };
*
* _.omitBy(object, _.isNumber);
* // => { 'b': '2' }
*/
function omitBy(object, predicate) {
return pickBy(object, negate(getIteratee(predicate)));
}
/**
* 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);
});
/**
* 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 = getIteratee(predicate);
return basePickBy(object, props, function(value, path) {
return predicate(value, path[0]);
});
}
/**
* This method is like `_.get` except that if the resolved value is a
* function it's invoked with the `this` binding of its parent object and
* its result is returned.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to resolve.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
*
* _.result(object, 'a[0].b.c1');
* // => 3
*
* _.result(object, 'a[0].b.c2');
* // => 4
*
* _.result(object, 'a[0].b.c3', 'default');
* // => 'default'
*
* _.result(object, 'a[0].b.c3', _.constant('default'));
* // => 'default'
*/
function result(object, path, defaultValue) {
path = castPath(path, object);
var index = -1,
length = path.length;
// Ensure the loop is entered when path is empty.
if (!length) {
length = 1;
object = undefined;
}
while (++index < length) {
var value = object == null ? undefined : object[toKey(path[index])];
if (value === undefined) {
index = length;
value = defaultValue;
}
object = isFunction(value) ? value.call(object) : value;
}
return object;
}
/**
* Sets the value at `path` of `object`. If a portion of `path` doesn't exist,
* it's created. Arrays are created for missing index properties while objects
* are created for all other missing properties. Use `_.setWith` to customize
* `path` creation.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @returns {Object} Returns `object`.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.set(object, 'a[0].b.c', 4);
* console.log(object.a[0].b.c);
* // => 4
*
* _.set(object, ['x', '0', 'y', 'z'], 5);
* console.log(object.x[0].y.z);
* // => 5
*/
function set(object, path, value) {
return object == null ? object : baseSet(object, path, value);
}
/**
* This method is like `_.set` except that it accepts `customizer` which is
* invoked to produce the objects of `path`. If `customizer` returns `undefined`
* path creation is handled by the method instead. The `customizer` is invoked
* with three arguments: (nsValue, key, nsObject).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @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 assigned values.
* @returns {Object} Returns `object`.
* @example
*
* var object = {};
*
* _.setWith(object, '[0][1]', 'a', Object);
* // => { '0': { '1': 'a' } }
*/
function setWith(object, path, value, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return object == null ? object : baseSet(object, path, value, customizer);
}
/**
* Creates an array of own enumerable string keyed-value pairs for `object`
* which can be consumed by `_.fromPairs`. If `object` is a map or set, its
* entries are returned.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias entries
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the key-value pairs.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.toPairs(new Foo);
* // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)
*/
var toPairs = createToPairs(keys);
/**
* Creates an array of own and inherited enumerable string keyed-value pairs
* for `object` which can be consumed by `_.fromPairs`. If `object` is a map
* or set, its entries are returned.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias entriesIn
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the key-value pairs.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.toPairsIn(new Foo);
* // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed)
*/
var toPairsIn = createToPairs(keysIn);
/**
* An alternative to `_.reduce`; this method transforms `object` to a new
* `accumulator` object which is the result of running each of its own
* enumerable string keyed properties thru `iteratee`, with each invocation
* potentially mutating the `accumulator` object. If `accumulator` is not
* provided, a new object with the same `[[Prototype]]` will be used. The
* iteratee is invoked with four arguments: (accumulator, value, key, object).
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @static
* @memberOf _
* @since 1.3.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The custom accumulator value.
* @returns {*} Returns the accumulated value.
* @example
*
* _.transform([2, 3, 4], function(result, n) {
* result.push(n *= n);
* return n % 2 == 0;
* }, []);
* // => [4, 9]
*
* _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
* (result[value] || (result[value] = [])).push(key);
* }, {});
* // => { '1': ['a', 'c'], '2': ['b'] }
*/
function transform(object, iteratee, accumulator) {
var isArr = isArray(object),
isArrLike = isArr || isBuffer(object) || isTypedArray(object);
iteratee = getIteratee(iteratee, 4);
if (accumulator == null) {
var Ctor = object && object.constructor;
if (isArrLike) {
accumulator = isArr ? new Ctor : [];
}
else if (isObject(object)) {
accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};
}
else {
accumulator = {};
}
}
(isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) {
return iteratee(accumulator, value, index, object);
});
return accumulator;
}
/**
* Removes the property at `path` of `object`.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to unset.
* @returns {boolean} Returns `true` if the property is deleted, else `false`.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 7 } }] };
* _.unset(object, 'a[0].b.c');
* // => true
*
* console.log(object);
* // => { 'a': [{ 'b': {} }] };
*
* _.unset(object, ['a', '0', 'b', 'c']);
* // => true
*
* console.log(object);
* // => { 'a': [{ 'b': {} }] };
*/
function unset(object, path) {
return object == null ? true : baseUnset(object, path);
}
/**
* This method is like `_.set` except that accepts `updater` to produce the
* value to set. Use `_.updateWith` to customize `path` creation. The `updater`
* is invoked with one argument: (value).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.6.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {Function} updater The function to produce the updated value.
* @returns {Object} Returns `object`.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.update(object, 'a[0].b.c', function(n) { return n * n; });
* console.log(object.a[0].b.c);
* // => 9
*
* _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });
* console.log(object.x[0].y.z);
* // => 0
*/
function update(object, path, updater) {
return object == null ? object : baseUpdate(object, path, castFunction(updater));
}
/**
* This method is like `_.update` except that it accepts `customizer` which is
* invoked to produce the objects of `path`. If `customizer` returns `undefined`
* path creation is handled by the method instead. The `customizer` is invoked
* with three arguments: (nsValue, key, nsObject).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.6.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {Function} updater The function to produce the updated value.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @example
*
* var object = {};
*
* _.updateWith(object, '[0][1]', _.constant('a'), Object);
* // => { '0': { '1': 'a' } }
*/
function updateWith(object, path, updater, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer);
}
/**
* Creates an array of the own enumerable string keyed property values of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.values(new Foo);
* // => [1, 2] (iteration order is not guaranteed)
*
* _.values('hi');
* // => ['h', 'i']
*/
function values(object) {
return object == null ? [] : baseValues(object, keys(object));
}
/**
* Creates an array of the own and inherited enumerable string keyed property
* values 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 values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.valuesIn(new Foo);
* // => [1, 2, 3] (iteration order is not guaranteed)
*/
function valuesIn(object) {
return object == null ? [] : baseValues(object, keysIn(object));
}
/*------------------------------------------------------------------------*/
/**
* Clamps `number` within the inclusive `lower` and `upper` bounds.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Number
* @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.
* @example
*
* _.clamp(-10, -5, 5);
* // => -5
*
* _.clamp(10, -5, 5);
* // => 5
*/
function clamp(number, lower, upper) {
if (upper === undefined) {
upper = lower;
lower = undefined;
}
if (upper !== undefined) {
upper = toNumber(upper);
upper = upper === upper ? upper : 0;
}
if (lower !== undefined) {
lower = toNumber(lower);
lower = lower === lower ? lower : 0;
}
return baseClamp(toNumber(number), lower, upper);
}
/**
* Checks if `n` is between `start` and up to, but not including, `end`. If
* `end` is not specified, it's set to `start` with `start` then set to `0`.
* If `start` is greater than `end` the params are swapped to support
* negative ranges.
*
* @static
* @memberOf _
* @since 3.3.0
* @category Number
* @param {number} number The number to check.
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @returns {boolean} Returns `true` if `number` is in the range, else `false`.
* @see _.range, _.rangeRight
* @example
*
* _.inRange(3, 2, 4);
* // => true
*
* _.inRange(4, 8);
* // => true
*
* _.inRange(4, 2);
* // => false
*
* _.inRange(2, 2);
* // => false
*
* _.inRange(1.2, 2);
* // => true
*
* _.inRange(5.2, 4);
* // => false
*
* _.inRange(-3, -2, -6);
* // => true
*/
function inRange(number, start, end) {
start = toFinite(start);
if (end === undefined) {
end = start;
start = 0;
} else {
end = toFinite(end);
}
number = toNumber(number);
return baseInRange(number, start, end);
}
/**
* Produces a random number between the inclusive `lower` and `upper` bounds.
* If only one argument is provided a number between `0` and the given number
* is returned. If `floating` is `true`, or either `lower` or `upper` are
* floats, a floating-point number is returned instead of an integer.
*
* **Note:** JavaScript follows the IEEE-754 standard for resolving
* floating-point values which can produce unexpected results.
*
* @static
* @memberOf _
* @since 0.7.0
* @category Number
* @param {number} [lower=0] The lower bound.
* @param {number} [upper=1] The upper bound.
* @param {boolean} [floating] Specify returning a floating-point number.
* @returns {number} Returns the random number.
* @example
*
* _.random(0, 5);
* // => an integer between 0 and 5
*
* _.random(5);
* // => also an integer between 0 and 5
*
* _.random(5, true);
* // => a floating-point number between 0 and 5
*
* _.random(1.2, 5.2);
* // => a floating-point number between 1.2 and 5.2
*/
function random(lower, upper, floating) {
if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) {
upper = floating = undefined;
}
if (floating === undefined) {
if (typeof upper == 'boolean') {
floating = upper;
upper = undefined;
}
else if (typeof lower == 'boolean') {
floating = lower;
lower = undefined;
}
}
if (lower === undefined && upper === undefined) {
lower = 0;
upper = 1;
}
else {
lower = toFinite(lower);
if (upper === undefined) {
upper = lower;
lower = 0;
} else {
upper = toFinite(upper);
}
}
if (lower > upper) {
var temp = lower;
lower = upper;
upper = temp;
}
if (floating || lower % 1 || upper % 1) {
var rand = nativeRandom();
return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper);
}
return baseRandom(lower, upper);
}
/*------------------------------------------------------------------------*/
/**
* Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the camel cased string.
* @example
*
* _.camelCase('Foo Bar');
* // => 'fooBar'
*
* _.camelCase('--foo-bar--');
* // => 'fooBar'
*
* _.camelCase('__FOO_BAR__');
* // => 'fooBar'
*/
var camelCase = createCompounder(function(result, word, index) {
word = word.toLowerCase();
return result + (index ? capitalize(word) : word);
});
/**
* Converts the first character of `string` to upper case and the remaining
* to lower case.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to capitalize.
* @returns {string} Returns the capitalized string.
* @example
*
* _.capitalize('FRED');
* // => 'Fred'
*/
function capitalize(string) {
return upperFirst(toString(string).toLowerCase());
}
/**
* Deburrs `string` by converting
* [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
* and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
* letters to basic Latin letters and removing
* [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to deburr.
* @returns {string} Returns the deburred string.
* @example
*
* _.deburr('déjà vu');
* // => 'deja vu'
*/
function deburr(string) {
string = toString(string);
return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
}
/**
* Checks if `string` ends 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=string.length] The position to search up to.
* @returns {boolean} Returns `true` if `string` ends with `target`,
* else `false`.
* @example
*
* _.endsWith('abc', 'c');
* // => true
*
* _.endsWith('abc', 'b');
* // => false
*
* _.endsWith('abc', 'b', 2);
* // => true
*/
function endsWith(string, target, position) {
string = toString(string);
target = baseToString(target);
var length = string.length;
position = position === undefined
? length
: baseClamp(toInteger(position), 0, length);
var end = position;
position -= target.length;
return position >= 0 && string.slice(position, end) == target;
}
/**
* Converts the characters "&", "<", ">", '"', and "'" in `string` to their
* corresponding HTML entities.
*
* **Note:** No other characters are escaped. To escape additional
* characters use a third-party library like [_he_](https://mths.be/he).
*
* Though the ">" character is escaped for symmetry, characters like
* ">" and "/" don't need escaping in HTML and have no special meaning
* unless they're part of a tag or unquoted attribute value. See
* [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
* (under "semi-related fun fact") for more details.
*
* When working with HTML you should always
* [quote attribute values](http://wonko.com/post/html-escaping) to reduce
* XSS vectors.
*
* @static
* @since 0.1.0
* @memberOf _
* @category String
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escape('fred, barney, & pebbles');
* // => 'fred, barney, & pebbles'
*/
function escape(string) {
string = toString(string);
return (string && reHasUnescapedHtml.test(string))
? string.replace(reUnescapedHtml, escapeHtmlChar)
: string;
}
/**
* Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+",
* "?", "(", ")", "[", "]", "{", "}", and "|" in `string`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escapeRegExp('[lodash](https://lodash.com/)');
* // => '\[lodash\]\(https://lodash\.com/\)'
*/
function escapeRegExp(string) {
string = toString(string);
return (string && reHasRegExpChar.test(string))
? string.replace(reRegExpChar, '\\$&')
: string;
}
/**
* Converts `string` to
* [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the kebab cased string.
* @example
*
* _.kebabCase('Foo Bar');
* // => 'foo-bar'
*
* _.kebabCase('fooBar');
* // => 'foo-bar'
*
* _.kebabCase('__FOO_BAR__');
* // => 'foo-bar'
*/
var kebabCase = createCompounder(function(result, word, index) {
return result + (index ? '-' : '') + word.toLowerCase();
});
/**
* Converts `string`, as space separated words, to lower case.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the lower cased string.
* @example
*
* _.lowerCase('--Foo-Bar--');
* // => 'foo bar'
*
* _.lowerCase('fooBar');
* // => 'foo bar'
*
* _.lowerCase('__FOO_BAR__');
* // => 'foo bar'
*/
var lowerCase = createCompounder(function(result, word, index) {
return result + (index ? ' ' : '') + word.toLowerCase();
});
/**
* Converts the first character of `string` to lower case.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.lowerFirst('Fred');
* // => 'fred'
*
* _.lowerFirst('FRED');
* // => 'fRED'
*/
var lowerFirst = createCaseFirst('toLowerCase');
/**
* Pads `string` on the left and right sides if it's shorter than `length`.
* Padding characters are truncated if they can't be evenly divided by `length`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.pad('abc', 8);
* // => ' abc '
*
* _.pad('abc', 8, '_-');
* // => '_-abc_-_'
*
* _.pad('abc', 3);
* // => 'abc'
*/
function pad(string, length, chars) {
string = toString(string);
length = toInteger(length);
var strLength = length ? stringSize(string) : 0;
if (!length || strLength >= length) {
return string;
}
var mid = (length - strLength) / 2;
return (
createPadding(nativeFloor(mid), chars) +
string +
createPadding(nativeCeil(mid), chars)
);
}
/**
* Pads `string` on the right side if it's shorter than `length`. Padding
* characters are truncated if they exceed `length`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.padEnd('abc', 6);
* // => 'abc '
*
* _.padEnd('abc', 6, '_-');
* // => 'abc_-_'
*
* _.padEnd('abc', 3);
* // => 'abc'
*/
function padEnd(string, length, chars) {
string = toString(string);
length = toInteger(length);
var strLength = length ? stringSize(string) : 0;
return (length && strLength < length)
? (string + createPadding(length - strLength, chars))
: string;
}
/**
* Pads `string` on the left side if it's shorter than `length`. Padding
* characters are truncated if they exceed `length`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.padStart('abc', 6);
* // => ' abc'
*
* _.padStart('abc', 6, '_-');
* // => '_-_abc'
*
* _.padStart('abc', 3);
* // => 'abc'
*/
function padStart(string, length, chars) {
string = toString(string);
length = toInteger(length);
var strLength = length ? stringSize(string) : 0;
return (length && strLength < length)
? (createPadding(length - strLength, chars) + string)
: string;
}
/**
* Converts `string` to an integer of the specified radix. If `radix` is
* `undefined` or `0`, a `radix` of `10` is used unless `value` is a
* hexadecimal, in which case a `radix` of `16` is used.
*
* **Note:** This method aligns with the
* [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.
*
* @static
* @memberOf _
* @since 1.1.0
* @category String
* @param {string} string The string to convert.
* @param {number} [radix=10] The radix to interpret `value` by.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {number} Returns the converted integer.
* @example
*
* _.parseInt('08');
* // => 8
*
* _.map(['6', '08', '10'], _.parseInt);
* // => [6, 8, 10]
*/
function parseInt(string, radix, guard) {
if (guard || radix == null) {
radix = 0;
} else if (radix) {
radix = +radix;
}
return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0);
}
/**
* Repeats the given string `n` times.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to repeat.
* @param {number} [n=1] The number of times to repeat the string.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the repeated string.
* @example
*
* _.repeat('*', 3);
* // => '***'
*
* _.repeat('abc', 2);
* // => 'abcabc'
*
* _.repeat('abc', 0);
* // => ''
*/
function repeat(string, n, guard) {
if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) {
n = 1;
} else {
n = toInteger(n);
}
return baseRepeat(toString(string), n);
}
/**
* Replaces matches for `pattern` in `string` with `replacement`.
*
* **Note:** This method is based on
* [`String#replace`](https://mdn.io/String/replace).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to modify.
* @param {RegExp|string} pattern The pattern to replace.
* @param {Function|string} replacement The match replacement.
* @returns {string} Returns the modified string.
* @example
*
* _.replace('Hi Fred', 'Fred', 'Barney');
* // => 'Hi Barney'
*/
function replace() {
var args = arguments,
string = toString(args[0]);
return args.length < 3 ? string : string.replace(args[1], args[2]);
}
/**
* Converts `string` to
* [snake case](https://en.wikipedia.org/wiki/Snake_case).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the snake cased string.
* @example
*
* _.snakeCase('Foo Bar');
* // => 'foo_bar'
*
* _.snakeCase('fooBar');
* // => 'foo_bar'
*
* _.snakeCase('--FOO-BAR--');
* // => 'foo_bar'
*/
var snakeCase = createCompounder(function(result, word, index) {
return result + (index ? '_' : '') + word.toLowerCase();
});
/**
* Splits `string` by `separator`.
*
* **Note:** This method is based on
* [`String#split`](https://mdn.io/String/split).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to split.
* @param {RegExp|string} separator The separator pattern to split by.
* @param {number} [limit] The length to truncate results to.
* @returns {Array} Returns the string segments.
* @example
*
* _.split('a-b-c', '-', 2);
* // => ['a', 'b']
*/
function split(string, separator, limit) {
if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) {
separator = limit = undefined;
}
limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0;
if (!limit) {
return [];
}
string = toString(string);
if (string && (
typeof separator == 'string' ||
(separator != null && !isRegExp(separator))
)) {
separator = baseToString(separator);
if (!separator && hasUnicode(string)) {
return castSlice(stringToArray(string), 0, limit);
}
}
return string.split(separator, limit);
}
/**
* Converts `string` to
* [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
*
* @static
* @memberOf _
* @since 3.1.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the start cased string.
* @example
*
* _.startCase('--foo-bar--');
* // => 'Foo Bar'
*
* _.startCase('fooBar');
* // => 'Foo Bar'
*
* _.startCase('__FOO_BAR__');
* // => 'FOO BAR'
*/
var startCase = createCompounder(function(result, word, index) {
return result + (index ? ' ' : '') + upperFirst(word);
});
/**
* Checks if `string` starts with the given target string.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {string} [target] The string to search for.
* @param {number} [position=0] The position to search from.
* @returns {boolean} Returns `true` if `string` starts with `target`,
* else `false`.
* @example
*
* _.startsWith('abc', 'a');
* // => true
*
* _.startsWith('abc', 'b');
* // => false
*
* _.startsWith('abc', 'b', 1);
* // => true
*/
function startsWith(string, target, position) {
string = toString(string);
position = position == null
? 0
: baseClamp(toInteger(position), 0, string.length);
target = baseToString(target);
return string.slice(position, position + target.length) == target;
}
/**
* Creates a compiled template function that can interpolate data properties
* in "interpolate" delimiters, HTML-escape interpolated data properties in
* "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
* properties may be accessed as free variables in the template. If a setting
* object is given, it takes precedence over `_.templateSettings` values.
*
* **Note:** In the development build `_.template` utilizes
* [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
* for easier debugging.
*
* For more information on precompiling templates see
* [lodash's custom builds documentation](https://lodash.com/custom-builds).
*
* For more information on Chrome extension sandboxes see
* [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
*
* @static
* @since 0.1.0
* @memberOf _
* @category String
* @param {string} [string=''] The template string.
* @param {Object} [options={}] The options object.
* @param {RegExp} [options.escape=_.templateSettings.escape]
* The HTML "escape" delimiter.
* @param {RegExp} [options.evaluate=_.templateSettings.evaluate]
* The "evaluate" delimiter.
* @param {Object} [options.imports=_.templateSettings.imports]
* An object to import into the template as free variables.
* @param {RegExp} [options.interpolate=_.templateSettings.interpolate]
* The "interpolate" delimiter.
* @param {string} [options.sourceURL='lodash.templateSources[n]']
* The sourceURL of the compiled template.
* @param {string} [options.variable='obj']
* The data object variable name.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the compiled template function.
* @example
*
* // Use the "interpolate" delimiter to create a compiled template.
* var compiled = _.template('hello <%= user %>!');
* compiled({ 'user': 'fred' });
* // => 'hello fred!'
*
* // Use the HTML "escape" delimiter to escape data property values.
* var compiled = _.template('<b><%- value %></b>');
* compiled({ 'value': '<script>' });
* // => '<b><script></b>'
*
* // Use the "evaluate" delimiter to execute JavaScript and generate HTML.
* var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
* compiled({ 'users': ['fred', 'barney'] });
* // => '<li>fred</li><li>barney</li>'
*
* // Use the internal `print` function in "evaluate" delimiters.
* var compiled = _.template('<% print("hello " + user); %>!');
* compiled({ 'user': 'barney' });
* // => 'hello barney!'
*
* // Use the ES template literal delimiter as an "interpolate" delimiter.
* // Disable support by replacing the "interpolate" delimiter.
* var compiled = _.template('hello ${ user }!');
* compiled({ 'user': 'pebbles' });
* // => 'hello pebbles!'
*
* // Use backslashes to treat delimiters as plain text.
* var compiled = _.template('<%= "\\<%- value %\\>" %>');
* compiled({ 'value': 'ignored' });
* // => '<%- value %>'
*
* // Use the `imports` option to import `jQuery` as `jq`.
* var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
* var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
* compiled({ 'users': ['fred', 'barney'] });
* // => '<li>fred</li><li>barney</li>'
*
* // Use the `sourceURL` option to specify a custom sourceURL for the template.
* var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
* compiled(data);
* // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector.
*
* // Use the `variable` option to ensure a with-statement isn't used in the compiled template.
* var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
* compiled.source;
* // => function(data) {
* // var __t, __p = '';
* // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
* // return __p;
* // }
*
* // Use custom template delimiters.
* _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
* var compiled = _.template('hello {{ user }}!');
* compiled({ 'user': 'mustache' });
* // => 'hello mustache!'
*
* // Use the `source` property to inline compiled templates for meaningful
* // line numbers in error messages and stack traces.
* fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\
* var JST = {\
* "main": ' + _.template(mainText).source + '\
* };\
* ');
*/
function template(string, options, guard) {
// Based on John Resig's `tmpl` implementation
// (http://ejohn.org/blog/javascript-micro-templating/)
// and Laura Doktorova's doT.js (https://github.com/olado/doT).
var settings = lodash.templateSettings;
if (guard && isIterateeCall(string, options, guard)) {
options = undefined;
}
string = toString(string);
options = assignInWith({}, options, settings, customDefaultsAssignIn);
var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn),
importsKeys = keys(imports),
importsValues = baseValues(imports, importsKeys);
var isEscaping,
isEvaluating,
index = 0,
interpolate = options.interpolate || reNoMatch,
source = "__p += '";
// Compile the regexp to match each delimiter.
var reDelimiters = RegExp(
(options.escape || reNoMatch).source + '|' +
interpolate.source + '|' +
(interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
(options.evaluate || reNoMatch).source + '|$'
, 'g');
// Use a sourceURL for easier debugging.
// The sourceURL gets injected into the source that's eval-ed, so be careful
// to normalize all kinds of whitespace, so e.g. newlines (and unicode versions of it) can't sneak in
// and escape the comment, thus injecting code that gets evaled.
var sourceURL = '//# sourceURL=' +
(hasOwnProperty.call(options, 'sourceURL')
? (options.sourceURL + '').replace(/\s/g, ' ')
: ('lodash.templateSources[' + (++templateCounter) + ']')
) + '\n';
string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
interpolateValue || (interpolateValue = esTemplateValue);
// Escape characters that can't be included in string literals.
source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
// Replace delimiters with snippets.
if (escapeValue) {
isEscaping = true;
source += "' +\n__e(" + escapeValue + ") +\n'";
}
if (evaluateValue) {
isEvaluating = true;
source += "';\n" + evaluateValue + ";\n__p += '";
}
if (interpolateValue) {
source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
}
index = offset + match.length;
// The JS engine embedded in Adobe products needs `match` returned in
// order to produce the correct `offset` value.
return match;
});
source += "';\n";
// If `variable` is not specified wrap a with-statement around the generated
// code to add the data object to the top of the scope chain.
var variable = hasOwnProperty.call(options, 'variable') && options.variable;
if (!variable) {
source = 'with (obj) {\n' + source + '\n}\n';
}
// Throw an error if a forbidden character was found in `variable`, to prevent
// potential command injection attacks.
else if (reForbiddenIdentifierChars.test(variable)) {
throw new Error(INVALID_TEMPL_VAR_ERROR_TEXT);
}
// Cleanup code by stripping empty strings.
source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
.replace(reEmptyStringMiddle, '$1')
.replace(reEmptyStringTrailing, '$1;');
// Frame code as the function body.
source = 'function(' + (variable || 'obj') + ') {\n' +
(variable
? ''
: 'obj || (obj = {});\n'
) +
"var __t, __p = ''" +
(isEscaping
? ', __e = _.escape'
: ''
) +
(isEvaluating
? ', __j = Array.prototype.join;\n' +
"function print() { __p += __j.call(arguments, '') }\n"
: ';\n'
) +
source +
'return __p\n}';
var result = attempt(function() {
return Function(importsKeys, sourceURL + 'return ' + source)
.apply(undefined, importsValues);
});
// Provide the compiled function's source by its `toString` method or
// the `source` property as a convenience for inlining compiled templates.
result.source = source;
if (isError(result)) {
throw result;
}
return result;
}
/**
* Converts `string`, as a whole, to lower case just like
* [String#toLowerCase](https://mdn.io/toLowerCase).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the lower cased string.
* @example
*
* _.toLower('--Foo-Bar--');
* // => '--foo-bar--'
*
* _.toLower('fooBar');
* // => 'foobar'
*
* _.toLower('__FOO_BAR__');
* // => '__foo_bar__'
*/
function toLower(value) {
return toString(value).toLowerCase();
}
/**
* Converts `string`, as a whole, to upper case just like
* [String#toUpperCase](https://mdn.io/toUpperCase).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the upper cased string.
* @example
*
* _.toUpper('--foo-bar--');
* // => '--FOO-BAR--'
*
* _.toUpper('fooBar');
* // => 'FOOBAR'
*
* _.toUpper('__foo_bar__');
* // => '__FOO_BAR__'
*/
function toUpper(value) {
return toString(value).toUpperCase();
}
/**
* Removes leading and trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trim(' abc ');
* // => 'abc'
*
* _.trim('-_-abc-_-', '_-');
* // => 'abc'
*
* _.map([' foo ', ' bar '], _.trim);
* // => ['foo', 'bar']
*/
function trim(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return baseTrim(string);
}
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('');
}
/**
* Removes trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 4.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
*
* _.trimEnd(' abc ');
* // => ' abc'
*
* _.trimEnd('-_-abc-_-', '_-');
* // => '-_-abc'
*/
function trimEnd(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return string.slice(0, trimmedEndIndex(string) + 1);
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
end = charsEndIndex(strSymbols, stringToArray(chars)) + 1;
return castSlice(strSymbols, 0, end).join('');
}
/**
* Removes leading whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 4.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
*
* _.trimStart(' abc ');
* // => 'abc '
*
* _.trimStart('-_-abc-_-', '_-');
* // => 'abc-_-'
*/
function trimStart(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return string.replace(reTrimStart, '');
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
start = charsStartIndex(strSymbols, stringToArray(chars));
return castSlice(strSymbols, start).join('');
}
/**
* Truncates `string` if it's longer than the given maximum string length.
* The last characters of the truncated string are replaced with the omission
* string which defaults to "...".
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to truncate.
* @param {Object} [options={}] The options object.
* @param {number} [options.length=30] The maximum string length.
* @param {string} [options.omission='...'] The string to indicate text is omitted.
* @param {RegExp|string} [options.separator] The separator pattern to truncate to.
* @returns {string} Returns the truncated string.
* @example
*
* _.truncate('hi-diddly-ho there, neighborino');
* // => 'hi-diddly-ho there, neighbo...'
*
* _.truncate('hi-diddly-ho there, neighborino', {
* 'length': 24,
* 'separator': ' '
* });
* // => 'hi-diddly-ho there,...'
*
* _.truncate('hi-diddly-ho there, neighborino', {
* 'length': 24,
* 'separator': /,? +/
* });
* // => 'hi-diddly-ho there...'
*
* _.truncate('hi-diddly-ho there, neighborino', {
* 'omission': ' [...]'
* });
* // => 'hi-diddly-ho there, neig [...]'
*/
function truncate(string, options) {
var length = DEFAULT_TRUNC_LENGTH,
omission = DEFAULT_TRUNC_OMISSION;
if (isObject(options)) {
var separator = 'separator' in options ? options.separator : separator;
length = 'length' in options ? toInteger(options.length) : length;
omission = 'omission' in options ? baseToString(options.omission) : omission;
}
string = toString(string);
var strLength = string.length;
if (hasUnicode(string)) {
var strSymbols = stringToArray(string);
strLength = strSymbols.length;
}
if (length >= strLength) {
return string;
}
var end = length - stringSize(omission);
if (end < 1) {
return omission;
}
var result = strSymbols
? castSlice(strSymbols, 0, end).join('')
: string.slice(0, end);
if (separator === undefined) {
return result + omission;
}
if (strSymbols) {
end += (result.length - end);
}
if (isRegExp(separator)) {
if (string.slice(end).search(separator)) {
var match,
substring = result;
if (!separator.global) {
separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g');
}
separator.lastIndex = 0;
while ((match = separator.exec(substring))) {
var newEnd = match.index;
}
result = result.slice(0, newEnd === undefined ? end : newEnd);
}
} else if (string.indexOf(baseToString(separator), end) != end) {
var index = result.lastIndexOf(separator);
if (index > -1) {
result = result.slice(0, index);
}
}
return result + omission;
}
/**
* The inverse of `_.escape`; this method converts the HTML entities
* `&`, `<`, `>`, `"`, and `'` in `string` to
* their corresponding characters.
*
* **Note:** No other HTML entities are unescaped. To unescape additional
* HTML entities use a third-party library like [_he_](https://mths.be/he).
*
* @static
* @memberOf _
* @since 0.6.0
* @category String
* @param {string} [string=''] The string to unescape.
* @returns {string} Returns the unescaped string.
* @example
*
* _.unescape('fred, barney, & pebbles');
* // => 'fred, barney, & pebbles'
*/
function unescape(string) {
string = toString(string);
return (string && reHasEscapedHtml.test(string))
? string.replace(reEscapedHtml, unescapeHtmlChar)
: string;
}
/**
* Converts `string`, as space separated words, to upper case.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the upper cased string.
* @example
*
* _.upperCase('--foo-bar');
* // => 'FOO BAR'
*
* _.upperCase('fooBar');
* // => 'FOO BAR'
*
* _.upperCase('__foo_bar__');
* // => 'FOO BAR'
*/
var upperCase = createCompounder(function(result, word, index) {
return result + (index ? ' ' : '') + word.toUpperCase();
});
/**
* Converts the first character of `string` to upper case.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.upperFirst('fred');
* // => 'Fred'
*
* _.upperFirst('FRED');
* // => 'FRED'
*/
var upperFirst = createCaseFirst('toUpperCase');
/**
* Splits `string` into an array of its words.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {RegExp|string} [pattern] The pattern to match words.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the words of `string`.
* @example
*
* _.words('fred, barney, & pebbles');
* // => ['fred', 'barney', 'pebbles']
*
* _.words('fred, barney, & pebbles', /[^, ]+/g);
* // => ['fred', 'barney', '&', 'pebbles']
*/
function words(string, pattern, guard) {
string = toString(string);
pattern = guard ? undefined : pattern;
if (pattern === undefined) {
return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
}
return string.match(pattern) || [];
}
/*------------------------------------------------------------------------*/
/**
* Attempts to invoke `func`, returning either the result or the caught error
* object. Any additional arguments are provided to `func` when it's invoked.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {Function} func The function to attempt.
* @param {...*} [args] The arguments to invoke `func` with.
* @returns {*} Returns the `func` result or error object.
* @example
*
* // Avoid throwing errors for invalid selectors.
* var elements = _.attempt(function(selector) {
* return document.querySelectorAll(selector);
* }, '>_>');
*
* if (_.isError(elements)) {
* elements = [];
* }
*/
var attempt = baseRest(function(func, args) {
try {
return apply(func, undefined, args);
} catch (e) {
return isError(e) ? e : new Error(e);
}
});
/**
* Binds methods of an object to the object itself, overwriting the existing
* method.
*
* **Note:** This method doesn't set the "length" property of bound functions.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {Object} object The object to bind and assign the bound methods to.
* @param {...(string|string[])} methodNames The object method names to bind.
* @returns {Object} Returns `object`.
* @example
*
* var view = {
* 'label': 'docs',
* 'click': function() {
* console.log('clicked ' + this.label);
* }
* };
*
* _.bindAll(view, ['click']);
* jQuery(element).on('click', view.click);
* // => Logs 'clicked docs' when clicked.
*/
var bindAll = flatRest(function(object, methodNames) {
arrayEach(methodNames, function(key) {
key = toKey(key);
baseAssignValue(object, key, bind(object[key], object));
});
return object;
});
/**
* Creates a function that iterates over `pairs` and invokes the corresponding
* function of the first predicate to return truthy. The predicate-function
* pairs are invoked with the `this` binding and arguments of the created
* function.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {Array} pairs The predicate-function pairs.
* @returns {Function} Returns the new composite function.
* @example
*
* var func = _.cond([
* [_.matches({ 'a': 1 }), _.constant('matches A')],
* [_.conforms({ 'b': _.isNumber }), _.constant('matches B')],
* [_.stubTrue, _.constant('no match')]
* ]);
*
* func({ 'a': 1, 'b': 2 });
* // => 'matches A'
*
* func({ 'a': 0, 'b': 1 });
* // => 'matches B'
*
* func({ 'a': '1', 'b': '2' });
* // => 'no match'
*/
function cond(pairs) {
var length = pairs == null ? 0 : pairs.length,
toIteratee = getIteratee();
pairs = !length ? [] : arrayMap(pairs, function(pair) {
if (typeof pair[1] != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
return [toIteratee(pair[0]), pair[1]];
});
return baseRest(function(args) {
var index = -1;
while (++index < length) {
var pair = pairs[index];
if (apply(pair[0], this, args)) {
return apply(pair[1], this, args);
}
}
});
}
/**
* Creates a function that invokes the predicate properties of `source` with
* the corresponding property values of a given object, returning `true` if
* all predicates return truthy, else `false`.
*
* **Note:** The created function is equivalent to `_.conformsTo` with
* `source` partially applied.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {Object} source The object of property predicates to conform to.
* @returns {Function} Returns the new spec function.
* @example
*
* var objects = [
* { 'a': 2, 'b': 1 },
* { 'a': 1, 'b': 2 }
* ];
*
* _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } }));
* // => [{ 'a': 1, 'b': 2 }]
*/
function conforms(source) {
return baseConforms(baseClone(source, CLONE_DEEP_FLAG));
}
/**
* 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;
};
}
/**
* Checks `value` to determine whether a default value should be returned in
* its place. The `defaultValue` is returned if `value` is `NaN`, `null`,
* or `undefined`.
*
* @static
* @memberOf _
* @since 4.14.0
* @category Util
* @param {*} value The value to check.
* @param {*} defaultValue The default value.
* @returns {*} Returns the resolved value.
* @example
*
* _.defaultTo(1, 10);
* // => 1
*
* _.defaultTo(undefined, 10);
* // => 10
*/
function defaultTo(value, defaultValue) {
return (value == null || value !== value) ? defaultValue : value;
}
/**
* Creates a function that returns the result of invoking the given functions
* with the `this` binding of the created function, where each successive
* invocation is supplied the return value of the previous.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {...(Function|Function[])} [funcs] The functions to invoke.
* @returns {Function} Returns the new composite function.
* @see _.flowRight
* @example
*
* function square(n) {
* return n * n;
* }
*
* var addSquare = _.flow([_.add, square]);
* addSquare(1, 2);
* // => 9
*/
var flow = createFlow();
/**
* This method is like `_.flow` except that it creates a function that
* invokes the given functions from right to left.
*
* @static
* @since 3.0.0
* @memberOf _
* @category Util
* @param {...(Function|Function[])} [funcs] The functions to invoke.
* @returns {Function} Returns the new composite function.
* @see _.flow
* @example
*
* function square(n) {
* return n * n;
* }
*
* var addSquare = _.flowRight([square, _.add]);
* addSquare(1, 2);
* // => 9
*/
var flowRight = createFlow(true);
/**
* 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;
}
/**
* Creates a function that invokes `func` with the arguments of the created
* function. If `func` is a property name, the created function returns the
* property value for a given element. If `func` is an array or object, the
* created function returns `true` for elements that contain the equivalent
* source properties, otherwise it returns `false`.
*
* @static
* @since 4.0.0
* @memberOf _
* @category Util
* @param {*} [func=_.identity] The value to convert to a callback.
* @returns {Function} Returns the callback.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
* // => [{ 'user': 'barney', 'age': 36, 'active': true }]
*
* // The `_.matchesProperty` iteratee shorthand.
* _.filter(users, _.iteratee(['user', 'fred']));
* // => [{ 'user': 'fred', 'age': 40 }]
*
* // The `_.property` iteratee shorthand.
* _.map(users, _.iteratee('user'));
* // => ['barney', 'fred']
*
* // Create custom iteratee shorthands.
* _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
* return !_.isRegExp(func) ? iteratee(func) : function(string) {
* return func.test(string);
* };
* });
*
* _.filter(['abc', 'def'], /ef/);
* // => ['def']
*/
function iteratee(func) {
return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG));
}
/**
* Creates a function that performs a partial deep comparison between a given
* object and `source`, returning `true` if the given object has equivalent
* property values, else `false`.
*
* **Note:** The created function is equivalent to `_.isMatch` with `source`
* partially applied.
*
* Partial comparisons will match empty array and empty object `source`
* values against any array or object value, respectively. See `_.isEqual`
* for a list of supported value comparisons.
*
* **Note:** Multiple values can be checked by combining several matchers
* using `_.overSome`
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new spec function.
* @example
*
* var objects = [
* { 'a': 1, 'b': 2, 'c': 3 },
* { 'a': 4, 'b': 5, 'c': 6 }
* ];
*
* _.filter(objects, _.matches({ 'a': 4, 'c': 6 }));
* // => [{ 'a': 4, 'b': 5, 'c': 6 }]
*
* // Checking for several possible values
* _.filter(objects, _.overSome([_.matches({ 'a': 1 }), _.matches({ 'a': 4 })]));
* // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]
*/
function matches(source) {
return baseMatches(baseClone(source, CLONE_DEEP_FLAG));
}
/**
* Creates a function that performs a partial deep comparison between the
* value at `path` of a given object to `srcValue`, returning `true` if the
* object value is equivalent, else `false`.
*
* **Note:** Partial comparisons will match empty array and empty object
* `srcValue` values against any array or object value, respectively. See
* `_.isEqual` for a list of supported value comparisons.
*
* **Note:** Multiple values can be checked by combining several matchers
* using `_.overSome`
*
* @static
* @memberOf _
* @since 3.2.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
* @example
*
* var objects = [
* { 'a': 1, 'b': 2, 'c': 3 },
* { 'a': 4, 'b': 5, 'c': 6 }
* ];
*
* _.find(objects, _.matchesProperty('a', 4));
* // => { 'a': 4, 'b': 5, 'c': 6 }
*
* // Checking for several possible values
* _.filter(objects, _.overSome([_.matchesProperty('a', 1), _.matchesProperty('a', 4)]));
* // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]
*/
function matchesProperty(path, srcValue) {
return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG));
}
/**
* Creates a function that invokes the method at `path` of a given object.
* Any additional arguments are provided to the invoked method.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Util
* @param {Array|string} path The path of the method to invoke.
* @param {...*} [args] The arguments to invoke the method with.
* @returns {Function} Returns the new invoker function.
* @example
*
* var objects = [
* { 'a': { 'b': _.constant(2) } },
* { 'a': { 'b': _.constant(1) } }
* ];
*
* _.map(objects, _.method('a.b'));
* // => [2, 1]
*
* _.map(objects, _.method(['a', 'b']));
* // => [2, 1]
*/
var method = baseRest(function(path, args) {
return function(object) {
return baseInvoke(object, path, args);
};
});
/**
* The opposite of `_.method`; this method creates a function that invokes
* the method at a given path of `object`. Any additional arguments are
* provided to the invoked method.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Util
* @param {Object} object The object to query.
* @param {...*} [args] The arguments to invoke the method with.
* @returns {Function} Returns the new invoker function.
* @example
*
* var array = _.times(3, _.constant),
* object = { 'a': array, 'b': array, 'c': array };
*
* _.map(['a[2]', 'c[0]'], _.methodOf(object));
* // => [2, 0]
*
* _.map([['a', '2'], ['c', '0']], _.methodOf(object));
* // => [2, 0]
*/
var methodOf = baseRest(function(object, args) {
return function(path) {
return baseInvoke(object, path, args);
};
});
/**
* Adds all own enumerable string keyed function properties of a source
* object to the destination object. If `object` is a function, then methods
* are added to its prototype as well.
*
* **Note:** Use `_.runInContext` to create a pristine `lodash` function to
* avoid conflicts caused by modifying the original.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {Function|Object} [object=lodash] The destination object.
* @param {Object} source The object of functions to add.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.chain=true] Specify whether mixins are chainable.
* @returns {Function|Object} Returns `object`.
* @example
*
* function vowels(string) {
* return _.filter(string, function(v) {
* return /[aeiou]/i.test(v);
* });
* }
*
* _.mixin({ 'vowels': vowels });
* _.vowels('fred');
* // => ['e']
*
* _('fred').vowels().value();
* // => ['e']
*
* _.mixin({ 'vowels': vowels }, { 'chain': false });
* _('fred').vowels();
* // => ['e']
*/
function mixin(object, source, options) {
var props = keys(source),
methodNames = baseFunctions(source, props);
if (options == null &&
!(isObject(source) && (methodNames.length || !props.length))) {
options = source;
source = object;
object = this;
methodNames = baseFunctions(source, keys(source));
}
var chain = !(isObject(options) && 'chain' in options) || !!options.chain,
isFunc = isFunction(object);
arrayEach(methodNames, function(methodName) {
var func = source[methodName];
object[methodName] = func;
if (isFunc) {
object.prototype[methodName] = function() {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
};
}
});
return object;
}
/**
* Reverts the `_` variable to its previous value and returns a reference to
* the `lodash` function.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @returns {Function} Returns the `lodash` function.
* @example
*
* var lodash = _.noConflict();
*/
function noConflict() {
if (root._ === this) {
root._ = oldDash;
}
return this;
}
/**
* This method returns `undefined`.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Util
* @example
*
* _.times(2, _.noop);
* // => [undefined, undefined]
*/
function noop() {
// No operation performed.
}
/**
* Creates a function that gets the argument at index `n`. If `n` is negative,
* the nth argument from the end is returned.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {number} [n=0] The index of the argument to return.
* @returns {Function} Returns the new pass-thru function.
* @example
*
* var func = _.nthArg(1);
* func('a', 'b', 'c', 'd');
* // => 'b'
*
* var func = _.nthArg(-2);
* func('a', 'b', 'c', 'd');
* // => 'c'
*/
function nthArg(n) {
n = toInteger(n);
return baseRest(function(args) {
return baseNth(args, n);
});
}
/**
* Creates a function that invokes `iteratees` with the arguments it receives
* and returns their results.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {...(Function|Function[])} [iteratees=[_.identity]]
* The iteratees to invoke.
* @returns {Function} Returns the new function.
* @example
*
* var func = _.over([Math.max, Math.min]);
*
* func(1, 2, 3, 4);
* // => [4, 1]
*/
var over = createOver(arrayMap);
/**
* Creates a function that checks if **all** of the `predicates` return
* truthy when invoked with the arguments it receives.
*
* Following shorthands are possible for providing predicates.
* Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate.
* Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {...(Function|Function[])} [predicates=[_.identity]]
* The predicates to check.
* @returns {Function} Returns the new function.
* @example
*
* var func = _.overEvery([Boolean, isFinite]);
*
* func('1');
* // => true
*
* func(null);
* // => false
*
* func(NaN);
* // => false
*/
var overEvery = createOver(arrayEvery);
/**
* Creates a function that checks if **any** of the `predicates` return
* truthy when invoked with the arguments it receives.
*
* Following shorthands are possible for providing predicates.
* Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate.
* Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {...(Function|Function[])} [predicates=[_.identity]]
* The predicates to check.
* @returns {Function} Returns the new function.
* @example
*
* var func = _.overSome([Boolean, isFinite]);
*
* func('1');
* // => true
*
* func(null);
* // => true
*
* func(NaN);
* // => false
*
* var matchesFunc = _.overSome([{ 'a': 1 }, { 'a': 2 }])
* var matchesPropertyFunc = _.overSome([['a', 1], ['a', 2]])
*/
var overSome = createOver(arraySome);
/**
* 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);
}
/**
* The opposite of `_.property`; this method creates a function that returns
* the value at a given path of `object`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {Object} object The object to query.
* @returns {Function} Returns the new accessor function.
* @example
*
* var array = [0, 1, 2],
* object = { 'a': array, 'b': array, 'c': array };
*
* _.map(['a[2]', 'c[0]'], _.propertyOf(object));
* // => [2, 0]
*
* _.map([['a', '2'], ['c', '0']], _.propertyOf(object));
* // => [2, 0]
*/
function propertyOf(object) {
return function(path) {
return object == null ? undefined : baseGet(object, path);
};
}
/**
* 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();
/**
* This method is like `_.range` except that it populates values in
* descending order.
*
* @static
* @memberOf _
* @since 4.0.0
* @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, _.range
* @example
*
* _.rangeRight(4);
* // => [3, 2, 1, 0]
*
* _.rangeRight(-4);
* // => [-3, -2, -1, 0]
*
* _.rangeRight(1, 5);
* // => [4, 3, 2, 1]
*
* _.rangeRight(0, 20, 5);
* // => [15, 10, 5, 0]
*
* _.rangeRight(0, -4, -1);
* // => [-3, -2, -1, 0]
*
* _.rangeRight(1, 4, 0);
* // => [1, 1, 1]
*
* _.rangeRight(0);
* // => []
*/
var rangeRight = createRange(true);
/**
* 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 [];
}
/**
* 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;
}
/**
* This method returns a new empty object.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Object} Returns the new empty object.
* @example
*
* var objects = _.times(2, _.stubObject);
*
* console.log(objects);
* // => [{}, {}]
*
* console.log(objects[0] === objects[1]);
* // => false
*/
function stubObject() {
return {};
}
/**
* This method returns an empty string.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {string} Returns the empty string.
* @example
*
* _.times(2, _.stubString);
* // => ['', '']
*/
function stubString() {
return '';
}
/**
* This method returns `true`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `true`.
* @example
*
* _.times(2, _.stubTrue);
* // => [true, true]
*/
function stubTrue() {
return true;
}
/**
* Invokes the iteratee `n` times, returning an array of the results of
* each invocation. The iteratee is invoked with one argument; (index).
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the array of results.
* @example
*
* _.times(3, String);
* // => ['0', '1', '2']
*
* _.times(4, _.constant(0));
* // => [0, 0, 0, 0]
*/
function times(n, iteratee) {
n = toInteger(n);
if (n < 1 || n > MAX_SAFE_INTEGER) {
return [];
}
var index = MAX_ARRAY_LENGTH,
length = nativeMin(n, MAX_ARRAY_LENGTH);
iteratee = getIteratee(iteratee);
n -= MAX_ARRAY_LENGTH;
var result = baseTimes(length, iteratee);
while (++index < n) {
iteratee(index);
}
return result;
}
/**
* Converts `value` to a property path array.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {*} value The value to convert.
* @returns {Array} Returns the new property path array.
* @example
*
* _.toPath('a.b.c');
* // => ['a', 'b', 'c']
*
* _.toPath('a[0].b.c');
* // => ['a', '0', 'b', 'c']
*/
function toPath(value) {
if (isArray(value)) {
return arrayMap(value, toKey);
}
return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value)));
}
/**
* Generates a unique ID. If `prefix` is given, the ID is appended to it.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {string} [prefix=''] The value to prefix the ID with.
* @returns {string} Returns the unique ID.
* @example
*
* _.uniqueId('contact_');
* // => 'contact_104'
*
* _.uniqueId();
* // => '105'
*/
function uniqueId(prefix) {
var id = ++idCounter;
return toString(prefix) + id;
}
/*------------------------------------------------------------------------*/
/**
* Adds two numbers.
*
* @static
* @memberOf _
* @since 3.4.0
* @category Math
* @param {number} augend The first number in an addition.
* @param {number} addend The second number in an addition.
* @returns {number} Returns the total.
* @example
*
* _.add(6, 4);
* // => 10
*/
var add = createMathOperation(function(augend, addend) {
return augend + addend;
}, 0);
/**
* Computes `number` rounded up to `precision`.
*
* @static
* @memberOf _
* @since 3.10.0
* @category Math
* @param {number} number The number to round up.
* @param {number} [precision=0] The precision to round up to.
* @returns {number} Returns the rounded up number.
* @example
*
* _.ceil(4.006);
* // => 5
*
* _.ceil(6.004, 2);
* // => 6.01
*
* _.ceil(6040, -2);
* // => 6100
*/
var ceil = createRound('ceil');
/**
* Divide two numbers.
*
* @static
* @memberOf _
* @since 4.7.0
* @category Math
* @param {number} dividend The first number in a division.
* @param {number} divisor The second number in a division.
* @returns {number} Returns the quotient.
* @example
*
* _.divide(6, 4);
* // => 1.5
*/
var divide = createMathOperation(function(dividend, divisor) {
return dividend / divisor;
}, 1);
/**
* Computes `number` rounded down to `precision`.
*
* @static
* @memberOf _
* @since 3.10.0
* @category Math
* @param {number} number The number to round down.
* @param {number} [precision=0] The precision to round down to.
* @returns {number} Returns the rounded down number.
* @example
*
* _.floor(4.006);
* // => 4
*
* _.floor(0.046, 2);
* // => 0.04
*
* _.floor(4060, -2);
* // => 4000
*/
var floor = createRound('floor');
/**
* Computes the maximum value of `array`. If `array` is empty or falsey,
* `undefined` is returned.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Math
* @param {Array} array The array to iterate over.
* @returns {*} Returns the maximum value.
* @example
*
* _.max([4, 2, 8, 6]);
* // => 8
*
* _.max([]);
* // => undefined
*/
function max(array) {
return (array && array.length)
? baseExtremum(array, identity, baseGt)
: undefined;
}
/**
* This method is like `_.max` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the criterion by which
* the value is ranked. 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 {*} Returns the maximum value.
* @example
*
* var objects = [{ 'n': 1 }, { 'n': 2 }];
*
* _.maxBy(objects, function(o) { return o.n; });
* // => { 'n': 2 }
*
* // The `_.property` iteratee shorthand.
* _.maxBy(objects, 'n');
* // => { 'n': 2 }
*/
function maxBy(array, iteratee) {
return (array && array.length)
? baseExtremum(array, getIteratee(iteratee, 2), baseGt)
: undefined;
}
/**
* Computes the mean of the values in `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @returns {number} Returns the mean.
* @example
*
* _.mean([4, 2, 8, 6]);
* // => 5
*/
function mean(array) {
return baseMean(array, identity);
}
/**
* This method is like `_.mean` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the value to be averaged.
* The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.7.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the mean.
* @example
*
* var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
*
* _.meanBy(objects, function(o) { return o.n; });
* // => 5
*
* // The `_.property` iteratee shorthand.
* _.meanBy(objects, 'n');
* // => 5
*/
function meanBy(array, iteratee) {
return baseMean(array, getIteratee(iteratee, 2));
}
/**
* Computes the minimum value of `array`. If `array` is empty or falsey,
* `undefined` is returned.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Math
* @param {Array} array The array to iterate over.
* @returns {*} Returns the minimum value.
* @example
*
* _.min([4, 2, 8, 6]);
* // => 2
*
* _.min([]);
* // => undefined
*/
function min(array) {
return (array && array.length)
? baseExtremum(array, identity, baseLt)
: undefined;
}
/**
* This method is like `_.min` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the criterion by which
* the value is ranked. 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 {*} Returns the minimum value.
* @example
*
* var objects = [{ 'n': 1 }, { 'n': 2 }];
*
* _.minBy(objects, function(o) { return o.n; });
* // => { 'n': 1 }
*
* // The `_.property` iteratee shorthand.
* _.minBy(objects, 'n');
* // => { 'n': 1 }
*/
function minBy(array, iteratee) {
return (array && array.length)
? baseExtremum(array, getIteratee(iteratee, 2), baseLt)
: undefined;
}
/**
* Multiply two numbers.
*
* @static
* @memberOf _
* @since 4.7.0
* @category Math
* @param {number} multiplier The first number in a multiplication.
* @param {number} multiplicand The second number in a multiplication.
* @returns {number} Returns the product.
* @example
*
* _.multiply(6, 4);
* // => 24
*/
var multiply = createMathOperation(function(multiplier, multiplicand) {
return multiplier * multiplicand;
}, 1);
/**
* Computes `number` rounded to `precision`.
*
* @static
* @memberOf _
* @since 3.10.0
* @category Math
* @param {number} number The number to round.
* @param {number} [precision=0] The precision to round to.
* @returns {number} Returns the rounded number.
* @example
*
* _.round(4.006);
* // => 4
*
* _.round(4.006, 2);
* // => 4.01
*
* _.round(4060, -2);
* // => 4100
*/
var round = createRound('round');
/**
* Subtract two numbers.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {number} minuend The first number in a subtraction.
* @param {number} subtrahend The second number in a subtraction.
* @returns {number} Returns the difference.
* @example
*
* _.subtract(6, 4);
* // => 2
*/
var subtract = createMathOperation(function(minuend, subtrahend) {
return minuend - subtrahend;
}, 0);
/**
* Computes the sum of the values in `array`.
*
* @static
* @memberOf _
* @since 3.4.0
* @category Math
* @param {Array} array The array to iterate over.
* @returns {number} Returns the sum.
* @example
*
* _.sum([4, 2, 8, 6]);
* // => 20
*/
function sum(array) {
return (array && array.length)
? baseSum(array, identity)
: 0;
}
/**
* 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, getIteratee(iteratee, 2))
: 0;
}
/*------------------------------------------------------------------------*/
// Add methods that return wrapped values in chain sequences.
lodash.after = after;
lodash.ary = ary;
lodash.assign = assign;
lodash.assignIn = assignIn;
lodash.assignInWith = assignInWith;
lodash.assignWith = assignWith;
lodash.at = at;
lodash.before = before;
lodash.bind = bind;
lodash.bindAll = bindAll;
lodash.bindKey = bindKey;
lodash.castArray = castArray;
lodash.chain = chain;
lodash.chunk = chunk;
lodash.compact = compact;
lodash.concat = concat;
lodash.cond = cond;
lodash.conforms = conforms;
lodash.constant = constant;
lodash.countBy = countBy;
lodash.create = create;
lodash.curry = curry;
lodash.curryRight = curryRight;
lodash.debounce = debounce;
lodash.defaults = defaults;
lodash.defaultsDeep = defaultsDeep;
lodash.defer = defer;
lodash.delay = delay;
lodash.difference = difference;
lodash.differenceBy = differenceBy;
lodash.differenceWith = differenceWith;
lodash.drop = drop;
lodash.dropRight = dropRight;
lodash.dropRightWhile = dropRightWhile;
lodash.dropWhile = dropWhile;
lodash.fill = fill;
lodash.filter = filter;
lodash.flatMap = flatMap;
lodash.flatMapDeep = flatMapDeep;
lodash.flatMapDepth = flatMapDepth;
lodash.flatten = flatten;
lodash.flattenDeep = flattenDeep;
lodash.flattenDepth = flattenDepth;
lodash.flip = flip;
lodash.flow = flow;
lodash.flowRight = flowRight;
lodash.fromPairs = fromPairs;
lodash.functions = functions;
lodash.functionsIn = functionsIn;
lodash.groupBy = groupBy;
lodash.initial = initial;
lodash.intersection = intersection;
lodash.intersectionBy = intersectionBy;
lodash.intersectionWith = intersectionWith;
lodash.invert = invert;
lodash.invertBy = invertBy;
lodash.invokeMap = invokeMap;
lodash.iteratee = iteratee;
lodash.keyBy = keyBy;
lodash.keys = keys;
lodash.keysIn = keysIn;
lodash.map = map;
lodash.mapKeys = mapKeys;
lodash.mapValues = mapValues;
lodash.matches = matches;
lodash.matchesProperty = matchesProperty;
lodash.memoize = memoize;
lodash.merge = merge;
lodash.mergeWith = mergeWith;
lodash.method = method;
lodash.methodOf = methodOf;
lodash.mixin = mixin;
lodash.negate = negate;
lodash.nthArg = nthArg;
lodash.omit = omit;
lodash.omitBy = omitBy;
lodash.once = once;
lodash.orderBy = orderBy;
lodash.over = over;
lodash.overArgs = overArgs;
lodash.overEvery = overEvery;
lodash.overSome = overSome;
lodash.partial = partial;
lodash.partialRight = partialRight;
lodash.partition = partition;
lodash.pick = pick;
lodash.pickBy = pickBy;
lodash.property = property;
lodash.propertyOf = propertyOf;
lodash.pull = pull;
lodash.pullAll = pullAll;
lodash.pullAllBy = pullAllBy;
lodash.pullAllWith = pullAllWith;
lodash.pullAt = pullAt;
lodash.range = range;
lodash.rangeRight = rangeRight;
lodash.rearg = rearg;
lodash.reject = reject;
lodash.remove = remove;
lodash.rest = rest;
lodash.reverse = reverse;
lodash.sampleSize = sampleSize;
lodash.set = set;
lodash.setWith = setWith;
lodash.shuffle = shuffle;
lodash.slice = slice;
lodash.sortBy = sortBy;
lodash.sortedUniq = sortedUniq;
lodash.sortedUniqBy = sortedUniqBy;
lodash.split = split;
lodash.spread = spread;
lodash.tail = tail;
lodash.take = take;
lodash.takeRight = takeRight;
lodash.takeRightWhile = takeRightWhile;
lodash.takeWhile = takeWhile;
lodash.tap = tap;
lodash.throttle = throttle;
lodash.thru = thru;
lodash.toArray = toArray;
lodash.toPairs = toPairs;
lodash.toPairsIn = toPairsIn;
lodash.toPath = toPath;
lodash.toPlainObject = toPlainObject;
lodash.transform = transform;
lodash.unary = unary;
lodash.union = union;
lodash.unionBy = unionBy;
lodash.unionWith = unionWith;
lodash.uniq = uniq;
lodash.uniqBy = uniqBy;
lodash.uniqWith = uniqWith;
lodash.unset = unset;
lodash.unzip = unzip;
lodash.unzipWith = unzipWith;
lodash.update = update;
lodash.updateWith = updateWith;
lodash.values = values;
lodash.valuesIn = valuesIn;
lodash.without = without;
lodash.words = words;
lodash.wrap = wrap;
lodash.xor = xor;
lodash.xorBy = xorBy;
lodash.xorWith = xorWith;
lodash.zip = zip;
lodash.zipObject = zipObject;
lodash.zipObjectDeep = zipObjectDeep;
lodash.zipWith = zipWith;
// Add aliases.
lodash.entries = toPairs;
lodash.entriesIn = toPairsIn;
lodash.extend = assignIn;
lodash.extendWith = assignInWith;
// Add methods to `lodash.prototype`.
mixin(lodash, lodash);
/*------------------------------------------------------------------------*/
// Add methods that return unwrapped values in chain sequences.
lodash.add = add;
lodash.attempt = attempt;
lodash.camelCase = camelCase;
lodash.capitalize = capitalize;
lodash.ceil = ceil;
lodash.clamp = clamp;
lodash.clone = clone;
lodash.cloneDeep = cloneDeep;
lodash.cloneDeepWith = cloneDeepWith;
lodash.cloneWith = cloneWith;
lodash.conformsTo = conformsTo;
lodash.deburr = deburr;
lodash.defaultTo = defaultTo;
lodash.divide = divide;
lodash.endsWith = endsWith;
lodash.eq = eq;
lodash.escape = escape;
lodash.escapeRegExp = escapeRegExp;
lodash.every = every;
lodash.find = find;
lodash.findIndex = findIndex;
lodash.findKey = findKey;
lodash.findLast = findLast;
lodash.findLastIndex = findLastIndex;
lodash.findLastKey = findLastKey;
lodash.floor = floor;
lodash.forEach = forEach;
lodash.forEachRight = forEachRight;
lodash.forIn = forIn;
lodash.forInRight = forInRight;
lodash.forOwn = forOwn;
lodash.forOwnRight = forOwnRight;
lodash.get = get;
lodash.gt = gt;
lodash.gte = gte;
lodash.has = has;
lodash.hasIn = hasIn;
lodash.head = head;
lodash.identity = identity;
lodash.includes = includes;
lodash.indexOf = indexOf;
lodash.inRange = inRange;
lodash.invoke = invoke;
lodash.isArguments = isArguments;
lodash.isArray = isArray;
lodash.isArrayBuffer = isArrayBuffer;
lodash.isArrayLike = isArrayLike;
lodash.isArrayLikeObject = isArrayLikeObject;
lodash.isBoolean = isBoolean;
lodash.isBuffer = isBuffer;
lodash.isDate = isDate;
lodash.isElement = isElement;
lodash.isEmpty = isEmpty;
lodash.isEqual = isEqual;
lodash.isEqualWith = isEqualWith;
lodash.isError = isError;
lodash.isFinite = isFinite;
lodash.isFunction = isFunction;
lodash.isInteger = isInteger;
lodash.isLength = isLength;
lodash.isMap = isMap;
lodash.isMatch = isMatch;
lodash.isMatchWith = isMatchWith;
lodash.isNaN = isNaN;
lodash.isNative = isNative;
lodash.isNil = isNil;
lodash.isNull = isNull;
lodash.isNumber = isNumber;
lodash.isObject = isObject;
lodash.isObjectLike = isObjectLike;
lodash.isPlainObject = isPlainObject;
lodash.isRegExp = isRegExp;
lodash.isSafeInteger = isSafeInteger;
lodash.isSet = isSet;
lodash.isString = isString;
lodash.isSymbol = isSymbol;
lodash.isTypedArray = isTypedArray;
lodash.isUndefined = isUndefined;
lodash.isWeakMap = isWeakMap;
lodash.isWeakSet = isWeakSet;
lodash.join = join;
lodash.kebabCase = kebabCase;
lodash.last = last;
lodash.lastIndexOf = lastIndexOf;
lodash.lowerCase = lowerCase;
lodash.lowerFirst = lowerFirst;
lodash.lt = lt;
lodash.lte = lte;
lodash.max = max;
lodash.maxBy = maxBy;
lodash.mean = mean;
lodash.meanBy = meanBy;
lodash.min = min;
lodash.minBy = minBy;
lodash.stubArray = stubArray;
lodash.stubFalse = stubFalse;
lodash.stubObject = stubObject;
lodash.stubString = stubString;
lodash.stubTrue = stubTrue;
lodash.multiply = multiply;
lodash.nth = nth;
lodash.noConflict = noConflict;
lodash.noop = noop;
lodash.now = now;
lodash.pad = pad;
lodash.padEnd = padEnd;
lodash.padStart = padStart;
lodash.parseInt = parseInt;
lodash.random = random;
lodash.reduce = reduce;
lodash.reduceRight = reduceRight;
lodash.repeat = repeat;
lodash.replace = replace;
lodash.result = result;
lodash.round = round;
lodash.runInContext = runInContext;
lodash.sample = sample;
lodash.size = size;
lodash.snakeCase = snakeCase;
lodash.some = some;
lodash.sortedIndex = sortedIndex;
lodash.sortedIndexBy = sortedIndexBy;
lodash.sortedIndexOf = sortedIndexOf;
lodash.sortedLastIndex = sortedLastIndex;
lodash.sortedLastIndexBy = sortedLastIndexBy;
lodash.sortedLastIndexOf = sortedLastIndexOf;
lodash.startCase = startCase;
lodash.startsWith = startsWith;
lodash.subtract = subtract;
lodash.sum = sum;
lodash.sumBy = sumBy;
lodash.template = template;
lodash.times = times;
lodash.toFinite = toFinite;
lodash.toInteger = toInteger;
lodash.toLength = toLength;
lodash.toLower = toLower;
lodash.toNumber = toNumber;
lodash.toSafeInteger = toSafeInteger;
lodash.toString = toString;
lodash.toUpper = toUpper;
lodash.trim = trim;
lodash.trimEnd = trimEnd;
lodash.trimStart = trimStart;
lodash.truncate = truncate;
lodash.unescape = unescape;
lodash.uniqueId = uniqueId;
lodash.upperCase = upperCase;
lodash.upperFirst = upperFirst;
// Add aliases.
lodash.each = forEach;
lodash.eachRight = forEachRight;
lodash.first = head;
mixin(lodash, (function() {
var source = {};
baseForOwn(lodash, function(func, methodName) {
if (!hasOwnProperty.call(lodash.prototype, methodName)) {
source[methodName] = func;
}
});
return source;
}()), { 'chain': false });
/*------------------------------------------------------------------------*/
/**
* The semantic version number.
*
* @static
* @memberOf _
* @type {string}
*/
lodash.VERSION = VERSION;
// Assign default placeholders.
arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) {
lodash[methodName].placeholder = lodash;
});
// Add `LazyWrapper` methods for `_.drop` and `_.take` variants.
arrayEach(['drop', 'take'], function(methodName, index) {
LazyWrapper.prototype[methodName] = function(n) {
n = n === undefined ? 1 : nativeMax(toInteger(n), 0);
var result = (this.__filtered__ && !index)
? new LazyWrapper(this)
: this.clone();
if (result.__filtered__) {
result.__takeCount__ = nativeMin(n, result.__takeCount__);
} else {
result.__views__.push({
'size': nativeMin(n, MAX_ARRAY_LENGTH),
'type': methodName + (result.__dir__ < 0 ? 'Right' : '')
});
}
return result;
};
LazyWrapper.prototype[methodName + 'Right'] = function(n) {
return this.reverse()[methodName](n).reverse();
};
});
// Add `LazyWrapper` methods that accept an `iteratee` value.
arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) {
var type = index + 1,
isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG;
LazyWrapper.prototype[methodName] = function(iteratee) {
var result = this.clone();
result.__iteratees__.push({
'iteratee': getIteratee(iteratee, 3),
'type': type
});
result.__filtered__ = result.__filtered__ || isFilter;
return result;
};
});
// Add `LazyWrapper` methods for `_.head` and `_.last`.
arrayEach(['head', 'last'], function(methodName, index) {
var takeName = 'take' + (index ? 'Right' : '');
LazyWrapper.prototype[methodName] = function() {
return this[takeName](1).value()[0];
};
});
// Add `LazyWrapper` methods for `_.initial` and `_.tail`.
arrayEach(['initial', 'tail'], function(methodName, index) {
var dropName = 'drop' + (index ? '' : 'Right');
LazyWrapper.prototype[methodName] = function() {
return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1);
};
});
LazyWrapper.prototype.compact = function() {
return this.filter(identity);
};
LazyWrapper.prototype.find = function(predicate) {
return this.filter(predicate).head();
};
LazyWrapper.prototype.findLast = function(predicate) {
return this.reverse().find(predicate);
};
LazyWrapper.prototype.invokeMap = baseRest(function(path, args) {
if (typeof path == 'function') {
return new LazyWrapper(this);
}
return this.map(function(value) {
return baseInvoke(value, path, args);
});
});
LazyWrapper.prototype.reject = function(predicate) {
return this.filter(negate(getIteratee(predicate)));
};
LazyWrapper.prototype.slice = function(start, end) {
start = toInteger(start);
var result = this;
if (result.__filtered__ && (start > 0 || end < 0)) {
return new LazyWrapper(result);
}
if (start < 0) {
result = result.takeRight(-start);
} else if (start) {
result = result.drop(start);
}
if (end !== undefined) {
end = toInteger(end);
result = end < 0 ? result.dropRight(-end) : result.take(end - start);
}
return result;
};
LazyWrapper.prototype.takeRightWhile = function(predicate) {
return this.reverse().takeWhile(predicate).reverse();
};
LazyWrapper.prototype.toArray = function() {
return this.take(MAX_ARRAY_LENGTH);
};
// Add `LazyWrapper` methods to `lodash.prototype`.
baseForOwn(LazyWrapper.prototype, function(func, methodName) {
var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName),
isTaker = /^(?:head|last)$/.test(methodName),
lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName],
retUnwrapped = isTaker || /^find/.test(methodName);
if (!lodashFunc) {
return;
}
lodash.prototype[methodName] = function() {
var value = this.__wrapped__,
args = isTaker ? [1] : arguments,
isLazy = value instanceof LazyWrapper,
iteratee = args[0],
useLazy = isLazy || isArray(value);
var interceptor = function(value) {
var result = lodashFunc.apply(lodash, arrayPush([value], args));
return (isTaker && chainAll) ? result[0] : result;
};
if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
// Avoid lazy use if the iteratee has a "length" value other than `1`.
isLazy = useLazy = false;
}
var chainAll = this.__chain__,
isHybrid = !!this.__actions__.length,
isUnwrapped = retUnwrapped && !chainAll,
onlyLazy = isLazy && !isHybrid;
if (!retUnwrapped && useLazy) {
value = onlyLazy ? value : new LazyWrapper(this);
var result = func.apply(value, args);
result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
return new LodashWrapper(result, chainAll);
}
if (isUnwrapped && onlyLazy) {
return func.apply(this, args);
}
result = this.thru(interceptor);
return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
};
});
// Add `Array` methods to `lodash.prototype`.
arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) {
var func = arrayProto[methodName],
chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru',
retUnwrapped = /^(?:pop|shift)$/.test(methodName);
lodash.prototype[methodName] = function() {
var args = arguments;
if (retUnwrapped && !this.__chain__) {
var value = this.value();
return func.apply(isArray(value) ? value : [], args);
}
return this[chainName](function(value) {
return func.apply(isArray(value) ? value : [], args);
});
};
});
// Map minified method names to their real names.
baseForOwn(LazyWrapper.prototype, function(func, methodName) {
var lodashFunc = lodash[methodName];
if (lodashFunc) {
var key = lodashFunc.name + '';
if (!hasOwnProperty.call(realNames, key)) {
realNames[key] = [];
}
realNames[key].push({ 'name': methodName, 'func': lodashFunc });
}
});
realNames[createHybrid(undefined, WRAP_BIND_KEY_FLAG).name] = [{
'name': 'wrapper',
'func': undefined
}];
// Add methods to `LazyWrapper`.
LazyWrapper.prototype.clone = lazyClone;
LazyWrapper.prototype.reverse = lazyReverse;
LazyWrapper.prototype.value = lazyValue;
// Add chain sequence methods to the `lodash` wrapper.
lodash.prototype.at = wrapperAt;
lodash.prototype.chain = wrapperChain;
lodash.prototype.commit = wrapperCommit;
lodash.prototype.next = wrapperNext;
lodash.prototype.plant = wrapperPlant;
lodash.prototype.reverse = wrapperReverse;
lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue;
// Add lazy aliases.
lodash.prototype.first = lodash.prototype.head;
if (symIterator) {
lodash.prototype[symIterator] = wrapperToIterator;
}
return lodash;
});
/*--------------------------------------------------------------------------*/
// Export lodash.
var _ = runInContext();
// Some AMD build optimizers, like r.js, check for condition patterns like:
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
// Expose Lodash on the global object to prevent errors when Lodash is
// loaded by a script tag in the presence of an AMD loader.
// See http://requirejs.org/docs/errors.html#mismatch for more details.
// Use `_.noConflict` to remove Lodash from the global object.
root._ = _;
// Define as an anonymous module so, through path mapping, it can be
// referenced as the "underscore" module.
define(function() {
return _;
});
}
// Check for `exports` after `define` in case a build optimizer adds it.
else if (freeModule) {
// Export for Node.js.
(freeModule.exports = _)._ = _;
// Export for CommonJS support.
freeExports._ = _;
}
else {
// Export to the global object.
root._ = _;
}
}.call(this));
webpack://frontend-mybets/../../node_modules/lodash/map.js
var arrayMap = require('./_arrayMap'),
baseIteratee = require('./_baseIteratee'),
baseMap = require('./_baseMap'),
isArray = require('./isArray');
/**
* Creates an array of values by running each element in `collection` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
*
* The guarded methods are:
* `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
* `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
* `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
* `template`, `trim`, `trimEnd`, `trimStart`, and `words`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
* @example
*
* function square(n) {
* return n * n;
* }
*
* _.map([4, 8], square);
* // => [16, 64]
*
* _.map({ 'a': 4, 'b': 8 }, square);
* // => [16, 64] (iteration order is not guaranteed)
*
* var users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
*
* // The `_.property` iteratee shorthand.
* _.map(users, 'user');
* // => ['barney', 'fred']
*/
function map(collection, iteratee) {
var func = isArray(collection) ? arrayMap : baseMap;
return func(collection, baseIteratee(iteratee, 3));
}
module.exports = map;
webpack://frontend-mybets/../../node_modules/lodash/memoize.js
var MapCache = require('./_MapCache');
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided, it determines the cache key for storing the result based on the
* arguments provided to the memoized function. By default, the first argument
* provided to the memoized function is used as the map cache key. The `func`
* is invoked with the `this` binding of the memoized function.
*
* **Note:** The cache is exposed as the `cache` property on the memoized
* function. Its creation may be customized by replacing the `_.memoize.Cache`
* constructor with one whose instances implement the
* [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
* method interface of `clear`, `delete`, `get`, `has`, and `set`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] The function to resolve the cache key.
* @returns {Function} Returns the new memoized function.
* @example
*
* var object = { 'a': 1, 'b': 2 };
* var other = { 'c': 3, 'd': 4 };
*
* var values = _.memoize(_.values);
* values(object);
* // => [1, 2]
*
* values(other);
* // => [3, 4]
*
* object.a = 2;
* values(object);
* // => [1, 2]
*
* // Modify the result cache.
* values.cache.set(object, ['a', 'b']);
* values(object);
* // => ['a', 'b']
*
* // Replace `_.memoize.Cache`.
* _.memoize.Cache = WeakMap;
*/
function memoize(func, resolver) {
if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
throw new TypeError(FUNC_ERROR_TEXT);
}
var memoized = function() {
var args = arguments,
key = resolver ? resolver.apply(this, args) : args[0],
cache = memoized.cache;
if (cache.has(key)) {
return cache.get(key);
}
var result = func.apply(this, args);
memoized.cache = cache.set(key, result) || cache;
return result;
};
memoized.cache = new (memoize.Cache || MapCache);
return memoized;
}
// Expose `MapCache`.
memoize.Cache = MapCache;
module.exports = memoize;
webpack://frontend-mybets/../../node_modules/lodash/merge.js
var baseMerge = require('./_baseMerge'),
createAssigner = require('./_createAssigner');
/**
* This method is like `_.assign` except that it recursively merges own and
* inherited enumerable string keyed properties of source objects into the
* destination object. Source properties that resolve to `undefined` are
* skipped if a destination value exists. Array and plain object properties
* are merged recursively. Other objects and value types are overridden by
* assignment. Source objects are applied from left to right. Subsequent
* sources overwrite property assignments of previous sources.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 0.5.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @example
*
* var object = {
* 'a': [{ 'b': 2 }, { 'd': 4 }]
* };
*
* var other = {
* 'a': [{ 'c': 3 }, { 'e': 5 }]
* };
*
* _.merge(object, other);
* // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
*/
var merge = createAssigner(function(object, source, srcIndex) {
baseMerge(object, source, srcIndex);
});
module.exports = merge;
webpack://frontend-mybets/../../node_modules/lodash/negate.js
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* Creates a function that negates the result of the predicate `func`. The
* `func` predicate is invoked with the `this` binding and arguments of the
* created function.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} predicate The predicate to negate.
* @returns {Function} Returns the new negated function.
* @example
*
* function isEven(n) {
* return n % 2 == 0;
* }
*
* _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
* // => [1, 3, 5]
*/
function negate(predicate) {
if (typeof predicate != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
return function() {
var args = arguments;
switch (args.length) {
case 0: return !predicate.call(this);
case 1: return !predicate.call(this, args[0]);
case 2: return !predicate.call(this, args[0], args[1]);
case 3: return !predicate.call(this, args[0], args[1], args[2]);
}
return !predicate.apply(this, args);
};
}
module.exports = negate;
webpack://frontend-mybets/../../node_modules/lodash/noop.js
/**
* This method returns `undefined`.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Util
* @example
*
* _.times(2, _.noop);
* // => [undefined, undefined]
*/
function noop() {
// No operation performed.
}
module.exports = noop;
webpack://frontend-mybets/../../node_modules/lodash/now.js
var root = require('./_root');
/**
* Gets the timestamp of the number of milliseconds that have elapsed since
* the Unix epoch (1 January 1970 00:00:00 UTC).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Date
* @returns {number} Returns the timestamp.
* @example
*
* _.defer(function(stamp) {
* console.log(_.now() - stamp);
* }, _.now());
* // => Logs the number of milliseconds it took for the deferred invocation.
*/
var now = function() {
return root.Date.now();
};
module.exports = now;
webpack://frontend-mybets/../../node_modules/lodash/omit.js
var arrayMap = require('./_arrayMap'),
baseClone = require('./_baseClone'),
baseUnset = require('./_baseUnset'),
castPath = require('./_castPath'),
copyObject = require('./_copyObject'),
customOmitClone = require('./_customOmitClone'),
flatRest = require('./_flatRest'),
getAllKeysIn = require('./_getAllKeysIn');
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
CLONE_FLAT_FLAG = 2,
CLONE_SYMBOLS_FLAG = 4;
/**
* The opposite of `_.pick`; this method creates an object composed of the
* own and inherited enumerable property paths of `object` that are not omitted.
*
* **Note:** This method is considerably slower than `_.pick`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to omit.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.omit(object, ['a', 'c']);
* // => { 'b': '2' }
*/
var omit = flatRest(function(object, paths) {
var result = {};
if (object == null) {
return result;
}
var isDeep = false;
paths = arrayMap(paths, function(path) {
path = castPath(path, object);
isDeep || (isDeep = path.length > 1);
return path;
});
copyObject(object, getAllKeysIn(object), result);
if (isDeep) {
result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);
}
var length = paths.length;
while (length--) {
baseUnset(result, paths[length]);
}
return result;
});
module.exports = omit;
webpack://frontend-mybets/../../node_modules/lodash/omitBy.js
var baseIteratee = require('./_baseIteratee'),
negate = require('./negate'),
pickBy = require('./pickBy');
/**
* The opposite of `_.pickBy`; this method creates an object composed of
* the own and inherited enumerable string keyed properties of `object` that
* `predicate` doesn't return 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 };
*
* _.omitBy(object, _.isNumber);
* // => { 'b': '2' }
*/
function omitBy(object, predicate) {
return pickBy(object, negate(baseIteratee(predicate)));
}
module.exports = omitBy;
webpack://frontend-mybets/../../node_modules/lodash/orderBy.js
var baseOrderBy = require('./_baseOrderBy'),
isArray = require('./isArray');
/**
* This method is like `_.sortBy` except that it allows specifying the sort
* orders of the iteratees to sort by. If `orders` is unspecified, all values
* are sorted in ascending order. Otherwise, specify an order of "desc" for
* descending or "asc" for ascending sort order of corresponding values.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]
* The iteratees to sort by.
* @param {string[]} [orders] The sort orders of `iteratees`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 48 },
* { 'user': 'barney', 'age': 34 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'barney', 'age': 36 }
* ];
*
* // Sort by `user` in ascending order and by `age` in descending order.
* _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
* // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
*/
function orderBy(collection, iteratees, orders, guard) {
if (collection == null) {
return [];
}
if (!isArray(iteratees)) {
iteratees = iteratees == null ? [] : [iteratees];
}
orders = guard ? undefined : orders;
if (!isArray(orders)) {
orders = orders == null ? [] : [orders];
}
return baseOrderBy(collection, iteratees, orders);
}
module.exports = orderBy;
webpack://frontend-mybets/../../node_modules/lodash/pickBy.js
var arrayMap = require('./_arrayMap'),
baseIteratee = require('./_baseIteratee'),
basePickBy = require('./_basePickBy'),
getAllKeysIn = require('./_getAllKeysIn');
/**
* Creates an object composed of the `object` properties `predicate` returns
* truthy for. The predicate is invoked with two arguments: (value, key).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The source object.
* @param {Function} [predicate=_.identity] The function invoked per property.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pickBy(object, _.isNumber);
* // => { 'a': 1, 'c': 3 }
*/
function pickBy(object, predicate) {
if (object == null) {
return {};
}
var props = arrayMap(getAllKeysIn(object), function(prop) {
return [prop];
});
predicate = baseIteratee(predicate);
return basePickBy(object, props, function(value, path) {
return predicate(value, path[0]);
});
}
module.exports = pickBy;
webpack://frontend-mybets/../../node_modules/lodash/property.js
var baseProperty = require('./_baseProperty'),
basePropertyDeep = require('./_basePropertyDeep'),
isKey = require('./_isKey'),
toKey = require('./_toKey');
/**
* Creates a function that returns the value at `path` of a given object.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
* @example
*
* var objects = [
* { 'a': { 'b': 2 } },
* { 'a': { 'b': 1 } }
* ];
*
* _.map(objects, _.property('a.b'));
* // => [2, 1]
*
* _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
* // => [1, 2]
*/
function property(path) {
return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
}
module.exports = property;
webpack://frontend-mybets/../../node_modules/lodash/range.js
var createRange = require('./_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();
module.exports = range;
webpack://frontend-mybets/../../node_modules/lodash/rearg.js
var createWrap = require('./_createWrap'),
flatRest = require('./_flatRest');
/** Used to compose bitmasks for function metadata. */
var WRAP_REARG_FLAG = 256;
/**
* Creates a function that invokes `func` with arguments arranged according
* to the specified `indexes` where the argument value at the first index is
* provided as the first argument, the argument value at the second index is
* provided as the second argument, and so on.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} func The function to rearrange arguments for.
* @param {...(number|number[])} indexes The arranged argument indexes.
* @returns {Function} Returns the new function.
* @example
*
* var rearged = _.rearg(function(a, b, c) {
* return [a, b, c];
* }, [2, 0, 1]);
*
* rearged('b', 'c', 'a')
* // => ['a', 'b', 'c']
*/
var rearg = flatRest(function(func, indexes) {
return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes);
});
module.exports = rearg;
webpack://frontend-mybets/../../node_modules/lodash/replace.js
var toString = require('./toString');
/**
* Replaces matches for `pattern` in `string` with `replacement`.
*
* **Note:** This method is based on
* [`String#replace`](https://mdn.io/String/replace).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to modify.
* @param {RegExp|string} pattern The pattern to replace.
* @param {Function|string} replacement The match replacement.
* @returns {string} Returns the modified string.
* @example
*
* _.replace('Hi Fred', 'Fred', 'Barney');
* // => 'Hi Barney'
*/
function replace() {
var args = arguments,
string = toString(args[0]);
return args.length < 3 ? string : string.replace(args[1], args[2]);
}
module.exports = replace;
webpack://frontend-mybets/../../node_modules/lodash/reverse.js
/** Used for built-in method references. */
var arrayProto = Array.prototype;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeReverse = arrayProto.reverse;
/**
* Reverses `array` so that the first element becomes the last, the second
* element becomes the second to last, and so on.
*
* **Note:** This method mutates `array` and is based on
* [`Array#reverse`](https://mdn.io/Array/reverse).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to modify.
* @returns {Array} Returns `array`.
* @example
*
* var array = [1, 2, 3];
*
* _.reverse(array);
* // => [3, 2, 1]
*
* console.log(array);
* // => [3, 2, 1]
*/
function reverse(array) {
return array == null ? array : nativeReverse.call(array);
}
module.exports = reverse;
webpack://frontend-mybets/../../node_modules/lodash/set.js
var baseSet = require('./_baseSet');
/**
* Sets the value at `path` of `object`. If a portion of `path` doesn't exist,
* it's created. Arrays are created for missing index properties while objects
* are created for all other missing properties. Use `_.setWith` to customize
* `path` creation.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @returns {Object} Returns `object`.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.set(object, 'a[0].b.c', 4);
* console.log(object.a[0].b.c);
* // => 4
*
* _.set(object, ['x', '0', 'y', 'z'], 5);
* console.log(object.x[0].y.z);
* // => 5
*/
function set(object, path, value) {
return object == null ? object : baseSet(object, path, value);
}
module.exports = set;
webpack://frontend-mybets/../../node_modules/lodash/size.js
var baseKeys = require('./_baseKeys'),
getTag = require('./_getTag'),
isArrayLike = require('./isArrayLike'),
isString = require('./isString'),
stringSize = require('./_stringSize');
/** `Object#toString` result references. */
var mapTag = '[object Map]',
setTag = '[object Set]';
/**
* Gets the size of `collection` by returning its length for array-like
* values or the number of own enumerable string keyed properties for objects.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @returns {number} Returns the collection size.
* @example
*
* _.size([1, 2, 3]);
* // => 3
*
* _.size({ 'a': 1, 'b': 2 });
* // => 2
*
* _.size('pebbles');
* // => 7
*/
function size(collection) {
if (collection == null) {
return 0;
}
if (isArrayLike(collection)) {
return isString(collection) ? stringSize(collection) : collection.length;
}
var tag = getTag(collection);
if (tag == mapTag || tag == setTag) {
return collection.size;
}
return baseKeys(collection).length;
}
module.exports = size;
webpack://frontend-mybets/../../node_modules/lodash/some.js
var arraySome = require('./_arraySome'),
baseIteratee = require('./_baseIteratee'),
baseSome = require('./_baseSome'),
isArray = require('./isArray'),
isIterateeCall = require('./_isIterateeCall');
/**
* Checks if `predicate` returns truthy for **any** element of `collection`.
* Iteration is stopped once `predicate` returns truthy. 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 iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
* @example
*
* _.some([null, 0, 'yes', false], Boolean);
* // => true
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.some(users, { 'user': 'barney', 'active': false });
* // => false
*
* // The `_.matchesProperty` iteratee shorthand.
* _.some(users, ['active', false]);
* // => true
*
* // The `_.property` iteratee shorthand.
* _.some(users, 'active');
* // => true
*/
function some(collection, predicate, guard) {
var func = isArray(collection) ? arraySome : baseSome;
if (guard && isIterateeCall(collection, predicate, guard)) {
predicate = undefined;
}
return func(collection, baseIteratee(predicate, 3));
}
module.exports = some;
webpack://frontend-mybets/../../node_modules/lodash/sortBy.js
var baseFlatten = require('./_baseFlatten'),
baseOrderBy = require('./_baseOrderBy'),
baseRest = require('./_baseRest'),
isIterateeCall = require('./_isIterateeCall');
/**
* Creates an array of elements, sorted in ascending order by the results of
* running each element in a collection thru each iteratee. This method
* performs a stable sort, that is, it preserves the original sort order of
* equal elements. The iteratees are invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {...(Function|Function[])} [iteratees=[_.identity]]
* The iteratees to sort by.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 48 },
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 30 },
* { 'user': 'barney', 'age': 34 }
* ];
*
* _.sortBy(users, [function(o) { return o.user; }]);
* // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]
*
* _.sortBy(users, ['user', 'age']);
* // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]
*/
var sortBy = baseRest(function(collection, iteratees) {
if (collection == null) {
return [];
}
var length = iteratees.length;
if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {
iteratees = [];
} else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
iteratees = [iteratees[0]];
}
return baseOrderBy(collection, baseFlatten(iteratees, 1), []);
});
module.exports = sortBy;
webpack://frontend-mybets/../../node_modules/lodash/startCase.js
var createCompounder = require('./_createCompounder'),
upperFirst = require('./upperFirst');
/**
* Converts `string` to
* [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
*
* @static
* @memberOf _
* @since 3.1.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the start cased string.
* @example
*
* _.startCase('--foo-bar--');
* // => 'Foo Bar'
*
* _.startCase('fooBar');
* // => 'Foo Bar'
*
* _.startCase('__FOO_BAR__');
* // => 'FOO BAR'
*/
var startCase = createCompounder(function(result, word, index) {
return result + (index ? ' ' : '') + upperFirst(word);
});
module.exports = startCase;
webpack://frontend-mybets/../../node_modules/lodash/stubArray.js
/**
* This method returns a new empty array.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Array} Returns the new empty array.
* @example
*
* var arrays = _.times(2, _.stubArray);
*
* console.log(arrays);
* // => [[], []]
*
* console.log(arrays[0] === arrays[1]);
* // => false
*/
function stubArray() {
return [];
}
module.exports = stubArray;
webpack://frontend-mybets/../../node_modules/lodash/stubFalse.js
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/
function stubFalse() {
return false;
}
module.exports = stubFalse;
webpack://frontend-mybets/../../node_modules/lodash/throttle.js
var debounce = require('./debounce'),
isObject = require('./isObject');
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* Creates a throttled function that only invokes `func` at most once per
* every `wait` milliseconds. The throttled function comes with a `cancel`
* method to cancel delayed `func` invocations and a `flush` method to
* immediately invoke them. Provide `options` to indicate whether `func`
* should be invoked on the leading and/or trailing edge of the `wait`
* timeout. The `func` is invoked with the last arguments provided to the
* throttled function. Subsequent calls to the throttled function return the
* result of the last `func` invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the throttled function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.throttle` and `_.debounce`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to throttle.
* @param {number} [wait=0] The number of milliseconds to throttle invocations to.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=true]
* Specify invoking on the leading edge of the timeout.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new throttled function.
* @example
*
* // Avoid excessively updating the position while scrolling.
* jQuery(window).on('scroll', _.throttle(updatePosition, 100));
*
* // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
* var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
* jQuery(element).on('click', throttled);
*
* // Cancel the trailing throttled invocation.
* jQuery(window).on('popstate', throttled.cancel);
*/
function throttle(func, wait, options) {
var leading = true,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
if (isObject(options)) {
leading = 'leading' in options ? !!options.leading : leading;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
return debounce(func, wait, {
'leading': leading,
'maxWait': wait,
'trailing': trailing
});
}
module.exports = throttle;
webpack://frontend-mybets/../../node_modules/lodash/times.js
var baseTimes = require('./_baseTimes'),
castFunction = require('./_castFunction'),
toInteger = require('./toInteger');
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** Used as references for the maximum length and index of an array. */
var MAX_ARRAY_LENGTH = 4294967295;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;
/**
* Invokes the iteratee `n` times, returning an array of the results of
* each invocation. The iteratee is invoked with one argument; (index).
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the array of results.
* @example
*
* _.times(3, String);
* // => ['0', '1', '2']
*
* _.times(4, _.constant(0));
* // => [0, 0, 0, 0]
*/
function times(n, iteratee) {
n = toInteger(n);
if (n < 1 || n > MAX_SAFE_INTEGER) {
return [];
}
var index = MAX_ARRAY_LENGTH,
length = nativeMin(n, MAX_ARRAY_LENGTH);
iteratee = castFunction(iteratee);
n -= MAX_ARRAY_LENGTH;
var result = baseTimes(length, iteratee);
while (++index < n) {
iteratee(index);
}
return result;
}
module.exports = times;
webpack://frontend-mybets/../../node_modules/lodash/toFinite.js
var toNumber = require('./toNumber');
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0,
MAX_INTEGER = 1.7976931348623157e+308;
/**
* Converts `value` to a finite number.
*
* @static
* @memberOf _
* @since 4.12.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted number.
* @example
*
* _.toFinite(3.2);
* // => 3.2
*
* _.toFinite(Number.MIN_VALUE);
* // => 5e-324
*
* _.toFinite(Infinity);
* // => 1.7976931348623157e+308
*
* _.toFinite('3.2');
* // => 3.2
*/
function toFinite(value) {
if (!value) {
return value === 0 ? value : 0;
}
value = toNumber(value);
if (value === INFINITY || value === -INFINITY) {
var sign = (value < 0 ? -1 : 1);
return sign * MAX_INTEGER;
}
return value === value ? value : 0;
}
module.exports = toFinite;
webpack://frontend-mybets/../../node_modules/lodash/toInteger.js
var toFinite = require('./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(value),
remainder = result % 1;
return result === result ? (remainder ? result - remainder : result) : 0;
}
module.exports = toInteger;
webpack://frontend-mybets/../../node_modules/lodash/toNumber.js
var baseTrim = require('./_baseTrim'),
isObject = require('./isObject'),
isSymbol = require('./isSymbol');
/** Used as references for various `Number` constants. */
var NAN = 0 / 0;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
if (isObject(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = baseTrim(value);
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
module.exports = toNumber;
webpack://frontend-mybets/../../node_modules/lodash/toPairs.js
var createToPairs = require('./_createToPairs'),
keys = require('./keys');
/**
* Creates an array of own enumerable string keyed-value pairs for `object`
* which can be consumed by `_.fromPairs`. If `object` is a map or set, its
* entries are returned.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias entries
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the key-value pairs.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.toPairs(new Foo);
* // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)
*/
var toPairs = createToPairs(keys);
module.exports = toPairs;
webpack://frontend-mybets/../../node_modules/lodash/toPath.js
var arrayMap = require('./_arrayMap'),
copyArray = require('./_copyArray'),
isArray = require('./isArray'),
isSymbol = require('./isSymbol'),
stringToPath = require('./_stringToPath'),
toKey = require('./_toKey'),
toString = require('./toString');
/**
* Converts `value` to a property path array.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {*} value The value to convert.
* @returns {Array} Returns the new property path array.
* @example
*
* _.toPath('a.b.c');
* // => ['a', 'b', 'c']
*
* _.toPath('a[0].b.c');
* // => ['a', '0', 'b', 'c']
*/
function toPath(value) {
if (isArray(value)) {
return arrayMap(value, toKey);
}
return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value)));
}
module.exports = toPath;
webpack://frontend-mybets/../../node_modules/lodash/toPlainObject.js
var copyObject = require('./_copyObject'),
keysIn = require('./keysIn');
/**
* Converts `value` to a plain object flattening inherited enumerable string
* keyed properties of `value` to own properties of the plain object.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {Object} Returns the converted plain object.
* @example
*
* function Foo() {
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.assign({ 'a': 1 }, new Foo);
* // => { 'a': 1, 'b': 2 }
*
* _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
* // => { 'a': 1, 'b': 2, 'c': 3 }
*/
function toPlainObject(value) {
return copyObject(value, keysIn(value));
}
module.exports = toPlainObject;
webpack://frontend-mybets/../../node_modules/lodash/toString.js
var baseToString = require('./_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);
}
module.exports = toString;
webpack://frontend-mybets/../../node_modules/lodash/trim.js
var baseToString = require('./_baseToString'),
baseTrim = require('./_baseTrim'),
castSlice = require('./_castSlice'),
charsEndIndex = require('./_charsEndIndex'),
charsStartIndex = require('./_charsStartIndex'),
stringToArray = require('./_stringToArray'),
toString = require('./toString');
/**
* Removes leading and trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trim(' abc ');
* // => 'abc'
*
* _.trim('-_-abc-_-', '_-');
* // => 'abc'
*
* _.map([' foo ', ' bar '], _.trim);
* // => ['foo', 'bar']
*/
function trim(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return baseTrim(string);
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
chrSymbols = stringToArray(chars),
start = charsStartIndex(strSymbols, chrSymbols),
end = charsEndIndex(strSymbols, chrSymbols) + 1;
return castSlice(strSymbols, start, end).join('');
}
module.exports = trim;
webpack://frontend-mybets/../../node_modules/lodash/truncate.js
var baseToString = require('./_baseToString'),
castSlice = require('./_castSlice'),
hasUnicode = require('./_hasUnicode'),
isObject = require('./isObject'),
isRegExp = require('./isRegExp'),
stringSize = require('./_stringSize'),
stringToArray = require('./_stringToArray'),
toInteger = require('./toInteger'),
toString = require('./toString');
/** Used as default options for `_.truncate`. */
var DEFAULT_TRUNC_LENGTH = 30,
DEFAULT_TRUNC_OMISSION = '...';
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/**
* Truncates `string` if it's longer than the given maximum string length.
* The last characters of the truncated string are replaced with the omission
* string which defaults to "...".
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to truncate.
* @param {Object} [options={}] The options object.
* @param {number} [options.length=30] The maximum string length.
* @param {string} [options.omission='...'] The string to indicate text is omitted.
* @param {RegExp|string} [options.separator] The separator pattern to truncate to.
* @returns {string} Returns the truncated string.
* @example
*
* _.truncate('hi-diddly-ho there, neighborino');
* // => 'hi-diddly-ho there, neighbo...'
*
* _.truncate('hi-diddly-ho there, neighborino', {
* 'length': 24,
* 'separator': ' '
* });
* // => 'hi-diddly-ho there,...'
*
* _.truncate('hi-diddly-ho there, neighborino', {
* 'length': 24,
* 'separator': /,? +/
* });
* // => 'hi-diddly-ho there...'
*
* _.truncate('hi-diddly-ho there, neighborino', {
* 'omission': ' [...]'
* });
* // => 'hi-diddly-ho there, neig [...]'
*/
function truncate(string, options) {
var length = DEFAULT_TRUNC_LENGTH,
omission = DEFAULT_TRUNC_OMISSION;
if (isObject(options)) {
var separator = 'separator' in options ? options.separator : separator;
length = 'length' in options ? toInteger(options.length) : length;
omission = 'omission' in options ? baseToString(options.omission) : omission;
}
string = toString(string);
var strLength = string.length;
if (hasUnicode(string)) {
var strSymbols = stringToArray(string);
strLength = strSymbols.length;
}
if (length >= strLength) {
return string;
}
var end = length - stringSize(omission);
if (end < 1) {
return omission;
}
var result = strSymbols
? castSlice(strSymbols, 0, end).join('')
: string.slice(0, end);
if (separator === undefined) {
return result + omission;
}
if (strSymbols) {
end += (result.length - end);
}
if (isRegExp(separator)) {
if (string.slice(end).search(separator)) {
var match,
substring = result;
if (!separator.global) {
separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g');
}
separator.lastIndex = 0;
while ((match = separator.exec(substring))) {
var newEnd = match.index;
}
result = result.slice(0, newEnd === undefined ? end : newEnd);
}
} else if (string.indexOf(baseToString(separator), end) != end) {
var index = result.lastIndexOf(separator);
if (index > -1) {
result = result.slice(0, index);
}
}
return result + omission;
}
module.exports = truncate;
webpack://frontend-mybets/../../node_modules/lodash/uniqBy.js
var baseIteratee = require('./_baseIteratee'),
baseUniq = require('./_baseUniq');
/**
* This method is like `_.uniq` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the criterion by which
* uniqueness is computed. The order of result values is determined by the
* order they occur in the array. The iteratee is invoked with one argument:
* (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.uniqBy([2.1, 1.2, 2.3], Math.floor);
* // => [2.1, 1.2]
*
* // The `_.property` iteratee shorthand.
* _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }, { 'x': 2 }]
*/
function uniqBy(array, iteratee) {
return (array && array.length) ? baseUniq(array, baseIteratee(iteratee, 2)) : [];
}
module.exports = uniqBy;
webpack://frontend-mybets/../../node_modules/lodash/uniqWith.js
var baseUniq = require('./_baseUniq');
/**
* This method is like `_.uniq` except that it accepts `comparator` which
* is invoked to compare elements of `array`. The order of result values is
* determined by the order they occur in the array.The comparator is invoked
* with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.uniqWith(objects, _.isEqual);
* // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
*/
function uniqWith(array, comparator) {
comparator = typeof comparator == 'function' ? comparator : undefined;
return (array && array.length) ? baseUniq(array, undefined, comparator) : [];
}
module.exports = uniqWith;
webpack://frontend-mybets/../../node_modules/lodash/upperFirst.js
var createCaseFirst = require('./_createCaseFirst');
/**
* Converts the first character of `string` to upper case.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.upperFirst('fred');
* // => 'Fred'
*
* _.upperFirst('FRED');
* // => 'FRED'
*/
var upperFirst = createCaseFirst('toUpperCase');
module.exports = upperFirst;
webpack://frontend-mybets/../../node_modules/lodash/values.js
var baseValues = require('./_baseValues'),
keys = require('./keys');
/**
* Creates an array of the own enumerable string keyed property values of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.values(new Foo);
* // => [1, 2] (iteration order is not guaranteed)
*
* _.values('hi');
* // => ['h', 'i']
*/
function values(object) {
return object == null ? [] : baseValues(object, keys(object));
}
module.exports = values;
webpack://frontend-mybets/../../node_modules/lodash/without.js
var baseDifference = require('./_baseDifference'),
baseRest = require('./_baseRest'),
isArrayLikeObject = require('./isArrayLikeObject');
/**
* Creates an array excluding all given values using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* **Note:** Unlike `_.pull`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...*} [values] The values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @see _.difference, _.xor
* @example
*
* _.without([2, 1, 2, 3], 1, 2);
* // => [3]
*/
var without = baseRest(function(array, values) {
return isArrayLikeObject(array)
? baseDifference(array, values)
: [];
});
module.exports = without;
webpack://frontend-mybets/../../node_modules/lodash/words.js
var asciiWords = require('./_asciiWords'),
hasUnicodeWord = require('./_hasUnicodeWord'),
toString = require('./toString'),
unicodeWords = require('./_unicodeWords');
/**
* Splits `string` into an array of its words.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {RegExp|string} [pattern] The pattern to match words.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the words of `string`.
* @example
*
* _.words('fred, barney, & pebbles');
* // => ['fred', 'barney', 'pebbles']
*
* _.words('fred, barney, & pebbles', /[^, ]+/g);
* // => ['fred', 'barney', '&', 'pebbles']
*/
function words(string, pattern, guard) {
string = toString(string);
pattern = guard ? undefined : pattern;
if (pattern === undefined) {
return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
}
return string.match(pattern) || [];
}
module.exports = words;
webpack://frontend-mybets/../../node_modules/lodash/wrapperLodash.js
var LazyWrapper = require('./_LazyWrapper'),
LodashWrapper = require('./_LodashWrapper'),
baseLodash = require('./_baseLodash'),
isArray = require('./isArray'),
isObjectLike = require('./isObjectLike'),
wrapperClone = require('./_wrapperClone');
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Creates a `lodash` object which wraps `value` to enable implicit method
* chain sequences. Methods that operate on and return arrays, collections,
* and functions can be chained together. Methods that retrieve a single value
* or may return a primitive value will automatically end the chain sequence
* and return the unwrapped value. Otherwise, the value must be unwrapped
* with `_#value`.
*
* Explicit chain sequences, which must be unwrapped with `_#value`, may be
* enabled using `_.chain`.
*
* The execution of chained methods is lazy, that is, it's deferred until
* `_#value` is implicitly or explicitly called.
*
* Lazy evaluation allows several methods to support shortcut fusion.
* Shortcut fusion is an optimization to merge iteratee calls; this avoids
* the creation of intermediate arrays and can greatly reduce the number of
* iteratee executions. Sections of a chain sequence qualify for shortcut
* fusion if the section is applied to an array and iteratees accept only
* one argument. The heuristic for whether a section qualifies for shortcut
* fusion is subject to change.
*
* Chaining is supported in custom builds as long as the `_#value` method is
* directly or indirectly included in the build.
*
* In addition to lodash methods, wrappers have `Array` and `String` methods.
*
* The wrapper `Array` methods are:
* `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
*
* The wrapper `String` methods are:
* `replace` and `split`
*
* The wrapper methods that support shortcut fusion are:
* `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
* `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
* `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
*
* The chainable wrapper methods are:
* `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
* `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
* `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
* `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
* `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
* `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
* `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
* `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
* `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
* `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
* `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
* `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
* `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
* `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
* `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
* `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
* `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
* `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
* `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
* `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
* `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
* `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
* `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
* `zipObject`, `zipObjectDeep`, and `zipWith`
*
* The wrapper methods that are **not** chainable by default are:
* `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
* `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
* `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
* `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
* `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
* `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
* `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
* `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
* `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
* `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
* `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
* `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
* `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
* `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
* `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
* `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
* `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
* `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
* `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
* `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
* `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
* `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
* `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
* `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
* `upperFirst`, `value`, and `words`
*
* @name _
* @constructor
* @category Seq
* @param {*} value The value to wrap in a `lodash` instance.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* function square(n) {
* return n * n;
* }
*
* var wrapped = _([1, 2, 3]);
*
* // Returns an unwrapped value.
* wrapped.reduce(_.add);
* // => 6
*
* // Returns a wrapped value.
* var squares = wrapped.map(square);
*
* _.isArray(squares);
* // => false
*
* _.isArray(squares.value());
* // => true
*/
function lodash(value) {
if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
if (value instanceof LodashWrapper) {
return value;
}
if (hasOwnProperty.call(value, '__wrapped__')) {
return wrapperClone(value);
}
}
return new LodashWrapper(value);
}
// Ensure wrappers are instances of `baseLodash`.
lodash.prototype = baseLodash.prototype;
lodash.prototype.constructor = lodash;
module.exports = lodash;
webpack://frontend-mybets/../../node_modules/memoize-one/dist/memoize-one.esm.js
var safeIsNaN = Number.isNaN ||
function ponyfill(value) {
return typeof value === 'number' && value !== value;
};
function isEqual(first, second) {
if (first === second) {
return true;
}
if (safeIsNaN(first) && safeIsNaN(second)) {
return true;
}
return false;
}
function areInputsEqual(newInputs, lastInputs) {
if (newInputs.length !== lastInputs.length) {
return false;
}
for (var i = 0; i < newInputs.length; i++) {
if (!isEqual(newInputs[i], lastInputs[i])) {
return false;
}
}
return true;
}
function memoizeOne(resultFn, isEqual) {
if (isEqual === void 0) { isEqual = areInputsEqual; }
var cache = null;
function memoized() {
var newArgs = [];
for (var _i = 0; _i < arguments.length; _i++) {
newArgs[_i] = arguments[_i];
}
if (cache && cache.lastThis === this && isEqual(newArgs, cache.lastArgs)) {
return cache.lastResult;
}
var lastResult = resultFn.apply(this, newArgs);
cache = {
lastResult: lastResult,
lastArgs: newArgs,
lastThis: this,
};
return lastResult;
}
memoized.clear = function clear() {
cache = null;
};
return memoized;
}
export { memoizeOne as default };
webpack://frontend-mybets/../../node_modules/mobile-detect/mobile-detect.js
// THIS FILE IS GENERATED - DO NOT EDIT!
/*!mobile-detect v1.4.5 2021-03-13*/
/*global module:false, define:false*/
/*jshint latedef:false*/
/*!@license Copyright 2013, Heinrich Goebl, License: MIT, see https://github.com/hgoebl/mobile-detect.js*/
(function (define, undefined) {
define(function () {
'use strict';
var impl = {};
impl.mobileDetectRules = {
"phones": {
"iPhone": "\\biPhone\\b|\\biPod\\b",
"BlackBerry": "BlackBerry|\\bBB10\\b|rim[0-9]+|\\b(BBA100|BBB100|BBD100|BBE100|BBF100|STH100)\\b-[0-9]+",
"Pixel": "; \\bPixel\\b",
"HTC": "HTC|HTC.*(Sensation|Evo|Vision|Explorer|6800|8100|8900|A7272|S510e|C110e|Legend|Desire|T8282)|APX515CKT|Qtek9090|APA9292KT|HD_mini|Sensation.*Z710e|PG86100|Z715e|Desire.*(A8181|HD)|ADR6200|ADR6400L|ADR6425|001HT|Inspire 4G|Android.*\\bEVO\\b|T-Mobile G1|Z520m|Android [0-9.]+; Pixel",
"Nexus": "Nexus One|Nexus S|Galaxy.*Nexus|Android.*Nexus.*Mobile|Nexus 4|Nexus 5|Nexus 5X|Nexus 6",
"Dell": "Dell[;]? (Streak|Aero|Venue|Venue Pro|Flash|Smoke|Mini 3iX)|XCD28|XCD35|\\b001DL\\b|\\b101DL\\b|\\bGS01\\b",
"Motorola": "Motorola|DROIDX|DROID BIONIC|\\bDroid\\b.*Build|Android.*Xoom|HRI39|MOT-|A1260|A1680|A555|A853|A855|A953|A955|A956|Motorola.*ELECTRIFY|Motorola.*i1|i867|i940|MB200|MB300|MB501|MB502|MB508|MB511|MB520|MB525|MB526|MB611|MB612|MB632|MB810|MB855|MB860|MB861|MB865|MB870|ME501|ME502|ME511|ME525|ME600|ME632|ME722|ME811|ME860|ME863|ME865|MT620|MT710|MT716|MT720|MT810|MT870|MT917|Motorola.*TITANIUM|WX435|WX445|XT300|XT301|XT311|XT316|XT317|XT319|XT320|XT390|XT502|XT530|XT531|XT532|XT535|XT603|XT610|XT611|XT615|XT681|XT701|XT702|XT711|XT720|XT800|XT806|XT860|XT862|XT875|XT882|XT883|XT894|XT901|XT907|XT909|XT910|XT912|XT928|XT926|XT915|XT919|XT925|XT1021|\\bMoto E\\b|XT1068|XT1092|XT1052",
"Samsung": "\\bSamsung\\b|SM-G950F|SM-G955F|SM-G9250|GT-19300|SGH-I337|BGT-S5230|GT-B2100|GT-B2700|GT-B2710|GT-B3210|GT-B3310|GT-B3410|GT-B3730|GT-B3740|GT-B5510|GT-B5512|GT-B5722|GT-B6520|GT-B7300|GT-B7320|GT-B7330|GT-B7350|GT-B7510|GT-B7722|GT-B7800|GT-C3010|GT-C3011|GT-C3060|GT-C3200|GT-C3212|GT-C3212I|GT-C3262|GT-C3222|GT-C3300|GT-C3300K|GT-C3303|GT-C3303K|GT-C3310|GT-C3322|GT-C3330|GT-C3350|GT-C3500|GT-C3510|GT-C3530|GT-C3630|GT-C3780|GT-C5010|GT-C5212|GT-C6620|GT-C6625|GT-C6712|GT-E1050|GT-E1070|GT-E1075|GT-E1080|GT-E1081|GT-E1085|GT-E1087|GT-E1100|GT-E1107|GT-E1110|GT-E1120|GT-E1125|GT-E1130|GT-E1160|GT-E1170|GT-E1175|GT-E1180|GT-E1182|GT-E1200|GT-E1210|GT-E1225|GT-E1230|GT-E1390|GT-E2100|GT-E2120|GT-E2121|GT-E2152|GT-E2220|GT-E2222|GT-E2230|GT-E2232|GT-E2250|GT-E2370|GT-E2550|GT-E2652|GT-E3210|GT-E3213|GT-I5500|GT-I5503|GT-I5700|GT-I5800|GT-I5801|GT-I6410|GT-I6420|GT-I7110|GT-I7410|GT-I7500|GT-I8000|GT-I8150|GT-I8160|GT-I8190|GT-I8320|GT-I8330|GT-I8350|GT-I8530|GT-I8700|GT-I8703|GT-I8910|GT-I9000|GT-I9001|GT-I9003|GT-I9010|GT-I9020|GT-I9023|GT-I9070|GT-I9082|GT-I9100|GT-I9103|GT-I9220|GT-I9250|GT-I9300|GT-I9305|GT-I9500|GT-I9505|GT-M3510|GT-M5650|GT-M7500|GT-M7600|GT-M7603|GT-M8800|GT-M8910|GT-N7000|GT-S3110|GT-S3310|GT-S3350|GT-S3353|GT-S3370|GT-S3650|GT-S3653|GT-S3770|GT-S3850|GT-S5210|GT-S5220|GT-S5229|GT-S5230|GT-S5233|GT-S5250|GT-S5253|GT-S5260|GT-S5263|GT-S5270|GT-S5300|GT-S5330|GT-S5350|GT-S5360|GT-S5363|GT-S5369|GT-S5380|GT-S5380D|GT-S5560|GT-S5570|GT-S5600|GT-S5603|GT-S5610|GT-S5620|GT-S5660|GT-S5670|GT-S5690|GT-S5750|GT-S5780|GT-S5830|GT-S5839|GT-S6102|GT-S6500|GT-S7070|GT-S7200|GT-S7220|GT-S7230|GT-S7233|GT-S7250|GT-S7500|GT-S7530|GT-S7550|GT-S7562|GT-S7710|GT-S8000|GT-S8003|GT-S8500|GT-S8530|GT-S8600|SCH-A310|SCH-A530|SCH-A570|SCH-A610|SCH-A630|SCH-A650|SCH-A790|SCH-A795|SCH-A850|SCH-A870|SCH-A890|SCH-A930|SCH-A950|SCH-A970|SCH-A990|SCH-I100|SCH-I110|SCH-I400|SCH-I405|SCH-I500|SCH-I510|SCH-I515|SCH-I600|SCH-I730|SCH-I760|SCH-I770|SCH-I830|SCH-I910|SCH-I920|SCH-I959|SCH-LC11|SCH-N150|SCH-N300|SCH-R100|SCH-R300|SCH-R351|SCH-R400|SCH-R410|SCH-T300|SCH-U310|SCH-U320|SCH-U350|SCH-U360|SCH-U365|SCH-U370|SCH-U380|SCH-U410|SCH-U430|SCH-U450|SCH-U460|SCH-U470|SCH-U490|SCH-U540|SCH-U550|SCH-U620|SCH-U640|SCH-U650|SCH-U660|SCH-U700|SCH-U740|SCH-U750|SCH-U810|SCH-U820|SCH-U900|SCH-U940|SCH-U960|SCS-26UC|SGH-A107|SGH-A117|SGH-A127|SGH-A137|SGH-A157|SGH-A167|SGH-A177|SGH-A187|SGH-A197|SGH-A227|SGH-A237|SGH-A257|SGH-A437|SGH-A517|SGH-A597|SGH-A637|SGH-A657|SGH-A667|SGH-A687|SGH-A697|SGH-A707|SGH-A717|SGH-A727|SGH-A737|SGH-A747|SGH-A767|SGH-A777|SGH-A797|SGH-A817|SGH-A827|SGH-A837|SGH-A847|SGH-A867|SGH-A877|SGH-A887|SGH-A897|SGH-A927|SGH-B100|SGH-B130|SGH-B200|SGH-B220|SGH-C100|SGH-C110|SGH-C120|SGH-C130|SGH-C140|SGH-C160|SGH-C170|SGH-C180|SGH-C200|SGH-C207|SGH-C210|SGH-C225|SGH-C230|SGH-C417|SGH-C450|SGH-D307|SGH-D347|SGH-D357|SGH-D407|SGH-D415|SGH-D780|SGH-D807|SGH-D980|SGH-E105|SGH-E200|SGH-E315|SGH-E316|SGH-E317|SGH-E335|SGH-E590|SGH-E635|SGH-E715|SGH-E890|SGH-F300|SGH-F480|SGH-I200|SGH-I300|SGH-I320|SGH-I550|SGH-I577|SGH-I600|SGH-I607|SGH-I617|SGH-I627|SGH-I637|SGH-I677|SGH-I700|SGH-I717|SGH-I727|SGH-i747M|SGH-I777|SGH-I780|SGH-I827|SGH-I847|SGH-I857|SGH-I896|SGH-I897|SGH-I900|SGH-I907|SGH-I917|SGH-I927|SGH-I937|SGH-I997|SGH-J150|SGH-J200|SGH-L170|SGH-L700|SGH-M110|SGH-M150|SGH-M200|SGH-N105|SGH-N500|SGH-N600|SGH-N620|SGH-N625|SGH-N700|SGH-N710|SGH-P107|SGH-P207|SGH-P300|SGH-P310|SGH-P520|SGH-P735|SGH-P777|SGH-Q105|SGH-R210|SGH-R220|SGH-R225|SGH-S105|SGH-S307|SGH-T109|SGH-T119|SGH-T139|SGH-T209|SGH-T219|SGH-T229|SGH-T239|SGH-T249|SGH-T259|SGH-T309|SGH-T319|SGH-T329|SGH-T339|SGH-T349|SGH-T359|SGH-T369|SGH-T379|SGH-T409|SGH-T429|SGH-T439|SGH-T459|SGH-T469|SGH-T479|SGH-T499|SGH-T509|SGH-T519|SGH-T539|SGH-T559|SGH-T589|SGH-T609|SGH-T619|SGH-T629|SGH-T639|SGH-T659|SGH-T669|SGH-T679|SGH-T709|SGH-T719|SGH-T729|SGH-T739|SGH-T746|SGH-T749|SGH-T759|SGH-T769|SGH-T809|SGH-T819|SGH-T839|SGH-T919|SGH-T929|SGH-T939|SGH-T959|SGH-T989|SGH-U100|SGH-U200|SGH-U800|SGH-V205|SGH-V206|SGH-X100|SGH-X105|SGH-X120|SGH-X140|SGH-X426|SGH-X427|SGH-X475|SGH-X495|SGH-X497|SGH-X507|SGH-X600|SGH-X610|SGH-X620|SGH-X630|SGH-X700|SGH-X820|SGH-X890|SGH-Z130|SGH-Z150|SGH-Z170|SGH-ZX10|SGH-ZX20|SHW-M110|SPH-A120|SPH-A400|SPH-A420|SPH-A460|SPH-A500|SPH-A560|SPH-A600|SPH-A620|SPH-A660|SPH-A700|SPH-A740|SPH-A760|SPH-A790|SPH-A800|SPH-A820|SPH-A840|SPH-A880|SPH-A900|SPH-A940|SPH-A960|SPH-D600|SPH-D700|SPH-D710|SPH-D720|SPH-I300|SPH-I325|SPH-I330|SPH-I350|SPH-I500|SPH-I600|SPH-I700|SPH-L700|SPH-M100|SPH-M220|SPH-M240|SPH-M300|SPH-M305|SPH-M320|SPH-M330|SPH-M350|SPH-M360|SPH-M370|SPH-M380|SPH-M510|SPH-M540|SPH-M550|SPH-M560|SPH-M570|SPH-M580|SPH-M610|SPH-M620|SPH-M630|SPH-M800|SPH-M810|SPH-M850|SPH-M900|SPH-M910|SPH-M920|SPH-M930|SPH-N100|SPH-N200|SPH-N240|SPH-N300|SPH-N400|SPH-Z400|SWC-E100|SCH-i909|GT-N7100|GT-N7105|SCH-I535|SM-N900A|SGH-I317|SGH-T999L|GT-S5360B|GT-I8262|GT-S6802|GT-S6312|GT-S6310|GT-S5312|GT-S5310|GT-I9105|GT-I8510|GT-S6790N|SM-G7105|SM-N9005|GT-S5301|GT-I9295|GT-I9195|SM-C101|GT-S7392|GT-S7560|GT-B7610|GT-I5510|GT-S7582|GT-S7530E|GT-I8750|SM-G9006V|SM-G9008V|SM-G9009D|SM-G900A|SM-G900D|SM-G900F|SM-G900H|SM-G900I|SM-G900J|SM-G900K|SM-G900L|SM-G900M|SM-G900P|SM-G900R4|SM-G900S|SM-G900T|SM-G900V|SM-G900W8|SHV-E160K|SCH-P709|SCH-P729|SM-T2558|GT-I9205|SM-G9350|SM-J120F|SM-G920F|SM-G920V|SM-G930F|SM-N910C|SM-A310F|GT-I9190|SM-J500FN|SM-G903F|SM-J330F|SM-G610F|SM-G981B|SM-G892A|SM-A530F",
"LG": "\\bLG\\b;|LG[- ]?(C800|C900|E400|E610|E900|E-900|F160|F180K|F180L|F180S|730|855|L160|LS740|LS840|LS970|LU6200|MS690|MS695|MS770|MS840|MS870|MS910|P500|P700|P705|VM696|AS680|AS695|AX840|C729|E970|GS505|272|C395|E739BK|E960|L55C|L75C|LS696|LS860|P769BK|P350|P500|P509|P870|UN272|US730|VS840|VS950|LN272|LN510|LS670|LS855|LW690|MN270|MN510|P509|P769|P930|UN200|UN270|UN510|UN610|US670|US740|US760|UX265|UX840|VN271|VN530|VS660|VS700|VS740|VS750|VS910|VS920|VS930|VX9200|VX11000|AX840A|LW770|P506|P925|P999|E612|D955|D802|MS323|M257)|LM-G710",
"Sony": "SonyST|SonyLT|SonyEricsson|SonyEricssonLT15iv|LT18i|E10i|LT28h|LT26w|SonyEricssonMT27i|C5303|C6902|C6903|C6906|C6943|D2533|SOV34|601SO|F8332",
"Asus": "Asus.*Galaxy|PadFone.*Mobile",
"Xiaomi": "^(?!.*\\bx11\\b).*xiaomi.*$|POCOPHONE F1|MI 8|Redmi Note 9S|Redmi Note 5A Prime|N2G47H|M2001J2G|M2001J2I|M1805E10A|M2004J11G|M1902F1G|M2002J9G|M2004J19G|M2003J6A1G",
"NokiaLumia": "Lumia [0-9]{3,4}",
"Micromax": "Micromax.*\\b(A210|A92|A88|A72|A111|A110Q|A115|A116|A110|A90S|A26|A51|A35|A54|A25|A27|A89|A68|A65|A57|A90)\\b",
"Palm": "PalmSource|Palm",
"Vertu": "Vertu|Vertu.*Ltd|Vertu.*Ascent|Vertu.*Ayxta|Vertu.*Constellation(F|Quest)?|Vertu.*Monika|Vertu.*Signature",
"Pantech": "PANTECH|IM-A850S|IM-A840S|IM-A830L|IM-A830K|IM-A830S|IM-A820L|IM-A810K|IM-A810S|IM-A800S|IM-T100K|IM-A725L|IM-A780L|IM-A775C|IM-A770K|IM-A760S|IM-A750K|IM-A740S|IM-A730S|IM-A720L|IM-A710K|IM-A690L|IM-A690S|IM-A650S|IM-A630K|IM-A600S|VEGA PTL21|PT003|P8010|ADR910L|P6030|P6020|P9070|P4100|P9060|P5000|CDM8992|TXT8045|ADR8995|IS11PT|P2030|P6010|P8000|PT002|IS06|CDM8999|P9050|PT001|TXT8040|P2020|P9020|P2000|P7040|P7000|C790",
"Fly": "IQ230|IQ444|IQ450|IQ440|IQ442|IQ441|IQ245|IQ256|IQ236|IQ255|IQ235|IQ245|IQ275|IQ240|IQ285|IQ280|IQ270|IQ260|IQ250",
"Wiko": "KITE 4G|HIGHWAY|GETAWAY|STAIRWAY|DARKSIDE|DARKFULL|DARKNIGHT|DARKMOON|SLIDE|WAX 4G|RAINBOW|BLOOM|SUNSET|GOA(?!nna)|LENNY|BARRY|IGGY|OZZY|CINK FIVE|CINK PEAX|CINK PEAX 2|CINK SLIM|CINK SLIM 2|CINK +|CINK KING|CINK PEAX|CINK SLIM|SUBLIM",
"iMobile": "i-mobile (IQ|i-STYLE|idea|ZAA|Hitz)",
"SimValley": "\\b(SP-80|XT-930|SX-340|XT-930|SX-310|SP-360|SP60|SPT-800|SP-120|SPT-800|SP-140|SPX-5|SPX-8|SP-100|SPX-8|SPX-12)\\b",
"Wolfgang": "AT-B24D|AT-AS50HD|AT-AS40W|AT-AS55HD|AT-AS45q2|AT-B26D|AT-AS50Q",
"Alcatel": "Alcatel",
"Nintendo": "Nintendo (3DS|Switch)",
"Amoi": "Amoi",
"INQ": "INQ",
"OnePlus": "ONEPLUS",
"GenericPhone": "Tapatalk|PDA;|SAGEM|\\bmmp\\b|pocket|\\bpsp\\b|symbian|Smartphone|smartfon|treo|up.browser|up.link|vodafone|\\bwap\\b|nokia|Series40|Series60|S60|SonyEricsson|N900|MAUI.*WAP.*Browser"
},
"tablets": {
"iPad": "iPad|iPad.*Mobile",
"NexusTablet": "Android.*Nexus[\\s]+(7|9|10)",
"GoogleTablet": "Android.*Pixel C",
"SamsungTablet": "SAMSUNG.*Tablet|Galaxy.*Tab|SC-01C|GT-P1000|GT-P1003|GT-P1010|GT-P3105|GT-P6210|GT-P6800|GT-P6810|GT-P7100|GT-P7300|GT-P7310|GT-P7500|GT-P7510|SCH-I800|SCH-I815|SCH-I905|SGH-I957|SGH-I987|SGH-T849|SGH-T859|SGH-T869|SPH-P100|GT-P3100|GT-P3108|GT-P3110|GT-P5100|GT-P5110|GT-P6200|GT-P7320|GT-P7511|GT-N8000|GT-P8510|SGH-I497|SPH-P500|SGH-T779|SCH-I705|SCH-I915|GT-N8013|GT-P3113|GT-P5113|GT-P8110|GT-N8010|GT-N8005|GT-N8020|GT-P1013|GT-P6201|GT-P7501|GT-N5100|GT-N5105|GT-N5110|SHV-E140K|SHV-E140L|SHV-E140S|SHV-E150S|SHV-E230K|SHV-E230L|SHV-E230S|SHW-M180K|SHW-M180L|SHW-M180S|SHW-M180W|SHW-M300W|SHW-M305W|SHW-M380K|SHW-M380S|SHW-M380W|SHW-M430W|SHW-M480K|SHW-M480S|SHW-M480W|SHW-M485W|SHW-M486W|SHW-M500W|GT-I9228|SCH-P739|SCH-I925|GT-I9200|GT-P5200|GT-P5210|GT-P5210X|SM-T311|SM-T310|SM-T310X|SM-T210|SM-T210R|SM-T211|SM-P600|SM-P601|SM-P605|SM-P900|SM-P901|SM-T217|SM-T217A|SM-T217S|SM-P6000|SM-T3100|SGH-I467|XE500|SM-T110|GT-P5220|GT-I9200X|GT-N5110X|GT-N5120|SM-P905|SM-T111|SM-T2105|SM-T315|SM-T320|SM-T320X|SM-T321|SM-T520|SM-T525|SM-T530NU|SM-T230NU|SM-T330NU|SM-T900|XE500T1C|SM-P605V|SM-P905V|SM-T337V|SM-T537V|SM-T707V|SM-T807V|SM-P600X|SM-P900X|SM-T210X|SM-T230|SM-T230X|SM-T325|GT-P7503|SM-T531|SM-T330|SM-T530|SM-T705|SM-T705C|SM-T535|SM-T331|SM-T800|SM-T700|SM-T537|SM-T807|SM-P907A|SM-T337A|SM-T537A|SM-T707A|SM-T807A|SM-T237|SM-T807P|SM-P607T|SM-T217T|SM-T337T|SM-T807T|SM-T116NQ|SM-T116BU|SM-P550|SM-T350|SM-T550|SM-T9000|SM-P9000|SM-T705Y|SM-T805|GT-P3113|SM-T710|SM-T810|SM-T815|SM-T360|SM-T533|SM-T113|SM-T335|SM-T715|SM-T560|SM-T670|SM-T677|SM-T377|SM-T567|SM-T357T|SM-T555|SM-T561|SM-T713|SM-T719|SM-T813|SM-T819|SM-T580|SM-T355Y?|SM-T280|SM-T817A|SM-T820|SM-W700|SM-P580|SM-T587|SM-P350|SM-P555M|SM-P355M|SM-T113NU|SM-T815Y|SM-T585|SM-T285|SM-T825|SM-W708|SM-T835|SM-T830|SM-T837V|SM-T720|SM-T510|SM-T387V|SM-P610|SM-T290|SM-T515|SM-T590|SM-T595|SM-T725|SM-T817P|SM-P585N0|SM-T395|SM-T295|SM-T865|SM-P610N|SM-P615|SM-T970|SM-T380|SM-T5950|SM-T905|SM-T231|SM-T500|SM-T860",
"Kindle": "Kindle|Silk.*Accelerated|Android.*\\b(KFOT|KFTT|KFJWI|KFJWA|KFOTE|KFSOWI|KFTHWI|KFTHWA|KFAPWI|KFAPWA|WFJWAE|KFSAWA|KFSAWI|KFASWI|KFARWI|KFFOWI|KFGIWI|KFMEWI)\\b|Android.*Silk\/[0-9.]+ like Chrome\/[0-9.]+ (?!Mobile)",
"SurfaceTablet": "Windows NT [0-9.]+; ARM;.*(Tablet|ARMBJS)",
"HPTablet": "HP Slate (7|8|10)|HP ElitePad 900|hp-tablet|EliteBook.*Touch|HP 8|Slate 21|HP SlateBook 10",
"AsusTablet": "^.*PadFone((?!Mobile).)*$|Transformer|TF101|TF101G|TF300T|TF300TG|TF300TL|TF700T|TF700KL|TF701T|TF810C|ME171|ME301T|ME302C|ME371MG|ME370T|ME372MG|ME172V|ME173X|ME400C|Slider SL101|\\bK00F\\b|\\bK00C\\b|\\bK00E\\b|\\bK00L\\b|TX201LA|ME176C|ME102A|\\bM80TA\\b|ME372CL|ME560CG|ME372CG|ME302KL| K010 | K011 | K017 | K01E |ME572C|ME103K|ME170C|ME171C|\\bME70C\\b|ME581C|ME581CL|ME8510C|ME181C|P01Y|PO1MA|P01Z|\\bP027\\b|\\bP024\\b|\\bP00C\\b",
"BlackBerryTablet": "PlayBook|RIM Tablet",
"HTCtablet": "HTC_Flyer_P512|HTC Flyer|HTC Jetstream|HTC-P715a|HTC EVO View 4G|PG41200|PG09410",
"MotorolaTablet": "xoom|sholest|MZ615|MZ605|MZ505|MZ601|MZ602|MZ603|MZ604|MZ606|MZ607|MZ608|MZ609|MZ615|MZ616|MZ617",
"NookTablet": "Android.*Nook|NookColor|nook browser|BNRV200|BNRV200A|BNTV250|BNTV250A|BNTV400|BNTV600|LogicPD Zoom2",
"AcerTablet": "Android.*; \\b(A100|A101|A110|A200|A210|A211|A500|A501|A510|A511|A700|A701|W500|W500P|W501|W501P|W510|W511|W700|G100|G100W|B1-A71|B1-710|B1-711|A1-810|A1-811|A1-830)\\b|W3-810|\\bA3-A10\\b|\\bA3-A11\\b|\\bA3-A20\\b|\\bA3-A30|A3-A40",
"ToshibaTablet": "Android.*(AT100|AT105|AT200|AT205|AT270|AT275|AT300|AT305|AT1S5|AT500|AT570|AT700|AT830)|TOSHIBA.*FOLIO",
"LGTablet": "\\bL-06C|LG-V909|LG-V900|LG-V700|LG-V510|LG-V500|LG-V410|LG-V400|LG-VK810\\b",
"FujitsuTablet": "Android.*\\b(F-01D|F-02F|F-05E|F-10D|M532|Q572)\\b",
"PrestigioTablet": "PMP3170B|PMP3270B|PMP3470B|PMP7170B|PMP3370B|PMP3570C|PMP5870C|PMP3670B|PMP5570C|PMP5770D|PMP3970B|PMP3870C|PMP5580C|PMP5880D|PMP5780D|PMP5588C|PMP7280C|PMP7280C3G|PMP7280|PMP7880D|PMP5597D|PMP5597|PMP7100D|PER3464|PER3274|PER3574|PER3884|PER5274|PER5474|PMP5097CPRO|PMP5097|PMP7380D|PMP5297C|PMP5297C_QUAD|PMP812E|PMP812E3G|PMP812F|PMP810E|PMP880TD|PMT3017|PMT3037|PMT3047|PMT3057|PMT7008|PMT5887|PMT5001|PMT5002",
"LenovoTablet": "Lenovo TAB|Idea(Tab|Pad)( A1|A10| K1|)|ThinkPad([ ]+)?Tablet|YT3-850M|YT3-X90L|YT3-X90F|YT3-X90X|Lenovo.*(S2109|S2110|S5000|S6000|K3011|A3000|A3500|A1000|A2107|A2109|A1107|A5500|A7600|B6000|B8000|B8080)(-|)(FL|F|HV|H|)|TB-X103F|TB-X304X|TB-X304F|TB-X304L|TB-X505F|TB-X505L|TB-X505X|TB-X605F|TB-X605L|TB-8703F|TB-8703X|TB-8703N|TB-8704N|TB-8704F|TB-8704X|TB-8704V|TB-7304F|TB-7304I|TB-7304X|Tab2A7-10F|Tab2A7-20F|TB2-X30L|YT3-X50L|YT3-X50F|YT3-X50M|YT-X705F|YT-X703F|YT-X703L|YT-X705L|YT-X705X|TB2-X30F|TB2-X30L|TB2-X30M|A2107A-F|A2107A-H|TB3-730F|TB3-730M|TB3-730X|TB-7504F|TB-7504X|TB-X704F|TB-X104F|TB3-X70F|TB-X705F|TB-8504F|TB3-X70L|TB3-710F|TB-X704L",
"DellTablet": "Venue 11|Venue 8|Venue 7|Dell Streak 10|Dell Streak 7",
"YarvikTablet": "Android.*\\b(TAB210|TAB211|TAB224|TAB250|TAB260|TAB264|TAB310|TAB360|TAB364|TAB410|TAB411|TAB420|TAB424|TAB450|TAB460|TAB461|TAB464|TAB465|TAB467|TAB468|TAB07-100|TAB07-101|TAB07-150|TAB07-151|TAB07-152|TAB07-200|TAB07-201-3G|TAB07-210|TAB07-211|TAB07-212|TAB07-214|TAB07-220|TAB07-400|TAB07-485|TAB08-150|TAB08-200|TAB08-201-3G|TAB08-201-30|TAB09-100|TAB09-211|TAB09-410|TAB10-150|TAB10-201|TAB10-211|TAB10-400|TAB10-410|TAB13-201|TAB274EUK|TAB275EUK|TAB374EUK|TAB462EUK|TAB474EUK|TAB9-200)\\b",
"MedionTablet": "Android.*\\bOYO\\b|LIFE.*(P9212|P9514|P9516|S9512)|LIFETAB",
"ArnovaTablet": "97G4|AN10G2|AN7bG3|AN7fG3|AN8G3|AN8cG3|AN7G3|AN9G3|AN7dG3|AN7dG3ST|AN7dG3ChildPad|AN10bG3|AN10bG3DT|AN9G2",
"IntensoTablet": "INM8002KP|INM1010FP|INM805ND|Intenso Tab|TAB1004",
"IRUTablet": "M702pro",
"MegafonTablet": "MegaFon V9|\\bZTE V9\\b|Android.*\\bMT7A\\b",
"EbodaTablet": "E-Boda (Supreme|Impresspeed|Izzycomm|Essential)",
"AllViewTablet": "Allview.*(Viva|Alldro|City|Speed|All TV|Frenzy|Quasar|Shine|TX1|AX1|AX2)",
"ArchosTablet": "\\b(101G9|80G9|A101IT)\\b|Qilive 97R|Archos5|\\bARCHOS (70|79|80|90|97|101|FAMILYPAD|)(b|c|)(G10| Cobalt| TITANIUM(HD|)| Xenon| Neon|XSK| 2| XS 2| PLATINUM| CARBON|GAMEPAD)\\b",
"AinolTablet": "NOVO7|NOVO8|NOVO10|Novo7Aurora|Novo7Basic|NOVO7PALADIN|novo9-Spark",
"NokiaLumiaTablet": "Lumia 2520",
"SonyTablet": "Sony.*Tablet|Xperia Tablet|Sony Tablet S|SO-03E|SGPT12|SGPT13|SGPT114|SGPT121|SGPT122|SGPT123|SGPT111|SGPT112|SGPT113|SGPT131|SGPT132|SGPT133|SGPT211|SGPT212|SGPT213|SGP311|SGP312|SGP321|EBRD1101|EBRD1102|EBRD1201|SGP351|SGP341|SGP511|SGP512|SGP521|SGP541|SGP551|SGP621|SGP641|SGP612|SOT31|SGP771|SGP611|SGP612|SGP712",
"PhilipsTablet": "\\b(PI2010|PI3000|PI3100|PI3105|PI3110|PI3205|PI3210|PI3900|PI4010|PI7000|PI7100)\\b",
"CubeTablet": "Android.*(K8GT|U9GT|U10GT|U16GT|U17GT|U18GT|U19GT|U20GT|U23GT|U30GT)|CUBE U8GT",
"CobyTablet": "MID1042|MID1045|MID1125|MID1126|MID7012|MID7014|MID7015|MID7034|MID7035|MID7036|MID7042|MID7048|MID7127|MID8042|MID8048|MID8127|MID9042|MID9740|MID9742|MID7022|MID7010",
"MIDTablet": "M9701|M9000|M9100|M806|M1052|M806|T703|MID701|MID713|MID710|MID727|MID760|MID830|MID728|MID933|MID125|MID810|MID732|MID120|MID930|MID800|MID731|MID900|MID100|MID820|MID735|MID980|MID130|MID833|MID737|MID960|MID135|MID860|MID736|MID140|MID930|MID835|MID733|MID4X10",
"MSITablet": "MSI \\b(Primo 73K|Primo 73L|Primo 81L|Primo 77|Primo 93|Primo 75|Primo 76|Primo 73|Primo 81|Primo 91|Primo 90|Enjoy 71|Enjoy 7|Enjoy 10)\\b",
"SMiTTablet": "Android.*(\\bMID\\b|MID-560|MTV-T1200|MTV-PND531|MTV-P1101|MTV-PND530)",
"RockChipTablet": "Android.*(RK2818|RK2808A|RK2918|RK3066)|RK2738|RK2808A",
"FlyTablet": "IQ310|Fly Vision",
"bqTablet": "Android.*(bq)?.*\\b(Elcano|Curie|Edison|Maxwell|Kepler|Pascal|Tesla|Hypatia|Platon|Newton|Livingstone|Cervantes|Avant|Aquaris ([E|M]10|M8))\\b|Maxwell.*Lite|Maxwell.*Plus",
"HuaweiTablet": "MediaPad|MediaPad 7 Youth|IDEOS S7|S7-201c|S7-202u|S7-101|S7-103|S7-104|S7-105|S7-106|S7-201|S7-Slim|M2-A01L|BAH-L09|BAH-W09|AGS-L09|CMR-AL19",
"NecTablet": "\\bN-06D|\\bN-08D",
"PantechTablet": "Pantech.*P4100",
"BronchoTablet": "Broncho.*(N701|N708|N802|a710)",
"VersusTablet": "TOUCHPAD.*[78910]|\\bTOUCHTAB\\b",
"ZyncTablet": "z1000|Z99 2G|z930|z990|z909|Z919|z900",
"PositivoTablet": "TB07STA|TB10STA|TB07FTA|TB10FTA",
"NabiTablet": "Android.*\\bNabi",
"KoboTablet": "Kobo Touch|\\bK080\\b|\\bVox\\b Build|\\bArc\\b Build",
"DanewTablet": "DSlide.*\\b(700|701R|702|703R|704|802|970|971|972|973|974|1010|1012)\\b",
"TexetTablet": "NaviPad|TB-772A|TM-7045|TM-7055|TM-9750|TM-7016|TM-7024|TM-7026|TM-7041|TM-7043|TM-7047|TM-8041|TM-9741|TM-9747|TM-9748|TM-9751|TM-7022|TM-7021|TM-7020|TM-7011|TM-7010|TM-7023|TM-7025|TM-7037W|TM-7038W|TM-7027W|TM-9720|TM-9725|TM-9737W|TM-1020|TM-9738W|TM-9740|TM-9743W|TB-807A|TB-771A|TB-727A|TB-725A|TB-719A|TB-823A|TB-805A|TB-723A|TB-715A|TB-707A|TB-705A|TB-709A|TB-711A|TB-890HD|TB-880HD|TB-790HD|TB-780HD|TB-770HD|TB-721HD|TB-710HD|TB-434HD|TB-860HD|TB-840HD|TB-760HD|TB-750HD|TB-740HD|TB-730HD|TB-722HD|TB-720HD|TB-700HD|TB-500HD|TB-470HD|TB-431HD|TB-430HD|TB-506|TB-504|TB-446|TB-436|TB-416|TB-146SE|TB-126SE",
"PlaystationTablet": "Playstation.*(Portable|Vita)",
"TrekstorTablet": "ST10416-1|VT10416-1|ST70408-1|ST702xx-1|ST702xx-2|ST80208|ST97216|ST70104-2|VT10416-2|ST10216-2A|SurfTab",
"PyleAudioTablet": "\\b(PTBL10CEU|PTBL10C|PTBL72BC|PTBL72BCEU|PTBL7CEU|PTBL7C|PTBL92BC|PTBL92BCEU|PTBL9CEU|PTBL9CUK|PTBL9C)\\b",
"AdvanTablet": "Android.* \\b(E3A|T3X|T5C|T5B|T3E|T3C|T3B|T1J|T1F|T2A|T1H|T1i|E1C|T1-E|T5-A|T4|E1-B|T2Ci|T1-B|T1-D|O1-A|E1-A|T1-A|T3A|T4i)\\b ",
"DanyTechTablet": "Genius Tab G3|Genius Tab S2|Genius Tab Q3|Genius Tab G4|Genius Tab Q4|Genius Tab G-II|Genius TAB GII|Genius TAB GIII|Genius Tab S1",
"GalapadTablet": "Android [0-9.]+; [a-z-]+; \\bG1\\b",
"MicromaxTablet": "Funbook|Micromax.*\\b(P250|P560|P360|P362|P600|P300|P350|P500|P275)\\b",
"KarbonnTablet": "Android.*\\b(A39|A37|A34|ST8|ST10|ST7|Smart Tab3|Smart Tab2)\\b",
"AllFineTablet": "Fine7 Genius|Fine7 Shine|Fine7 Air|Fine8 Style|Fine9 More|Fine10 Joy|Fine11 Wide",
"PROSCANTablet": "\\b(PEM63|PLT1023G|PLT1041|PLT1044|PLT1044G|PLT1091|PLT4311|PLT4311PL|PLT4315|PLT7030|PLT7033|PLT7033D|PLT7035|PLT7035D|PLT7044K|PLT7045K|PLT7045KB|PLT7071KG|PLT7072|PLT7223G|PLT7225G|PLT7777G|PLT7810K|PLT7849G|PLT7851G|PLT7852G|PLT8015|PLT8031|PLT8034|PLT8036|PLT8080K|PLT8082|PLT8088|PLT8223G|PLT8234G|PLT8235G|PLT8816K|PLT9011|PLT9045K|PLT9233G|PLT9735|PLT9760G|PLT9770G)\\b",
"YONESTablet": "BQ1078|BC1003|BC1077|RK9702|BC9730|BC9001|IT9001|BC7008|BC7010|BC708|BC728|BC7012|BC7030|BC7027|BC7026",
"ChangJiaTablet": "TPC7102|TPC7103|TPC7105|TPC7106|TPC7107|TPC7201|TPC7203|TPC7205|TPC7210|TPC7708|TPC7709|TPC7712|TPC7110|TPC8101|TPC8103|TPC8105|TPC8106|TPC8203|TPC8205|TPC8503|TPC9106|TPC9701|TPC97101|TPC97103|TPC97105|TPC97106|TPC97111|TPC97113|TPC97203|TPC97603|TPC97809|TPC97205|TPC10101|TPC10103|TPC10106|TPC10111|TPC10203|TPC10205|TPC10503",
"GUTablet": "TX-A1301|TX-M9002|Q702|kf026",
"PointOfViewTablet": "TAB-P506|TAB-navi-7-3G-M|TAB-P517|TAB-P-527|TAB-P701|TAB-P703|TAB-P721|TAB-P731N|TAB-P741|TAB-P825|TAB-P905|TAB-P925|TAB-PR945|TAB-PL1015|TAB-P1025|TAB-PI1045|TAB-P1325|TAB-PROTAB[0-9]+|TAB-PROTAB25|TAB-PROTAB26|TAB-PROTAB27|TAB-PROTAB26XL|TAB-PROTAB2-IPS9|TAB-PROTAB30-IPS9|TAB-PROTAB25XXL|TAB-PROTAB26-IPS10|TAB-PROTAB30-IPS10",
"OvermaxTablet": "OV-(SteelCore|NewBase|Basecore|Baseone|Exellen|Quattor|EduTab|Solution|ACTION|BasicTab|TeddyTab|MagicTab|Stream|TB-08|TB-09)|Qualcore 1027",
"HCLTablet": "HCL.*Tablet|Connect-3G-2.0|Connect-2G-2.0|ME Tablet U1|ME Tablet U2|ME Tablet G1|ME Tablet X1|ME Tablet Y2|ME Tablet Sync",
"DPSTablet": "DPS Dream 9|DPS Dual 7",
"VistureTablet": "V97 HD|i75 3G|Visture V4( HD)?|Visture V5( HD)?|Visture V10",
"CrestaTablet": "CTP(-)?810|CTP(-)?818|CTP(-)?828|CTP(-)?838|CTP(-)?888|CTP(-)?978|CTP(-)?980|CTP(-)?987|CTP(-)?988|CTP(-)?989",
"MediatekTablet": "\\bMT8125|MT8389|MT8135|MT8377\\b",
"ConcordeTablet": "Concorde([ ]+)?Tab|ConCorde ReadMan",
"GoCleverTablet": "GOCLEVER TAB|A7GOCLEVER|M1042|M7841|M742|R1042BK|R1041|TAB A975|TAB A7842|TAB A741|TAB A741L|TAB M723G|TAB M721|TAB A1021|TAB I921|TAB R721|TAB I720|TAB T76|TAB R70|TAB R76.2|TAB R106|TAB R83.2|TAB M813G|TAB I721|GCTA722|TAB I70|TAB I71|TAB S73|TAB R73|TAB R74|TAB R93|TAB R75|TAB R76.1|TAB A73|TAB A93|TAB A93.2|TAB T72|TAB R83|TAB R974|TAB R973|TAB A101|TAB A103|TAB A104|TAB A104.2|R105BK|M713G|A972BK|TAB A971|TAB R974.2|TAB R104|TAB R83.3|TAB A1042",
"ModecomTablet": "FreeTAB 9000|FreeTAB 7.4|FreeTAB 7004|FreeTAB 7800|FreeTAB 2096|FreeTAB 7.5|FreeTAB 1014|FreeTAB 1001 |FreeTAB 8001|FreeTAB 9706|FreeTAB 9702|FreeTAB 7003|FreeTAB 7002|FreeTAB 1002|FreeTAB 7801|FreeTAB 1331|FreeTAB 1004|FreeTAB 8002|FreeTAB 8014|FreeTAB 9704|FreeTAB 1003",
"VoninoTablet": "\\b(Argus[ _]?S|Diamond[ _]?79HD|Emerald[ _]?78E|Luna[ _]?70C|Onyx[ _]?S|Onyx[ _]?Z|Orin[ _]?HD|Orin[ _]?S|Otis[ _]?S|SpeedStar[ _]?S|Magnet[ _]?M9|Primus[ _]?94[ _]?3G|Primus[ _]?94HD|Primus[ _]?QS|Android.*\\bQ8\\b|Sirius[ _]?EVO[ _]?QS|Sirius[ _]?QS|Spirit[ _]?S)\\b",
"ECSTablet": "V07OT2|TM105A|S10OT1|TR10CS1",
"StorexTablet": "eZee[_']?(Tab|Go)[0-9]+|TabLC7|Looney Tunes Tab",
"VodafoneTablet": "SmartTab([ ]+)?[0-9]+|SmartTabII10|SmartTabII7|VF-1497|VFD 1400",
"EssentielBTablet": "Smart[ ']?TAB[ ]+?[0-9]+|Family[ ']?TAB2",
"RossMoorTablet": "RM-790|RM-997|RMD-878G|RMD-974R|RMT-705A|RMT-701|RME-601|RMT-501|RMT-711",
"iMobileTablet": "i-mobile i-note",
"TolinoTablet": "tolino tab [0-9.]+|tolino shine",
"AudioSonicTablet": "\\bC-22Q|T7-QC|T-17B|T-17P\\b",
"AMPETablet": "Android.* A78 ",
"SkkTablet": "Android.* (SKYPAD|PHOENIX|CYCLOPS)",
"TecnoTablet": "TECNO P9|TECNO DP8D",
"JXDTablet": "Android.* \\b(F3000|A3300|JXD5000|JXD3000|JXD2000|JXD300B|JXD300|S5800|S7800|S602b|S5110b|S7300|S5300|S602|S603|S5100|S5110|S601|S7100a|P3000F|P3000s|P101|P200s|P1000m|P200m|P9100|P1000s|S6600b|S908|P1000|P300|S18|S6600|S9100)\\b",
"iJoyTablet": "Tablet (Spirit 7|Essentia|Galatea|Fusion|Onix 7|Landa|Titan|Scooby|Deox|Stella|Themis|Argon|Unique 7|Sygnus|Hexen|Finity 7|Cream|Cream X2|Jade|Neon 7|Neron 7|Kandy|Scape|Saphyr 7|Rebel|Biox|Rebel|Rebel 8GB|Myst|Draco 7|Myst|Tab7-004|Myst|Tadeo Jones|Tablet Boing|Arrow|Draco Dual Cam|Aurix|Mint|Amity|Revolution|Finity 9|Neon 9|T9w|Amity 4GB Dual Cam|Stone 4GB|Stone 8GB|Andromeda|Silken|X2|Andromeda II|Halley|Flame|Saphyr 9,7|Touch 8|Planet|Triton|Unique 10|Hexen 10|Memphis 4GB|Memphis 8GB|Onix 10)",
"FX2Tablet": "FX2 PAD7|FX2 PAD10",
"XoroTablet": "KidsPAD 701|PAD[ ]?712|PAD[ ]?714|PAD[ ]?716|PAD[ ]?717|PAD[ ]?718|PAD[ ]?720|PAD[ ]?721|PAD[ ]?722|PAD[ ]?790|PAD[ ]?792|PAD[ ]?900|PAD[ ]?9715D|PAD[ ]?9716DR|PAD[ ]?9718DR|PAD[ ]?9719QR|PAD[ ]?9720QR|TelePAD1030|Telepad1032|TelePAD730|TelePAD731|TelePAD732|TelePAD735Q|TelePAD830|TelePAD9730|TelePAD795|MegaPAD 1331|MegaPAD 1851|MegaPAD 2151",
"ViewsonicTablet": "ViewPad 10pi|ViewPad 10e|ViewPad 10s|ViewPad E72|ViewPad7|ViewPad E100|ViewPad 7e|ViewSonic VB733|VB100a",
"VerizonTablet": "QTAQZ3|QTAIR7|QTAQTZ3|QTASUN1|QTASUN2|QTAXIA1",
"OdysTablet": "LOOX|XENO10|ODYS[ -](Space|EVO|Xpress|NOON)|\\bXELIO\\b|Xelio10Pro|XELIO7PHONETAB|XELIO10EXTREME|XELIOPT2|NEO_QUAD10",
"CaptivaTablet": "CAPTIVA PAD",
"IconbitTablet": "NetTAB|NT-3702|NT-3702S|NT-3702S|NT-3603P|NT-3603P|NT-0704S|NT-0704S|NT-3805C|NT-3805C|NT-0806C|NT-0806C|NT-0909T|NT-0909T|NT-0907S|NT-0907S|NT-0902S|NT-0902S",
"TeclastTablet": "T98 4G|\\bP80\\b|\\bX90HD\\b|X98 Air|X98 Air 3G|\\bX89\\b|P80 3G|\\bX80h\\b|P98 Air|\\bX89HD\\b|P98 3G|\\bP90HD\\b|P89 3G|X98 3G|\\bP70h\\b|P79HD 3G|G18d 3G|\\bP79HD\\b|\\bP89s\\b|\\bA88\\b|\\bP10HD\\b|\\bP19HD\\b|G18 3G|\\bP78HD\\b|\\bA78\\b|\\bP75\\b|G17s 3G|G17h 3G|\\bP85t\\b|\\bP90\\b|\\bP11\\b|\\bP98t\\b|\\bP98HD\\b|\\bG18d\\b|\\bP85s\\b|\\bP11HD\\b|\\bP88s\\b|\\bA80HD\\b|\\bA80se\\b|\\bA10h\\b|\\bP89\\b|\\bP78s\\b|\\bG18\\b|\\bP85\\b|\\bA70h\\b|\\bA70\\b|\\bG17\\b|\\bP18\\b|\\bA80s\\b|\\bA11s\\b|\\bP88HD\\b|\\bA80h\\b|\\bP76s\\b|\\bP76h\\b|\\bP98\\b|\\bA10HD\\b|\\bP78\\b|\\bP88\\b|\\bA11\\b|\\bA10t\\b|\\bP76a\\b|\\bP76t\\b|\\bP76e\\b|\\bP85HD\\b|\\bP85a\\b|\\bP86\\b|\\bP75HD\\b|\\bP76v\\b|\\bA12\\b|\\bP75a\\b|\\bA15\\b|\\bP76Ti\\b|\\bP81HD\\b|\\bA10\\b|\\bT760VE\\b|\\bT720HD\\b|\\bP76\\b|\\bP73\\b|\\bP71\\b|\\bP72\\b|\\bT720SE\\b|\\bC520Ti\\b|\\bT760\\b|\\bT720VE\\b|T720-3GE|T720-WiFi",
"OndaTablet": "\\b(V975i|Vi30|VX530|V701|Vi60|V701s|Vi50|V801s|V719|Vx610w|VX610W|V819i|Vi10|VX580W|Vi10|V711s|V813|V811|V820w|V820|Vi20|V711|VI30W|V712|V891w|V972|V819w|V820w|Vi60|V820w|V711|V813s|V801|V819|V975s|V801|V819|V819|V818|V811|V712|V975m|V101w|V961w|V812|V818|V971|V971s|V919|V989|V116w|V102w|V973|Vi40)\\b[\\s]+|V10 \\b4G\\b",
"JaytechTablet": "TPC-PA762",
"BlaupunktTablet": "Endeavour 800NG|Endeavour 1010",
"DigmaTablet": "\\b(iDx10|iDx9|iDx8|iDx7|iDxD7|iDxD8|iDsQ8|iDsQ7|iDsQ8|iDsD10|iDnD7|3TS804H|iDsQ11|iDj7|iDs10)\\b",
"EvolioTablet": "ARIA_Mini_wifi|Aria[ _]Mini|Evolio X10|Evolio X7|Evolio X8|\\bEvotab\\b|\\bNeura\\b",
"LavaTablet": "QPAD E704|\\bIvoryS\\b|E-TAB IVORY|\\bE-TAB\\b",
"AocTablet": "MW0811|MW0812|MW0922|MTK8382|MW1031|MW0831|MW0821|MW0931|MW0712",
"MpmanTablet": "MP11 OCTA|MP10 OCTA|MPQC1114|MPQC1004|MPQC994|MPQC974|MPQC973|MPQC804|MPQC784|MPQC780|\\bMPG7\\b|MPDCG75|MPDCG71|MPDC1006|MP101DC|MPDC9000|MPDC905|MPDC706HD|MPDC706|MPDC705|MPDC110|MPDC100|MPDC99|MPDC97|MPDC88|MPDC8|MPDC77|MP709|MID701|MID711|MID170|MPDC703|MPQC1010",
"CelkonTablet": "CT695|CT888|CT[\\s]?910|CT7 Tab|CT9 Tab|CT3 Tab|CT2 Tab|CT1 Tab|C820|C720|\\bCT-1\\b",
"WolderTablet": "miTab \\b(DIAMOND|SPACE|BROOKLYN|NEO|FLY|MANHATTAN|FUNK|EVOLUTION|SKY|GOCAR|IRON|GENIUS|POP|MINT|EPSILON|BROADWAY|JUMP|HOP|LEGEND|NEW AGE|LINE|ADVANCE|FEEL|FOLLOW|LIKE|LINK|LIVE|THINK|FREEDOM|CHICAGO|CLEVELAND|BALTIMORE-GH|IOWA|BOSTON|SEATTLE|PHOENIX|DALLAS|IN 101|MasterChef)\\b",
"MediacomTablet": "M-MPI10C3G|M-SP10EG|M-SP10EGP|M-SP10HXAH|M-SP7HXAH|M-SP10HXBH|M-SP8HXAH|M-SP8MXA",
"MiTablet": "\\bMI PAD\\b|\\bHM NOTE 1W\\b",
"NibiruTablet": "Nibiru M1|Nibiru Jupiter One",
"NexoTablet": "NEXO NOVA|NEXO 10|NEXO AVIO|NEXO FREE|NEXO GO|NEXO EVO|NEXO 3G|NEXO SMART|NEXO KIDDO|NEXO MOBI",
"LeaderTablet": "TBLT10Q|TBLT10I|TBL-10WDKB|TBL-10WDKBO2013|TBL-W230V2|TBL-W450|TBL-W500|SV572|TBLT7I|TBA-AC7-8G|TBLT79|TBL-8W16|TBL-10W32|TBL-10WKB|TBL-W100",
"UbislateTablet": "UbiSlate[\\s]?7C",
"PocketBookTablet": "Pocketbook",
"KocasoTablet": "\\b(TB-1207)\\b",
"HisenseTablet": "\\b(F5281|E2371)\\b",
"Hudl": "Hudl HT7S3|Hudl 2",
"TelstraTablet": "T-Hub2",
"GenericTablet": "Android.*\\b97D\\b|Tablet(?!.*PC)|BNTV250A|MID-WCDMA|LogicPD Zoom2|\\bA7EB\\b|CatNova8|A1_07|CT704|CT1002|\\bM721\\b|rk30sdk|\\bEVOTAB\\b|M758A|ET904|ALUMIUM10|Smartfren Tab|Endeavour 1010|Tablet-PC-4|Tagi Tab|\\bM6pro\\b|CT1020W|arc 10HD|\\bTP750\\b|\\bQTAQZ3\\b|WVT101|TM1088|KT107"
},
"oss": {
"AndroidOS": "Android",
"BlackBerryOS": "blackberry|\\bBB10\\b|rim tablet os",
"PalmOS": "PalmOS|avantgo|blazer|elaine|hiptop|palm|plucker|xiino",
"SymbianOS": "Symbian|SymbOS|Series60|Series40|SYB-[0-9]+|\\bS60\\b",
"WindowsMobileOS": "Windows CE.*(PPC|Smartphone|Mobile|[0-9]{3}x[0-9]{3})|Windows Mobile|Windows Phone [0-9.]+|WCE;",
"WindowsPhoneOS": "Windows Phone 10.0|Windows Phone 8.1|Windows Phone 8.0|Windows Phone OS|XBLWP7|ZuneWP7|Windows NT 6.[23]; ARM;",
"iOS": "\\biPhone.*Mobile|\\biPod|\\biPad|AppleCoreMedia",
"iPadOS": "CPU OS 13",
"SailfishOS": "Sailfish",
"MeeGoOS": "MeeGo",
"MaemoOS": "Maemo",
"JavaOS": "J2ME\/|\\bMIDP\\b|\\bCLDC\\b",
"webOS": "webOS|hpwOS",
"badaOS": "\\bBada\\b",
"BREWOS": "BREW"
},
"uas": {
"Chrome": "\\bCrMo\\b|CriOS|Android.*Chrome\/[.0-9]* (Mobile)?",
"Dolfin": "\\bDolfin\\b",
"Opera": "Opera.*Mini|Opera.*Mobi|Android.*Opera|Mobile.*OPR\/[0-9.]+$|Coast\/[0-9.]+",
"Skyfire": "Skyfire",
"Edge": "\\bEdgiOS\\b|Mobile Safari\/[.0-9]* Edge",
"IE": "IEMobile|MSIEMobile",
"Firefox": "fennec|firefox.*maemo|(Mobile|Tablet).*Firefox|Firefox.*Mobile|FxiOS",
"Bolt": "bolt",
"TeaShark": "teashark",
"Blazer": "Blazer",
"Safari": "Version((?!\\bEdgiOS\\b).)*Mobile.*Safari|Safari.*Mobile|MobileSafari",
"WeChat": "\\bMicroMessenger\\b",
"UCBrowser": "UC.*Browser|UCWEB",
"baiduboxapp": "baiduboxapp",
"baidubrowser": "baidubrowser",
"DiigoBrowser": "DiigoBrowser",
"Mercury": "\\bMercury\\b",
"ObigoBrowser": "Obigo",
"NetFront": "NF-Browser",
"GenericBrowser": "NokiaBrowser|OviBrowser|OneBrowser|TwonkyBeamBrowser|SEMC.*Browser|FlyFlow|Minimo|NetFront|Novarra-Vision|MQQBrowser|MicroMessenger",
"PaleMoon": "Android.*PaleMoon|Mobile.*PaleMoon"
},
"props": {
"Mobile": "Mobile\/[VER]",
"Build": "Build\/[VER]",
"Version": "Version\/[VER]",
"VendorID": "VendorID\/[VER]",
"iPad": "iPad.*CPU[a-z ]+[VER]",
"iPhone": "iPhone.*CPU[a-z ]+[VER]",
"iPod": "iPod.*CPU[a-z ]+[VER]",
"Kindle": "Kindle\/[VER]",
"Chrome": [
"Chrome\/[VER]",
"CriOS\/[VER]",
"CrMo\/[VER]"
],
"Coast": [
"Coast\/[VER]"
],
"Dolfin": "Dolfin\/[VER]",
"Firefox": [
"Firefox\/[VER]",
"FxiOS\/[VER]"
],
"Fennec": "Fennec\/[VER]",
"Edge": "Edge\/[VER]",
"IE": [
"IEMobile\/[VER];",
"IEMobile [VER]",
"MSIE [VER];",
"Trident\/[0-9.]+;.*rv:[VER]"
],
"NetFront": "NetFront\/[VER]",
"NokiaBrowser": "NokiaBrowser\/[VER]",
"Opera": [
" OPR\/[VER]",
"Opera Mini\/[VER]",
"Version\/[VER]"
],
"Opera Mini": "Opera Mini\/[VER]",
"Opera Mobi": "Version\/[VER]",
"UCBrowser": [
"UCWEB[VER]",
"UC.*Browser\/[VER]"
],
"MQQBrowser": "MQQBrowser\/[VER]",
"MicroMessenger": "MicroMessenger\/[VER]",
"baiduboxapp": "baiduboxapp\/[VER]",
"baidubrowser": "baidubrowser\/[VER]",
"SamsungBrowser": "SamsungBrowser\/[VER]",
"Iron": "Iron\/[VER]",
"Safari": [
"Version\/[VER]",
"Safari\/[VER]"
],
"Skyfire": "Skyfire\/[VER]",
"Tizen": "Tizen\/[VER]",
"Webkit": "webkit[ \/][VER]",
"PaleMoon": "PaleMoon\/[VER]",
"SailfishBrowser": "SailfishBrowser\/[VER]",
"Gecko": "Gecko\/[VER]",
"Trident": "Trident\/[VER]",
"Presto": "Presto\/[VER]",
"Goanna": "Goanna\/[VER]",
"iOS": " \\bi?OS\\b [VER][ ;]{1}",
"Android": "Android [VER]",
"Sailfish": "Sailfish [VER]",
"BlackBerry": [
"BlackBerry[\\w]+\/[VER]",
"BlackBerry.*Version\/[VER]",
"Version\/[VER]"
],
"BREW": "BREW [VER]",
"Java": "Java\/[VER]",
"Windows Phone OS": [
"Windows Phone OS [VER]",
"Windows Phone [VER]"
],
"Windows Phone": "Windows Phone [VER]",
"Windows CE": "Windows CE\/[VER]",
"Windows NT": "Windows NT [VER]",
"Symbian": [
"SymbianOS\/[VER]",
"Symbian\/[VER]"
],
"webOS": [
"webOS\/[VER]",
"hpwOS\/[VER];"
]
},
"utils": {
"Bot": "Googlebot|facebookexternalhit|Google-AMPHTML|s~amp-validator|AdsBot-Google|Google Keyword Suggestion|Facebot|YandexBot|YandexMobileBot|bingbot|ia_archiver|AhrefsBot|Ezooms|GSLFbot|WBSearchBot|Twitterbot|TweetmemeBot|Twikle|PaperLiBot|Wotbox|UnwindFetchor|Exabot|MJ12bot|YandexImages|TurnitinBot|Pingdom|contentkingapp|AspiegelBot",
"MobileBot": "Googlebot-Mobile|AdsBot-Google-Mobile|YahooSeeker\/M1A1-R2D2",
"DesktopMode": "WPDesktop",
"TV": "SonyDTV|HbbTV",
"WebKit": "(webkit)[ \/]([\\w.]+)",
"Console": "\\b(Nintendo|Nintendo WiiU|Nintendo 3DS|Nintendo Switch|PLAYSTATION|Xbox)\\b",
"Watch": "SM-V700"
}
};
// following patterns come from http://detectmobilebrowsers.com/
impl.detectMobileBrowsers = {
fullPattern: /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i,
shortPattern: /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i,
tabletPattern: /android|ipad|playbook|silk/i
};
var hasOwnProp = Object.prototype.hasOwnProperty,
isArray;
impl.FALLBACK_PHONE = 'UnknownPhone';
impl.FALLBACK_TABLET = 'UnknownTablet';
impl.FALLBACK_MOBILE = 'UnknownMobile';
isArray = ('isArray' in Array) ?
Array.isArray : function (value) { return Object.prototype.toString.call(value) === '[object Array]'; };
function equalIC(a, b) {
return a != null && b != null && a.toLowerCase() === b.toLowerCase();
}
function containsIC(array, value) {
var valueLC, i, len = array.length;
if (!len || !value) {
return false;
}
valueLC = value.toLowerCase();
for (i = 0; i < len; ++i) {
if (valueLC === array[i].toLowerCase()) {
return true;
}
}
return false;
}
function convertPropsToRegExp(object) {
for (var key in object) {
if (hasOwnProp.call(object, key)) {
object[key] = new RegExp(object[key], 'i');
}
}
}
function prepareUserAgent(userAgent) {
return (userAgent || '').substr(0, 500); // mitigate vulnerable to ReDoS
}
(function init() {
var key, values, value, i, len, verPos, mobileDetectRules = impl.mobileDetectRules;
for (key in mobileDetectRules.props) {
if (hasOwnProp.call(mobileDetectRules.props, key)) {
values = mobileDetectRules.props[key];
if (!isArray(values)) {
values = [values];
}
len = values.length;
for (i = 0; i < len; ++i) {
value = values[i];
verPos = value.indexOf('[VER]');
if (verPos >= 0) {
value = value.substring(0, verPos) + '([\\w._\\+]+)' + value.substring(verPos + 5);
}
values[i] = new RegExp(value, 'i');
}
mobileDetectRules.props[key] = values;
}
}
convertPropsToRegExp(mobileDetectRules.oss);
convertPropsToRegExp(mobileDetectRules.phones);
convertPropsToRegExp(mobileDetectRules.tablets);
convertPropsToRegExp(mobileDetectRules.uas);
convertPropsToRegExp(mobileDetectRules.utils);
// copy some patterns to oss0 which are tested first (see issue#15)
mobileDetectRules.oss0 = {
WindowsPhoneOS: mobileDetectRules.oss.WindowsPhoneOS,
WindowsMobileOS: mobileDetectRules.oss.WindowsMobileOS
};
}());
/**
* Test userAgent string against a set of rules and find the first matched key.
* @param {Object} rules (key is String, value is RegExp)
* @param {String} userAgent the navigator.userAgent (or HTTP-Header 'User-Agent').
* @returns {String|null} the matched key if found, otherwise <tt>null</tt>
* @private
*/
impl.findMatch = function(rules, userAgent) {
for (var key in rules) {
if (hasOwnProp.call(rules, key)) {
if (rules[key].test(userAgent)) {
return key;
}
}
}
return null;
};
/**
* Test userAgent string against a set of rules and return an array of matched keys.
* @param {Object} rules (key is String, value is RegExp)
* @param {String} userAgent the navigator.userAgent (or HTTP-Header 'User-Agent').
* @returns {Array} an array of matched keys, may be empty when there is no match, but not <tt>null</tt>
* @private
*/
impl.findMatches = function(rules, userAgent) {
var result = [];
for (var key in rules) {
if (hasOwnProp.call(rules, key)) {
if (rules[key].test(userAgent)) {
result.push(key);
}
}
}
return result;
};
/**
* Check the version of the given property in the User-Agent.
*
* @param {String} propertyName
* @param {String} userAgent
* @return {String} version or <tt>null</tt> if version not found
* @private
*/
impl.getVersionStr = function (propertyName, userAgent) {
var props = impl.mobileDetectRules.props, patterns, i, len, match;
if (hasOwnProp.call(props, propertyName)) {
patterns = props[propertyName];
len = patterns.length;
for (i = 0; i < len; ++i) {
match = patterns[i].exec(userAgent);
if (match !== null) {
return match[1];
}
}
}
return null;
};
/**
* Check the version of the given property in the User-Agent.
* Will return a float number. (eg. 2_0 will return 2.0, 4.3.1 will return 4.31)
*
* @param {String} propertyName
* @param {String} userAgent
* @return {Number} version or <tt>NaN</tt> if version not found
* @private
*/
impl.getVersion = function (propertyName, userAgent) {
var version = impl.getVersionStr(propertyName, userAgent);
return version ? impl.prepareVersionNo(version) : NaN;
};
/**
* Prepare the version number.
*
* @param {String} version
* @return {Number} the version number as a floating number
* @private
*/
impl.prepareVersionNo = function (version) {
var numbers;
numbers = version.split(/[a-z._ \/\-]/i);
if (numbers.length === 1) {
version = numbers[0];
}
if (numbers.length > 1) {
version = numbers[0] + '.';
numbers.shift();
version += numbers.join('');
}
return Number(version);
};
impl.isMobileFallback = function (userAgent) {
return impl.detectMobileBrowsers.fullPattern.test(userAgent) ||
impl.detectMobileBrowsers.shortPattern.test(userAgent.substr(0,4));
};
impl.isTabletFallback = function (userAgent) {
return impl.detectMobileBrowsers.tabletPattern.test(userAgent);
};
impl.prepareDetectionCache = function (cache, userAgent, maxPhoneWidth) {
if (cache.mobile !== undefined) {
return;
}
var phone, tablet, phoneSized;
// first check for stronger tablet rules, then phone (see issue#5)
tablet = impl.findMatch(impl.mobileDetectRules.tablets, userAgent);
if (tablet) {
cache.mobile = cache.tablet = tablet;
cache.phone = null;
return; // unambiguously identified as tablet
}
phone = impl.findMatch(impl.mobileDetectRules.phones, userAgent);
if (phone) {
cache.mobile = cache.phone = phone;
cache.tablet = null;
return; // unambiguously identified as phone
}
// our rules haven't found a match -> try more general fallback rules
if (impl.isMobileFallback(userAgent)) {
phoneSized = MobileDetect.isPhoneSized(maxPhoneWidth);
if (phoneSized === undefined) {
cache.mobile = impl.FALLBACK_MOBILE;
cache.tablet = cache.phone = null;
} else if (phoneSized) {
cache.mobile = cache.phone = impl.FALLBACK_PHONE;
cache.tablet = null;
} else {
cache.mobile = cache.tablet = impl.FALLBACK_TABLET;
cache.phone = null;
}
} else if (impl.isTabletFallback(userAgent)) {
cache.mobile = cache.tablet = impl.FALLBACK_TABLET;
cache.phone = null;
} else {
// not mobile at all!
cache.mobile = cache.tablet = cache.phone = null;
}
};
// t is a reference to a MobileDetect instance
impl.mobileGrade = function (t) {
// impl note:
// To keep in sync w/ Mobile_Detect.php easily, the following code is tightly aligned to the PHP version.
// When changes are made in Mobile_Detect.php, copy this method and replace:
// $this-> / t.
// self::MOBILE_GRADE_(.) / '$1'
// , self::VERSION_TYPE_FLOAT / (nothing)
// isIOS() / os('iOS')
// [reg] / (nothing) <-- jsdelivr complaining about unescaped unicode character U+00AE
var $isMobile = t.mobile() !== null;
if (
// Apple iOS 3.2-5.1 - Tested on the original iPad (4.3 / 5.0), iPad 2 (4.3), iPad 3 (5.1), original iPhone (3.1), iPhone 3 (3.2), 3GS (4.3), 4 (4.3 / 5.0), and 4S (5.1)
t.os('iOS') && t.version('iPad')>=4.3 ||
t.os('iOS') && t.version('iPhone')>=3.1 ||
t.os('iOS') && t.version('iPod')>=3.1 ||
// Android 2.1-2.3 - Tested on the HTC Incredible (2.2), original Droid (2.2), HTC Aria (2.1), Google Nexus S (2.3). Functional on 1.5 & 1.6 but performance may be sluggish, tested on Google G1 (1.5)
// Android 3.1 (Honeycomb) - Tested on the Samsung Galaxy Tab 10.1 and Motorola XOOM
// Android 4.0 (ICS) - Tested on a Galaxy Nexus. Note: transition performance can be poor on upgraded devices
// Android 4.1 (Jelly Bean) - Tested on a Galaxy Nexus and Galaxy 7
( t.version('Android')>2.1 && t.is('Webkit') ) ||
// Windows Phone 7-7.5 - Tested on the HTC Surround (7.0) HTC Trophy (7.5), LG-E900 (7.5), Nokia Lumia 800
t.version('Windows Phone OS')>=7.0 ||
// Blackberry 7 - Tested on BlackBerry Torch 9810
// Blackberry 6.0 - Tested on the Torch 9800 and Style 9670
t.is('BlackBerry') && t.version('BlackBerry')>=6.0 ||
// Blackberry Playbook (1.0-2.0) - Tested on PlayBook
t.match('Playbook.*Tablet') ||
// Palm WebOS (1.4-2.0) - Tested on the Palm Pixi (1.4), Pre (1.4), Pre 2 (2.0)
( t.version('webOS')>=1.4 && t.match('Palm|Pre|Pixi') ) ||
// Palm WebOS 3.0 - Tested on HP TouchPad
t.match('hp.*TouchPad') ||
// Firefox Mobile (12 Beta) - Tested on Android 2.3 device
( t.is('Firefox') && t.version('Firefox')>=12 ) ||
// Chrome for Android - Tested on Android 4.0, 4.1 device
( t.is('Chrome') && t.is('AndroidOS') && t.version('Android')>=4.0 ) ||
// Skyfire 4.1 - Tested on Android 2.3 device
( t.is('Skyfire') && t.version('Skyfire')>=4.1 && t.is('AndroidOS') && t.version('Android')>=2.3 ) ||
// Opera Mobile 11.5-12: Tested on Android 2.3
( t.is('Opera') && t.version('Opera Mobi')>11 && t.is('AndroidOS') ) ||
// Meego 1.2 - Tested on Nokia 950 and N9
t.is('MeeGoOS') ||
// Tizen (pre-release) - Tested on early hardware
t.is('Tizen') ||
// Samsung Bada 2.0 - Tested on a Samsung Wave 3, Dolphin browser
// @todo: more tests here!
t.is('Dolfin') && t.version('Bada')>=2.0 ||
// UC Browser - Tested on Android 2.3 device
( (t.is('UC Browser') || t.is('Dolfin')) && t.version('Android')>=2.3 ) ||
// Kindle 3 and Fire - Tested on the built-in WebKit browser for each
( t.match('Kindle Fire') ||
t.is('Kindle') && t.version('Kindle')>=3.0 ) ||
// Nook Color 1.4.1 - Tested on original Nook Color, not Nook Tablet
t.is('AndroidOS') && t.is('NookTablet') ||
// Chrome Desktop 11-21 - Tested on OS X 10.7 and Windows 7
t.version('Chrome')>=11 && !$isMobile ||
// Safari Desktop 4-5 - Tested on OS X 10.7 and Windows 7
t.version('Safari')>=5.0 && !$isMobile ||
// Firefox Desktop 4-13 - Tested on OS X 10.7 and Windows 7
t.version('Firefox')>=4.0 && !$isMobile ||
// Internet Explorer 7-9 - Tested on Windows XP, Vista and 7
t.version('MSIE')>=7.0 && !$isMobile ||
// Opera Desktop 10-12 - Tested on OS X 10.7 and Windows 7
// @reference: http://my.opera.com/community/openweb/idopera/
t.version('Opera')>=10 && !$isMobile
){
return 'A';
}
if (
t.os('iOS') && t.version('iPad')<4.3 ||
t.os('iOS') && t.version('iPhone')<3.1 ||
t.os('iOS') && t.version('iPod')<3.1 ||
// Blackberry 5.0: Tested on the Storm 2 9550, Bold 9770
t.is('Blackberry') && t.version('BlackBerry')>=5 && t.version('BlackBerry')<6 ||
//Opera Mini (5.0-6.5) - Tested on iOS 3.2/4.3 and Android 2.3
( t.version('Opera Mini')>=5.0 && t.version('Opera Mini')<=6.5 &&
(t.version('Android')>=2.3 || t.is('iOS')) ) ||
// Nokia Symbian^3 - Tested on Nokia N8 (Symbian^3), C7 (Symbian^3), also works on N97 (Symbian^1)
t.match('NokiaN8|NokiaC7|N97.*Series60|Symbian/3') ||
// @todo: report this (tested on Nokia N71)
t.version('Opera Mobi')>=11 && t.is('SymbianOS')
){
return 'B';
}
if (
// Blackberry 4.x - Tested on the Curve 8330
t.version('BlackBerry')<5.0 ||
// Windows Mobile - Tested on the HTC Leo (WinMo 5.2)
t.match('MSIEMobile|Windows CE.*Mobile') || t.version('Windows Mobile')<=5.2
){
return 'C';
}
//All older smartphone platforms and featurephones - Any device that doesn't support media queries
//will receive the basic, C grade experience.
return 'C';
};
impl.detectOS = function (ua) {
return impl.findMatch(impl.mobileDetectRules.oss0, ua) ||
impl.findMatch(impl.mobileDetectRules.oss, ua);
};
impl.getDeviceSmallerSide = function () {
return window.screen.width < window.screen.height ?
window.screen.width :
window.screen.height;
};
/**
* Constructor for MobileDetect object.
* <br>
* Such an object will keep a reference to the given user-agent string and cache most of the detect queries.<br>
* <div style="background-color: #d9edf7; border: 1px solid #bce8f1; color: #3a87ad; padding: 14px; border-radius: 2px; margin-top: 20px">
* <strong>Find information how to download and install:</strong>
* <a href="https://github.com/hgoebl/mobile-detect.js/">github.com/hgoebl/mobile-detect.js/</a>
* </div>
*
* @example <pre>
* var md = new MobileDetect(window.navigator.userAgent);
* if (md.mobile()) {
* location.href = (md.mobileGrade() === 'A') ? '/mobile/' : '/lynx/';
* }
* </pre>
*
* @param {string} userAgent typically taken from window.navigator.userAgent or http_header['User-Agent']
* @param {number} [maxPhoneWidth=600] <strong>only for browsers</strong> specify a value for the maximum
* width of smallest device side (in logical "CSS" pixels) until a device detected as mobile will be handled
* as phone.
* This is only used in cases where the device cannot be classified as phone or tablet.<br>
* See <a href="http://developer.android.com/guide/practices/screens_support.html">Declaring Tablet Layouts
* for Android</a>.<br>
* If you provide a value < 0, then this "fuzzy" check is disabled.
* @constructor
* @global
*/
function MobileDetect(userAgent, maxPhoneWidth) {
this.ua = prepareUserAgent(userAgent);
this._cache = {};
//600dp is typical 7" tablet minimum width
this.maxPhoneWidth = maxPhoneWidth || 600;
}
MobileDetect.prototype = {
constructor: MobileDetect,
/**
* Returns the detected phone or tablet type or <tt>null</tt> if it is not a mobile device.
* <br>
* For a list of possible return values see {@link MobileDetect#phone} and {@link MobileDetect#tablet}.<br>
* <br>
* If the device is not detected by the regular expressions from Mobile-Detect, a test is made against
* the patterns of <a href="http://detectmobilebrowsers.com/">detectmobilebrowsers.com</a>. If this test
* is positive, a value of <code>UnknownPhone</code>, <code>UnknownTablet</code> or
* <code>UnknownMobile</code> is returned.<br>
* When used in browser, the decision whether phone or tablet is made based on <code>screen.width/height</code>.<br>
* <br>
* When used server-side (node.js), there is no way to tell the difference between <code>UnknownTablet</code>
* and <code>UnknownMobile</code>, so you will get <code>UnknownMobile</code> here.<br>
* Be aware that since v1.0.0 in this special case you will get <code>UnknownMobile</code> only for:
* {@link MobileDetect#mobile}, not for {@link MobileDetect#phone} and {@link MobileDetect#tablet}.
* In versions before v1.0.0 all 3 methods returned <code>UnknownMobile</code> which was tedious to use.
* <br>
* In most cases you will use the return value just as a boolean.
*
* @returns {String} the key for the phone family or tablet family, e.g. "Nexus".
* @function MobileDetect#mobile
*/
mobile: function () {
impl.prepareDetectionCache(this._cache, this.ua, this.maxPhoneWidth);
return this._cache.mobile;
},
/**
* Returns the detected phone type/family string or <tt>null</tt>.
* <br>
* The returned tablet (family or producer) is one of following keys:<br>
* <br><tt>iPhone, BlackBerry, Pixel, HTC, Nexus, Dell, Motorola, Samsung, LG, Sony, Asus,
* Xiaomi, NokiaLumia, Micromax, Palm, Vertu, Pantech, Fly, Wiko, iMobile,
* SimValley, Wolfgang, Alcatel, Nintendo, Amoi, INQ, OnePlus, GenericPhone</tt><br>
* <br>
* If the device is not detected by the regular expressions from Mobile-Detect, a test is made against
* the patterns of <a href="http://detectmobilebrowsers.com/">detectmobilebrowsers.com</a>. If this test
* is positive, a value of <code>UnknownPhone</code> or <code>UnknownMobile</code> is returned.<br>
* When used in browser, the decision whether phone or tablet is made based on <code>screen.width/height</code>.<br>
* <br>
* When used server-side (node.js), there is no way to tell the difference between <code>UnknownTablet</code>
* and <code>UnknownMobile</code>, so you will get <code>null</code> here, while {@link MobileDetect#mobile}
* will return <code>UnknownMobile</code>.<br>
* Be aware that since v1.0.0 in this special case you will get <code>UnknownMobile</code> only for:
* {@link MobileDetect#mobile}, not for {@link MobileDetect#phone} and {@link MobileDetect#tablet}.
* In versions before v1.0.0 all 3 methods returned <code>UnknownMobile</code> which was tedious to use.
* <br>
* In most cases you will use the return value just as a boolean.
*
* @returns {String} the key of the phone family or producer, e.g. "iPhone"
* @function MobileDetect#phone
*/
phone: function () {
impl.prepareDetectionCache(this._cache, this.ua, this.maxPhoneWidth);
return this._cache.phone;
},
/**
* Returns the detected tablet type/family string or <tt>null</tt>.
* <br>
* The returned tablet (family or producer) is one of following keys:<br>
* <br><tt>iPad, NexusTablet, GoogleTablet, SamsungTablet, Kindle, SurfaceTablet,
* HPTablet, AsusTablet, BlackBerryTablet, HTCtablet, MotorolaTablet, NookTablet,
* AcerTablet, ToshibaTablet, LGTablet, FujitsuTablet, PrestigioTablet,
* LenovoTablet, DellTablet, YarvikTablet, MedionTablet, ArnovaTablet,
* IntensoTablet, IRUTablet, MegafonTablet, EbodaTablet, AllViewTablet,
* ArchosTablet, AinolTablet, NokiaLumiaTablet, SonyTablet, PhilipsTablet,
* CubeTablet, CobyTablet, MIDTablet, MSITablet, SMiTTablet, RockChipTablet,
* FlyTablet, bqTablet, HuaweiTablet, NecTablet, PantechTablet, BronchoTablet,
* VersusTablet, ZyncTablet, PositivoTablet, NabiTablet, KoboTablet, DanewTablet,
* TexetTablet, PlaystationTablet, TrekstorTablet, PyleAudioTablet, AdvanTablet,
* DanyTechTablet, GalapadTablet, MicromaxTablet, KarbonnTablet, AllFineTablet,
* PROSCANTablet, YONESTablet, ChangJiaTablet, GUTablet, PointOfViewTablet,
* OvermaxTablet, HCLTablet, DPSTablet, VistureTablet, CrestaTablet,
* MediatekTablet, ConcordeTablet, GoCleverTablet, ModecomTablet, VoninoTablet,
* ECSTablet, StorexTablet, VodafoneTablet, EssentielBTablet, RossMoorTablet,
* iMobileTablet, TolinoTablet, AudioSonicTablet, AMPETablet, SkkTablet,
* TecnoTablet, JXDTablet, iJoyTablet, FX2Tablet, XoroTablet, ViewsonicTablet,
* VerizonTablet, OdysTablet, CaptivaTablet, IconbitTablet, TeclastTablet,
* OndaTablet, JaytechTablet, BlaupunktTablet, DigmaTablet, EvolioTablet,
* LavaTablet, AocTablet, MpmanTablet, CelkonTablet, WolderTablet, MediacomTablet,
* MiTablet, NibiruTablet, NexoTablet, LeaderTablet, UbislateTablet,
* PocketBookTablet, KocasoTablet, HisenseTablet, Hudl, TelstraTablet,
* GenericTablet</tt><br>
* <br>
* If the device is not detected by the regular expressions from Mobile-Detect, a test is made against
* the patterns of <a href="http://detectmobilebrowsers.com/">detectmobilebrowsers.com</a>. If this test
* is positive, a value of <code>UnknownTablet</code> or <code>UnknownMobile</code> is returned.<br>
* When used in browser, the decision whether phone or tablet is made based on <code>screen.width/height</code>.<br>
* <br>
* When used server-side (node.js), there is no way to tell the difference between <code>UnknownTablet</code>
* and <code>UnknownMobile</code>, so you will get <code>null</code> here, while {@link MobileDetect#mobile}
* will return <code>UnknownMobile</code>.<br>
* Be aware that since v1.0.0 in this special case you will get <code>UnknownMobile</code> only for:
* {@link MobileDetect#mobile}, not for {@link MobileDetect#phone} and {@link MobileDetect#tablet}.
* In versions before v1.0.0 all 3 methods returned <code>UnknownMobile</code> which was tedious to use.
* <br>
* In most cases you will use the return value just as a boolean.
*
* @returns {String} the key of the tablet family or producer, e.g. "SamsungTablet"
* @function MobileDetect#tablet
*/
tablet: function () {
impl.prepareDetectionCache(this._cache, this.ua, this.maxPhoneWidth);
return this._cache.tablet;
},
/**
* Returns the (first) detected user-agent string or <tt>null</tt>.
* <br>
* The returned user-agent is one of following keys:<br>
* <br><tt>Chrome, Dolfin, Opera, Skyfire, Edge, IE, Firefox, Bolt, TeaShark, Blazer,
* Safari, WeChat, UCBrowser, baiduboxapp, baidubrowser, DiigoBrowser, Mercury,
* ObigoBrowser, NetFront, GenericBrowser, PaleMoon</tt><br>
* <br>
* In most cases calling {@link MobileDetect#userAgent} will be sufficient. But there are rare
* cases where a mobile device pretends to be more than one particular browser. You can get the
* list of all matches with {@link MobileDetect#userAgents} or check for a particular value by
* providing one of the defined keys as first argument to {@link MobileDetect#is}.
*
* @returns {String} the key for the detected user-agent or <tt>null</tt>
* @function MobileDetect#userAgent
*/
userAgent: function () {
if (this._cache.userAgent === undefined) {
this._cache.userAgent = impl.findMatch(impl.mobileDetectRules.uas, this.ua);
}
return this._cache.userAgent;
},
/**
* Returns all detected user-agent strings.
* <br>
* The array is empty or contains one or more of following keys:<br>
* <br><tt>Chrome, Dolfin, Opera, Skyfire, Edge, IE, Firefox, Bolt, TeaShark, Blazer,
* Safari, WeChat, UCBrowser, baiduboxapp, baidubrowser, DiigoBrowser, Mercury,
* ObigoBrowser, NetFront, GenericBrowser, PaleMoon</tt><br>
* <br>
* In most cases calling {@link MobileDetect#userAgent} will be sufficient. But there are rare
* cases where a mobile device pretends to be more than one particular browser. You can get the
* list of all matches with {@link MobileDetect#userAgents} or check for a particular value by
* providing one of the defined keys as first argument to {@link MobileDetect#is}.
*
* @returns {Array} the array of detected user-agent keys or <tt>[]</tt>
* @function MobileDetect#userAgents
*/
userAgents: function () {
if (this._cache.userAgents === undefined) {
this._cache.userAgents = impl.findMatches(impl.mobileDetectRules.uas, this.ua);
}
return this._cache.userAgents;
},
/**
* Returns the detected operating system string or <tt>null</tt>.
* <br>
* The operating system is one of following keys:<br>
* <br><tt>AndroidOS, BlackBerryOS, PalmOS, SymbianOS, WindowsMobileOS, WindowsPhoneOS,
* iOS, iPadOS, SailfishOS, MeeGoOS, MaemoOS, JavaOS, webOS, badaOS, BREWOS</tt><br>
*
* @returns {String} the key for the detected operating system.
* @function MobileDetect#os
*/
os: function () {
if (this._cache.os === undefined) {
this._cache.os = impl.detectOS(this.ua);
}
return this._cache.os;
},
/**
* Get the version (as Number) of the given property in the User-Agent.
* <br>
* Will return a float number. (eg. 2_0 will return 2.0, 4.3.1 will return 4.31)
*
* @param {String} key a key defining a thing which has a version.<br>
* You can use one of following keys:<br>
* <br><tt>Mobile, Build, Version, VendorID, iPad, iPhone, iPod, Kindle, Chrome, Coast,
* Dolfin, Firefox, Fennec, Edge, IE, NetFront, NokiaBrowser, Opera, Opera Mini,
* Opera Mobi, UCBrowser, MQQBrowser, MicroMessenger, baiduboxapp, baidubrowser,
* SamsungBrowser, Iron, Safari, Skyfire, Tizen, Webkit, PaleMoon,
* SailfishBrowser, Gecko, Trident, Presto, Goanna, iOS, Android, Sailfish,
* BlackBerry, BREW, Java, Windows Phone OS, Windows Phone, Windows CE, Windows
* NT, Symbian, webOS</tt><br>
*
* @returns {Number} the version as float or <tt>NaN</tt> if User-Agent doesn't contain this version.
* Be careful when comparing this value with '==' operator!
* @function MobileDetect#version
*/
version: function (key) {
return impl.getVersion(key, this.ua);
},
/**
* Get the version (as String) of the given property in the User-Agent.
* <br>
*
* @param {String} key a key defining a thing which has a version.<br>
* You can use one of following keys:<br>
* <br><tt>Mobile, Build, Version, VendorID, iPad, iPhone, iPod, Kindle, Chrome, Coast,
* Dolfin, Firefox, Fennec, Edge, IE, NetFront, NokiaBrowser, Opera, Opera Mini,
* Opera Mobi, UCBrowser, MQQBrowser, MicroMessenger, baiduboxapp, baidubrowser,
* SamsungBrowser, Iron, Safari, Skyfire, Tizen, Webkit, PaleMoon,
* SailfishBrowser, Gecko, Trident, Presto, Goanna, iOS, Android, Sailfish,
* BlackBerry, BREW, Java, Windows Phone OS, Windows Phone, Windows CE, Windows
* NT, Symbian, webOS</tt><br>
*
* @returns {String} the "raw" version as String or <tt>null</tt> if User-Agent doesn't contain this version.
*
* @function MobileDetect#versionStr
*/
versionStr: function (key) {
return impl.getVersionStr(key, this.ua);
},
/**
* Global test key against userAgent, os, phone, tablet and some other properties of userAgent string.
*
* @param {String} key the key (case-insensitive) of a userAgent, an operating system, phone or
* tablet family.<br>
* For a complete list of possible values, see {@link MobileDetect#userAgent},
* {@link MobileDetect#os}, {@link MobileDetect#phone}, {@link MobileDetect#tablet}.<br>
* Additionally you have following keys:<br>
* <br><tt>Bot, MobileBot, DesktopMode, TV, WebKit, Console, Watch</tt><br>
*
* @returns {boolean} <tt>true</tt> when the given key is one of the defined keys of userAgent, os, phone,
* tablet or one of the listed additional keys, otherwise <tt>false</tt>
* @function MobileDetect#is
*/
is: function (key) {
return containsIC(this.userAgents(), key) ||
equalIC(key, this.os()) ||
equalIC(key, this.phone()) ||
equalIC(key, this.tablet()) ||
containsIC(impl.findMatches(impl.mobileDetectRules.utils, this.ua), key);
},
/**
* Do a quick test against navigator::userAgent.
*
* @param {String|RegExp} pattern the pattern, either as String or RegExp
* (a string will be converted to a case-insensitive RegExp).
* @returns {boolean} <tt>true</tt> when the pattern matches, otherwise <tt>false</tt>
* @function MobileDetect#match
*/
match: function (pattern) {
if (!(pattern instanceof RegExp)) {
pattern = new RegExp(pattern, 'i');
}
return pattern.test(this.ua);
},
/**
* Checks whether the mobile device can be considered as phone regarding <code>screen.width</code>.
* <br>
* Obviously this method makes sense in browser environments only (not for Node.js)!
* @param {number} [maxPhoneWidth] the maximum logical pixels (aka. CSS-pixels) to be considered as phone.<br>
* The argument is optional and if not present or falsy, the value of the constructor is taken.
* @returns {boolean|undefined} <code>undefined</code> if screen size wasn't detectable, else <code>true</code>
* when screen.width is less or equal to maxPhoneWidth, otherwise <code>false</code>.<br>
* Will always return <code>undefined</code> server-side.
*/
isPhoneSized: function (maxPhoneWidth) {
return MobileDetect.isPhoneSized(maxPhoneWidth || this.maxPhoneWidth);
},
/**
* Returns the mobile grade ('A', 'B', 'C').
*
* @returns {String} one of the mobile grades ('A', 'B', 'C').
* @function MobileDetect#mobileGrade
*/
mobileGrade: function () {
if (this._cache.grade === undefined) {
this._cache.grade = impl.mobileGrade(this);
}
return this._cache.grade;
}
};
// environment-dependent
if (typeof window !== 'undefined' && window.screen) {
MobileDetect.isPhoneSized = function (maxPhoneWidth) {
return maxPhoneWidth < 0 ? undefined : impl.getDeviceSmallerSide() <= maxPhoneWidth;
};
} else {
MobileDetect.isPhoneSized = function () {};
}
// should not be replaced by a completely new object - just overwrite existing methods
MobileDetect._impl = impl;
MobileDetect.version = '1.4.5 2021-03-13';
return MobileDetect;
}); // end of call of define()
})((function (undefined) {
if (typeof module !== 'undefined' && module.exports) {
return function (factory) { module.exports = factory(); };
} else if (typeof define === 'function' && define.amd) {
return define;
} else if (typeof window !== 'undefined') {
return function (factory) { window.MobileDetect = factory(); };
} else {
// please file a bug if you get this error!
throw new Error('unknown environment');
}
})());
webpack://frontend-mybets/../../node_modules/moment/locale/ sync ^\.\/(en)$
function webpackEmptyContext(req) {
var e = new Error("Cannot find module '" + req + "'");
e.code = 'MODULE_NOT_FOUND';
throw e;
}
webpackEmptyContext.keys = () => ([]);
webpackEmptyContext.resolve = webpackEmptyContext;
webpackEmptyContext.id = 39253;
module.exports = webpackEmptyContext;
webpack://frontend-mybets/../../node_modules/moment/moment.js
//! moment.js
//! version : 2.29.4
//! authors : Tim Wood, Iskren Chernev, Moment.js contributors
//! license : MIT
//! momentjs.com
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
global.moment = factory()
}(this, (function () { 'use strict';
var hookCallback;
function hooks() {
return hookCallback.apply(null, arguments);
}
// This is done to register the method called with moment()
// without creating circular dependencies.
function setHookCallback(callback) {
hookCallback = callback;
}
function isArray(input) {
return (
input instanceof Array ||
Object.prototype.toString.call(input) === '[object Array]'
);
}
function isObject(input) {
// IE8 will treat undefined and null as object if it wasn't for
// input != null
return (
input != null &&
Object.prototype.toString.call(input) === '[object Object]'
);
}
function hasOwnProp(a, b) {
return Object.prototype.hasOwnProperty.call(a, b);
}
function isObjectEmpty(obj) {
if (Object.getOwnPropertyNames) {
return Object.getOwnPropertyNames(obj).length === 0;
} else {
var k;
for (k in obj) {
if (hasOwnProp(obj, k)) {
return false;
}
}
return true;
}
}
function isUndefined(input) {
return input === void 0;
}
function isNumber(input) {
return (
typeof input === 'number' ||
Object.prototype.toString.call(input) === '[object Number]'
);
}
function isDate(input) {
return (
input instanceof Date ||
Object.prototype.toString.call(input) === '[object Date]'
);
}
function map(arr, fn) {
var res = [],
i,
arrLen = arr.length;
for (i = 0; i < arrLen; ++i) {
res.push(fn(arr[i], i));
}
return res;
}
function extend(a, b) {
for (var i in b) {
if (hasOwnProp(b, i)) {
a[i] = b[i];
}
}
if (hasOwnProp(b, 'toString')) {
a.toString = b.toString;
}
if (hasOwnProp(b, 'valueOf')) {
a.valueOf = b.valueOf;
}
return a;
}
function createUTC(input, format, locale, strict) {
return createLocalOrUTC(input, format, locale, strict, true).utc();
}
function defaultParsingFlags() {
// We need to deep clone this object.
return {
empty: false,
unusedTokens: [],
unusedInput: [],
overflow: -2,
charsLeftOver: 0,
nullInput: false,
invalidEra: null,
invalidMonth: null,
invalidFormat: false,
userInvalidated: false,
iso: false,
parsedDateParts: [],
era: null,
meridiem: null,
rfc2822: false,
weekdayMismatch: false,
};
}
function getParsingFlags(m) {
if (m._pf == null) {
m._pf = defaultParsingFlags();
}
return m._pf;
}
var some;
if (Array.prototype.some) {
some = Array.prototype.some;
} else {
some = function (fun) {
var t = Object(this),
len = t.length >>> 0,
i;
for (i = 0; i < len; i++) {
if (i in t && fun.call(this, t[i], i, t)) {
return true;
}
}
return false;
};
}
function isValid(m) {
if (m._isValid == null) {
var flags = getParsingFlags(m),
parsedParts = some.call(flags.parsedDateParts, function (i) {
return i != null;
}),
isNowValid =
!isNaN(m._d.getTime()) &&
flags.overflow < 0 &&
!flags.empty &&
!flags.invalidEra &&
!flags.invalidMonth &&
!flags.invalidWeekday &&
!flags.weekdayMismatch &&
!flags.nullInput &&
!flags.invalidFormat &&
!flags.userInvalidated &&
(!flags.meridiem || (flags.meridiem && parsedParts));
if (m._strict) {
isNowValid =
isNowValid &&
flags.charsLeftOver === 0 &&
flags.unusedTokens.length === 0 &&
flags.bigHour === undefined;
}
if (Object.isFrozen == null || !Object.isFrozen(m)) {
m._isValid = isNowValid;
} else {
return isNowValid;
}
}
return m._isValid;
}
function createInvalid(flags) {
var m = createUTC(NaN);
if (flags != null) {
extend(getParsingFlags(m), flags);
} else {
getParsingFlags(m).userInvalidated = true;
}
return m;
}
// Plugins that add properties should also add the key here (null value),
// so we can properly clone ourselves.
var momentProperties = (hooks.momentProperties = []),
updateInProgress = false;
function copyConfig(to, from) {
var i,
prop,
val,
momentPropertiesLen = momentProperties.length;
if (!isUndefined(from._isAMomentObject)) {
to._isAMomentObject = from._isAMomentObject;
}
if (!isUndefined(from._i)) {
to._i = from._i;
}
if (!isUndefined(from._f)) {
to._f = from._f;
}
if (!isUndefined(from._l)) {
to._l = from._l;
}
if (!isUndefined(from._strict)) {
to._strict = from._strict;
}
if (!isUndefined(from._tzm)) {
to._tzm = from._tzm;
}
if (!isUndefined(from._isUTC)) {
to._isUTC = from._isUTC;
}
if (!isUndefined(from._offset)) {
to._offset = from._offset;
}
if (!isUndefined(from._pf)) {
to._pf = getParsingFlags(from);
}
if (!isUndefined(from._locale)) {
to._locale = from._locale;
}
if (momentPropertiesLen > 0) {
for (i = 0; i < momentPropertiesLen; i++) {
prop = momentProperties[i];
val = from[prop];
if (!isUndefined(val)) {
to[prop] = val;
}
}
}
return to;
}
// Moment prototype object
function Moment(config) {
copyConfig(this, config);
this._d = new Date(config._d != null ? config._d.getTime() : NaN);
if (!this.isValid()) {
this._d = new Date(NaN);
}
// Prevent infinite loop in case updateOffset creates new moment
// objects.
if (updateInProgress === false) {
updateInProgress = true;
hooks.updateOffset(this);
updateInProgress = false;
}
}
function isMoment(obj) {
return (
obj instanceof Moment || (obj != null && obj._isAMomentObject != null)
);
}
function warn(msg) {
if (
hooks.suppressDeprecationWarnings === false &&
typeof console !== 'undefined' &&
console.warn
) {
console.warn('Deprecation warning: ' + msg);
}
}
function deprecate(msg, fn) {
var firstTime = true;
return extend(function () {
if (hooks.deprecationHandler != null) {
hooks.deprecationHandler(null, msg);
}
if (firstTime) {
var args = [],
arg,
i,
key,
argLen = arguments.length;
for (i = 0; i < argLen; i++) {
arg = '';
if (typeof arguments[i] === 'object') {
arg += '\n[' + i + '] ';
for (key in arguments[0]) {
if (hasOwnProp(arguments[0], key)) {
arg += key + ': ' + arguments[0][key] + ', ';
}
}
arg = arg.slice(0, -2); // Remove trailing comma and space
} else {
arg = arguments[i];
}
args.push(arg);
}
warn(
msg +
'\nArguments: ' +
Array.prototype.slice.call(args).join('') +
'\n' +
new Error().stack
);
firstTime = false;
}
return fn.apply(this, arguments);
}, fn);
}
var deprecations = {};
function deprecateSimple(name, msg) {
if (hooks.deprecationHandler != null) {
hooks.deprecationHandler(name, msg);
}
if (!deprecations[name]) {
warn(msg);
deprecations[name] = true;
}
}
hooks.suppressDeprecationWarnings = false;
hooks.deprecationHandler = null;
function isFunction(input) {
return (
(typeof Function !== 'undefined' && input instanceof Function) ||
Object.prototype.toString.call(input) === '[object Function]'
);
}
function set(config) {
var prop, i;
for (i in config) {
if (hasOwnProp(config, i)) {
prop = config[i];
if (isFunction(prop)) {
this[i] = prop;
} else {
this['_' + i] = prop;
}
}
}
this._config = config;
// Lenient ordinal parsing accepts just a number in addition to
// number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
// TODO: Remove "ordinalParse" fallback in next major release.
this._dayOfMonthOrdinalParseLenient = new RegExp(
(this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) +
'|' +
/\d{1,2}/.source
);
}
function mergeConfigs(parentConfig, childConfig) {
var res = extend({}, parentConfig),
prop;
for (prop in childConfig) {
if (hasOwnProp(childConfig, prop)) {
if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
res[prop] = {};
extend(res[prop], parentConfig[prop]);
extend(res[prop], childConfig[prop]);
} else if (childConfig[prop] != null) {
res[prop] = childConfig[prop];
} else {
delete res[prop];
}
}
}
for (prop in parentConfig) {
if (
hasOwnProp(parentConfig, prop) &&
!hasOwnProp(childConfig, prop) &&
isObject(parentConfig[prop])
) {
// make sure changes to properties don't modify parent config
res[prop] = extend({}, res[prop]);
}
}
return res;
}
function Locale(config) {
if (config != null) {
this.set(config);
}
}
var keys;
if (Object.keys) {
keys = Object.keys;
} else {
keys = function (obj) {
var i,
res = [];
for (i in obj) {
if (hasOwnProp(obj, i)) {
res.push(i);
}
}
return res;
};
}
var defaultCalendar = {
sameDay: '[Today at] LT',
nextDay: '[Tomorrow at] LT',
nextWeek: 'dddd [at] LT',
lastDay: '[Yesterday at] LT',
lastWeek: '[Last] dddd [at] LT',
sameElse: 'L',
};
function calendar(key, mom, now) {
var output = this._calendar[key] || this._calendar['sameElse'];
return isFunction(output) ? output.call(mom, now) : output;
}
function zeroFill(number, targetLength, forceSign) {
var absNumber = '' + Math.abs(number),
zerosToFill = targetLength - absNumber.length,
sign = number >= 0;
return (
(sign ? (forceSign ? '+' : '') : '-') +
Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) +
absNumber
);
}
var formattingTokens =
/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,
localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,
formatFunctions = {},
formatTokenFunctions = {};
// token: 'M'
// padded: ['MM', 2]
// ordinal: 'Mo'
// callback: function () { this.month() + 1 }
function addFormatToken(token, padded, ordinal, callback) {
var func = callback;
if (typeof callback === 'string') {
func = function () {
return this[callback]();
};
}
if (token) {
formatTokenFunctions[token] = func;
}
if (padded) {
formatTokenFunctions[padded[0]] = function () {
return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
};
}
if (ordinal) {
formatTokenFunctions[ordinal] = function () {
return this.localeData().ordinal(
func.apply(this, arguments),
token
);
};
}
}
function removeFormattingTokens(input) {
if (input.match(/\[[\s\S]/)) {
return input.replace(/^\[|\]$/g, '');
}
return input.replace(/\\/g, '');
}
function makeFormatFunction(format) {
var array = format.match(formattingTokens),
i,
length;
for (i = 0, length = array.length; i < length; i++) {
if (formatTokenFunctions[array[i]]) {
array[i] = formatTokenFunctions[array[i]];
} else {
array[i] = removeFormattingTokens(array[i]);
}
}
return function (mom) {
var output = '',
i;
for (i = 0; i < length; i++) {
output += isFunction(array[i])
? array[i].call(mom, format)
: array[i];
}
return output;
};
}
// format date using native date object
function formatMoment(m, format) {
if (!m.isValid()) {
return m.localeData().invalidDate();
}
format = expandFormat(format, m.localeData());
formatFunctions[format] =
formatFunctions[format] || makeFormatFunction(format);
return formatFunctions[format](m);
}
function expandFormat(format, locale) {
var i = 5;
function replaceLongDateFormatTokens(input) {
return locale.longDateFormat(input) || input;
}
localFormattingTokens.lastIndex = 0;
while (i >= 0 && localFormattingTokens.test(format)) {
format = format.replace(
localFormattingTokens,
replaceLongDateFormatTokens
);
localFormattingTokens.lastIndex = 0;
i -= 1;
}
return format;
}
var defaultLongDateFormat = {
LTS: 'h:mm:ss A',
LT: 'h:mm A',
L: 'MM/DD/YYYY',
LL: 'MMMM D, YYYY',
LLL: 'MMMM D, YYYY h:mm A',
LLLL: 'dddd, MMMM D, YYYY h:mm A',
};
function longDateFormat(key) {
var format = this._longDateFormat[key],
formatUpper = this._longDateFormat[key.toUpperCase()];
if (format || !formatUpper) {
return format;
}
this._longDateFormat[key] = formatUpper
.match(formattingTokens)
.map(function (tok) {
if (
tok === 'MMMM' ||
tok === 'MM' ||
tok === 'DD' ||
tok === 'dddd'
) {
return tok.slice(1);
}
return tok;
})
.join('');
return this._longDateFormat[key];
}
var defaultInvalidDate = 'Invalid date';
function invalidDate() {
return this._invalidDate;
}
var defaultOrdinal = '%d',
defaultDayOfMonthOrdinalParse = /\d{1,2}/;
function ordinal(number) {
return this._ordinal.replace('%d', number);
}
var defaultRelativeTime = {
future: 'in %s',
past: '%s ago',
s: 'a few seconds',
ss: '%d seconds',
m: 'a minute',
mm: '%d minutes',
h: 'an hour',
hh: '%d hours',
d: 'a day',
dd: '%d days',
w: 'a week',
ww: '%d weeks',
M: 'a month',
MM: '%d months',
y: 'a year',
yy: '%d years',
};
function relativeTime(number, withoutSuffix, string, isFuture) {
var output = this._relativeTime[string];
return isFunction(output)
? output(number, withoutSuffix, string, isFuture)
: output.replace(/%d/i, number);
}
function pastFuture(diff, output) {
var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
return isFunction(format) ? format(output) : format.replace(/%s/i, output);
}
var aliases = {};
function addUnitAlias(unit, shorthand) {
var lowerCase = unit.toLowerCase();
aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
}
function normalizeUnits(units) {
return typeof units === 'string'
? aliases[units] || aliases[units.toLowerCase()]
: undefined;
}
function normalizeObjectUnits(inputObject) {
var normalizedInput = {},
normalizedProp,
prop;
for (prop in inputObject) {
if (hasOwnProp(inputObject, prop)) {
normalizedProp = normalizeUnits(prop);
if (normalizedProp) {
normalizedInput[normalizedProp] = inputObject[prop];
}
}
}
return normalizedInput;
}
var priorities = {};
function addUnitPriority(unit, priority) {
priorities[unit] = priority;
}
function getPrioritizedUnits(unitsObj) {
var units = [],
u;
for (u in unitsObj) {
if (hasOwnProp(unitsObj, u)) {
units.push({ unit: u, priority: priorities[u] });
}
}
units.sort(function (a, b) {
return a.priority - b.priority;
});
return units;
}
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
function absFloor(number) {
if (number < 0) {
// -0 -> 0
return Math.ceil(number) || 0;
} else {
return Math.floor(number);
}
}
function toInt(argumentForCoercion) {
var coercedNumber = +argumentForCoercion,
value = 0;
if (coercedNumber !== 0 && isFinite(coercedNumber)) {
value = absFloor(coercedNumber);
}
return value;
}
function makeGetSet(unit, keepTime) {
return function (value) {
if (value != null) {
set$1(this, unit, value);
hooks.updateOffset(this, keepTime);
return this;
} else {
return get(this, unit);
}
};
}
function get(mom, unit) {
return mom.isValid()
? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]()
: NaN;
}
function set$1(mom, unit, value) {
if (mom.isValid() && !isNaN(value)) {
if (
unit === 'FullYear' &&
isLeapYear(mom.year()) &&
mom.month() === 1 &&
mom.date() === 29
) {
value = toInt(value);
mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](
value,
mom.month(),
daysInMonth(value, mom.month())
);
} else {
mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
}
}
}
// MOMENTS
function stringGet(units) {
units = normalizeUnits(units);
if (isFunction(this[units])) {
return this[units]();
}
return this;
}
function stringSet(units, value) {
if (typeof units === 'object') {
units = normalizeObjectUnits(units);
var prioritized = getPrioritizedUnits(units),
i,
prioritizedLen = prioritized.length;
for (i = 0; i < prioritizedLen; i++) {
this[prioritized[i].unit](units[prioritized[i].unit]);
}
} else {
units = normalizeUnits(units);
if (isFunction(this[units])) {
return this[units](value);
}
}
return this;
}
var match1 = /\d/, // 0 - 9
match2 = /\d\d/, // 00 - 99
match3 = /\d{3}/, // 000 - 999
match4 = /\d{4}/, // 0000 - 9999
match6 = /[+-]?\d{6}/, // -999999 - 999999
match1to2 = /\d\d?/, // 0 - 99
match3to4 = /\d\d\d\d?/, // 999 - 9999
match5to6 = /\d\d\d\d\d\d?/, // 99999 - 999999
match1to3 = /\d{1,3}/, // 0 - 999
match1to4 = /\d{1,4}/, // 0 - 9999
match1to6 = /[+-]?\d{1,6}/, // -999999 - 999999
matchUnsigned = /\d+/, // 0 - inf
matchSigned = /[+-]?\d+/, // -inf - inf
matchOffset = /Z|[+-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi, // +00 -00 +00:00 -00:00 +0000 -0000 or Z
matchTimestamp = /[+-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
// any word (or two) characters or numbers including two/three word month in arabic.
// includes scottish gaelic two word and hyphenated months
matchWord =
/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i,
regexes;
regexes = {};
function addRegexToken(token, regex, strictRegex) {
regexes[token] = isFunction(regex)
? regex
: function (isStrict, localeData) {
return isStrict && strictRegex ? strictRegex : regex;
};
}
function getParseRegexForToken(token, config) {
if (!hasOwnProp(regexes, token)) {
return new RegExp(unescapeFormat(token));
}
return regexes[token](config._strict, config._locale);
}
// Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
function unescapeFormat(s) {
return regexEscape(
s
.replace('\\', '')
.replace(
/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,
function (matched, p1, p2, p3, p4) {
return p1 || p2 || p3 || p4;
}
)
);
}
function regexEscape(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var tokens = {};
function addParseToken(token, callback) {
var i,
func = callback,
tokenLen;
if (typeof token === 'string') {
token = [token];
}
if (isNumber(callback)) {
func = function (input, array) {
array[callback] = toInt(input);
};
}
tokenLen = token.length;
for (i = 0; i < tokenLen; i++) {
tokens[token[i]] = func;
}
}
function addWeekParseToken(token, callback) {
addParseToken(token, function (input, array, config, token) {
config._w = config._w || {};
callback(input, config._w, config, token);
});
}
function addTimeToArrayFromToken(token, input, config) {
if (input != null && hasOwnProp(tokens, token)) {
tokens[token](input, config._a, config, token);
}
}
var YEAR = 0,
MONTH = 1,
DATE = 2,
HOUR = 3,
MINUTE = 4,
SECOND = 5,
MILLISECOND = 6,
WEEK = 7,
WEEKDAY = 8;
function mod(n, x) {
return ((n % x) + x) % x;
}
var indexOf;
if (Array.prototype.indexOf) {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function (o) {
// I know
var i;
for (i = 0; i < this.length; ++i) {
if (this[i] === o) {
return i;
}
}
return -1;
};
}
function daysInMonth(year, month) {
if (isNaN(year) || isNaN(month)) {
return NaN;
}
var modMonth = mod(month, 12);
year += (month - modMonth) / 12;
return modMonth === 1
? isLeapYear(year)
? 29
: 28
: 31 - ((modMonth % 7) % 2);
}
// FORMATTING
addFormatToken('M', ['MM', 2], 'Mo', function () {
return this.month() + 1;
});
addFormatToken('MMM', 0, 0, function (format) {
return this.localeData().monthsShort(this, format);
});
addFormatToken('MMMM', 0, 0, function (format) {
return this.localeData().months(this, format);
});
// ALIASES
addUnitAlias('month', 'M');
// PRIORITY
addUnitPriority('month', 8);
// PARSING
addRegexToken('M', match1to2);
addRegexToken('MM', match1to2, match2);
addRegexToken('MMM', function (isStrict, locale) {
return locale.monthsShortRegex(isStrict);
});
addRegexToken('MMMM', function (isStrict, locale) {
return locale.monthsRegex(isStrict);
});
addParseToken(['M', 'MM'], function (input, array) {
array[MONTH] = toInt(input) - 1;
});
addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
var month = config._locale.monthsParse(input, token, config._strict);
// if we didn't find a month name, mark the date as invalid.
if (month != null) {
array[MONTH] = month;
} else {
getParsingFlags(config).invalidMonth = input;
}
});
// LOCALES
var defaultLocaleMonths =
'January_February_March_April_May_June_July_August_September_October_November_December'.split(
'_'
),
defaultLocaleMonthsShort =
'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,
defaultMonthsShortRegex = matchWord,
defaultMonthsRegex = matchWord;
function localeMonths(m, format) {
if (!m) {
return isArray(this._months)
? this._months
: this._months['standalone'];
}
return isArray(this._months)
? this._months[m.month()]
: this._months[
(this._months.isFormat || MONTHS_IN_FORMAT).test(format)
? 'format'
: 'standalone'
][m.month()];
}
function localeMonthsShort(m, format) {
if (!m) {
return isArray(this._monthsShort)
? this._monthsShort
: this._monthsShort['standalone'];
}
return isArray(this._monthsShort)
? this._monthsShort[m.month()]
: this._monthsShort[
MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'
][m.month()];
}
function handleStrictParse(monthName, format, strict) {
var i,
ii,
mom,
llc = monthName.toLocaleLowerCase();
if (!this._monthsParse) {
// this is not used
this._monthsParse = [];
this._longMonthsParse = [];
this._shortMonthsParse = [];
for (i = 0; i < 12; ++i) {
mom = createUTC([2000, i]);
this._shortMonthsParse[i] = this.monthsShort(
mom,
''
).toLocaleLowerCase();
this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
}
}
if (strict) {
if (format === 'MMM') {
ii = indexOf.call(this._shortMonthsParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._longMonthsParse, llc);
return ii !== -1 ? ii : null;
}
} else {
if (format === 'MMM') {
ii = indexOf.call(this._shortMonthsParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._longMonthsParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._longMonthsParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._shortMonthsParse, llc);
return ii !== -1 ? ii : null;
}
}
}
function localeMonthsParse(monthName, format, strict) {
var i, mom, regex;
if (this._monthsParseExact) {
return handleStrictParse.call(this, monthName, format, strict);
}
if (!this._monthsParse) {
this._monthsParse = [];
this._longMonthsParse = [];
this._shortMonthsParse = [];
}
// TODO: add sorting
// Sorting makes sure if one month (or abbr) is a prefix of another
// see sorting in computeMonthsParse
for (i = 0; i < 12; i++) {
// make the regex if we don't have it already
mom = createUTC([2000, i]);
if (strict && !this._longMonthsParse[i]) {
this._longMonthsParse[i] = new RegExp(
'^' + this.months(mom, '').replace('.', '') + '$',
'i'
);
this._shortMonthsParse[i] = new RegExp(
'^' + this.monthsShort(mom, '').replace('.', '') + '$',
'i'
);
}
if (!strict && !this._monthsParse[i]) {
regex =
'^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
}
// test the regex
if (
strict &&
format === 'MMMM' &&
this._longMonthsParse[i].test(monthName)
) {
return i;
} else if (
strict &&
format === 'MMM' &&
this._shortMonthsParse[i].test(monthName)
) {
return i;
} else if (!strict && this._monthsParse[i].test(monthName)) {
return i;
}
}
}
// MOMENTS
function setMonth(mom, value) {
var dayOfMonth;
if (!mom.isValid()) {
// No op
return mom;
}
if (typeof value === 'string') {
if (/^\d+$/.test(value)) {
value = toInt(value);
} else {
value = mom.localeData().monthsParse(value);
// TODO: Another silent failure?
if (!isNumber(value)) {
return mom;
}
}
}
dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
return mom;
}
function getSetMonth(value) {
if (value != null) {
setMonth(this, value);
hooks.updateOffset(this, true);
return this;
} else {
return get(this, 'Month');
}
}
function getDaysInMonth() {
return daysInMonth(this.year(), this.month());
}
function monthsShortRegex(isStrict) {
if (this._monthsParseExact) {
if (!hasOwnProp(this, '_monthsRegex')) {
computeMonthsParse.call(this);
}
if (isStrict) {
return this._monthsShortStrictRegex;
} else {
return this._monthsShortRegex;
}
} else {
if (!hasOwnProp(this, '_monthsShortRegex')) {
this._monthsShortRegex = defaultMonthsShortRegex;
}
return this._monthsShortStrictRegex && isStrict
? this._monthsShortStrictRegex
: this._monthsShortRegex;
}
}
function monthsRegex(isStrict) {
if (this._monthsParseExact) {
if (!hasOwnProp(this, '_monthsRegex')) {
computeMonthsParse.call(this);
}
if (isStrict) {
return this._monthsStrictRegex;
} else {
return this._monthsRegex;
}
} else {
if (!hasOwnProp(this, '_monthsRegex')) {
this._monthsRegex = defaultMonthsRegex;
}
return this._monthsStrictRegex && isStrict
? this._monthsStrictRegex
: this._monthsRegex;
}
}
function computeMonthsParse() {
function cmpLenRev(a, b) {
return b.length - a.length;
}
var shortPieces = [],
longPieces = [],
mixedPieces = [],
i,
mom;
for (i = 0; i < 12; i++) {
// make the regex if we don't have it already
mom = createUTC([2000, i]);
shortPieces.push(this.monthsShort(mom, ''));
longPieces.push(this.months(mom, ''));
mixedPieces.push(this.months(mom, ''));
mixedPieces.push(this.monthsShort(mom, ''));
}
// Sorting makes sure if one month (or abbr) is a prefix of another it
// will match the longer piece.
shortPieces.sort(cmpLenRev);
longPieces.sort(cmpLenRev);
mixedPieces.sort(cmpLenRev);
for (i = 0; i < 12; i++) {
shortPieces[i] = regexEscape(shortPieces[i]);
longPieces[i] = regexEscape(longPieces[i]);
}
for (i = 0; i < 24; i++) {
mixedPieces[i] = regexEscape(mixedPieces[i]);
}
this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
this._monthsShortRegex = this._monthsRegex;
this._monthsStrictRegex = new RegExp(
'^(' + longPieces.join('|') + ')',
'i'
);
this._monthsShortStrictRegex = new RegExp(
'^(' + shortPieces.join('|') + ')',
'i'
);
}
// FORMATTING
addFormatToken('Y', 0, 0, function () {
var y = this.year();
return y <= 9999 ? zeroFill(y, 4) : '+' + y;
});
addFormatToken(0, ['YY', 2], 0, function () {
return this.year() % 100;
});
addFormatToken(0, ['YYYY', 4], 0, 'year');
addFormatToken(0, ['YYYYY', 5], 0, 'year');
addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
// ALIASES
addUnitAlias('year', 'y');
// PRIORITIES
addUnitPriority('year', 1);
// PARSING
addRegexToken('Y', matchSigned);
addRegexToken('YY', match1to2, match2);
addRegexToken('YYYY', match1to4, match4);
addRegexToken('YYYYY', match1to6, match6);
addRegexToken('YYYYYY', match1to6, match6);
addParseToken(['YYYYY', 'YYYYYY'], YEAR);
addParseToken('YYYY', function (input, array) {
array[YEAR] =
input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
});
addParseToken('YY', function (input, array) {
array[YEAR] = hooks.parseTwoDigitYear(input);
});
addParseToken('Y', function (input, array) {
array[YEAR] = parseInt(input, 10);
});
// HELPERS
function daysInYear(year) {
return isLeapYear(year) ? 366 : 365;
}
// HOOKS
hooks.parseTwoDigitYear = function (input) {
return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
};
// MOMENTS
var getSetYear = makeGetSet('FullYear', true);
function getIsLeapYear() {
return isLeapYear(this.year());
}
function createDate(y, m, d, h, M, s, ms) {
// can't just apply() to create a date:
// https://stackoverflow.com/q/181348
var date;
// the date constructor remaps years 0-99 to 1900-1999
if (y < 100 && y >= 0) {
// preserve leap years using a full 400 year cycle, then reset
date = new Date(y + 400, m, d, h, M, s, ms);
if (isFinite(date.getFullYear())) {
date.setFullYear(y);
}
} else {
date = new Date(y, m, d, h, M, s, ms);
}
return date;
}
function createUTCDate(y) {
var date, args;
// the Date.UTC function remaps years 0-99 to 1900-1999
if (y < 100 && y >= 0) {
args = Array.prototype.slice.call(arguments);
// preserve leap years using a full 400 year cycle, then reset
args[0] = y + 400;
date = new Date(Date.UTC.apply(null, args));
if (isFinite(date.getUTCFullYear())) {
date.setUTCFullYear(y);
}
} else {
date = new Date(Date.UTC.apply(null, arguments));
}
return date;
}
// start-of-first-week - start-of-year
function firstWeekOffset(year, dow, doy) {
var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
fwd = 7 + dow - doy,
// first-week day local weekday -- which local weekday is fwd
fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
return -fwdlw + fwd - 1;
}
// https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
var localWeekday = (7 + weekday - dow) % 7,
weekOffset = firstWeekOffset(year, dow, doy),
dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
resYear,
resDayOfYear;
if (dayOfYear <= 0) {
resYear = year - 1;
resDayOfYear = daysInYear(resYear) + dayOfYear;
} else if (dayOfYear > daysInYear(year)) {
resYear = year + 1;
resDayOfYear = dayOfYear - daysInYear(year);
} else {
resYear = year;
resDayOfYear = dayOfYear;
}
return {
year: resYear,
dayOfYear: resDayOfYear,
};
}
function weekOfYear(mom, dow, doy) {
var weekOffset = firstWeekOffset(mom.year(), dow, doy),
week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
resWeek,
resYear;
if (week < 1) {
resYear = mom.year() - 1;
resWeek = week + weeksInYear(resYear, dow, doy);
} else if (week > weeksInYear(mom.year(), dow, doy)) {
resWeek = week - weeksInYear(mom.year(), dow, doy);
resYear = mom.year() + 1;
} else {
resYear = mom.year();
resWeek = week;
}
return {
week: resWeek,
year: resYear,
};
}
function weeksInYear(year, dow, doy) {
var weekOffset = firstWeekOffset(year, dow, doy),
weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
}
// FORMATTING
addFormatToken('w', ['ww', 2], 'wo', 'week');
addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
// ALIASES
addUnitAlias('week', 'w');
addUnitAlias('isoWeek', 'W');
// PRIORITIES
addUnitPriority('week', 5);
addUnitPriority('isoWeek', 5);
// PARSING
addRegexToken('w', match1to2);
addRegexToken('ww', match1to2, match2);
addRegexToken('W', match1to2);
addRegexToken('WW', match1to2, match2);
addWeekParseToken(
['w', 'ww', 'W', 'WW'],
function (input, week, config, token) {
week[token.substr(0, 1)] = toInt(input);
}
);
// HELPERS
// LOCALES
function localeWeek(mom) {
return weekOfYear(mom, this._week.dow, this._week.doy).week;
}
var defaultLocaleWeek = {
dow: 0, // Sunday is the first day of the week.
doy: 6, // The week that contains Jan 6th is the first week of the year.
};
function localeFirstDayOfWeek() {
return this._week.dow;
}
function localeFirstDayOfYear() {
return this._week.doy;
}
// MOMENTS
function getSetWeek(input) {
var week = this.localeData().week(this);
return input == null ? week : this.add((input - week) * 7, 'd');
}
function getSetISOWeek(input) {
var week = weekOfYear(this, 1, 4).week;
return input == null ? week : this.add((input - week) * 7, 'd');
}
// FORMATTING
addFormatToken('d', 0, 'do', 'day');
addFormatToken('dd', 0, 0, function (format) {
return this.localeData().weekdaysMin(this, format);
});
addFormatToken('ddd', 0, 0, function (format) {
return this.localeData().weekdaysShort(this, format);
});
addFormatToken('dddd', 0, 0, function (format) {
return this.localeData().weekdays(this, format);
});
addFormatToken('e', 0, 0, 'weekday');
addFormatToken('E', 0, 0, 'isoWeekday');
// ALIASES
addUnitAlias('day', 'd');
addUnitAlias('weekday', 'e');
addUnitAlias('isoWeekday', 'E');
// PRIORITY
addUnitPriority('day', 11);
addUnitPriority('weekday', 11);
addUnitPriority('isoWeekday', 11);
// PARSING
addRegexToken('d', match1to2);
addRegexToken('e', match1to2);
addRegexToken('E', match1to2);
addRegexToken('dd', function (isStrict, locale) {
return locale.weekdaysMinRegex(isStrict);
});
addRegexToken('ddd', function (isStrict, locale) {
return locale.weekdaysShortRegex(isStrict);
});
addRegexToken('dddd', function (isStrict, locale) {
return locale.weekdaysRegex(isStrict);
});
addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
var weekday = config._locale.weekdaysParse(input, token, config._strict);
// if we didn't get a weekday name, mark the date as invalid
if (weekday != null) {
week.d = weekday;
} else {
getParsingFlags(config).invalidWeekday = input;
}
});
addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
week[token] = toInt(input);
});
// HELPERS
function parseWeekday(input, locale) {
if (typeof input !== 'string') {
return input;
}
if (!isNaN(input)) {
return parseInt(input, 10);
}
input = locale.weekdaysParse(input);
if (typeof input === 'number') {
return input;
}
return null;
}
function parseIsoWeekday(input, locale) {
if (typeof input === 'string') {
return locale.weekdaysParse(input) % 7 || 7;
}
return isNaN(input) ? null : input;
}
// LOCALES
function shiftWeekdays(ws, n) {
return ws.slice(n, 7).concat(ws.slice(0, n));
}
var defaultLocaleWeekdays =
'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
defaultWeekdaysRegex = matchWord,
defaultWeekdaysShortRegex = matchWord,
defaultWeekdaysMinRegex = matchWord;
function localeWeekdays(m, format) {
var weekdays = isArray(this._weekdays)
? this._weekdays
: this._weekdays[
m && m !== true && this._weekdays.isFormat.test(format)
? 'format'
: 'standalone'
];
return m === true
? shiftWeekdays(weekdays, this._week.dow)
: m
? weekdays[m.day()]
: weekdays;
}
function localeWeekdaysShort(m) {
return m === true
? shiftWeekdays(this._weekdaysShort, this._week.dow)
: m
? this._weekdaysShort[m.day()]
: this._weekdaysShort;
}
function localeWeekdaysMin(m) {
return m === true
? shiftWeekdays(this._weekdaysMin, this._week.dow)
: m
? this._weekdaysMin[m.day()]
: this._weekdaysMin;
}
function handleStrictParse$1(weekdayName, format, strict) {
var i,
ii,
mom,
llc = weekdayName.toLocaleLowerCase();
if (!this._weekdaysParse) {
this._weekdaysParse = [];
this._shortWeekdaysParse = [];
this._minWeekdaysParse = [];
for (i = 0; i < 7; ++i) {
mom = createUTC([2000, 1]).day(i);
this._minWeekdaysParse[i] = this.weekdaysMin(
mom,
''
).toLocaleLowerCase();
this._shortWeekdaysParse[i] = this.weekdaysShort(
mom,
''
).toLocaleLowerCase();
this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
}
}
if (strict) {
if (format === 'dddd') {
ii = indexOf.call(this._weekdaysParse, llc);
return ii !== -1 ? ii : null;
} else if (format === 'ddd') {
ii = indexOf.call(this._shortWeekdaysParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._minWeekdaysParse, llc);
return ii !== -1 ? ii : null;
}
} else {
if (format === 'dddd') {
ii = indexOf.call(this._weekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._shortWeekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._minWeekdaysParse, llc);
return ii !== -1 ? ii : null;
} else if (format === 'ddd') {
ii = indexOf.call(this._shortWeekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._weekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._minWeekdaysParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._minWeekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._weekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._shortWeekdaysParse, llc);
return ii !== -1 ? ii : null;
}
}
}
function localeWeekdaysParse(weekdayName, format, strict) {
var i, mom, regex;
if (this._weekdaysParseExact) {
return handleStrictParse$1.call(this, weekdayName, format, strict);
}
if (!this._weekdaysParse) {
this._weekdaysParse = [];
this._minWeekdaysParse = [];
this._shortWeekdaysParse = [];
this._fullWeekdaysParse = [];
}
for (i = 0; i < 7; i++) {
// make the regex if we don't have it already
mom = createUTC([2000, 1]).day(i);
if (strict && !this._fullWeekdaysParse[i]) {
this._fullWeekdaysParse[i] = new RegExp(
'^' + this.weekdays(mom, '').replace('.', '\\.?') + '$',
'i'
);
this._shortWeekdaysParse[i] = new RegExp(
'^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$',
'i'
);
this._minWeekdaysParse[i] = new RegExp(
'^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$',
'i'
);
}
if (!this._weekdaysParse[i]) {
regex =
'^' +
this.weekdays(mom, '') +
'|^' +
this.weekdaysShort(mom, '') +
'|^' +
this.weekdaysMin(mom, '');
this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
}
// test the regex
if (
strict &&
format === 'dddd' &&
this._fullWeekdaysParse[i].test(weekdayName)
) {
return i;
} else if (
strict &&
format === 'ddd' &&
this._shortWeekdaysParse[i].test(weekdayName)
) {
return i;
} else if (
strict &&
format === 'dd' &&
this._minWeekdaysParse[i].test(weekdayName)
) {
return i;
} else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
return i;
}
}
}
// MOMENTS
function getSetDayOfWeek(input) {
if (!this.isValid()) {
return input != null ? this : NaN;
}
var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
if (input != null) {
input = parseWeekday(input, this.localeData());
return this.add(input - day, 'd');
} else {
return day;
}
}
function getSetLocaleDayOfWeek(input) {
if (!this.isValid()) {
return input != null ? this : NaN;
}
var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
return input == null ? weekday : this.add(input - weekday, 'd');
}
function getSetISODayOfWeek(input) {
if (!this.isValid()) {
return input != null ? this : NaN;
}
// behaves the same as moment#day except
// as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
// as a setter, sunday should belong to the previous week.
if (input != null) {
var weekday = parseIsoWeekday(input, this.localeData());
return this.day(this.day() % 7 ? weekday : weekday - 7);
} else {
return this.day() || 7;
}
}
function weekdaysRegex(isStrict) {
if (this._weekdaysParseExact) {
if (!hasOwnProp(this, '_weekdaysRegex')) {
computeWeekdaysParse.call(this);
}
if (isStrict) {
return this._weekdaysStrictRegex;
} else {
return this._weekdaysRegex;
}
} else {
if (!hasOwnProp(this, '_weekdaysRegex')) {
this._weekdaysRegex = defaultWeekdaysRegex;
}
return this._weekdaysStrictRegex && isStrict
? this._weekdaysStrictRegex
: this._weekdaysRegex;
}
}
function weekdaysShortRegex(isStrict) {
if (this._weekdaysParseExact) {
if (!hasOwnProp(this, '_weekdaysRegex')) {
computeWeekdaysParse.call(this);
}
if (isStrict) {
return this._weekdaysShortStrictRegex;
} else {
return this._weekdaysShortRegex;
}
} else {
if (!hasOwnProp(this, '_weekdaysShortRegex')) {
this._weekdaysShortRegex = defaultWeekdaysShortRegex;
}
return this._weekdaysShortStrictRegex && isStrict
? this._weekdaysShortStrictRegex
: this._weekdaysShortRegex;
}
}
function weekdaysMinRegex(isStrict) {
if (this._weekdaysParseExact) {
if (!hasOwnProp(this, '_weekdaysRegex')) {
computeWeekdaysParse.call(this);
}
if (isStrict) {
return this._weekdaysMinStrictRegex;
} else {
return this._weekdaysMinRegex;
}
} else {
if (!hasOwnProp(this, '_weekdaysMinRegex')) {
this._weekdaysMinRegex = defaultWeekdaysMinRegex;
}
return this._weekdaysMinStrictRegex && isStrict
? this._weekdaysMinStrictRegex
: this._weekdaysMinRegex;
}
}
function computeWeekdaysParse() {
function cmpLenRev(a, b) {
return b.length - a.length;
}
var minPieces = [],
shortPieces = [],
longPieces = [],
mixedPieces = [],
i,
mom,
minp,
shortp,
longp;
for (i = 0; i < 7; i++) {
// make the regex if we don't have it already
mom = createUTC([2000, 1]).day(i);
minp = regexEscape(this.weekdaysMin(mom, ''));
shortp = regexEscape(this.weekdaysShort(mom, ''));
longp = regexEscape(this.weekdays(mom, ''));
minPieces.push(minp);
shortPieces.push(shortp);
longPieces.push(longp);
mixedPieces.push(minp);
mixedPieces.push(shortp);
mixedPieces.push(longp);
}
// Sorting makes sure if one weekday (or abbr) is a prefix of another it
// will match the longer piece.
minPieces.sort(cmpLenRev);
shortPieces.sort(cmpLenRev);
longPieces.sort(cmpLenRev);
mixedPieces.sort(cmpLenRev);
this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
this._weekdaysShortRegex = this._weekdaysRegex;
this._weekdaysMinRegex = this._weekdaysRegex;
this._weekdaysStrictRegex = new RegExp(
'^(' + longPieces.join('|') + ')',
'i'
);
this._weekdaysShortStrictRegex = new RegExp(
'^(' + shortPieces.join('|') + ')',
'i'
);
this._weekdaysMinStrictRegex = new RegExp(
'^(' + minPieces.join('|') + ')',
'i'
);
}
// FORMATTING
function hFormat() {
return this.hours() % 12 || 12;
}
function kFormat() {
return this.hours() || 24;
}
addFormatToken('H', ['HH', 2], 0, 'hour');
addFormatToken('h', ['hh', 2], 0, hFormat);
addFormatToken('k', ['kk', 2], 0, kFormat);
addFormatToken('hmm', 0, 0, function () {
return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
});
addFormatToken('hmmss', 0, 0, function () {
return (
'' +
hFormat.apply(this) +
zeroFill(this.minutes(), 2) +
zeroFill(this.seconds(), 2)
);
});
addFormatToken('Hmm', 0, 0, function () {
return '' + this.hours() + zeroFill(this.minutes(), 2);
});
addFormatToken('Hmmss', 0, 0, function () {
return (
'' +
this.hours() +
zeroFill(this.minutes(), 2) +
zeroFill(this.seconds(), 2)
);
});
function meridiem(token, lowercase) {
addFormatToken(token, 0, 0, function () {
return this.localeData().meridiem(
this.hours(),
this.minutes(),
lowercase
);
});
}
meridiem('a', true);
meridiem('A', false);
// ALIASES
addUnitAlias('hour', 'h');
// PRIORITY
addUnitPriority('hour', 13);
// PARSING
function matchMeridiem(isStrict, locale) {
return locale._meridiemParse;
}
addRegexToken('a', matchMeridiem);
addRegexToken('A', matchMeridiem);
addRegexToken('H', match1to2);
addRegexToken('h', match1to2);
addRegexToken('k', match1to2);
addRegexToken('HH', match1to2, match2);
addRegexToken('hh', match1to2, match2);
addRegexToken('kk', match1to2, match2);
addRegexToken('hmm', match3to4);
addRegexToken('hmmss', match5to6);
addRegexToken('Hmm', match3to4);
addRegexToken('Hmmss', match5to6);
addParseToken(['H', 'HH'], HOUR);
addParseToken(['k', 'kk'], function (input, array, config) {
var kInput = toInt(input);
array[HOUR] = kInput === 24 ? 0 : kInput;
});
addParseToken(['a', 'A'], function (input, array, config) {
config._isPm = config._locale.isPM(input);
config._meridiem = input;
});
addParseToken(['h', 'hh'], function (input, array, config) {
array[HOUR] = toInt(input);
getParsingFlags(config).bigHour = true;
});
addParseToken('hmm', function (input, array, config) {
var pos = input.length - 2;
array[HOUR] = toInt(input.substr(0, pos));
array[MINUTE] = toInt(input.substr(pos));
getParsingFlags(config).bigHour = true;
});
addParseToken('hmmss', function (input, array, config) {
var pos1 = input.length - 4,
pos2 = input.length - 2;
array[HOUR] = toInt(input.substr(0, pos1));
array[MINUTE] = toInt(input.substr(pos1, 2));
array[SECOND] = toInt(input.substr(pos2));
getParsingFlags(config).bigHour = true;
});
addParseToken('Hmm', function (input, array, config) {
var pos = input.length - 2;
array[HOUR] = toInt(input.substr(0, pos));
array[MINUTE] = toInt(input.substr(pos));
});
addParseToken('Hmmss', function (input, array, config) {
var pos1 = input.length - 4,
pos2 = input.length - 2;
array[HOUR] = toInt(input.substr(0, pos1));
array[MINUTE] = toInt(input.substr(pos1, 2));
array[SECOND] = toInt(input.substr(pos2));
});
// LOCALES
function localeIsPM(input) {
// IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
// Using charAt should be more compatible.
return (input + '').toLowerCase().charAt(0) === 'p';
}
var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i,
// Setting the hour should keep the time, because the user explicitly
// specified which hour they want. So trying to maintain the same hour (in
// a new timezone) makes sense. Adding/subtracting hours does not follow
// this rule.
getSetHour = makeGetSet('Hours', true);
function localeMeridiem(hours, minutes, isLower) {
if (hours > 11) {
return isLower ? 'pm' : 'PM';
} else {
return isLower ? 'am' : 'AM';
}
}
var baseConfig = {
calendar: defaultCalendar,
longDateFormat: defaultLongDateFormat,
invalidDate: defaultInvalidDate,
ordinal: defaultOrdinal,
dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
relativeTime: defaultRelativeTime,
months: defaultLocaleMonths,
monthsShort: defaultLocaleMonthsShort,
week: defaultLocaleWeek,
weekdays: defaultLocaleWeekdays,
weekdaysMin: defaultLocaleWeekdaysMin,
weekdaysShort: defaultLocaleWeekdaysShort,
meridiemParse: defaultLocaleMeridiemParse,
};
// internal storage for locale config files
var locales = {},
localeFamilies = {},
globalLocale;
function commonPrefix(arr1, arr2) {
var i,
minl = Math.min(arr1.length, arr2.length);
for (i = 0; i < minl; i += 1) {
if (arr1[i] !== arr2[i]) {
return i;
}
}
return minl;
}
function normalizeLocale(key) {
return key ? key.toLowerCase().replace('_', '-') : key;
}
// pick the locale from the array
// try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
// substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
function chooseLocale(names) {
var i = 0,
j,
next,
locale,
split;
while (i < names.length) {
split = normalizeLocale(names[i]).split('-');
j = split.length;
next = normalizeLocale(names[i + 1]);
next = next ? next.split('-') : null;
while (j > 0) {
locale = loadLocale(split.slice(0, j).join('-'));
if (locale) {
return locale;
}
if (
next &&
next.length >= j &&
commonPrefix(split, next) >= j - 1
) {
//the next array item is better than a shallower substring of this one
break;
}
j--;
}
i++;
}
return globalLocale;
}
function isLocaleNameSane(name) {
// Prevent names that look like filesystem paths, i.e contain '/' or '\'
return name.match('^[^/\\\\]*$') != null;
}
function loadLocale(name) {
var oldLocale = null,
aliasedRequire;
// TODO: Find a better way to register and load all the locales in Node
if (
locales[name] === undefined &&
typeof module !== 'undefined' &&
module &&
module.exports &&
isLocaleNameSane(name)
) {
try {
oldLocale = globalLocale._abbr;
aliasedRequire = require;
aliasedRequire('./locale/' + name);
getSetGlobalLocale(oldLocale);
} catch (e) {
// mark as not found to avoid repeating expensive file require call causing high CPU
// when trying to find en-US, en_US, en-us for every format call
locales[name] = null; // null means not found
}
}
return locales[name];
}
// This function will load locale and then set the global locale. If
// no arguments are passed in, it will simply return the current global
// locale key.
function getSetGlobalLocale(key, values) {
var data;
if (key) {
if (isUndefined(values)) {
data = getLocale(key);
} else {
data = defineLocale(key, values);
}
if (data) {
// moment.duration._locale = moment._locale = data;
globalLocale = data;
} else {
if (typeof console !== 'undefined' && console.warn) {
//warn user if arguments are passed but the locale could not be set
console.warn(
'Locale ' + key + ' not found. Did you forget to load it?'
);
}
}
}
return globalLocale._abbr;
}
function defineLocale(name, config) {
if (config !== null) {
var locale,
parentConfig = baseConfig;
config.abbr = name;
if (locales[name] != null) {
deprecateSimple(
'defineLocaleOverride',
'use moment.updateLocale(localeName, config) to change ' +
'an existing locale. moment.defineLocale(localeName, ' +
'config) should only be used for creating a new locale ' +
'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.'
);
parentConfig = locales[name]._config;
} else if (config.parentLocale != null) {
if (locales[config.parentLocale] != null) {
parentConfig = locales[config.parentLocale]._config;
} else {
locale = loadLocale(config.parentLocale);
if (locale != null) {
parentConfig = locale._config;
} else {
if (!localeFamilies[config.parentLocale]) {
localeFamilies[config.parentLocale] = [];
}
localeFamilies[config.parentLocale].push({
name: name,
config: config,
});
return null;
}
}
}
locales[name] = new Locale(mergeConfigs(parentConfig, config));
if (localeFamilies[name]) {
localeFamilies[name].forEach(function (x) {
defineLocale(x.name, x.config);
});
}
// backwards compat for now: also set the locale
// make sure we set the locale AFTER all child locales have been
// created, so we won't end up with the child locale set.
getSetGlobalLocale(name);
return locales[name];
} else {
// useful for testing
delete locales[name];
return null;
}
}
function updateLocale(name, config) {
if (config != null) {
var locale,
tmpLocale,
parentConfig = baseConfig;
if (locales[name] != null && locales[name].parentLocale != null) {
// Update existing child locale in-place to avoid memory-leaks
locales[name].set(mergeConfigs(locales[name]._config, config));
} else {
// MERGE
tmpLocale = loadLocale(name);
if (tmpLocale != null) {
parentConfig = tmpLocale._config;
}
config = mergeConfigs(parentConfig, config);
if (tmpLocale == null) {
// updateLocale is called for creating a new locale
// Set abbr so it will have a name (getters return
// undefined otherwise).
config.abbr = name;
}
locale = new Locale(config);
locale.parentLocale = locales[name];
locales[name] = locale;
}
// backwards compat for now: also set the locale
getSetGlobalLocale(name);
} else {
// pass null for config to unupdate, useful for tests
if (locales[name] != null) {
if (locales[name].parentLocale != null) {
locales[name] = locales[name].parentLocale;
if (name === getSetGlobalLocale()) {
getSetGlobalLocale(name);
}
} else if (locales[name] != null) {
delete locales[name];
}
}
}
return locales[name];
}
// returns locale data
function getLocale(key) {
var locale;
if (key && key._locale && key._locale._abbr) {
key = key._locale._abbr;
}
if (!key) {
return globalLocale;
}
if (!isArray(key)) {
//short-circuit everything else
locale = loadLocale(key);
if (locale) {
return locale;
}
key = [key];
}
return chooseLocale(key);
}
function listLocales() {
return keys(locales);
}
function checkOverflow(m) {
var overflow,
a = m._a;
if (a && getParsingFlags(m).overflow === -2) {
overflow =
a[MONTH] < 0 || a[MONTH] > 11
? MONTH
: a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH])
? DATE
: a[HOUR] < 0 ||
a[HOUR] > 24 ||
(a[HOUR] === 24 &&
(a[MINUTE] !== 0 ||
a[SECOND] !== 0 ||
a[MILLISECOND] !== 0))
? HOUR
: a[MINUTE] < 0 || a[MINUTE] > 59
? MINUTE
: a[SECOND] < 0 || a[SECOND] > 59
? SECOND
: a[MILLISECOND] < 0 || a[MILLISECOND] > 999
? MILLISECOND
: -1;
if (
getParsingFlags(m)._overflowDayOfYear &&
(overflow < YEAR || overflow > DATE)
) {
overflow = DATE;
}
if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
overflow = WEEK;
}
if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
overflow = WEEKDAY;
}
getParsingFlags(m).overflow = overflow;
}
return m;
}
// iso 8601 regex
// 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
var extendedIsoRegex =
/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,
basicIsoRegex =
/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,
tzRegex = /Z|[+-]\d\d(?::?\d\d)?/,
isoDates = [
['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
['GGGG-[W]WW', /\d{4}-W\d\d/, false],
['YYYY-DDD', /\d{4}-\d{3}/],
['YYYY-MM', /\d{4}-\d\d/, false],
['YYYYYYMMDD', /[+-]\d{10}/],
['YYYYMMDD', /\d{8}/],
['GGGG[W]WWE', /\d{4}W\d{3}/],
['GGGG[W]WW', /\d{4}W\d{2}/, false],
['YYYYDDD', /\d{7}/],
['YYYYMM', /\d{6}/, false],
['YYYY', /\d{4}/, false],
],
// iso time formats and regexes
isoTimes = [
['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
['HH:mm:ss', /\d\d:\d\d:\d\d/],
['HH:mm', /\d\d:\d\d/],
['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
['HHmmss', /\d\d\d\d\d\d/],
['HHmm', /\d\d\d\d/],
['HH', /\d\d/],
],
aspNetJsonRegex = /^\/?Date\((-?\d+)/i,
// RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
rfc2822 =
/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/,
obsOffsets = {
UT: 0,
GMT: 0,
EDT: -4 * 60,
EST: -5 * 60,
CDT: -5 * 60,
CST: -6 * 60,
MDT: -6 * 60,
MST: -7 * 60,
PDT: -7 * 60,
PST: -8 * 60,
};
// date from iso format
function configFromISO(config) {
var i,
l,
string = config._i,
match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
allowTime,
dateFormat,
timeFormat,
tzFormat,
isoDatesLen = isoDates.length,
isoTimesLen = isoTimes.length;
if (match) {
getParsingFlags(config).iso = true;
for (i = 0, l = isoDatesLen; i < l; i++) {
if (isoDates[i][1].exec(match[1])) {
dateFormat = isoDates[i][0];
allowTime = isoDates[i][2] !== false;
break;
}
}
if (dateFormat == null) {
config._isValid = false;
return;
}
if (match[3]) {
for (i = 0, l = isoTimesLen; i < l; i++) {
if (isoTimes[i][1].exec(match[3])) {
// match[2] should be 'T' or space
timeFormat = (match[2] || ' ') + isoTimes[i][0];
break;
}
}
if (timeFormat == null) {
config._isValid = false;
return;
}
}
if (!allowTime && timeFormat != null) {
config._isValid = false;
return;
}
if (match[4]) {
if (tzRegex.exec(match[4])) {
tzFormat = 'Z';
} else {
config._isValid = false;
return;
}
}
config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
configFromStringAndFormat(config);
} else {
config._isValid = false;
}
}
function extractFromRFC2822Strings(
yearStr,
monthStr,
dayStr,
hourStr,
minuteStr,
secondStr
) {
var result = [
untruncateYear(yearStr),
defaultLocaleMonthsShort.indexOf(monthStr),
parseInt(dayStr, 10),
parseInt(hourStr, 10),
parseInt(minuteStr, 10),
];
if (secondStr) {
result.push(parseInt(secondStr, 10));
}
return result;
}
function untruncateYear(yearStr) {
var year = parseInt(yearStr, 10);
if (year <= 49) {
return 2000 + year;
} else if (year <= 999) {
return 1900 + year;
}
return year;
}
function preprocessRFC2822(s) {
// Remove comments and folding whitespace and replace multiple-spaces with a single space
return s
.replace(/\([^()]*\)|[\n\t]/g, ' ')
.replace(/(\s\s+)/g, ' ')
.replace(/^\s\s*/, '')
.replace(/\s\s*$/, '');
}
function checkWeekday(weekdayStr, parsedInput, config) {
if (weekdayStr) {
// TODO: Replace the vanilla JS Date object with an independent day-of-week check.
var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr),
weekdayActual = new Date(
parsedInput[0],
parsedInput[1],
parsedInput[2]
).getDay();
if (weekdayProvided !== weekdayActual) {
getParsingFlags(config).weekdayMismatch = true;
config._isValid = false;
return false;
}
}
return true;
}
function calculateOffset(obsOffset, militaryOffset, numOffset) {
if (obsOffset) {
return obsOffsets[obsOffset];
} else if (militaryOffset) {
// the only allowed military tz is Z
return 0;
} else {
var hm = parseInt(numOffset, 10),
m = hm % 100,
h = (hm - m) / 100;
return h * 60 + m;
}
}
// date and time from ref 2822 format
function configFromRFC2822(config) {
var match = rfc2822.exec(preprocessRFC2822(config._i)),
parsedArray;
if (match) {
parsedArray = extractFromRFC2822Strings(
match[4],
match[3],
match[2],
match[5],
match[6],
match[7]
);
if (!checkWeekday(match[1], parsedArray, config)) {
return;
}
config._a = parsedArray;
config._tzm = calculateOffset(match[8], match[9], match[10]);
config._d = createUTCDate.apply(null, config._a);
config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
getParsingFlags(config).rfc2822 = true;
} else {
config._isValid = false;
}
}
// date from 1) ASP.NET, 2) ISO, 3) RFC 2822 formats, or 4) optional fallback if parsing isn't strict
function configFromString(config) {
var matched = aspNetJsonRegex.exec(config._i);
if (matched !== null) {
config._d = new Date(+matched[1]);
return;
}
configFromISO(config);
if (config._isValid === false) {
delete config._isValid;
} else {
return;
}
configFromRFC2822(config);
if (config._isValid === false) {
delete config._isValid;
} else {
return;
}
if (config._strict) {
config._isValid = false;
} else {
// Final attempt, use Input Fallback
hooks.createFromInputFallback(config);
}
}
hooks.createFromInputFallback = deprecate(
'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' +
'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' +
'discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.',
function (config) {
config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
}
);
// Pick the first defined of two or three arguments.
function defaults(a, b, c) {
if (a != null) {
return a;
}
if (b != null) {
return b;
}
return c;
}
function currentDateArray(config) {
// hooks is actually the exported moment object
var nowValue = new Date(hooks.now());
if (config._useUTC) {
return [
nowValue.getUTCFullYear(),
nowValue.getUTCMonth(),
nowValue.getUTCDate(),
];
}
return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
}
// convert an array to a date.
// the array should mirror the parameters below
// note: all values past the year are optional and will default to the lowest possible value.
// [year, month, day , hour, minute, second, millisecond]
function configFromArray(config) {
var i,
date,
input = [],
currentDate,
expectedWeekday,
yearToUse;
if (config._d) {
return;
}
currentDate = currentDateArray(config);
//compute day of the year from weeks and weekdays
if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
dayOfYearFromWeekInfo(config);
}
//if the day of the year is set, figure out what it is
if (config._dayOfYear != null) {
yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
if (
config._dayOfYear > daysInYear(yearToUse) ||
config._dayOfYear === 0
) {
getParsingFlags(config)._overflowDayOfYear = true;
}
date = createUTCDate(yearToUse, 0, config._dayOfYear);
config._a[MONTH] = date.getUTCMonth();
config._a[DATE] = date.getUTCDate();
}
// Default to current date.
// * if no year, month, day of month are given, default to today
// * if day of month is given, default month and year
// * if month is given, default only year
// * if year is given, don't default anything
for (i = 0; i < 3 && config._a[i] == null; ++i) {
config._a[i] = input[i] = currentDate[i];
}
// Zero out whatever was not defaulted, including time
for (; i < 7; i++) {
config._a[i] = input[i] =
config._a[i] == null ? (i === 2 ? 1 : 0) : config._a[i];
}
// Check for 24:00:00.000
if (
config._a[HOUR] === 24 &&
config._a[MINUTE] === 0 &&
config._a[SECOND] === 0 &&
config._a[MILLISECOND] === 0
) {
config._nextDay = true;
config._a[HOUR] = 0;
}
config._d = (config._useUTC ? createUTCDate : createDate).apply(
null,
input
);
expectedWeekday = config._useUTC
? config._d.getUTCDay()
: config._d.getDay();
// Apply timezone offset from input. The actual utcOffset can be changed
// with parseZone.
if (config._tzm != null) {
config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
}
if (config._nextDay) {
config._a[HOUR] = 24;
}
// check for mismatching day of week
if (
config._w &&
typeof config._w.d !== 'undefined' &&
config._w.d !== expectedWeekday
) {
getParsingFlags(config).weekdayMismatch = true;
}
}
function dayOfYearFromWeekInfo(config) {
var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek;
w = config._w;
if (w.GG != null || w.W != null || w.E != null) {
dow = 1;
doy = 4;
// TODO: We need to take the current isoWeekYear, but that depends on
// how we interpret now (local, utc, fixed offset). So create
// a now version of current config (take local/utc/offset flags, and
// create now).
weekYear = defaults(
w.GG,
config._a[YEAR],
weekOfYear(createLocal(), 1, 4).year
);
week = defaults(w.W, 1);
weekday = defaults(w.E, 1);
if (weekday < 1 || weekday > 7) {
weekdayOverflow = true;
}
} else {
dow = config._locale._week.dow;
doy = config._locale._week.doy;
curWeek = weekOfYear(createLocal(), dow, doy);
weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);
// Default to current week.
week = defaults(w.w, curWeek.week);
if (w.d != null) {
// weekday -- low day numbers are considered next week
weekday = w.d;
if (weekday < 0 || weekday > 6) {
weekdayOverflow = true;
}
} else if (w.e != null) {
// local weekday -- counting starts from beginning of week
weekday = w.e + dow;
if (w.e < 0 || w.e > 6) {
weekdayOverflow = true;
}
} else {
// default to beginning of week
weekday = dow;
}
}
if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
getParsingFlags(config)._overflowWeeks = true;
} else if (weekdayOverflow != null) {
getParsingFlags(config)._overflowWeekday = true;
} else {
temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
config._a[YEAR] = temp.year;
config._dayOfYear = temp.dayOfYear;
}
}
// constant that refers to the ISO standard
hooks.ISO_8601 = function () {};
// constant that refers to the RFC 2822 form
hooks.RFC_2822 = function () {};
// date from string and format string
function configFromStringAndFormat(config) {
// TODO: Move this to another part of the creation flow to prevent circular deps
if (config._f === hooks.ISO_8601) {
configFromISO(config);
return;
}
if (config._f === hooks.RFC_2822) {
configFromRFC2822(config);
return;
}
config._a = [];
getParsingFlags(config).empty = true;
// This array is used to make a Date, either with `new Date` or `Date.UTC`
var string = '' + config._i,
i,
parsedInput,
tokens,
token,
skipped,
stringLength = string.length,
totalParsedInputLength = 0,
era,
tokenLen;
tokens =
expandFormat(config._f, config._locale).match(formattingTokens) || [];
tokenLen = tokens.length;
for (i = 0; i < tokenLen; i++) {
token = tokens[i];
parsedInput = (string.match(getParseRegexForToken(token, config)) ||
[])[0];
if (parsedInput) {
skipped = string.substr(0, string.indexOf(parsedInput));
if (skipped.length > 0) {
getParsingFlags(config).unusedInput.push(skipped);
}
string = string.slice(
string.indexOf(parsedInput) + parsedInput.length
);
totalParsedInputLength += parsedInput.length;
}
// don't parse if it's not a known token
if (formatTokenFunctions[token]) {
if (parsedInput) {
getParsingFlags(config).empty = false;
} else {
getParsingFlags(config).unusedTokens.push(token);
}
addTimeToArrayFromToken(token, parsedInput, config);
} else if (config._strict && !parsedInput) {
getParsingFlags(config).unusedTokens.push(token);
}
}
// add remaining unparsed input length to the string
getParsingFlags(config).charsLeftOver =
stringLength - totalParsedInputLength;
if (string.length > 0) {
getParsingFlags(config).unusedInput.push(string);
}
// clear _12h flag if hour is <= 12
if (
config._a[HOUR] <= 12 &&
getParsingFlags(config).bigHour === true &&
config._a[HOUR] > 0
) {
getParsingFlags(config).bigHour = undefined;
}
getParsingFlags(config).parsedDateParts = config._a.slice(0);
getParsingFlags(config).meridiem = config._meridiem;
// handle meridiem
config._a[HOUR] = meridiemFixWrap(
config._locale,
config._a[HOUR],
config._meridiem
);
// handle era
era = getParsingFlags(config).era;
if (era !== null) {
config._a[YEAR] = config._locale.erasConvertYear(era, config._a[YEAR]);
}
configFromArray(config);
checkOverflow(config);
}
function meridiemFixWrap(locale, hour, meridiem) {
var isPm;
if (meridiem == null) {
// nothing to do
return hour;
}
if (locale.meridiemHour != null) {
return locale.meridiemHour(hour, meridiem);
} else if (locale.isPM != null) {
// Fallback
isPm = locale.isPM(meridiem);
if (isPm && hour < 12) {
hour += 12;
}
if (!isPm && hour === 12) {
hour = 0;
}
return hour;
} else {
// this is not supposed to happen
return hour;
}
}
// date from string and array of format strings
function configFromStringAndArray(config) {
var tempConfig,
bestMoment,
scoreToBeat,
i,
currentScore,
validFormatFound,
bestFormatIsValid = false,
configfLen = config._f.length;
if (configfLen === 0) {
getParsingFlags(config).invalidFormat = true;
config._d = new Date(NaN);
return;
}
for (i = 0; i < configfLen; i++) {
currentScore = 0;
validFormatFound = false;
tempConfig = copyConfig({}, config);
if (config._useUTC != null) {
tempConfig._useUTC = config._useUTC;
}
tempConfig._f = config._f[i];
configFromStringAndFormat(tempConfig);
if (isValid(tempConfig)) {
validFormatFound = true;
}
// if there is any input that was not parsed add a penalty for that format
currentScore += getParsingFlags(tempConfig).charsLeftOver;
//or tokens
currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
getParsingFlags(tempConfig).score = currentScore;
if (!bestFormatIsValid) {
if (
scoreToBeat == null ||
currentScore < scoreToBeat ||
validFormatFound
) {
scoreToBeat = currentScore;
bestMoment = tempConfig;
if (validFormatFound) {
bestFormatIsValid = true;
}
}
} else {
if (currentScore < scoreToBeat) {
scoreToBeat = currentScore;
bestMoment = tempConfig;
}
}
}
extend(config, bestMoment || tempConfig);
}
function configFromObject(config) {
if (config._d) {
return;
}
var i = normalizeObjectUnits(config._i),
dayOrDate = i.day === undefined ? i.date : i.day;
config._a = map(
[i.year, i.month, dayOrDate, i.hour, i.minute, i.second, i.millisecond],
function (obj) {
return obj && parseInt(obj, 10);
}
);
configFromArray(config);
}
function createFromConfig(config) {
var res = new Moment(checkOverflow(prepareConfig(config)));
if (res._nextDay) {
// Adding is smart enough around DST
res.add(1, 'd');
res._nextDay = undefined;
}
return res;
}
function prepareConfig(config) {
var input = config._i,
format = config._f;
config._locale = config._locale || getLocale(config._l);
if (input === null || (format === undefined && input === '')) {
return createInvalid({ nullInput: true });
}
if (typeof input === 'string') {
config._i = input = config._locale.preparse(input);
}
if (isMoment(input)) {
return new Moment(checkOverflow(input));
} else if (isDate(input)) {
config._d = input;
} else if (isArray(format)) {
configFromStringAndArray(config);
} else if (format) {
configFromStringAndFormat(config);
} else {
configFromInput(config);
}
if (!isValid(config)) {
config._d = null;
}
return config;
}
function configFromInput(config) {
var input = config._i;
if (isUndefined(input)) {
config._d = new Date(hooks.now());
} else if (isDate(input)) {
config._d = new Date(input.valueOf());
} else if (typeof input === 'string') {
configFromString(config);
} else if (isArray(input)) {
config._a = map(input.slice(0), function (obj) {
return parseInt(obj, 10);
});
configFromArray(config);
} else if (isObject(input)) {
configFromObject(config);
} else if (isNumber(input)) {
// from milliseconds
config._d = new Date(input);
} else {
hooks.createFromInputFallback(config);
}
}
function createLocalOrUTC(input, format, locale, strict, isUTC) {
var c = {};
if (format === true || format === false) {
strict = format;
format = undefined;
}
if (locale === true || locale === false) {
strict = locale;
locale = undefined;
}
if (
(isObject(input) && isObjectEmpty(input)) ||
(isArray(input) && input.length === 0)
) {
input = undefined;
}
// object construction must be done this way.
// https://github.com/moment/moment/issues/1423
c._isAMomentObject = true;
c._useUTC = c._isUTC = isUTC;
c._l = locale;
c._i = input;
c._f = format;
c._strict = strict;
return createFromConfig(c);
}
function createLocal(input, format, locale, strict) {
return createLocalOrUTC(input, format, locale, strict, false);
}
var prototypeMin = deprecate(
'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
function () {
var other = createLocal.apply(null, arguments);
if (this.isValid() && other.isValid()) {
return other < this ? this : other;
} else {
return createInvalid();
}
}
),
prototypeMax = deprecate(
'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
function () {
var other = createLocal.apply(null, arguments);
if (this.isValid() && other.isValid()) {
return other > this ? this : other;
} else {
return createInvalid();
}
}
);
// Pick a moment m from moments so that m[fn](other) is true for all
// other. This relies on the function fn to be transitive.
//
// moments should either be an array of moment objects or an array, whose
// first element is an array of moment objects.
function pickBy(fn, moments) {
var res, i;
if (moments.length === 1 && isArray(moments[0])) {
moments = moments[0];
}
if (!moments.length) {
return createLocal();
}
res = moments[0];
for (i = 1; i < moments.length; ++i) {
if (!moments[i].isValid() || moments[i][fn](res)) {
res = moments[i];
}
}
return res;
}
// TODO: Use [].sort instead?
function min() {
var args = [].slice.call(arguments, 0);
return pickBy('isBefore', args);
}
function max() {
var args = [].slice.call(arguments, 0);
return pickBy('isAfter', args);
}
var now = function () {
return Date.now ? Date.now() : +new Date();
};
var ordering = [
'year',
'quarter',
'month',
'week',
'day',
'hour',
'minute',
'second',
'millisecond',
];
function isDurationValid(m) {
var key,
unitHasDecimal = false,
i,
orderLen = ordering.length;
for (key in m) {
if (
hasOwnProp(m, key) &&
!(
indexOf.call(ordering, key) !== -1 &&
(m[key] == null || !isNaN(m[key]))
)
) {
return false;
}
}
for (i = 0; i < orderLen; ++i) {
if (m[ordering[i]]) {
if (unitHasDecimal) {
return false; // only allow non-integers for smallest unit
}
if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
unitHasDecimal = true;
}
}
}
return true;
}
function isValid$1() {
return this._isValid;
}
function createInvalid$1() {
return createDuration(NaN);
}
function Duration(duration) {
var normalizedInput = normalizeObjectUnits(duration),
years = normalizedInput.year || 0,
quarters = normalizedInput.quarter || 0,
months = normalizedInput.month || 0,
weeks = normalizedInput.week || normalizedInput.isoWeek || 0,
days = normalizedInput.day || 0,
hours = normalizedInput.hour || 0,
minutes = normalizedInput.minute || 0,
seconds = normalizedInput.second || 0,
milliseconds = normalizedInput.millisecond || 0;
this._isValid = isDurationValid(normalizedInput);
// representation for dateAddRemove
this._milliseconds =
+milliseconds +
seconds * 1e3 + // 1000
minutes * 6e4 + // 1000 * 60
hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
// Because of dateAddRemove treats 24 hours as different from a
// day when working around DST, we need to store them separately
this._days = +days + weeks * 7;
// It is impossible to translate months into days without knowing
// which months you are are talking about, so we have to store
// it separately.
this._months = +months + quarters * 3 + years * 12;
this._data = {};
this._locale = getLocale();
this._bubble();
}
function isDuration(obj) {
return obj instanceof Duration;
}
function absRound(number) {
if (number < 0) {
return Math.round(-1 * number) * -1;
} else {
return Math.round(number);
}
}
// compare two arrays, return the number of differences
function compareArrays(array1, array2, dontConvert) {
var len = Math.min(array1.length, array2.length),
lengthDiff = Math.abs(array1.length - array2.length),
diffs = 0,
i;
for (i = 0; i < len; i++) {
if (
(dontConvert && array1[i] !== array2[i]) ||
(!dontConvert && toInt(array1[i]) !== toInt(array2[i]))
) {
diffs++;
}
}
return diffs + lengthDiff;
}
// FORMATTING
function offset(token, separator) {
addFormatToken(token, 0, 0, function () {
var offset = this.utcOffset(),
sign = '+';
if (offset < 0) {
offset = -offset;
sign = '-';
}
return (
sign +
zeroFill(~~(offset / 60), 2) +
separator +
zeroFill(~~offset % 60, 2)
);
});
}
offset('Z', ':');
offset('ZZ', '');
// PARSING
addRegexToken('Z', matchShortOffset);
addRegexToken('ZZ', matchShortOffset);
addParseToken(['Z', 'ZZ'], function (input, array, config) {
config._useUTC = true;
config._tzm = offsetFromString(matchShortOffset, input);
});
// HELPERS
// timezone chunker
// '+10:00' > ['10', '00']
// '-1530' > ['-15', '30']
var chunkOffset = /([\+\-]|\d\d)/gi;
function offsetFromString(matcher, string) {
var matches = (string || '').match(matcher),
chunk,
parts,
minutes;
if (matches === null) {
return null;
}
chunk = matches[matches.length - 1] || [];
parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
minutes = +(parts[1] * 60) + toInt(parts[2]);
return minutes === 0 ? 0 : parts[0] === '+' ? minutes : -minutes;
}
// Return a moment from input, that is local/utc/zone equivalent to model.
function cloneWithOffset(input, model) {
var res, diff;
if (model._isUTC) {
res = model.clone();
diff =
(isMoment(input) || isDate(input)
? input.valueOf()
: createLocal(input).valueOf()) - res.valueOf();
// Use low-level api, because this fn is low-level api.
res._d.setTime(res._d.valueOf() + diff);
hooks.updateOffset(res, false);
return res;
} else {
return createLocal(input).local();
}
}
function getDateOffset(m) {
// On Firefox.24 Date#getTimezoneOffset returns a floating point.
// https://github.com/moment/moment/pull/1871
return -Math.round(m._d.getTimezoneOffset());
}
// HOOKS
// This function will be called whenever a moment is mutated.
// It is intended to keep the offset in sync with the timezone.
hooks.updateOffset = function () {};
// MOMENTS
// keepLocalTime = true means only change the timezone, without
// affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
// 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
// +0200, so we adjust the time as needed, to be valid.
//
// Keeping the time actually adds/subtracts (one hour)
// from the actual represented time. That is why we call updateOffset
// a second time. In case it wants us to change the offset again
// _changeInProgress == true case, then we have to adjust, because
// there is no such time in the given timezone.
function getSetOffset(input, keepLocalTime, keepMinutes) {
var offset = this._offset || 0,
localAdjust;
if (!this.isValid()) {
return input != null ? this : NaN;
}
if (input != null) {
if (typeof input === 'string') {
input = offsetFromString(matchShortOffset, input);
if (input === null) {
return this;
}
} else if (Math.abs(input) < 16 && !keepMinutes) {
input = input * 60;
}
if (!this._isUTC && keepLocalTime) {
localAdjust = getDateOffset(this);
}
this._offset = input;
this._isUTC = true;
if (localAdjust != null) {
this.add(localAdjust, 'm');
}
if (offset !== input) {
if (!keepLocalTime || this._changeInProgress) {
addSubtract(
this,
createDuration(input - offset, 'm'),
1,
false
);
} else if (!this._changeInProgress) {
this._changeInProgress = true;
hooks.updateOffset(this, true);
this._changeInProgress = null;
}
}
return this;
} else {
return this._isUTC ? offset : getDateOffset(this);
}
}
function getSetZone(input, keepLocalTime) {
if (input != null) {
if (typeof input !== 'string') {
input = -input;
}
this.utcOffset(input, keepLocalTime);
return this;
} else {
return -this.utcOffset();
}
}
function setOffsetToUTC(keepLocalTime) {
return this.utcOffset(0, keepLocalTime);
}
function setOffsetToLocal(keepLocalTime) {
if (this._isUTC) {
this.utcOffset(0, keepLocalTime);
this._isUTC = false;
if (keepLocalTime) {
this.subtract(getDateOffset(this), 'm');
}
}
return this;
}
function setOffsetToParsedOffset() {
if (this._tzm != null) {
this.utcOffset(this._tzm, false, true);
} else if (typeof this._i === 'string') {
var tZone = offsetFromString(matchOffset, this._i);
if (tZone != null) {
this.utcOffset(tZone);
} else {
this.utcOffset(0, true);
}
}
return this;
}
function hasAlignedHourOffset(input) {
if (!this.isValid()) {
return false;
}
input = input ? createLocal(input).utcOffset() : 0;
return (this.utcOffset() - input) % 60 === 0;
}
function isDaylightSavingTime() {
return (
this.utcOffset() > this.clone().month(0).utcOffset() ||
this.utcOffset() > this.clone().month(5).utcOffset()
);
}
function isDaylightSavingTimeShifted() {
if (!isUndefined(this._isDSTShifted)) {
return this._isDSTShifted;
}
var c = {},
other;
copyConfig(c, this);
c = prepareConfig(c);
if (c._a) {
other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
this._isDSTShifted =
this.isValid() && compareArrays(c._a, other.toArray()) > 0;
} else {
this._isDSTShifted = false;
}
return this._isDSTShifted;
}
function isLocal() {
return this.isValid() ? !this._isUTC : false;
}
function isUtcOffset() {
return this.isValid() ? this._isUTC : false;
}
function isUtc() {
return this.isValid() ? this._isUTC && this._offset === 0 : false;
}
// ASP.NET json date format regex
var aspNetRegex = /^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,
// from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
// somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
// and further modified to allow for strings containing both week and day
isoRegex =
/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
function createDuration(input, key) {
var duration = input,
// matching against regexp is expensive, do it on demand
match = null,
sign,
ret,
diffRes;
if (isDuration(input)) {
duration = {
ms: input._milliseconds,
d: input._days,
M: input._months,
};
} else if (isNumber(input) || !isNaN(+input)) {
duration = {};
if (key) {
duration[key] = +input;
} else {
duration.milliseconds = +input;
}
} else if ((match = aspNetRegex.exec(input))) {
sign = match[1] === '-' ? -1 : 1;
duration = {
y: 0,
d: toInt(match[DATE]) * sign,
h: toInt(match[HOUR]) * sign,
m: toInt(match[MINUTE]) * sign,
s: toInt(match[SECOND]) * sign,
ms: toInt(absRound(match[MILLISECOND] * 1000)) * sign, // the millisecond decimal point is included in the match
};
} else if ((match = isoRegex.exec(input))) {
sign = match[1] === '-' ? -1 : 1;
duration = {
y: parseIso(match[2], sign),
M: parseIso(match[3], sign),
w: parseIso(match[4], sign),
d: parseIso(match[5], sign),
h: parseIso(match[6], sign),
m: parseIso(match[7], sign),
s: parseIso(match[8], sign),
};
} else if (duration == null) {
// checks for null or undefined
duration = {};
} else if (
typeof duration === 'object' &&
('from' in duration || 'to' in duration)
) {
diffRes = momentsDifference(
createLocal(duration.from),
createLocal(duration.to)
);
duration = {};
duration.ms = diffRes.milliseconds;
duration.M = diffRes.months;
}
ret = new Duration(duration);
if (isDuration(input) && hasOwnProp(input, '_locale')) {
ret._locale = input._locale;
}
if (isDuration(input) && hasOwnProp(input, '_isValid')) {
ret._isValid = input._isValid;
}
return ret;
}
createDuration.fn = Duration.prototype;
createDuration.invalid = createInvalid$1;
function parseIso(inp, sign) {
// We'd normally use ~~inp for this, but unfortunately it also
// converts floats to ints.
// inp may be undefined, so careful calling replace on it.
var res = inp && parseFloat(inp.replace(',', '.'));
// apply sign while we're at it
return (isNaN(res) ? 0 : res) * sign;
}
function positiveMomentsDifference(base, other) {
var res = {};
res.months =
other.month() - base.month() + (other.year() - base.year()) * 12;
if (base.clone().add(res.months, 'M').isAfter(other)) {
--res.months;
}
res.milliseconds = +other - +base.clone().add(res.months, 'M');
return res;
}
function momentsDifference(base, other) {
var res;
if (!(base.isValid() && other.isValid())) {
return { milliseconds: 0, months: 0 };
}
other = cloneWithOffset(other, base);
if (base.isBefore(other)) {
res = positiveMomentsDifference(base, other);
} else {
res = positiveMomentsDifference(other, base);
res.milliseconds = -res.milliseconds;
res.months = -res.months;
}
return res;
}
// TODO: remove 'name' arg after deprecation is removed
function createAdder(direction, name) {
return function (val, period) {
var dur, tmp;
//invert the arguments, but complain about it
if (period !== null && !isNaN(+period)) {
deprecateSimple(
name,
'moment().' +
name +
'(period, number) is deprecated. Please use moment().' +
name +
'(number, period). ' +
'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.'
);
tmp = val;
val = period;
period = tmp;
}
dur = createDuration(val, period);
addSubtract(this, dur, direction);
return this;
};
}
function addSubtract(mom, duration, isAdding, updateOffset) {
var milliseconds = duration._milliseconds,
days = absRound(duration._days),
months = absRound(duration._months);
if (!mom.isValid()) {
// No op
return;
}
updateOffset = updateOffset == null ? true : updateOffset;
if (months) {
setMonth(mom, get(mom, 'Month') + months * isAdding);
}
if (days) {
set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
}
if (milliseconds) {
mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
}
if (updateOffset) {
hooks.updateOffset(mom, days || months);
}
}
var add = createAdder(1, 'add'),
subtract = createAdder(-1, 'subtract');
function isString(input) {
return typeof input === 'string' || input instanceof String;
}
// type MomentInput = Moment | Date | string | number | (number | string)[] | MomentInputObject | void; // null | undefined
function isMomentInput(input) {
return (
isMoment(input) ||
isDate(input) ||
isString(input) ||
isNumber(input) ||
isNumberOrStringArray(input) ||
isMomentInputObject(input) ||
input === null ||
input === undefined
);
}
function isMomentInputObject(input) {
var objectTest = isObject(input) && !isObjectEmpty(input),
propertyTest = false,
properties = [
'years',
'year',
'y',
'months',
'month',
'M',
'days',
'day',
'd',
'dates',
'date',
'D',
'hours',
'hour',
'h',
'minutes',
'minute',
'm',
'seconds',
'second',
's',
'milliseconds',
'millisecond',
'ms',
],
i,
property,
propertyLen = properties.length;
for (i = 0; i < propertyLen; i += 1) {
property = properties[i];
propertyTest = propertyTest || hasOwnProp(input, property);
}
return objectTest && propertyTest;
}
function isNumberOrStringArray(input) {
var arrayTest = isArray(input),
dataTypeTest = false;
if (arrayTest) {
dataTypeTest =
input.filter(function (item) {
return !isNumber(item) && isString(input);
}).length === 0;
}
return arrayTest && dataTypeTest;
}
function isCalendarSpec(input) {
var objectTest = isObject(input) && !isObjectEmpty(input),
propertyTest = false,
properties = [
'sameDay',
'nextDay',
'lastDay',
'nextWeek',
'lastWeek',
'sameElse',
],
i,
property;
for (i = 0; i < properties.length; i += 1) {
property = properties[i];
propertyTest = propertyTest || hasOwnProp(input, property);
}
return objectTest && propertyTest;
}
function getCalendarFormat(myMoment, now) {
var diff = myMoment.diff(now, 'days', true);
return diff < -6
? 'sameElse'
: diff < -1
? 'lastWeek'
: diff < 0
? 'lastDay'
: diff < 1
? 'sameDay'
: diff < 2
? 'nextDay'
: diff < 7
? 'nextWeek'
: 'sameElse';
}
function calendar$1(time, formats) {
// Support for single parameter, formats only overload to the calendar function
if (arguments.length === 1) {
if (!arguments[0]) {
time = undefined;
formats = undefined;
} else if (isMomentInput(arguments[0])) {
time = arguments[0];
formats = undefined;
} else if (isCalendarSpec(arguments[0])) {
formats = arguments[0];
time = undefined;
}
}
// We want to compare the start of today, vs this.
// Getting start-of-today depends on whether we're local/utc/offset or not.
var now = time || createLocal(),
sod = cloneWithOffset(now, this).startOf('day'),
format = hooks.calendarFormat(this, sod) || 'sameElse',
output =
formats &&
(isFunction(formats[format])
? formats[format].call(this, now)
: formats[format]);
return this.format(
output || this.localeData().calendar(format, this, createLocal(now))
);
}
function clone() {
return new Moment(this);
}
function isAfter(input, units) {
var localInput = isMoment(input) ? input : createLocal(input);
if (!(this.isValid() && localInput.isValid())) {
return false;
}
units = normalizeUnits(units) || 'millisecond';
if (units === 'millisecond') {
return this.valueOf() > localInput.valueOf();
} else {
return localInput.valueOf() < this.clone().startOf(units).valueOf();
}
}
function isBefore(input, units) {
var localInput = isMoment(input) ? input : createLocal(input);
if (!(this.isValid() && localInput.isValid())) {
return false;
}
units = normalizeUnits(units) || 'millisecond';
if (units === 'millisecond') {
return this.valueOf() < localInput.valueOf();
} else {
return this.clone().endOf(units).valueOf() < localInput.valueOf();
}
}
function isBetween(from, to, units, inclusivity) {
var localFrom = isMoment(from) ? from : createLocal(from),
localTo = isMoment(to) ? to : createLocal(to);
if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) {
return false;
}
inclusivity = inclusivity || '()';
return (
(inclusivity[0] === '('
? this.isAfter(localFrom, units)
: !this.isBefore(localFrom, units)) &&
(inclusivity[1] === ')'
? this.isBefore(localTo, units)
: !this.isAfter(localTo, units))
);
}
function isSame(input, units) {
var localInput = isMoment(input) ? input : createLocal(input),
inputMs;
if (!(this.isValid() && localInput.isValid())) {
return false;
}
units = normalizeUnits(units) || 'millisecond';
if (units === 'millisecond') {
return this.valueOf() === localInput.valueOf();
} else {
inputMs = localInput.valueOf();
return (
this.clone().startOf(units).valueOf() <= inputMs &&
inputMs <= this.clone().endOf(units).valueOf()
);
}
}
function isSameOrAfter(input, units) {
return this.isSame(input, units) || this.isAfter(input, units);
}
function isSameOrBefore(input, units) {
return this.isSame(input, units) || this.isBefore(input, units);
}
function diff(input, units, asFloat) {
var that, zoneDelta, output;
if (!this.isValid()) {
return NaN;
}
that = cloneWithOffset(input, this);
if (!that.isValid()) {
return NaN;
}
zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
units = normalizeUnits(units);
switch (units) {
case 'year':
output = monthDiff(this, that) / 12;
break;
case 'month':
output = monthDiff(this, that);
break;
case 'quarter':
output = monthDiff(this, that) / 3;
break;
case 'second':
output = (this - that) / 1e3;
break; // 1000
case 'minute':
output = (this - that) / 6e4;
break; // 1000 * 60
case 'hour':
output = (this - that) / 36e5;
break; // 1000 * 60 * 60
case 'day':
output = (this - that - zoneDelta) / 864e5;
break; // 1000 * 60 * 60 * 24, negate dst
case 'week':
output = (this - that - zoneDelta) / 6048e5;
break; // 1000 * 60 * 60 * 24 * 7, negate dst
default:
output = this - that;
}
return asFloat ? output : absFloor(output);
}
function monthDiff(a, b) {
if (a.date() < b.date()) {
// end-of-month calculations work correct when the start month has more
// days than the end month.
return -monthDiff(b, a);
}
// difference in months
var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()),
// b is in (anchor - 1 month, anchor + 1 month)
anchor = a.clone().add(wholeMonthDiff, 'months'),
anchor2,
adjust;
if (b - anchor < 0) {
anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
// linear across the month
adjust = (b - anchor) / (anchor - anchor2);
} else {
anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
// linear across the month
adjust = (b - anchor) / (anchor2 - anchor);
}
//check for negative zero, return zero if negative zero
return -(wholeMonthDiff + adjust) || 0;
}
hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
function toString() {
return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
}
function toISOString(keepOffset) {
if (!this.isValid()) {
return null;
}
var utc = keepOffset !== true,
m = utc ? this.clone().utc() : this;
if (m.year() < 0 || m.year() > 9999) {
return formatMoment(
m,
utc
? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'
: 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ'
);
}
if (isFunction(Date.prototype.toISOString)) {
// native implementation is ~50x faster, use it when we can
if (utc) {
return this.toDate().toISOString();
} else {
return new Date(this.valueOf() + this.utcOffset() * 60 * 1000)
.toISOString()
.replace('Z', formatMoment(m, 'Z'));
}
}
return formatMoment(
m,
utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ'
);
}
/**
* Return a human readable representation of a moment that can
* also be evaluated to get a new moment which is the same
*
* @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
*/
function inspect() {
if (!this.isValid()) {
return 'moment.invalid(/* ' + this._i + ' */)';
}
var func = 'moment',
zone = '',
prefix,
year,
datetime,
suffix;
if (!this.isLocal()) {
func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
zone = 'Z';
}
prefix = '[' + func + '("]';
year = 0 <= this.year() && this.year() <= 9999 ? 'YYYY' : 'YYYYYY';
datetime = '-MM-DD[T]HH:mm:ss.SSS';
suffix = zone + '[")]';
return this.format(prefix + year + datetime + suffix);
}
function format(inputString) {
if (!inputString) {
inputString = this.isUtc()
? hooks.defaultFormatUtc
: hooks.defaultFormat;
}
var output = formatMoment(this, inputString);
return this.localeData().postformat(output);
}
function from(time, withoutSuffix) {
if (
this.isValid() &&
((isMoment(time) && time.isValid()) || createLocal(time).isValid())
) {
return createDuration({ to: this, from: time })
.locale(this.locale())
.humanize(!withoutSuffix);
} else {
return this.localeData().invalidDate();
}
}
function fromNow(withoutSuffix) {
return this.from(createLocal(), withoutSuffix);
}
function to(time, withoutSuffix) {
if (
this.isValid() &&
((isMoment(time) && time.isValid()) || createLocal(time).isValid())
) {
return createDuration({ from: this, to: time })
.locale(this.locale())
.humanize(!withoutSuffix);
} else {
return this.localeData().invalidDate();
}
}
function toNow(withoutSuffix) {
return this.to(createLocal(), withoutSuffix);
}
// If passed a locale key, it will set the locale for this
// instance. Otherwise, it will return the locale configuration
// variables for this instance.
function locale(key) {
var newLocaleData;
if (key === undefined) {
return this._locale._abbr;
} else {
newLocaleData = getLocale(key);
if (newLocaleData != null) {
this._locale = newLocaleData;
}
return this;
}
}
var lang = deprecate(
'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
function (key) {
if (key === undefined) {
return this.localeData();
} else {
return this.locale(key);
}
}
);
function localeData() {
return this._locale;
}
var MS_PER_SECOND = 1000,
MS_PER_MINUTE = 60 * MS_PER_SECOND,
MS_PER_HOUR = 60 * MS_PER_MINUTE,
MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR;
// actual modulo - handles negative numbers (for dates before 1970):
function mod$1(dividend, divisor) {
return ((dividend % divisor) + divisor) % divisor;
}
function localStartOfDate(y, m, d) {
// the date constructor remaps years 0-99 to 1900-1999
if (y < 100 && y >= 0) {
// preserve leap years using a full 400 year cycle, then reset
return new Date(y + 400, m, d) - MS_PER_400_YEARS;
} else {
return new Date(y, m, d).valueOf();
}
}
function utcStartOfDate(y, m, d) {
// Date.UTC remaps years 0-99 to 1900-1999
if (y < 100 && y >= 0) {
// preserve leap years using a full 400 year cycle, then reset
return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS;
} else {
return Date.UTC(y, m, d);
}
}
function startOf(units) {
var time, startOfDate;
units = normalizeUnits(units);
if (units === undefined || units === 'millisecond' || !this.isValid()) {
return this;
}
startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
switch (units) {
case 'year':
time = startOfDate(this.year(), 0, 1);
break;
case 'quarter':
time = startOfDate(
this.year(),
this.month() - (this.month() % 3),
1
);
break;
case 'month':
time = startOfDate(this.year(), this.month(), 1);
break;
case 'week':
time = startOfDate(
this.year(),
this.month(),
this.date() - this.weekday()
);
break;
case 'isoWeek':
time = startOfDate(
this.year(),
this.month(),
this.date() - (this.isoWeekday() - 1)
);
break;
case 'day':
case 'date':
time = startOfDate(this.year(), this.month(), this.date());
break;
case 'hour':
time = this._d.valueOf();
time -= mod$1(
time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE),
MS_PER_HOUR
);
break;
case 'minute':
time = this._d.valueOf();
time -= mod$1(time, MS_PER_MINUTE);
break;
case 'second':
time = this._d.valueOf();
time -= mod$1(time, MS_PER_SECOND);
break;
}
this._d.setTime(time);
hooks.updateOffset(this, true);
return this;
}
function endOf(units) {
var time, startOfDate;
units = normalizeUnits(units);
if (units === undefined || units === 'millisecond' || !this.isValid()) {
return this;
}
startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
switch (units) {
case 'year':
time = startOfDate(this.year() + 1, 0, 1) - 1;
break;
case 'quarter':
time =
startOfDate(
this.year(),
this.month() - (this.month() % 3) + 3,
1
) - 1;
break;
case 'month':
time = startOfDate(this.year(), this.month() + 1, 1) - 1;
break;
case 'week':
time =
startOfDate(
this.year(),
this.month(),
this.date() - this.weekday() + 7
) - 1;
break;
case 'isoWeek':
time =
startOfDate(
this.year(),
this.month(),
this.date() - (this.isoWeekday() - 1) + 7
) - 1;
break;
case 'day':
case 'date':
time = startOfDate(this.year(), this.month(), this.date() + 1) - 1;
break;
case 'hour':
time = this._d.valueOf();
time +=
MS_PER_HOUR -
mod$1(
time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE),
MS_PER_HOUR
) -
1;
break;
case 'minute':
time = this._d.valueOf();
time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1;
break;
case 'second':
time = this._d.valueOf();
time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1;
break;
}
this._d.setTime(time);
hooks.updateOffset(this, true);
return this;
}
function valueOf() {
return this._d.valueOf() - (this._offset || 0) * 60000;
}
function unix() {
return Math.floor(this.valueOf() / 1000);
}
function toDate() {
return new Date(this.valueOf());
}
function toArray() {
var m = this;
return [
m.year(),
m.month(),
m.date(),
m.hour(),
m.minute(),
m.second(),
m.millisecond(),
];
}
function toObject() {
var m = this;
return {
years: m.year(),
months: m.month(),
date: m.date(),
hours: m.hours(),
minutes: m.minutes(),
seconds: m.seconds(),
milliseconds: m.milliseconds(),
};
}
function toJSON() {
// new Date(NaN).toJSON() === null
return this.isValid() ? this.toISOString() : null;
}
function isValid$2() {
return isValid(this);
}
function parsingFlags() {
return extend({}, getParsingFlags(this));
}
function invalidAt() {
return getParsingFlags(this).overflow;
}
function creationData() {
return {
input: this._i,
format: this._f,
locale: this._locale,
isUTC: this._isUTC,
strict: this._strict,
};
}
addFormatToken('N', 0, 0, 'eraAbbr');
addFormatToken('NN', 0, 0, 'eraAbbr');
addFormatToken('NNN', 0, 0, 'eraAbbr');
addFormatToken('NNNN', 0, 0, 'eraName');
addFormatToken('NNNNN', 0, 0, 'eraNarrow');
addFormatToken('y', ['y', 1], 'yo', 'eraYear');
addFormatToken('y', ['yy', 2], 0, 'eraYear');
addFormatToken('y', ['yyy', 3], 0, 'eraYear');
addFormatToken('y', ['yyyy', 4], 0, 'eraYear');
addRegexToken('N', matchEraAbbr);
addRegexToken('NN', matchEraAbbr);
addRegexToken('NNN', matchEraAbbr);
addRegexToken('NNNN', matchEraName);
addRegexToken('NNNNN', matchEraNarrow);
addParseToken(
['N', 'NN', 'NNN', 'NNNN', 'NNNNN'],
function (input, array, config, token) {
var era = config._locale.erasParse(input, token, config._strict);
if (era) {
getParsingFlags(config).era = era;
} else {
getParsingFlags(config).invalidEra = input;
}
}
);
addRegexToken('y', matchUnsigned);
addRegexToken('yy', matchUnsigned);
addRegexToken('yyy', matchUnsigned);
addRegexToken('yyyy', matchUnsigned);
addRegexToken('yo', matchEraYearOrdinal);
addParseToken(['y', 'yy', 'yyy', 'yyyy'], YEAR);
addParseToken(['yo'], function (input, array, config, token) {
var match;
if (config._locale._eraYearOrdinalRegex) {
match = input.match(config._locale._eraYearOrdinalRegex);
}
if (config._locale.eraYearOrdinalParse) {
array[YEAR] = config._locale.eraYearOrdinalParse(input, match);
} else {
array[YEAR] = parseInt(input, 10);
}
});
function localeEras(m, format) {
var i,
l,
date,
eras = this._eras || getLocale('en')._eras;
for (i = 0, l = eras.length; i < l; ++i) {
switch (typeof eras[i].since) {
case 'string':
// truncate time
date = hooks(eras[i].since).startOf('day');
eras[i].since = date.valueOf();
break;
}
switch (typeof eras[i].until) {
case 'undefined':
eras[i].until = +Infinity;
break;
case 'string':
// truncate time
date = hooks(eras[i].until).startOf('day').valueOf();
eras[i].until = date.valueOf();
break;
}
}
return eras;
}
function localeErasParse(eraName, format, strict) {
var i,
l,
eras = this.eras(),
name,
abbr,
narrow;
eraName = eraName.toUpperCase();
for (i = 0, l = eras.length; i < l; ++i) {
name = eras[i].name.toUpperCase();
abbr = eras[i].abbr.toUpperCase();
narrow = eras[i].narrow.toUpperCase();
if (strict) {
switch (format) {
case 'N':
case 'NN':
case 'NNN':
if (abbr === eraName) {
return eras[i];
}
break;
case 'NNNN':
if (name === eraName) {
return eras[i];
}
break;
case 'NNNNN':
if (narrow === eraName) {
return eras[i];
}
break;
}
} else if ([name, abbr, narrow].indexOf(eraName) >= 0) {
return eras[i];
}
}
}
function localeErasConvertYear(era, year) {
var dir = era.since <= era.until ? +1 : -1;
if (year === undefined) {
return hooks(era.since).year();
} else {
return hooks(era.since).year() + (year - era.offset) * dir;
}
}
function getEraName() {
var i,
l,
val,
eras = this.localeData().eras();
for (i = 0, l = eras.length; i < l; ++i) {
// truncate time
val = this.clone().startOf('day').valueOf();
if (eras[i].since <= val && val <= eras[i].until) {
return eras[i].name;
}
if (eras[i].until <= val && val <= eras[i].since) {
return eras[i].name;
}
}
return '';
}
function getEraNarrow() {
var i,
l,
val,
eras = this.localeData().eras();
for (i = 0, l = eras.length; i < l; ++i) {
// truncate time
val = this.clone().startOf('day').valueOf();
if (eras[i].since <= val && val <= eras[i].until) {
return eras[i].narrow;
}
if (eras[i].until <= val && val <= eras[i].since) {
return eras[i].narrow;
}
}
return '';
}
function getEraAbbr() {
var i,
l,
val,
eras = this.localeData().eras();
for (i = 0, l = eras.length; i < l; ++i) {
// truncate time
val = this.clone().startOf('day').valueOf();
if (eras[i].since <= val && val <= eras[i].until) {
return eras[i].abbr;
}
if (eras[i].until <= val && val <= eras[i].since) {
return eras[i].abbr;
}
}
return '';
}
function getEraYear() {
var i,
l,
dir,
val,
eras = this.localeData().eras();
for (i = 0, l = eras.length; i < l; ++i) {
dir = eras[i].since <= eras[i].until ? +1 : -1;
// truncate time
val = this.clone().startOf('day').valueOf();
if (
(eras[i].since <= val && val <= eras[i].until) ||
(eras[i].until <= val && val <= eras[i].since)
) {
return (
(this.year() - hooks(eras[i].since).year()) * dir +
eras[i].offset
);
}
}
return this.year();
}
function erasNameRegex(isStrict) {
if (!hasOwnProp(this, '_erasNameRegex')) {
computeErasParse.call(this);
}
return isStrict ? this._erasNameRegex : this._erasRegex;
}
function erasAbbrRegex(isStrict) {
if (!hasOwnProp(this, '_erasAbbrRegex')) {
computeErasParse.call(this);
}
return isStrict ? this._erasAbbrRegex : this._erasRegex;
}
function erasNarrowRegex(isStrict) {
if (!hasOwnProp(this, '_erasNarrowRegex')) {
computeErasParse.call(this);
}
return isStrict ? this._erasNarrowRegex : this._erasRegex;
}
function matchEraAbbr(isStrict, locale) {
return locale.erasAbbrRegex(isStrict);
}
function matchEraName(isStrict, locale) {
return locale.erasNameRegex(isStrict);
}
function matchEraNarrow(isStrict, locale) {
return locale.erasNarrowRegex(isStrict);
}
function matchEraYearOrdinal(isStrict, locale) {
return locale._eraYearOrdinalRegex || matchUnsigned;
}
function computeErasParse() {
var abbrPieces = [],
namePieces = [],
narrowPieces = [],
mixedPieces = [],
i,
l,
eras = this.eras();
for (i = 0, l = eras.length; i < l; ++i) {
namePieces.push(regexEscape(eras[i].name));
abbrPieces.push(regexEscape(eras[i].abbr));
narrowPieces.push(regexEscape(eras[i].narrow));
mixedPieces.push(regexEscape(eras[i].name));
mixedPieces.push(regexEscape(eras[i].abbr));
mixedPieces.push(regexEscape(eras[i].narrow));
}
this._erasRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
this._erasNameRegex = new RegExp('^(' + namePieces.join('|') + ')', 'i');
this._erasAbbrRegex = new RegExp('^(' + abbrPieces.join('|') + ')', 'i');
this._erasNarrowRegex = new RegExp(
'^(' + narrowPieces.join('|') + ')',
'i'
);
}
// FORMATTING
addFormatToken(0, ['gg', 2], 0, function () {
return this.weekYear() % 100;
});
addFormatToken(0, ['GG', 2], 0, function () {
return this.isoWeekYear() % 100;
});
function addWeekYearFormatToken(token, getter) {
addFormatToken(0, [token, token.length], 0, getter);
}
addWeekYearFormatToken('gggg', 'weekYear');
addWeekYearFormatToken('ggggg', 'weekYear');
addWeekYearFormatToken('GGGG', 'isoWeekYear');
addWeekYearFormatToken('GGGGG', 'isoWeekYear');
// ALIASES
addUnitAlias('weekYear', 'gg');
addUnitAlias('isoWeekYear', 'GG');
// PRIORITY
addUnitPriority('weekYear', 1);
addUnitPriority('isoWeekYear', 1);
// PARSING
addRegexToken('G', matchSigned);
addRegexToken('g', matchSigned);
addRegexToken('GG', match1to2, match2);
addRegexToken('gg', match1to2, match2);
addRegexToken('GGGG', match1to4, match4);
addRegexToken('gggg', match1to4, match4);
addRegexToken('GGGGG', match1to6, match6);
addRegexToken('ggggg', match1to6, match6);
addWeekParseToken(
['gggg', 'ggggg', 'GGGG', 'GGGGG'],
function (input, week, config, token) {
week[token.substr(0, 2)] = toInt(input);
}
);
addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
week[token] = hooks.parseTwoDigitYear(input);
});
// MOMENTS
function getSetWeekYear(input) {
return getSetWeekYearHelper.call(
this,
input,
this.week(),
this.weekday(),
this.localeData()._week.dow,
this.localeData()._week.doy
);
}
function getSetISOWeekYear(input) {
return getSetWeekYearHelper.call(
this,
input,
this.isoWeek(),
this.isoWeekday(),
1,
4
);
}
function getISOWeeksInYear() {
return weeksInYear(this.year(), 1, 4);
}
function getISOWeeksInISOWeekYear() {
return weeksInYear(this.isoWeekYear(), 1, 4);
}
function getWeeksInYear() {
var weekInfo = this.localeData()._week;
return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
}
function getWeeksInWeekYear() {
var weekInfo = this.localeData()._week;
return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy);
}
function getSetWeekYearHelper(input, week, weekday, dow, doy) {
var weeksTarget;
if (input == null) {
return weekOfYear(this, dow, doy).year;
} else {
weeksTarget = weeksInYear(input, dow, doy);
if (week > weeksTarget) {
week = weeksTarget;
}
return setWeekAll.call(this, input, week, weekday, dow, doy);
}
}
function setWeekAll(weekYear, week, weekday, dow, doy) {
var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
this.year(date.getUTCFullYear());
this.month(date.getUTCMonth());
this.date(date.getUTCDate());
return this;
}
// FORMATTING
addFormatToken('Q', 0, 'Qo', 'quarter');
// ALIASES
addUnitAlias('quarter', 'Q');
// PRIORITY
addUnitPriority('quarter', 7);
// PARSING
addRegexToken('Q', match1);
addParseToken('Q', function (input, array) {
array[MONTH] = (toInt(input) - 1) * 3;
});
// MOMENTS
function getSetQuarter(input) {
return input == null
? Math.ceil((this.month() + 1) / 3)
: this.month((input - 1) * 3 + (this.month() % 3));
}
// FORMATTING
addFormatToken('D', ['DD', 2], 'Do', 'date');
// ALIASES
addUnitAlias('date', 'D');
// PRIORITY
addUnitPriority('date', 9);
// PARSING
addRegexToken('D', match1to2);
addRegexToken('DD', match1to2, match2);
addRegexToken('Do', function (isStrict, locale) {
// TODO: Remove "ordinalParse" fallback in next major release.
return isStrict
? locale._dayOfMonthOrdinalParse || locale._ordinalParse
: locale._dayOfMonthOrdinalParseLenient;
});
addParseToken(['D', 'DD'], DATE);
addParseToken('Do', function (input, array) {
array[DATE] = toInt(input.match(match1to2)[0]);
});
// MOMENTS
var getSetDayOfMonth = makeGetSet('Date', true);
// FORMATTING
addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
// ALIASES
addUnitAlias('dayOfYear', 'DDD');
// PRIORITY
addUnitPriority('dayOfYear', 4);
// PARSING
addRegexToken('DDD', match1to3);
addRegexToken('DDDD', match3);
addParseToken(['DDD', 'DDDD'], function (input, array, config) {
config._dayOfYear = toInt(input);
});
// HELPERS
// MOMENTS
function getSetDayOfYear(input) {
var dayOfYear =
Math.round(
(this.clone().startOf('day') - this.clone().startOf('year')) / 864e5
) + 1;
return input == null ? dayOfYear : this.add(input - dayOfYear, 'd');
}
// FORMATTING
addFormatToken('m', ['mm', 2], 0, 'minute');
// ALIASES
addUnitAlias('minute', 'm');
// PRIORITY
addUnitPriority('minute', 14);
// PARSING
addRegexToken('m', match1to2);
addRegexToken('mm', match1to2, match2);
addParseToken(['m', 'mm'], MINUTE);
// MOMENTS
var getSetMinute = makeGetSet('Minutes', false);
// FORMATTING
addFormatToken('s', ['ss', 2], 0, 'second');
// ALIASES
addUnitAlias('second', 's');
// PRIORITY
addUnitPriority('second', 15);
// PARSING
addRegexToken('s', match1to2);
addRegexToken('ss', match1to2, match2);
addParseToken(['s', 'ss'], SECOND);
// MOMENTS
var getSetSecond = makeGetSet('Seconds', false);
// FORMATTING
addFormatToken('S', 0, 0, function () {
return ~~(this.millisecond() / 100);
});
addFormatToken(0, ['SS', 2], 0, function () {
return ~~(this.millisecond() / 10);
});
addFormatToken(0, ['SSS', 3], 0, 'millisecond');
addFormatToken(0, ['SSSS', 4], 0, function () {
return this.millisecond() * 10;
});
addFormatToken(0, ['SSSSS', 5], 0, function () {
return this.millisecond() * 100;
});
addFormatToken(0, ['SSSSSS', 6], 0, function () {
return this.millisecond() * 1000;
});
addFormatToken(0, ['SSSSSSS', 7], 0, function () {
return this.millisecond() * 10000;
});
addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
return this.millisecond() * 100000;
});
addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
return this.millisecond() * 1000000;
});
// ALIASES
addUnitAlias('millisecond', 'ms');
// PRIORITY
addUnitPriority('millisecond', 16);
// PARSING
addRegexToken('S', match1to3, match1);
addRegexToken('SS', match1to3, match2);
addRegexToken('SSS', match1to3, match3);
var token, getSetMillisecond;
for (token = 'SSSS'; token.length <= 9; token += 'S') {
addRegexToken(token, matchUnsigned);
}
function parseMs(input, array) {
array[MILLISECOND] = toInt(('0.' + input) * 1000);
}
for (token = 'S'; token.length <= 9; token += 'S') {
addParseToken(token, parseMs);
}
getSetMillisecond = makeGetSet('Milliseconds', false);
// FORMATTING
addFormatToken('z', 0, 0, 'zoneAbbr');
addFormatToken('zz', 0, 0, 'zoneName');
// MOMENTS
function getZoneAbbr() {
return this._isUTC ? 'UTC' : '';
}
function getZoneName() {
return this._isUTC ? 'Coordinated Universal Time' : '';
}
var proto = Moment.prototype;
proto.add = add;
proto.calendar = calendar$1;
proto.clone = clone;
proto.diff = diff;
proto.endOf = endOf;
proto.format = format;
proto.from = from;
proto.fromNow = fromNow;
proto.to = to;
proto.toNow = toNow;
proto.get = stringGet;
proto.invalidAt = invalidAt;
proto.isAfter = isAfter;
proto.isBefore = isBefore;
proto.isBetween = isBetween;
proto.isSame = isSame;
proto.isSameOrAfter = isSameOrAfter;
proto.isSameOrBefore = isSameOrBefore;
proto.isValid = isValid$2;
proto.lang = lang;
proto.locale = locale;
proto.localeData = localeData;
proto.max = prototypeMax;
proto.min = prototypeMin;
proto.parsingFlags = parsingFlags;
proto.set = stringSet;
proto.startOf = startOf;
proto.subtract = subtract;
proto.toArray = toArray;
proto.toObject = toObject;
proto.toDate = toDate;
proto.toISOString = toISOString;
proto.inspect = inspect;
if (typeof Symbol !== 'undefined' && Symbol.for != null) {
proto[Symbol.for('nodejs.util.inspect.custom')] = function () {
return 'Moment<' + this.format() + '>';
};
}
proto.toJSON = toJSON;
proto.toString = toString;
proto.unix = unix;
proto.valueOf = valueOf;
proto.creationData = creationData;
proto.eraName = getEraName;
proto.eraNarrow = getEraNarrow;
proto.eraAbbr = getEraAbbr;
proto.eraYear = getEraYear;
proto.year = getSetYear;
proto.isLeapYear = getIsLeapYear;
proto.weekYear = getSetWeekYear;
proto.isoWeekYear = getSetISOWeekYear;
proto.quarter = proto.quarters = getSetQuarter;
proto.month = getSetMonth;
proto.daysInMonth = getDaysInMonth;
proto.week = proto.weeks = getSetWeek;
proto.isoWeek = proto.isoWeeks = getSetISOWeek;
proto.weeksInYear = getWeeksInYear;
proto.weeksInWeekYear = getWeeksInWeekYear;
proto.isoWeeksInYear = getISOWeeksInYear;
proto.isoWeeksInISOWeekYear = getISOWeeksInISOWeekYear;
proto.date = getSetDayOfMonth;
proto.day = proto.days = getSetDayOfWeek;
proto.weekday = getSetLocaleDayOfWeek;
proto.isoWeekday = getSetISODayOfWeek;
proto.dayOfYear = getSetDayOfYear;
proto.hour = proto.hours = getSetHour;
proto.minute = proto.minutes = getSetMinute;
proto.second = proto.seconds = getSetSecond;
proto.millisecond = proto.milliseconds = getSetMillisecond;
proto.utcOffset = getSetOffset;
proto.utc = setOffsetToUTC;
proto.local = setOffsetToLocal;
proto.parseZone = setOffsetToParsedOffset;
proto.hasAlignedHourOffset = hasAlignedHourOffset;
proto.isDST = isDaylightSavingTime;
proto.isLocal = isLocal;
proto.isUtcOffset = isUtcOffset;
proto.isUtc = isUtc;
proto.isUTC = isUtc;
proto.zoneAbbr = getZoneAbbr;
proto.zoneName = getZoneName;
proto.dates = deprecate(
'dates accessor is deprecated. Use date instead.',
getSetDayOfMonth
);
proto.months = deprecate(
'months accessor is deprecated. Use month instead',
getSetMonth
);
proto.years = deprecate(
'years accessor is deprecated. Use year instead',
getSetYear
);
proto.zone = deprecate(
'moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/',
getSetZone
);
proto.isDSTShifted = deprecate(
'isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information',
isDaylightSavingTimeShifted
);
function createUnix(input) {
return createLocal(input * 1000);
}
function createInZone() {
return createLocal.apply(null, arguments).parseZone();
}
function preParsePostFormat(string) {
return string;
}
var proto$1 = Locale.prototype;
proto$1.calendar = calendar;
proto$1.longDateFormat = longDateFormat;
proto$1.invalidDate = invalidDate;
proto$1.ordinal = ordinal;
proto$1.preparse = preParsePostFormat;
proto$1.postformat = preParsePostFormat;
proto$1.relativeTime = relativeTime;
proto$1.pastFuture = pastFuture;
proto$1.set = set;
proto$1.eras = localeEras;
proto$1.erasParse = localeErasParse;
proto$1.erasConvertYear = localeErasConvertYear;
proto$1.erasAbbrRegex = erasAbbrRegex;
proto$1.erasNameRegex = erasNameRegex;
proto$1.erasNarrowRegex = erasNarrowRegex;
proto$1.months = localeMonths;
proto$1.monthsShort = localeMonthsShort;
proto$1.monthsParse = localeMonthsParse;
proto$1.monthsRegex = monthsRegex;
proto$1.monthsShortRegex = monthsShortRegex;
proto$1.week = localeWeek;
proto$1.firstDayOfYear = localeFirstDayOfYear;
proto$1.firstDayOfWeek = localeFirstDayOfWeek;
proto$1.weekdays = localeWeekdays;
proto$1.weekdaysMin = localeWeekdaysMin;
proto$1.weekdaysShort = localeWeekdaysShort;
proto$1.weekdaysParse = localeWeekdaysParse;
proto$1.weekdaysRegex = weekdaysRegex;
proto$1.weekdaysShortRegex = weekdaysShortRegex;
proto$1.weekdaysMinRegex = weekdaysMinRegex;
proto$1.isPM = localeIsPM;
proto$1.meridiem = localeMeridiem;
function get$1(format, index, field, setter) {
var locale = getLocale(),
utc = createUTC().set(setter, index);
return locale[field](utc, format);
}
function listMonthsImpl(format, index, field) {
if (isNumber(format)) {
index = format;
format = undefined;
}
format = format || '';
if (index != null) {
return get$1(format, index, field, 'month');
}
var i,
out = [];
for (i = 0; i < 12; i++) {
out[i] = get$1(format, i, field, 'month');
}
return out;
}
// ()
// (5)
// (fmt, 5)
// (fmt)
// (true)
// (true, 5)
// (true, fmt, 5)
// (true, fmt)
function listWeekdaysImpl(localeSorted, format, index, field) {
if (typeof localeSorted === 'boolean') {
if (isNumber(format)) {
index = format;
format = undefined;
}
format = format || '';
} else {
format = localeSorted;
index = format;
localeSorted = false;
if (isNumber(format)) {
index = format;
format = undefined;
}
format = format || '';
}
var locale = getLocale(),
shift = localeSorted ? locale._week.dow : 0,
i,
out = [];
if (index != null) {
return get$1(format, (index + shift) % 7, field, 'day');
}
for (i = 0; i < 7; i++) {
out[i] = get$1(format, (i + shift) % 7, field, 'day');
}
return out;
}
function listMonths(format, index) {
return listMonthsImpl(format, index, 'months');
}
function listMonthsShort(format, index) {
return listMonthsImpl(format, index, 'monthsShort');
}
function listWeekdays(localeSorted, format, index) {
return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
}
function listWeekdaysShort(localeSorted, format, index) {
return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
}
function listWeekdaysMin(localeSorted, format, index) {
return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
}
getSetGlobalLocale('en', {
eras: [
{
since: '0001-01-01',
until: +Infinity,
offset: 1,
name: 'Anno Domini',
narrow: 'AD',
abbr: 'AD',
},
{
since: '0000-12-31',
until: -Infinity,
offset: 1,
name: 'Before Christ',
narrow: 'BC',
abbr: 'BC',
},
],
dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
ordinal: function (number) {
var b = number % 10,
output =
toInt((number % 100) / 10) === 1
? 'th'
: b === 1
? 'st'
: b === 2
? 'nd'
: b === 3
? 'rd'
: 'th';
return number + output;
},
});
// Side effect imports
hooks.lang = deprecate(
'moment.lang is deprecated. Use moment.locale instead.',
getSetGlobalLocale
);
hooks.langData = deprecate(
'moment.langData is deprecated. Use moment.localeData instead.',
getLocale
);
var mathAbs = Math.abs;
function abs() {
var data = this._data;
this._milliseconds = mathAbs(this._milliseconds);
this._days = mathAbs(this._days);
this._months = mathAbs(this._months);
data.milliseconds = mathAbs(data.milliseconds);
data.seconds = mathAbs(data.seconds);
data.minutes = mathAbs(data.minutes);
data.hours = mathAbs(data.hours);
data.months = mathAbs(data.months);
data.years = mathAbs(data.years);
return this;
}
function addSubtract$1(duration, input, value, direction) {
var other = createDuration(input, value);
duration._milliseconds += direction * other._milliseconds;
duration._days += direction * other._days;
duration._months += direction * other._months;
return duration._bubble();
}
// supports only 2.0-style add(1, 's') or add(duration)
function add$1(input, value) {
return addSubtract$1(this, input, value, 1);
}
// supports only 2.0-style subtract(1, 's') or subtract(duration)
function subtract$1(input, value) {
return addSubtract$1(this, input, value, -1);
}
function absCeil(number) {
if (number < 0) {
return Math.floor(number);
} else {
return Math.ceil(number);
}
}
function bubble() {
var milliseconds = this._milliseconds,
days = this._days,
months = this._months,
data = this._data,
seconds,
minutes,
hours,
years,
monthsFromDays;
// if we have a mix of positive and negative values, bubble down first
// check: https://github.com/moment/moment/issues/2166
if (
!(
(milliseconds >= 0 && days >= 0 && months >= 0) ||
(milliseconds <= 0 && days <= 0 && months <= 0)
)
) {
milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
days = 0;
months = 0;
}
// The following code bubbles up values, see the tests for
// examples of what that means.
data.milliseconds = milliseconds % 1000;
seconds = absFloor(milliseconds / 1000);
data.seconds = seconds % 60;
minutes = absFloor(seconds / 60);
data.minutes = minutes % 60;
hours = absFloor(minutes / 60);
data.hours = hours % 24;
days += absFloor(hours / 24);
// convert days to months
monthsFromDays = absFloor(daysToMonths(days));
months += monthsFromDays;
days -= absCeil(monthsToDays(monthsFromDays));
// 12 months -> 1 year
years = absFloor(months / 12);
months %= 12;
data.days = days;
data.months = months;
data.years = years;
return this;
}
function daysToMonths(days) {
// 400 years have 146097 days (taking into account leap year rules)
// 400 years have 12 months === 4800
return (days * 4800) / 146097;
}
function monthsToDays(months) {
// the reverse of daysToMonths
return (months * 146097) / 4800;
}
function as(units) {
if (!this.isValid()) {
return NaN;
}
var days,
months,
milliseconds = this._milliseconds;
units = normalizeUnits(units);
if (units === 'month' || units === 'quarter' || units === 'year') {
days = this._days + milliseconds / 864e5;
months = this._months + daysToMonths(days);
switch (units) {
case 'month':
return months;
case 'quarter':
return months / 3;
case 'year':
return months / 12;
}
} else {
// handle milliseconds separately because of floating point math errors (issue #1867)
days = this._days + Math.round(monthsToDays(this._months));
switch (units) {
case 'week':
return days / 7 + milliseconds / 6048e5;
case 'day':
return days + milliseconds / 864e5;
case 'hour':
return days * 24 + milliseconds / 36e5;
case 'minute':
return days * 1440 + milliseconds / 6e4;
case 'second':
return days * 86400 + milliseconds / 1000;
// Math.floor prevents floating point math errors here
case 'millisecond':
return Math.floor(days * 864e5) + milliseconds;
default:
throw new Error('Unknown unit ' + units);
}
}
}
// TODO: Use this.as('ms')?
function valueOf$1() {
if (!this.isValid()) {
return NaN;
}
return (
this._milliseconds +
this._days * 864e5 +
(this._months % 12) * 2592e6 +
toInt(this._months / 12) * 31536e6
);
}
function makeAs(alias) {
return function () {
return this.as(alias);
};
}
var asMilliseconds = makeAs('ms'),
asSeconds = makeAs('s'),
asMinutes = makeAs('m'),
asHours = makeAs('h'),
asDays = makeAs('d'),
asWeeks = makeAs('w'),
asMonths = makeAs('M'),
asQuarters = makeAs('Q'),
asYears = makeAs('y');
function clone$1() {
return createDuration(this);
}
function get$2(units) {
units = normalizeUnits(units);
return this.isValid() ? this[units + 's']() : NaN;
}
function makeGetter(name) {
return function () {
return this.isValid() ? this._data[name] : NaN;
};
}
var milliseconds = makeGetter('milliseconds'),
seconds = makeGetter('seconds'),
minutes = makeGetter('minutes'),
hours = makeGetter('hours'),
days = makeGetter('days'),
months = makeGetter('months'),
years = makeGetter('years');
function weeks() {
return absFloor(this.days() / 7);
}
var round = Math.round,
thresholds = {
ss: 44, // a few seconds to seconds
s: 45, // seconds to minute
m: 45, // minutes to hour
h: 22, // hours to day
d: 26, // days to month/week
w: null, // weeks to month
M: 11, // months to year
};
// helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
}
function relativeTime$1(posNegDuration, withoutSuffix, thresholds, locale) {
var duration = createDuration(posNegDuration).abs(),
seconds = round(duration.as('s')),
minutes = round(duration.as('m')),
hours = round(duration.as('h')),
days = round(duration.as('d')),
months = round(duration.as('M')),
weeks = round(duration.as('w')),
years = round(duration.as('y')),
a =
(seconds <= thresholds.ss && ['s', seconds]) ||
(seconds < thresholds.s && ['ss', seconds]) ||
(minutes <= 1 && ['m']) ||
(minutes < thresholds.m && ['mm', minutes]) ||
(hours <= 1 && ['h']) ||
(hours < thresholds.h && ['hh', hours]) ||
(days <= 1 && ['d']) ||
(days < thresholds.d && ['dd', days]);
if (thresholds.w != null) {
a =
a ||
(weeks <= 1 && ['w']) ||
(weeks < thresholds.w && ['ww', weeks]);
}
a = a ||
(months <= 1 && ['M']) ||
(months < thresholds.M && ['MM', months]) ||
(years <= 1 && ['y']) || ['yy', years];
a[2] = withoutSuffix;
a[3] = +posNegDuration > 0;
a[4] = locale;
return substituteTimeAgo.apply(null, a);
}
// This function allows you to set the rounding function for relative time strings
function getSetRelativeTimeRounding(roundingFunction) {
if (roundingFunction === undefined) {
return round;
}
if (typeof roundingFunction === 'function') {
round = roundingFunction;
return true;
}
return false;
}
// This function allows you to set a threshold for relative time strings
function getSetRelativeTimeThreshold(threshold, limit) {
if (thresholds[threshold] === undefined) {
return false;
}
if (limit === undefined) {
return thresholds[threshold];
}
thresholds[threshold] = limit;
if (threshold === 's') {
thresholds.ss = limit - 1;
}
return true;
}
function humanize(argWithSuffix, argThresholds) {
if (!this.isValid()) {
return this.localeData().invalidDate();
}
var withSuffix = false,
th = thresholds,
locale,
output;
if (typeof argWithSuffix === 'object') {
argThresholds = argWithSuffix;
argWithSuffix = false;
}
if (typeof argWithSuffix === 'boolean') {
withSuffix = argWithSuffix;
}
if (typeof argThresholds === 'object') {
th = Object.assign({}, thresholds, argThresholds);
if (argThresholds.s != null && argThresholds.ss == null) {
th.ss = argThresholds.s - 1;
}
}
locale = this.localeData();
output = relativeTime$1(this, !withSuffix, th, locale);
if (withSuffix) {
output = locale.pastFuture(+this, output);
}
return locale.postformat(output);
}
var abs$1 = Math.abs;
function sign(x) {
return (x > 0) - (x < 0) || +x;
}
function toISOString$1() {
// for ISO strings we do not use the normal bubbling rules:
// * milliseconds bubble up until they become hours
// * days do not bubble at all
// * months bubble up until they become years
// This is because there is no context-free conversion between hours and days
// (think of clock changes)
// and also not between days and months (28-31 days per month)
if (!this.isValid()) {
return this.localeData().invalidDate();
}
var seconds = abs$1(this._milliseconds) / 1000,
days = abs$1(this._days),
months = abs$1(this._months),
minutes,
hours,
years,
s,
total = this.asSeconds(),
totalSign,
ymSign,
daysSign,
hmsSign;
if (!total) {
// this is the same as C#'s (Noda) and python (isodate)...
// but not other JS (goog.date)
return 'P0D';
}
// 3600 seconds -> 60 minutes -> 1 hour
minutes = absFloor(seconds / 60);
hours = absFloor(minutes / 60);
seconds %= 60;
minutes %= 60;
// 12 months -> 1 year
years = absFloor(months / 12);
months %= 12;
// inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
totalSign = total < 0 ? '-' : '';
ymSign = sign(this._months) !== sign(total) ? '-' : '';
daysSign = sign(this._days) !== sign(total) ? '-' : '';
hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';
return (
totalSign +
'P' +
(years ? ymSign + years + 'Y' : '') +
(months ? ymSign + months + 'M' : '') +
(days ? daysSign + days + 'D' : '') +
(hours || minutes || seconds ? 'T' : '') +
(hours ? hmsSign + hours + 'H' : '') +
(minutes ? hmsSign + minutes + 'M' : '') +
(seconds ? hmsSign + s + 'S' : '')
);
}
var proto$2 = Duration.prototype;
proto$2.isValid = isValid$1;
proto$2.abs = abs;
proto$2.add = add$1;
proto$2.subtract = subtract$1;
proto$2.as = as;
proto$2.asMilliseconds = asMilliseconds;
proto$2.asSeconds = asSeconds;
proto$2.asMinutes = asMinutes;
proto$2.asHours = asHours;
proto$2.asDays = asDays;
proto$2.asWeeks = asWeeks;
proto$2.asMonths = asMonths;
proto$2.asQuarters = asQuarters;
proto$2.asYears = asYears;
proto$2.valueOf = valueOf$1;
proto$2._bubble = bubble;
proto$2.clone = clone$1;
proto$2.get = get$2;
proto$2.milliseconds = milliseconds;
proto$2.seconds = seconds;
proto$2.minutes = minutes;
proto$2.hours = hours;
proto$2.days = days;
proto$2.weeks = weeks;
proto$2.months = months;
proto$2.years = years;
proto$2.humanize = humanize;
proto$2.toISOString = toISOString$1;
proto$2.toString = toISOString$1;
proto$2.toJSON = toISOString$1;
proto$2.locale = locale;
proto$2.localeData = localeData;
proto$2.toIsoString = deprecate(
'toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)',
toISOString$1
);
proto$2.lang = lang;
// FORMATTING
addFormatToken('X', 0, 0, 'unix');
addFormatToken('x', 0, 0, 'valueOf');
// PARSING
addRegexToken('x', matchSigned);
addRegexToken('X', matchTimestamp);
addParseToken('X', function (input, array, config) {
config._d = new Date(parseFloat(input) * 1000);
});
addParseToken('x', function (input, array, config) {
config._d = new Date(toInt(input));
});
//! moment.js
hooks.version = '2.29.4';
setHookCallback(createLocal);
hooks.fn = proto;
hooks.min = min;
hooks.max = max;
hooks.now = now;
hooks.utc = createUTC;
hooks.unix = createUnix;
hooks.months = listMonths;
hooks.isDate = isDate;
hooks.locale = getSetGlobalLocale;
hooks.invalid = createInvalid;
hooks.duration = createDuration;
hooks.isMoment = isMoment;
hooks.weekdays = listWeekdays;
hooks.parseZone = createInZone;
hooks.localeData = getLocale;
hooks.isDuration = isDuration;
hooks.monthsShort = listMonthsShort;
hooks.weekdaysMin = listWeekdaysMin;
hooks.defineLocale = defineLocale;
hooks.updateLocale = updateLocale;
hooks.locales = listLocales;
hooks.weekdaysShort = listWeekdaysShort;
hooks.normalizeUnits = normalizeUnits;
hooks.relativeTimeRounding = getSetRelativeTimeRounding;
hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
hooks.calendarFormat = getCalendarFormat;
hooks.prototype = proto;
// currently HTML5 input type only supports 24-hour formats
hooks.HTML5_FMT = {
DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // <input type="datetime-local" />
DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // <input type="datetime-local" step="1" />
DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // <input type="datetime-local" step="0.001" />
DATE: 'YYYY-MM-DD', // <input type="date" />
TIME: 'HH:mm', // <input type="time" />
TIME_SECONDS: 'HH:mm:ss', // <input type="time" step="1" />
TIME_MS: 'HH:mm:ss.SSS', // <input type="time" step="0.001" />
WEEK: 'GGGG-[W]WW', // <input type="week" />
MONTH: 'YYYY-MM', // <input type="month" />
};
return hooks;
})));
webpack://frontend-mybets/../../node_modules/node-fetch/browser.js
"use strict";
// ref: https://github.com/tc39/proposal-global
var getGlobal = function () {
// the only reliable means to get the global object is
// `Function('return this')()`
// However, this causes CSP violations in Chrome apps.
if (typeof self !== 'undefined') { return self; }
if (typeof window !== 'undefined') { return window; }
if (typeof global !== 'undefined') { return global; }
throw new Error('unable to locate global object');
}
var global = getGlobal();
module.exports = exports = global.fetch;
// Needed for TypeScript and Webpack.
if (global.fetch) {
exports.default = global.fetch.bind(global);
}
exports.Headers = global.Headers;
exports.Request = global.Request;
exports.Response = global.Response;
webpack://frontend-mybets/../../node_modules/nullthrows/nullthrows.js
'use strict';
function nullthrows(x, message) {
if (x != null) {
return x;
}
var error = new Error(message !== undefined ? message : 'Got unexpected ' + x);
error.framesToPop = 1; // Skip nullthrows's own stack frame.
throw error;
}
module.exports = nullthrows;
module.exports.default = nullthrows;
Object.defineProperty(module.exports, '__esModule', {value: true});
webpack://frontend-mybets/../../node_modules/numeral/numeral.js
/*! @preserve
* numeral.js
* version : 2.0.6
* author : Adam Draper
* license : MIT
* http://adamwdraper.github.com/Numeral-js/
*/
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(factory);
} else if (typeof module === 'object' && module.exports) {
module.exports = factory();
} else {
global.numeral = factory();
}
}(this, function () {
/************************************
Variables
************************************/
var numeral,
_,
VERSION = '2.0.6',
formats = {},
locales = {},
defaults = {
currentLocale: 'en',
zeroFormat: null,
nullFormat: null,
defaultFormat: '0,0',
scalePercentBy100: true
},
options = {
currentLocale: defaults.currentLocale,
zeroFormat: defaults.zeroFormat,
nullFormat: defaults.nullFormat,
defaultFormat: defaults.defaultFormat,
scalePercentBy100: defaults.scalePercentBy100
};
/************************************
Constructors
************************************/
// Numeral prototype object
function Numeral(input, number) {
this._input = input;
this._value = number;
}
numeral = function(input) {
var value,
kind,
unformatFunction,
regexp;
if (numeral.isNumeral(input)) {
value = input.value();
} else if (input === 0 || typeof input === 'undefined') {
value = 0;
} else if (input === null || _.isNaN(input)) {
value = null;
} else if (typeof input === 'string') {
if (options.zeroFormat && input === options.zeroFormat) {
value = 0;
} else if (options.nullFormat && input === options.nullFormat || !input.replace(/[^0-9]+/g, '').length) {
value = null;
} else {
for (kind in formats) {
regexp = typeof formats[kind].regexps.unformat === 'function' ? formats[kind].regexps.unformat() : formats[kind].regexps.unformat;
if (regexp && input.match(regexp)) {
unformatFunction = formats[kind].unformat;
break;
}
}
unformatFunction = unformatFunction || numeral._.stringToNumber;
value = unformatFunction(input);
}
} else {
value = Number(input)|| null;
}
return new Numeral(input, value);
};
// version number
numeral.version = VERSION;
// compare numeral object
numeral.isNumeral = function(obj) {
return obj instanceof Numeral;
};
// helper functions
numeral._ = _ = {
// formats numbers separators, decimals places, signs, abbreviations
numberToFormat: function(value, format, roundingFunction) {
var locale = locales[numeral.options.currentLocale],
negP = false,
optDec = false,
leadingCount = 0,
abbr = '',
trillion = 1000000000000,
billion = 1000000000,
million = 1000000,
thousand = 1000,
decimal = '',
neg = false,
abbrForce, // force abbreviation
abs,
min,
max,
power,
int,
precision,
signed,
thousands,
output;
// make sure we never format a null value
value = value || 0;
abs = Math.abs(value);
// see if we should use parentheses for negative number or if we should prefix with a sign
// if both are present we default to parentheses
if (numeral._.includes(format, '(')) {
negP = true;
format = format.replace(/[\(|\)]/g, '');
} else if (numeral._.includes(format, '+') || numeral._.includes(format, '-')) {
signed = numeral._.includes(format, '+') ? format.indexOf('+') : value < 0 ? format.indexOf('-') : -1;
format = format.replace(/[\+|\-]/g, '');
}
// see if abbreviation is wanted
if (numeral._.includes(format, 'a')) {
abbrForce = format.match(/a(k|m|b|t)?/);
abbrForce = abbrForce ? abbrForce[1] : false;
// check for space before abbreviation
if (numeral._.includes(format, ' a')) {
abbr = ' ';
}
format = format.replace(new RegExp(abbr + 'a[kmbt]?'), '');
if (abs >= trillion && !abbrForce || abbrForce === 't') {
// trillion
abbr += locale.abbreviations.trillion;
value = value / trillion;
} else if (abs < trillion && abs >= billion && !abbrForce || abbrForce === 'b') {
// billion
abbr += locale.abbreviations.billion;
value = value / billion;
} else if (abs < billion && abs >= million && !abbrForce || abbrForce === 'm') {
// million
abbr += locale.abbreviations.million;
value = value / million;
} else if (abs < million && abs >= thousand && !abbrForce || abbrForce === 'k') {
// thousand
abbr += locale.abbreviations.thousand;
value = value / thousand;
}
}
// check for optional decimals
if (numeral._.includes(format, '[.]')) {
optDec = true;
format = format.replace('[.]', '.');
}
// break number and format
int = value.toString().split('.')[0];
precision = format.split('.')[1];
thousands = format.indexOf(',');
leadingCount = (format.split('.')[0].split(',')[0].match(/0/g) || []).length;
if (precision) {
if (numeral._.includes(precision, '[')) {
precision = precision.replace(']', '');
precision = precision.split('[');
decimal = numeral._.toFixed(value, (precision[0].length + precision[1].length), roundingFunction, precision[1].length);
} else {
decimal = numeral._.toFixed(value, precision.length, roundingFunction);
}
int = decimal.split('.')[0];
if (numeral._.includes(decimal, '.')) {
decimal = locale.delimiters.decimal + decimal.split('.')[1];
} else {
decimal = '';
}
if (optDec && Number(decimal.slice(1)) === 0) {
decimal = '';
}
} else {
int = numeral._.toFixed(value, 0, roundingFunction);
}
// check abbreviation again after rounding
if (abbr && !abbrForce && Number(int) >= 1000 && abbr !== locale.abbreviations.trillion) {
int = String(Number(int) / 1000);
switch (abbr) {
case locale.abbreviations.thousand:
abbr = locale.abbreviations.million;
break;
case locale.abbreviations.million:
abbr = locale.abbreviations.billion;
break;
case locale.abbreviations.billion:
abbr = locale.abbreviations.trillion;
break;
}
}
// format number
if (numeral._.includes(int, '-')) {
int = int.slice(1);
neg = true;
}
if (int.length < leadingCount) {
for (var i = leadingCount - int.length; i > 0; i--) {
int = '0' + int;
}
}
if (thousands > -1) {
int = int.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + locale.delimiters.thousands);
}
if (format.indexOf('.') === 0) {
int = '';
}
output = int + decimal + (abbr ? abbr : '');
if (negP) {
output = (negP && neg ? '(' : '') + output + (negP && neg ? ')' : '');
} else {
if (signed >= 0) {
output = signed === 0 ? (neg ? '-' : '+') + output : output + (neg ? '-' : '+');
} else if (neg) {
output = '-' + output;
}
}
return output;
},
// unformats numbers separators, decimals places, signs, abbreviations
stringToNumber: function(string) {
var locale = locales[options.currentLocale],
stringOriginal = string,
abbreviations = {
thousand: 3,
million: 6,
billion: 9,
trillion: 12
},
abbreviation,
value,
i,
regexp;
if (options.zeroFormat && string === options.zeroFormat) {
value = 0;
} else if (options.nullFormat && string === options.nullFormat || !string.replace(/[^0-9]+/g, '').length) {
value = null;
} else {
value = 1;
if (locale.delimiters.decimal !== '.') {
string = string.replace(/\./g, '').replace(locale.delimiters.decimal, '.');
}
for (abbreviation in abbreviations) {
regexp = new RegExp('[^a-zA-Z]' + locale.abbreviations[abbreviation] + '(?:\\)|(\\' + locale.currency.symbol + ')?(?:\\))?)?$');
if (stringOriginal.match(regexp)) {
value *= Math.pow(10, abbreviations[abbreviation]);
break;
}
}
// check for negative number
value *= (string.split('-').length + Math.min(string.split('(').length - 1, string.split(')').length - 1)) % 2 ? 1 : -1;
// remove non numbers
string = string.replace(/[^0-9\.]+/g, '');
value *= Number(string);
}
return value;
},
isNaN: function(value) {
return typeof value === 'number' && isNaN(value);
},
includes: function(string, search) {
return string.indexOf(search) !== -1;
},
insert: function(string, subString, start) {
return string.slice(0, start) + subString + string.slice(start);
},
reduce: function(array, callback /*, initialValue*/) {
if (this === null) {
throw new TypeError('Array.prototype.reduce called on null or undefined');
}
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
var t = Object(array),
len = t.length >>> 0,
k = 0,
value;
if (arguments.length === 3) {
value = arguments[2];
} else {
while (k < len && !(k in t)) {
k++;
}
if (k >= len) {
throw new TypeError('Reduce of empty array with no initial value');
}
value = t[k++];
}
for (; k < len; k++) {
if (k in t) {
value = callback(value, t[k], k, t);
}
}
return value;
},
/**
* Computes the multiplier necessary to make x >= 1,
* effectively eliminating miscalculations caused by
* finite precision.
*/
multiplier: function (x) {
var parts = x.toString().split('.');
return parts.length < 2 ? 1 : Math.pow(10, parts[1].length);
},
/**
* Given a variable number of arguments, returns the maximum
* multiplier that must be used to normalize an operation involving
* all of them.
*/
correctionFactor: function () {
var args = Array.prototype.slice.call(arguments);
return args.reduce(function(accum, next) {
var mn = _.multiplier(next);
return accum > mn ? accum : mn;
}, 1);
},
/**
* Implementation of toFixed() that treats floats more like decimals
*
* Fixes binary rounding issues (eg. (0.615).toFixed(2) === '0.61') that present
* problems for accounting- and finance-related software.
*/
toFixed: function(value, maxDecimals, roundingFunction, optionals) {
var splitValue = value.toString().split('.'),
minDecimals = maxDecimals - (optionals || 0),
boundedPrecision,
optionalsRegExp,
power,
output;
// Use the smallest precision value possible to avoid errors from floating point representation
if (splitValue.length === 2) {
boundedPrecision = Math.min(Math.max(splitValue[1].length, minDecimals), maxDecimals);
} else {
boundedPrecision = minDecimals;
}
power = Math.pow(10, boundedPrecision);
// Multiply up by precision, round accurately, then divide and use native toFixed():
output = (roundingFunction(value + 'e+' + boundedPrecision) / power).toFixed(boundedPrecision);
if (optionals > maxDecimals - boundedPrecision) {
optionalsRegExp = new RegExp('\\.?0{1,' + (optionals - (maxDecimals - boundedPrecision)) + '}$');
output = output.replace(optionalsRegExp, '');
}
return output;
}
};
// avaliable options
numeral.options = options;
// avaliable formats
numeral.formats = formats;
// avaliable formats
numeral.locales = locales;
// This function sets the current locale. If
// no arguments are passed in, it will simply return the current global
// locale key.
numeral.locale = function(key) {
if (key) {
options.currentLocale = key.toLowerCase();
}
return options.currentLocale;
};
// This function provides access to the loaded locale data. If
// no arguments are passed in, it will simply return the current
// global locale object.
numeral.localeData = function(key) {
if (!key) {
return locales[options.currentLocale];
}
key = key.toLowerCase();
if (!locales[key]) {
throw new Error('Unknown locale : ' + key);
}
return locales[key];
};
numeral.reset = function() {
for (var property in defaults) {
options[property] = defaults[property];
}
};
numeral.zeroFormat = function(format) {
options.zeroFormat = typeof(format) === 'string' ? format : null;
};
numeral.nullFormat = function (format) {
options.nullFormat = typeof(format) === 'string' ? format : null;
};
numeral.defaultFormat = function(format) {
options.defaultFormat = typeof(format) === 'string' ? format : '0.0';
};
numeral.register = function(type, name, format) {
name = name.toLowerCase();
if (this[type + 's'][name]) {
throw new TypeError(name + ' ' + type + ' already registered.');
}
this[type + 's'][name] = format;
return format;
};
numeral.validate = function(val, culture) {
var _decimalSep,
_thousandSep,
_currSymbol,
_valArray,
_abbrObj,
_thousandRegEx,
localeData,
temp;
//coerce val to string
if (typeof val !== 'string') {
val += '';
if (console.warn) {
console.warn('Numeral.js: Value is not string. It has been co-erced to: ', val);
}
}
//trim whitespaces from either sides
val = val.trim();
//if val is just digits return true
if (!!val.match(/^\d+$/)) {
return true;
}
//if val is empty return false
if (val === '') {
return false;
}
//get the decimal and thousands separator from numeral.localeData
try {
//check if the culture is understood by numeral. if not, default it to current locale
localeData = numeral.localeData(culture);
} catch (e) {
localeData = numeral.localeData(numeral.locale());
}
//setup the delimiters and currency symbol based on culture/locale
_currSymbol = localeData.currency.symbol;
_abbrObj = localeData.abbreviations;
_decimalSep = localeData.delimiters.decimal;
if (localeData.delimiters.thousands === '.') {
_thousandSep = '\\.';
} else {
_thousandSep = localeData.delimiters.thousands;
}
// validating currency symbol
temp = val.match(/^[^\d]+/);
if (temp !== null) {
val = val.substr(1);
if (temp[0] !== _currSymbol) {
return false;
}
}
//validating abbreviation symbol
temp = val.match(/[^\d]+$/);
if (temp !== null) {
val = val.slice(0, -1);
if (temp[0] !== _abbrObj.thousand && temp[0] !== _abbrObj.million && temp[0] !== _abbrObj.billion && temp[0] !== _abbrObj.trillion) {
return false;
}
}
_thousandRegEx = new RegExp(_thousandSep + '{2}');
if (!val.match(/[^\d.,]/g)) {
_valArray = val.split(_decimalSep);
if (_valArray.length > 2) {
return false;
} else {
if (_valArray.length < 2) {
return ( !! _valArray[0].match(/^\d+.*\d$/) && !_valArray[0].match(_thousandRegEx));
} else {
if (_valArray[0].length === 1) {
return ( !! _valArray[0].match(/^\d+$/) && !_valArray[0].match(_thousandRegEx) && !! _valArray[1].match(/^\d+$/));
} else {
return ( !! _valArray[0].match(/^\d+.*\d$/) && !_valArray[0].match(_thousandRegEx) && !! _valArray[1].match(/^\d+$/));
}
}
}
}
return false;
};
/************************************
Numeral Prototype
************************************/
numeral.fn = Numeral.prototype = {
clone: function() {
return numeral(this);
},
format: function(inputString, roundingFunction) {
var value = this._value,
format = inputString || options.defaultFormat,
kind,
output,
formatFunction;
// make sure we have a roundingFunction
roundingFunction = roundingFunction || Math.round;
// format based on value
if (value === 0 && options.zeroFormat !== null) {
output = options.zeroFormat;
} else if (value === null && options.nullFormat !== null) {
output = options.nullFormat;
} else {
for (kind in formats) {
if (format.match(formats[kind].regexps.format)) {
formatFunction = formats[kind].format;
break;
}
}
formatFunction = formatFunction || numeral._.numberToFormat;
output = formatFunction(value, format, roundingFunction);
}
return output;
},
value: function() {
return this._value;
},
input: function() {
return this._input;
},
set: function(value) {
this._value = Number(value);
return this;
},
add: function(value) {
var corrFactor = _.correctionFactor.call(null, this._value, value);
function cback(accum, curr, currI, O) {
return accum + Math.round(corrFactor * curr);
}
this._value = _.reduce([this._value, value], cback, 0) / corrFactor;
return this;
},
subtract: function(value) {
var corrFactor = _.correctionFactor.call(null, this._value, value);
function cback(accum, curr, currI, O) {
return accum - Math.round(corrFactor * curr);
}
this._value = _.reduce([value], cback, Math.round(this._value * corrFactor)) / corrFactor;
return this;
},
multiply: function(value) {
function cback(accum, curr, currI, O) {
var corrFactor = _.correctionFactor(accum, curr);
return Math.round(accum * corrFactor) * Math.round(curr * corrFactor) / Math.round(corrFactor * corrFactor);
}
this._value = _.reduce([this._value, value], cback, 1);
return this;
},
divide: function(value) {
function cback(accum, curr, currI, O) {
var corrFactor = _.correctionFactor(accum, curr);
return Math.round(accum * corrFactor) / Math.round(curr * corrFactor);
}
this._value = _.reduce([this._value, value], cback);
return this;
},
difference: function(value) {
return Math.abs(numeral(this._value).subtract(value).value());
}
};
/************************************
Default Locale && Format
************************************/
numeral.register('locale', 'en', {
delimiters: {
thousands: ',',
decimal: '.'
},
abbreviations: {
thousand: 'k',
million: 'm',
billion: 'b',
trillion: 't'
},
ordinal: function(number) {
var b = number % 10;
return (~~(number % 100 / 10) === 1) ? 'th' :
(b === 1) ? 'st' :
(b === 2) ? 'nd' :
(b === 3) ? 'rd' : 'th';
},
currency: {
symbol: '$'
}
});
(function() {
numeral.register('format', 'bps', {
regexps: {
format: /(BPS)/,
unformat: /(BPS)/
},
format: function(value, format, roundingFunction) {
var space = numeral._.includes(format, ' BPS') ? ' ' : '',
output;
value = value * 10000;
// check for space before BPS
format = format.replace(/\s?BPS/, '');
output = numeral._.numberToFormat(value, format, roundingFunction);
if (numeral._.includes(output, ')')) {
output = output.split('');
output.splice(-1, 0, space + 'BPS');
output = output.join('');
} else {
output = output + space + 'BPS';
}
return output;
},
unformat: function(string) {
return +(numeral._.stringToNumber(string) * 0.0001).toFixed(15);
}
});
})();
(function() {
var decimal = {
base: 1000,
suffixes: ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
},
binary = {
base: 1024,
suffixes: ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']
};
var allSuffixes = decimal.suffixes.concat(binary.suffixes.filter(function (item) {
return decimal.suffixes.indexOf(item) < 0;
}));
var unformatRegex = allSuffixes.join('|');
// Allow support for BPS (http://www.investopedia.com/terms/b/basispoint.asp)
unformatRegex = '(' + unformatRegex.replace('B', 'B(?!PS)') + ')';
numeral.register('format', 'bytes', {
regexps: {
format: /([0\s]i?b)/,
unformat: new RegExp(unformatRegex)
},
format: function(value, format, roundingFunction) {
var output,
bytes = numeral._.includes(format, 'ib') ? binary : decimal,
suffix = numeral._.includes(format, ' b') || numeral._.includes(format, ' ib') ? ' ' : '',
power,
min,
max;
// check for space before
format = format.replace(/\s?i?b/, '');
for (power = 0; power <= bytes.suffixes.length; power++) {
min = Math.pow(bytes.base, power);
max = Math.pow(bytes.base, power + 1);
if (value === null || value === 0 || value >= min && value < max) {
suffix += bytes.suffixes[power];
if (min > 0) {
value = value / min;
}
break;
}
}
output = numeral._.numberToFormat(value, format, roundingFunction);
return output + suffix;
},
unformat: function(string) {
var value = numeral._.stringToNumber(string),
power,
bytesMultiplier;
if (value) {
for (power = decimal.suffixes.length - 1; power >= 0; power--) {
if (numeral._.includes(string, decimal.suffixes[power])) {
bytesMultiplier = Math.pow(decimal.base, power);
break;
}
if (numeral._.includes(string, binary.suffixes[power])) {
bytesMultiplier = Math.pow(binary.base, power);
break;
}
}
value *= (bytesMultiplier || 1);
}
return value;
}
});
})();
(function() {
numeral.register('format', 'currency', {
regexps: {
format: /(\$)/
},
format: function(value, format, roundingFunction) {
var locale = numeral.locales[numeral.options.currentLocale],
symbols = {
before: format.match(/^([\+|\-|\(|\s|\$]*)/)[0],
after: format.match(/([\+|\-|\)|\s|\$]*)$/)[0]
},
output,
symbol,
i;
// strip format of spaces and $
format = format.replace(/\s?\$\s?/, '');
// format the number
output = numeral._.numberToFormat(value, format, roundingFunction);
// update the before and after based on value
if (value >= 0) {
symbols.before = symbols.before.replace(/[\-\(]/, '');
symbols.after = symbols.after.replace(/[\-\)]/, '');
} else if (value < 0 && (!numeral._.includes(symbols.before, '-') && !numeral._.includes(symbols.before, '('))) {
symbols.before = '-' + symbols.before;
}
// loop through each before symbol
for (i = 0; i < symbols.before.length; i++) {
symbol = symbols.before[i];
switch (symbol) {
case '$':
output = numeral._.insert(output, locale.currency.symbol, i);
break;
case ' ':
output = numeral._.insert(output, ' ', i + locale.currency.symbol.length - 1);
break;
}
}
// loop through each after symbol
for (i = symbols.after.length - 1; i >= 0; i--) {
symbol = symbols.after[i];
switch (symbol) {
case '$':
output = i === symbols.after.length - 1 ? output + locale.currency.symbol : numeral._.insert(output, locale.currency.symbol, -(symbols.after.length - (1 + i)));
break;
case ' ':
output = i === symbols.after.length - 1 ? output + ' ' : numeral._.insert(output, ' ', -(symbols.after.length - (1 + i) + locale.currency.symbol.length - 1));
break;
}
}
return output;
}
});
})();
(function() {
numeral.register('format', 'exponential', {
regexps: {
format: /(e\+|e-)/,
unformat: /(e\+|e-)/
},
format: function(value, format, roundingFunction) {
var output,
exponential = typeof value === 'number' && !numeral._.isNaN(value) ? value.toExponential() : '0e+0',
parts = exponential.split('e');
format = format.replace(/e[\+|\-]{1}0/, '');
output = numeral._.numberToFormat(Number(parts[0]), format, roundingFunction);
return output + 'e' + parts[1];
},
unformat: function(string) {
var parts = numeral._.includes(string, 'e+') ? string.split('e+') : string.split('e-'),
value = Number(parts[0]),
power = Number(parts[1]);
power = numeral._.includes(string, 'e-') ? power *= -1 : power;
function cback(accum, curr, currI, O) {
var corrFactor = numeral._.correctionFactor(accum, curr),
num = (accum * corrFactor) * (curr * corrFactor) / (corrFactor * corrFactor);
return num;
}
return numeral._.reduce([value, Math.pow(10, power)], cback, 1);
}
});
})();
(function() {
numeral.register('format', 'ordinal', {
regexps: {
format: /(o)/
},
format: function(value, format, roundingFunction) {
var locale = numeral.locales[numeral.options.currentLocale],
output,
ordinal = numeral._.includes(format, ' o') ? ' ' : '';
// check for space before
format = format.replace(/\s?o/, '');
ordinal += locale.ordinal(value);
output = numeral._.numberToFormat(value, format, roundingFunction);
return output + ordinal;
}
});
})();
(function() {
numeral.register('format', 'percentage', {
regexps: {
format: /(%)/,
unformat: /(%)/
},
format: function(value, format, roundingFunction) {
var space = numeral._.includes(format, ' %') ? ' ' : '',
output;
if (numeral.options.scalePercentBy100) {
value = value * 100;
}
// check for space before %
format = format.replace(/\s?\%/, '');
output = numeral._.numberToFormat(value, format, roundingFunction);
if (numeral._.includes(output, ')')) {
output = output.split('');
output.splice(-1, 0, space + '%');
output = output.join('');
} else {
output = output + space + '%';
}
return output;
},
unformat: function(string) {
var number = numeral._.stringToNumber(string);
if (numeral.options.scalePercentBy100) {
return number * 0.01;
}
return number;
}
});
})();
(function() {
numeral.register('format', 'time', {
regexps: {
format: /(:)/,
unformat: /(:)/
},
format: function(value, format, roundingFunction) {
var hours = Math.floor(value / 60 / 60),
minutes = Math.floor((value - (hours * 60 * 60)) / 60),
seconds = Math.round(value - (hours * 60 * 60) - (minutes * 60));
return hours + ':' + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds);
},
unformat: function(string) {
var timeArray = string.split(':'),
seconds = 0;
// turn hours and minutes into seconds and add them all up
if (timeArray.length === 3) {
// hours
seconds = seconds + (Number(timeArray[0]) * 60 * 60);
// minutes
seconds = seconds + (Number(timeArray[1]) * 60);
// seconds
seconds = seconds + Number(timeArray[2]);
} else if (timeArray.length === 2) {
// minutes
seconds = seconds + (Number(timeArray[0]) * 60);
// seconds
seconds = seconds + Number(timeArray[1]);
}
return Number(seconds);
}
});
})();
return numeral;
}));
webpack://frontend-mybets/../../node_modules/object-assign/index.js
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
'use strict';
/* 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;
}
}
module.exports = 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;
};
webpack://frontend-mybets/../../node_modules/polished/dist/polished.es.js
import _extends from '@babel/runtime/helpers/esm/extends';
import _taggedTemplateLiteralLoose from '@babel/runtime/helpers/esm/taggedTemplateLiteralLoose';
// @private
function capitalizeString(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
var positionMap = ['Top', 'Right', 'Bottom', 'Left'];
function generateProperty(property, position) {
if (!property) return position.toLowerCase();
var splitProperty = property.split('-');
if (splitProperty.length > 1) {
splitProperty.splice(1, 0, position);
return splitProperty.reduce(function (acc, val) {
return "" + acc + capitalizeString(val);
});
}
var joinedProperty = property.replace(/([a-z])([A-Z])/g, "$1" + position + "$2");
return property === joinedProperty ? "" + property + position : joinedProperty;
}
function generateStyles(property, valuesWithDefaults) {
var styles = {};
for (var i = 0; i < valuesWithDefaults.length; i += 1) {
if (valuesWithDefaults[i] || valuesWithDefaults[i] === 0) {
styles[generateProperty(property, positionMap[i])] = valuesWithDefaults[i];
}
}
return styles;
}
/**
* Enables shorthand for direction-based properties. It accepts a property (hyphenated or camelCased) and up to four values that map to top, right, bottom, and left, respectively. You can optionally pass an empty string to get only the directional values as properties. You can also optionally pass a null argument for a directional value to ignore it.
* @example
* // Styles as object usage
* const styles = {
* ...directionalProperty('padding', '12px', '24px', '36px', '48px')
* }
*
* // styled-components usage
* const div = styled.div`
* ${directionalProperty('padding', '12px', '24px', '36px', '48px')}
* `
*
* // CSS as JS Output
*
* div {
* 'paddingTop': '12px',
* 'paddingRight': '24px',
* 'paddingBottom': '36px',
* 'paddingLeft': '48px'
* }
*/
function directionalProperty(property) {
for (var _len = arguments.length, values = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
values[_key - 1] = arguments[_key];
}
// prettier-ignore
var firstValue = values[0],
_values$ = values[1],
secondValue = _values$ === void 0 ? firstValue : _values$,
_values$2 = values[2],
thirdValue = _values$2 === void 0 ? firstValue : _values$2,
_values$3 = values[3],
fourthValue = _values$3 === void 0 ? secondValue : _values$3;
var valuesWithDefaults = [firstValue, secondValue, thirdValue, fourthValue];
return generateStyles(property, valuesWithDefaults);
}
function endsWith (string, suffix) {
return string.substr(-suffix.length) === suffix;
}
/**
* Returns a given CSS value minus its unit (or the original value if an invalid string is passed).
*
* @example
* // Styles as object usage
* const styles = {
* '--dimension': stripUnit('100px')
* }
*
* // styled-components usage
* const div = styled.div`
* --dimension: ${stripUnit('100px')}
* `
*
* // CSS in JS Output
*
* element {
* '--dimension': 100
* }
*/
function stripUnit(value) {
var unitlessValue = parseFloat(value);
if (isNaN(unitlessValue)) return value;
return unitlessValue;
}
/**
* Factory function that creates pixel-to-x converters
* @private
*/
var pxtoFactory = function pxtoFactory(to) {
return function (pxval, base) {
if (base === void 0) {
base = '16px';
}
var newPxval = pxval;
var newBase = base;
if (typeof pxval === 'string') {
if (!endsWith(pxval, 'px')) {
throw new Error("Expected a string ending in \"px\" or a number passed as the first argument to " + to + "(), got \"" + pxval + "\" instead.");
}
newPxval = stripUnit(pxval);
}
if (typeof base === 'string') {
if (!endsWith(base, 'px')) {
throw new Error("Expected a string ending in \"px\" or a number passed as the second argument to " + to + "(), got \"" + base + "\" instead.");
}
newBase = stripUnit(base);
}
if (typeof newPxval === 'string') {
throw new Error("Passed invalid pixel value (\"" + pxval + "\") to " + to + "(), please pass a value like \"12px\" or 12.");
}
if (typeof newBase === 'string') {
throw new Error("Passed invalid base value (\"" + base + "\") to " + to + "(), please pass a value like \"12px\" or 12.");
}
return "" + newPxval / newBase + to;
};
};
/**
* Convert pixel value to ems. The default base value is 16px, but can be changed by passing a
* second argument to the function.
* @function
* @param {string|number} pxval
* @param {string|number} [base='16px']
* @example
* // Styles as object usage
* const styles = {
* 'height': em('16px')
* }
*
* // styled-components usage
* const div = styled.div`
* height: ${em('16px')}
* `
*
* // CSS in JS Output
*
* element {
* 'height': '1em'
* }
*/
var em =
/*#__PURE__*/
pxtoFactory('em');
var cssRegex = /^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/;
/**
* Returns a given CSS value and its unit as elements of an array.
*
* @example
* // Styles as object usage
* const styles = {
* '--dimension': getValueAndUnit('100px')[0]
* '--unit': getValueAndUnit('100px')[1]
* }
*
* // styled-components usage
* const div = styled.div`
* --dimension: ${getValueAndUnit('100px')[0]}
* --unit: ${getValueAndUnit('100px')[1]}
* `
*
* // CSS in JS Output
*
* element {
* '--dimension': 100
* '--unit': 'px'
* }
*/
function getValueAndUnit(value) {
if (typeof value !== 'string') return [value, ''];
var matchedValue = value.match(cssRegex);
if (matchedValue) return [parseFloat(value), matchedValue[2]];
return [value, undefined];
}
var ratioNames = {
minorSecond: 1.067,
majorSecond: 1.125,
minorThird: 1.2,
majorThird: 1.25,
perfectFourth: 1.333,
augFourth: 1.414,
perfectFifth: 1.5,
minorSixth: 1.6,
goldenSection: 1.618,
majorSixth: 1.667,
minorSeventh: 1.778,
majorSeventh: 1.875,
octave: 2,
majorTenth: 2.5,
majorEleventh: 2.667,
majorTwelfth: 3,
doubleOctave: 4
};
function getRatio(ratioName) {
return ratioNames[ratioName];
}
/**
* Establish consistent measurements and spacial relationships throughout your projects by incrementing up or down a defined scale. We provide a list of commonly used scales as pre-defined variables.
* @example
* // Styles as object usage
* const styles = {
* // Increment two steps up the default scale
* 'fontSize': modularScale(2)
* }
*
* // styled-components usage
* const div = styled.div`
* // Increment two steps up the default scale
* fontSize: ${modularScale(2)}
* `
*
* // CSS in JS Output
*
* element {
* 'fontSize': '1.77689em'
* }
*/
function modularScale(steps, base, ratio) {
if (base === void 0) {
base = '1em';
}
if (ratio === void 0) {
ratio = 'perfectFourth';
}
if (typeof steps !== 'number') {
throw new Error('Please provide a number of steps to the modularScale helper.');
}
if (typeof ratio === 'string' && !ratioNames[ratio]) {
throw new Error('Please pass a number or one of the predefined scales to the modularScale helper as the ratio.');
}
var realBase = typeof base === 'string' ? stripUnit(base) : base;
var realRatio = typeof ratio === 'string' ? getRatio(ratio) : ratio;
if (typeof realBase === 'string') {
throw new Error("Invalid value passed as base to modularScale, expected number or em string but got \"" + base + "\"");
}
return realBase * Math.pow(realRatio, steps) + "em";
}
/**
* Convert pixel value to rems. The default base value is 16px, but can be changed by passing a
* second argument to the function.
* @function
* @param {string|number} pxval
* @param {string|number} [base='16px']
* @example
* // Styles as object usage
* const styles = {
* 'height': rem('16px')
* }
*
* // styled-components usage
* const div = styled.div`
* height: ${rem('16px')}
* `
*
* // CSS in JS Output
*
* element {
* 'height': '1rem'
* }
*/
var rem =
/*#__PURE__*/
pxtoFactory('rem');
/**
* Returns a CSS calc formula for linear interpolation of a property between two values. Accepts optional minScreen (defaults to '320px') and maxScreen (defaults to '1200px').
*
* @example
* // Styles as object usage
* const styles = {
* fontSize: between('20px', '100px', '400px', '1000px'),
* fontSize: between('20px', '100px')
* }
*
* // styled-components usage
* const div = styled.div`
* fontSize: ${between('20px', '100px', '400px', '1000px')};
* fontSize: ${between('20px', '100px')}
* `
*
* // CSS as JS Output
*
* h1: {
* 'fontSize': 'calc(-33.33333333333334px + 13.333333333333334vw)',
* 'fontSize': 'calc(-9.090909090909093px + 9.090909090909092vw)'
* }
*/
function between(fromSize, toSize, minScreen, maxScreen) {
if (minScreen === void 0) {
minScreen = '320px';
}
if (maxScreen === void 0) {
maxScreen = '1200px';
}
var _getValueAndUnit = getValueAndUnit(fromSize),
unitlessFromSize = _getValueAndUnit[0],
fromSizeUnit = _getValueAndUnit[1];
var _getValueAndUnit2 = getValueAndUnit(toSize),
unitlessToSize = _getValueAndUnit2[0],
toSizeUnit = _getValueAndUnit2[1];
var _getValueAndUnit3 = getValueAndUnit(minScreen),
unitlessMinScreen = _getValueAndUnit3[0],
minScreenUnit = _getValueAndUnit3[1];
var _getValueAndUnit4 = getValueAndUnit(maxScreen),
unitlessMaxScreen = _getValueAndUnit4[0],
maxScreenUnit = _getValueAndUnit4[1];
if (typeof unitlessMinScreen !== 'number' || typeof unitlessMaxScreen !== 'number' || !minScreenUnit || !maxScreenUnit || minScreenUnit !== maxScreenUnit) {
throw new Error('minScreen and maxScreen must be provided as stringified numbers with the same units.');
}
if (typeof unitlessFromSize !== 'number' || typeof unitlessToSize !== 'number' || !fromSizeUnit || !toSizeUnit || fromSizeUnit !== toSizeUnit) {
throw new Error('fromSize and toSize must be provided as stringified numbers with the same units.');
}
var slope = (unitlessFromSize - unitlessToSize) / (unitlessMinScreen - unitlessMaxScreen);
var base = unitlessToSize - slope * unitlessMaxScreen;
return "calc(" + base.toFixed(2) + fromSizeUnit + " + " + (100 * slope).toFixed(2) + "vw)";
}
/**
* CSS to contain a float (credit to CSSMojo).
*
* @example
* // Styles as object usage
* const styles = {
* ...clearFix(),
* }
*
* // styled-components usage
* const div = styled.div`
* ${clearFix()}
* `
*
* // CSS as JS Output
*
* '&::after': {
* 'clear': 'both',
* 'content': '""',
* 'display': 'table'
* }
*/
function clearFix(parent) {
var _ref;
if (parent === void 0) {
parent = '&';
}
var pseudoSelector = parent + "::after";
return _ref = {}, _ref[pseudoSelector] = {
clear: 'both',
content: '""',
display: 'table'
}, _ref;
}
/**
* CSS to fully cover an area. Can optionally be passed an offset to act as a "padding".
*
* @example
* // Styles as object usage
* const styles = {
* ...cover()
* }
*
* // styled-components usage
* const div = styled.div`
* ${cover()}
* `
*
* // CSS as JS Output
*
* div: {
* 'position': 'absolute',
* 'top': '0',
* 'right: '0',
* 'bottom': '0',
* 'left: '0'
* }
*/
function cover(offset) {
if (offset === void 0) {
offset = 0;
}
return {
position: 'absolute',
top: offset,
right: offset,
bottom: offset,
left: offset
};
}
/**
* CSS to represent truncated text with an ellipsis.
*
* @example
* // Styles as object usage
* const styles = {
* ...ellipsis('250px')
* }
*
* // styled-components usage
* const div = styled.div`
* ${ellipsis('250px')}
* `
*
* // CSS as JS Output
*
* div: {
* 'display': 'inline-block',
* 'maxWidth': '250px',
* 'overflow': 'hidden',
* 'textOverflow': 'ellipsis',
* 'whiteSpace': 'nowrap',
* 'wordWrap': 'normal'
* }
*/
function ellipsis(width) {
if (width === void 0) {
width = '100%';
}
return {
display: 'inline-block',
maxWidth: width,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
wordWrap: 'normal'
};
}
/**
* Returns a set of media queries that resizes a property (or set of properties) between a provided fromSize and toSize. Accepts optional minScreen (defaults to '320px') and maxScreen (defaults to '1200px') to constrain the interpolation.
*
* @example
* // Styles as object usage
* const styles = {
* ...fluidRange(
* {
* prop: 'padding',
* fromSize: '20px',
* toSize: '100px',
* },
* '400px',
* '1000px',
* )
* }
*
* // styled-components usage
* const div = styled.div`
* ${fluidRange(
* {
* prop: 'padding',
* fromSize: '20px',
* toSize: '100px',
* },
* '400px',
* '1000px',
* )}
* `
*
* // CSS as JS Output
*
* div: {
* "@media (min-width: 1000px)": Object {
* "padding": "100px",
* },
* "@media (min-width: 400px)": Object {
* "padding": "calc(-33.33333333333334px + 13.333333333333334vw)",
* },
* "padding": "20px",
* }
*/
function fluidRange(cssProp, minScreen, maxScreen) {
if (minScreen === void 0) {
minScreen = '320px';
}
if (maxScreen === void 0) {
maxScreen = '1200px';
}
if (!Array.isArray(cssProp) && typeof cssProp !== 'object' || cssProp === null) {
throw new Error('expects either an array of objects or a single object with the properties prop, fromSize, and toSize.');
}
if (Array.isArray(cssProp)) {
var mediaQueries = {};
var fallbacks = {};
for (var _iterator = cssProp, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _extends2, _extends3;
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var obj = _ref;
if (!obj.prop || !obj.fromSize || !obj.toSize) {
throw new Error('expects the objects in the first argument array to have the properties `prop`, `fromSize`, and `toSize`.');
}
fallbacks[obj.prop] = obj.fromSize;
mediaQueries["@media (min-width: " + minScreen + ")"] = _extends({}, mediaQueries["@media (min-width: " + minScreen + ")"], (_extends2 = {}, _extends2[obj.prop] = between(obj.fromSize, obj.toSize, minScreen, maxScreen), _extends2));
mediaQueries["@media (min-width: " + maxScreen + ")"] = _extends({}, mediaQueries["@media (min-width: " + maxScreen + ")"], (_extends3 = {}, _extends3[obj.prop] = obj.toSize, _extends3));
}
return _extends({}, fallbacks, mediaQueries);
} else {
var _ref2, _ref3, _ref4;
if (!cssProp.prop || !cssProp.fromSize || !cssProp.toSize) {
throw new Error('expects the first argument object to have the properties `prop`, `fromSize`, and `toSize`.');
}
return _ref4 = {}, _ref4[cssProp.prop] = cssProp.fromSize, _ref4["@media (min-width: " + minScreen + ")"] = (_ref2 = {}, _ref2[cssProp.prop] = between(cssProp.fromSize, cssProp.toSize, minScreen, maxScreen), _ref2), _ref4["@media (min-width: " + maxScreen + ")"] = (_ref3 = {}, _ref3[cssProp.prop] = cssProp.toSize, _ref3), _ref4;
}
}
function generateFileReferences(fontFilePath, fileFormats) {
var fileFontReferences = fileFormats.map(function (format) {
return "url(\"" + fontFilePath + "." + format + "\")";
});
return fileFontReferences.join(', ');
}
function generateLocalReferences(localFonts) {
var localFontReferences = localFonts.map(function (font) {
return "local(\"" + font + "\")";
});
return localFontReferences.join(', ');
}
function generateSources(fontFilePath, localFonts, fileFormats) {
var fontReferences = [];
if (localFonts) fontReferences.push(generateLocalReferences(localFonts));
if (fontFilePath) {
fontReferences.push(generateFileReferences(fontFilePath, fileFormats));
}
return fontReferences.join(', ');
}
/**
* CSS for a @font-face declaration.
*
* @example
* // Styles as object basic usage
* const styles = {
* ...fontFace({
* 'fontFamily': 'Sans-Pro',
* 'fontFilePath': 'path/to/file'
* })
* }
*
* // styled-components basic usage
* const GlobalStyle = createGlobalStyle`${
* fontFace({
* 'fontFamily': 'Sans-Pro',
* 'fontFilePath': 'path/to/file'
* }
* )}`
*
* // CSS as JS Output
*
* '@font-face': {
* 'fontFamily': 'Sans-Pro',
* 'src': 'url("path/to/file.eot"), url("path/to/file.woff2"), url("path/to/file.woff"), url("path/to/file.ttf"), url("path/to/file.svg")',
* }
*/
function fontFace(_ref) {
var fontFamily = _ref.fontFamily,
fontFilePath = _ref.fontFilePath,
fontStretch = _ref.fontStretch,
fontStyle = _ref.fontStyle,
fontVariant = _ref.fontVariant,
fontWeight = _ref.fontWeight,
_ref$fileFormats = _ref.fileFormats,
fileFormats = _ref$fileFormats === void 0 ? ['eot', 'woff2', 'woff', 'ttf', 'svg'] : _ref$fileFormats,
localFonts = _ref.localFonts,
unicodeRange = _ref.unicodeRange,
fontDisplay = _ref.fontDisplay,
fontVariationSettings = _ref.fontVariationSettings,
fontFeatureSettings = _ref.fontFeatureSettings;
// Error Handling
if (!fontFamily) throw new Error('fontFace expects a name of a font-family.');
if (!fontFilePath && !localFonts) {
throw new Error('fontFace expects either the path to the font file(s) or a name of a local copy.');
}
if (localFonts && !Array.isArray(localFonts)) {
throw new Error('fontFace expects localFonts to be an array.');
}
if (!Array.isArray(fileFormats)) {
throw new Error('fontFace expects fileFormats to be an array.');
}
var fontFaceDeclaration = {
'@font-face': {
fontFamily: fontFamily,
src: generateSources(fontFilePath, localFonts, fileFormats),
unicodeRange: unicodeRange,
fontStretch: fontStretch,
fontStyle: fontStyle,
fontVariant: fontVariant,
fontWeight: fontWeight,
fontDisplay: fontDisplay,
fontVariationSettings: fontVariationSettings,
fontFeatureSettings: fontFeatureSettings
} // Removes undefined fields for cleaner css object.
};
return JSON.parse(JSON.stringify(fontFaceDeclaration));
}
/**
* CSS to hide text to show a background image in a SEO-friendly way.
*
* @example
* // Styles as object usage
* const styles = {
* 'backgroundImage': 'url(logo.png)',
* ...hideText(),
* }
*
* // styled-components usage
* const div = styled.div`
* backgroundImage: url(logo.png);
* ${hideText()};
* `
*
* // CSS as JS Output
*
* 'div': {
* 'backgroundImage': 'url(logo.png)',
* 'textIndent': '101%',
* 'overflow': 'hidden',
* 'whiteSpace': 'nowrap',
* }
*/
function hideText() {
return {
textIndent: '101%',
overflow: 'hidden',
whiteSpace: 'nowrap'
};
}
/**
* CSS to hide content visually but remain accessible to screen readers.
* from [HTML5 Boilerplate](https://github.com/h5bp/html5-boilerplate/blob/9a176f57af1cfe8ec70300da4621fb9b07e5fa31/src/css/main.css#L121)
*
* @example
* // Styles as object usage
* const styles = {
* ...hideVisually(),
* }
*
* // styled-components usage
* const div = styled.div`
* ${hideVisually()};
* `
*
* // CSS as JS Output
*
* 'div': {
* 'border': '0',
* 'clip': 'rect(0 0 0 0)',
* 'clipPath': 'inset(50%)',
* 'height': '1px',
* 'margin': '-1px',
* 'overflow': 'hidden',
* 'padding': '0',
* 'position': 'absolute',
* 'whiteSpace': 'nowrap',
* 'width': '1px',
* }
*/
function hideVisually() {
return {
border: '0',
clip: 'rect(0 0 0 0)',
clipPath: 'inset(50%)',
height: '1px',
margin: '-1px',
overflow: 'hidden',
padding: '0',
position: 'absolute',
whiteSpace: 'nowrap',
width: '1px'
};
}
/**
* Generates a media query to target HiDPI devices.
*
* @example
* // Styles as object usage
* const styles = {
* [hiDPI(1.5)]: {
* width: 200px;
* }
* }
*
* // styled-components usage
* const div = styled.div`
* ${hiDPI(1.5)} {
* width: 200px;
* }
* `
*
* // CSS as JS Output
*
* '@media only screen and (-webkit-min-device-pixel-ratio: 1.5),
* only screen and (min--moz-device-pixel-ratio: 1.5),
* only screen and (-o-min-device-pixel-ratio: 1.5/1),
* only screen and (min-resolution: 144dpi),
* only screen and (min-resolution: 1.5dppx)': {
* 'width': '200px',
* }
*/
function hiDPI(ratio) {
if (ratio === void 0) {
ratio = 1.3;
}
return "\n @media only screen and (-webkit-min-device-pixel-ratio: " + ratio + "),\n only screen and (min--moz-device-pixel-ratio: " + ratio + "),\n only screen and (-o-min-device-pixel-ratio: " + ratio + "/1),\n only screen and (min-resolution: " + Math.round(ratio * 96) + "dpi),\n only screen and (min-resolution: " + ratio + "dppx)\n ";
}
/**
* CSS to normalize abnormalities across browsers (normalize.css v8.0.0 | MIT License | github.com/necolas/normalize.css)
*
* @example
* // Styles as object usage
* const styles = {
* ...normalize(),
* }
*
* // styled-components usage
* const GlobalStyle = createGlobalStyle`${normalize()}`
*
* // CSS as JS Output
*
* html {
* lineHeight: 1.15,
* textSizeAdjust: 100%,
* } ...
*/
function normalize() {
var _ref;
return [(_ref = {
html: {
lineHeight: '1.15',
textSizeAdjust: '100%'
},
body: {
margin: '0'
},
h1: {
fontSize: '2em',
margin: '0.67em 0'
},
hr: {
boxSizing: 'content-box',
height: '0',
overflow: 'visible'
},
pre: {
fontFamily: 'monospace, monospace',
fontSize: '1em'
},
a: {
backgroundColor: 'transparent'
},
'abbr[title]': {
borderBottom: 'none',
textDecoration: 'underline'
}
}, _ref["b,\n strong"] = {
fontWeight: 'bolder'
}, _ref["code,\n kbd,\n samp"] = {
fontFamily: 'monospace, monospace',
fontSize: '1em'
}, _ref.small = {
fontSize: '80%'
}, _ref["sub,\n sup"] = {
fontSize: '75%',
lineHeight: '0',
position: 'relative',
verticalAlign: 'baseline'
}, _ref.sub = {
bottom: '-0.25em'
}, _ref.sup = {
top: '-0.5em'
}, _ref.img = {
borderStyle: 'none'
}, _ref["button,\n input,\n optgroup,\n select,\n textarea"] = {
fontFamily: 'inherit',
fontSize: '100%',
lineHeight: '1.15',
margin: '0'
}, _ref["button,\n input"] = {
overflow: 'visible'
}, _ref["button,\n select"] = {
textTransform: 'none'
}, _ref["button,\n html [type=\"button\"],\n [type=\"reset\"],\n [type=\"submit\"]"] = {
WebkitAppearance: 'button'
}, _ref["button::-moz-focus-inner,\n [type=\"button\"]::-moz-focus-inner,\n [type=\"reset\"]::-moz-focus-inner,\n [type=\"submit\"]::-moz-focus-inner"] = {
borderStyle: 'none',
padding: '0'
}, _ref["button:-moz-focusring,\n [type=\"button\"]:-moz-focusring,\n [type=\"reset\"]:-moz-focusring,\n [type=\"submit\"]:-moz-focusring"] = {
outline: '1px dotted ButtonText'
}, _ref.fieldset = {
padding: '0.35em 0.625em 0.75em'
}, _ref.legend = {
boxSizing: 'border-box',
color: 'inherit',
display: 'table',
maxWidth: '100%',
padding: '0',
whiteSpace: 'normal'
}, _ref.progress = {
verticalAlign: 'baseline'
}, _ref.textarea = {
overflow: 'auto'
}, _ref["[type=\"checkbox\"],\n [type=\"radio\"]"] = {
boxSizing: 'border-box',
padding: '0'
}, _ref["[type=\"number\"]::-webkit-inner-spin-button,\n [type=\"number\"]::-webkit-outer-spin-button"] = {
height: 'auto'
}, _ref['[type="search"]'] = {
WebkitAppearance: 'textfield',
outlineOffset: '-2px'
}, _ref['[type="search"]::-webkit-search-decoration'] = {
WebkitAppearance: 'none'
}, _ref['::-webkit-file-upload-button'] = {
WebkitAppearance: 'button',
font: 'inherit'
}, _ref.details = {
display: 'block'
}, _ref.summary = {
display: 'list-item'
}, _ref.template = {
display: 'none'
}, _ref['[hidden]'] = {
display: 'none'
}, _ref), {
'abbr[title]': {
textDecoration: 'underline dotted'
}
}];
}
/**
* CSS to style the placeholder pseudo-element.
*
* @deprecated - placeholder has been marked for deprecation in polished 2.0 and will be fully deprecated in 3.0. It is no longer needed and can safely be replaced with the non-prefixed placeholder pseudo-element.
*
* @example
* // Styles as object usage
* const styles = {
* ...placeholder({'color': 'blue'})
* }
*
* // styled-components usage
* const div = styled.input`
* ${placeholder({'color': 'blue'})}
* `
*
* // CSS as JS Output
*
* 'input': {
* '&:-moz-placeholder': {
* 'color': 'blue',
* },
* '&:-ms-input-placeholder': {
* 'color': 'blue',
* },
* '&::-moz-placeholder': {
* 'color': 'blue',
* },
* '&::-webkit-input-placeholder': {
* 'color': 'blue',
* },
* },
*/
function placeholder(styles, parent) {
var _ref;
if (parent === void 0) {
parent = '&';
}
return _ref = {}, _ref[parent + "::-webkit-input-placeholder"] = _extends({}, styles), _ref[parent + ":-moz-placeholder"] = _extends({}, styles), _ref[parent + "::-moz-placeholder"] = _extends({}, styles), _ref[parent + ":-ms-input-placeholder"] = _extends({}, styles), _ref;
}
function _templateObject() {
var data = _taggedTemplateLiteralLoose(["radial-gradient(", "", "", "", ")"]);
_templateObject = function _templateObject() {
return data;
};
return data;
}
function parseFallback(colorStops) {
return colorStops[0].split(' ')[0];
}
function constructGradientValue(literals) {
var template = '';
for (var i = 0; i < literals.length; i += 1) {
template += literals[i]; // Adds leading coma if properties preceed color-stops
if (i === 3 && (i + 1 < 1 || arguments.length <= i + 1 ? undefined : arguments[i + 1]) && ((arguments.length <= 1 ? undefined : arguments[1]) || (arguments.length <= 2 ? undefined : arguments[2]) || (arguments.length <= 3 ? undefined : arguments[3]))) {
template = template.slice(0, -1);
template += ", " + (i + 1 < 1 || arguments.length <= i + 1 ? undefined : arguments[i + 1]); // No trailing space if color-stops is the only param provided
} else if (i === 3 && (i + 1 < 1 || arguments.length <= i + 1 ? undefined : arguments[i + 1]) && !(arguments.length <= 1 ? undefined : arguments[1]) && !(arguments.length <= 2 ? undefined : arguments[2]) && !(arguments.length <= 3 ? undefined : arguments[3])) {
template += "" + (i + 1 < 1 || arguments.length <= i + 1 ? undefined : arguments[i + 1]); // Only adds substitution if it is defined
} else if (i + 1 < 1 || arguments.length <= i + 1 ? undefined : arguments[i + 1]) {
template += (i + 1 < 1 || arguments.length <= i + 1 ? undefined : arguments[i + 1]) + " ";
}
}
return template.trim();
}
/**
* CSS for declaring a radial gradient, including a fallback background-color. The fallback is either the first color-stop or an explicitly passed fallback color.
*
* @example
* // Styles as object usage
* const styles = {
* ...radialGradient({
* colorStops: ['#00FFFF 0%', 'rgba(0, 0, 255, 0) 50%', '#0000FF 95%'],
* extent: 'farthest-corner at 45px 45px',
* position: 'center',
* shape: 'ellipse',
* })
* }
*
* // styled-components usage
* const div = styled.div`
* ${radialGradient({
* colorStops: ['#00FFFF 0%', 'rgba(0, 0, 255, 0) 50%', '#0000FF 95%'],
* extent: 'farthest-corner at 45px 45px',
* position: 'center',
* shape: 'ellipse',
* })}
*`
*
* // CSS as JS Output
*
* div: {
* 'backgroundColor': '#00FFFF',
* 'backgroundImage': 'radial-gradient(center ellipse farthest-corner at 45px 45px, #00FFFF 0%, rgba(0, 0, 255, 0) 50%, #0000FF 95%)',
* }
*/
function radialGradient(_ref) {
var colorStops = _ref.colorStops,
extent = _ref.extent,
fallback = _ref.fallback,
position = _ref.position,
shape = _ref.shape;
if (!colorStops || colorStops.length < 2) {
throw new Error('radialGradient requries at least 2 color-stops to properly render.');
}
return {
backgroundColor: fallback || parseFallback(colorStops),
backgroundImage: constructGradientValue(_templateObject(), position, shape, extent, colorStops.join(', '))
};
}
/**
* A helper to generate a retina background image and non-retina
* background image. The retina background image will output to a HiDPI media query. The mixin uses
* a _2x.png filename suffix by default.
*
* @example
* // Styles as object usage
* const styles = {
* ...retinaImage('my-img')
* }
*
* // styled-components usage
* const div = styled.div`
* ${retinaImage('my-img')}
* `
*
* // CSS as JS Output
* div {
* backgroundImage: 'url(my-img.png)',
* '@media only screen and (-webkit-min-device-pixel-ratio: 1.3),
* only screen and (min--moz-device-pixel-ratio: 1.3),
* only screen and (-o-min-device-pixel-ratio: 1.3/1),
* only screen and (min-resolution: 144dpi),
* only screen and (min-resolution: 1.5dppx)': {
* backgroundImage: 'url(my-img_2x.png)',
* }
* }
*/
function retinaImage(filename, backgroundSize, extension, retinaFilename, retinaSuffix) {
var _ref;
if (extension === void 0) {
extension = 'png';
}
if (retinaSuffix === void 0) {
retinaSuffix = '_2x';
}
if (!filename) {
throw new Error('Please supply a filename to retinaImage() as the first argument.');
} // Replace the dot at the beginning of the passed extension if one exists
var ext = extension.replace(/^\./, '');
var rFilename = retinaFilename ? retinaFilename + "." + ext : "" + filename + retinaSuffix + "." + ext;
return _ref = {
backgroundImage: "url(" + filename + "." + ext + ")"
}, _ref[hiDPI()] = _extends({
backgroundImage: "url(" + rFilename + ")"
}, backgroundSize ? {
backgroundSize: backgroundSize
} : {}), _ref;
}
/**
* CSS to style the selection pseudo-element.
*
* @deprecated - selection has been marked for deprecation in polished 2.0 and will be fully deprecated in 3.0. It is no longer needed and can safely be replaced with the non-prefixed selection pseudo-element.
*
* @example
* // Styles as object usage
* const styles = {
* ...selection({
* 'backgroundColor': 'blue'
* }, 'section')
* }
*
* // styled-components usage
* const div = styled.div`
* ${selection({'backgroundColor': 'blue'}, 'section')}
* `
*
* // CSS as JS Output
*
* 'div': {
* 'section::-moz-selection': {
* 'backgroundColor':'blue',
* },
* 'section::selection': {
* 'backgroundColor': 'blue',
* }
* }
*/
function selection(styles, parent) {
var _ref;
if (parent === void 0) {
parent = '';
}
return _ref = {}, _ref[parent + "::-moz-selection"] = _extends({}, styles), _ref[parent + "::selection"] = _extends({}, styles), _ref;
}
/* eslint-disable key-spacing */
var functionsMap = {
easeInBack: 'cubic-bezier(0.600, -0.280, 0.735, 0.045)',
easeInCirc: 'cubic-bezier(0.600, 0.040, 0.980, 0.335)',
easeInCubic: 'cubic-bezier(0.550, 0.055, 0.675, 0.190)',
easeInExpo: 'cubic-bezier(0.950, 0.050, 0.795, 0.035)',
easeInQuad: 'cubic-bezier(0.550, 0.085, 0.680, 0.530)',
easeInQuart: 'cubic-bezier(0.895, 0.030, 0.685, 0.220)',
easeInQuint: 'cubic-bezier(0.755, 0.050, 0.855, 0.060)',
easeInSine: 'cubic-bezier(0.470, 0.000, 0.745, 0.715)',
easeOutBack: 'cubic-bezier(0.175, 0.885, 0.320, 1.275)',
easeOutCubic: 'cubic-bezier(0.215, 0.610, 0.355, 1.000)',
easeOutCirc: 'cubic-bezier(0.075, 0.820, 0.165, 1.000)',
easeOutExpo: 'cubic-bezier(0.190, 1.000, 0.220, 1.000)',
easeOutQuad: 'cubic-bezier(0.250, 0.460, 0.450, 0.940)',
easeOutQuart: 'cubic-bezier(0.165, 0.840, 0.440, 1.000)',
easeOutQuint: 'cubic-bezier(0.230, 1.000, 0.320, 1.000)',
easeOutSine: 'cubic-bezier(0.390, 0.575, 0.565, 1.000)',
easeInOutBack: 'cubic-bezier(0.680, -0.550, 0.265, 1.550)',
easeInOutCirc: 'cubic-bezier(0.785, 0.135, 0.150, 0.860)',
easeInOutCubic: 'cubic-bezier(0.645, 0.045, 0.355, 1.000)',
easeInOutExpo: 'cubic-bezier(1.000, 0.000, 0.000, 1.000)',
easeInOutQuad: 'cubic-bezier(0.455, 0.030, 0.515, 0.955)',
easeInOutQuart: 'cubic-bezier(0.770, 0.000, 0.175, 1.000)',
easeInOutQuint: 'cubic-bezier(0.860, 0.000, 0.070, 1.000)',
easeInOutSine: 'cubic-bezier(0.445, 0.050, 0.550, 0.950)'
/* eslint-enable key-spacing */
};
function getTimingFunction(functionName) {
return functionsMap[functionName];
}
/**
* String to represent common easing functions as demonstrated here: (github.com/jaukia/easie).
*
* @example
* // Styles as object usage
* const styles = {
* 'transitionTimingFunction': timingFunctions('easeInQuad')
* }
*
* // styled-components usage
* const div = styled.div`
* transitionTimingFunction: ${timingFunctions('easeInQuad')};
* `
*
* // CSS as JS Output
*
* 'div': {
* 'transitionTimingFunction': 'cubic-bezier(0.550, 0.085, 0.680, 0.530)',
* }
*/
function timingFunctions(timingFunction) {
return getTimingFunction(timingFunction);
}
/**
* Shorthand that accepts up to four values, including null to skip a value, and maps them to their respective directions.
* @example
* // Styles as object usage
* const styles = {
* ...borderColor('red', 'green', 'blue', 'yellow')
* }
*
* // styled-components usage
* const div = styled.div`
* ${borderColor('red', 'green', 'blue', 'yellow')}
* `
*
* // CSS as JS Output
*
* div {
* 'borderTopColor': 'red',
* 'borderRightColor': 'green',
* 'borderBottomColor': 'blue',
* 'borderLeftColor': 'yellow'
* }
*/
function borderColor() {
for (var _len = arguments.length, values = new Array(_len), _key = 0; _key < _len; _key++) {
values[_key] = arguments[_key];
}
return directionalProperty.apply(void 0, ['borderColor'].concat(values));
}
var getBorderWidth = function getBorderWidth(pointingDirection, height, width) {
switch (pointingDirection) {
case 'top':
return "0 " + width[0] / 2 + width[1] + " " + height[0] + height[1] + " " + width[0] / 2 + width[1];
case 'left':
return "" + height[0] / 2 + height[1] + " " + width[0] + width[1] + " " + height[0] / 2 + height[1] + " 0";
case 'bottom':
return "" + height[0] + height[1] + " " + width[0] / 2 + width[1] + " 0 " + width[0] / 2 + width[1];
case 'right':
return "" + height[0] / 2 + height[1] + " 0 " + height[0] / 2 + height[1] + " " + width[0] + width[1];
default:
throw new Error("Passed invalid argument to triangle, please pass correct pointingDirection e.g. 'right'.");
}
}; // needed for border-color
var reverseDirection = ['bottom', 'left', 'top', 'right'];
var NUMBER_AND_FLOAT = /(\d*\.?\d*)/;
/**
* CSS to represent triangle with any pointing direction with an optional background color. Accepts number or px values for height and width.
*
* @example
* // Styles as object usage
*
* const styles = {
* ...triangle({ pointingDirection: 'right', width: '100px', height: '100px', foregroundColor: 'red' })
* }
*
*
* // styled-components usage
* const div = styled.div`
* ${triangle({ pointingDirection: 'right', width: '100px', height: '100px', foregroundColor: 'red' })}
*
*
* // CSS as JS Output
*
* div: {
* 'borderColor': 'transparent',
* 'borderLeftColor': 'red !important',
* 'borderStyle': 'solid',
* 'borderWidth': '50px 0 50px 100px',
* 'height': '0',
* 'width': '0',
* }
*/
function triangle(_ref) {
var pointingDirection = _ref.pointingDirection,
height = _ref.height,
width = _ref.width,
foregroundColor = _ref.foregroundColor,
_ref$backgroundColor = _ref.backgroundColor,
backgroundColor = _ref$backgroundColor === void 0 ? 'transparent' : _ref$backgroundColor;
var widthAndUnit = [parseFloat(width), String(width).replace(NUMBER_AND_FLOAT, '') || 'px'];
var heightAndUnit = [parseFloat(height), String(height).replace(NUMBER_AND_FLOAT, '') || 'px'];
if (isNaN(heightAndUnit[0]) || isNaN(widthAndUnit[0])) {
throw new Error('Passed an invalid value to `height` or `width`. Please provide a pixel based unit');
}
var reverseDirectionIndex = reverseDirection.indexOf(pointingDirection);
return _extends({
width: '0',
height: '0',
borderWidth: getBorderWidth(pointingDirection, heightAndUnit, widthAndUnit),
borderStyle: 'solid'
}, borderColor.apply(void 0, Array.from({
length: 4
}).map(function (_, index) {
return index === reverseDirectionIndex ? foregroundColor : backgroundColor;
})));
}
/**
* Provides an easy way to change the `wordWrap` property.
*
* @example
* // Styles as object usage
* const styles = {
* ...wordWrap('break-word')
* }
*
* // styled-components usage
* const div = styled.div`
* ${wordWrap('break-word')}
* `
*
* // CSS as JS Output
*
* const styles = {
* overflowWrap: 'break-word',
* wordWrap: 'break-word',
* wordBreak: 'break-all',
* }
*/
function wordWrap(wrap) {
if (wrap === void 0) {
wrap = 'break-word';
}
var wordBreak = wrap === 'break-word' ? 'break-all' : wrap;
return {
overflowWrap: wrap,
wordWrap: wrap,
wordBreak: wordBreak
};
}
function colorToInt(color) {
return Math.round(color * 255);
}
function convertToInt(red, green, blue) {
return colorToInt(red) + "," + colorToInt(green) + "," + colorToInt(blue);
}
function hslToRgb(hue, saturation, lightness, convert) {
if (convert === void 0) {
convert = convertToInt;
}
if (saturation === 0) {
// achromatic
return convert(lightness, lightness, lightness);
} // formular from https://en.wikipedia.org/wiki/HSL_and_HSV
var huePrime = hue % 360 / 60;
var chroma = (1 - Math.abs(2 * lightness - 1)) * saturation;
var secondComponent = chroma * (1 - Math.abs(huePrime % 2 - 1));
var red = 0;
var green = 0;
var blue = 0;
if (huePrime >= 0 && huePrime < 1) {
red = chroma;
green = secondComponent;
} else if (huePrime >= 1 && huePrime < 2) {
red = secondComponent;
green = chroma;
} else if (huePrime >= 2 && huePrime < 3) {
green = chroma;
blue = secondComponent;
} else if (huePrime >= 3 && huePrime < 4) {
green = secondComponent;
blue = chroma;
} else if (huePrime >= 4 && huePrime < 5) {
red = secondComponent;
blue = chroma;
} else if (huePrime >= 5 && huePrime < 6) {
red = chroma;
blue = secondComponent;
}
var lightnessModification = lightness - chroma / 2;
var finalRed = red + lightnessModification;
var finalGreen = green + lightnessModification;
var finalBlue = blue + lightnessModification;
return convert(finalRed, finalGreen, finalBlue);
}
var namedColorMap = {
aliceblue: 'f0f8ff',
antiquewhite: 'faebd7',
aqua: '00ffff',
aquamarine: '7fffd4',
azure: 'f0ffff',
beige: 'f5f5dc',
bisque: 'ffe4c4',
black: '000',
blanchedalmond: 'ffebcd',
blue: '0000ff',
blueviolet: '8a2be2',
brown: 'a52a2a',
burlywood: 'deb887',
cadetblue: '5f9ea0',
chartreuse: '7fff00',
chocolate: 'd2691e',
coral: 'ff7f50',
cornflowerblue: '6495ed',
cornsilk: 'fff8dc',
crimson: 'dc143c',
cyan: '00ffff',
darkblue: '00008b',
darkcyan: '008b8b',
darkgoldenrod: 'b8860b',
darkgray: 'a9a9a9',
darkgreen: '006400',
darkgrey: 'a9a9a9',
darkkhaki: 'bdb76b',
darkmagenta: '8b008b',
darkolivegreen: '556b2f',
darkorange: 'ff8c00',
darkorchid: '9932cc',
darkred: '8b0000',
darksalmon: 'e9967a',
darkseagreen: '8fbc8f',
darkslateblue: '483d8b',
darkslategray: '2f4f4f',
darkslategrey: '2f4f4f',
darkturquoise: '00ced1',
darkviolet: '9400d3',
deeppink: 'ff1493',
deepskyblue: '00bfff',
dimgray: '696969',
dimgrey: '696969',
dodgerblue: '1e90ff',
firebrick: 'b22222',
floralwhite: 'fffaf0',
forestgreen: '228b22',
fuchsia: 'ff00ff',
gainsboro: 'dcdcdc',
ghostwhite: 'f8f8ff',
gold: 'ffd700',
goldenrod: 'daa520',
gray: '808080',
green: '008000',
greenyellow: 'adff2f',
grey: '808080',
honeydew: 'f0fff0',
hotpink: 'ff69b4',
indianred: 'cd5c5c',
indigo: '4b0082',
ivory: 'fffff0',
khaki: 'f0e68c',
lavender: 'e6e6fa',
lavenderblush: 'fff0f5',
lawngreen: '7cfc00',
lemonchiffon: 'fffacd',
lightblue: 'add8e6',
lightcoral: 'f08080',
lightcyan: 'e0ffff',
lightgoldenrodyellow: 'fafad2',
lightgray: 'd3d3d3',
lightgreen: '90ee90',
lightgrey: 'd3d3d3',
lightpink: 'ffb6c1',
lightsalmon: 'ffa07a',
lightseagreen: '20b2aa',
lightskyblue: '87cefa',
lightslategray: '789',
lightslategrey: '789',
lightsteelblue: 'b0c4de',
lightyellow: 'ffffe0',
lime: '0f0',
limegreen: '32cd32',
linen: 'faf0e6',
magenta: 'f0f',
maroon: '800000',
mediumaquamarine: '66cdaa',
mediumblue: '0000cd',
mediumorchid: 'ba55d3',
mediumpurple: '9370db',
mediumseagreen: '3cb371',
mediumslateblue: '7b68ee',
mediumspringgreen: '00fa9a',
mediumturquoise: '48d1cc',
mediumvioletred: 'c71585',
midnightblue: '191970',
mintcream: 'f5fffa',
mistyrose: 'ffe4e1',
moccasin: 'ffe4b5',
navajowhite: 'ffdead',
navy: '000080',
oldlace: 'fdf5e6',
olive: '808000',
olivedrab: '6b8e23',
orange: 'ffa500',
orangered: 'ff4500',
orchid: 'da70d6',
palegoldenrod: 'eee8aa',
palegreen: '98fb98',
paleturquoise: 'afeeee',
palevioletred: 'db7093',
papayawhip: 'ffefd5',
peachpuff: 'ffdab9',
peru: 'cd853f',
pink: 'ffc0cb',
plum: 'dda0dd',
powderblue: 'b0e0e6',
purple: '800080',
rebeccapurple: '639',
red: 'f00',
rosybrown: 'bc8f8f',
royalblue: '4169e1',
saddlebrown: '8b4513',
salmon: 'fa8072',
sandybrown: 'f4a460',
seagreen: '2e8b57',
seashell: 'fff5ee',
sienna: 'a0522d',
silver: 'c0c0c0',
skyblue: '87ceeb',
slateblue: '6a5acd',
slategray: '708090',
slategrey: '708090',
snow: 'fffafa',
springgreen: '00ff7f',
steelblue: '4682b4',
tan: 'd2b48c',
teal: '008080',
thistle: 'd8bfd8',
tomato: 'ff6347',
turquoise: '40e0d0',
violet: 'ee82ee',
wheat: 'f5deb3',
white: 'fff',
whitesmoke: 'f5f5f5',
yellow: 'ff0',
yellowgreen: '9acd32'
/**
* Checks if a string is a CSS named color and returns its equivalent hex value, otherwise returns the original color.
* @private
*/
};
function nameToHex(color) {
if (typeof color !== 'string') return color;
var normalizedColorName = color.toLowerCase();
return namedColorMap[normalizedColorName] ? "#" + namedColorMap[normalizedColorName] : color;
}
var hexRegex = /^#[a-fA-F0-9]{6}$/;
var hexRgbaRegex = /^#[a-fA-F0-9]{8}$/;
var reducedHexRegex = /^#[a-fA-F0-9]{3}$/;
var reducedRgbaHexRegex = /^#[a-fA-F0-9]{4}$/;
var rgbRegex = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/;
var rgbaRegex = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*([-+]?[0-9]*[.]?[0-9]+)\s*\)$/;
var hslRegex = /^hsl\(\s*(\d{0,3}[.]?[0-9]+)\s*,\s*(\d{1,3})%\s*,\s*(\d{1,3})%\s*\)$/;
var hslaRegex = /^hsla\(\s*(\d{0,3}[.]?[0-9]+)\s*,\s*(\d{1,3})%\s*,\s*(\d{1,3})%\s*,\s*([-+]?[0-9]*[.]?[0-9]+)\s*\)$/;
/**
* Returns an RgbColor or RgbaColor object. This utility function is only useful
* if want to extract a color component. With the color util `toColorString` you
* can convert a RgbColor or RgbaColor object back to a string.
*
* @example
* // Assigns `{ red: 255, green: 0, blue: 0 }` to color1
* const color1 = parseToRgb('rgb(255, 0, 0)');
* // Assigns `{ red: 92, green: 102, blue: 112, alpha: 0.75 }` to color2
* const color2 = parseToRgb('hsla(210, 10%, 40%, 0.75)');
*/
function parseToRgb(color) {
if (typeof color !== 'string') {
throw new Error('Passed an incorrect argument to a color function, please pass a string representation of a color.');
}
var normalizedColor = nameToHex(color);
if (normalizedColor.match(hexRegex)) {
return {
red: parseInt("" + normalizedColor[1] + normalizedColor[2], 16),
green: parseInt("" + normalizedColor[3] + normalizedColor[4], 16),
blue: parseInt("" + normalizedColor[5] + normalizedColor[6], 16)
};
}
if (normalizedColor.match(hexRgbaRegex)) {
var alpha = parseFloat((parseInt("" + normalizedColor[7] + normalizedColor[8], 16) / 255).toFixed(2));
return {
red: parseInt("" + normalizedColor[1] + normalizedColor[2], 16),
green: parseInt("" + normalizedColor[3] + normalizedColor[4], 16),
blue: parseInt("" + normalizedColor[5] + normalizedColor[6], 16),
alpha: alpha
};
}
if (normalizedColor.match(reducedHexRegex)) {
return {
red: parseInt("" + normalizedColor[1] + normalizedColor[1], 16),
green: parseInt("" + normalizedColor[2] + normalizedColor[2], 16),
blue: parseInt("" + normalizedColor[3] + normalizedColor[3], 16)
};
}
if (normalizedColor.match(reducedRgbaHexRegex)) {
var _alpha = parseFloat((parseInt("" + normalizedColor[4] + normalizedColor[4], 16) / 255).toFixed(2));
return {
red: parseInt("" + normalizedColor[1] + normalizedColor[1], 16),
green: parseInt("" + normalizedColor[2] + normalizedColor[2], 16),
blue: parseInt("" + normalizedColor[3] + normalizedColor[3], 16),
alpha: _alpha
};
}
var rgbMatched = rgbRegex.exec(normalizedColor);
if (rgbMatched) {
return {
red: parseInt("" + rgbMatched[1], 10),
green: parseInt("" + rgbMatched[2], 10),
blue: parseInt("" + rgbMatched[3], 10)
};
}
var rgbaMatched = rgbaRegex.exec(normalizedColor);
if (rgbaMatched) {
return {
red: parseInt("" + rgbaMatched[1], 10),
green: parseInt("" + rgbaMatched[2], 10),
blue: parseInt("" + rgbaMatched[3], 10),
alpha: parseFloat("" + rgbaMatched[4])
};
}
var hslMatched = hslRegex.exec(normalizedColor);
if (hslMatched) {
var hue = parseInt("" + hslMatched[1], 10);
var saturation = parseInt("" + hslMatched[2], 10) / 100;
var lightness = parseInt("" + hslMatched[3], 10) / 100;
var rgbColorString = "rgb(" + hslToRgb(hue, saturation, lightness) + ")";
var hslRgbMatched = rgbRegex.exec(rgbColorString);
if (!hslRgbMatched) {
throw new Error("Couldn't generate valid rgb string from " + normalizedColor + ", it returned " + rgbColorString + ".");
}
return {
red: parseInt("" + hslRgbMatched[1], 10),
green: parseInt("" + hslRgbMatched[2], 10),
blue: parseInt("" + hslRgbMatched[3], 10)
};
}
var hslaMatched = hslaRegex.exec(normalizedColor);
if (hslaMatched) {
var _hue = parseInt("" + hslaMatched[1], 10);
var _saturation = parseInt("" + hslaMatched[2], 10) / 100;
var _lightness = parseInt("" + hslaMatched[3], 10) / 100;
var _rgbColorString = "rgb(" + hslToRgb(_hue, _saturation, _lightness) + ")";
var _hslRgbMatched = rgbRegex.exec(_rgbColorString);
if (!_hslRgbMatched) {
throw new Error("Couldn't generate valid rgb string from " + normalizedColor + ", it returned " + _rgbColorString + ".");
}
return {
red: parseInt("" + _hslRgbMatched[1], 10),
green: parseInt("" + _hslRgbMatched[2], 10),
blue: parseInt("" + _hslRgbMatched[3], 10),
alpha: parseFloat("" + hslaMatched[4])
};
}
throw new Error("Couldn't parse the color string. Please provide the color as a string in hex, rgb, rgba, hsl or hsla notation.");
}
function rgbToHsl(color) {
// make sure rgb are contained in a set of [0, 255]
var red = color.red / 255;
var green = color.green / 255;
var blue = color.blue / 255;
var max = Math.max(red, green, blue);
var min = Math.min(red, green, blue);
var lightness = (max + min) / 2;
if (max === min) {
// achromatic
if (color.alpha !== undefined) {
return {
hue: 0,
saturation: 0,
lightness: lightness,
alpha: color.alpha
};
} else {
return {
hue: 0,
saturation: 0,
lightness: lightness
};
}
}
var hue;
var delta = max - min;
var saturation = lightness > 0.5 ? delta / (2 - max - min) : delta / (max + min);
switch (max) {
case red:
hue = (green - blue) / delta + (green < blue ? 6 : 0);
break;
case green:
hue = (blue - red) / delta + 2;
break;
default:
// blue case
hue = (red - green) / delta + 4;
break;
}
hue *= 60;
if (color.alpha !== undefined) {
return {
hue: hue,
saturation: saturation,
lightness: lightness,
alpha: color.alpha
};
}
return {
hue: hue,
saturation: saturation,
lightness: lightness
};
}
/**
* Returns an HslColor or HslaColor object. This utility function is only useful
* if want to extract a color component. With the color util `toColorString` you
* can convert a HslColor or HslaColor object back to a string.
*
* @example
* // Assigns `{ hue: 0, saturation: 1, lightness: 0.5 }` to color1
* const color1 = parseToHsl('rgb(255, 0, 0)');
* // Assigns `{ hue: 128, saturation: 1, lightness: 0.5, alpha: 0.75 }` to color2
* const color2 = parseToHsl('hsla(128, 100%, 50%, 0.75)');
*/
function parseToHsl(color) {
// Note: At a later stage we can optimize this function as right now a hsl
// color would be parsed converted to rgb values and converted back to hsl.
return rgbToHsl(parseToRgb(color));
}
/**
* Reduces hex values if possible e.g. #ff8866 to #f86
* @private
*/
var reduceHexValue = function reduceHexValue(value) {
if (value.length === 7 && value[1] === value[2] && value[3] === value[4] && value[5] === value[6]) {
return "#" + value[1] + value[3] + value[5];
}
return value;
};
function numberToHex(value) {
var hex = value.toString(16);
return hex.length === 1 ? "0" + hex : hex;
}
function colorToHex(color) {
return numberToHex(Math.round(color * 255));
}
function convertToHex(red, green, blue) {
return reduceHexValue("#" + colorToHex(red) + colorToHex(green) + colorToHex(blue));
}
function hslToHex(hue, saturation, lightness) {
return hslToRgb(hue, saturation, lightness, convertToHex);
}
/**
* Returns a string value for the color. The returned result is the smallest possible hex notation.
*
* @example
* // Styles as object usage
* const styles = {
* background: hsl(359, 0.75, 0.4),
* background: hsl({ hue: 360, saturation: 0.75, lightness: 0.4 }),
* }
*
* // styled-components usage
* const div = styled.div`
* background: ${hsl(359, 0.75, 0.4)};
* background: ${hsl({ hue: 360, saturation: 0.75, lightness: 0.4 })};
* `
*
* // CSS in JS Output
*
* element {
* background: "#b3191c";
* background: "#b3191c";
* }
*/
function hsl(value, saturation, lightness) {
if (typeof value === 'number' && typeof saturation === 'number' && typeof lightness === 'number') {
return hslToHex(value, saturation, lightness);
} else if (typeof value === 'object' && saturation === undefined && lightness === undefined) {
return hslToHex(value.hue, value.saturation, value.lightness);
}
throw new Error('Passed invalid arguments to hsl, please pass multiple numbers e.g. hsl(360, 0.75, 0.4) or an object e.g. rgb({ hue: 255, saturation: 0.4, lightness: 0.75 }).');
}
/**
* Returns a string value for the color. The returned result is the smallest possible rgba or hex notation.
*
* @example
* // Styles as object usage
* const styles = {
* background: hsla(359, 0.75, 0.4, 0.7),
* background: hsla({ hue: 360, saturation: 0.75, lightness: 0.4, alpha: 0,7 }),
* background: hsla(359, 0.75, 0.4, 1),
* }
*
* // styled-components usage
* const div = styled.div`
* background: ${hsla(359, 0.75, 0.4, 0.7)};
* background: ${hsla({ hue: 360, saturation: 0.75, lightness: 0.4, alpha: 0,7 })};
* background: ${hsla(359, 0.75, 0.4, 1)};
* `
*
* // CSS in JS Output
*
* element {
* background: "rgba(179,25,28,0.7)";
* background: "rgba(179,25,28,0.7)";
* background: "#b3191c";
* }
*/
function hsla(value, saturation, lightness, alpha) {
if (typeof value === 'number' && typeof saturation === 'number' && typeof lightness === 'number' && typeof alpha === 'number') {
return alpha >= 1 ? hslToHex(value, saturation, lightness) : "rgba(" + hslToRgb(value, saturation, lightness) + "," + alpha + ")";
} else if (typeof value === 'object' && saturation === undefined && lightness === undefined && alpha === undefined) {
return value.alpha >= 1 ? hslToHex(value.hue, value.saturation, value.lightness) : "rgba(" + hslToRgb(value.hue, value.saturation, value.lightness) + "," + value.alpha + ")";
}
throw new Error('Passed invalid arguments to hsla, please pass multiple numbers e.g. hsl(360, 0.75, 0.4, 0.7) or an object e.g. rgb({ hue: 255, saturation: 0.4, lightness: 0.75, alpha: 0.7 }).');
}
/**
* Returns a string value for the color. The returned result is the smallest possible hex notation.
*
* @example
* // Styles as object usage
* const styles = {
* background: rgb(255, 205, 100),
* background: rgb({ red: 255, green: 205, blue: 100 }),
* }
*
* // styled-components usage
* const div = styled.div`
* background: ${rgb(255, 205, 100)};
* background: ${rgb({ red: 255, green: 205, blue: 100 })};
* `
*
* // CSS in JS Output
*
* element {
* background: "#ffcd64";
* background: "#ffcd64";
* }
*/
function rgb(value, green, blue) {
if (typeof value === 'number' && typeof green === 'number' && typeof blue === 'number') {
return reduceHexValue("#" + numberToHex(value) + numberToHex(green) + numberToHex(blue));
} else if (typeof value === 'object' && green === undefined && blue === undefined) {
return reduceHexValue("#" + numberToHex(value.red) + numberToHex(value.green) + numberToHex(value.blue));
}
throw new Error('Passed invalid arguments to rgb, please pass multiple numbers e.g. rgb(255, 205, 100) or an object e.g. rgb({ red: 255, green: 205, blue: 100 }).');
}
/**
* Returns a string value for the color. The returned result is the smallest possible rgba or hex notation.
*
* Can also be used to fade a color by passing a hex value or named CSS color along with an alpha value.
*
* @example
* // Styles as object usage
* const styles = {
* background: rgba(255, 205, 100, 0.7),
* background: rgba({ red: 255, green: 205, blue: 100, alpha: 0.7 }),
* background: rgba(255, 205, 100, 1),
* background: rgba('#ffffff', 0.4),
* background: rgba('black', 0.7),
* }
*
* // styled-components usage
* const div = styled.div`
* background: ${rgba(255, 205, 100, 0.7)};
* background: ${rgba({ red: 255, green: 205, blue: 100, alpha: 0.7 })};
* background: ${rgba(255, 205, 100, 1)};
* background: ${rgba('#ffffff', 0.4)};
* background: ${rgba('black', 0.7)};
* `
*
* // CSS in JS Output
*
* element {
* background: "rgba(255,205,100,0.7)";
* background: "rgba(255,205,100,0.7)";
* background: "#ffcd64";
* background: "rgba(255,255,255,0.4)";
* background: "rgba(0,0,0,0.7)";
* }
*/
function rgba(firstValue, secondValue, thirdValue, fourthValue) {
if (typeof firstValue === 'string' && typeof secondValue === 'number') {
var rgbValue = parseToRgb(firstValue);
return "rgba(" + rgbValue.red + "," + rgbValue.green + "," + rgbValue.blue + "," + secondValue + ")";
} else if (typeof firstValue === 'number' && typeof secondValue === 'number' && typeof thirdValue === 'number' && typeof fourthValue === 'number') {
return fourthValue >= 1 ? rgb(firstValue, secondValue, thirdValue) : "rgba(" + firstValue + "," + secondValue + "," + thirdValue + "," + fourthValue + ")";
} else if (typeof firstValue === 'object' && secondValue === undefined && thirdValue === undefined && fourthValue === undefined) {
return firstValue.alpha >= 1 ? rgb(firstValue.red, firstValue.green, firstValue.blue) : "rgba(" + firstValue.red + "," + firstValue.green + "," + firstValue.blue + "," + firstValue.alpha + ")";
}
throw new Error('Passed invalid arguments to rgba, please pass multiple numbers e.g. rgb(255, 205, 100, 0.75) or an object e.g. rgb({ red: 255, green: 205, blue: 100, alpha: 0.75 }).');
}
var isRgb = function isRgb(color) {
return typeof color.red === 'number' && typeof color.green === 'number' && typeof color.blue === 'number' && (typeof color.alpha !== 'number' || typeof color.alpha === 'undefined');
};
var isRgba = function isRgba(color) {
return typeof color.red === 'number' && typeof color.green === 'number' && typeof color.blue === 'number' && typeof color.alpha === 'number';
};
var isHsl = function isHsl(color) {
return typeof color.hue === 'number' && typeof color.saturation === 'number' && typeof color.lightness === 'number' && (typeof color.alpha !== 'number' || typeof color.alpha === 'undefined');
};
var isHsla = function isHsla(color) {
return typeof color.hue === 'number' && typeof color.saturation === 'number' && typeof color.lightness === 'number' && typeof color.alpha === 'number';
};
var errMsg = 'Passed invalid argument to toColorString, please pass a RgbColor, RgbaColor, HslColor or HslaColor object.';
/**
* Converts a RgbColor, RgbaColor, HslColor or HslaColor object to a color string.
* This util is useful in case you only know on runtime which color object is
* used. Otherwise we recommend to rely on `rgb`, `rgba`, `hsl` or `hsla`.
*
* @example
* // Styles as object usage
* const styles = {
* background: toColorString({ red: 255, green: 205, blue: 100 }),
* background: toColorString({ red: 255, green: 205, blue: 100, alpha: 0.72 }),
* background: toColorString({ hue: 240, saturation: 1, lightness: 0.5 }),
* background: toColorString({ hue: 360, saturation: 0.75, lightness: 0.4, alpha: 0.72 }),
* }
*
* // styled-components usage
* const div = styled.div`
* background: ${toColorString({ red: 255, green: 205, blue: 100 })};
* background: ${toColorString({ red: 255, green: 205, blue: 100, alpha: 0.72 })};
* background: ${toColorString({ hue: 240, saturation: 1, lightness: 0.5 })};
* background: ${toColorString({ hue: 360, saturation: 0.75, lightness: 0.4, alpha: 0.72 })};
* `
*
* // CSS in JS Output
* element {
* background: "#ffcd64";
* background: "rgba(255,205,100,0.72)";
* background: "#00f";
* background: "rgba(179,25,25,0.72)";
* }
*/
function toColorString(color) {
if (typeof color !== 'object') throw new Error(errMsg);
if (isRgba(color)) return rgba(color);
if (isRgb(color)) return rgb(color);
if (isHsla(color)) return hsla(color);
if (isHsl(color)) return hsl(color);
throw new Error(errMsg);
}
// Type definitions taken from https://github.com/gcanti/flow-static-land/blob/master/src/Fun.js
// eslint-disable-next-line no-unused-vars
// eslint-disable-next-line no-unused-vars
// eslint-disable-next-line no-redeclare
function curried(f, length, acc) {
return function fn() {
// eslint-disable-next-line prefer-rest-params
var combined = acc.concat(Array.prototype.slice.call(arguments));
return combined.length >= length ? f.apply(this, combined) : curried(f, length, combined);
};
} // eslint-disable-next-line no-redeclare
function curry(f) {
// eslint-disable-line no-redeclare
return curried(f, f.length, []);
}
/**
* Changes the hue of the color. Hue is a number between 0 to 360. The first
* argument for adjustHue is the amount of degrees the color is rotated along
* the color wheel.
*
* @example
* // Styles as object usage
* const styles = {
* background: adjustHue(180, '#448'),
* background: adjustHue('180', 'rgba(101,100,205,0.7)'),
* }
*
* // styled-components usage
* const div = styled.div`
* background: ${adjustHue(180, '#448')};
* background: ${adjustHue('180', 'rgba(101,100,205,0.7)')};
* `
*
* // CSS in JS Output
* element {
* background: "#888844";
* background: "rgba(136,136,68,0.7)";
* }
*/
function adjustHue(degree, color) {
var hslColor = parseToHsl(color);
return toColorString(_extends({}, hslColor, {
hue: (hslColor.hue + parseFloat(degree)) % 360
}));
} // prettier-ignore
var curriedAdjustHue =
/*#__PURE__*/
curry
/* ::<number | string, string, string> */
(adjustHue);
/**
* Returns the complement of the provided color. This is identical to adjustHue(180, <color>).
*
* @example
* // Styles as object usage
* const styles = {
* background: complement('#448'),
* background: complement('rgba(204,205,100,0.7)'),
* }
*
* // styled-components usage
* const div = styled.div`
* background: ${complement('#448')};
* background: ${complement('rgba(204,205,100,0.7)')};
* `
*
* // CSS in JS Output
* element {
* background: "#884";
* background: "rgba(153,153,153,0.7)";
* }
*/
function complement(color) {
var hslColor = parseToHsl(color);
return toColorString(_extends({}, hslColor, {
hue: (hslColor.hue + 180) % 360
}));
}
function guard(lowerBoundary, upperBoundary, value) {
return Math.max(lowerBoundary, Math.min(upperBoundary, value));
}
/**
* Returns a string value for the darkened color.
*
* @example
* // Styles as object usage
* const styles = {
* background: darken(0.2, '#FFCD64'),
* background: darken('0.2', 'rgba(255,205,100,0.7)'),
* }
*
* // styled-components usage
* const div = styled.div`
* background: ${darken(0.2, '#FFCD64')};
* background: ${darken('0.2', 'rgba(255,205,100,0.7)')};
* `
*
* // CSS in JS Output
*
* element {
* background: "#ffbd31";
* background: "rgba(255,189,49,0.7)";
* }
*/
function darken(amount, color) {
var hslColor = parseToHsl(color);
return toColorString(_extends({}, hslColor, {
lightness: guard(0, 1, hslColor.lightness - parseFloat(amount))
}));
} // prettier-ignore
var curriedDarken =
/*#__PURE__*/
curry
/* ::<number | string, string, string> */
(darken);
/**
* Decreases the intensity of a color. Its range is between 0 to 1. The first
* argument of the desaturate function is the amount by how much the color
* intensity should be decreased.
*
* @example
* // Styles as object usage
* const styles = {
* background: desaturate(0.2, '#CCCD64'),
* background: desaturate('0.2', 'rgba(204,205,100,0.7)'),
* }
*
* // styled-components usage
* const div = styled.div`
* background: ${desaturate(0.2, '#CCCD64')};
* background: ${desaturate('0.2', 'rgba(204,205,100,0.7)')};
* `
*
* // CSS in JS Output
* element {
* background: "#b8b979";
* background: "rgba(184,185,121,0.7)";
* }
*/
function desaturate(amount, color) {
var hslColor = parseToHsl(color);
return toColorString(_extends({}, hslColor, {
saturation: guard(0, 1, hslColor.saturation - parseFloat(amount))
}));
} // prettier-ignore
var curriedDesaturate =
/*#__PURE__*/
curry
/* ::<number | string, string, string> */
(desaturate);
/**
* Returns a number (float) representing the luminance of a color.
*
* @example
* // Styles as object usage
* const styles = {
* background: getLuminance('#CCCD64') >= getLuminance('#0000ff') ? '#CCCD64' : '#0000ff',
* background: getLuminance('rgba(58, 133, 255, 1)') >= getLuminance('rgba(255, 57, 149, 1)') ?
* 'rgba(58, 133, 255, 1)' :
* 'rgba(255, 57, 149, 1)',
* }
*
* // styled-components usage
* const div = styled.div`
* background: ${getLuminance('#CCCD64') >= getLuminance('#0000ff') ? '#CCCD64' : '#0000ff'};
* background: ${getLuminance('rgba(58, 133, 255, 1)') >= getLuminance('rgba(255, 57, 149, 1)') ?
* 'rgba(58, 133, 255, 1)' :
* 'rgba(255, 57, 149, 1)'};
*
* // CSS in JS Output
*
* div {
* background: "#CCCD64";
* background: "rgba(58, 133, 255, 1)";
* }
*/
function getLuminance(color) {
var rgbColor = parseToRgb(color);
var _Object$keys$map = Object.keys(rgbColor).map(function (key) {
var channel = rgbColor[key] / 255;
return channel <= 0.03928 ? channel / 12.92 : Math.pow((channel + 0.055) / 1.055, 2.4);
}),
r = _Object$keys$map[0],
g = _Object$keys$map[1],
b = _Object$keys$map[2];
return parseFloat((0.2126 * r + 0.7152 * g + 0.0722 * b).toFixed(3));
}
/**
* Converts the color to a grayscale, by reducing its saturation to 0.
*
* @example
* // Styles as object usage
* const styles = {
* background: grayscale('#CCCD64'),
* background: grayscale('rgba(204,205,100,0.7)'),
* }
*
* // styled-components usage
* const div = styled.div`
* background: ${grayscale('#CCCD64')};
* background: ${grayscale('rgba(204,205,100,0.7)')};
* `
*
* // CSS in JS Output
* element {
* background: "#999";
* background: "rgba(153,153,153,0.7)";
* }
*/
function grayscale(color) {
return toColorString(_extends({}, parseToHsl(color), {
saturation: 0
}));
}
/**
* Inverts the red, green and blue values of a color.
*
* @example
* // Styles as object usage
* const styles = {
* background: invert('#CCCD64'),
* background: invert('rgba(101,100,205,0.7)'),
* }
*
* // styled-components usage
* const div = styled.div`
* background: ${invert('#CCCD64')};
* background: ${invert('rgba(101,100,205,0.7)')};
* `
*
* // CSS in JS Output
*
* element {
* background: "#33329b";
* background: "rgba(154,155,50,0.7)";
* }
*/
function invert(color) {
// parse color string to rgb
var value = parseToRgb(color);
return toColorString(_extends({}, value, {
red: 255 - value.red,
green: 255 - value.green,
blue: 255 - value.blue
}));
}
/**
* Returns a string value for the lightened color.
*
* @example
* // Styles as object usage
* const styles = {
* background: lighten(0.2, '#CCCD64'),
* background: lighten('0.2', 'rgba(204,205,100,0.7)'),
* }
*
* // styled-components usage
* const div = styled.div`
* background: ${lighten(0.2, '#FFCD64')};
* background: ${lighten('0.2', 'rgba(204,205,100,0.7)')};
* `
*
* // CSS in JS Output
*
* element {
* background: "#e5e6b1";
* background: "rgba(229,230,177,0.7)";
* }
*/
function lighten(amount, color) {
var hslColor = parseToHsl(color);
return toColorString(_extends({}, hslColor, {
lightness: guard(0, 1, hslColor.lightness + parseFloat(amount))
}));
} // prettier-ignore
var curriedLighten =
/*#__PURE__*/
curry
/* ::<number | string, string, string> */
(lighten);
/**
* Mixes the two provided colors together by calculating the average of each of the RGB components weighted to the first color by the provided weight.
*
* @example
* // Styles as object usage
* const styles = {
* background: mix(0.5, '#f00', '#00f')
* background: mix(0.25, '#f00', '#00f')
* background: mix('0.5', 'rgba(255, 0, 0, 0.5)', '#00f')
* }
*
* // styled-components usage
* const div = styled.div`
* background: ${mix(0.5, '#f00', '#00f')};
* background: ${mix(0.25, '#f00', '#00f')};
* background: ${mix('0.5', 'rgba(255, 0, 0, 0.5)', '#00f')};
* `
*
* // CSS in JS Output
*
* element {
* background: "#7f007f";
* background: "#3f00bf";
* background: "rgba(63, 0, 191, 0.75)";
* }
*/
function mix(weight, color, otherColor) {
var parsedColor1 = parseToRgb(color);
var color1 = _extends({}, parsedColor1, {
alpha: typeof parsedColor1.alpha === 'number' ? parsedColor1.alpha : 1
});
var parsedColor2 = parseToRgb(otherColor);
var color2 = _extends({}, parsedColor2, {
alpha: typeof parsedColor2.alpha === 'number' ? parsedColor2.alpha : 1 // The formular is copied from the original Sass implementation:
// http://sass-lang.com/documentation/Sass/Script/Functions.html#mix-instance_method
});
var alphaDelta = color1.alpha - color2.alpha;
var x = parseFloat(weight) * 2 - 1;
var y = x * alphaDelta === -1 ? x : x + alphaDelta;
var z = 1 + x * alphaDelta;
var weight1 = (y / z + 1) / 2.0;
var weight2 = 1 - weight1;
var mixedColor = {
red: Math.floor(color1.red * weight1 + color2.red * weight2),
green: Math.floor(color1.green * weight1 + color2.green * weight2),
blue: Math.floor(color1.blue * weight1 + color2.blue * weight2),
alpha: color1.alpha + (color2.alpha - color1.alpha) * (parseFloat(weight) / 1.0)
};
return rgba(mixedColor);
} // prettier-ignore
var curriedMix =
/*#__PURE__*/
curry
/* ::<number | string, string, string, string> */
(mix);
/**
* Increases the opacity of a color. Its range for the amount is between 0 to 1.
*
*
* @example
* // Styles as object usage
* const styles = {
* background: opacify(0.1, 'rgba(255, 255, 255, 0.9)');
* background: opacify(0.2, 'hsla(0, 0%, 100%, 0.5)'),
* background: opacify('0.5', 'rgba(255, 0, 0, 0.2)'),
* }
*
* // styled-components usage
* const div = styled.div`
* background: ${opacify(0.1, 'rgba(255, 255, 255, 0.9)')};
* background: ${opacify(0.2, 'hsla(0, 0%, 100%, 0.5)')},
* background: ${opacify('0.5', 'rgba(255, 0, 0, 0.2)')},
* `
*
* // CSS in JS Output
*
* element {
* background: "#fff";
* background: "rgba(255,255,255,0.7)";
* background: "rgba(255,0,0,0.7)";
* }
*/
function opacify(amount, color) {
var parsedColor = parseToRgb(color);
var alpha = typeof parsedColor.alpha === 'number' ? parsedColor.alpha : 1;
var colorWithAlpha = _extends({}, parsedColor, {
alpha: guard(0, 1, (alpha * 100 + parseFloat(amount) * 100) / 100)
});
return rgba(colorWithAlpha);
} // prettier-ignore
var curriedOpacify =
/*#__PURE__*/
curry
/* ::<number | string, string, string> */
(opacify);
/**
* Returns black or white for best contrast depending on the luminosity of the given color.
* Follows W3C specs for readability at https://www.w3.org/TR/WCAG20-TECHS/G18.html
*
* @example
* // Styles as object usage
* const styles = {
* color: readableColor('#000'),
* color: readableColor('papayawhip'),
* color: readableColor('rgb(255,0,0)'),
* }
*
* // styled-components usage
* const div = styled.div`
* color: ${readableColor('#000')};
* color: ${readableColor('papayawhip')};
* color: ${readableColor('rgb(255,0,0)')};
* `
*
* // CSS in JS Output
*
* element {
* color: "#fff";
* color: "#fff";
* color: "#000";
* }
*/
function readableColor(color) {
return getLuminance(color) > 0.179 ? '#000' : '#fff';
}
/**
* Increases the intensity of a color. Its range is between 0 to 1. The first
* argument of the saturate function is the amount by how much the color
* intensity should be increased.
*
* @example
* // Styles as object usage
* const styles = {
* background: saturate(0.2, '#CCCD64'),
* background: saturate('0.2', 'rgba(204,205,100,0.7)'),
* }
*
* // styled-components usage
* const div = styled.div`
* background: ${saturate(0.2, '#FFCD64')};
* background: ${saturate('0.2', 'rgba(204,205,100,0.7)')};
* `
*
* // CSS in JS Output
*
* element {
* background: "#e0e250";
* background: "rgba(224,226,80,0.7)";
* }
*/
function saturate(amount, color) {
var hslColor = parseToHsl(color);
return toColorString(_extends({}, hslColor, {
saturation: guard(0, 1, hslColor.saturation + parseFloat(amount))
}));
} // prettier-ignore
var curriedSaturate =
/*#__PURE__*/
curry
/* ::<number | string, string, string> */
(saturate);
/**
* Sets the hue of a color to the provided value. The hue range can be
* from 0 and 359.
*
* @example
* // Styles as object usage
* const styles = {
* background: setHue(42, '#CCCD64'),
* background: setHue('244', 'rgba(204,205,100,0.7)'),
* }
*
* // styled-components usage
* const div = styled.div`
* background: ${setHue(42, '#CCCD64')};
* background: ${setHue('244', 'rgba(204,205,100,0.7)')};
* `
*
* // CSS in JS Output
* element {
* background: "#cdae64";
* background: "rgba(107,100,205,0.7)";
* }
*/
function setHue(hue, color) {
return toColorString(_extends({}, parseToHsl(color), {
hue: parseFloat(hue)
}));
} // prettier-ignore
var curriedSetHue =
/*#__PURE__*/
curry
/* ::<number | string, string, string> */
(setHue);
/**
* Sets the lightness of a color to the provided value. The lightness range can be
* from 0 and 1.
*
* @example
* // Styles as object usage
* const styles = {
* background: setLightness(0.2, '#CCCD64'),
* background: setLightness('0.75', 'rgba(204,205,100,0.7)'),
* }
*
* // styled-components usage
* const div = styled.div`
* background: ${setLightness(0.2, '#CCCD64')};
* background: ${setLightness('0.75', 'rgba(204,205,100,0.7)')};
* `
*
* // CSS in JS Output
* element {
* background: "#4d4d19";
* background: "rgba(223,224,159,0.7)";
* }
*/
function setLightness(lightness, color) {
return toColorString(_extends({}, parseToHsl(color), {
lightness: parseFloat(lightness)
}));
} // prettier-ignore
var curriedSetLightness =
/*#__PURE__*/
curry
/* ::<number | string, string, string> */
(setLightness);
/**
* Sets the saturation of a color to the provided value. The lightness range can be
* from 0 and 1.
*
* @example
* // Styles as object usage
* const styles = {
* background: setSaturation(0.2, '#CCCD64'),
* background: setSaturation('0.75', 'rgba(204,205,100,0.7)'),
* }
*
* // styled-components usage
* const div = styled.div`
* background: ${setSaturation(0.2, '#CCCD64')};
* background: ${setSaturation('0.75', 'rgba(204,205,100,0.7)')};
* `
*
* // CSS in JS Output
* element {
* background: "#adad84";
* background: "rgba(228,229,76,0.7)";
* }
*/
function setSaturation(saturation, color) {
return toColorString(_extends({}, parseToHsl(color), {
saturation: parseFloat(saturation)
}));
} // prettier-ignore
var curriedSetSaturation =
/*#__PURE__*/
curry
/* ::<number | string, string, string> */
(setSaturation);
/**
* Shades a color by mixing it with black. `shade` can produce
* hue shifts, where as `darken` manipulates the luminance channel and therefore
* doesn't produce hue shifts.
*
* @example
* // Styles as object usage
* const styles = {
* background: shade(0.25, '#00f')
* }
*
* // styled-components usage
* const div = styled.div`
* background: ${shade(0.25, '#00f')};
* `
*
* // CSS in JS Output
*
* element {
* background: "#00003f";
* }
*/
function shade(percentage, color) {
return curriedMix(parseFloat(percentage), 'rgb(0, 0, 0)', color);
} // prettier-ignore
var curriedShade =
/*#__PURE__*/
curry
/* ::<number | string, string, string> */
(shade);
/**
* Tints a color by mixing it with white. `tint` can produce
* hue shifts, where as `lighten` manipulates the luminance channel and therefore
* doesn't produce hue shifts.
*
* @example
* // Styles as object usage
* const styles = {
* background: tint(0.25, '#00f')
* }
*
* // styled-components usage
* const div = styled.div`
* background: ${tint(0.25, '#00f')};
* `
*
* // CSS in JS Output
*
* element {
* background: "#bfbfff";
* }
*/
function tint(percentage, color) {
return curriedMix(parseFloat(percentage), 'rgb(255, 255, 255)', color);
} // prettier-ignore
var curriedTint =
/*#__PURE__*/
curry
/* ::<number | string, string, string> */
(tint);
/**
* Decreases the opacity of a color. Its range for the amount is between 0 to 1.
*
*
* @example
* // Styles as object usage
* const styles = {
* background: transparentize(0.1, '#fff');
* background: transparentize(0.2, 'hsl(0, 0%, 100%)'),
* background: transparentize('0.5', 'rgba(255, 0, 0, 0.8)'),
* }
*
* // styled-components usage
* const div = styled.div`
* background: ${transparentize(0.1, '#fff')};
* background: ${transparentize(0.2, 'hsl(0, 0%, 100%)')},
* background: ${transparentize('0.5', 'rgba(255, 0, 0, 0.8)')},
* `
*
* // CSS in JS Output
*
* element {
* background: "rgba(255,255,255,0.9)";
* background: "rgba(255,255,255,0.8)";
* background: "rgba(255,0,0,0.3)";
* }
*/
function transparentize(amount, color) {
var parsedColor = parseToRgb(color);
var alpha = typeof parsedColor.alpha === 'number' ? parsedColor.alpha : 1;
var colorWithAlpha = _extends({}, parsedColor, {
alpha: guard(0, 1, (alpha * 100 - parseFloat(amount) * 100) / 100)
});
return rgba(colorWithAlpha);
} // prettier-ignore
var curriedTransparentize =
/*#__PURE__*/
curry
/* ::<number | string, string, string> */
(transparentize);
/**
* Shorthand for easily setting the animation property. Allows either multiple arrays with animations
* or a single animation spread over the arguments.
* @example
* // Styles as object usage
* const styles = {
* ...animation(['rotate', '1s', 'ease-in-out'], ['colorchange', '2s'])
* }
*
* // styled-components usage
* const div = styled.div`
* ${animation(['rotate', '1s', 'ease-in-out'], ['colorchange', '2s'])}
* `
*
* // CSS as JS Output
*
* div {
* 'animation': 'rotate 1s ease-in-out, colorchange 2s'
* }
* @example
* // Styles as object usage
* const styles = {
* ...animation('rotate', '1s', 'ease-in-out')
* }
*
* // styled-components usage
* const div = styled.div`
* ${animation('rotate', '1s', 'ease-in-out')}
* `
*
* // CSS as JS Output
*
* div {
* 'animation': 'rotate 1s ease-in-out'
* }
*/
function animation() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
// Allow single or multiple animations passed
var multiMode = Array.isArray(args[0]);
if (!multiMode && args.length > 8) {
throw new Error('The animation shorthand only takes 8 arguments. See the specification for more information: http://mdn.io/animation');
}
var code = args.map(function (arg) {
if (multiMode && !Array.isArray(arg) || !multiMode && Array.isArray(arg)) {
throw new Error("To pass multiple animations please supply them in arrays, e.g. animation(['rotate', '2s'], ['move', '1s'])\nTo pass a single animation please supply them in simple values, e.g. animation('rotate', '2s')");
}
if (Array.isArray(arg) && arg.length > 8) {
throw new Error('The animation shorthand arrays can only have 8 elements. See the specification for more information: http://mdn.io/animation');
}
return Array.isArray(arg) ? arg.join(' ') : arg;
}).join(', ');
return {
animation: code
};
}
/**
* Shorthand that accepts any number of backgroundImage values as parameters for creating a single background statement.
* @example
* // Styles as object usage
* const styles = {
* ...backgroundImages('url("/image/background.jpg")', 'linear-gradient(red, green)')
* }
*
* // styled-components usage
* const div = styled.div`
* ${backgroundImages('url("/image/background.jpg")', 'linear-gradient(red, green)')}
* `
*
* // CSS as JS Output
*
* div {
* 'backgroundImage': 'url("/image/background.jpg"), linear-gradient(red, green)'
* }
*/
function backgroundImages() {
for (var _len = arguments.length, properties = new Array(_len), _key = 0; _key < _len; _key++) {
properties[_key] = arguments[_key];
}
return {
backgroundImage: properties.join(', ')
};
}
/**
* Shorthand that accepts any number of background values as parameters for creating a single background statement.
* @example
* // Styles as object usage
* const styles = {
* ...backgrounds('url("/image/background.jpg")', 'linear-gradient(red, green)', 'center no-repeat')
* }
*
* // styled-components usage
* const div = styled.div`
* ${backgrounds('url("/image/background.jpg")', 'linear-gradient(red, green)', 'center no-repeat')}
* `
*
* // CSS as JS Output
*
* div {
* 'background': 'url("/image/background.jpg"), linear-gradient(red, green), center no-repeat'
* }
*/
function backgrounds() {
for (var _len = arguments.length, properties = new Array(_len), _key = 0; _key < _len; _key++) {
properties[_key] = arguments[_key];
}
return {
background: properties.join(', ')
};
}
var sideMap = ['top', 'right', 'bottom', 'left'];
/**
* Shorthand for the border property that splits out individual properties for use with tools like Fela and Styletron. A side keyword can optionally be passed to target only one side's border properties.
*
* @example
* // Styles as object usage
* const styles = {
* ...border('1px', 'solid', 'red')
* }
*
* // styled-components usage
* const div = styled.div`
* ${border('1px', 'solid', 'red')}
* `
*
* // CSS as JS Output
*
* div {
* 'borderColor': 'red',
* 'borderStyle': 'solid',
* 'borderWidth': `1px`,
* }
*
* // Styles as object usage
* const styles = {
* ...border('top', '1px', 'solid', 'red')
* }
*
* // styled-components usage
* const div = styled.div`
* ${border('top', '1px', 'solid', 'red')}
* `
*
* // CSS as JS Output
*
* div {
* 'borderTopColor': 'red',
* 'borderTopStyle': 'solid',
* 'borderTopWidth': `1px`,
* }
*/
function border(sideKeyword) {
for (var _len = arguments.length, values = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
values[_key - 1] = arguments[_key];
}
if (typeof sideKeyword === 'string' && sideMap.indexOf(sideKeyword) >= 0) {
var _ref;
return _ref = {}, _ref["border" + capitalizeString(sideKeyword) + "Width"] = values[0], _ref["border" + capitalizeString(sideKeyword) + "Style"] = values[1], _ref["border" + capitalizeString(sideKeyword) + "Color"] = values[2], _ref;
} else {
values.unshift(sideKeyword);
return {
borderWidth: values[0],
borderStyle: values[1],
borderColor: values[2]
};
}
}
/**
* Shorthand that accepts a value for side and a value for radius and applies the radius value to both corners of the side.
* @example
* // Styles as object usage
* const styles = {
* ...borderRadius('top', '5px')
* }
*
* // styled-components usage
* const div = styled.div`
* ${borderRadius('top', '5px')}
* `
*
* // CSS as JS Output
*
* div {
* 'borderTopRightRadius': '5px',
* 'borderTopLeftRadius': '5px',
* }
*/
function borderRadius(side, radius) {
var uppercaseSide = capitalizeString(side);
if (!radius && radius !== 0) {
throw new Error('borderRadius expects a radius value as a string or number as the second argument.');
}
if (uppercaseSide === 'Top' || uppercaseSide === 'Bottom') {
var _ref;
return _ref = {}, _ref["border" + uppercaseSide + "RightRadius"] = radius, _ref["border" + uppercaseSide + "LeftRadius"] = radius, _ref;
}
if (uppercaseSide === 'Left' || uppercaseSide === 'Right') {
var _ref2;
return _ref2 = {}, _ref2["borderTop" + uppercaseSide + "Radius"] = radius, _ref2["borderBottom" + uppercaseSide + "Radius"] = radius, _ref2;
}
throw new Error('borderRadius expects one of "top", "bottom", "left" or "right" as the first argument.');
}
/**
* Shorthand that accepts up to four values, including null to skip a value, and maps them to their respective directions.
* @example
* // Styles as object usage
* const styles = {
* ...borderStyle('solid', 'dashed', 'dotted', 'double')
* }
*
* // styled-components usage
* const div = styled.div`
* ${borderStyle('solid', 'dashed', 'dotted', 'double')}
* `
*
* // CSS as JS Output
*
* div {
* 'borderTopStyle': 'solid',
* 'borderRightStyle': 'dashed',
* 'borderBottomStyle': 'dotted',
* 'borderLeftStyle': 'double'
* }
*/
function borderStyle() {
for (var _len = arguments.length, values = new Array(_len), _key = 0; _key < _len; _key++) {
values[_key] = arguments[_key];
}
return directionalProperty.apply(void 0, ['borderStyle'].concat(values));
}
/**
* Shorthand that accepts up to four values, including null to skip a value, and maps them to their respective directions.
* @example
* // Styles as object usage
* const styles = {
* ...borderWidth('12px', '24px', '36px', '48px')
* }
*
* // styled-components usage
* const div = styled.div`
* ${borderWidth('12px', '24px', '36px', '48px')}
* `
*
* // CSS as JS Output
*
* div {
* 'borderTopWidth': '12px',
* 'borderRightWidth': '24px',
* 'borderBottomWidth': '36px',
* 'borderLeftWidth': '48px'
* }
*/
function borderWidth() {
for (var _len = arguments.length, values = new Array(_len), _key = 0; _key < _len; _key++) {
values[_key] = arguments[_key];
}
return directionalProperty.apply(void 0, ['borderWidth'].concat(values));
}
function generateSelectors(template, state) {
var stateSuffix = state ? ":" + state : '';
return template(stateSuffix);
}
/**
* Function helper that adds an array of states to a template of selectors. Used in textInputs and buttons.
* @private
*/
function statefulSelectors(states, template, stateMap) {
if (!template) throw new Error('You must provide a template to this method.');
if (states.length === 0) return generateSelectors(template, null);
var selectors = [];
for (var i = 0; i < states.length; i += 1) {
if (stateMap && stateMap.indexOf(states[i]) < 0) {
throw new Error('You passed an unsupported selector state to this method.');
}
selectors.push(generateSelectors(template, states[i]));
}
selectors = selectors.join(',');
return selectors;
}
var stateMap = [undefined, null, 'active', 'focus', 'hover'];
function template(state) {
return "button" + state + ",\n input[type=\"button\"]" + state + ",\n input[type=\"reset\"]" + state + ",\n input[type=\"submit\"]" + state;
}
/**
* Populates selectors that target all buttons. You can pass optional states to append to the selectors.
* @example
* // Styles as object usage
* const styles = {
* [buttons('active')]: {
* 'border': 'none'
* }
* }
*
* // styled-components usage
* const div = styled.div`
* > ${buttons('active')} {
* border: none;
* }
* `
*
* // CSS in JS Output
*
* 'button:active,
* 'input[type="button"]:active,
* 'input[type=\"reset\"]:active,
* 'input[type=\"submit\"]:active: {
* 'border': 'none'
* }
*/
function buttons() {
for (var _len = arguments.length, states = new Array(_len), _key = 0; _key < _len; _key++) {
states[_key] = arguments[_key];
}
return statefulSelectors(states, template, stateMap);
}
/**
* Shorthand that accepts up to four values, including null to skip a value, and maps them to their respective directions.
* @example
* // Styles as object usage
* const styles = {
* ...margin('12px', '24px', '36px', '48px')
* }
*
* // styled-components usage
* const div = styled.div`
* ${margin('12px', '24px', '36px', '48px')}
* `
*
* // CSS as JS Output
*
* div {
* 'marginTop': '12px',
* 'marginRight': '24px',
* 'marginBottom': '36px',
* 'marginLeft': '48px'
* }
*/
function margin() {
for (var _len = arguments.length, values = new Array(_len), _key = 0; _key < _len; _key++) {
values[_key] = arguments[_key];
}
return directionalProperty.apply(void 0, ['margin'].concat(values));
}
/**
* Shorthand that accepts up to four values, including null to skip a value, and maps them to their respective directions.
* @example
* // Styles as object usage
* const styles = {
* ...padding('12px', '24px', '36px', '48px')
* }
*
* // styled-components usage
* const div = styled.div`
* ${padding('12px', '24px', '36px', '48px')}
* `
*
* // CSS as JS Output
*
* div {
* 'paddingTop': '12px',
* 'paddingRight': '24px',
* 'paddingBottom': '36px',
* 'paddingLeft': '48px'
* }
*/
function padding() {
for (var _len = arguments.length, values = new Array(_len), _key = 0; _key < _len; _key++) {
values[_key] = arguments[_key];
}
return directionalProperty.apply(void 0, ['padding'].concat(values));
}
var positionMap$1 = ['absolute', 'fixed', 'relative', 'static', 'sticky'];
/**
* Shorthand accepts up to five values, including null to skip a value, and maps them to their respective directions. The first value can optionally be a position keyword.
* @example
* // Styles as object usage
* const styles = {
* ...position('12px', '24px', '36px', '48px')
* }
*
* // styled-components usage
* const div = styled.div`
* ${position('12px', '24px', '36px', '48px')}
* `
*
* // CSS as JS Output
*
* div {
* 'top': '12px',
* 'right': '24px',
* 'bottom': '36px',
* 'left': '48px'
* }
*
* // Styles as object usage
* const styles = {
* ...position('absolute', '12px', '24px', '36px', '48px')
* }
*
* // styled-components usage
* const div = styled.div`
* ${position('absolute', '12px', '24px', '36px', '48px')}
* `
*
* // CSS as JS Output
*
* div {
* 'position': 'absolute',
* 'top': '12px',
* 'right': '24px',
* 'bottom': '36px',
* 'left': '48px'
* }
*/
function position(positionKeyword) {
for (var _len = arguments.length, values = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
values[_key - 1] = arguments[_key];
}
if (positionMap$1.indexOf(positionKeyword) >= 0) {
return _extends({
position: positionKeyword
}, directionalProperty.apply(void 0, [''].concat(values)));
} else {
var firstValue = positionKeyword; // in this case position is actually the first value
return directionalProperty.apply(void 0, ['', firstValue].concat(values));
}
}
/**
* Shorthand to set the height and width properties in a single statement.
* @example
* // Styles as object usage
* const styles = {
* ...size('300px', '250px')
* }
*
* // styled-components usage
* const div = styled.div`
* ${size('300px', '250px')}
* `
*
* // CSS as JS Output
*
* div {
* 'height': '300px',
* 'width': '250px',
* }
*/
function size(height, width) {
if (width === void 0) {
width = height;
}
return {
height: height,
width: width
};
}
var stateMap$1 = [undefined, null, 'active', 'focus', 'hover'];
function template$1(state) {
return "input[type=\"color\"]" + state + ",\n input[type=\"date\"]" + state + ",\n input[type=\"datetime\"]" + state + ",\n input[type=\"datetime-local\"]" + state + ",\n input[type=\"email\"]" + state + ",\n input[type=\"month\"]" + state + ",\n input[type=\"number\"]" + state + ",\n input[type=\"password\"]" + state + ",\n input[type=\"search\"]" + state + ",\n input[type=\"tel\"]" + state + ",\n input[type=\"text\"]" + state + ",\n input[type=\"time\"]" + state + ",\n input[type=\"url\"]" + state + ",\n input[type=\"week\"]" + state + ",\n input:not([type])" + state + ",\n textarea" + state;
}
/**
* Populates selectors that target all text inputs. You can pass optional states to append to the selectors.
* @example
* // Styles as object usage
* const styles = {
* [textInputs('active')]: {
* 'border': 'none'
* }
* }
*
* // styled-components usage
* const div = styled.div`
* > ${textInputs('active')} {
* border: none;
* }
* `
*
* // CSS in JS Output
*
* 'input[type="color"]:active,
* input[type="date"]:active,
* input[type="datetime"]:active,
* input[type="datetime-local"]:active,
* input[type="email"]:active,
* input[type="month"]:active,
* input[type="number"]:active,
* input[type="password"]:active,
* input[type="search"]:active,
* input[type="tel"]:active,
* input[type="text"]:active,
* input[type="time"]:active,
* input[type="url"]:active,
* input[type="week"]:active,
* input:not([type]):active,
* textarea:active': {
* 'border': 'none'
* }
*/
function textInputs() {
for (var _len = arguments.length, states = new Array(_len), _key = 0; _key < _len; _key++) {
states[_key] = arguments[_key];
}
return statefulSelectors(states, template$1, stateMap$1);
}
/**
* Accepts any number of transition values as parameters for creating a single transition statement. You may also pass an array of properties as the first parameter that you would like to apply the same tranisition values to (second parameter).
* @example
* // Styles as object usage
* const styles = {
* ...transitions('opacity 1.0s ease-in 0s', 'width 2.0s ease-in 2s'),
* ...transitions(['color', 'background-color'], '2.0s ease-in 2s')
* }
*
* // styled-components usage
* const div = styled.div`
* ${transitions('opacity 1.0s ease-in 0s', 'width 2.0s ease-in 2s')};
* ${transitions(['color', 'background-color'], '2.0s ease-in 2s'),};
* `
*
* // CSS as JS Output
*
* div {
* 'transition': 'opacity 1.0s ease-in 0s, width 2.0s ease-in 2s'
* 'transition': 'color 2.0s ease-in 2s, background-color 2.0s ease-in 2s',
* }
*/
function transitions() {
for (var _len = arguments.length, properties = new Array(_len), _key = 0; _key < _len; _key++) {
properties[_key] = arguments[_key];
}
if (Array.isArray(properties[0]) && properties.length === 2) {
var value = properties[1];
if (typeof value !== 'string') {
throw new Error('Property must be a string value.');
}
var transitionsString = properties[0].map(function (property) {
return property + " " + value;
}).join(', ');
return {
transition: transitionsString
};
} else {
return {
transition: properties.join(', ')
};
}
}
// Helpers
export { curriedAdjustHue as adjustHue, animation, backgroundImages, backgrounds, between, border, borderColor, borderRadius, borderStyle, borderWidth, buttons, clearFix, complement, cover, curriedDarken as darken, curriedDesaturate as desaturate, directionalProperty, ellipsis, em, fluidRange, fontFace, getLuminance, getValueAndUnit, grayscale, invert, hideText, hideVisually, hiDPI, hsl, hsla, curriedLighten as lighten, margin, curriedMix as mix, modularScale, normalize, curriedOpacify as opacify, padding, parseToHsl, parseToRgb, placeholder, position, radialGradient, readableColor, rem, retinaImage, rgb, rgba, curriedSaturate as saturate, selection, curriedSetHue as setHue, curriedSetLightness as setLightness, curriedSetSaturation as setSaturation, curriedShade as shade, size, stripUnit, textInputs, timingFunctions, curriedTint as tint, toColorString, transitions, curriedTransparentize as transparentize, triangle, wordWrap };
webpack://frontend-mybets/../../node_modules/postcss-value-parser/lib/index.js
var parse = require("./parse");
var walk = require("./walk");
var stringify = require("./stringify");
function ValueParser(value) {
if (this instanceof ValueParser) {
this.nodes = parse(value);
return this;
}
return new ValueParser(value);
}
ValueParser.prototype.toString = function() {
return Array.isArray(this.nodes) ? stringify(this.nodes) : "";
};
ValueParser.prototype.walk = function(cb, bubble) {
walk(this.nodes, cb, bubble);
return this;
};
ValueParser.unit = require("./unit");
ValueParser.walk = walk;
ValueParser.stringify = stringify;
module.exports = ValueParser;
webpack://frontend-mybets/../../node_modules/postcss-value-parser/lib/parse.js
var openParentheses = "(".charCodeAt(0);
var closeParentheses = ")".charCodeAt(0);
var singleQuote = "'".charCodeAt(0);
var doubleQuote = '"'.charCodeAt(0);
var backslash = "\\".charCodeAt(0);
var slash = "/".charCodeAt(0);
var comma = ",".charCodeAt(0);
var colon = ":".charCodeAt(0);
var star = "*".charCodeAt(0);
var uLower = "u".charCodeAt(0);
var uUpper = "U".charCodeAt(0);
var plus = "+".charCodeAt(0);
var isUnicodeRange = /^[a-f0-9?-]+$/i;
module.exports = function(input) {
var tokens = [];
var value = input;
var next,
quote,
prev,
token,
escape,
escapePos,
whitespacePos,
parenthesesOpenPos;
var pos = 0;
var code = value.charCodeAt(pos);
var max = value.length;
var stack = [{ nodes: tokens }];
var balanced = 0;
var parent;
var name = "";
var before = "";
var after = "";
while (pos < max) {
// Whitespaces
if (code <= 32) {
next = pos;
do {
next += 1;
code = value.charCodeAt(next);
} while (code <= 32);
token = value.slice(pos, next);
prev = tokens[tokens.length - 1];
if (code === closeParentheses && balanced) {
after = token;
} else if (prev && prev.type === "div") {
prev.after = token;
prev.sourceEndIndex += token.length;
} else if (
code === comma ||
code === colon ||
(code === slash &&
value.charCodeAt(next + 1) !== star &&
(!parent ||
(parent && parent.type === "function" && parent.value !== "calc")))
) {
before = token;
} else {
tokens.push({
type: "space",
sourceIndex: pos,
sourceEndIndex: next,
value: token
});
}
pos = next;
// Quotes
} else if (code === singleQuote || code === doubleQuote) {
next = pos;
quote = code === singleQuote ? "'" : '"';
token = {
type: "string",
sourceIndex: pos,
quote: quote
};
do {
escape = false;
next = value.indexOf(quote, next + 1);
if (~next) {
escapePos = next;
while (value.charCodeAt(escapePos - 1) === backslash) {
escapePos -= 1;
escape = !escape;
}
} else {
value += quote;
next = value.length - 1;
token.unclosed = true;
}
} while (escape);
token.value = value.slice(pos + 1, next);
token.sourceEndIndex = token.unclosed ? next : next + 1;
tokens.push(token);
pos = next + 1;
code = value.charCodeAt(pos);
// Comments
} else if (code === slash && value.charCodeAt(pos + 1) === star) {
next = value.indexOf("*/", pos);
token = {
type: "comment",
sourceIndex: pos,
sourceEndIndex: next + 2
};
if (next === -1) {
token.unclosed = true;
next = value.length;
token.sourceEndIndex = next;
}
token.value = value.slice(pos + 2, next);
tokens.push(token);
pos = next + 2;
code = value.charCodeAt(pos);
// Operation within calc
} else if (
(code === slash || code === star) &&
parent &&
parent.type === "function" &&
parent.value === "calc"
) {
token = value[pos];
tokens.push({
type: "word",
sourceIndex: pos - before.length,
sourceEndIndex: pos + token.length,
value: token
});
pos += 1;
code = value.charCodeAt(pos);
// Dividers
} else if (code === slash || code === comma || code === colon) {
token = value[pos];
tokens.push({
type: "div",
sourceIndex: pos - before.length,
sourceEndIndex: pos + token.length,
value: token,
before: before,
after: ""
});
before = "";
pos += 1;
code = value.charCodeAt(pos);
// Open parentheses
} else if (openParentheses === code) {
// Whitespaces after open parentheses
next = pos;
do {
next += 1;
code = value.charCodeAt(next);
} while (code <= 32);
parenthesesOpenPos = pos;
token = {
type: "function",
sourceIndex: pos - name.length,
value: name,
before: value.slice(parenthesesOpenPos + 1, next)
};
pos = next;
if (name === "url" && code !== singleQuote && code !== doubleQuote) {
next -= 1;
do {
escape = false;
next = value.indexOf(")", next + 1);
if (~next) {
escapePos = next;
while (value.charCodeAt(escapePos - 1) === backslash) {
escapePos -= 1;
escape = !escape;
}
} else {
value += ")";
next = value.length - 1;
token.unclosed = true;
}
} while (escape);
// Whitespaces before closed
whitespacePos = next;
do {
whitespacePos -= 1;
code = value.charCodeAt(whitespacePos);
} while (code <= 32);
if (parenthesesOpenPos < whitespacePos) {
if (pos !== whitespacePos + 1) {
token.nodes = [
{
type: "word",
sourceIndex: pos,
sourceEndIndex: whitespacePos + 1,
value: value.slice(pos, whitespacePos + 1)
}
];
} else {
token.nodes = [];
}
if (token.unclosed && whitespacePos + 1 !== next) {
token.after = "";
token.nodes.push({
type: "space",
sourceIndex: whitespacePos + 1,
sourceEndIndex: next,
value: value.slice(whitespacePos + 1, next)
});
} else {
token.after = value.slice(whitespacePos + 1, next);
token.sourceEndIndex = next;
}
} else {
token.after = "";
token.nodes = [];
}
pos = next + 1;
token.sourceEndIndex = token.unclosed ? next : pos;
code = value.charCodeAt(pos);
tokens.push(token);
} else {
balanced += 1;
token.after = "";
token.sourceEndIndex = pos + 1;
tokens.push(token);
stack.push(token);
tokens = token.nodes = [];
parent = token;
}
name = "";
// Close parentheses
} else if (closeParentheses === code && balanced) {
pos += 1;
code = value.charCodeAt(pos);
parent.after = after;
parent.sourceEndIndex += after.length;
after = "";
balanced -= 1;
stack[stack.length - 1].sourceEndIndex = pos;
stack.pop();
parent = stack[balanced];
tokens = parent.nodes;
// Words
} else {
next = pos;
do {
if (code === backslash) {
next += 1;
}
next += 1;
code = value.charCodeAt(next);
} while (
next < max &&
!(
code <= 32 ||
code === singleQuote ||
code === doubleQuote ||
code === comma ||
code === colon ||
code === slash ||
code === openParentheses ||
(code === star &&
parent &&
parent.type === "function" &&
parent.value === "calc") ||
(code === slash &&
parent.type === "function" &&
parent.value === "calc") ||
(code === closeParentheses && balanced)
)
);
token = value.slice(pos, next);
if (openParentheses === code) {
name = token;
} else if (
(uLower === token.charCodeAt(0) || uUpper === token.charCodeAt(0)) &&
plus === token.charCodeAt(1) &&
isUnicodeRange.test(token.slice(2))
) {
tokens.push({
type: "unicode-range",
sourceIndex: pos,
sourceEndIndex: next,
value: token
});
} else {
tokens.push({
type: "word",
sourceIndex: pos,
sourceEndIndex: next,
value: token
});
}
pos = next;
}
}
for (pos = stack.length - 1; pos; pos -= 1) {
stack[pos].unclosed = true;
stack[pos].sourceEndIndex = value.length;
}
return stack[0].nodes;
};
webpack://frontend-mybets/../../node_modules/postcss-value-parser/lib/stringify.js
function stringifyNode(node, custom) {
var type = node.type;
var value = node.value;
var buf;
var customResult;
if (custom && (customResult = custom(node)) !== undefined) {
return customResult;
} else if (type === "word" || type === "space") {
return value;
} else if (type === "string") {
buf = node.quote || "";
return buf + value + (node.unclosed ? "" : buf);
} else if (type === "comment") {
return "/*" + value + (node.unclosed ? "" : "*/");
} else if (type === "div") {
return (node.before || "") + value + (node.after || "");
} else if (Array.isArray(node.nodes)) {
buf = stringify(node.nodes, custom);
if (type !== "function") {
return buf;
}
return (
value +
"(" +
(node.before || "") +
buf +
(node.after || "") +
(node.unclosed ? "" : ")")
);
}
return value;
}
function stringify(nodes, custom) {
var result, i;
if (Array.isArray(nodes)) {
result = "";
for (i = nodes.length - 1; ~i; i -= 1) {
result = stringifyNode(nodes[i], custom) + result;
}
return result;
}
return stringifyNode(nodes, custom);
}
module.exports = stringify;
webpack://frontend-mybets/../../node_modules/postcss-value-parser/lib/unit.js
var minus = "-".charCodeAt(0);
var plus = "+".charCodeAt(0);
var dot = ".".charCodeAt(0);
var exp = "e".charCodeAt(0);
var EXP = "E".charCodeAt(0);
// Check if three code points would start a number
// https://www.w3.org/TR/css-syntax-3/#starts-with-a-number
function likeNumber(value) {
var code = value.charCodeAt(0);
var nextCode;
if (code === plus || code === minus) {
nextCode = value.charCodeAt(1);
if (nextCode >= 48 && nextCode <= 57) {
return true;
}
var nextNextCode = value.charCodeAt(2);
if (nextCode === dot && nextNextCode >= 48 && nextNextCode <= 57) {
return true;
}
return false;
}
if (code === dot) {
nextCode = value.charCodeAt(1);
if (nextCode >= 48 && nextCode <= 57) {
return true;
}
return false;
}
if (code >= 48 && code <= 57) {
return true;
}
return false;
}
// Consume a number
// https://www.w3.org/TR/css-syntax-3/#consume-number
module.exports = function(value) {
var pos = 0;
var length = value.length;
var code;
var nextCode;
var nextNextCode;
if (length === 0 || !likeNumber(value)) {
return false;
}
code = value.charCodeAt(pos);
if (code === plus || code === minus) {
pos++;
}
while (pos < length) {
code = value.charCodeAt(pos);
if (code < 48 || code > 57) {
break;
}
pos += 1;
}
code = value.charCodeAt(pos);
nextCode = value.charCodeAt(pos + 1);
if (code === dot && nextCode >= 48 && nextCode <= 57) {
pos += 2;
while (pos < length) {
code = value.charCodeAt(pos);
if (code < 48 || code > 57) {
break;
}
pos += 1;
}
}
code = value.charCodeAt(pos);
nextCode = value.charCodeAt(pos + 1);
nextNextCode = value.charCodeAt(pos + 2);
if (
(code === exp || code === EXP) &&
((nextCode >= 48 && nextCode <= 57) ||
((nextCode === plus || nextCode === minus) &&
nextNextCode >= 48 &&
nextNextCode <= 57))
) {
pos += nextCode === plus || nextCode === minus ? 3 : 2;
while (pos < length) {
code = value.charCodeAt(pos);
if (code < 48 || code > 57) {
break;
}
pos += 1;
}
}
return {
number: value.slice(0, pos),
unit: value.slice(pos)
};
};
webpack://frontend-mybets/../../node_modules/postcss-value-parser/lib/walk.js
module.exports = function walk(nodes, cb, bubble) {
var i, max, node, result;
for (i = 0, max = nodes.length; i < max; i += 1) {
node = nodes[i];
if (!bubble) {
result = cb(node, i, nodes);
}
if (
result !== false &&
node.type === "function" &&
Array.isArray(node.nodes)
) {
walk(node.nodes, cb, bubble);
}
if (bubble) {
cb(node, i, nodes);
}
}
};
webpack://frontend-mybets/../../node_modules/prop-types/factoryWithThrowingShims.js
/**
* 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.
*/
'use strict';
var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');
function emptyFunction() {}
function emptyFunctionWithReset() {}
emptyFunctionWithReset.resetWarningCache = emptyFunction;
module.exports = 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,
bigint: 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;
};
webpack://frontend-mybets/../../node_modules/prop-types/index.js
/**
* 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.
*/
if (process.env.NODE_ENV !== 'production') {
var ReactIs = require('react-is');
// By explicitly using `prop-types` you are opting into new development behavior.
// http://fb.me/prop-types-in-prod
var throwOnDirectAccess = true;
module.exports = require('./factoryWithTypeCheckers')(ReactIs.isElement, throwOnDirectAccess);
} else {
// By explicitly using `prop-types` you are opting into new production behavior.
// http://fb.me/prop-types-in-prod
module.exports = require('./factoryWithThrowingShims')();
}
webpack://frontend-mybets/../../node_modules/prop-types/lib/ReactPropTypesSecret.js
/** * 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. */ 'use strict'; var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret;
webpack://frontend-mybets/../../node_modules/query-string/index.js
'use strict';
const strictUriEncode = require('strict-uri-encode');
const decodeComponent = require('decode-uri-component');
const splitOnFirst = require('split-on-first');
const filterObject = require('filter-obj');
const isNullOrUndefined = value => value === null || value === undefined;
const encodeFragmentIdentifier = Symbol('encodeFragmentIdentifier');
function encoderForArrayFormat(options) {
switch (options.arrayFormat) {
case 'index':
return key => (result, value) => {
const index = result.length;
if (
value === undefined ||
(options.skipNull && value === null) ||
(options.skipEmptyString && value === '')
) {
return result;
}
if (value === null) {
return [...result, [encode(key, options), '[', index, ']'].join('')];
}
return [
...result,
[encode(key, options), '[', encode(index, options), ']=', encode(value, options)].join('')
];
};
case 'bracket':
return key => (result, value) => {
if (
value === undefined ||
(options.skipNull && value === null) ||
(options.skipEmptyString && value === '')
) {
return result;
}
if (value === null) {
return [...result, [encode(key, options), '[]'].join('')];
}
return [...result, [encode(key, options), '[]=', encode(value, options)].join('')];
};
case 'colon-list-separator':
return key => (result, value) => {
if (
value === undefined ||
(options.skipNull && value === null) ||
(options.skipEmptyString && value === '')
) {
return result;
}
if (value === null) {
return [...result, [encode(key, options), ':list='].join('')];
}
return [...result, [encode(key, options), ':list=', encode(value, options)].join('')];
};
case 'comma':
case 'separator':
case 'bracket-separator': {
const keyValueSep = options.arrayFormat === 'bracket-separator' ?
'[]=' :
'=';
return key => (result, value) => {
if (
value === undefined ||
(options.skipNull && value === null) ||
(options.skipEmptyString && value === '')
) {
return result;
}
// Translate null to an empty string so that it doesn't serialize as 'null'
value = value === null ? '' : value;
if (result.length === 0) {
return [[encode(key, options), keyValueSep, encode(value, options)].join('')];
}
return [[result, encode(value, options)].join(options.arrayFormatSeparator)];
};
}
default:
return key => (result, value) => {
if (
value === undefined ||
(options.skipNull && value === null) ||
(options.skipEmptyString && value === '')
) {
return result;
}
if (value === null) {
return [...result, encode(key, options)];
}
return [...result, [encode(key, options), '=', encode(value, options)].join('')];
};
}
}
function parserForArrayFormat(options) {
let result;
switch (options.arrayFormat) {
case 'index':
return (key, value, accumulator) => {
result = /\[(\d*)\]$/.exec(key);
key = key.replace(/\[\d*\]$/, '');
if (!result) {
accumulator[key] = value;
return;
}
if (accumulator[key] === undefined) {
accumulator[key] = {};
}
accumulator[key][result[1]] = value;
};
case 'bracket':
return (key, value, accumulator) => {
result = /(\[\])$/.exec(key);
key = key.replace(/\[\]$/, '');
if (!result) {
accumulator[key] = value;
return;
}
if (accumulator[key] === undefined) {
accumulator[key] = [value];
return;
}
accumulator[key] = [].concat(accumulator[key], value);
};
case 'colon-list-separator':
return (key, value, accumulator) => {
result = /(:list)$/.exec(key);
key = key.replace(/:list$/, '');
if (!result) {
accumulator[key] = value;
return;
}
if (accumulator[key] === undefined) {
accumulator[key] = [value];
return;
}
accumulator[key] = [].concat(accumulator[key], value);
};
case 'comma':
case 'separator':
return (key, value, accumulator) => {
const isArray = typeof value === 'string' && value.includes(options.arrayFormatSeparator);
const isEncodedArray = (typeof value === 'string' && !isArray && decode(value, options).includes(options.arrayFormatSeparator));
value = isEncodedArray ? decode(value, options) : value;
const newValue = isArray || isEncodedArray ? value.split(options.arrayFormatSeparator).map(item => decode(item, options)) : value === null ? value : decode(value, options);
accumulator[key] = newValue;
};
case 'bracket-separator':
return (key, value, accumulator) => {
const isArray = /(\[\])$/.test(key);
key = key.replace(/\[\]$/, '');
if (!isArray) {
accumulator[key] = value ? decode(value, options) : value;
return;
}
const arrayValue = value === null ?
[] :
value.split(options.arrayFormatSeparator).map(item => decode(item, options));
if (accumulator[key] === undefined) {
accumulator[key] = arrayValue;
return;
}
accumulator[key] = [].concat(accumulator[key], arrayValue);
};
default:
return (key, value, accumulator) => {
if (accumulator[key] === undefined) {
accumulator[key] = value;
return;
}
accumulator[key] = [].concat(accumulator[key], value);
};
}
}
function validateArrayFormatSeparator(value) {
if (typeof value !== 'string' || value.length !== 1) {
throw new TypeError('arrayFormatSeparator must be single character string');
}
}
function encode(value, options) {
if (options.encode) {
return options.strict ? strictUriEncode(value) : encodeURIComponent(value);
}
return value;
}
function decode(value, options) {
if (options.decode) {
return decodeComponent(value);
}
return value;
}
function keysSorter(input) {
if (Array.isArray(input)) {
return input.sort();
}
if (typeof input === 'object') {
return keysSorter(Object.keys(input))
.sort((a, b) => Number(a) - Number(b))
.map(key => input[key]);
}
return input;
}
function removeHash(input) {
const hashStart = input.indexOf('#');
if (hashStart !== -1) {
input = input.slice(0, hashStart);
}
return input;
}
function getHash(url) {
let hash = '';
const hashStart = url.indexOf('#');
if (hashStart !== -1) {
hash = url.slice(hashStart);
}
return hash;
}
function extract(input) {
input = removeHash(input);
const queryStart = input.indexOf('?');
if (queryStart === -1) {
return '';
}
return input.slice(queryStart + 1);
}
function parseValue(value, options) {
if (options.parseNumbers && !Number.isNaN(Number(value)) && (typeof value === 'string' && value.trim() !== '')) {
value = Number(value);
} else if (options.parseBooleans && value !== null && (value.toLowerCase() === 'true' || value.toLowerCase() === 'false')) {
value = value.toLowerCase() === 'true';
}
return value;
}
function parse(query, options) {
options = Object.assign({
decode: true,
sort: true,
arrayFormat: 'none',
arrayFormatSeparator: ',',
parseNumbers: false,
parseBooleans: false
}, options);
validateArrayFormatSeparator(options.arrayFormatSeparator);
const formatter = parserForArrayFormat(options);
// Create an object with no prototype
const ret = Object.create(null);
if (typeof query !== 'string') {
return ret;
}
query = query.trim().replace(/^[?#&]/, '');
if (!query) {
return ret;
}
for (const param of query.split('&')) {
if (param === '') {
continue;
}
let [key, value] = splitOnFirst(options.decode ? param.replace(/\+/g, ' ') : param, '=');
// Missing `=` should be `null`:
// http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters
value = value === undefined ? null : ['comma', 'separator', 'bracket-separator'].includes(options.arrayFormat) ? value : decode(value, options);
formatter(decode(key, options), value, ret);
}
for (const key of Object.keys(ret)) {
const value = ret[key];
if (typeof value === 'object' && value !== null) {
for (const k of Object.keys(value)) {
value[k] = parseValue(value[k], options);
}
} else {
ret[key] = parseValue(value, options);
}
}
if (options.sort === false) {
return ret;
}
return (options.sort === true ? Object.keys(ret).sort() : Object.keys(ret).sort(options.sort)).reduce((result, key) => {
const value = ret[key];
if (Boolean(value) && typeof value === 'object' && !Array.isArray(value)) {
// Sort object keys, not values
result[key] = keysSorter(value);
} else {
result[key] = value;
}
return result;
}, Object.create(null));
}
exports.extract = extract;
exports.parse = parse;
exports.stringify = (object, options) => {
if (!object) {
return '';
}
options = Object.assign({
encode: true,
strict: true,
arrayFormat: 'none',
arrayFormatSeparator: ','
}, options);
validateArrayFormatSeparator(options.arrayFormatSeparator);
const shouldFilter = key => (
(options.skipNull && isNullOrUndefined(object[key])) ||
(options.skipEmptyString && object[key] === '')
);
const formatter = encoderForArrayFormat(options);
const objectCopy = {};
for (const key of Object.keys(object)) {
if (!shouldFilter(key)) {
objectCopy[key] = object[key];
}
}
const keys = Object.keys(objectCopy);
if (options.sort !== false) {
keys.sort(options.sort);
}
return keys.map(key => {
const value = object[key];
if (value === undefined) {
return '';
}
if (value === null) {
return encode(key, options);
}
if (Array.isArray(value)) {
if (value.length === 0 && options.arrayFormat === 'bracket-separator') {
return encode(key, options) + '[]';
}
return value
.reduce(formatter(key), [])
.join('&');
}
return encode(key, options) + '=' + encode(value, options);
}).filter(x => x.length > 0).join('&');
};
exports.parseUrl = (url, options) => {
options = Object.assign({
decode: true
}, options);
const [url_, hash] = splitOnFirst(url, '#');
return Object.assign(
{
url: url_.split('?')[0] || '',
query: parse(extract(url), options)
},
options && options.parseFragmentIdentifier && hash ? {fragmentIdentifier: decode(hash, options)} : {}
);
};
exports.stringifyUrl = (object, options) => {
options = Object.assign({
encode: true,
strict: true,
[encodeFragmentIdentifier]: true
}, options);
const url = removeHash(object.url).split('?')[0] || '';
const queryFromUrl = exports.extract(object.url);
const parsedQueryFromUrl = exports.parse(queryFromUrl, {sort: false});
const query = Object.assign(parsedQueryFromUrl, object.query);
let queryString = exports.stringify(query, options);
if (queryString) {
queryString = `?${queryString}`;
}
let hash = getHash(object.url);
if (object.fragmentIdentifier) {
hash = `#${options[encodeFragmentIdentifier] ? encode(object.fragmentIdentifier, options) : object.fragmentIdentifier}`;
}
return `${url}${queryString}${hash}`;
};
exports.pick = (input, filter, options) => {
options = Object.assign({
parseFragmentIdentifier: true,
[encodeFragmentIdentifier]: false
}, options);
const {url, query, fragmentIdentifier} = exports.parseUrl(input, options);
return exports.stringifyUrl({
url,
query: filterObject(query, filter),
fragmentIdentifier
}, options);
};
exports.exclude = (input, filter, options) => {
const exclusionFilter = Array.isArray(filter) ? key => !filter.includes(key) : (key, value) => !filter(key, value);
return exports.pick(input, exclusionFilter, options);
};
webpack://frontend-mybets/../../node_modules/react-cookie/build/cookie.js
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.load = load;
exports.select = select;
exports.save = save;
exports.remove = remove;
exports.setRawCookie = setRawCookie;
exports.plugToRequest = plugToRequest;
var _cookie = require('cookie');
var _cookie2 = _interopRequireDefault(_cookie);
var _objectAssign = require('object-assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var _isNode = require('is-node');
var _isNode2 = _interopRequireDefault(_isNode);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _rawCookie = {};
var _res = undefined;
function _isResWritable() {
return _res && !_res.headersSent;
}
function load(name, doNotParse, opt) {
var cookies = _isNode2.default ? _rawCookie : _cookie2.default.parse(document.cookie, opt);
var cookieVal = cookies && cookies[name];
if (typeof doNotParse === 'undefined') {
doNotParse = !cookieVal || cookieVal[0] !== '{' && cookieVal[0] !== '[';
}
if (!doNotParse) {
try {
cookieVal = JSON.parse(cookieVal);
} catch (e) {
// Not serialized object
}
}
return cookieVal;
}
function select(regex) {
var cookies = _isNode2.default ? _rawCookie : _cookie2.default.parse(document.cookie);
if (!cookies) {
return {};
}
if (!regex) {
return cookies;
}
return Object.keys(cookies).reduce(function (accumulator, name) {
if (!regex.test(name)) {
return accumulator;
}
var newCookie = {};
newCookie[name] = cookies[name];
return (0, _objectAssign2.default)({}, accumulator, newCookie);
}, {});
}
function save(name, val, opt) {
_rawCookie[name] = val;
// allow you to work with cookies as objects.
if ((typeof val === 'undefined' ? 'undefined' : _typeof(val)) === 'object') {
_rawCookie[name] = JSON.stringify(val);
}
// Cookies only work in the browser
if (!_isNode2.default) {
document.cookie = _cookie2.default.serialize(name, _rawCookie[name], opt);
}
if (_isResWritable() && _res.cookie) {
var expressOpt = _extends({}, opt);
if (expressOpt.maxAge) {
// the standard for maxAge is seconds but express uses milliseconds
expressOpt.maxAge = opt.maxAge * 1000;
}
_res.cookie(name, val, opt);
}
}
function remove(name, opt) {
delete _rawCookie[name];
if (typeof opt === 'undefined') {
opt = {};
} else if (typeof opt === 'string') {
// Will be deprecated in future versions
opt = { path: opt };
} else {
// Prevent mutation of opt below
opt = (0, _objectAssign2.default)({}, opt);
}
if (typeof document !== 'undefined') {
opt.expires = new Date(1970, 1, 1, 0, 0, 1);
opt.maxAge = 0;
document.cookie = _cookie2.default.serialize(name, '', opt);
}
if (_isResWritable() && _res.clearCookie) {
_res.clearCookie(name, opt);
}
}
function setRawCookie(rawCookie) {
if (rawCookie) {
_rawCookie = _cookie2.default.parse(rawCookie);
} else {
_rawCookie = {};
}
}
function plugToRequest(req, res) {
if (req.cookie) {
_rawCookie = req.cookie;
} else if (req.cookies) {
_rawCookie = req.cookies;
} else if (req.headers && req.headers.cookie) {
setRawCookie(req.headers.cookie);
} else {
_rawCookie = {};
}
_res = res;
return function unplug() {
_res = null;
_rawCookie = {};
};
}
exports.default = {
setRawCookie: setRawCookie,
load: load,
select: select,
save: save,
remove: remove,
plugToRequest: plugToRequest
};
webpack://frontend-mybets/../../node_modules/react-day-picker/lib/react-day-picker.min.js
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):"object"==typeof exports?exports.DayPicker=t(require("react")):e.DayPicker=t(e.React)}("undefined"!=typeof self?self:this,function(e){return function(e){function t(o){if(n[o])return n[o].exports;var r=n[o]={i:o,l:!1,exports:{}};return e[o].call(r.exports,r,r.exports,t),r.l=!0,r.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,o){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:o})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=8)}([function(t,n){t.exports=e},function(e,t,n){"use strict";function o(e){return new Date(e.getTime())}function r(e){return e instanceof Date&&!isNaN(e.valueOf())}function a(e,t){var n=o(e);return n.setMonth(e.getMonth()+t),n}function s(e,t){return!(!e||!t)&&(e.getDate()===t.getDate()&&e.getMonth()===t.getMonth()&&e.getFullYear()===t.getFullYear())}function i(e,t){return!(!e||!t)&&(e.getMonth()===t.getMonth()&&e.getFullYear()===t.getFullYear())}function u(e,t){return o(e).setHours(0,0,0,0)<o(t).setHours(0,0,0,0)}function l(e,t){return o(e).setHours(0,0,0,0)>o(t).setHours(0,0,0,0)}function c(e){var t=new Date;return t.setHours(0,0,0,0),u(e,t)}function p(e){var t=new Date((new Date).getTime()+864e5);return t.setHours(0,0,0,0),e>=t}function f(e,t,n){var r=o(e);return r.setHours(0,0,0,0),l(r,t)&&u(r,n)||l(r,n)&&u(r,t)}function h(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{from:null,to:null},n=t.from,o=t.to;return n?n&&o&&s(n,o)&&s(e,n)?(n=null,o=null):o&&u(e,n)?n=e:o&&s(e,o)?(n=e,o=e):(o=e,u(o,n)&&(o=n,n=e)):n=e,{from:n,to:o}}function d(e,t){var n=t.from,o=t.to;return n&&s(e,n)||o&&s(e,o)||n&&o&&f(e,n,o)}function y(e){var t=o(e);return t.setHours(0,0,0),t.setDate(t.getDate()+4-(t.getDay()||7)),Math.ceil(((t-new Date(t.getFullYear(),0,1))/864e5+1)/7)}Object.defineProperty(t,"__esModule",{value:!0}),t.clone=o,t.isDate=r,t.addMonths=a,t.isSameDay=s,t.isSameMonth=i,t.isDayBefore=u,t.isDayAfter=l,t.isPastDay=c,t.isFutureDay=p,t.isDayBetween=f,t.addDayToRange=h,t.isDayInRange=d,t.getWeekNumber=y,t.default={addDayToRange:h,addMonths:a,clone:o,getWeekNumber:y,isDate:r,isDayAfter:l,isDayBefore:u,isDayBetween:f,isDayInRange:d,isFutureDay:p,isPastDay:c,isSameDay:s,isSameMonth:i}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.LEFT=37,t.UP=38,t.RIGHT=39,t.DOWN=40,t.ENTER=13,t.SPACE=32,t.ESC=27,t.TAB=9},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default={container:"DayPicker",wrapper:"DayPicker-wrapper",interactionDisabled:"DayPicker--interactionDisabled",months:"DayPicker-Months",month:"DayPicker-Month",navBar:"DayPicker-NavBar",navButtonPrev:"DayPicker-NavButton DayPicker-NavButton--prev",navButtonNext:"DayPicker-NavButton DayPicker-NavButton--next",navButtonInteractionDisabled:"DayPicker-NavButton--interactionDisabled",caption:"DayPicker-Caption",weekdays:"DayPicker-Weekdays",weekdaysRow:"DayPicker-WeekdaysRow",weekday:"DayPicker-Weekday",body:"DayPicker-Body",week:"DayPicker-Week",weekNumber:"DayPicker-WeekNumber",day:"DayPicker-Day",footer:"DayPicker-Footer",todayButton:"DayPicker-TodayButton",today:"today",selected:"selected",disabled:"disabled",outside:"outside"}},function(e,t,n){"use strict";function o(e){e.preventDefault(),e.stopPropagation()}function r(e){return new Date(e.getFullYear(),e.getMonth(),1,12)}function a(e){var t=r(e);return t.setMonth(t.getMonth()+1),t.setDate(t.getDate()-1),t.getDate()}function s(e){var t=y({},e.modifiers);return e.selectedDays&&(t[e.classNames.selected]=e.selectedDays),e.disabledDays&&(t[e.classNames.disabled]=e.disabledDays),t}function i(e){var t=e.firstDayOfWeek,n=e.locale,o=void 0===n?"en":n,r=e.localeUtils,a=void 0===r?{}:r;return isNaN(t)?a.getFirstDayOfWeek?a.getFirstDayOfWeek(o):0:t}function u(e){return!!(e&&e.from&&e.to)}function l(e,t){return t.getMonth()-e.getMonth()+12*(t.getFullYear()-e.getFullYear())}function c(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(0,m.getFirstDayOfWeek)(),n=arguments[2],o=a(e),r=[],s=[],i=[],u=1;u<=o;u+=1)r.push(new Date(e.getFullYear(),e.getMonth(),u,12));r.forEach(function(e){s.length>0&&e.getDay()===t&&(i.push(s),s=[]),s.push(e),r.indexOf(e)===r.length-1&&i.push(s)});for(var l=i[0],c=7-l.length;c>0;c-=1){var p=(0,v.clone)(l[0]);p.setDate(l[0].getDate()-1),l.unshift(p)}for(var f=i[i.length-1],h=f.length;h<7;h+=1){var d=(0,v.clone)(f[f.length-1]);d.setDate(f[f.length-1].getDate()+1),f.push(d)}if(n&&i.length<6)for(var y=void 0,k=i.length;k<6;k+=1){y=i[i.length-1];for(var D=y[y.length-1],b=[],g=0;g<7;g+=1){var w=(0,v.clone)(D);w.setDate(D.getDate()+g+1),b.push(w)}i.push(b)}return i}function p(e){var t=(0,v.clone)(e);return t.setDate(1),t.setHours(12,0,0,0),t}function f(e,t){var n=void 0;n=t===D.default?t.day+"--"+t.outside:""+t.outside;var o=t.day.replace(/ /g,"."),r=n.replace(/ /g,"."),a="."+o+":not(."+r+")";return e.querySelectorAll(a)}function h(e){return Array.prototype.slice.call(e,0)}function d(e,t){return Object.prototype.hasOwnProperty.call(e,t)}Object.defineProperty(t,"__esModule",{value:!0});var y=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e};t.cancelEvent=o,t.getFirstDayOfMonth=r,t.getDaysInMonth=a,t.getModifiersFromProps=s,t.getFirstDayOfWeekFromProps=i,t.isRangeOfDates=u,t.getMonthsDiff=l,t.getWeekArray=c,t.startOfMonth=p,t.getDayNodes=f,t.nodeListToArray=h,t.hasOwnProp=d;var v=n(1),m=n(5),k=n(3),D=function(e){return e&&e.__esModule?e:{default:e}}(k)},function(e,t,n){"use strict";function o(e){return e.toDateString()}function r(e){return p[e.getMonth()]+" "+e.getFullYear()}function a(e){return c[e]}function s(e){return l[e]}function i(){return 0}function u(){return p}Object.defineProperty(t,"__esModule",{value:!0}),t.formatDay=o,t.formatMonthTitle=r,t.formatWeekdayShort=a,t.formatWeekdayLong=s,t.getFirstDayOfWeek=i,t.getMonths=u;var l=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],c=["Su","Mo","Tu","We","Th","Fr","Sa"],p=["January","February","March","April","May","June","July","August","September","October","November","December"];t.default={formatDay:o,formatMonthTitle:r,formatWeekdayShort:a,formatWeekdayLong:s,getFirstDayOfWeek:i,getMonths:u}},function(e,t,n){"use strict";function o(e,t){return!!t&&(Array.isArray(t)?t:[t]).some(function(t){return!!t&&(t instanceof Date?(0,a.isSameDay)(e,t):(0,s.isRangeOfDates)(t)?(0,a.isDayInRange)(e,t):t.after&&t.before&&(0,a.isDayAfter)(t.before,t.after)?(0,a.isDayAfter)(e,t.after)&&(0,a.isDayBefore)(e,t.before):t.after&&t.before&&((0,a.isDayAfter)(t.after,t.before)||(0,a.isSameDay)(t.after,t.before))?(0,a.isDayAfter)(e,t.after)||(0,a.isDayBefore)(e,t.before):t.after?(0,a.isDayAfter)(e,t.after):t.before?(0,a.isDayBefore)(e,t.before):t.daysOfWeek?t.daysOfWeek.some(function(t){return e.getDay()===t}):"function"==typeof t&&t(e))})}function r(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return Object.keys(t).reduce(function(n,r){var a=t[r];return o(e,a)&&n.push(r),n},[])}Object.defineProperty(t,"__esModule",{value:!0}),t.dayMatchesModifier=o,t.getModifiersForDay=r;var a=n(1),s=n(4);t.default={dayMatchesModifier:o,getModifiersForDay:r}},function(e,t,n){"use strict";function o(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function r(e){return e&&e.__esModule?e:{default:e}}function a(e,t){var n={};for(var o in e)t.indexOf(o)>=0||Object.prototype.hasOwnProperty.call(e,o)&&(n[o]=e[o]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0}),t.ModifiersUtils=t.LocaleUtils=t.DateUtils=t.DayPicker=void 0;var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},c=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),p=n(0),f=r(p),h=n(9),d=r(h),y=n(10),v=r(y),m=n(11),k=r(m),D=n(14),b=r(D),g=n(4),w=o(g),M=n(1),P=o(M),O=n(5),N=o(O),C=n(6),E=o(C),_=n(3),j=r(_),x=n(2),T=t.DayPicker=function(e){function t(e){s(this,t);var n=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));n.dayPicker=null,n.showNextMonth=function(e){if(n.allowNextMonth()){var t=n.props.pagedNavigation?n.props.numberOfMonths:1,o=P.addMonths(n.state.currentMonth,t);n.showMonth(o,e)}},n.showPreviousMonth=function(e){if(n.allowPreviousMonth()){var t=n.props.pagedNavigation?n.props.numberOfMonths:1,o=P.addMonths(n.state.currentMonth,-t);n.showMonth(o,e)}},n.handleKeyDown=function(e){switch(e.persist(),e.keyCode){case x.LEFT:"rtl"===n.props.dir?n.showNextMonth():n.showPreviousMonth(),w.cancelEvent(e);break;case x.RIGHT:"rtl"===n.props.dir?n.showPreviousMonth():n.showNextMonth(),w.cancelEvent(e);break;case x.UP:n.showPreviousYear(),w.cancelEvent(e);break;case x.DOWN:n.showNextYear(),w.cancelEvent(e)}n.props.onKeyDown&&n.props.onKeyDown(e)},n.handleDayKeyDown=function(e,t,o){switch(o.persist(),o.keyCode){case x.LEFT:w.cancelEvent(o),"rtl"===n.props.dir?n.focusNextDay(o.target):n.focusPreviousDay(o.target);break;case x.RIGHT:w.cancelEvent(o),"rtl"===n.props.dir?n.focusPreviousDay(o.target):n.focusNextDay(o.target);break;case x.UP:w.cancelEvent(o),n.focusPreviousWeek(o.target);break;case x.DOWN:w.cancelEvent(o),n.focusNextWeek(o.target);break;case x.ENTER:case x.SPACE:w.cancelEvent(o),n.props.onDayClick&&n.handleDayClick(e,t,o)}n.props.onDayKeyDown&&n.props.onDayKeyDown(e,t,o)},n.handleDayClick=function(e,t,o){o.persist(),t[n.props.classNames.outside]&&n.props.enableOutsideDaysClick&&n.handleOutsideDayClick(e),n.props.onDayClick&&n.props.onDayClick(e,t,o)},n.handleTodayButtonClick=function(e){var t=new Date,o=new Date(t.getFullYear(),t.getMonth());n.showMonth(o),e.target.blur(),n.props.onTodayButtonClick&&(e.persist(),n.props.onTodayButtonClick(new Date(t.getFullYear(),t.getMonth(),t.getDate()),E.getModifiersForDay(t,n.props.modifiers),e))};var o=n.getCurrentMonthFromProps(e);return n.state={currentMonth:o},n}return u(t,e),c(t,[{key:"componentDidUpdate",value:function(e){if(e.month!==this.props.month&&!P.isSameMonth(e.month,this.props.month)){var t=this.getCurrentMonthFromProps(this.props);this.setState({currentMonth:t})}}},{key:"getCurrentMonthFromProps",value:function(e){var t=w.startOfMonth(e.month||e.initialMonth||new Date),n=t;if(e.pagedNavigation&&e.numberOfMonths>1&&e.fromMonth){var o=w.startOfMonth(e.fromMonth),r=w.getMonthsDiff(o,n);n=P.addMonths(o,Math.floor(r/e.numberOfMonths)*e.numberOfMonths)}else e.toMonth&&e.numberOfMonths>1&&w.getMonthsDiff(n,e.toMonth)<=0&&(n=P.addMonths(w.startOfMonth(e.toMonth),1-this.props.numberOfMonths));return n}},{key:"getNextNavigableMonth",value:function(){return P.addMonths(this.state.currentMonth,this.props.numberOfMonths)}},{key:"getPreviousNavigableMonth",value:function(){return P.addMonths(this.state.currentMonth,-1)}},{key:"allowPreviousMonth",value:function(){var e=P.addMonths(this.state.currentMonth,-1);return this.allowMonth(e)}},{key:"allowNextMonth",value:function(){var e=P.addMonths(this.state.currentMonth,this.props.numberOfMonths);return this.allowMonth(e)}},{key:"allowMonth",value:function(e){var t=this.props,n=t.fromMonth,o=t.toMonth;return!(!t.canChangeMonth||n&&w.getMonthsDiff(n,e)<0||o&&w.getMonthsDiff(o,e)>0)}},{key:"allowYearChange",value:function(){return this.props.canChangeMonth}},{key:"showMonth",value:function(e,t){var n=this;this.allowMonth(e)&&this.setState({currentMonth:w.startOfMonth(e)},function(){t&&t(),n.props.onMonthChange&&n.props.onMonthChange(n.state.currentMonth)})}},{key:"showNextYear",value:function(){if(this.allowYearChange()){var e=P.addMonths(this.state.currentMonth,12);this.showMonth(e)}}},{key:"showPreviousYear",value:function(){if(this.allowYearChange()){var e=P.addMonths(this.state.currentMonth,-12);this.showMonth(e)}}},{key:"focus",value:function(){this.wrapper.focus()}},{key:"focusFirstDayOfMonth",value:function(){w.getDayNodes(this.dayPicker,this.props.classNames)[0].focus()}},{key:"focusLastDayOfMonth",value:function(){var e=w.getDayNodes(this.dayPicker,this.props.classNames);e[e.length-1].focus()}},{key:"focusPreviousDay",value:function(e){var t=this,n=w.getDayNodes(this.dayPicker,this.props.classNames),o=w.nodeListToArray(n).indexOf(e);-1!==o&&(0===o?this.showPreviousMonth(function(){return t.focusLastDayOfMonth()}):n[o-1].focus())}},{key:"focusNextDay",value:function(e){var t=this,n=w.getDayNodes(this.dayPicker,this.props.classNames),o=w.nodeListToArray(n).indexOf(e);-1!==o&&(o===n.length-1?this.showNextMonth(function(){return t.focusFirstDayOfMonth()}):n[o+1].focus())}},{key:"focusNextWeek",value:function(e){var t=this,n=w.getDayNodes(this.dayPicker,this.props.classNames),o=w.nodeListToArray(n).indexOf(e);o>n.length-8?this.showNextMonth(function(){var e=n.length-o,r=7-e;w.getDayNodes(t.dayPicker,t.props.classNames)[r].focus()}):n[o+7].focus()}},{key:"focusPreviousWeek",value:function(e){var t=this,n=w.getDayNodes(this.dayPicker,this.props.classNames),o=w.nodeListToArray(n).indexOf(e);o<=6?this.showPreviousMonth(function(){var e=w.getDayNodes(t.dayPicker,t.props.classNames);e[e.length-7+o].focus()}):n[o-7].focus()}},{key:"handleOutsideDayClick",value:function(e){var t=this.state.currentMonth,n=this.props.numberOfMonths,o=w.getMonthsDiff(t,e);o>0&&o>=n?this.showNextMonth():o<0&&this.showPreviousMonth()}},{key:"renderNavbar",value:function(){var e=this.props,t=e.labels,n=e.locale,o=e.localeUtils,r=e.canChangeMonth,s=e.navbarElement,i=a(e,["labels","locale","localeUtils","canChangeMonth","navbarElement"]);if(!r)return null;var u={month:this.state.currentMonth,classNames:this.props.classNames,className:this.props.classNames.navBar,nextMonth:this.getNextNavigableMonth(),previousMonth:this.getPreviousNavigableMonth(),showPreviousButton:this.allowPreviousMonth(),showNextButton:this.allowNextMonth(),onNextClick:this.showNextMonth,onPreviousClick:this.showPreviousMonth,dir:i.dir,labels:t,locale:n,localeUtils:o};return f.default.isValidElement(s)?f.default.cloneElement(s,u):f.default.createElement(s,u)}},{key:"renderMonths",value:function(){for(var e=[],t=w.getFirstDayOfWeekFromProps(this.props),n=0;n<this.props.numberOfMonths;n+=1){var o=P.addMonths(this.state.currentMonth,n);e.push(f.default.createElement(k.default,l({key:n},this.props,{month:o,firstDayOfWeek:t,onDayKeyDown:this.handleDayKeyDown,onDayClick:this.handleDayClick})))}return this.props.reverseMonths&&e.reverse(),e}},{key:"renderFooter",value:function(){return this.props.todayButton?f.default.createElement("div",{className:this.props.classNames.footer},this.renderTodayButton()):null}},{key:"renderTodayButton",value:function(){return f.default.createElement("button",{type:"button",tabIndex:0,className:this.props.classNames.todayButton,"aria-label":this.props.todayButton,onClick:this.handleTodayButtonClick},this.props.todayButton)}},{key:"render",value:function(){var e=this,t=this.props.classNames.container;return this.props.onDayClick||(t=t+" "+this.props.classNames.interactionDisabled),this.props.className&&(t=t+" "+this.props.className),f.default.createElement("div",l({},this.props.containerProps,{className:t,ref:function(t){return e.dayPicker=t},lang:this.props.locale}),f.default.createElement("div",{className:this.props.classNames.wrapper,ref:function(t){return e.wrapper=t},tabIndex:this.props.canChangeMonth&&void 0!==this.props.tabIndex?this.props.tabIndex:-1,onKeyDown:this.handleKeyDown,onFocus:this.props.onFocus,onBlur:this.props.onBlur},this.renderNavbar(),f.default.createElement("div",{className:this.props.classNames.months},this.renderMonths()),this.renderFooter()))}}]),t}(p.Component);T.defaultProps={classNames:j.default,tabIndex:0,numberOfMonths:1,labels:{previousMonth:"Previous Month",nextMonth:"Next Month"},locale:"en",localeUtils:N,showOutsideDays:!1,enableOutsideDaysClick:!0,fixedWeeks:!1,canChangeMonth:!0,reverseMonths:!1,pagedNavigation:!1,showWeekNumbers:!1,showWeekDays:!0,renderDay:function(e){return e.getDate()},renderWeek:function(e){return e},weekdayElement:f.default.createElement(b.default,null),navbarElement:f.default.createElement(v.default,{classNames:j.default}),captionElement:f.default.createElement(d.default,{classNames:j.default})},T.VERSION="7.4.10",T.DateUtils=P,T.LocaleUtils=N,T.ModifiersUtils=E,t.DateUtils=P,t.LocaleUtils=N,t.ModifiersUtils=E,t.default=T},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=n(7).default;o.Input=n(15).default,t.default=o},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),u=n(0),l=o(u),c=n(5),p=o(c),f=n(2),h=function(e){function t(e){r(this,t);var n=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.handleKeyUp=n.handleKeyUp.bind(n),n}return s(t,e),i(t,[{key:"shouldComponentUpdate",value:function(e){return e.locale!==this.props.locale||e.classNames!==this.props.classNames||e.date.getMonth()!==this.props.date.getMonth()||e.date.getFullYear()!==this.props.date.getFullYear()}},{key:"handleKeyUp",value:function(e){e.keyCode===f.ENTER&&this.props.onClick(e)}},{key:"render",value:function(){var e=this.props,t=e.classNames,n=e.date,o=e.months,r=e.locale,a=e.localeUtils,s=e.onClick;return l.default.createElement("div",{className:t.caption,role:"heading","aria-live":"polite"},l.default.createElement("div",{onClick:s,onKeyUp:this.handleKeyUp},o?o[n.getMonth()]+" "+n.getFullYear():a.formatMonthTitle(n,r)))}}]),t}(u.Component);h.defaultProps={localeUtils:p.default},t.default=h},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),u=n(0),l=o(u),c=n(3),p=o(c),f=n(2),h=function(e){function t(){var e,n,o,s;r(this,t);for(var i=arguments.length,u=Array(i),l=0;l<i;l++)u[l]=arguments[l];return n=o=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(u))),o.handleNextClick=function(){o.props.onNextClick&&o.props.onNextClick()},o.handlePreviousClick=function(){o.props.onPreviousClick&&o.props.onPreviousClick()},o.handleNextKeyDown=function(e){e.keyCode!==f.ENTER&&e.keyCode!==f.SPACE||(e.preventDefault(),o.handleNextClick())},o.handlePreviousKeyDown=function(e){e.keyCode!==f.ENTER&&e.keyCode!==f.SPACE||(e.preventDefault(),o.handlePreviousClick())},s=n,a(o,s)}return s(t,e),i(t,[{key:"shouldComponentUpdate",value:function(e){return e.labels!==this.props.labels||e.dir!==this.props.dir||this.props.showPreviousButton!==e.showPreviousButton||this.props.showNextButton!==e.showNextButton}},{key:"render",value:function(){var e=this.props,t=e.classNames,n=e.className,o=e.showPreviousButton,r=e.showNextButton,a=e.labels,s=e.dir,i=void 0,u=void 0,c=void 0,p=void 0,f=void 0,h=void 0;"rtl"===s?(i=this.handleNextClick,u=this.handlePreviousClick,c=this.handleNextKeyDown,p=this.handlePreviousKeyDown,h=o,f=r):(i=this.handlePreviousClick,u=this.handleNextClick,c=this.handlePreviousKeyDown,p=this.handleNextKeyDown,h=r,f=o);var d=f?t.navButtonPrev:t.navButtonPrev+" "+t.navButtonInteractionDisabled,y=h?t.navButtonNext:t.navButtonNext+" "+t.navButtonInteractionDisabled,v=l.default.createElement("span",{tabIndex:"0",role:"button","aria-label":a.previousMonth,key:"previous",className:d,onKeyDown:f?c:void 0,onClick:f?i:void 0}),m=l.default.createElement("span",{tabIndex:"0",role:"button","aria-label":a.nextMonth,key:"right",className:y,onKeyDown:h?p:void 0,onClick:h?u:void 0});return l.default.createElement("div",{className:n||t.navBar},"rtl"===s?[m,v]:[v,m])}}]),t}(u.Component);h.defaultProps={classNames:p.default,dir:"ltr",labels:{previousMonth:"Previous Month",nextMonth:"Next Month"},showPreviousButton:!0,showNextButton:!0},t.default=h},function(e,t,n){"use strict";function o(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function r(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var u=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),l=n(0),c=r(l),p=n(12),f=r(p),h=n(13),d=r(h),y=n(2),v=n(6),m=o(v),k=n(4),D=o(k),b=n(1),g=o(b),w=function(e){function t(){var e,n,o,r;a(this,t);for(var i=arguments.length,u=Array(i),l=0;l<i;l++)u[l]=arguments[l];return n=o=s(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(u))),o.renderDay=function(e){var t=o.props.month.getMonth(),n=D.getModifiersFromProps(o.props),r=m.getModifiersForDay(e,n);g.isSameDay(e,new Date)&&!Object.prototype.hasOwnProperty.call(n,o.props.classNames.today)&&r.push(o.props.classNames.today),e.getMonth()!==t&&r.push(o.props.classNames.outside);var a=e.getMonth()!==t,s=-1;o.props.onDayClick&&!a&&1===e.getDate()&&(s=o.props.tabIndex);var i=""+e.getFullYear()+e.getMonth()+e.getDate(),u={};return r.forEach(function(e){u[e]=!0}),c.default.createElement(d.default,{key:(a?"outside-":"")+i,classNames:o.props.classNames,day:e,modifiers:u,modifiersStyles:o.props.modifiersStyles,empty:a&&!o.props.showOutsideDays&&!o.props.fixedWeeks,tabIndex:s,ariaLabel:o.props.localeUtils.formatDay(e,o.props.locale),ariaDisabled:a||r.indexOf(o.props.classNames.disabled)>-1,ariaSelected:r.indexOf(o.props.classNames.selected)>-1,onClick:o.props.onDayClick,onFocus:o.props.onDayFocus,onKeyDown:o.props.onDayKeyDown,onMouseEnter:o.props.onDayMouseEnter,onMouseLeave:o.props.onDayMouseLeave,onMouseDown:o.props.onDayMouseDown,onMouseUp:o.props.onDayMouseUp,onTouchEnd:o.props.onDayTouchEnd,onTouchStart:o.props.onDayTouchStart},o.props.renderDay(e,u))},r=n,s(o,r)}return i(t,e),u(t,[{key:"render",value:function(){var e=this,t=this.props,n=t.classNames,o=t.month,r=t.months,a=t.fixedWeeks,s=t.captionElement,i=t.weekdayElement,u=t.locale,l=t.localeUtils,p=t.weekdaysLong,h=t.weekdaysShort,d=t.firstDayOfWeek,v=t.onCaptionClick,m=t.showWeekNumbers,k=t.showWeekDays,b=t.onWeekClick,w={date:o,classNames:n,months:r,localeUtils:l,locale:u,onClick:v?function(e){return v(o,e)}:void 0},M=c.default.isValidElement(s)?c.default.cloneElement(s,w):c.default.createElement(s,w),P=D.getWeekArray(o,d,a);return c.default.createElement("div",{className:n.month,role:"grid"},M,k&&c.default.createElement(f.default,{classNames:n,weekdaysShort:h,weekdaysLong:p,firstDayOfWeek:d,showWeekNumbers:m,locale:u,localeUtils:l,weekdayElement:i}),c.default.createElement("div",{className:n.body,role:"rowgroup"},P.map(function(t){var r=void 0;return m&&(r=g.getWeekNumber(t[6])),c.default.createElement("div",{key:t[0].getTime(),className:n.week,role:"row"},m&&c.default.createElement("div",{className:n.weekNumber,tabIndex:b?0:-1,role:"gridcell",onClick:b?function(e){return b(r,t,e)}:void 0,onKeyUp:b?function(e){return e.keyCode===y.ENTER&&b(r,t,e)}:void 0},e.props.renderWeek(r,t,o)),t.map(e.renderDay))})))}}]),t}(l.Component);t.default=w},function(e,t,n){"use strict";function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function r(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),i=n(0),u=function(e){return e&&e.__esModule?e:{default:e}}(i),l=function(e){function t(){return o(this,t),r(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return a(t,e),s(t,[{key:"shouldComponentUpdate",value:function(e){return this.props!==e}},{key:"render",value:function(){for(var e=this.props,t=e.classNames,n=e.firstDayOfWeek,o=e.showWeekNumbers,r=e.weekdaysLong,a=e.weekdaysShort,s=e.locale,i=e.localeUtils,l=e.weekdayElement,c=[],p=0;p<7;p+=1){var f=(p+n)%7,h={key:p,className:t.weekday,weekday:f,weekdaysLong:r,weekdaysShort:a,localeUtils:i,locale:s},d=u.default.isValidElement(l)?u.default.cloneElement(l,h):u.default.createElement(l,h);c.push(d)}return u.default.createElement("div",{className:t.weekdays,role:"rowgroup"},u.default.createElement("div",{className:t.weekdaysRow,role:"row"},o&&u.default.createElement("div",{className:t.weekday}),c))}}]),t}(i.Component);t.default=l},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function i(e,t,n){if(e)return function(o){o.persist(),e(t,n,o)}}Object.defineProperty(t,"__esModule",{value:!0});var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},l=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),c=n(0),p=o(c),f=n(1),h=n(4),d=n(3),y=o(d),v=function(e){function t(){return r(this,t),a(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return s(t,e),l(t,[{key:"shouldComponentUpdate",value:function(e){var t=this,n=Object.keys(this.props),o=Object.keys(e);return n.length!==o.length||n.some(function(n){if("modifiers"===n||"modifiersStyles"===n||"classNames"===n){var o=t.props[n],r=e[n],a=Object.keys(o),s=Object.keys(r);return a.length!==s.length||a.some(function(e){return!(0,h.hasOwnProp)(r,e)||o[e]!==r[e]})}return"day"===n?!(0,f.isSameDay)(t.props[n],e[n]):!(0,h.hasOwnProp)(e,n)||t.props[n]!==e[n]})}},{key:"render",value:function(){var e=this.props,t=e.classNames,n=e.modifiersStyles,o=e.day,r=e.tabIndex,a=e.empty,s=e.modifiers,l=e.onMouseEnter,c=e.onMouseLeave,f=e.onMouseUp,h=e.onMouseDown,d=e.onClick,v=e.onKeyDown,m=e.onTouchStart,k=e.onTouchEnd,D=e.onFocus,b=e.ariaLabel,g=e.ariaDisabled,w=e.ariaSelected,M=e.children,P=t.day;t!==y.default?P+=" "+Object.keys(s).join(" "):P+=Object.keys(s).map(function(e){return" "+P+"--"+e}).join("");var O=void 0;return n&&Object.keys(s).filter(function(e){return!!n[e]}).forEach(function(e){O=u({},O,n[e])}),a?p.default.createElement("div",{"aria-disabled":!0,className:P,style:O}):p.default.createElement("div",{className:P,tabIndex:r,style:O,role:"gridcell","aria-label":b,"aria-disabled":g,"aria-selected":w,onClick:i(d,o,s),onKeyDown:i(v,o,s),onMouseEnter:i(l,o,s),onMouseLeave:i(c,o,s),onMouseUp:i(f,o,s),onMouseDown:i(h,o,s),onTouchEnd:i(k,o,s),onTouchStart:i(m,o,s),onFocus:i(D,o,s)},M)}}]),t}(c.Component);v.defaultProps={tabIndex:-1},v.defaultProps={modifiers:{},modifiersStyles:{},empty:!1},t.default=v},function(e,t,n){"use strict";function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function r(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),i=n(0),u=function(e){return e&&e.__esModule?e:{default:e}}(i),l=function(e){function t(){return o(this,t),r(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return a(t,e),s(t,[{key:"shouldComponentUpdate",value:function(e){return this.props!==e}},{key:"render",value:function(){var e=this.props,t=e.weekday,n=e.className,o=e.weekdaysLong,r=e.weekdaysShort,a=e.localeUtils,s=e.locale,i=void 0;i=o?o[t]:a.formatWeekdayLong(t,s);var l=void 0;return l=r?r[t]:a.formatWeekdayShort(t,s),u.default.createElement("div",{className:n,role:"columnheader"},u.default.createElement("abbr",{title:i},l))}}]),t}(i.Component);t.default=l},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function u(e,t){var n={};for(var o in e)t.indexOf(o)>=0||Object.prototype.hasOwnProperty.call(e,o)&&(n[o]=e[o]);return n}function l(e){var t=(e.input,e.selectedDay,e.month,e.children),n=e.classNames,o=u(e,["input","selectedDay","month","children","classNames"]);return y.default.createElement("div",h({className:n.overlayWrapper},o),y.default.createElement("div",{className:n.overlay},t))}function c(e){if((0,k.isDate)(e)){return e.getFullYear()+"-"+(""+(e.getMonth()+1))+"-"+(""+e.getDate())}return""}function p(e){if("string"==typeof e){var t=e.split("-");if(3===t.length){var n=parseInt(t[0],10),o=parseInt(t[1],10)-1,r=parseInt(t[2],10);if(!(isNaN(n)||String(n).length>4||isNaN(o)||isNaN(r)||r<=0||r>31||o<0||o>=12))return new Date(n,o,r,12,0,0,0)}}}Object.defineProperty(t,"__esModule",{value:!0}),t.HIDE_TIMEOUT=void 0;var f=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),h=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e};t.OverlayComponent=l,t.defaultFormat=c,t.defaultParse=p;var d=n(0),y=o(d),v=n(7),m=o(v),k=n(1),D=n(6),b=n(2),g=t.HIDE_TIMEOUT=100,w=function(e){function t(e){a(this,t);var n=s(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.input=null,n.daypicker=null,n.clickTimeout=null,n.hideTimeout=null,n.inputBlurTimeout=null,n.inputFocusTimeout=null,n.state=n.getInitialStateFromProps(e),n.state.showOverlay=e.showOverlay,n.hideAfterDayClick=n.hideAfterDayClick.bind(n),n.handleInputClick=n.handleInputClick.bind(n),n.handleInputFocus=n.handleInputFocus.bind(n),n.handleInputBlur=n.handleInputBlur.bind(n),n.handleInputChange=n.handleInputChange.bind(n),n.handleInputKeyDown=n.handleInputKeyDown.bind(n),n.handleInputKeyUp=n.handleInputKeyUp.bind(n),n.handleDayClick=n.handleDayClick.bind(n),n.handleMonthChange=n.handleMonthChange.bind(n),n.handleOverlayFocus=n.handleOverlayFocus.bind(n),n.handleOverlayBlur=n.handleOverlayBlur.bind(n),n}return i(t,e),f(t,[{key:"componentDidUpdate",value:function(e){var t={},n=this.props,o=n.value,r=n.formatDate,a=n.format,s=n.dayPickerProps;o===e.value&&s.locale===e.dayPickerProps.locale&&a===e.format||((0,k.isDate)(o)?t.value=r(o,a,s.locale):t.value=o);var i=e.dayPickerProps.month;s.month&&s.month!==i&&!(0,k.isSameMonth)(s.month,i)&&(t.month=s.month),e.dayPickerProps.selectedDays!==s.selectedDays&&(t.selectedDays=s.selectedDays),Object.keys(t).length>0&&this.setState(t)}},{key:"componentWillUnmount",value:function(){clearTimeout(this.clickTimeout),clearTimeout(this.hideTimeout),clearTimeout(this.inputFocusTimeout),clearTimeout(this.inputBlurTimeout),clearTimeout(this.overlayBlurTimeout)}},{key:"getInitialMonthFromProps",value:function(e){var t=e.dayPickerProps,n=e.format,o=void 0;return e.value&&(o=(0,k.isDate)(e.value)?e.value:e.parseDate(e.value,n,t.locale)),t.initialMonth||t.month||o||new Date}},{key:"getInitialStateFromProps",value:function(e){var t=e.dayPickerProps,n=e.formatDate,o=e.format,r=e.typedValue,a=e.value;return e.value&&(0,k.isDate)(e.value)&&(a=n(e.value,o,t.locale)),{value:a,typedValue:r,month:this.getInitialMonthFromProps(e),selectedDays:t.selectedDays}}},{key:"getInput",value:function(){return this.input}},{key:"getDayPicker",value:function(){return this.daypicker}},{key:"updateState",value:function(e,t,n){var o=this,a=this.props,s=a.dayPickerProps,i=a.onDayChange;this.setState({month:e,value:t,typedValue:""},function(){if(n&&n(),i){var t=h({disabled:s.disabledDays,selected:s.selectedDays},s.modifiers),a=(0,D.getModifiersForDay)(e,t).reduce(function(e,t){return h({},e,r({},t,!0))},{});i(e,a,o)}})}},{key:"showDayPicker",value:function(){var e=this,t=this.props,n=t.parseDate,o=t.format,r=t.dayPickerProps,a=this.state,s=a.value;if(!a.showOverlay){var i=s?n(s,o,r.locale):this.getInitialMonthFromProps(this.props);this.setState(function(e){return{showOverlay:!0,month:i||e.month}},function(){e.props.onDayPickerShow&&e.props.onDayPickerShow()})}}},{key:"hideDayPicker",value:function(){var e=this;!1!==this.state.showOverlay&&this.setState({showOverlay:!1},function(){e.props.onDayPickerHide&&e.props.onDayPickerHide()})}},{key:"hideAfterDayClick",value:function(){var e=this;this.props.hideOnDayClick&&(this.hideTimeout=setTimeout(function(){e.overlayHasFocus=!1,e.hideDayPicker()},g))}},{key:"handleInputClick",value:function(e){this.showDayPicker(),this.props.inputProps.onClick&&(e.persist(),this.props.inputProps.onClick(e))}},{key:"handleInputFocus",value:function(e){var t=this;this.showDayPicker(),this.inputFocusTimeout=setTimeout(function(){t.overlayHasFocus=!1},2),this.props.inputProps.onFocus&&(e.persist(),this.props.inputProps.onFocus(e))}},{key:"handleInputBlur",value:function(e){var t=this;this.inputBlurTimeout=setTimeout(function(){t.overlayHasFocus||t.hideDayPicker()},1),this.props.inputProps.onBlur&&(e.persist(),this.props.inputProps.onBlur(e))}},{key:"handleOverlayFocus",value:function(e){e.preventDefault(),this.overlayHasFocus=!0,this.props.keepFocus&&this.input&&"function"==typeof this.input.focus&&this.input.focus()}},{key:"handleOverlayBlur",value:function(){var e=this;this.overlayBlurTimeout=setTimeout(function(){e.overlayHasFocus=!1},3)}},{key:"handleInputChange",value:function(e){var t=this.props,n=t.dayPickerProps,o=t.format,r=t.inputProps,a=t.onDayChange,s=t.parseDate;r.onChange&&(e.persist(),r.onChange(e));var i=e.target.value;if(""===i.trim())return this.setState({value:i,typedValue:""}),void(a&&a(void 0,{},this));var u=s(i,o,n.locale);if(!u)return this.setState({value:i,typedValue:i}),void(a&&a(void 0,{},this));this.updateState(u,i)}},{key:"handleInputKeyDown",value:function(e){e.keyCode===b.TAB?this.hideDayPicker():this.showDayPicker(),this.props.inputProps.onKeyDown&&(e.persist(),this.props.inputProps.onKeyDown(e))}},{key:"handleInputKeyUp",value:function(e){e.keyCode===b.ESC?this.hideDayPicker():this.showDayPicker(),this.props.inputProps.onKeyUp&&(e.persist(),this.props.inputProps.onKeyUp(e))}},{key:"handleMonthChange",value:function(e){var t=this;this.setState({month:e},function(){t.props.dayPickerProps&&t.props.dayPickerProps.onMonthChange&&t.props.dayPickerProps.onMonthChange(e)})}},{key:"handleDayClick",value:function(e,t,n){var o=this,r=this.props,a=r.clickUnselectsDay,s=r.dayPickerProps,i=r.onDayChange,u=r.formatDate,l=r.format;if(s.onDayClick&&s.onDayClick(e,t,n),!(t.disabled||s&&s.classNames&&t[s.classNames.disabled])){if(t.selected&&a){var c=this.state.selectedDays;if(Array.isArray(c)){c=c.slice(0);var p=c.indexOf(e);c.splice(p,1)}else c&&(c=null);return this.setState({value:"",typedValue:"",selectedDays:c},this.hideAfterDayClick),void(i&&i(void 0,t,this))}var f=u(e,l,s.locale);this.setState({value:f,typedValue:"",month:e},function(){i&&i(e,t,o),o.hideAfterDayClick()})}}},{key:"renderOverlay",value:function(){var e=this,t=this.props,n=t.classNames,o=t.dayPickerProps,r=t.parseDate,a=t.formatDate,s=t.format,i=this.state,u=i.selectedDays,l=i.value,c=void 0;if(!u&&l){var p=r(l,s,o.locale);p&&(c=p)}else u&&(c=u);var f=void 0;o.todayButton&&(f=function(){return e.updateState(new Date,a(new Date,s,o.locale),e.hideAfterDayClick)});var d=this.props.overlayComponent;return y.default.createElement(d,{classNames:n,month:this.state.month,selectedDay:c,input:this.input,tabIndex:0,onFocus:this.handleOverlayFocus,onBlur:this.handleOverlayBlur},y.default.createElement(m.default,h({ref:function(t){return e.daypicker=t},onTodayButtonClick:f},o,{month:this.state.month,selectedDays:c,onDayClick:this.handleDayClick,onMonthChange:this.handleMonthChange})))}},{key:"render",value:function(){var e=this,t=this.props.component,n=this.props.inputProps;return y.default.createElement("div",{className:this.props.classNames.container,style:this.props.style},y.default.createElement(t,h({ref:function(t){return e.input=t},placeholder:this.props.placeholder},n,{value:this.state.value||this.state.typedValue,onChange:this.handleInputChange,onFocus:this.handleInputFocus,onBlur:this.handleInputBlur,onKeyDown:this.handleInputKeyDown,onKeyUp:this.handleInputKeyUp,onClick:n.disabled?void 0:this.handleInputClick})),this.state.showOverlay&&this.renderOverlay())}}]),t}(y.default.Component);w.defaultProps={dayPickerProps:{},value:"",typedValue:"",placeholder:"YYYY-M-D",format:"L",formatDate:c,parseDate:p,showOverlay:!1,hideOnDayClick:!0,clickUnselectsDay:!1,keepFocus:!0,component:"input",inputProps:{},overlayComponent:l,classNames:{container:"DayPickerInput",overlayWrapper:"DayPickerInput-OverlayWrapper",overlay:"DayPickerInput-Overlay"}},t.default=w}]).default});
//# sourceMappingURL=react-day-picker.min.js.map
webpack://frontend-mybets/../../node_modules/react-dom/cjs/react-dom.production.min.js
/**
* @license React
* react-dom.production.min.js
*
* 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.
*/
/*
Modernizr 3.0.0pre (Custom Build) | MIT
*/
'use strict';var aa=require("react"),ca=require("scheduler");function p(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c<arguments.length;c++)b+="&args[]="+encodeURIComponent(arguments[c]);return"Minified React error #"+a+"; visit "+b+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var da=new Set,ea={};function fa(a,b){ha(a,b);ha(a+"Capture",b)}
function ha(a,b){ea[a]=b;for(a=0;a<b.length;a++)da.add(b[a])}
var ia=!("undefined"===typeof window||"undefined"===typeof window.document||"undefined"===typeof window.document.createElement),ja=Object.prototype.hasOwnProperty,ka=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,la=
{},ma={};function oa(a){if(ja.call(ma,a))return!0;if(ja.call(la,a))return!1;if(ka.test(a))return ma[a]=!0;la[a]=!0;return!1}function pa(a,b,c,d){if(null!==c&&0===c.type)return!1;switch(typeof b){case "function":case "symbol":return!0;case "boolean":if(d)return!1;if(null!==c)return!c.acceptsBooleans;a=a.toLowerCase().slice(0,5);return"data-"!==a&&"aria-"!==a;default:return!1}}
function qa(a,b,c,d){if(null===b||"undefined"===typeof b||pa(a,b,c,d))return!0;if(d)return!1;if(null!==c)switch(c.type){case 3:return!b;case 4:return!1===b;case 5:return isNaN(b);case 6:return isNaN(b)||1>b}return!1}function v(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g}var z={};
"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){z[a]=new v(a,0,!1,a,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];z[b]=new v(b,1,!1,a[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(a){z[a]=new v(a,2,!1,a.toLowerCase(),null,!1,!1)});
["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){z[a]=new v(a,2,!1,a,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){z[a]=new v(a,3,!1,a.toLowerCase(),null,!1,!1)});
["checked","multiple","muted","selected"].forEach(function(a){z[a]=new v(a,3,!0,a,null,!1,!1)});["capture","download"].forEach(function(a){z[a]=new v(a,4,!1,a,null,!1,!1)});["cols","rows","size","span"].forEach(function(a){z[a]=new v(a,6,!1,a,null,!1,!1)});["rowSpan","start"].forEach(function(a){z[a]=new v(a,5,!1,a.toLowerCase(),null,!1,!1)});var ra=/[\-:]([a-z])/g;function sa(a){return a[1].toUpperCase()}
"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(ra,
sa);z[b]=new v(b,1,!1,a,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!1,!1)});
z.xlinkHref=new v("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!0,!0)});
function ta(a,b,c,d){var e=z.hasOwnProperty(b)?z[b]:null;if(null!==e?0!==e.type:d||!(2<b.length)||"o"!==b[0]&&"O"!==b[0]||"n"!==b[1]&&"N"!==b[1])qa(b,c,e,d)&&(c=null),d||null===e?oa(b)&&(null===c?a.removeAttribute(b):a.setAttribute(b,""+c)):e.mustUseProperty?a[e.propertyName]=null===c?3===e.type?!1:"":c:(b=e.attributeName,d=e.attributeNamespace,null===c?a.removeAttribute(b):(e=e.type,c=3===e||4===e&&!0===c?"":""+c,d?a.setAttributeNS(d,b,c):a.setAttribute(b,c)))}
var ua=aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,va=Symbol.for("react.element"),wa=Symbol.for("react.portal"),ya=Symbol.for("react.fragment"),za=Symbol.for("react.strict_mode"),Aa=Symbol.for("react.profiler"),Ba=Symbol.for("react.provider"),Ca=Symbol.for("react.context"),Da=Symbol.for("react.forward_ref"),Ea=Symbol.for("react.suspense"),Fa=Symbol.for("react.suspense_list"),Ga=Symbol.for("react.memo"),Ha=Symbol.for("react.lazy");Symbol.for("react.scope");Symbol.for("react.debug_trace_mode");
var Ia=Symbol.for("react.offscreen");Symbol.for("react.legacy_hidden");Symbol.for("react.cache");Symbol.for("react.tracing_marker");var Ja=Symbol.iterator;function Ka(a){if(null===a||"object"!==typeof a)return null;a=Ja&&a[Ja]||a["@@iterator"];return"function"===typeof a?a:null}var A=Object.assign,La;function Ma(a){if(void 0===La)try{throw Error();}catch(c){var b=c.stack.trim().match(/\n( *(at )?)/);La=b&&b[1]||""}return"\n"+La+a}var Na=!1;
function Oa(a,b){if(!a||Na)return"";Na=!0;var c=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(b)if(b=function(){throw Error();},Object.defineProperty(b.prototype,"props",{set:function(){throw Error();}}),"object"===typeof Reflect&&Reflect.construct){try{Reflect.construct(b,[])}catch(l){var d=l}Reflect.construct(a,[],b)}else{try{b.call()}catch(l){d=l}a.call(b.prototype)}else{try{throw Error();}catch(l){d=l}a()}}catch(l){if(l&&d&&"string"===typeof l.stack){for(var e=l.stack.split("\n"),
f=d.stack.split("\n"),g=e.length-1,h=f.length-1;1<=g&&0<=h&&e[g]!==f[h];)h--;for(;1<=g&&0<=h;g--,h--)if(e[g]!==f[h]){if(1!==g||1!==h){do if(g--,h--,0>h||e[g]!==f[h]){var k="\n"+e[g].replace(" at new "," at ");a.displayName&&k.includes("<anonymous>")&&(k=k.replace("<anonymous>",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{Na=!1,Error.prepareStackTrace=c}return(a=a?a.displayName||a.name:"")?Ma(a):""}
function Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma("Lazy");case 13:return Ma("Suspense");case 19:return Ma("SuspenseList");case 0:case 2:case 15:return a=Oa(a.type,!1),a;case 11:return a=Oa(a.type.render,!1),a;case 1:return a=Oa(a.type,!0),a;default:return""}}
function Qa(a){if(null==a)return null;if("function"===typeof a)return a.displayName||a.name||null;if("string"===typeof a)return a;switch(a){case ya:return"Fragment";case wa:return"Portal";case Aa:return"Profiler";case za:return"StrictMode";case Ea:return"Suspense";case Fa:return"SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case Ca:return(a.displayName||"Context")+".Consumer";case Ba:return(a._context.displayName||"Context")+".Provider";case Da:var b=a.render;a=a.displayName;a||(a=b.displayName||
b.name||"",a=""!==a?"ForwardRef("+a+")":"ForwardRef");return a;case Ga:return b=a.displayName||null,null!==b?b:Qa(a.type)||"Memo";case Ha:b=a._payload;a=a._init;try{return Qa(a(b))}catch(c){}}return null}
function Ra(a){var b=a.type;switch(a.tag){case 24:return"Cache";case 9:return(b.displayName||"Context")+".Consumer";case 10:return(b._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return a=b.render,a=a.displayName||a.name||"",b.displayName||(""!==a?"ForwardRef("+a+")":"ForwardRef");case 7:return"Fragment";case 5:return b;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Qa(b);case 8:return b===za?"StrictMode":"Mode";case 22:return"Offscreen";
case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if("function"===typeof b)return b.displayName||b.name||null;if("string"===typeof b)return b}return null}function Sa(a){switch(typeof a){case "boolean":case "number":case "string":case "undefined":return a;case "object":return a;default:return""}}
function Ta(a){var b=a.type;return(a=a.nodeName)&&"input"===a.toLowerCase()&&("checkbox"===b||"radio"===b)}
function Ua(a){var b=Ta(a)?"checked":"value",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=""+a[b];if(!a.hasOwnProperty(b)&&"undefined"!==typeof c&&"function"===typeof c.get&&"function"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=""+a;f.call(this,a)}});Object.defineProperty(a,b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=""+a},stopTracking:function(){a._valueTracker=
null;delete a[b]}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a))}function Wa(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d="";a&&(d=Ta(a)?a.checked?"true":"false":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Xa(a){a=a||("undefined"!==typeof document?document:void 0);if("undefined"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}
function Ya(a,b){var c=b.checked;return A({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Za(a,b){var c=null==b.defaultValue?"":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Sa(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:"checkbox"===b.type||"radio"===b.type?null!=b.checked:null!=b.value}}function ab(a,b){b=b.checked;null!=b&&ta(a,"checked",b,!1)}
function bb(a,b){ab(a,b);var c=Sa(b.value),d=b.type;if(null!=c)if("number"===d){if(0===c&&""===a.value||a.value!=c)a.value=""+c}else a.value!==""+c&&(a.value=""+c);else if("submit"===d||"reset"===d){a.removeAttribute("value");return}b.hasOwnProperty("value")?cb(a,b.type,c):b.hasOwnProperty("defaultValue")&&cb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)}
function db(a,b,c){if(b.hasOwnProperty("value")||b.hasOwnProperty("defaultValue")){var d=b.type;if(!("submit"!==d&&"reset"!==d||void 0!==b.value&&null!==b.value))return;b=""+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b}c=a.name;""!==c&&(a.name="");a.defaultChecked=!!a._wrapperState.initialChecked;""!==c&&(a.name=c)}
function cb(a,b,c){if("number"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=""+a._wrapperState.initialValue:a.defaultValue!==""+c&&(a.defaultValue=""+c)}var eb=Array.isArray;
function fb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e<c.length;e++)b["$"+c[e]]=!0;for(c=0;c<a.length;c++)e=b.hasOwnProperty("$"+a[c].value),a[c].selected!==e&&(a[c].selected=e),e&&d&&(a[c].defaultSelected=!0)}else{c=""+Sa(c);b=null;for(e=0;e<a.length;e++){if(a[e].value===c){a[e].selected=!0;d&&(a[e].defaultSelected=!0);return}null!==b||a[e].disabled||(b=a[e])}null!==b&&(b.selected=!0)}}
function gb(a,b){if(null!=b.dangerouslySetInnerHTML)throw Error(p(91));return A({},b,{value:void 0,defaultValue:void 0,children:""+a._wrapperState.initialValue})}function hb(a,b){var c=b.value;if(null==c){c=b.children;b=b.defaultValue;if(null!=c){if(null!=b)throw Error(p(92));if(eb(c)){if(1<c.length)throw Error(p(93));c=c[0]}b=c}null==b&&(b="");c=b}a._wrapperState={initialValue:Sa(c)}}
function ib(a,b){var c=Sa(b.value),d=Sa(b.defaultValue);null!=c&&(c=""+c,c!==a.value&&(a.value=c),null==b.defaultValue&&a.defaultValue!==c&&(a.defaultValue=c));null!=d&&(a.defaultValue=""+d)}function jb(a){var b=a.textContent;b===a._wrapperState.initialValue&&""!==b&&null!==b&&(a.value=b)}function kb(a){switch(a){case "svg":return"http://www.w3.org/2000/svg";case "math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}
function lb(a,b){return null==a||"http://www.w3.org/1999/xhtml"===a?kb(b):"http://www.w3.org/2000/svg"===a&&"foreignObject"===b?"http://www.w3.org/1999/xhtml":a}
var mb,nb=function(a){return"undefined"!==typeof MSApp&&MSApp.execUnsafeLocalFunction?function(b,c,d,e){MSApp.execUnsafeLocalFunction(function(){return a(b,c,d,e)})}:a}(function(a,b){if("http://www.w3.org/2000/svg"!==a.namespaceURI||"innerHTML"in a)a.innerHTML=b;else{mb=mb||document.createElement("div");mb.innerHTML="<svg>"+b.valueOf().toString()+"</svg>";for(b=mb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}});
function ob(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b}
var pb={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,
zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},qb=["Webkit","ms","Moz","O"];Object.keys(pb).forEach(function(a){qb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);pb[b]=pb[a]})});function rb(a,b,c){return null==b||"boolean"===typeof b||""===b?"":c||"number"!==typeof b||0===b||pb.hasOwnProperty(a)&&pb[a]?(""+b).trim():b+"px"}
function sb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf("--"),e=rb(c,b[c],d);"float"===c&&(c="cssFloat");d?a.setProperty(c,e):a[c]=e}}var tb=A({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});
function ub(a,b){if(b){if(tb[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(p(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p(60));if("object"!==typeof b.dangerouslySetInnerHTML||!("__html"in b.dangerouslySetInnerHTML))throw Error(p(61));}if(null!=b.style&&"object"!==typeof b.style)throw Error(p(62));}}
function vb(a,b){if(-1===a.indexOf("-"))return"string"===typeof b.is;switch(a){case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":return!1;default:return!0}}var wb=null;function xb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}var yb=null,zb=null,Ab=null;
function Bb(a){if(a=Cb(a)){if("function"!==typeof yb)throw Error(p(280));var b=a.stateNode;b&&(b=Db(b),yb(a.stateNode,a.type,b))}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a}function Fb(){if(zb){var a=zb,b=Ab;Ab=zb=null;Bb(a);if(b)for(a=0;a<b.length;a++)Bb(b[a])}}function Gb(a,b){return a(b)}function Hb(){}var Ib=!1;function Jb(a,b,c){if(Ib)return a(b,c);Ib=!0;try{return Gb(a,b,c)}finally{if(Ib=!1,null!==zb||null!==Ab)Hb(),Fb()}}
function Kb(a,b){var c=a.stateNode;if(null===c)return null;var d=Db(c);if(null===d)return null;c=d[b];a:switch(b){case "onClick":case "onClickCapture":case "onDoubleClick":case "onDoubleClickCapture":case "onMouseDown":case "onMouseDownCapture":case "onMouseMove":case "onMouseMoveCapture":case "onMouseUp":case "onMouseUpCapture":case "onMouseEnter":(d=!d.disabled)||(a=a.type,d=!("button"===a||"input"===a||"select"===a||"textarea"===a));a=!d;break a;default:a=!1}if(a)return null;if(c&&"function"!==
typeof c)throw Error(p(231,b,typeof c));return c}var Lb=!1;if(ia)try{var Mb={};Object.defineProperty(Mb,"passive",{get:function(){Lb=!0}});window.addEventListener("test",Mb,Mb);window.removeEventListener("test",Mb,Mb)}catch(a){Lb=!1}function Nb(a,b,c,d,e,f,g,h,k){var l=Array.prototype.slice.call(arguments,3);try{b.apply(c,l)}catch(m){this.onError(m)}}var Ob=!1,Pb=null,Qb=!1,Rb=null,Sb={onError:function(a){Ob=!0;Pb=a}};function Tb(a,b,c,d,e,f,g,h,k){Ob=!1;Pb=null;Nb.apply(Sb,arguments)}
function Ub(a,b,c,d,e,f,g,h,k){Tb.apply(this,arguments);if(Ob){if(Ob){var l=Pb;Ob=!1;Pb=null}else throw Error(p(198));Qb||(Qb=!0,Rb=l)}}function Vb(a){var b=a,c=a;if(a.alternate)for(;b.return;)b=b.return;else{a=b;do b=a,0!==(b.flags&4098)&&(c=b.return),a=b.return;while(a)}return 3===b.tag?c:null}function Wb(a){if(13===a.tag){var b=a.memoizedState;null===b&&(a=a.alternate,null!==a&&(b=a.memoizedState));if(null!==b)return b.dehydrated}return null}function Xb(a){if(Vb(a)!==a)throw Error(p(188));}
function Yb(a){var b=a.alternate;if(!b){b=Vb(a);if(null===b)throw Error(p(188));return b!==a?null:a}for(var c=a,d=b;;){var e=c.return;if(null===e)break;var f=e.alternate;if(null===f){d=e.return;if(null!==d){c=d;continue}break}if(e.child===f.child){for(f=e.child;f;){if(f===c)return Xb(e),a;if(f===d)return Xb(e),b;f=f.sibling}throw Error(p(188));}if(c.return!==d.return)c=e,d=f;else{for(var g=!1,h=e.child;h;){if(h===c){g=!0;c=e;d=f;break}if(h===d){g=!0;d=e;c=f;break}h=h.sibling}if(!g){for(h=f.child;h;){if(h===
c){g=!0;c=f;d=e;break}if(h===d){g=!0;d=f;c=e;break}h=h.sibling}if(!g)throw Error(p(189));}}if(c.alternate!==d)throw Error(p(190));}if(3!==c.tag)throw Error(p(188));return c.stateNode.current===c?a:b}function Zb(a){a=Yb(a);return null!==a?$b(a):null}function $b(a){if(5===a.tag||6===a.tag)return a;for(a=a.child;null!==a;){var b=$b(a);if(null!==b)return b;a=a.sibling}return null}
var ac=ca.unstable_scheduleCallback,bc=ca.unstable_cancelCallback,cc=ca.unstable_shouldYield,dc=ca.unstable_requestPaint,B=ca.unstable_now,ec=ca.unstable_getCurrentPriorityLevel,fc=ca.unstable_ImmediatePriority,gc=ca.unstable_UserBlockingPriority,hc=ca.unstable_NormalPriority,ic=ca.unstable_LowPriority,jc=ca.unstable_IdlePriority,kc=null,lc=null;function mc(a){if(lc&&"function"===typeof lc.onCommitFiberRoot)try{lc.onCommitFiberRoot(kc,a,void 0,128===(a.current.flags&128))}catch(b){}}
var oc=Math.clz32?Math.clz32:nc,pc=Math.log,qc=Math.LN2;function nc(a){a>>>=0;return 0===a?32:31-(pc(a)/qc|0)|0}var rc=64,sc=4194304;
function tc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;
default:return a}}function uc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=tc(h):(f&=g,0!==f&&(d=tc(f)))}else g=c&~e,0!==g?d=tc(g):0!==f&&(d=tc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0<b;)c=31-oc(b),e=1<<c,d|=a[c],b&=~e;return d}
function vc(a,b){switch(a){case 1:case 2:case 4:return b+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return b+5E3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}
function wc(a,b){for(var c=a.suspendedLanes,d=a.pingedLanes,e=a.expirationTimes,f=a.pendingLanes;0<f;){var g=31-oc(f),h=1<<g,k=e[g];if(-1===k){if(0===(h&c)||0!==(h&d))e[g]=vc(h,b)}else k<=b&&(a.expiredLanes|=h);f&=~h}}function xc(a){a=a.pendingLanes&-1073741825;return 0!==a?a:a&1073741824?1073741824:0}function yc(){var a=rc;rc<<=1;0===(rc&4194240)&&(rc=64);return a}function zc(a){for(var b=[],c=0;31>c;c++)b.push(a);return b}
function Ac(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-oc(b);a[b]=c}function Bc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0<c;){var e=31-oc(c),f=1<<e;b[e]=0;d[e]=-1;a[e]=-1;c&=~f}}
function Cc(a,b){var c=a.entangledLanes|=b;for(a=a.entanglements;c;){var d=31-oc(c),e=1<<d;e&b|a[d]&b&&(a[d]|=b);c&=~e}}var C=0;function Dc(a){a&=-a;return 1<a?4<a?0!==(a&268435455)?16:536870912:4:1}var Ec,Fc,Gc,Hc,Ic,Jc=!1,Kc=[],Lc=null,Mc=null,Nc=null,Oc=new Map,Pc=new Map,Qc=[],Rc="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");
function Sc(a,b){switch(a){case "focusin":case "focusout":Lc=null;break;case "dragenter":case "dragleave":Mc=null;break;case "mouseover":case "mouseout":Nc=null;break;case "pointerover":case "pointerout":Oc.delete(b.pointerId);break;case "gotpointercapture":case "lostpointercapture":Pc.delete(b.pointerId)}}
function Tc(a,b,c,d,e,f){if(null===a||a.nativeEvent!==f)return a={blockedOn:b,domEventName:c,eventSystemFlags:d,nativeEvent:f,targetContainers:[e]},null!==b&&(b=Cb(b),null!==b&&Fc(b)),a;a.eventSystemFlags|=d;b=a.targetContainers;null!==e&&-1===b.indexOf(e)&&b.push(e);return a}
function Uc(a,b,c,d,e){switch(b){case "focusin":return Lc=Tc(Lc,a,b,c,d,e),!0;case "dragenter":return Mc=Tc(Mc,a,b,c,d,e),!0;case "mouseover":return Nc=Tc(Nc,a,b,c,d,e),!0;case "pointerover":var f=e.pointerId;Oc.set(f,Tc(Oc.get(f)||null,a,b,c,d,e));return!0;case "gotpointercapture":return f=e.pointerId,Pc.set(f,Tc(Pc.get(f)||null,a,b,c,d,e)),!0}return!1}
function Vc(a){var b=Wc(a.target);if(null!==b){var c=Vb(b);if(null!==c)if(b=c.tag,13===b){if(b=Wb(c),null!==b){a.blockedOn=b;Ic(a.priority,function(){Gc(c)});return}}else if(3===b&&c.stateNode.current.memoizedState.isDehydrated){a.blockedOn=3===c.tag?c.stateNode.containerInfo:null;return}}a.blockedOn=null}
function Xc(a){if(null!==a.blockedOn)return!1;for(var b=a.targetContainers;0<b.length;){var c=Yc(a.domEventName,a.eventSystemFlags,b[0],a.nativeEvent);if(null===c){c=a.nativeEvent;var d=new c.constructor(c.type,c);wb=d;c.target.dispatchEvent(d);wb=null}else return b=Cb(c),null!==b&&Fc(b),a.blockedOn=c,!1;b.shift()}return!0}function Zc(a,b,c){Xc(a)&&c.delete(b)}function $c(){Jc=!1;null!==Lc&&Xc(Lc)&&(Lc=null);null!==Mc&&Xc(Mc)&&(Mc=null);null!==Nc&&Xc(Nc)&&(Nc=null);Oc.forEach(Zc);Pc.forEach(Zc)}
function ad(a,b){a.blockedOn===b&&(a.blockedOn=null,Jc||(Jc=!0,ca.unstable_scheduleCallback(ca.unstable_NormalPriority,$c)))}
function bd(a){function b(b){return ad(b,a)}if(0<Kc.length){ad(Kc[0],a);for(var c=1;c<Kc.length;c++){var d=Kc[c];d.blockedOn===a&&(d.blockedOn=null)}}null!==Lc&&ad(Lc,a);null!==Mc&&ad(Mc,a);null!==Nc&&ad(Nc,a);Oc.forEach(b);Pc.forEach(b);for(c=0;c<Qc.length;c++)d=Qc[c],d.blockedOn===a&&(d.blockedOn=null);for(;0<Qc.length&&(c=Qc[0],null===c.blockedOn);)Vc(c),null===c.blockedOn&&Qc.shift()}var cd=ua.ReactCurrentBatchConfig,dd=!0;
function ed(a,b,c,d){var e=C,f=cd.transition;cd.transition=null;try{C=1,fd(a,b,c,d)}finally{C=e,cd.transition=f}}function gd(a,b,c,d){var e=C,f=cd.transition;cd.transition=null;try{C=4,fd(a,b,c,d)}finally{C=e,cd.transition=f}}
function fd(a,b,c,d){if(dd){var e=Yc(a,b,c,d);if(null===e)hd(a,b,d,id,c),Sc(a,d);else if(Uc(e,a,b,c,d))d.stopPropagation();else if(Sc(a,d),b&4&&-1<Rc.indexOf(a)){for(;null!==e;){var f=Cb(e);null!==f&&Ec(f);f=Yc(a,b,c,d);null===f&&hd(a,b,d,id,c);if(f===e)break;e=f}null!==e&&d.stopPropagation()}else hd(a,b,d,null,c)}}var id=null;
function Yc(a,b,c,d){id=null;a=xb(d);a=Wc(a);if(null!==a)if(b=Vb(a),null===b)a=null;else if(c=b.tag,13===c){a=Wb(b);if(null!==a)return a;a=null}else if(3===c){if(b.stateNode.current.memoizedState.isDehydrated)return 3===b.tag?b.stateNode.containerInfo:null;a=null}else b!==a&&(a=null);id=a;return null}
function jd(a){switch(a){case "cancel":case "click":case "close":case "contextmenu":case "copy":case "cut":case "auxclick":case "dblclick":case "dragend":case "dragstart":case "drop":case "focusin":case "focusout":case "input":case "invalid":case "keydown":case "keypress":case "keyup":case "mousedown":case "mouseup":case "paste":case "pause":case "play":case "pointercancel":case "pointerdown":case "pointerup":case "ratechange":case "reset":case "resize":case "seeked":case "submit":case "touchcancel":case "touchend":case "touchstart":case "volumechange":case "change":case "selectionchange":case "textInput":case "compositionstart":case "compositionend":case "compositionupdate":case "beforeblur":case "afterblur":case "beforeinput":case "blur":case "fullscreenchange":case "focus":case "hashchange":case "popstate":case "select":case "selectstart":return 1;case "drag":case "dragenter":case "dragexit":case "dragleave":case "dragover":case "mousemove":case "mouseout":case "mouseover":case "pointermove":case "pointerout":case "pointerover":case "scroll":case "toggle":case "touchmove":case "wheel":case "mouseenter":case "mouseleave":case "pointerenter":case "pointerleave":return 4;
case "message":switch(ec()){case fc:return 1;case gc:return 4;case hc:case ic:return 16;case jc:return 536870912;default:return 16}default:return 16}}var kd=null,ld=null,md=null;function nd(){if(md)return md;var a,b=ld,c=b.length,d,e="value"in kd?kd.value:kd.textContent,f=e.length;for(a=0;a<c&&b[a]===e[a];a++);var g=c-a;for(d=1;d<=g&&b[c-d]===e[f-d];d++);return md=e.slice(a,1<d?1-d:void 0)}
function od(a){var b=a.keyCode;"charCode"in a?(a=a.charCode,0===a&&13===b&&(a=13)):a=b;10===a&&(a=13);return 32<=a||13===a?a:0}function pd(){return!0}function qd(){return!1}
function rd(a){function b(b,d,e,f,g){this._reactName=b;this._targetInst=e;this.type=d;this.nativeEvent=f;this.target=g;this.currentTarget=null;for(var c in a)a.hasOwnProperty(c)&&(b=a[c],this[c]=b?b(f):f[c]);this.isDefaultPrevented=(null!=f.defaultPrevented?f.defaultPrevented:!1===f.returnValue)?pd:qd;this.isPropagationStopped=qd;return this}A(b.prototype,{preventDefault:function(){this.defaultPrevented=!0;var a=this.nativeEvent;a&&(a.preventDefault?a.preventDefault():"unknown"!==typeof a.returnValue&&
(a.returnValue=!1),this.isDefaultPrevented=pd)},stopPropagation:function(){var a=this.nativeEvent;a&&(a.stopPropagation?a.stopPropagation():"unknown"!==typeof a.cancelBubble&&(a.cancelBubble=!0),this.isPropagationStopped=pd)},persist:function(){},isPersistent:pd});return b}
var sd={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(a){return a.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},td=rd(sd),ud=A({},sd,{view:0,detail:0}),vd=rd(ud),wd,xd,yd,Ad=A({},ud,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:zd,button:0,buttons:0,relatedTarget:function(a){return void 0===a.relatedTarget?a.fromElement===a.srcElement?a.toElement:a.fromElement:a.relatedTarget},movementX:function(a){if("movementX"in
a)return a.movementX;a!==yd&&(yd&&"mousemove"===a.type?(wd=a.screenX-yd.screenX,xd=a.screenY-yd.screenY):xd=wd=0,yd=a);return wd},movementY:function(a){return"movementY"in a?a.movementY:xd}}),Bd=rd(Ad),Cd=A({},Ad,{dataTransfer:0}),Dd=rd(Cd),Ed=A({},ud,{relatedTarget:0}),Fd=rd(Ed),Gd=A({},sd,{animationName:0,elapsedTime:0,pseudoElement:0}),Hd=rd(Gd),Id=A({},sd,{clipboardData:function(a){return"clipboardData"in a?a.clipboardData:window.clipboardData}}),Jd=rd(Id),Kd=A({},sd,{data:0}),Ld=rd(Kd),Md={Esc:"Escape",
Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Nd={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",
119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},Od={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Pd(a){var b=this.nativeEvent;return b.getModifierState?b.getModifierState(a):(a=Od[a])?!!b[a]:!1}function zd(){return Pd}
var Qd=A({},ud,{key:function(a){if(a.key){var b=Md[a.key]||a.key;if("Unidentified"!==b)return b}return"keypress"===a.type?(a=od(a),13===a?"Enter":String.fromCharCode(a)):"keydown"===a.type||"keyup"===a.type?Nd[a.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:zd,charCode:function(a){return"keypress"===a.type?od(a):0},keyCode:function(a){return"keydown"===a.type||"keyup"===a.type?a.keyCode:0},which:function(a){return"keypress"===
a.type?od(a):"keydown"===a.type||"keyup"===a.type?a.keyCode:0}}),Rd=rd(Qd),Sd=A({},Ad,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Td=rd(Sd),Ud=A({},ud,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:zd}),Vd=rd(Ud),Wd=A({},sd,{propertyName:0,elapsedTime:0,pseudoElement:0}),Xd=rd(Wd),Yd=A({},Ad,{deltaX:function(a){return"deltaX"in a?a.deltaX:"wheelDeltaX"in a?-a.wheelDeltaX:0},
deltaY:function(a){return"deltaY"in a?a.deltaY:"wheelDeltaY"in a?-a.wheelDeltaY:"wheelDelta"in a?-a.wheelDelta:0},deltaZ:0,deltaMode:0}),Zd=rd(Yd),$d=[9,13,27,32],ae=ia&&"CompositionEvent"in window,be=null;ia&&"documentMode"in document&&(be=document.documentMode);var ce=ia&&"TextEvent"in window&&!be,de=ia&&(!ae||be&&8<be&&11>=be),ee=String.fromCharCode(32),fe=!1;
function ge(a,b){switch(a){case "keyup":return-1!==$d.indexOf(b.keyCode);case "keydown":return 229!==b.keyCode;case "keypress":case "mousedown":case "focusout":return!0;default:return!1}}function he(a){a=a.detail;return"object"===typeof a&&"data"in a?a.data:null}var ie=!1;function je(a,b){switch(a){case "compositionend":return he(b);case "keypress":if(32!==b.which)return null;fe=!0;return ee;case "textInput":return a=b.data,a===ee&&fe?null:a;default:return null}}
function ke(a,b){if(ie)return"compositionend"===a||!ae&&ge(a,b)?(a=nd(),md=ld=kd=null,ie=!1,a):null;switch(a){case "paste":return null;case "keypress":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1<b.char.length)return b.char;if(b.which)return String.fromCharCode(b.which)}return null;case "compositionend":return de&&"ko"!==b.locale?null:b.data;default:return null}}
var le={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function me(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return"input"===b?!!le[a.type]:"textarea"===b?!0:!1}function ne(a,b,c,d){Eb(d);b=oe(b,"onChange");0<b.length&&(c=new td("onChange","change",null,c,d),a.push({event:c,listeners:b}))}var pe=null,qe=null;function re(a){se(a,0)}function te(a){var b=ue(a);if(Wa(b))return a}
function ve(a,b){if("change"===a)return b}var we=!1;if(ia){var xe;if(ia){var ye="oninput"in document;if(!ye){var ze=document.createElement("div");ze.setAttribute("oninput","return;");ye="function"===typeof ze.oninput}xe=ye}else xe=!1;we=xe&&(!document.documentMode||9<document.documentMode)}function Ae(){pe&&(pe.detachEvent("onpropertychange",Be),qe=pe=null)}function Be(a){if("value"===a.propertyName&&te(qe)){var b=[];ne(b,qe,a,xb(a));Jb(re,b)}}
function Ce(a,b,c){"focusin"===a?(Ae(),pe=b,qe=c,pe.attachEvent("onpropertychange",Be)):"focusout"===a&&Ae()}function De(a){if("selectionchange"===a||"keyup"===a||"keydown"===a)return te(qe)}function Ee(a,b){if("click"===a)return te(b)}function Fe(a,b){if("input"===a||"change"===a)return te(b)}function Ge(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var He="function"===typeof Object.is?Object.is:Ge;
function Ie(a,b){if(He(a,b))return!0;if("object"!==typeof a||null===a||"object"!==typeof b||null===b)return!1;var c=Object.keys(a),d=Object.keys(b);if(c.length!==d.length)return!1;for(d=0;d<c.length;d++){var e=c[d];if(!ja.call(b,e)||!He(a[e],b[e]))return!1}return!0}function Je(a){for(;a&&a.firstChild;)a=a.firstChild;return a}
function Ke(a,b){var c=Je(a);a=0;for(var d;c;){if(3===c.nodeType){d=a+c.textContent.length;if(a<=b&&d>=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=Je(c)}}function Le(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Le(a,b.parentNode):"contains"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}
function Me(){for(var a=window,b=Xa();b instanceof a.HTMLIFrameElement;){try{var c="string"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=Xa(a.document)}return b}function Ne(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&("input"===b&&("text"===a.type||"search"===a.type||"tel"===a.type||"url"===a.type||"password"===a.type)||"textarea"===b||"true"===a.contentEditable)}
function Oe(a){var b=Me(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Le(c.ownerDocument.documentElement,c)){if(null!==d&&Ne(c))if(b=d.start,a=d.end,void 0===a&&(a=b),"selectionStart"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Ke(c,f);var g=Ke(c,
d);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)))}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});"function"===typeof c.focus&&c.focus();for(c=0;c<b.length;c++)a=b[c],a.element.scrollLeft=a.left,a.element.scrollTop=a.top}}
var Pe=ia&&"documentMode"in document&&11>=document.documentMode,Qe=null,Re=null,Se=null,Te=!1;
function Ue(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Te||null==Qe||Qe!==Xa(d)||(d=Qe,"selectionStart"in d&&Ne(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Se&&Ie(Se,d)||(Se=d,d=oe(Re,"onSelect"),0<d.length&&(b=new td("onSelect","select",null,b,c),a.push({event:b,listeners:d}),b.target=Qe)))}
function Ve(a,b){var c={};c[a.toLowerCase()]=b.toLowerCase();c["Webkit"+a]="webkit"+b;c["Moz"+a]="moz"+b;return c}var We={animationend:Ve("Animation","AnimationEnd"),animationiteration:Ve("Animation","AnimationIteration"),animationstart:Ve("Animation","AnimationStart"),transitionend:Ve("Transition","TransitionEnd")},Xe={},Ye={};
ia&&(Ye=document.createElement("div").style,"AnimationEvent"in window||(delete We.animationend.animation,delete We.animationiteration.animation,delete We.animationstart.animation),"TransitionEvent"in window||delete We.transitionend.transition);function Ze(a){if(Xe[a])return Xe[a];if(!We[a])return a;var b=We[a],c;for(c in b)if(b.hasOwnProperty(c)&&c in Ye)return Xe[a]=b[c];return a}var $e=Ze("animationend"),af=Ze("animationiteration"),bf=Ze("animationstart"),cf=Ze("transitionend"),df=new Map,ef="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");
function ff(a,b){df.set(a,b);fa(b,[a])}for(var gf=0;gf<ef.length;gf++){var hf=ef[gf],jf=hf.toLowerCase(),kf=hf[0].toUpperCase()+hf.slice(1);ff(jf,"on"+kf)}ff($e,"onAnimationEnd");ff(af,"onAnimationIteration");ff(bf,"onAnimationStart");ff("dblclick","onDoubleClick");ff("focusin","onFocus");ff("focusout","onBlur");ff(cf,"onTransitionEnd");ha("onMouseEnter",["mouseout","mouseover"]);ha("onMouseLeave",["mouseout","mouseover"]);ha("onPointerEnter",["pointerout","pointerover"]);
ha("onPointerLeave",["pointerout","pointerover"]);fa("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));fa("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));fa("onBeforeInput",["compositionend","keypress","textInput","paste"]);fa("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));fa("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));
fa("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var lf="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),mf=new Set("cancel close invalid load scroll toggle".split(" ").concat(lf));
function nf(a,b,c){var d=a.type||"unknown-event";a.currentTarget=c;Ub(d,b,void 0,a);a.currentTarget=null}
function se(a,b){b=0!==(b&4);for(var c=0;c<a.length;c++){var d=a[c],e=d.event;d=d.listeners;a:{var f=void 0;if(b)for(var g=d.length-1;0<=g;g--){var h=d[g],k=h.instance,l=h.currentTarget;h=h.listener;if(k!==f&&e.isPropagationStopped())break a;nf(e,h,l);f=k}else for(g=0;g<d.length;g++){h=d[g];k=h.instance;l=h.currentTarget;h=h.listener;if(k!==f&&e.isPropagationStopped())break a;nf(e,h,l);f=k}}}if(Qb)throw a=Rb,Qb=!1,Rb=null,a;}
function D(a,b){var c=b[of];void 0===c&&(c=b[of]=new Set);var d=a+"__bubble";c.has(d)||(pf(b,a,2,!1),c.add(d))}function qf(a,b,c){var d=0;b&&(d|=4);pf(c,a,d,b)}var rf="_reactListening"+Math.random().toString(36).slice(2);function sf(a){if(!a[rf]){a[rf]=!0;da.forEach(function(b){"selectionchange"!==b&&(mf.has(b)||qf(b,!1,a),qf(b,!0,a))});var b=9===a.nodeType?a:a.ownerDocument;null===b||b[rf]||(b[rf]=!0,qf("selectionchange",!1,b))}}
function pf(a,b,c,d){switch(jd(b)){case 1:var e=ed;break;case 4:e=gd;break;default:e=fd}c=e.bind(null,b,c,a);e=void 0;!Lb||"touchstart"!==b&&"touchmove"!==b&&"wheel"!==b||(e=!0);d?void 0!==e?a.addEventListener(b,c,{capture:!0,passive:e}):a.addEventListener(b,c,!0):void 0!==e?a.addEventListener(b,c,{passive:e}):a.addEventListener(b,c,!1)}
function hd(a,b,c,d,e){var f=d;if(0===(b&1)&&0===(b&2)&&null!==d)a:for(;;){if(null===d)return;var g=d.tag;if(3===g||4===g){var h=d.stateNode.containerInfo;if(h===e||8===h.nodeType&&h.parentNode===e)break;if(4===g)for(g=d.return;null!==g;){var k=g.tag;if(3===k||4===k)if(k=g.stateNode.containerInfo,k===e||8===k.nodeType&&k.parentNode===e)return;g=g.return}for(;null!==h;){g=Wc(h);if(null===g)return;k=g.tag;if(5===k||6===k){d=f=g;continue a}h=h.parentNode}}d=d.return}Jb(function(){var d=f,e=xb(c),g=[];
a:{var h=df.get(a);if(void 0!==h){var k=td,n=a;switch(a){case "keypress":if(0===od(c))break a;case "keydown":case "keyup":k=Rd;break;case "focusin":n="focus";k=Fd;break;case "focusout":n="blur";k=Fd;break;case "beforeblur":case "afterblur":k=Fd;break;case "click":if(2===c.button)break a;case "auxclick":case "dblclick":case "mousedown":case "mousemove":case "mouseup":case "mouseout":case "mouseover":case "contextmenu":k=Bd;break;case "drag":case "dragend":case "dragenter":case "dragexit":case "dragleave":case "dragover":case "dragstart":case "drop":k=
Dd;break;case "touchcancel":case "touchend":case "touchmove":case "touchstart":k=Vd;break;case $e:case af:case bf:k=Hd;break;case cf:k=Xd;break;case "scroll":k=vd;break;case "wheel":k=Zd;break;case "copy":case "cut":case "paste":k=Jd;break;case "gotpointercapture":case "lostpointercapture":case "pointercancel":case "pointerdown":case "pointermove":case "pointerout":case "pointerover":case "pointerup":k=Td}var t=0!==(b&4),J=!t&&"scroll"===a,x=t?null!==h?h+"Capture":null:h;t=[];for(var w=d,u;null!==
w;){u=w;var F=u.stateNode;5===u.tag&&null!==F&&(u=F,null!==x&&(F=Kb(w,x),null!=F&&t.push(tf(w,F,u))));if(J)break;w=w.return}0<t.length&&(h=new k(h,n,null,c,e),g.push({event:h,listeners:t}))}}if(0===(b&7)){a:{h="mouseover"===a||"pointerover"===a;k="mouseout"===a||"pointerout"===a;if(h&&c!==wb&&(n=c.relatedTarget||c.fromElement)&&(Wc(n)||n[uf]))break a;if(k||h){h=e.window===e?e:(h=e.ownerDocument)?h.defaultView||h.parentWindow:window;if(k){if(n=c.relatedTarget||c.toElement,k=d,n=n?Wc(n):null,null!==
n&&(J=Vb(n),n!==J||5!==n.tag&&6!==n.tag))n=null}else k=null,n=d;if(k!==n){t=Bd;F="onMouseLeave";x="onMouseEnter";w="mouse";if("pointerout"===a||"pointerover"===a)t=Td,F="onPointerLeave",x="onPointerEnter",w="pointer";J=null==k?h:ue(k);u=null==n?h:ue(n);h=new t(F,w+"leave",k,c,e);h.target=J;h.relatedTarget=u;F=null;Wc(e)===d&&(t=new t(x,w+"enter",n,c,e),t.target=u,t.relatedTarget=J,F=t);J=F;if(k&&n)b:{t=k;x=n;w=0;for(u=t;u;u=vf(u))w++;u=0;for(F=x;F;F=vf(F))u++;for(;0<w-u;)t=vf(t),w--;for(;0<u-w;)x=
vf(x),u--;for(;w--;){if(t===x||null!==x&&t===x.alternate)break b;t=vf(t);x=vf(x)}t=null}else t=null;null!==k&&wf(g,h,k,t,!1);null!==n&&null!==J&&wf(g,J,n,t,!0)}}}a:{h=d?ue(d):window;k=h.nodeName&&h.nodeName.toLowerCase();if("select"===k||"input"===k&&"file"===h.type)var na=ve;else if(me(h))if(we)na=Fe;else{na=De;var xa=Ce}else(k=h.nodeName)&&"input"===k.toLowerCase()&&("checkbox"===h.type||"radio"===h.type)&&(na=Ee);if(na&&(na=na(a,d))){ne(g,na,c,e);break a}xa&&xa(a,h,d);"focusout"===a&&(xa=h._wrapperState)&&
xa.controlled&&"number"===h.type&&cb(h,"number",h.value)}xa=d?ue(d):window;switch(a){case "focusin":if(me(xa)||"true"===xa.contentEditable)Qe=xa,Re=d,Se=null;break;case "focusout":Se=Re=Qe=null;break;case "mousedown":Te=!0;break;case "contextmenu":case "mouseup":case "dragend":Te=!1;Ue(g,c,e);break;case "selectionchange":if(Pe)break;case "keydown":case "keyup":Ue(g,c,e)}var $a;if(ae)b:{switch(a){case "compositionstart":var ba="onCompositionStart";break b;case "compositionend":ba="onCompositionEnd";
break b;case "compositionupdate":ba="onCompositionUpdate";break b}ba=void 0}else ie?ge(a,c)&&(ba="onCompositionEnd"):"keydown"===a&&229===c.keyCode&&(ba="onCompositionStart");ba&&(de&&"ko"!==c.locale&&(ie||"onCompositionStart"!==ba?"onCompositionEnd"===ba&&ie&&($a=nd()):(kd=e,ld="value"in kd?kd.value:kd.textContent,ie=!0)),xa=oe(d,ba),0<xa.length&&(ba=new Ld(ba,a,null,c,e),g.push({event:ba,listeners:xa}),$a?ba.data=$a:($a=he(c),null!==$a&&(ba.data=$a))));if($a=ce?je(a,c):ke(a,c))d=oe(d,"onBeforeInput"),
0<d.length&&(e=new Ld("onBeforeInput","beforeinput",null,c,e),g.push({event:e,listeners:d}),e.data=$a)}se(g,b)})}function tf(a,b,c){return{instance:a,listener:b,currentTarget:c}}function oe(a,b){for(var c=b+"Capture",d=[];null!==a;){var e=a,f=e.stateNode;5===e.tag&&null!==f&&(e=f,f=Kb(a,c),null!=f&&d.unshift(tf(a,f,e)),f=Kb(a,b),null!=f&&d.push(tf(a,f,e)));a=a.return}return d}function vf(a){if(null===a)return null;do a=a.return;while(a&&5!==a.tag);return a?a:null}
function wf(a,b,c,d,e){for(var f=b._reactName,g=[];null!==c&&c!==d;){var h=c,k=h.alternate,l=h.stateNode;if(null!==k&&k===d)break;5===h.tag&&null!==l&&(h=l,e?(k=Kb(c,f),null!=k&&g.unshift(tf(c,k,h))):e||(k=Kb(c,f),null!=k&&g.push(tf(c,k,h))));c=c.return}0!==g.length&&a.push({event:b,listeners:g})}var xf=/\r\n?/g,yf=/\u0000|\uFFFD/g;function zf(a){return("string"===typeof a?a:""+a).replace(xf,"\n").replace(yf,"")}function Af(a,b,c){b=zf(b);if(zf(a)!==b&&c)throw Error(p(425));}function Bf(){}
var Cf=null,Df=null;function Ef(a,b){return"textarea"===a||"noscript"===a||"string"===typeof b.children||"number"===typeof b.children||"object"===typeof b.dangerouslySetInnerHTML&&null!==b.dangerouslySetInnerHTML&&null!=b.dangerouslySetInnerHTML.__html}
var Ff="function"===typeof setTimeout?setTimeout:void 0,Gf="function"===typeof clearTimeout?clearTimeout:void 0,Hf="function"===typeof Promise?Promise:void 0,Jf="function"===typeof queueMicrotask?queueMicrotask:"undefined"!==typeof Hf?function(a){return Hf.resolve(null).then(a).catch(If)}:Ff;function If(a){setTimeout(function(){throw a;})}
function Kf(a,b){var c=b,d=0;do{var e=c.nextSibling;a.removeChild(c);if(e&&8===e.nodeType)if(c=e.data,"/$"===c){if(0===d){a.removeChild(e);bd(b);return}d--}else"$"!==c&&"$?"!==c&&"$!"!==c||d++;c=e}while(c);bd(b)}function Lf(a){for(;null!=a;a=a.nextSibling){var b=a.nodeType;if(1===b||3===b)break;if(8===b){b=a.data;if("$"===b||"$!"===b||"$?"===b)break;if("/$"===b)return null}}return a}
function Mf(a){a=a.previousSibling;for(var b=0;a;){if(8===a.nodeType){var c=a.data;if("$"===c||"$!"===c||"$?"===c){if(0===b)return a;b--}else"/$"===c&&b++}a=a.previousSibling}return null}var Nf=Math.random().toString(36).slice(2),Of="__reactFiber$"+Nf,Pf="__reactProps$"+Nf,uf="__reactContainer$"+Nf,of="__reactEvents$"+Nf,Qf="__reactListeners$"+Nf,Rf="__reactHandles$"+Nf;
function Wc(a){var b=a[Of];if(b)return b;for(var c=a.parentNode;c;){if(b=c[uf]||c[Of]){c=b.alternate;if(null!==b.child||null!==c&&null!==c.child)for(a=Mf(a);null!==a;){if(c=a[Of])return c;a=Mf(a)}return b}a=c;c=a.parentNode}return null}function Cb(a){a=a[Of]||a[uf];return!a||5!==a.tag&&6!==a.tag&&13!==a.tag&&3!==a.tag?null:a}function ue(a){if(5===a.tag||6===a.tag)return a.stateNode;throw Error(p(33));}function Db(a){return a[Pf]||null}var Sf=[],Tf=-1;function Uf(a){return{current:a}}
function E(a){0>Tf||(a.current=Sf[Tf],Sf[Tf]=null,Tf--)}function G(a,b){Tf++;Sf[Tf]=a.current;a.current=b}var Vf={},H=Uf(Vf),Wf=Uf(!1),Xf=Vf;function Yf(a,b){var c=a.type.contextTypes;if(!c)return Vf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}
function Zf(a){a=a.childContextTypes;return null!==a&&void 0!==a}function $f(){E(Wf);E(H)}function ag(a,b,c){if(H.current!==Vf)throw Error(p(168));G(H,b);G(Wf,c)}function bg(a,b,c){var d=a.stateNode;b=b.childContextTypes;if("function"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(p(108,Ra(a)||"Unknown",e));return A({},c,d)}
function cg(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Vf;Xf=H.current;G(H,a);G(Wf,Wf.current);return!0}function dg(a,b,c){var d=a.stateNode;if(!d)throw Error(p(169));c?(a=bg(a,b,Xf),d.__reactInternalMemoizedMergedChildContext=a,E(Wf),E(H),G(H,a)):E(Wf);G(Wf,c)}var eg=null,fg=!1,gg=!1;function hg(a){null===eg?eg=[a]:eg.push(a)}function ig(a){fg=!0;hg(a)}
function jg(){if(!gg&&null!==eg){gg=!0;var a=0,b=C;try{var c=eg;for(C=1;a<c.length;a++){var d=c[a];do d=d(!0);while(null!==d)}eg=null;fg=!1}catch(e){throw null!==eg&&(eg=eg.slice(a+1)),ac(fc,jg),e;}finally{C=b,gg=!1}}return null}var kg=[],lg=0,mg=null,ng=0,og=[],pg=0,qg=null,rg=1,sg="";function tg(a,b){kg[lg++]=ng;kg[lg++]=mg;mg=a;ng=b}
function ug(a,b,c){og[pg++]=rg;og[pg++]=sg;og[pg++]=qg;qg=a;var d=rg;a=sg;var e=32-oc(d)-1;d&=~(1<<e);c+=1;var f=32-oc(b)+e;if(30<f){var g=e-e%5;f=(d&(1<<g)-1).toString(32);d>>=g;e-=g;rg=1<<32-oc(b)+e|c<<e|d;sg=f+a}else rg=1<<f|c<<e|d,sg=a}function vg(a){null!==a.return&&(tg(a,1),ug(a,1,0))}function wg(a){for(;a===mg;)mg=kg[--lg],kg[lg]=null,ng=kg[--lg],kg[lg]=null;for(;a===qg;)qg=og[--pg],og[pg]=null,sg=og[--pg],og[pg]=null,rg=og[--pg],og[pg]=null}var xg=null,yg=null,I=!1,zg=null;
function Ag(a,b){var c=Bg(5,null,null,0);c.elementType="DELETED";c.stateNode=b;c.return=a;b=a.deletions;null===b?(a.deletions=[c],a.flags|=16):b.push(c)}
function Cg(a,b){switch(a.tag){case 5:var c=a.type;b=1!==b.nodeType||c.toLowerCase()!==b.nodeName.toLowerCase()?null:b;return null!==b?(a.stateNode=b,xg=a,yg=Lf(b.firstChild),!0):!1;case 6:return b=""===a.pendingProps||3!==b.nodeType?null:b,null!==b?(a.stateNode=b,xg=a,yg=null,!0):!1;case 13:return b=8!==b.nodeType?null:b,null!==b?(c=null!==qg?{id:rg,overflow:sg}:null,a.memoizedState={dehydrated:b,treeContext:c,retryLane:1073741824},c=Bg(18,null,null,0),c.stateNode=b,c.return=a,a.child=c,xg=a,yg=
null,!0):!1;default:return!1}}function Dg(a){return 0!==(a.mode&1)&&0===(a.flags&128)}function Eg(a){if(I){var b=yg;if(b){var c=b;if(!Cg(a,b)){if(Dg(a))throw Error(p(418));b=Lf(c.nextSibling);var d=xg;b&&Cg(a,b)?Ag(d,c):(a.flags=a.flags&-4097|2,I=!1,xg=a)}}else{if(Dg(a))throw Error(p(418));a.flags=a.flags&-4097|2;I=!1;xg=a}}}function Fg(a){for(a=a.return;null!==a&&5!==a.tag&&3!==a.tag&&13!==a.tag;)a=a.return;xg=a}
function Gg(a){if(a!==xg)return!1;if(!I)return Fg(a),I=!0,!1;var b;(b=3!==a.tag)&&!(b=5!==a.tag)&&(b=a.type,b="head"!==b&&"body"!==b&&!Ef(a.type,a.memoizedProps));if(b&&(b=yg)){if(Dg(a))throw Hg(),Error(p(418));for(;b;)Ag(a,b),b=Lf(b.nextSibling)}Fg(a);if(13===a.tag){a=a.memoizedState;a=null!==a?a.dehydrated:null;if(!a)throw Error(p(317));a:{a=a.nextSibling;for(b=0;a;){if(8===a.nodeType){var c=a.data;if("/$"===c){if(0===b){yg=Lf(a.nextSibling);break a}b--}else"$"!==c&&"$!"!==c&&"$?"!==c||b++}a=a.nextSibling}yg=
null}}else yg=xg?Lf(a.stateNode.nextSibling):null;return!0}function Hg(){for(var a=yg;a;)a=Lf(a.nextSibling)}function Ig(){yg=xg=null;I=!1}function Jg(a){null===zg?zg=[a]:zg.push(a)}var Kg=ua.ReactCurrentBatchConfig;function Lg(a,b){if(a&&a.defaultProps){b=A({},b);a=a.defaultProps;for(var c in a)void 0===b[c]&&(b[c]=a[c]);return b}return b}var Mg=Uf(null),Ng=null,Og=null,Pg=null;function Qg(){Pg=Og=Ng=null}function Rg(a){var b=Mg.current;E(Mg);a._currentValue=b}
function Sg(a,b,c){for(;null!==a;){var d=a.alternate;(a.childLanes&b)!==b?(a.childLanes|=b,null!==d&&(d.childLanes|=b)):null!==d&&(d.childLanes&b)!==b&&(d.childLanes|=b);if(a===c)break;a=a.return}}function Tg(a,b){Ng=a;Pg=Og=null;a=a.dependencies;null!==a&&null!==a.firstContext&&(0!==(a.lanes&b)&&(Ug=!0),a.firstContext=null)}
function Vg(a){var b=a._currentValue;if(Pg!==a)if(a={context:a,memoizedValue:b,next:null},null===Og){if(null===Ng)throw Error(p(308));Og=a;Ng.dependencies={lanes:0,firstContext:a}}else Og=Og.next=a;return b}var Wg=null;function Xg(a){null===Wg?Wg=[a]:Wg.push(a)}function Yg(a,b,c,d){var e=b.interleaved;null===e?(c.next=c,Xg(b)):(c.next=e.next,e.next=c);b.interleaved=c;return Zg(a,d)}
function Zg(a,b){a.lanes|=b;var c=a.alternate;null!==c&&(c.lanes|=b);c=a;for(a=a.return;null!==a;)a.childLanes|=b,c=a.alternate,null!==c&&(c.childLanes|=b),c=a,a=a.return;return 3===c.tag?c.stateNode:null}var $g=!1;function ah(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}
function bh(a,b){a=a.updateQueue;b.updateQueue===a&&(b.updateQueue={baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,effects:a.effects})}function ch(a,b){return{eventTime:a,lane:b,tag:0,payload:null,callback:null,next:null}}
function dh(a,b,c){var d=a.updateQueue;if(null===d)return null;d=d.shared;if(0!==(K&2)){var e=d.pending;null===e?b.next=b:(b.next=e.next,e.next=b);d.pending=b;return Zg(a,c)}e=d.interleaved;null===e?(b.next=b,Xg(d)):(b.next=e.next,e.next=b);d.interleaved=b;return Zg(a,c)}function eh(a,b,c){b=b.updateQueue;if(null!==b&&(b=b.shared,0!==(c&4194240))){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}
function fh(a,b){var c=a.updateQueue,d=a.alternate;if(null!==d&&(d=d.updateQueue,c===d)){var e=null,f=null;c=c.firstBaseUpdate;if(null!==c){do{var g={eventTime:c.eventTime,lane:c.lane,tag:c.tag,payload:c.payload,callback:c.callback,next:null};null===f?e=f=g:f=f.next=g;c=c.next}while(null!==c);null===f?e=f=b:f=f.next=b}else e=f=b;c={baseState:d.baseState,firstBaseUpdate:e,lastBaseUpdate:f,shared:d.shared,effects:d.effects};a.updateQueue=c;return}a=c.lastBaseUpdate;null===a?c.firstBaseUpdate=b:a.next=
b;c.lastBaseUpdate=b}
function gh(a,b,c,d){var e=a.updateQueue;$g=!1;var f=e.firstBaseUpdate,g=e.lastBaseUpdate,h=e.shared.pending;if(null!==h){e.shared.pending=null;var k=h,l=k.next;k.next=null;null===g?f=l:g.next=l;g=k;var m=a.alternate;null!==m&&(m=m.updateQueue,h=m.lastBaseUpdate,h!==g&&(null===h?m.firstBaseUpdate=l:h.next=l,m.lastBaseUpdate=k))}if(null!==f){var q=e.baseState;g=0;m=l=k=null;h=f;do{var r=h.lane,y=h.eventTime;if((d&r)===r){null!==m&&(m=m.next={eventTime:y,lane:0,tag:h.tag,payload:h.payload,callback:h.callback,
next:null});a:{var n=a,t=h;r=b;y=c;switch(t.tag){case 1:n=t.payload;if("function"===typeof n){q=n.call(y,q,r);break a}q=n;break a;case 3:n.flags=n.flags&-65537|128;case 0:n=t.payload;r="function"===typeof n?n.call(y,q,r):n;if(null===r||void 0===r)break a;q=A({},q,r);break a;case 2:$g=!0}}null!==h.callback&&0!==h.lane&&(a.flags|=64,r=e.effects,null===r?e.effects=[h]:r.push(h))}else y={eventTime:y,lane:r,tag:h.tag,payload:h.payload,callback:h.callback,next:null},null===m?(l=m=y,k=q):m=m.next=y,g|=r;
h=h.next;if(null===h)if(h=e.shared.pending,null===h)break;else r=h,h=r.next,r.next=null,e.lastBaseUpdate=r,e.shared.pending=null}while(1);null===m&&(k=q);e.baseState=k;e.firstBaseUpdate=l;e.lastBaseUpdate=m;b=e.shared.interleaved;if(null!==b){e=b;do g|=e.lane,e=e.next;while(e!==b)}else null===f&&(e.shared.lanes=0);hh|=g;a.lanes=g;a.memoizedState=q}}
function ih(a,b,c){a=b.effects;b.effects=null;if(null!==a)for(b=0;b<a.length;b++){var d=a[b],e=d.callback;if(null!==e){d.callback=null;d=c;if("function"!==typeof e)throw Error(p(191,e));e.call(d)}}}var jh=(new aa.Component).refs;function kh(a,b,c,d){b=a.memoizedState;c=c(d,b);c=null===c||void 0===c?b:A({},b,c);a.memoizedState=c;0===a.lanes&&(a.updateQueue.baseState=c)}
var nh={isMounted:function(a){return(a=a._reactInternals)?Vb(a)===a:!1},enqueueSetState:function(a,b,c){a=a._reactInternals;var d=L(),e=lh(a),f=ch(d,e);f.payload=b;void 0!==c&&null!==c&&(f.callback=c);b=dh(a,f,e);null!==b&&(mh(b,a,e,d),eh(b,a,e))},enqueueReplaceState:function(a,b,c){a=a._reactInternals;var d=L(),e=lh(a),f=ch(d,e);f.tag=1;f.payload=b;void 0!==c&&null!==c&&(f.callback=c);b=dh(a,f,e);null!==b&&(mh(b,a,e,d),eh(b,a,e))},enqueueForceUpdate:function(a,b){a=a._reactInternals;var c=L(),d=
lh(a),e=ch(c,d);e.tag=2;void 0!==b&&null!==b&&(e.callback=b);b=dh(a,e,d);null!==b&&(mh(b,a,d,c),eh(b,a,d))}};function oh(a,b,c,d,e,f,g){a=a.stateNode;return"function"===typeof a.shouldComponentUpdate?a.shouldComponentUpdate(d,f,g):b.prototype&&b.prototype.isPureReactComponent?!Ie(c,d)||!Ie(e,f):!0}
function ph(a,b,c){var d=!1,e=Vf;var f=b.contextType;"object"===typeof f&&null!==f?f=Vg(f):(e=Zf(b)?Xf:H.current,d=b.contextTypes,f=(d=null!==d&&void 0!==d)?Yf(a,e):Vf);b=new b(c,f);a.memoizedState=null!==b.state&&void 0!==b.state?b.state:null;b.updater=nh;a.stateNode=b;b._reactInternals=a;d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=e,a.__reactInternalMemoizedMaskedChildContext=f);return b}
function qh(a,b,c,d){a=b.state;"function"===typeof b.componentWillReceiveProps&&b.componentWillReceiveProps(c,d);"function"===typeof b.UNSAFE_componentWillReceiveProps&&b.UNSAFE_componentWillReceiveProps(c,d);b.state!==a&&nh.enqueueReplaceState(b,b.state,null)}
function rh(a,b,c,d){var e=a.stateNode;e.props=c;e.state=a.memoizedState;e.refs=jh;ah(a);var f=b.contextType;"object"===typeof f&&null!==f?e.context=Vg(f):(f=Zf(b)?Xf:H.current,e.context=Yf(a,f));e.state=a.memoizedState;f=b.getDerivedStateFromProps;"function"===typeof f&&(kh(a,b,f,c),e.state=a.memoizedState);"function"===typeof b.getDerivedStateFromProps||"function"===typeof e.getSnapshotBeforeUpdate||"function"!==typeof e.UNSAFE_componentWillMount&&"function"!==typeof e.componentWillMount||(b=e.state,
"function"===typeof e.componentWillMount&&e.componentWillMount(),"function"===typeof e.UNSAFE_componentWillMount&&e.UNSAFE_componentWillMount(),b!==e.state&&nh.enqueueReplaceState(e,e.state,null),gh(a,c,e,d),e.state=a.memoizedState);"function"===typeof e.componentDidMount&&(a.flags|=4194308)}
function sh(a,b,c){a=c.ref;if(null!==a&&"function"!==typeof a&&"object"!==typeof a){if(c._owner){c=c._owner;if(c){if(1!==c.tag)throw Error(p(309));var d=c.stateNode}if(!d)throw Error(p(147,a));var e=d,f=""+a;if(null!==b&&null!==b.ref&&"function"===typeof b.ref&&b.ref._stringRef===f)return b.ref;b=function(a){var b=e.refs;b===jh&&(b=e.refs={});null===a?delete b[f]:b[f]=a};b._stringRef=f;return b}if("string"!==typeof a)throw Error(p(284));if(!c._owner)throw Error(p(290,a));}return a}
function th(a,b){a=Object.prototype.toString.call(b);throw Error(p(31,"[object Object]"===a?"object with keys {"+Object.keys(b).join(", ")+"}":a));}function uh(a){var b=a._init;return b(a._payload)}
function vh(a){function b(b,c){if(a){var d=b.deletions;null===d?(b.deletions=[c],b.flags|=16):d.push(c)}}function c(c,d){if(!a)return null;for(;null!==d;)b(c,d),d=d.sibling;return null}function d(a,b){for(a=new Map;null!==b;)null!==b.key?a.set(b.key,b):a.set(b.index,b),b=b.sibling;return a}function e(a,b){a=wh(a,b);a.index=0;a.sibling=null;return a}function f(b,c,d){b.index=d;if(!a)return b.flags|=1048576,c;d=b.alternate;if(null!==d)return d=d.index,d<c?(b.flags|=2,c):d;b.flags|=2;return c}function g(b){a&&
null===b.alternate&&(b.flags|=2);return b}function h(a,b,c,d){if(null===b||6!==b.tag)return b=xh(c,a.mode,d),b.return=a,b;b=e(b,c);b.return=a;return b}function k(a,b,c,d){var f=c.type;if(f===ya)return m(a,b,c.props.children,d,c.key);if(null!==b&&(b.elementType===f||"object"===typeof f&&null!==f&&f.$$typeof===Ha&&uh(f)===b.type))return d=e(b,c.props),d.ref=sh(a,b,c),d.return=a,d;d=yh(c.type,c.key,c.props,null,a.mode,d);d.ref=sh(a,b,c);d.return=a;return d}function l(a,b,c,d){if(null===b||4!==b.tag||
b.stateNode.containerInfo!==c.containerInfo||b.stateNode.implementation!==c.implementation)return b=zh(c,a.mode,d),b.return=a,b;b=e(b,c.children||[]);b.return=a;return b}function m(a,b,c,d,f){if(null===b||7!==b.tag)return b=Ah(c,a.mode,d,f),b.return=a,b;b=e(b,c);b.return=a;return b}function q(a,b,c){if("string"===typeof b&&""!==b||"number"===typeof b)return b=xh(""+b,a.mode,c),b.return=a,b;if("object"===typeof b&&null!==b){switch(b.$$typeof){case va:return c=yh(b.type,b.key,b.props,null,a.mode,c),
c.ref=sh(a,null,b),c.return=a,c;case wa:return b=zh(b,a.mode,c),b.return=a,b;case Ha:var d=b._init;return q(a,d(b._payload),c)}if(eb(b)||Ka(b))return b=Ah(b,a.mode,c,null),b.return=a,b;th(a,b)}return null}function r(a,b,c,d){var e=null!==b?b.key:null;if("string"===typeof c&&""!==c||"number"===typeof c)return null!==e?null:h(a,b,""+c,d);if("object"===typeof c&&null!==c){switch(c.$$typeof){case va:return c.key===e?k(a,b,c,d):null;case wa:return c.key===e?l(a,b,c,d):null;case Ha:return e=c._init,r(a,
b,e(c._payload),d)}if(eb(c)||Ka(c))return null!==e?null:m(a,b,c,d,null);th(a,c)}return null}function y(a,b,c,d,e){if("string"===typeof d&&""!==d||"number"===typeof d)return a=a.get(c)||null,h(b,a,""+d,e);if("object"===typeof d&&null!==d){switch(d.$$typeof){case va:return a=a.get(null===d.key?c:d.key)||null,k(b,a,d,e);case wa:return a=a.get(null===d.key?c:d.key)||null,l(b,a,d,e);case Ha:var f=d._init;return y(a,b,c,f(d._payload),e)}if(eb(d)||Ka(d))return a=a.get(c)||null,m(b,a,d,e,null);th(b,d)}return null}
function n(e,g,h,k){for(var l=null,m=null,u=g,w=g=0,x=null;null!==u&&w<h.length;w++){u.index>w?(x=u,u=null):x=u.sibling;var n=r(e,u,h[w],k);if(null===n){null===u&&(u=x);break}a&&u&&null===n.alternate&&b(e,u);g=f(n,g,w);null===m?l=n:m.sibling=n;m=n;u=x}if(w===h.length)return c(e,u),I&&tg(e,w),l;if(null===u){for(;w<h.length;w++)u=q(e,h[w],k),null!==u&&(g=f(u,g,w),null===m?l=u:m.sibling=u,m=u);I&&tg(e,w);return l}for(u=d(e,u);w<h.length;w++)x=y(u,e,w,h[w],k),null!==x&&(a&&null!==x.alternate&&u.delete(null===
x.key?w:x.key),g=f(x,g,w),null===m?l=x:m.sibling=x,m=x);a&&u.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function t(e,g,h,k){var l=Ka(h);if("function"!==typeof l)throw Error(p(150));h=l.call(h);if(null==h)throw Error(p(151));for(var u=l=null,m=g,w=g=0,x=null,n=h.next();null!==m&&!n.done;w++,n=h.next()){m.index>w?(x=m,m=null):x=m.sibling;var t=r(e,m,n.value,k);if(null===t){null===m&&(m=x);break}a&&m&&null===t.alternate&&b(e,m);g=f(t,g,w);null===u?l=t:u.sibling=t;u=t;m=x}if(n.done)return c(e,
m),I&&tg(e,w),l;if(null===m){for(;!n.done;w++,n=h.next())n=q(e,n.value,k),null!==n&&(g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);I&&tg(e,w);return l}for(m=d(e,m);!n.done;w++,n=h.next())n=y(m,e,w,n.value,k),null!==n&&(a&&null!==n.alternate&&m.delete(null===n.key?w:n.key),g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);a&&m.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function J(a,d,f,h){"object"===typeof f&&null!==f&&f.type===ya&&null===f.key&&(f=f.props.children);if("object"===typeof f&&null!==f){switch(f.$$typeof){case va:a:{for(var k=
f.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ya){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||"object"===typeof k&&null!==k&&k.$$typeof===Ha&&uh(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=sh(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling}f.type===ya?(d=Ah(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=yh(f.type,f.key,f.props,null,a.mode,h),h.ref=sh(a,d,f),h.return=a,a=h)}return g(a);case wa:a:{for(l=f.key;null!==
d;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=zh(f,a.mode,h);d.return=a;a=d}return g(a);case Ha:return l=f._init,J(a,d,l(f._payload),h)}if(eb(f))return n(a,d,f,h);if(Ka(f))return t(a,d,f,h);th(a,f)}return"string"===typeof f&&""!==f||"number"===typeof f?(f=""+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):
(c(a,d),d=xh(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return J}var Bh=vh(!0),Ch=vh(!1),Dh={},Eh=Uf(Dh),Fh=Uf(Dh),Gh=Uf(Dh);function Hh(a){if(a===Dh)throw Error(p(174));return a}function Ih(a,b){G(Gh,b);G(Fh,a);G(Eh,Dh);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:lb(null,"");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=lb(b,a)}E(Eh);G(Eh,b)}function Jh(){E(Eh);E(Fh);E(Gh)}
function Kh(a){Hh(Gh.current);var b=Hh(Eh.current);var c=lb(b,a.type);b!==c&&(G(Fh,a),G(Eh,c))}function Lh(a){Fh.current===a&&(E(Eh),E(Fh))}var M=Uf(0);
function Mh(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||"$?"===c.data||"$!"===c.data))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.flags&128))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return;b=b.sibling}return null}var Nh=[];
function Oh(){for(var a=0;a<Nh.length;a++)Nh[a]._workInProgressVersionPrimary=null;Nh.length=0}var Ph=ua.ReactCurrentDispatcher,Qh=ua.ReactCurrentBatchConfig,Rh=0,N=null,O=null,P=null,Sh=!1,Th=!1,Uh=0,Vh=0;function Q(){throw Error(p(321));}function Wh(a,b){if(null===b)return!1;for(var c=0;c<b.length&&c<a.length;c++)if(!He(a[c],b[c]))return!1;return!0}
function Xh(a,b,c,d,e,f){Rh=f;N=b;b.memoizedState=null;b.updateQueue=null;b.lanes=0;Ph.current=null===a||null===a.memoizedState?Yh:Zh;a=c(d,e);if(Th){f=0;do{Th=!1;Uh=0;if(25<=f)throw Error(p(301));f+=1;P=O=null;b.updateQueue=null;Ph.current=$h;a=c(d,e)}while(Th)}Ph.current=ai;b=null!==O&&null!==O.next;Rh=0;P=O=N=null;Sh=!1;if(b)throw Error(p(300));return a}function bi(){var a=0!==Uh;Uh=0;return a}
function ci(){var a={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};null===P?N.memoizedState=P=a:P=P.next=a;return P}function di(){if(null===O){var a=N.alternate;a=null!==a?a.memoizedState:null}else a=O.next;var b=null===P?N.memoizedState:P.next;if(null!==b)P=b,O=a;else{if(null===a)throw Error(p(310));O=a;a={memoizedState:O.memoizedState,baseState:O.baseState,baseQueue:O.baseQueue,queue:O.queue,next:null};null===P?N.memoizedState=P=a:P=P.next=a}return P}
function ei(a,b){return"function"===typeof b?b(a):b}
function fi(a){var b=di(),c=b.queue;if(null===c)throw Error(p(311));c.lastRenderedReducer=a;var d=O,e=d.baseQueue,f=c.pending;if(null!==f){if(null!==e){var g=e.next;e.next=f.next;f.next=g}d.baseQueue=e=f;c.pending=null}if(null!==e){f=e.next;d=d.baseState;var h=g=null,k=null,l=f;do{var m=l.lane;if((Rh&m)===m)null!==k&&(k=k.next={lane:0,action:l.action,hasEagerState:l.hasEagerState,eagerState:l.eagerState,next:null}),d=l.hasEagerState?l.eagerState:a(d,l.action);else{var q={lane:m,action:l.action,hasEagerState:l.hasEagerState,
eagerState:l.eagerState,next:null};null===k?(h=k=q,g=d):k=k.next=q;N.lanes|=m;hh|=m}l=l.next}while(null!==l&&l!==f);null===k?g=d:k.next=h;He(d,b.memoizedState)||(Ug=!0);b.memoizedState=d;b.baseState=g;b.baseQueue=k;c.lastRenderedState=d}a=c.interleaved;if(null!==a){e=a;do f=e.lane,N.lanes|=f,hh|=f,e=e.next;while(e!==a)}else null===e&&(c.lanes=0);return[b.memoizedState,c.dispatch]}
function gi(a){var b=di(),c=b.queue;if(null===c)throw Error(p(311));c.lastRenderedReducer=a;var d=c.dispatch,e=c.pending,f=b.memoizedState;if(null!==e){c.pending=null;var g=e=e.next;do f=a(f,g.action),g=g.next;while(g!==e);He(f,b.memoizedState)||(Ug=!0);b.memoizedState=f;null===b.baseQueue&&(b.baseState=f);c.lastRenderedState=f}return[f,d]}function hi(){}
function ii(a,b){var c=N,d=di(),e=b(),f=!He(d.memoizedState,e);f&&(d.memoizedState=e,Ug=!0);d=d.queue;ji(ki.bind(null,c,d,a),[a]);if(d.getSnapshot!==b||f||null!==P&&P.memoizedState.tag&1){c.flags|=2048;li(9,mi.bind(null,c,d,e,b),void 0,null);if(null===R)throw Error(p(349));0!==(Rh&30)||ni(c,b,e)}return e}function ni(a,b,c){a.flags|=16384;a={getSnapshot:b,value:c};b=N.updateQueue;null===b?(b={lastEffect:null,stores:null},N.updateQueue=b,b.stores=[a]):(c=b.stores,null===c?b.stores=[a]:c.push(a))}
function mi(a,b,c,d){b.value=c;b.getSnapshot=d;oi(b)&&pi(a)}function ki(a,b,c){return c(function(){oi(b)&&pi(a)})}function oi(a){var b=a.getSnapshot;a=a.value;try{var c=b();return!He(a,c)}catch(d){return!0}}function pi(a){var b=Zg(a,1);null!==b&&mh(b,a,1,-1)}
function qi(a){var b=ci();"function"===typeof a&&(a=a());b.memoizedState=b.baseState=a;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:ei,lastRenderedState:a};b.queue=a;a=a.dispatch=ri.bind(null,N,a);return[b.memoizedState,a]}
function li(a,b,c,d){a={tag:a,create:b,destroy:c,deps:d,next:null};b=N.updateQueue;null===b?(b={lastEffect:null,stores:null},N.updateQueue=b,b.lastEffect=a.next=a):(c=b.lastEffect,null===c?b.lastEffect=a.next=a:(d=c.next,c.next=a,a.next=d,b.lastEffect=a));return a}function si(){return di().memoizedState}function ti(a,b,c,d){var e=ci();N.flags|=a;e.memoizedState=li(1|b,c,void 0,void 0===d?null:d)}
function ui(a,b,c,d){var e=di();d=void 0===d?null:d;var f=void 0;if(null!==O){var g=O.memoizedState;f=g.destroy;if(null!==d&&Wh(d,g.deps)){e.memoizedState=li(b,c,f,d);return}}N.flags|=a;e.memoizedState=li(1|b,c,f,d)}function vi(a,b){return ti(8390656,8,a,b)}function ji(a,b){return ui(2048,8,a,b)}function wi(a,b){return ui(4,2,a,b)}function xi(a,b){return ui(4,4,a,b)}
function yi(a,b){if("function"===typeof b)return a=a(),b(a),function(){b(null)};if(null!==b&&void 0!==b)return a=a(),b.current=a,function(){b.current=null}}function zi(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ui(4,4,yi.bind(null,b,a),c)}function Ai(){}function Bi(a,b){var c=di();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&Wh(b,d[1]))return d[0];c.memoizedState=[a,b];return a}
function Ci(a,b){var c=di();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&Wh(b,d[1]))return d[0];a=a();c.memoizedState=[a,b];return a}function Di(a,b,c){if(0===(Rh&21))return a.baseState&&(a.baseState=!1,Ug=!0),a.memoizedState=c;He(c,b)||(c=yc(),N.lanes|=c,hh|=c,a.baseState=!0);return b}function Ei(a,b){var c=C;C=0!==c&&4>c?c:4;a(!0);var d=Qh.transition;Qh.transition={};try{a(!1),b()}finally{C=c,Qh.transition=d}}function Fi(){return di().memoizedState}
function Gi(a,b,c){var d=lh(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,c);else if(c=Yg(a,b,c,d),null!==c){var e=L();mh(c,a,d,e);Ji(c,b,d)}}
function ri(a,b,c){var d=lh(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,e);else{var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(He(h,g)){var k=b.interleaved;null===k?(e.next=e,Xg(b)):(e.next=k.next,k.next=e);b.interleaved=e;return}}catch(l){}finally{}c=Yg(a,b,e,d);null!==c&&(e=L(),mh(c,a,d,e),Ji(c,b,d))}}
function Hi(a){var b=a.alternate;return a===N||null!==b&&b===N}function Ii(a,b){Th=Sh=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b}function Ji(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}
var ai={readContext:Vg,useCallback:Q,useContext:Q,useEffect:Q,useImperativeHandle:Q,useInsertionEffect:Q,useLayoutEffect:Q,useMemo:Q,useReducer:Q,useRef:Q,useState:Q,useDebugValue:Q,useDeferredValue:Q,useTransition:Q,useMutableSource:Q,useSyncExternalStore:Q,useId:Q,unstable_isNewReconciler:!1},Yh={readContext:Vg,useCallback:function(a,b){ci().memoizedState=[a,void 0===b?null:b];return a},useContext:Vg,useEffect:vi,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ti(4194308,
4,yi.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ti(4194308,4,a,b)},useInsertionEffect:function(a,b){return ti(4,2,a,b)},useMemo:function(a,b){var c=ci();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=ci();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=Gi.bind(null,N,a);return[d.memoizedState,a]},useRef:function(a){var b=
ci();a={current:a};return b.memoizedState=a},useState:qi,useDebugValue:Ai,useDeferredValue:function(a){return ci().memoizedState=a},useTransition:function(){var a=qi(!1),b=a[0];a=Ei.bind(null,a[1]);ci().memoizedState=a;return[b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=N,e=ci();if(I){if(void 0===c)throw Error(p(407));c=c()}else{c=b();if(null===R)throw Error(p(349));0!==(Rh&30)||ni(d,b,c)}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;vi(ki.bind(null,d,
f,a),[a]);d.flags|=2048;li(9,mi.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=ci(),b=R.identifierPrefix;if(I){var c=sg;var d=rg;c=(d&~(1<<32-oc(d)-1)).toString(32)+c;b=":"+b+"R"+c;c=Uh++;0<c&&(b+="H"+c.toString(32));b+=":"}else c=Vh++,b=":"+b+"r"+c.toString(32)+":";return a.memoizedState=b},unstable_isNewReconciler:!1},Zh={readContext:Vg,useCallback:Bi,useContext:Vg,useEffect:ji,useImperativeHandle:zi,useInsertionEffect:wi,useLayoutEffect:xi,useMemo:Ci,useReducer:fi,useRef:si,useState:function(){return fi(ei)},
useDebugValue:Ai,useDeferredValue:function(a){var b=di();return Di(b,O.memoizedState,a)},useTransition:function(){var a=fi(ei)[0],b=di().memoizedState;return[a,b]},useMutableSource:hi,useSyncExternalStore:ii,useId:Fi,unstable_isNewReconciler:!1},$h={readContext:Vg,useCallback:Bi,useContext:Vg,useEffect:ji,useImperativeHandle:zi,useInsertionEffect:wi,useLayoutEffect:xi,useMemo:Ci,useReducer:gi,useRef:si,useState:function(){return gi(ei)},useDebugValue:Ai,useDeferredValue:function(a){var b=di();return null===
O?b.memoizedState=a:Di(b,O.memoizedState,a)},useTransition:function(){var a=gi(ei)[0],b=di().memoizedState;return[a,b]},useMutableSource:hi,useSyncExternalStore:ii,useId:Fi,unstable_isNewReconciler:!1};function Ki(a,b){try{var c="",d=b;do c+=Pa(d),d=d.return;while(d);var e=c}catch(f){e="\nError generating stack: "+f.message+"\n"+f.stack}return{value:a,source:b,stack:e,digest:null}}function Li(a,b,c){return{value:a,source:null,stack:null!=c?c:null,digest:null!=b?b:null}}
function Mi(a,b){try{console.error(b.value)}catch(c){setTimeout(function(){throw c;})}}var Ni="function"===typeof WeakMap?WeakMap:Map;function Oi(a,b,c){c=ch(-1,c);c.tag=3;c.payload={element:null};var d=b.value;c.callback=function(){Pi||(Pi=!0,Qi=d);Mi(a,b)};return c}
function Ri(a,b,c){c=ch(-1,c);c.tag=3;var d=a.type.getDerivedStateFromError;if("function"===typeof d){var e=b.value;c.payload=function(){return d(e)};c.callback=function(){Mi(a,b)}}var f=a.stateNode;null!==f&&"function"===typeof f.componentDidCatch&&(c.callback=function(){Mi(a,b);"function"!==typeof d&&(null===Si?Si=new Set([this]):Si.add(this));var c=b.stack;this.componentDidCatch(b.value,{componentStack:null!==c?c:""})});return c}
function Ti(a,b,c){var d=a.pingCache;if(null===d){d=a.pingCache=new Ni;var e=new Set;d.set(b,e)}else e=d.get(b),void 0===e&&(e=new Set,d.set(b,e));e.has(c)||(e.add(c),a=Ui.bind(null,a,b,c),b.then(a,a))}function Vi(a){do{var b;if(b=13===a.tag)b=a.memoizedState,b=null!==b?null!==b.dehydrated?!0:!1:!0;if(b)return a;a=a.return}while(null!==a);return null}
function Wi(a,b,c,d,e){if(0===(a.mode&1))return a===b?a.flags|=65536:(a.flags|=128,c.flags|=131072,c.flags&=-52805,1===c.tag&&(null===c.alternate?c.tag=17:(b=ch(-1,1),b.tag=2,dh(c,b,1))),c.lanes|=1),a;a.flags|=65536;a.lanes=e;return a}var Xi=ua.ReactCurrentOwner,Ug=!1;function Yi(a,b,c,d){b.child=null===a?Ch(b,null,c,d):Bh(b,a.child,c,d)}
function Zi(a,b,c,d,e){c=c.render;var f=b.ref;Tg(b,e);d=Xh(a,b,c,d,f,e);c=bi();if(null!==a&&!Ug)return b.updateQueue=a.updateQueue,b.flags&=-2053,a.lanes&=~e,$i(a,b,e);I&&c&&vg(b);b.flags|=1;Yi(a,b,d,e);return b.child}
function aj(a,b,c,d,e){if(null===a){var f=c.type;if("function"===typeof f&&!bj(f)&&void 0===f.defaultProps&&null===c.compare&&void 0===c.defaultProps)return b.tag=15,b.type=f,cj(a,b,f,d,e);a=yh(c.type,null,d,b,b.mode,e);a.ref=b.ref;a.return=b;return b.child=a}f=a.child;if(0===(a.lanes&e)){var g=f.memoizedProps;c=c.compare;c=null!==c?c:Ie;if(c(g,d)&&a.ref===b.ref)return $i(a,b,e)}b.flags|=1;a=wh(f,d);a.ref=b.ref;a.return=b;return b.child=a}
function cj(a,b,c,d,e){if(null!==a){var f=a.memoizedProps;if(Ie(f,d)&&a.ref===b.ref)if(Ug=!1,b.pendingProps=d=f,0!==(a.lanes&e))0!==(a.flags&131072)&&(Ug=!0);else return b.lanes=a.lanes,$i(a,b,e)}return dj(a,b,c,d,e)}
function ej(a,b,c){var d=b.pendingProps,e=d.children,f=null!==a?a.memoizedState:null;if("hidden"===d.mode)if(0===(b.mode&1))b.memoizedState={baseLanes:0,cachePool:null,transitions:null},G(fj,gj),gj|=c;else{if(0===(c&1073741824))return a=null!==f?f.baseLanes|c:c,b.lanes=b.childLanes=1073741824,b.memoizedState={baseLanes:a,cachePool:null,transitions:null},b.updateQueue=null,G(fj,gj),gj|=a,null;b.memoizedState={baseLanes:0,cachePool:null,transitions:null};d=null!==f?f.baseLanes:c;G(fj,gj);gj|=d}else null!==
f?(d=f.baseLanes|c,b.memoizedState=null):d=c,G(fj,gj),gj|=d;Yi(a,b,e,c);return b.child}function hj(a,b){var c=b.ref;if(null===a&&null!==c||null!==a&&a.ref!==c)b.flags|=512,b.flags|=2097152}function dj(a,b,c,d,e){var f=Zf(c)?Xf:H.current;f=Yf(b,f);Tg(b,e);c=Xh(a,b,c,d,f,e);d=bi();if(null!==a&&!Ug)return b.updateQueue=a.updateQueue,b.flags&=-2053,a.lanes&=~e,$i(a,b,e);I&&d&&vg(b);b.flags|=1;Yi(a,b,c,e);return b.child}
function ij(a,b,c,d,e){if(Zf(c)){var f=!0;cg(b)}else f=!1;Tg(b,e);if(null===b.stateNode)jj(a,b),ph(b,c,d),rh(b,c,d,e),d=!0;else if(null===a){var g=b.stateNode,h=b.memoizedProps;g.props=h;var k=g.context,l=c.contextType;"object"===typeof l&&null!==l?l=Vg(l):(l=Zf(c)?Xf:H.current,l=Yf(b,l));var m=c.getDerivedStateFromProps,q="function"===typeof m||"function"===typeof g.getSnapshotBeforeUpdate;q||"function"!==typeof g.UNSAFE_componentWillReceiveProps&&"function"!==typeof g.componentWillReceiveProps||
(h!==d||k!==l)&&qh(b,g,d,l);$g=!1;var r=b.memoizedState;g.state=r;gh(b,d,g,e);k=b.memoizedState;h!==d||r!==k||Wf.current||$g?("function"===typeof m&&(kh(b,c,m,d),k=b.memoizedState),(h=$g||oh(b,c,h,d,r,k,l))?(q||"function"!==typeof g.UNSAFE_componentWillMount&&"function"!==typeof g.componentWillMount||("function"===typeof g.componentWillMount&&g.componentWillMount(),"function"===typeof g.UNSAFE_componentWillMount&&g.UNSAFE_componentWillMount()),"function"===typeof g.componentDidMount&&(b.flags|=4194308)):
("function"===typeof g.componentDidMount&&(b.flags|=4194308),b.memoizedProps=d,b.memoizedState=k),g.props=d,g.state=k,g.context=l,d=h):("function"===typeof g.componentDidMount&&(b.flags|=4194308),d=!1)}else{g=b.stateNode;bh(a,b);h=b.memoizedProps;l=b.type===b.elementType?h:Lg(b.type,h);g.props=l;q=b.pendingProps;r=g.context;k=c.contextType;"object"===typeof k&&null!==k?k=Vg(k):(k=Zf(c)?Xf:H.current,k=Yf(b,k));var y=c.getDerivedStateFromProps;(m="function"===typeof y||"function"===typeof g.getSnapshotBeforeUpdate)||
"function"!==typeof g.UNSAFE_componentWillReceiveProps&&"function"!==typeof g.componentWillReceiveProps||(h!==q||r!==k)&&qh(b,g,d,k);$g=!1;r=b.memoizedState;g.state=r;gh(b,d,g,e);var n=b.memoizedState;h!==q||r!==n||Wf.current||$g?("function"===typeof y&&(kh(b,c,y,d),n=b.memoizedState),(l=$g||oh(b,c,l,d,r,n,k)||!1)?(m||"function"!==typeof g.UNSAFE_componentWillUpdate&&"function"!==typeof g.componentWillUpdate||("function"===typeof g.componentWillUpdate&&g.componentWillUpdate(d,n,k),"function"===typeof g.UNSAFE_componentWillUpdate&&
g.UNSAFE_componentWillUpdate(d,n,k)),"function"===typeof g.componentDidUpdate&&(b.flags|=4),"function"===typeof g.getSnapshotBeforeUpdate&&(b.flags|=1024)):("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=1024),b.memoizedProps=d,b.memoizedState=n),g.props=d,g.state=n,g.context=k,d=l):("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&r===
a.memoizedState||(b.flags|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&r===a.memoizedState||(b.flags|=1024),d=!1)}return kj(a,b,c,d,f,e)}
function kj(a,b,c,d,e,f){hj(a,b);var g=0!==(b.flags&128);if(!d&&!g)return e&&dg(b,c,!1),$i(a,b,f);d=b.stateNode;Xi.current=b;var h=g&&"function"!==typeof c.getDerivedStateFromError?null:d.render();b.flags|=1;null!==a&&g?(b.child=Bh(b,a.child,null,f),b.child=Bh(b,null,h,f)):Yi(a,b,h,f);b.memoizedState=d.state;e&&dg(b,c,!0);return b.child}function lj(a){var b=a.stateNode;b.pendingContext?ag(a,b.pendingContext,b.pendingContext!==b.context):b.context&&ag(a,b.context,!1);Ih(a,b.containerInfo)}
function mj(a,b,c,d,e){Ig();Jg(e);b.flags|=256;Yi(a,b,c,d);return b.child}var nj={dehydrated:null,treeContext:null,retryLane:0};function oj(a){return{baseLanes:a,cachePool:null,transitions:null}}
function pj(a,b,c){var d=b.pendingProps,e=M.current,f=!1,g=0!==(b.flags&128),h;(h=g)||(h=null!==a&&null===a.memoizedState?!1:0!==(e&2));if(h)f=!0,b.flags&=-129;else if(null===a||null!==a.memoizedState)e|=1;G(M,e&1);if(null===a){Eg(b);a=b.memoizedState;if(null!==a&&(a=a.dehydrated,null!==a))return 0===(b.mode&1)?b.lanes=1:"$!"===a.data?b.lanes=8:b.lanes=1073741824,null;g=d.children;a=d.fallback;return f?(d=b.mode,f=b.child,g={mode:"hidden",children:g},0===(d&1)&&null!==f?(f.childLanes=0,f.pendingProps=
g):f=qj(g,d,0,null),a=Ah(a,d,c,null),f.return=b,a.return=b,f.sibling=a,b.child=f,b.child.memoizedState=oj(c),b.memoizedState=nj,a):rj(b,g)}e=a.memoizedState;if(null!==e&&(h=e.dehydrated,null!==h))return sj(a,b,g,d,h,e,c);if(f){f=d.fallback;g=b.mode;e=a.child;h=e.sibling;var k={mode:"hidden",children:d.children};0===(g&1)&&b.child!==e?(d=b.child,d.childLanes=0,d.pendingProps=k,b.deletions=null):(d=wh(e,k),d.subtreeFlags=e.subtreeFlags&14680064);null!==h?f=wh(h,f):(f=Ah(f,g,c,null),f.flags|=2);f.return=
b;d.return=b;d.sibling=f;b.child=d;d=f;f=b.child;g=a.child.memoizedState;g=null===g?oj(c):{baseLanes:g.baseLanes|c,cachePool:null,transitions:g.transitions};f.memoizedState=g;f.childLanes=a.childLanes&~c;b.memoizedState=nj;return d}f=a.child;a=f.sibling;d=wh(f,{mode:"visible",children:d.children});0===(b.mode&1)&&(d.lanes=c);d.return=b;d.sibling=null;null!==a&&(c=b.deletions,null===c?(b.deletions=[a],b.flags|=16):c.push(a));b.child=d;b.memoizedState=null;return d}
function rj(a,b){b=qj({mode:"visible",children:b},a.mode,0,null);b.return=a;return a.child=b}function tj(a,b,c,d){null!==d&&Jg(d);Bh(b,a.child,null,c);a=rj(b,b.pendingProps.children);a.flags|=2;b.memoizedState=null;return a}
function sj(a,b,c,d,e,f,g){if(c){if(b.flags&256)return b.flags&=-257,d=Li(Error(p(422))),tj(a,b,g,d);if(null!==b.memoizedState)return b.child=a.child,b.flags|=128,null;f=d.fallback;e=b.mode;d=qj({mode:"visible",children:d.children},e,0,null);f=Ah(f,e,g,null);f.flags|=2;d.return=b;f.return=b;d.sibling=f;b.child=d;0!==(b.mode&1)&&Bh(b,a.child,null,g);b.child.memoizedState=oj(g);b.memoizedState=nj;return f}if(0===(b.mode&1))return tj(a,b,g,null);if("$!"===e.data){d=e.nextSibling&&e.nextSibling.dataset;
if(d)var h=d.dgst;d=h;f=Error(p(419));d=Li(f,d,void 0);return tj(a,b,g,d)}h=0!==(g&a.childLanes);if(Ug||h){d=R;if(null!==d){switch(g&-g){case 4:e=2;break;case 16:e=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:e=32;break;case 536870912:e=268435456;break;default:e=0}e=0!==(e&(d.suspendedLanes|g))?0:e;
0!==e&&e!==f.retryLane&&(f.retryLane=e,Zg(a,e),mh(d,a,e,-1))}uj();d=Li(Error(p(421)));return tj(a,b,g,d)}if("$?"===e.data)return b.flags|=128,b.child=a.child,b=vj.bind(null,a),e._reactRetry=b,null;a=f.treeContext;yg=Lf(e.nextSibling);xg=b;I=!0;zg=null;null!==a&&(og[pg++]=rg,og[pg++]=sg,og[pg++]=qg,rg=a.id,sg=a.overflow,qg=b);b=rj(b,d.children);b.flags|=4096;return b}function wj(a,b,c){a.lanes|=b;var d=a.alternate;null!==d&&(d.lanes|=b);Sg(a.return,b,c)}
function xj(a,b,c,d,e){var f=a.memoizedState;null===f?a.memoizedState={isBackwards:b,rendering:null,renderingStartTime:0,last:d,tail:c,tailMode:e}:(f.isBackwards=b,f.rendering=null,f.renderingStartTime=0,f.last=d,f.tail=c,f.tailMode=e)}
function yj(a,b,c){var d=b.pendingProps,e=d.revealOrder,f=d.tail;Yi(a,b,d.children,c);d=M.current;if(0!==(d&2))d=d&1|2,b.flags|=128;else{if(null!==a&&0!==(a.flags&128))a:for(a=b.child;null!==a;){if(13===a.tag)null!==a.memoizedState&&wj(a,c,b);else if(19===a.tag)wj(a,c,b);else if(null!==a.child){a.child.return=a;a=a.child;continue}if(a===b)break a;for(;null===a.sibling;){if(null===a.return||a.return===b)break a;a=a.return}a.sibling.return=a.return;a=a.sibling}d&=1}G(M,d);if(0===(b.mode&1))b.memoizedState=
null;else switch(e){case "forwards":c=b.child;for(e=null;null!==c;)a=c.alternate,null!==a&&null===Mh(a)&&(e=c),c=c.sibling;c=e;null===c?(e=b.child,b.child=null):(e=c.sibling,c.sibling=null);xj(b,!1,e,c,f);break;case "backwards":c=null;e=b.child;for(b.child=null;null!==e;){a=e.alternate;if(null!==a&&null===Mh(a)){b.child=e;break}a=e.sibling;e.sibling=c;c=e;e=a}xj(b,!0,c,null,f);break;case "together":xj(b,!1,null,null,void 0);break;default:b.memoizedState=null}return b.child}
function jj(a,b){0===(b.mode&1)&&null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2)}function $i(a,b,c){null!==a&&(b.dependencies=a.dependencies);hh|=b.lanes;if(0===(c&b.childLanes))return null;if(null!==a&&b.child!==a.child)throw Error(p(153));if(null!==b.child){a=b.child;c=wh(a,a.pendingProps);b.child=c;for(c.return=b;null!==a.sibling;)a=a.sibling,c=c.sibling=wh(a,a.pendingProps),c.return=b;c.sibling=null}return b.child}
function zj(a,b,c){switch(b.tag){case 3:lj(b);Ig();break;case 5:Kh(b);break;case 1:Zf(b.type)&&cg(b);break;case 4:Ih(b,b.stateNode.containerInfo);break;case 10:var d=b.type._context,e=b.memoizedProps.value;G(Mg,d._currentValue);d._currentValue=e;break;case 13:d=b.memoizedState;if(null!==d){if(null!==d.dehydrated)return G(M,M.current&1),b.flags|=128,null;if(0!==(c&b.child.childLanes))return pj(a,b,c);G(M,M.current&1);a=$i(a,b,c);return null!==a?a.sibling:null}G(M,M.current&1);break;case 19:d=0!==(c&
b.childLanes);if(0!==(a.flags&128)){if(d)return yj(a,b,c);b.flags|=128}e=b.memoizedState;null!==e&&(e.rendering=null,e.tail=null,e.lastEffect=null);G(M,M.current);if(d)break;else return null;case 22:case 23:return b.lanes=0,ej(a,b,c)}return $i(a,b,c)}var Aj,Bj,Cj,Dj;
Aj=function(a,b){for(var c=b.child;null!==c;){if(5===c.tag||6===c.tag)a.appendChild(c.stateNode);else if(4!==c.tag&&null!==c.child){c.child.return=c;c=c.child;continue}if(c===b)break;for(;null===c.sibling;){if(null===c.return||c.return===b)return;c=c.return}c.sibling.return=c.return;c=c.sibling}};Bj=function(){};
Cj=function(a,b,c,d){var e=a.memoizedProps;if(e!==d){a=b.stateNode;Hh(Eh.current);var f=null;switch(c){case "input":e=Ya(a,e);d=Ya(a,d);f=[];break;case "select":e=A({},e,{value:void 0});d=A({},d,{value:void 0});f=[];break;case "textarea":e=gb(a,e);d=gb(a,d);f=[];break;default:"function"!==typeof e.onClick&&"function"===typeof d.onClick&&(a.onclick=Bf)}ub(c,d);var g;c=null;for(l in e)if(!d.hasOwnProperty(l)&&e.hasOwnProperty(l)&&null!=e[l])if("style"===l){var h=e[l];for(g in h)h.hasOwnProperty(g)&&
(c||(c={}),c[g]="")}else"dangerouslySetInnerHTML"!==l&&"children"!==l&&"suppressContentEditableWarning"!==l&&"suppressHydrationWarning"!==l&&"autoFocus"!==l&&(ea.hasOwnProperty(l)?f||(f=[]):(f=f||[]).push(l,null));for(l in d){var k=d[l];h=null!=e?e[l]:void 0;if(d.hasOwnProperty(l)&&k!==h&&(null!=k||null!=h))if("style"===l)if(h){for(g in h)!h.hasOwnProperty(g)||k&&k.hasOwnProperty(g)||(c||(c={}),c[g]="");for(g in k)k.hasOwnProperty(g)&&h[g]!==k[g]&&(c||(c={}),c[g]=k[g])}else c||(f||(f=[]),f.push(l,
c)),c=k;else"dangerouslySetInnerHTML"===l?(k=k?k.__html:void 0,h=h?h.__html:void 0,null!=k&&h!==k&&(f=f||[]).push(l,k)):"children"===l?"string"!==typeof k&&"number"!==typeof k||(f=f||[]).push(l,""+k):"suppressContentEditableWarning"!==l&&"suppressHydrationWarning"!==l&&(ea.hasOwnProperty(l)?(null!=k&&"onScroll"===l&&D("scroll",a),f||h===k||(f=[])):(f=f||[]).push(l,k))}c&&(f=f||[]).push("style",c);var l=f;if(b.updateQueue=l)b.flags|=4}};Dj=function(a,b,c,d){c!==d&&(b.flags|=4)};
function Ej(a,b){if(!I)switch(a.tailMode){case "hidden":b=a.tail;for(var c=null;null!==b;)null!==b.alternate&&(c=b),b=b.sibling;null===c?a.tail=null:c.sibling=null;break;case "collapsed":c=a.tail;for(var d=null;null!==c;)null!==c.alternate&&(d=c),c=c.sibling;null===d?b||null===a.tail?a.tail=null:a.tail.sibling=null:d.sibling=null}}
function S(a){var b=null!==a.alternate&&a.alternate.child===a.child,c=0,d=0;if(b)for(var e=a.child;null!==e;)c|=e.lanes|e.childLanes,d|=e.subtreeFlags&14680064,d|=e.flags&14680064,e.return=a,e=e.sibling;else for(e=a.child;null!==e;)c|=e.lanes|e.childLanes,d|=e.subtreeFlags,d|=e.flags,e.return=a,e=e.sibling;a.subtreeFlags|=d;a.childLanes=c;return b}
function Fj(a,b,c){var d=b.pendingProps;wg(b);switch(b.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return S(b),null;case 1:return Zf(b.type)&&$f(),S(b),null;case 3:d=b.stateNode;Jh();E(Wf);E(H);Oh();d.pendingContext&&(d.context=d.pendingContext,d.pendingContext=null);if(null===a||null===a.child)Gg(b)?b.flags|=4:null===a||a.memoizedState.isDehydrated&&0===(b.flags&256)||(b.flags|=1024,null!==zg&&(Gj(zg),zg=null));Bj(a,b);S(b);return null;case 5:Lh(b);var e=Hh(Gh.current);
c=b.type;if(null!==a&&null!=b.stateNode)Cj(a,b,c,d,e),a.ref!==b.ref&&(b.flags|=512,b.flags|=2097152);else{if(!d){if(null===b.stateNode)throw Error(p(166));S(b);return null}a=Hh(Eh.current);if(Gg(b)){d=b.stateNode;c=b.type;var f=b.memoizedProps;d[Of]=b;d[Pf]=f;a=0!==(b.mode&1);switch(c){case "dialog":D("cancel",d);D("close",d);break;case "iframe":case "object":case "embed":D("load",d);break;case "video":case "audio":for(e=0;e<lf.length;e++)D(lf[e],d);break;case "source":D("error",d);break;case "img":case "image":case "link":D("error",
d);D("load",d);break;case "details":D("toggle",d);break;case "input":Za(d,f);D("invalid",d);break;case "select":d._wrapperState={wasMultiple:!!f.multiple};D("invalid",d);break;case "textarea":hb(d,f),D("invalid",d)}ub(c,f);e=null;for(var g in f)if(f.hasOwnProperty(g)){var h=f[g];"children"===g?"string"===typeof h?d.textContent!==h&&(!0!==f.suppressHydrationWarning&&Af(d.textContent,h,a),e=["children",h]):"number"===typeof h&&d.textContent!==""+h&&(!0!==f.suppressHydrationWarning&&Af(d.textContent,
h,a),e=["children",""+h]):ea.hasOwnProperty(g)&&null!=h&&"onScroll"===g&&D("scroll",d)}switch(c){case "input":Va(d);db(d,f,!0);break;case "textarea":Va(d);jb(d);break;case "select":case "option":break;default:"function"===typeof f.onClick&&(d.onclick=Bf)}d=e;b.updateQueue=d;null!==d&&(b.flags|=4)}else{g=9===e.nodeType?e:e.ownerDocument;"http://www.w3.org/1999/xhtml"===a&&(a=kb(c));"http://www.w3.org/1999/xhtml"===a?"script"===c?(a=g.createElement("div"),a.innerHTML="<script>\x3c/script>",a=a.removeChild(a.firstChild)):
"string"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),"select"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[Of]=b;a[Pf]=d;Aj(a,b,!1,!1);b.stateNode=a;a:{g=vb(c,d);switch(c){case "dialog":D("cancel",a);D("close",a);e=d;break;case "iframe":case "object":case "embed":D("load",a);e=d;break;case "video":case "audio":for(e=0;e<lf.length;e++)D(lf[e],a);e=d;break;case "source":D("error",a);e=d;break;case "img":case "image":case "link":D("error",
a);D("load",a);e=d;break;case "details":D("toggle",a);e=d;break;case "input":Za(a,d);e=Ya(a,d);D("invalid",a);break;case "option":e=d;break;case "select":a._wrapperState={wasMultiple:!!d.multiple};e=A({},d,{value:void 0});D("invalid",a);break;case "textarea":hb(a,d);e=gb(a,d);D("invalid",a);break;default:e=d}ub(c,e);h=e;for(f in h)if(h.hasOwnProperty(f)){var k=h[f];"style"===f?sb(a,k):"dangerouslySetInnerHTML"===f?(k=k?k.__html:void 0,null!=k&&nb(a,k)):"children"===f?"string"===typeof k?("textarea"!==
c||""!==k)&&ob(a,k):"number"===typeof k&&ob(a,""+k):"suppressContentEditableWarning"!==f&&"suppressHydrationWarning"!==f&&"autoFocus"!==f&&(ea.hasOwnProperty(f)?null!=k&&"onScroll"===f&&D("scroll",a):null!=k&&ta(a,f,k,g))}switch(c){case "input":Va(a);db(a,d,!1);break;case "textarea":Va(a);jb(a);break;case "option":null!=d.value&&a.setAttribute("value",""+Sa(d.value));break;case "select":a.multiple=!!d.multiple;f=d.value;null!=f?fb(a,!!d.multiple,f,!1):null!=d.defaultValue&&fb(a,!!d.multiple,d.defaultValue,
!0);break;default:"function"===typeof e.onClick&&(a.onclick=Bf)}switch(c){case "button":case "input":case "select":case "textarea":d=!!d.autoFocus;break a;case "img":d=!0;break a;default:d=!1}}d&&(b.flags|=4)}null!==b.ref&&(b.flags|=512,b.flags|=2097152)}S(b);return null;case 6:if(a&&null!=b.stateNode)Dj(a,b,a.memoizedProps,d);else{if("string"!==typeof d&&null===b.stateNode)throw Error(p(166));c=Hh(Gh.current);Hh(Eh.current);if(Gg(b)){d=b.stateNode;c=b.memoizedProps;d[Of]=b;if(f=d.nodeValue!==c)if(a=
xg,null!==a)switch(a.tag){case 3:Af(d.nodeValue,c,0!==(a.mode&1));break;case 5:!0!==a.memoizedProps.suppressHydrationWarning&&Af(d.nodeValue,c,0!==(a.mode&1))}f&&(b.flags|=4)}else d=(9===c.nodeType?c:c.ownerDocument).createTextNode(d),d[Of]=b,b.stateNode=d}S(b);return null;case 13:E(M);d=b.memoizedState;if(null===a||null!==a.memoizedState&&null!==a.memoizedState.dehydrated){if(I&&null!==yg&&0!==(b.mode&1)&&0===(b.flags&128))Hg(),Ig(),b.flags|=98560,f=!1;else if(f=Gg(b),null!==d&&null!==d.dehydrated){if(null===
a){if(!f)throw Error(p(318));f=b.memoizedState;f=null!==f?f.dehydrated:null;if(!f)throw Error(p(317));f[Of]=b}else Ig(),0===(b.flags&128)&&(b.memoizedState=null),b.flags|=4;S(b);f=!1}else null!==zg&&(Gj(zg),zg=null),f=!0;if(!f)return b.flags&65536?b:null}if(0!==(b.flags&128))return b.lanes=c,b;d=null!==d;d!==(null!==a&&null!==a.memoizedState)&&d&&(b.child.flags|=8192,0!==(b.mode&1)&&(null===a||0!==(M.current&1)?0===T&&(T=3):uj()));null!==b.updateQueue&&(b.flags|=4);S(b);return null;case 4:return Jh(),
Bj(a,b),null===a&&sf(b.stateNode.containerInfo),S(b),null;case 10:return Rg(b.type._context),S(b),null;case 17:return Zf(b.type)&&$f(),S(b),null;case 19:E(M);f=b.memoizedState;if(null===f)return S(b),null;d=0!==(b.flags&128);g=f.rendering;if(null===g)if(d)Ej(f,!1);else{if(0!==T||null!==a&&0!==(a.flags&128))for(a=b.child;null!==a;){g=Mh(a);if(null!==g){b.flags|=128;Ej(f,!1);d=g.updateQueue;null!==d&&(b.updateQueue=d,b.flags|=4);b.subtreeFlags=0;d=c;for(c=b.child;null!==c;)f=c,a=d,f.flags&=14680066,
g=f.alternate,null===g?(f.childLanes=0,f.lanes=a,f.child=null,f.subtreeFlags=0,f.memoizedProps=null,f.memoizedState=null,f.updateQueue=null,f.dependencies=null,f.stateNode=null):(f.childLanes=g.childLanes,f.lanes=g.lanes,f.child=g.child,f.subtreeFlags=0,f.deletions=null,f.memoizedProps=g.memoizedProps,f.memoizedState=g.memoizedState,f.updateQueue=g.updateQueue,f.type=g.type,a=g.dependencies,f.dependencies=null===a?null:{lanes:a.lanes,firstContext:a.firstContext}),c=c.sibling;G(M,M.current&1|2);return b.child}a=
a.sibling}null!==f.tail&&B()>Hj&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304)}else{if(!d)if(a=Mh(g),null!==a){if(b.flags|=128,d=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.flags|=4),Ej(f,!0),null===f.tail&&"hidden"===f.tailMode&&!g.alternate&&!I)return S(b),null}else 2*B()-f.renderingStartTime>Hj&&1073741824!==c&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(c=f.last,null!==c?c.sibling=g:b.child=g,f.last=g)}if(null!==f.tail)return b=f.tail,f.rendering=
b,f.tail=b.sibling,f.renderingStartTime=B(),b.sibling=null,c=M.current,G(M,d?c&1|2:c&1),b;S(b);return null;case 22:case 23:return Ij(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(gj&1073741824)&&(S(b),b.subtreeFlags&6&&(b.flags|=8192)):S(b),null;case 24:return null;case 25:return null}throw Error(p(156,b.tag));}
function Jj(a,b){wg(b);switch(b.tag){case 1:return Zf(b.type)&&$f(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return Jh(),E(Wf),E(H),Oh(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return Lh(b),null;case 13:E(M);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(p(340));Ig()}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return E(M),null;case 4:return Jh(),null;case 10:return Rg(b.type._context),null;case 22:case 23:return Ij(),
null;case 24:return null;default:return null}}var Kj=!1,U=!1,Lj="function"===typeof WeakSet?WeakSet:Set,V=null;function Mj(a,b){var c=a.ref;if(null!==c)if("function"===typeof c)try{c(null)}catch(d){W(a,b,d)}else c.current=null}function Nj(a,b,c){try{c()}catch(d){W(a,b,d)}}var Oj=!1;
function Pj(a,b){Cf=dd;a=Me();if(Ne(a)){if("selectionStart"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&0!==d.rangeCount){c=d.anchorNode;var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType}catch(F){c=null;break a}var g=0,h=-1,k=-1,l=0,m=0,q=a,r=null;b:for(;;){for(var y;;){q!==c||0!==e&&3!==q.nodeType||(h=g+e);q!==f||0!==d&&3!==q.nodeType||(k=g+d);3===q.nodeType&&(g+=
q.nodeValue.length);if(null===(y=q.firstChild))break;r=q;q=y}for(;;){if(q===a)break b;r===c&&++l===e&&(h=g);r===f&&++m===d&&(k=g);if(null!==(y=q.nextSibling))break;q=r;r=q.parentNode}q=y}c=-1===h||-1===k?null:{start:h,end:k}}else c=null}c=c||{start:0,end:0}}else c=null;Df={focusedElem:a,selectionRange:c};dd=!1;for(V=b;null!==V;)if(b=V,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,V=a;else for(;null!==V;){b=V;try{var n=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break;
case 1:if(null!==n){var t=n.memoizedProps,J=n.memoizedState,x=b.stateNode,w=x.getSnapshotBeforeUpdate(b.elementType===b.type?t:Lg(b.type,t),J);x.__reactInternalSnapshotBeforeUpdate=w}break;case 3:var u=b.stateNode.containerInfo;1===u.nodeType?u.textContent="":9===u.nodeType&&u.documentElement&&u.removeChild(u.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p(163));}}catch(F){W(b,b.return,F)}a=b.sibling;if(null!==a){a.return=b.return;V=a;break}V=b.return}n=Oj;Oj=!1;return n}
function Qj(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Nj(b,c,f)}e=e.next}while(e!==d)}}function Rj(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d()}c=c.next}while(c!==b)}}function Sj(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=c;break;default:a=c}"function"===typeof b?b(a):b.current=a}}
function Tj(a){var b=a.alternate;null!==b&&(a.alternate=null,Tj(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[Of],delete b[Pf],delete b[of],delete b[Qf],delete b[Rf]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null}function Uj(a){return 5===a.tag||3===a.tag||4===a.tag}
function Vj(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Uj(a.return))return null;a=a.return}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}
function Wj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=Bf));else if(4!==d&&(a=a.child,null!==a))for(Wj(a,b,c),a=a.sibling;null!==a;)Wj(a,b,c),a=a.sibling}
function Xj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Xj(a,b,c),a=a.sibling;null!==a;)Xj(a,b,c),a=a.sibling}var X=null,Yj=!1;function Zj(a,b,c){for(c=c.child;null!==c;)ak(a,b,c),c=c.sibling}
function ak(a,b,c){if(lc&&"function"===typeof lc.onCommitFiberUnmount)try{lc.onCommitFiberUnmount(kc,c)}catch(h){}switch(c.tag){case 5:U||Mj(c,b);case 6:var d=X,e=Yj;X=null;Zj(a,b,c);X=d;Yj=e;null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?a.parentNode.removeChild(c):a.removeChild(c)):X.removeChild(c.stateNode));break;case 18:null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?Kf(a.parentNode,c):1===a.nodeType&&Kf(a,c),bd(a)):Kf(X,c.stateNode));break;case 4:d=X;e=Yj;X=c.stateNode.containerInfo;Yj=!0;
Zj(a,b,c);X=d;Yj=e;break;case 0:case 11:case 14:case 15:if(!U&&(d=c.updateQueue,null!==d&&(d=d.lastEffect,null!==d))){e=d=d.next;do{var f=e,g=f.destroy;f=f.tag;void 0!==g&&(0!==(f&2)?Nj(c,b,g):0!==(f&4)&&Nj(c,b,g));e=e.next}while(e!==d)}Zj(a,b,c);break;case 1:if(!U&&(Mj(c,b),d=c.stateNode,"function"===typeof d.componentWillUnmount))try{d.props=c.memoizedProps,d.state=c.memoizedState,d.componentWillUnmount()}catch(h){W(c,b,h)}Zj(a,b,c);break;case 21:Zj(a,b,c);break;case 22:c.mode&1?(U=(d=U)||null!==
c.memoizedState,Zj(a,b,c),U=d):Zj(a,b,c);break;default:Zj(a,b,c)}}function bk(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Lj);b.forEach(function(b){var d=ck.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d))})}}
function dk(a,b){var c=b.deletions;if(null!==c)for(var d=0;d<c.length;d++){var e=c[d];try{var f=a,g=b,h=g;a:for(;null!==h;){switch(h.tag){case 5:X=h.stateNode;Yj=!1;break a;case 3:X=h.stateNode.containerInfo;Yj=!0;break a;case 4:X=h.stateNode.containerInfo;Yj=!0;break a}h=h.return}if(null===X)throw Error(p(160));ak(f,g,e);X=null;Yj=!1;var k=e.alternate;null!==k&&(k.return=null);e.return=null}catch(l){W(e,b,l)}}if(b.subtreeFlags&12854)for(b=b.child;null!==b;)ek(b,a),b=b.sibling}
function ek(a,b){var c=a.alternate,d=a.flags;switch(a.tag){case 0:case 11:case 14:case 15:dk(b,a);fk(a);if(d&4){try{Qj(3,a,a.return),Rj(3,a)}catch(t){W(a,a.return,t)}try{Qj(5,a,a.return)}catch(t){W(a,a.return,t)}}break;case 1:dk(b,a);fk(a);d&512&&null!==c&&Mj(c,c.return);break;case 5:dk(b,a);fk(a);d&512&&null!==c&&Mj(c,c.return);if(a.flags&32){var e=a.stateNode;try{ob(e,"")}catch(t){W(a,a.return,t)}}if(d&4&&(e=a.stateNode,null!=e)){var f=a.memoizedProps,g=null!==c?c.memoizedProps:f,h=a.type,k=a.updateQueue;
a.updateQueue=null;if(null!==k)try{"input"===h&&"radio"===f.type&&null!=f.name&&ab(e,f);vb(h,g);var l=vb(h,f);for(g=0;g<k.length;g+=2){var m=k[g],q=k[g+1];"style"===m?sb(e,q):"dangerouslySetInnerHTML"===m?nb(e,q):"children"===m?ob(e,q):ta(e,m,q,l)}switch(h){case "input":bb(e,f);break;case "textarea":ib(e,f);break;case "select":var r=e._wrapperState.wasMultiple;e._wrapperState.wasMultiple=!!f.multiple;var y=f.value;null!=y?fb(e,!!f.multiple,y,!1):r!==!!f.multiple&&(null!=f.defaultValue?fb(e,!!f.multiple,
f.defaultValue,!0):fb(e,!!f.multiple,f.multiple?[]:"",!1))}e[Pf]=f}catch(t){W(a,a.return,t)}}break;case 6:dk(b,a);fk(a);if(d&4){if(null===a.stateNode)throw Error(p(162));e=a.stateNode;f=a.memoizedProps;try{e.nodeValue=f}catch(t){W(a,a.return,t)}}break;case 3:dk(b,a);fk(a);if(d&4&&null!==c&&c.memoizedState.isDehydrated)try{bd(b.containerInfo)}catch(t){W(a,a.return,t)}break;case 4:dk(b,a);fk(a);break;case 13:dk(b,a);fk(a);e=a.child;e.flags&8192&&(f=null!==e.memoizedState,e.stateNode.isHidden=f,!f||
null!==e.alternate&&null!==e.alternate.memoizedState||(gk=B()));d&4&&bk(a);break;case 22:m=null!==c&&null!==c.memoizedState;a.mode&1?(U=(l=U)||m,dk(b,a),U=l):dk(b,a);fk(a);if(d&8192){l=null!==a.memoizedState;if((a.stateNode.isHidden=l)&&!m&&0!==(a.mode&1))for(V=a,m=a.child;null!==m;){for(q=V=m;null!==V;){r=V;y=r.child;switch(r.tag){case 0:case 11:case 14:case 15:Qj(4,r,r.return);break;case 1:Mj(r,r.return);var n=r.stateNode;if("function"===typeof n.componentWillUnmount){d=r;c=r.return;try{b=d,n.props=
b.memoizedProps,n.state=b.memoizedState,n.componentWillUnmount()}catch(t){W(d,c,t)}}break;case 5:Mj(r,r.return);break;case 22:if(null!==r.memoizedState){hk(q);continue}}null!==y?(y.return=r,V=y):hk(q)}m=m.sibling}a:for(m=null,q=a;;){if(5===q.tag){if(null===m){m=q;try{e=q.stateNode,l?(f=e.style,"function"===typeof f.setProperty?f.setProperty("display","none","important"):f.display="none"):(h=q.stateNode,k=q.memoizedProps.style,g=void 0!==k&&null!==k&&k.hasOwnProperty("display")?k.display:null,h.style.display=
rb("display",g))}catch(t){W(a,a.return,t)}}}else if(6===q.tag){if(null===m)try{q.stateNode.nodeValue=l?"":q.memoizedProps}catch(t){W(a,a.return,t)}}else if((22!==q.tag&&23!==q.tag||null===q.memoizedState||q===a)&&null!==q.child){q.child.return=q;q=q.child;continue}if(q===a)break a;for(;null===q.sibling;){if(null===q.return||q.return===a)break a;m===q&&(m=null);q=q.return}m===q&&(m=null);q.sibling.return=q.return;q=q.sibling}}break;case 19:dk(b,a);fk(a);d&4&&bk(a);break;case 21:break;default:dk(b,
a),fk(a)}}function fk(a){var b=a.flags;if(b&2){try{a:{for(var c=a.return;null!==c;){if(Uj(c)){var d=c;break a}c=c.return}throw Error(p(160));}switch(d.tag){case 5:var e=d.stateNode;d.flags&32&&(ob(e,""),d.flags&=-33);var f=Vj(a);Xj(a,f,e);break;case 3:case 4:var g=d.stateNode.containerInfo,h=Vj(a);Wj(a,h,g);break;default:throw Error(p(161));}}catch(k){W(a,a.return,k)}a.flags&=-3}b&4096&&(a.flags&=-4097)}function ik(a,b,c){V=a;jk(a,b,c)}
function jk(a,b,c){for(var d=0!==(a.mode&1);null!==V;){var e=V,f=e.child;if(22===e.tag&&d){var g=null!==e.memoizedState||Kj;if(!g){var h=e.alternate,k=null!==h&&null!==h.memoizedState||U;h=Kj;var l=U;Kj=g;if((U=k)&&!l)for(V=e;null!==V;)g=V,k=g.child,22===g.tag&&null!==g.memoizedState?kk(e):null!==k?(k.return=g,V=k):kk(e);for(;null!==f;)V=f,jk(f,b,c),f=f.sibling;V=e;Kj=h;U=l}lk(a,b,c)}else 0!==(e.subtreeFlags&8772)&&null!==f?(f.return=e,V=f):lk(a,b,c)}}
function lk(a){for(;null!==V;){var b=V;if(0!==(b.flags&8772)){var c=b.alternate;try{if(0!==(b.flags&8772))switch(b.tag){case 0:case 11:case 15:U||Rj(5,b);break;case 1:var d=b.stateNode;if(b.flags&4&&!U)if(null===c)d.componentDidMount();else{var e=b.elementType===b.type?c.memoizedProps:Lg(b.type,c.memoizedProps);d.componentDidUpdate(e,c.memoizedState,d.__reactInternalSnapshotBeforeUpdate)}var f=b.updateQueue;null!==f&&ih(b,f,d);break;case 3:var g=b.updateQueue;if(null!==g){c=null;if(null!==b.child)switch(b.child.tag){case 5:c=
b.child.stateNode;break;case 1:c=b.child.stateNode}ih(b,g,c)}break;case 5:var h=b.stateNode;if(null===c&&b.flags&4){c=h;var k=b.memoizedProps;switch(b.type){case "button":case "input":case "select":case "textarea":k.autoFocus&&c.focus();break;case "img":k.src&&(c.src=k.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(null===b.memoizedState){var l=b.alternate;if(null!==l){var m=l.memoizedState;if(null!==m){var q=m.dehydrated;null!==q&&bd(q)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;
default:throw Error(p(163));}U||b.flags&512&&Sj(b)}catch(r){W(b,b.return,r)}}if(b===a){V=null;break}c=b.sibling;if(null!==c){c.return=b.return;V=c;break}V=b.return}}function hk(a){for(;null!==V;){var b=V;if(b===a){V=null;break}var c=b.sibling;if(null!==c){c.return=b.return;V=c;break}V=b.return}}
function kk(a){for(;null!==V;){var b=V;try{switch(b.tag){case 0:case 11:case 15:var c=b.return;try{Rj(4,b)}catch(k){W(b,c,k)}break;case 1:var d=b.stateNode;if("function"===typeof d.componentDidMount){var e=b.return;try{d.componentDidMount()}catch(k){W(b,e,k)}}var f=b.return;try{Sj(b)}catch(k){W(b,f,k)}break;case 5:var g=b.return;try{Sj(b)}catch(k){W(b,g,k)}}}catch(k){W(b,b.return,k)}if(b===a){V=null;break}var h=b.sibling;if(null!==h){h.return=b.return;V=h;break}V=b.return}}
var mk=Math.ceil,nk=ua.ReactCurrentDispatcher,ok=ua.ReactCurrentOwner,pk=ua.ReactCurrentBatchConfig,K=0,R=null,Y=null,Z=0,gj=0,fj=Uf(0),T=0,qk=null,hh=0,rk=0,sk=0,tk=null,uk=null,gk=0,Hj=Infinity,vk=null,Pi=!1,Qi=null,Si=null,wk=!1,xk=null,yk=0,zk=0,Ak=null,Bk=-1,Ck=0;function L(){return 0!==(K&6)?B():-1!==Bk?Bk:Bk=B()}
function lh(a){if(0===(a.mode&1))return 1;if(0!==(K&2)&&0!==Z)return Z&-Z;if(null!==Kg.transition)return 0===Ck&&(Ck=yc()),Ck;a=C;if(0!==a)return a;a=window.event;a=void 0===a?16:jd(a.type);return a}function mh(a,b,c,d){if(50<zk)throw zk=0,Ak=null,Error(p(185));Ac(a,c,d);if(0===(K&2)||a!==R)a===R&&(0===(K&2)&&(rk|=c),4===T&&Dk(a,Z)),Ek(a,d),1===c&&0===K&&0===(b.mode&1)&&(Hj=B()+500,fg&&jg())}
function Ek(a,b){var c=a.callbackNode;wc(a,b);var d=uc(a,a===R?Z:0);if(0===d)null!==c&&bc(c),a.callbackNode=null,a.callbackPriority=0;else if(b=d&-d,a.callbackPriority!==b){null!=c&&bc(c);if(1===b)0===a.tag?ig(Fk.bind(null,a)):hg(Fk.bind(null,a)),Jf(function(){0===(K&6)&&jg()}),c=null;else{switch(Dc(d)){case 1:c=fc;break;case 4:c=gc;break;case 16:c=hc;break;case 536870912:c=jc;break;default:c=hc}c=Gk(c,Hk.bind(null,a))}a.callbackPriority=b;a.callbackNode=c}}
function Hk(a,b){Bk=-1;Ck=0;if(0!==(K&6))throw Error(p(327));var c=a.callbackNode;if(Ik()&&a.callbackNode!==c)return null;var d=uc(a,a===R?Z:0);if(0===d)return null;if(0!==(d&30)||0!==(d&a.expiredLanes)||b)b=Jk(a,d);else{b=d;var e=K;K|=2;var f=Kk();if(R!==a||Z!==b)vk=null,Hj=B()+500,Lk(a,b);do try{Mk();break}catch(h){Nk(a,h)}while(1);Qg();nk.current=f;K=e;null!==Y?b=0:(R=null,Z=0,b=T)}if(0!==b){2===b&&(e=xc(a),0!==e&&(d=e,b=Ok(a,e)));if(1===b)throw c=qk,Lk(a,0),Dk(a,d),Ek(a,B()),c;if(6===b)Dk(a,d);
else{e=a.current.alternate;if(0===(d&30)&&!Pk(e)&&(b=Jk(a,d),2===b&&(f=xc(a),0!==f&&(d=f,b=Ok(a,f))),1===b))throw c=qk,Lk(a,0),Dk(a,d),Ek(a,B()),c;a.finishedWork=e;a.finishedLanes=d;switch(b){case 0:case 1:throw Error(p(345));case 2:Qk(a,uk,vk);break;case 3:Dk(a,d);if((d&130023424)===d&&(b=gk+500-B(),10<b)){if(0!==uc(a,0))break;e=a.suspendedLanes;if((e&d)!==d){L();a.pingedLanes|=a.suspendedLanes&e;break}a.timeoutHandle=Ff(Qk.bind(null,a,uk,vk),b);break}Qk(a,uk,vk);break;case 4:Dk(a,d);if((d&4194240)===
d)break;b=a.eventTimes;for(e=-1;0<d;){var g=31-oc(d);f=1<<g;g=b[g];g>e&&(e=g);d&=~f}d=e;d=B()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*mk(d/1960))-d;if(10<d){a.timeoutHandle=Ff(Qk.bind(null,a,uk,vk),d);break}Qk(a,uk,vk);break;case 5:Qk(a,uk,vk);break;default:throw Error(p(329));}}}Ek(a,B());return a.callbackNode===c?Hk.bind(null,a):null}
function Ok(a,b){var c=tk;a.current.memoizedState.isDehydrated&&(Lk(a,b).flags|=256);a=Jk(a,b);2!==a&&(b=uk,uk=c,null!==b&&Gj(b));return a}function Gj(a){null===uk?uk=a:uk.push.apply(uk,a)}
function Pk(a){for(var b=a;;){if(b.flags&16384){var c=b.updateQueue;if(null!==c&&(c=c.stores,null!==c))for(var d=0;d<c.length;d++){var e=c[d],f=e.getSnapshot;e=e.value;try{if(!He(f(),e))return!1}catch(g){return!1}}}c=b.child;if(b.subtreeFlags&16384&&null!==c)c.return=b,b=c;else{if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return!0;b=b.return}b.sibling.return=b.return;b=b.sibling}}return!0}
function Dk(a,b){b&=~sk;b&=~rk;a.suspendedLanes|=b;a.pingedLanes&=~b;for(a=a.expirationTimes;0<b;){var c=31-oc(b),d=1<<c;a[c]=-1;b&=~d}}function Fk(a){if(0!==(K&6))throw Error(p(327));Ik();var b=uc(a,0);if(0===(b&1))return Ek(a,B()),null;var c=Jk(a,b);if(0!==a.tag&&2===c){var d=xc(a);0!==d&&(b=d,c=Ok(a,d))}if(1===c)throw c=qk,Lk(a,0),Dk(a,b),Ek(a,B()),c;if(6===c)throw Error(p(345));a.finishedWork=a.current.alternate;a.finishedLanes=b;Qk(a,uk,vk);Ek(a,B());return null}
function Rk(a,b){var c=K;K|=1;try{return a(b)}finally{K=c,0===K&&(Hj=B()+500,fg&&jg())}}function Sk(a){null!==xk&&0===xk.tag&&0===(K&6)&&Ik();var b=K;K|=1;var c=pk.transition,d=C;try{if(pk.transition=null,C=1,a)return a()}finally{C=d,pk.transition=c,K=b,0===(K&6)&&jg()}}function Ij(){gj=fj.current;E(fj)}
function Lk(a,b){a.finishedWork=null;a.finishedLanes=0;var c=a.timeoutHandle;-1!==c&&(a.timeoutHandle=-1,Gf(c));if(null!==Y)for(c=Y.return;null!==c;){var d=c;wg(d);switch(d.tag){case 1:d=d.type.childContextTypes;null!==d&&void 0!==d&&$f();break;case 3:Jh();E(Wf);E(H);Oh();break;case 5:Lh(d);break;case 4:Jh();break;case 13:E(M);break;case 19:E(M);break;case 10:Rg(d.type._context);break;case 22:case 23:Ij()}c=c.return}R=a;Y=a=wh(a.current,null);Z=gj=b;T=0;qk=null;sk=rk=hh=0;uk=tk=null;if(null!==Wg){for(b=
0;b<Wg.length;b++)if(c=Wg[b],d=c.interleaved,null!==d){c.interleaved=null;var e=d.next,f=c.pending;if(null!==f){var g=f.next;f.next=e;d.next=g}c.pending=d}Wg=null}return a}
function Nk(a,b){do{var c=Y;try{Qg();Ph.current=ai;if(Sh){for(var d=N.memoizedState;null!==d;){var e=d.queue;null!==e&&(e.pending=null);d=d.next}Sh=!1}Rh=0;P=O=N=null;Th=!1;Uh=0;ok.current=null;if(null===c||null===c.return){T=1;qk=b;Y=null;break}a:{var f=a,g=c.return,h=c,k=b;b=Z;h.flags|=32768;if(null!==k&&"object"===typeof k&&"function"===typeof k.then){var l=k,m=h,q=m.tag;if(0===(m.mode&1)&&(0===q||11===q||15===q)){var r=m.alternate;r?(m.updateQueue=r.updateQueue,m.memoizedState=r.memoizedState,
m.lanes=r.lanes):(m.updateQueue=null,m.memoizedState=null)}var y=Vi(g);if(null!==y){y.flags&=-257;Wi(y,g,h,f,b);y.mode&1&&Ti(f,l,b);b=y;k=l;var n=b.updateQueue;if(null===n){var t=new Set;t.add(k);b.updateQueue=t}else n.add(k);break a}else{if(0===(b&1)){Ti(f,l,b);uj();break a}k=Error(p(426))}}else if(I&&h.mode&1){var J=Vi(g);if(null!==J){0===(J.flags&65536)&&(J.flags|=256);Wi(J,g,h,f,b);Jg(Ki(k,h));break a}}f=k=Ki(k,h);4!==T&&(T=2);null===tk?tk=[f]:tk.push(f);f=g;do{switch(f.tag){case 3:f.flags|=65536;
b&=-b;f.lanes|=b;var x=Oi(f,k,b);fh(f,x);break a;case 1:h=k;var w=f.type,u=f.stateNode;if(0===(f.flags&128)&&("function"===typeof w.getDerivedStateFromError||null!==u&&"function"===typeof u.componentDidCatch&&(null===Si||!Si.has(u)))){f.flags|=65536;b&=-b;f.lanes|=b;var F=Ri(f,h,b);fh(f,F);break a}}f=f.return}while(null!==f)}Tk(c)}catch(na){b=na;Y===c&&null!==c&&(Y=c=c.return);continue}break}while(1)}function Kk(){var a=nk.current;nk.current=ai;return null===a?ai:a}
function uj(){if(0===T||3===T||2===T)T=4;null===R||0===(hh&268435455)&&0===(rk&268435455)||Dk(R,Z)}function Jk(a,b){var c=K;K|=2;var d=Kk();if(R!==a||Z!==b)vk=null,Lk(a,b);do try{Uk();break}catch(e){Nk(a,e)}while(1);Qg();K=c;nk.current=d;if(null!==Y)throw Error(p(261));R=null;Z=0;return T}function Uk(){for(;null!==Y;)Vk(Y)}function Mk(){for(;null!==Y&&!cc();)Vk(Y)}function Vk(a){var b=Wk(a.alternate,a,gj);a.memoizedProps=a.pendingProps;null===b?Tk(a):Y=b;ok.current=null}
function Tk(a){var b=a;do{var c=b.alternate;a=b.return;if(0===(b.flags&32768)){if(c=Fj(c,b,gj),null!==c){Y=c;return}}else{c=Jj(c,b);if(null!==c){c.flags&=32767;Y=c;return}if(null!==a)a.flags|=32768,a.subtreeFlags=0,a.deletions=null;else{T=6;Y=null;return}}b=b.sibling;if(null!==b){Y=b;return}Y=b=a}while(null!==b);0===T&&(T=5)}function Qk(a,b,c){var d=C,e=pk.transition;try{pk.transition=null,C=1,Xk(a,b,c,d)}finally{pk.transition=e,C=d}return null}
function Xk(a,b,c,d){do Ik();while(null!==xk);if(0!==(K&6))throw Error(p(327));c=a.finishedWork;var e=a.finishedLanes;if(null===c)return null;a.finishedWork=null;a.finishedLanes=0;if(c===a.current)throw Error(p(177));a.callbackNode=null;a.callbackPriority=0;var f=c.lanes|c.childLanes;Bc(a,f);a===R&&(Y=R=null,Z=0);0===(c.subtreeFlags&2064)&&0===(c.flags&2064)||wk||(wk=!0,Gk(hc,function(){Ik();return null}));f=0!==(c.flags&15990);if(0!==(c.subtreeFlags&15990)||f){f=pk.transition;pk.transition=null;
var g=C;C=1;var h=K;K|=4;ok.current=null;Pj(a,c);ek(c,a);Oe(Df);dd=!!Cf;Df=Cf=null;a.current=c;ik(c,a,e);dc();K=h;C=g;pk.transition=f}else a.current=c;wk&&(wk=!1,xk=a,yk=e);f=a.pendingLanes;0===f&&(Si=null);mc(c.stateNode,d);Ek(a,B());if(null!==b)for(d=a.onRecoverableError,c=0;c<b.length;c++)e=b[c],d(e.value,{componentStack:e.stack,digest:e.digest});if(Pi)throw Pi=!1,a=Qi,Qi=null,a;0!==(yk&1)&&0!==a.tag&&Ik();f=a.pendingLanes;0!==(f&1)?a===Ak?zk++:(zk=0,Ak=a):zk=0;jg();return null}
function Ik(){if(null!==xk){var a=Dc(yk),b=pk.transition,c=C;try{pk.transition=null;C=16>a?16:a;if(null===xk)var d=!1;else{a=xk;xk=null;yk=0;if(0!==(K&6))throw Error(p(331));var e=K;K|=4;for(V=a.current;null!==V;){var f=V,g=f.child;if(0!==(V.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;k<h.length;k++){var l=h[k];for(V=l;null!==V;){var m=V;switch(m.tag){case 0:case 11:case 15:Qj(8,m,f)}var q=m.child;if(null!==q)q.return=m,V=q;else for(;null!==V;){m=V;var r=m.sibling,y=m.return;Tj(m);if(m===
l){V=null;break}if(null!==r){r.return=y;V=r;break}V=y}}}var n=f.alternate;if(null!==n){var t=n.child;if(null!==t){n.child=null;do{var J=t.sibling;t.sibling=null;t=J}while(null!==t)}}V=f}}if(0!==(f.subtreeFlags&2064)&&null!==g)g.return=f,V=g;else b:for(;null!==V;){f=V;if(0!==(f.flags&2048))switch(f.tag){case 0:case 11:case 15:Qj(9,f,f.return)}var x=f.sibling;if(null!==x){x.return=f.return;V=x;break b}V=f.return}}var w=a.current;for(V=w;null!==V;){g=V;var u=g.child;if(0!==(g.subtreeFlags&2064)&&null!==
u)u.return=g,V=u;else b:for(g=w;null!==V;){h=V;if(0!==(h.flags&2048))try{switch(h.tag){case 0:case 11:case 15:Rj(9,h)}}catch(na){W(h,h.return,na)}if(h===g){V=null;break b}var F=h.sibling;if(null!==F){F.return=h.return;V=F;break b}V=h.return}}K=e;jg();if(lc&&"function"===typeof lc.onPostCommitFiberRoot)try{lc.onPostCommitFiberRoot(kc,a)}catch(na){}d=!0}return d}finally{C=c,pk.transition=b}}return!1}function Yk(a,b,c){b=Ki(c,b);b=Oi(a,b,1);a=dh(a,b,1);b=L();null!==a&&(Ac(a,1,b),Ek(a,b))}
function W(a,b,c){if(3===a.tag)Yk(a,a,c);else for(;null!==b;){if(3===b.tag){Yk(b,a,c);break}else if(1===b.tag){var d=b.stateNode;if("function"===typeof b.type.getDerivedStateFromError||"function"===typeof d.componentDidCatch&&(null===Si||!Si.has(d))){a=Ki(c,a);a=Ri(b,a,1);b=dh(b,a,1);a=L();null!==b&&(Ac(b,1,a),Ek(b,a));break}}b=b.return}}
function Ui(a,b,c){var d=a.pingCache;null!==d&&d.delete(b);b=L();a.pingedLanes|=a.suspendedLanes&c;R===a&&(Z&c)===c&&(4===T||3===T&&(Z&130023424)===Z&&500>B()-gk?Lk(a,0):sk|=c);Ek(a,b)}function Zk(a,b){0===b&&(0===(a.mode&1)?b=1:(b=sc,sc<<=1,0===(sc&130023424)&&(sc=4194304)));var c=L();a=Zg(a,b);null!==a&&(Ac(a,b,c),Ek(a,c))}function vj(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Zk(a,c)}
function ck(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(p(314));}null!==d&&d.delete(b);Zk(a,c)}var Wk;
Wk=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||Wf.current)Ug=!0;else{if(0===(a.lanes&c)&&0===(b.flags&128))return Ug=!1,zj(a,b,c);Ug=0!==(a.flags&131072)?!0:!1}else Ug=!1,I&&0!==(b.flags&1048576)&&ug(b,ng,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;jj(a,b);a=b.pendingProps;var e=Yf(b,H.current);Tg(b,c);e=Xh(null,b,d,a,e,c);var f=bi();b.flags|=1;"object"===typeof e&&null!==e&&"function"===typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue=
null,Zf(d)?(f=!0,cg(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,ah(b),e.updater=nh,b.stateNode=e,e._reactInternals=b,rh(b,d,a,c),b=kj(null,b,d,!0,f,c)):(b.tag=0,I&&f&&vg(b),Yi(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{jj(a,b);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=$k(d);a=Lg(d,a);switch(e){case 0:b=dj(null,b,d,a,c);break a;case 1:b=ij(null,b,d,a,c);break a;case 11:b=Zi(null,b,d,a,c);break a;case 14:b=aj(null,b,d,Lg(d.type,a),c);break a}throw Error(p(306,
d,""));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),dj(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),ij(a,b,d,e,c);case 3:a:{lj(b);if(null===a)throw Error(p(387));d=b.pendingProps;f=b.memoizedState;e=f.element;bh(a,b);gh(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated)if(f={element:d,isDehydrated:!1,cache:g.cache,pendingSuspenseBoundaries:g.pendingSuspenseBoundaries,transitions:g.transitions},b.updateQueue.baseState=
f,b.memoizedState=f,b.flags&256){e=Ki(Error(p(423)),b);b=mj(a,b,d,c,e);break a}else if(d!==e){e=Ki(Error(p(424)),b);b=mj(a,b,d,c,e);break a}else for(yg=Lf(b.stateNode.containerInfo.firstChild),xg=b,I=!0,zg=null,c=Ch(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else{Ig();if(d===e){b=$i(a,b,c);break a}Yi(a,b,d,c)}b=b.child}return b;case 5:return Kh(b),null===a&&Eg(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Ef(d,e)?g=null:null!==f&&Ef(d,f)&&(b.flags|=32),
hj(a,b),Yi(a,b,g,c),b.child;case 6:return null===a&&Eg(b),null;case 13:return pj(a,b,c);case 4:return Ih(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Bh(b,null,d,c):Yi(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),Zi(a,b,d,e,c);case 7:return Yi(a,b,b.pendingProps,c),b.child;case 8:return Yi(a,b,b.pendingProps.children,c),b.child;case 12:return Yi(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;f=b.memoizedProps;
g=e.value;G(Mg,d._currentValue);d._currentValue=g;if(null!==f)if(He(f.value,g)){if(f.children===e.children&&!Wf.current){b=$i(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=ch(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|=c);Sg(f.return,
c,b);h.lanes|=c;break}k=k.next}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(p(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);Sg(g,c,b);g=f.sibling}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return}f=g}Yi(a,b,e.children,c);b=b.child}return b;case 9:return e=b.type,d=b.pendingProps.children,Tg(b,c),e=Vg(e),d=d(e),b.flags|=1,Yi(a,b,d,c),
b.child;case 14:return d=b.type,e=Lg(d,b.pendingProps),e=Lg(d.type,e),aj(a,b,d,e,c);case 15:return cj(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),jj(a,b),b.tag=1,Zf(d)?(a=!0,cg(b)):a=!1,Tg(b,c),ph(b,d,e),rh(b,d,e,c),kj(null,b,d,!0,a,c);case 19:return yj(a,b,c);case 22:return ej(a,b,c)}throw Error(p(156,b.tag));};function Gk(a,b){return ac(a,b)}
function al(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null}function Bg(a,b,c,d){return new al(a,b,c,d)}function bj(a){a=a.prototype;return!(!a||!a.isReactComponent)}
function $k(a){if("function"===typeof a)return bj(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Da)return 11;if(a===Ga)return 14}return 2}
function wh(a,b){var c=a.alternate;null===c?(c=Bg(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext};
c.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c}
function yh(a,b,c,d,e,f){var g=2;d=a;if("function"===typeof a)bj(a)&&(g=1);else if("string"===typeof a)g=5;else a:switch(a){case ya:return Ah(c.children,e,f,b);case za:g=8;e|=8;break;case Aa:return a=Bg(12,c,b,e|2),a.elementType=Aa,a.lanes=f,a;case Ea:return a=Bg(13,c,b,e),a.elementType=Ea,a.lanes=f,a;case Fa:return a=Bg(19,c,b,e),a.elementType=Fa,a.lanes=f,a;case Ia:return qj(c,e,f,b);default:if("object"===typeof a&&null!==a)switch(a.$$typeof){case Ba:g=10;break a;case Ca:g=9;break a;case Da:g=11;
break a;case Ga:g=14;break a;case Ha:g=16;d=null;break a}throw Error(p(130,null==a?a:typeof a,""));}b=Bg(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function Ah(a,b,c,d){a=Bg(7,a,d,b);a.lanes=c;return a}function qj(a,b,c,d){a=Bg(22,a,d,b);a.elementType=Ia;a.lanes=c;a.stateNode={isHidden:!1};return a}function xh(a,b,c){a=Bg(6,a,null,b);a.lanes=c;return a}
function zh(a,b,c){b=Bg(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b}
function bl(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=zc(0);this.expirationTimes=zc(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=zc(0);this.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData=
null}function cl(a,b,c,d,e,f,g,h,k){a=new bl(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=Bg(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null};ah(f);return a}function dl(a,b,c){var d=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:wa,key:null==d?null:""+d,children:a,containerInfo:b,implementation:c}}
function el(a){if(!a)return Vf;a=a._reactInternals;a:{if(Vb(a)!==a||1!==a.tag)throw Error(p(170));var b=a;do{switch(b.tag){case 3:b=b.stateNode.context;break a;case 1:if(Zf(b.type)){b=b.stateNode.__reactInternalMemoizedMergedChildContext;break a}}b=b.return}while(null!==b);throw Error(p(171));}if(1===a.tag){var c=a.type;if(Zf(c))return bg(a,c,b)}return b}
function fl(a,b,c,d,e,f,g,h,k){a=cl(c,d,!0,a,e,f,g,h,k);a.context=el(null);c=a.current;d=L();e=lh(c);f=ch(d,e);f.callback=void 0!==b&&null!==b?b:null;dh(c,f,e);a.current.lanes=e;Ac(a,e,d);Ek(a,d);return a}function gl(a,b,c,d){var e=b.current,f=L(),g=lh(e);c=el(c);null===b.context?b.context=c:b.pendingContext=c;b=ch(f,g);b.payload={element:a};d=void 0===d?null:d;null!==d&&(b.callback=d);a=dh(e,b,g);null!==a&&(mh(a,e,g,f),eh(a,e,g));return g}
function hl(a){a=a.current;if(!a.child)return null;switch(a.child.tag){case 5:return a.child.stateNode;default:return a.child.stateNode}}function il(a,b){a=a.memoizedState;if(null!==a&&null!==a.dehydrated){var c=a.retryLane;a.retryLane=0!==c&&c<b?c:b}}function jl(a,b){il(a,b);(a=a.alternate)&&il(a,b)}function kl(){return null}var ll="function"===typeof reportError?reportError:function(a){console.error(a)};function ml(a){this._internalRoot=a}
nl.prototype.render=ml.prototype.render=function(a){var b=this._internalRoot;if(null===b)throw Error(p(409));gl(a,b,null,null)};nl.prototype.unmount=ml.prototype.unmount=function(){var a=this._internalRoot;if(null!==a){this._internalRoot=null;var b=a.containerInfo;Sk(function(){gl(null,a,null,null)});b[uf]=null}};function nl(a){this._internalRoot=a}
nl.prototype.unstable_scheduleHydration=function(a){if(a){var b=Hc();a={blockedOn:null,target:a,priority:b};for(var c=0;c<Qc.length&&0!==b&&b<Qc[c].priority;c++);Qc.splice(c,0,a);0===c&&Vc(a)}};function ol(a){return!(!a||1!==a.nodeType&&9!==a.nodeType&&11!==a.nodeType)}function pl(a){return!(!a||1!==a.nodeType&&9!==a.nodeType&&11!==a.nodeType&&(8!==a.nodeType||" react-mount-point-unstable "!==a.nodeValue))}function ql(){}
function rl(a,b,c,d,e){if(e){if("function"===typeof d){var f=d;d=function(){var a=hl(g);f.call(a)}}var g=fl(b,d,a,0,null,!1,!1,"",ql);a._reactRootContainer=g;a[uf]=g.current;sf(8===a.nodeType?a.parentNode:a);Sk();return g}for(;e=a.lastChild;)a.removeChild(e);if("function"===typeof d){var h=d;d=function(){var a=hl(k);h.call(a)}}var k=cl(a,0,!1,null,null,!1,!1,"",ql);a._reactRootContainer=k;a[uf]=k.current;sf(8===a.nodeType?a.parentNode:a);Sk(function(){gl(b,k,c,d)});return k}
function sl(a,b,c,d,e){var f=c._reactRootContainer;if(f){var g=f;if("function"===typeof e){var h=e;e=function(){var a=hl(g);h.call(a)}}gl(b,g,a,e)}else g=rl(c,b,a,e,d);return hl(g)}Ec=function(a){switch(a.tag){case 3:var b=a.stateNode;if(b.current.memoizedState.isDehydrated){var c=tc(b.pendingLanes);0!==c&&(Cc(b,c|1),Ek(b,B()),0===(K&6)&&(Hj=B()+500,jg()))}break;case 13:Sk(function(){var b=Zg(a,1);if(null!==b){var c=L();mh(b,a,1,c)}}),jl(a,1)}};
Fc=function(a){if(13===a.tag){var b=Zg(a,134217728);if(null!==b){var c=L();mh(b,a,134217728,c)}jl(a,134217728)}};Gc=function(a){if(13===a.tag){var b=lh(a),c=Zg(a,b);if(null!==c){var d=L();mh(c,a,b,d)}jl(a,b)}};Hc=function(){return C};Ic=function(a,b){var c=C;try{return C=a,b()}finally{C=c}};
yb=function(a,b,c){switch(b){case "input":bb(a,c);b=c.name;if("radio"===c.type&&null!=b){for(c=a;c.parentNode;)c=c.parentNode;c=c.querySelectorAll("input[name="+JSON.stringify(""+b)+'][type="radio"]');for(b=0;b<c.length;b++){var d=c[b];if(d!==a&&d.form===a.form){var e=Db(d);if(!e)throw Error(p(90));Wa(d);bb(d,e)}}}break;case "textarea":ib(a,c);break;case "select":b=c.value,null!=b&&fb(a,!!c.multiple,b,!1)}};Gb=Rk;Hb=Sk;
var tl={usingClientEntryPoint:!1,Events:[Cb,ue,Db,Eb,Fb,Rk]},ul={findFiberByHostInstance:Wc,bundleType:0,version:"18.2.0",rendererPackageName:"react-dom"};
var vl={bundleType:ul.bundleType,version:ul.version,rendererPackageName:ul.rendererPackageName,rendererConfig:ul.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:ua.ReactCurrentDispatcher,findHostInstanceByFiber:function(a){a=Zb(a);return null===a?null:a.stateNode},findFiberByHostInstance:ul.findFiberByHostInstance||
kl,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.2.0-next-9e3b772b8-20220608"};if("undefined"!==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__){var wl=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!wl.isDisabled&&wl.supportsFiber)try{kc=wl.inject(vl),lc=wl}catch(a){}}exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=tl;
exports.createPortal=function(a,b){var c=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;if(!ol(b))throw Error(p(200));return dl(a,b,null,c)};exports.createRoot=function(a,b){if(!ol(a))throw Error(p(299));var c=!1,d="",e=ll;null!==b&&void 0!==b&&(!0===b.unstable_strictMode&&(c=!0),void 0!==b.identifierPrefix&&(d=b.identifierPrefix),void 0!==b.onRecoverableError&&(e=b.onRecoverableError));b=cl(a,1,!1,null,null,c,!1,d,e);a[uf]=b.current;sf(8===a.nodeType?a.parentNode:a);return new ml(b)};
exports.findDOMNode=function(a){if(null==a)return null;if(1===a.nodeType)return a;var b=a._reactInternals;if(void 0===b){if("function"===typeof a.render)throw Error(p(188));a=Object.keys(a).join(",");throw Error(p(268,a));}a=Zb(b);a=null===a?null:a.stateNode;return a};exports.flushSync=function(a){return Sk(a)};exports.hydrate=function(a,b,c){if(!pl(b))throw Error(p(200));return sl(null,a,b,!0,c)};
exports.hydrateRoot=function(a,b,c){if(!ol(a))throw Error(p(405));var d=null!=c&&c.hydratedSources||null,e=!1,f="",g=ll;null!==c&&void 0!==c&&(!0===c.unstable_strictMode&&(e=!0),void 0!==c.identifierPrefix&&(f=c.identifierPrefix),void 0!==c.onRecoverableError&&(g=c.onRecoverableError));b=fl(b,null,a,1,null!=c?c:null,e,!1,f,g);a[uf]=b.current;sf(a);if(d)for(a=0;a<d.length;a++)c=d[a],e=c._getVersion,e=e(c._source),null==b.mutableSourceEagerHydrationData?b.mutableSourceEagerHydrationData=[c,e]:b.mutableSourceEagerHydrationData.push(c,
e);return new nl(b)};exports.render=function(a,b,c){if(!pl(b))throw Error(p(200));return sl(null,a,b,!1,c)};exports.unmountComponentAtNode=function(a){if(!pl(a))throw Error(p(40));return a._reactRootContainer?(Sk(function(){sl(null,null,a,!1,function(){a._reactRootContainer=null;a[uf]=null})}),!0):!1};exports.unstable_batchedUpdates=Rk;
exports.unstable_renderSubtreeIntoContainer=function(a,b,c,d){if(!pl(c))throw Error(p(200));if(null==a||void 0===a._reactInternals)throw Error(p(38));return sl(a,b,c,!1,d)};exports.version="18.2.0-next-9e3b772b8-20220608";
webpack://frontend-mybets/../../node_modules/react-dom/client.js
'use strict';
var m = require('react-dom');
if (process.env.NODE_ENV === 'production') {
exports.createRoot = m.createRoot;
exports.hydrateRoot = m.hydrateRoot;
} else {
var i = m.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
exports.createRoot = function(c, o) {
i.usingClientEntryPoint = true;
try {
return m.createRoot(c, o);
} finally {
i.usingClientEntryPoint = false;
}
};
exports.hydrateRoot = function(c, h, o) {
i.usingClientEntryPoint = true;
try {
return m.hydrateRoot(c, h, o);
} finally {
i.usingClientEntryPoint = false;
}
};
}
webpack://frontend-mybets/../../node_modules/react-dom/index.js
'use strict';
function checkDCE() {
/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
if (
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' ||
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function'
) {
return;
}
if (process.env.NODE_ENV !== 'production') {
// This branch is unreachable because this function is only called
// in production, but the condition is true only in development.
// Therefore if the branch is still here, dead code elimination wasn't
// properly applied.
// Don't change the message. React DevTools relies on it. Also make sure
// this message doesn't occur elsewhere in this function, or it will cause
// a false positive.
throw new Error('^_^');
}
try {
// Verify that the code above has been dead code eliminated (DCE'd).
__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);
} catch (err) {
// DevTools shouldn't crash React, no matter what.
// We should still report in case we break this code.
console.error(err);
}
}
if (process.env.NODE_ENV === 'production') {
// DCE check should happen before ReactDOM bundle executes so that
// DevTools can report bad minification during injection.
checkDCE();
module.exports = require('./cjs/react-dom.production.min.js');
} else {
module.exports = require('./cjs/react-dom.development.js');
}
webpack://frontend-mybets/../../node_modules/react-fast-compare/index.js
/* global Map:readonly, Set:readonly, ArrayBuffer:readonly */
var hasElementType = typeof Element !== 'undefined';
var hasMap = typeof Map === 'function';
var hasSet = typeof Set === 'function';
var hasArrayBuffer = typeof ArrayBuffer === 'function' && !!ArrayBuffer.isView;
// Note: We **don't** need `envHasBigInt64Array` in fde es6/index.js
function equal(a, b) {
// START: fast-deep-equal es6/index.js 3.1.3
if (a === b) return true;
if (a && b && typeof a == 'object' && typeof b == 'object') {
if (a.constructor !== b.constructor) return false;
var length, i, keys;
if (Array.isArray(a)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (!equal(a[i], b[i])) return false;
return true;
}
// START: Modifications:
// 1. Extra `has<Type> &&` helpers in initial condition allow es6 code
// to co-exist with es5.
// 2. Replace `for of` with es5 compliant iteration using `for`.
// Basically, take:
//
// ```js
// for (i of a.entries())
// if (!b.has(i[0])) return false;
// ```
//
// ... and convert to:
//
// ```js
// it = a.entries();
// while (!(i = it.next()).done)
// if (!b.has(i.value[0])) return false;
// ```
//
// **Note**: `i` access switches to `i.value`.
var it;
if (hasMap && (a instanceof Map) && (b instanceof Map)) {
if (a.size !== b.size) return false;
it = a.entries();
while (!(i = it.next()).done)
if (!b.has(i.value[0])) return false;
it = a.entries();
while (!(i = it.next()).done)
if (!equal(i.value[1], b.get(i.value[0]))) return false;
return true;
}
if (hasSet && (a instanceof Set) && (b instanceof Set)) {
if (a.size !== b.size) return false;
it = a.entries();
while (!(i = it.next()).done)
if (!b.has(i.value[0])) return false;
return true;
}
// END: Modifications
if (hasArrayBuffer && ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (a[i] !== b[i]) return false;
return true;
}
if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
// START: Modifications:
// Apply guards for `Object.create(null)` handling. See:
// - https://github.com/FormidableLabs/react-fast-compare/issues/64
// - https://github.com/epoberezkin/fast-deep-equal/issues/49
if (a.valueOf !== Object.prototype.valueOf && typeof a.valueOf === 'function' && typeof b.valueOf === 'function') return a.valueOf() === b.valueOf();
if (a.toString !== Object.prototype.toString && typeof a.toString === 'function' && typeof b.toString === 'function') return a.toString() === b.toString();
// END: Modifications
keys = Object.keys(a);
length = keys.length;
if (length !== Object.keys(b).length) return false;
for (i = length; i-- !== 0;)
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
// END: fast-deep-equal
// START: react-fast-compare
// custom handling for DOM elements
if (hasElementType && a instanceof Element) return false;
// custom handling for React/Preact
for (i = length; i-- !== 0;) {
if ((keys[i] === '_owner' || keys[i] === '__v' || keys[i] === '__o') && a.$$typeof) {
// React-specific: avoid traversing React elements' _owner
// Preact-specific: avoid traversing Preact elements' __v and __o
// __v = $_original / $_vnode
// __o = $_owner
// These properties contain circular references and are not needed when
// comparing the actual elements (and not their owners)
// .$$typeof and ._store on just reasonable markers of elements
continue;
}
// all other properties should be traversed as usual
if (!equal(a[keys[i]], b[keys[i]])) return false;
}
// END: react-fast-compare
// START: fast-deep-equal
return true;
}
return a !== a && b !== b;
}
// end fast-deep-equal
module.exports = function isEqual(a, b) {
try {
return equal(a, b);
} catch (error) {
if (((error.message || '').match(/stack|recursion/i))) {
// warn on circular references, don't crash
// browsers give this different errors name and messages:
// chrome/safari: "RangeError", "Maximum call stack size exceeded"
// firefox: "InternalError", too much recursion"
// edge: "Error", "Out of stack space"
console.warn('react-fast-compare cannot handle circular refs');
return false;
}
// some other error. we should definitely know about these
throw error;
}
};
webpack://frontend-mybets/../../node_modules/react-infinite-scroller/dist/InfiniteScroll.js
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var InfiniteScroll = function (_Component) {
_inherits(InfiniteScroll, _Component);
function InfiniteScroll(props) {
_classCallCheck(this, InfiniteScroll);
var _this = _possibleConstructorReturn(this, (InfiniteScroll.__proto__ || Object.getPrototypeOf(InfiniteScroll)).call(this, props));
_this.scrollListener = _this.scrollListener.bind(_this);
_this.eventListenerOptions = _this.eventListenerOptions.bind(_this);
_this.mousewheelListener = _this.mousewheelListener.bind(_this);
return _this;
}
_createClass(InfiniteScroll, [{
key: 'componentDidMount',
value: function componentDidMount() {
this.pageLoaded = this.props.pageStart;
this.options = this.eventListenerOptions();
this.attachScrollListener();
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate() {
if (this.props.isReverse && this.loadMore) {
var parentElement = this.getParentElement(this.scrollComponent);
parentElement.scrollTop = parentElement.scrollHeight - this.beforeScrollHeight + this.beforeScrollTop;
this.loadMore = false;
}
this.attachScrollListener();
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.detachScrollListener();
this.detachMousewheelListener();
}
}, {
key: 'isPassiveSupported',
value: function isPassiveSupported() {
var passive = false;
var testOptions = {
get passive() {
passive = true;
}
};
try {
document.addEventListener('test', null, testOptions);
document.removeEventListener('test', null, testOptions);
} catch (e) {
// ignore
}
return passive;
}
}, {
key: 'eventListenerOptions',
value: function eventListenerOptions() {
var options = this.props.useCapture;
if (this.isPassiveSupported()) {
options = {
useCapture: this.props.useCapture,
passive: true
};
} else {
options = {
passive: false
};
}
return options;
}
// Set a defaut loader for all your `InfiniteScroll` components
}, {
key: 'setDefaultLoader',
value: function setDefaultLoader(loader) {
this.defaultLoader = loader;
}
}, {
key: 'detachMousewheelListener',
value: function detachMousewheelListener() {
var scrollEl = window;
if (this.props.useWindow === false) {
scrollEl = this.scrollComponent.parentNode;
}
scrollEl.removeEventListener('mousewheel', this.mousewheelListener, this.options ? this.options : this.props.useCapture);
}
}, {
key: 'detachScrollListener',
value: function detachScrollListener() {
var scrollEl = window;
if (this.props.useWindow === false) {
scrollEl = this.getParentElement(this.scrollComponent);
}
scrollEl.removeEventListener('scroll', this.scrollListener, this.options ? this.options : this.props.useCapture);
scrollEl.removeEventListener('resize', this.scrollListener, this.options ? this.options : this.props.useCapture);
}
}, {
key: 'getParentElement',
value: function getParentElement(el) {
var scrollParent = this.props.getScrollParent && this.props.getScrollParent();
if (scrollParent != null) {
return scrollParent;
}
return el && el.parentNode;
}
}, {
key: 'filterProps',
value: function filterProps(props) {
return props;
}
}, {
key: 'attachScrollListener',
value: function attachScrollListener() {
var parentElement = this.getParentElement(this.scrollComponent);
if (!this.props.hasMore || !parentElement) {
return;
}
var scrollEl = window;
if (this.props.useWindow === false) {
scrollEl = parentElement;
}
scrollEl.addEventListener('mousewheel', this.mousewheelListener, this.options ? this.options : this.props.useCapture);
scrollEl.addEventListener('scroll', this.scrollListener, this.options ? this.options : this.props.useCapture);
scrollEl.addEventListener('resize', this.scrollListener, this.options ? this.options : this.props.useCapture);
if (this.props.initialLoad) {
this.scrollListener();
}
}
}, {
key: 'mousewheelListener',
value: function mousewheelListener(e) {
// Prevents Chrome hangups
// See: https://stackoverflow.com/questions/47524205/random-high-content-download-time-in-chrome/47684257#47684257
if (e.deltaY === 1 && !this.isPassiveSupported()) {
e.preventDefault();
}
}
}, {
key: 'scrollListener',
value: function scrollListener() {
var el = this.scrollComponent;
var scrollEl = window;
var parentNode = this.getParentElement(el);
var offset = void 0;
if (this.props.useWindow) {
var doc = document.documentElement || document.body.parentNode || document.body;
var scrollTop = scrollEl.pageYOffset !== undefined ? scrollEl.pageYOffset : doc.scrollTop;
if (this.props.isReverse) {
offset = scrollTop;
} else {
offset = this.calculateOffset(el, scrollTop);
}
} else if (this.props.isReverse) {
offset = parentNode.scrollTop;
} else {
offset = el.scrollHeight - parentNode.scrollTop - parentNode.clientHeight;
}
// Here we make sure the element is visible as well as checking the offset
if (offset < Number(this.props.threshold) && el && el.offsetParent !== null) {
this.detachScrollListener();
this.beforeScrollHeight = parentNode.scrollHeight;
this.beforeScrollTop = parentNode.scrollTop;
// Call loadMore after detachScrollListener to allow for non-async loadMore functions
if (typeof this.props.loadMore === 'function') {
this.props.loadMore(this.pageLoaded += 1);
this.loadMore = true;
}
}
}
}, {
key: 'calculateOffset',
value: function calculateOffset(el, scrollTop) {
if (!el) {
return 0;
}
return this.calculateTopPosition(el) + (el.offsetHeight - scrollTop - window.innerHeight);
}
}, {
key: 'calculateTopPosition',
value: function calculateTopPosition(el) {
if (!el) {
return 0;
}
return el.offsetTop + this.calculateTopPosition(el.offsetParent);
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
var renderProps = this.filterProps(this.props);
var children = renderProps.children,
element = renderProps.element,
hasMore = renderProps.hasMore,
initialLoad = renderProps.initialLoad,
isReverse = renderProps.isReverse,
loader = renderProps.loader,
loadMore = renderProps.loadMore,
pageStart = renderProps.pageStart,
ref = renderProps.ref,
threshold = renderProps.threshold,
useCapture = renderProps.useCapture,
useWindow = renderProps.useWindow,
getScrollParent = renderProps.getScrollParent,
props = _objectWithoutProperties(renderProps, ['children', 'element', 'hasMore', 'initialLoad', 'isReverse', 'loader', 'loadMore', 'pageStart', 'ref', 'threshold', 'useCapture', 'useWindow', 'getScrollParent']);
props.ref = function (node) {
_this2.scrollComponent = node;
if (ref) {
ref(node);
}
};
var childrenArray = [children];
if (hasMore) {
if (loader) {
isReverse ? childrenArray.unshift(loader) : childrenArray.push(loader);
} else if (this.defaultLoader) {
isReverse ? childrenArray.unshift(this.defaultLoader) : childrenArray.push(this.defaultLoader);
}
}
return _react2.default.createElement(element, props, childrenArray);
}
}]);
return InfiniteScroll;
}(_react.Component);
InfiniteScroll.propTypes = {
children: _propTypes2.default.node.isRequired,
element: _propTypes2.default.node,
hasMore: _propTypes2.default.bool,
initialLoad: _propTypes2.default.bool,
isReverse: _propTypes2.default.bool,
loader: _propTypes2.default.node,
loadMore: _propTypes2.default.func.isRequired,
pageStart: _propTypes2.default.number,
ref: _propTypes2.default.func,
getScrollParent: _propTypes2.default.func,
threshold: _propTypes2.default.number,
useCapture: _propTypes2.default.bool,
useWindow: _propTypes2.default.bool
};
InfiniteScroll.defaultProps = {
element: 'div',
hasMore: false,
initialLoad: true,
pageStart: 0,
ref: null,
threshold: 250,
useWindow: true,
isReverse: false,
useCapture: false,
loader: null,
getScrollParent: null
};
exports.default = InfiniteScroll;
module.exports = exports['default'];
webpack://frontend-mybets/../../node_modules/react-infinite-scroller/index.js
module.exports = require('./dist/InfiniteScroll')
webpack://frontend-mybets/../../node_modules/react-is/cjs/react-is.production.min.js
/**
* @license React
* react-is.production.min.js
*
* 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.
*/
'use strict';var b=Symbol.for("react.element"),c=Symbol.for("react.portal"),d=Symbol.for("react.fragment"),e=Symbol.for("react.strict_mode"),f=Symbol.for("react.profiler"),g=Symbol.for("react.provider"),h=Symbol.for("react.context"),k=Symbol.for("react.server_context"),l=Symbol.for("react.forward_ref"),m=Symbol.for("react.suspense"),n=Symbol.for("react.suspense_list"),p=Symbol.for("react.memo"),q=Symbol.for("react.lazy"),t=Symbol.for("react.offscreen"),u;u=Symbol.for("react.module.reference");
function v(a){if("object"===typeof a&&null!==a){var r=a.$$typeof;switch(r){case b:switch(a=a.type,a){case d:case f:case e:case m:case n:return a;default:switch(a=a&&a.$$typeof,a){case k:case h:case l:case q:case p:case g:return a;default:return r}}case c:return r}}}exports.ContextConsumer=h;exports.ContextProvider=g;exports.Element=b;exports.ForwardRef=l;exports.Fragment=d;exports.Lazy=q;exports.Memo=p;exports.Portal=c;exports.Profiler=f;exports.StrictMode=e;exports.Suspense=m;
exports.SuspenseList=n;exports.isAsyncMode=function(){return!1};exports.isConcurrentMode=function(){return!1};exports.isContextConsumer=function(a){return v(a)===h};exports.isContextProvider=function(a){return v(a)===g};exports.isElement=function(a){return"object"===typeof a&&null!==a&&a.$$typeof===b};exports.isForwardRef=function(a){return v(a)===l};exports.isFragment=function(a){return v(a)===d};exports.isLazy=function(a){return v(a)===q};exports.isMemo=function(a){return v(a)===p};
exports.isPortal=function(a){return v(a)===c};exports.isProfiler=function(a){return v(a)===f};exports.isStrictMode=function(a){return v(a)===e};exports.isSuspense=function(a){return v(a)===m};exports.isSuspenseList=function(a){return v(a)===n};
exports.isValidElementType=function(a){return"string"===typeof a||"function"===typeof a||a===d||a===f||a===e||a===m||a===n||a===t||"object"===typeof a&&null!==a&&(a.$$typeof===q||a.$$typeof===p||a.$$typeof===g||a.$$typeof===h||a.$$typeof===l||a.$$typeof===u||void 0!==a.getModuleId)?!0:!1};exports.typeOf=v;
webpack://frontend-mybets/../../node_modules/react-is/index.js
'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/react-is.production.min.js');
} else {
module.exports = require('./cjs/react-is.development.js');
}
webpack://frontend-mybets/../../node_modules/react-native-safe-area-context/lib/module/NativeSafeAreaProvider.js
/* eslint-env browser */
import * as React from 'react';
import { View } from 'react-native';
/**
* TODO:
* Currently insets and frame are based on the window and are not
* relative to the provider view. This is inconsistent with iOS and Android.
* However in most cases if the provider view covers the screen this is not
* an issue.
*/
const CSSTransitions = {
WebkitTransition: 'webkitTransitionEnd',
Transition: 'transitionEnd',
MozTransition: 'transitionend',
MSTransition: 'msTransitionEnd',
OTransition: 'oTransitionEnd'
};
export default function NativeSafeAreaView({
children,
style,
onInsetsChange
}) {
React.useEffect(() => {
// Skip for SSR.
if (typeof document === 'undefined') {
return;
}
const element = createContextElement();
document.body.appendChild(element);
const onEnd = () => {
const {
paddingTop,
paddingBottom,
paddingLeft,
paddingRight
} = window.getComputedStyle(element);
const insets = {
top: paddingTop ? parseInt(paddingTop, 10) : 0,
bottom: paddingBottom ? parseInt(paddingBottom, 10) : 0,
left: paddingLeft ? parseInt(paddingLeft, 10) : 0,
right: paddingRight ? parseInt(paddingRight, 10) : 0
};
const frame = {
x: 0,
y: 0,
width: document.documentElement.offsetWidth,
height: document.documentElement.offsetHeight
}; // @ts-ignore: missing properties
onInsetsChange({
nativeEvent: {
insets,
frame
}
});
};
element.addEventListener(getSupportedTransitionEvent(), onEnd);
onEnd();
return () => {
document.body.removeChild(element);
element.removeEventListener(getSupportedTransitionEvent(), onEnd);
};
}, [onInsetsChange]);
return /*#__PURE__*/React.createElement(View, {
style: style
}, children);
}
let _supportedTransitionEvent = null;
function getSupportedTransitionEvent() {
if (_supportedTransitionEvent !== null) {
return _supportedTransitionEvent;
}
const element = document.createElement('invalidtype');
_supportedTransitionEvent = CSSTransitions.Transition;
for (const key in CSSTransitions) {
if (element.style[key] !== undefined) {
_supportedTransitionEvent = CSSTransitions[key];
break;
}
}
return _supportedTransitionEvent;
}
let _supportedEnv = null;
function getSupportedEnv() {
if (_supportedEnv !== null) {
return _supportedEnv;
}
const {
CSS
} = window;
if (CSS && CSS.supports && CSS.supports('top: constant(safe-area-inset-top)')) {
_supportedEnv = 'constant';
} else {
_supportedEnv = 'env';
}
return _supportedEnv;
}
function getInset(side) {
return `${getSupportedEnv()}(safe-area-inset-${side})`;
}
function createContextElement() {
const element = document.createElement('div');
const {
style
} = element;
style.position = 'fixed';
style.left = '0';
style.top = '0';
style.width = '0';
style.height = '0';
style.zIndex = '-1';
style.overflow = 'hidden';
style.visibility = 'hidden'; // Bacon: Anything faster than this and the callback will be invoked too early with the wrong insets
style.transitionDuration = '0.05s';
style.transitionProperty = 'padding';
style.transitionDelay = '0s';
style.paddingTop = getInset('top');
style.paddingBottom = getInset('bottom');
style.paddingLeft = getInset('left');
style.paddingRight = getInset('right');
return element;
}
//# sourceMappingURL=NativeSafeAreaProvider.js.map
webpack://frontend-mybets/../../node_modules/react-native-safe-area-context/lib/module/SafeAreaContext.js
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); }
import * as React from 'react';
import { Dimensions, StyleSheet } from 'react-native';
import NativeSafeAreaProvider from './NativeSafeAreaProvider';
export const SafeAreaInsetsContext = /*#__PURE__*/React.createContext(null);
SafeAreaInsetsContext.displayName = 'SafeAreaInsetsContext';
export const SafeAreaFrameContext = /*#__PURE__*/React.createContext(null);
SafeAreaFrameContext.displayName = 'SafeAreaFrameContext';
export function SafeAreaProvider({
children,
initialMetrics,
initialSafeAreaInsets,
style
}) {
var _ref, _ref2, _initialMetrics$inset, _ref3, _initialMetrics$frame;
const parentInsets = useParentSafeAreaInsets();
const parentFrame = useParentSafeAreaFrame();
const [insets, setInsets] = React.useState((_ref = (_ref2 = (_initialMetrics$inset = initialMetrics === null || initialMetrics === void 0 ? void 0 : initialMetrics.insets) !== null && _initialMetrics$inset !== void 0 ? _initialMetrics$inset : initialSafeAreaInsets) !== null && _ref2 !== void 0 ? _ref2 : parentInsets) !== null && _ref !== void 0 ? _ref : null);
const [frame, setFrame] = React.useState((_ref3 = (_initialMetrics$frame = initialMetrics === null || initialMetrics === void 0 ? void 0 : initialMetrics.frame) !== null && _initialMetrics$frame !== void 0 ? _initialMetrics$frame : parentFrame) !== null && _ref3 !== void 0 ? _ref3 : {
// Backwards compat so we render anyway if we don't have frame.
x: 0,
y: 0,
width: Dimensions.get('window').width,
height: Dimensions.get('window').height
});
const onInsetsChange = React.useCallback(event => {
const {
nativeEvent: {
frame: nextFrame,
insets: nextInsets
}
} = event;
if ( // Backwards compat with old native code that won't send frame.
nextFrame && (nextFrame.height !== frame.height || nextFrame.width !== frame.width || nextFrame.x !== frame.x || nextFrame.y !== frame.y)) {
setFrame(nextFrame);
}
if (!insets || nextInsets.bottom !== insets.bottom || nextInsets.left !== insets.left || nextInsets.right !== insets.right || nextInsets.top !== insets.top) {
setInsets(nextInsets);
}
}, [frame, insets]);
return /*#__PURE__*/React.createElement(NativeSafeAreaProvider, {
style: [styles.fill, style],
onInsetsChange: onInsetsChange
}, insets != null ? /*#__PURE__*/React.createElement(SafeAreaFrameContext.Provider, {
value: frame
}, /*#__PURE__*/React.createElement(SafeAreaInsetsContext.Provider, {
value: insets
}, children)) : null);
}
const styles = StyleSheet.create({
fill: {
flex: 1
}
});
function useParentSafeAreaInsets() {
return React.useContext(SafeAreaInsetsContext);
}
function useParentSafeAreaFrame() {
return React.useContext(SafeAreaFrameContext);
}
export function useSafeAreaInsets() {
const safeArea = React.useContext(SafeAreaInsetsContext);
if (safeArea == null) {
throw new Error('No safe area insets value available. Make sure you are rendering `<SafeAreaProvider>` at the top of your app.');
}
return safeArea;
}
export function useSafeAreaFrame() {
const frame = React.useContext(SafeAreaFrameContext);
if (frame == null) {
throw new Error('No safe area frame value available. Make sure you are rendering `<SafeAreaProvider>` at the top of your app.');
}
return frame;
}
export function withSafeAreaInsets(WrappedComponent) {
return /*#__PURE__*/React.forwardRef((props, ref) => /*#__PURE__*/React.createElement(SafeAreaConsumer, null, insets => /*#__PURE__*/React.createElement(WrappedComponent, _extends({}, props, {
insets: insets,
ref: ref
}))));
}
/**
* @deprecated
*/
export function useSafeArea() {
return useSafeAreaInsets();
}
/**
* @deprecated
*/
export const SafeAreaConsumer = SafeAreaInsetsContext.Consumer;
/**
* @deprecated
*/
export const SafeAreaContext = SafeAreaInsetsContext;
//# sourceMappingURL=SafeAreaContext.js.map
webpack://frontend-mybets/../../node_modules/react-native-svg/lib/module/ReactNativeSVG.web.js
var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=exports.WebShape=exports.Use=exports.TextPath=exports.Text=exports.TSpan=exports.Symbol=exports.Svg=exports.Stop=exports.Rect=exports.RadialGradient=exports.Polyline=exports.Polygon=exports.Pattern=exports.Path=exports.Mask=exports.Marker=exports.LinearGradient=exports.Line=exports.Image=exports.G=exports.ForeignObject=exports.Ellipse=exports.Defs=exports.ClipPath=exports.Circle=void 0;var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _assertThisInitialized2=_interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));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 _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _objectWithoutProperties2=_interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));var React=_interopRequireWildcard(require("react"));var _reactNative=require("react-native");var _SvgTouchableMixin=_interopRequireDefault(require("./lib/SvgTouchableMixin"));var _resolve=require("./lib/resolve");var _excluded=["translate","translateX","translateY","scale","rotation","skewX","skewY","originX","originY","fontFamily","fontSize","fontWeight","fontStyle","style","forwardedRef"],_excluded2=["x","y"];function _getRequireWildcardCache(nodeInterop){if(typeof WeakMap!=="function")return null;var cacheBabelInterop=new WeakMap();var cacheNodeInterop=new WeakMap();return(_getRequireWildcardCache=function _getRequireWildcardCache(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop;})(nodeInterop);}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule){return obj;}if(obj===null||typeof obj!=="object"&&typeof obj!=="function"){return{default:obj};}var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj)){return cache.get(obj);}var newObj={};var hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj){if(key!=="default"&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;if(desc&&(desc.get||desc.set)){Object.defineProperty(newObj,key,desc);}else{newObj[key]=obj[key];}}}newObj.default=obj;if(cache){cache.set(obj,newObj);}return newObj;}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{Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));return true;}catch(e){return false;}}var createElement=_reactNative.createElement||_reactNative.unstable_createElement;var hasTouchableProperty=function hasTouchableProperty(props){return props.onPress||props.onPressIn||props.onPressOut||props.onLongPress;};var prepare=function prepare(self){var props=arguments.length>1&&arguments[1]!==undefined?arguments[1]:self.props;var translate=props.translate,translateX=props.translateX,translateY=props.translateY,scale=props.scale,rotation=props.rotation,skewX=props.skewX,skewY=props.skewY,originX=props.originX,originY=props.originY,fontFamily=props.fontFamily,fontSize=props.fontSize,fontWeight=props.fontWeight,fontStyle=props.fontStyle,style=props.style,forwardedRef=props.forwardedRef,rest=(0,_objectWithoutProperties2.default)(props,_excluded);var clean=Object.assign({},hasTouchableProperty(props)?{onStartShouldSetResponder:self.touchableHandleStartShouldSetResponder,onResponderTerminationRequest:self.touchableHandleResponderTerminationRequest,onResponderGrant:self.touchableHandleResponderGrant,onResponderMove:self.touchableHandleResponderMove,onResponderRelease:self.touchableHandleResponderRelease,onResponderTerminate:self.touchableHandleResponderTerminate}:null,rest);var transform=[];if(originX!=null||originY!=null){transform.push("translate("+(originX||0)+", "+(originY||0)+")");}if(translate!=null){transform.push("translate("+translate+")");}if(translateX!=null||translateY!=null){transform.push("translate("+(translateX||0)+", "+(translateY||0)+")");}if(scale!=null){transform.push("scale("+scale+")");}if(rotation!=null){transform.push("rotate("+rotation+")");}if(skewX!=null){transform.push("skewX("+skewX+")");}if(skewY!=null){transform.push("skewY("+skewY+")");}if(originX!=null||originY!=null){transform.push("translate("+(-originX||0)+", "+(-originY||0)+")");}if(transform.length){clean.transform=transform.join(' ');}if(forwardedRef){clean.ref=forwardedRef;}var styles={};if(fontFamily!=null){styles.fontFamily=fontFamily;}if(fontSize!=null){styles.fontSize=fontSize;}if(fontWeight!=null){styles.fontWeight=fontWeight;}if(fontStyle!=null){styles.fontStyle=fontStyle;}clean.style=(0,_resolve.resolve)(style,styles);return clean;};var getBoundingClientRect=function getBoundingClientRect(node){if(node){var isElement=node.nodeType===1;if(isElement&&typeof node.getBoundingClientRect==='function'){return node.getBoundingClientRect();}}};var measureLayout=function measureLayout(node,callback){var relativeNode=node&&node.parentNode;if(relativeNode){setTimeout(function(){var relativeRect=getBoundingClientRect(relativeNode);var _getBoundingClientRec=getBoundingClientRect(node),height=_getBoundingClientRec.height,left=_getBoundingClientRec.left,top=_getBoundingClientRec.top,width=_getBoundingClientRec.width;var x=left-relativeRect.left;var y=top-relativeRect.top;callback(x,y,width,height,left,top);},0);}};function remeasure(){var tag=this.state.touchable.responderID;if(tag==null){return;}measureLayout(tag,this._handleQueryLayout);}var WebShape=function(_React$Component){(0,_inherits2.default)(WebShape,_React$Component);var _super=_createSuper(WebShape);function WebShape(props,context){var _this;(0,_classCallCheck2.default)(this,WebShape);_this=_super.call(this,props,context);(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"_remeasureMetricsOnActivation",void 0);(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"touchableHandleStartShouldSetResponder",void 0);(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"touchableHandleResponderMove",void 0);(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"touchableHandleResponderGrant",void 0);(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"touchableHandleResponderRelease",void 0);(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"touchableHandleResponderTerminate",void 0);(0,_defineProperty2.default)((0,_assertThisInitialized2.default)(_this),"touchableHandleResponderTerminationRequest",void 0);if(hasTouchableProperty(props)){(0,_SvgTouchableMixin.default)((0,_assertThisInitialized2.default)(_this));}_this._remeasureMetricsOnActivation=remeasure.bind((0,_assertThisInitialized2.default)(_this));return _this;}return(0,_createClass2.default)(WebShape);}(React.Component);exports.WebShape=WebShape;var Circle=function(_WebShape){(0,_inherits2.default)(Circle,_WebShape);var _super2=_createSuper(Circle);function Circle(){(0,_classCallCheck2.default)(this,Circle);return _super2.apply(this,arguments);}(0,_createClass2.default)(Circle,[{key:"render",value:function render(){return createElement('circle',prepare(this));}}]);return Circle;}(WebShape);exports.Circle=Circle;var ClipPath=function(_WebShape2){(0,_inherits2.default)(ClipPath,_WebShape2);var _super3=_createSuper(ClipPath);function ClipPath(){(0,_classCallCheck2.default)(this,ClipPath);return _super3.apply(this,arguments);}(0,_createClass2.default)(ClipPath,[{key:"render",value:function render(){return createElement('clipPath',prepare(this));}}]);return ClipPath;}(WebShape);exports.ClipPath=ClipPath;var Defs=function(_WebShape3){(0,_inherits2.default)(Defs,_WebShape3);var _super4=_createSuper(Defs);function Defs(){(0,_classCallCheck2.default)(this,Defs);return _super4.apply(this,arguments);}(0,_createClass2.default)(Defs,[{key:"render",value:function render(){return createElement('defs',prepare(this));}}]);return Defs;}(WebShape);exports.Defs=Defs;var Ellipse=function(_WebShape4){(0,_inherits2.default)(Ellipse,_WebShape4);var _super5=_createSuper(Ellipse);function Ellipse(){(0,_classCallCheck2.default)(this,Ellipse);return _super5.apply(this,arguments);}(0,_createClass2.default)(Ellipse,[{key:"render",value:function render(){return createElement('ellipse',prepare(this));}}]);return Ellipse;}(WebShape);exports.Ellipse=Ellipse;var G=function(_WebShape5){(0,_inherits2.default)(G,_WebShape5);var _super6=_createSuper(G);function G(){(0,_classCallCheck2.default)(this,G);return _super6.apply(this,arguments);}(0,_createClass2.default)(G,[{key:"render",value:function render(){var _this$props=this.props,x=_this$props.x,y=_this$props.y,rest=(0,_objectWithoutProperties2.default)(_this$props,_excluded2);if((x||y)&&!rest.translate){rest.translate=(x||0)+", "+(y||0);}return createElement('g',prepare(this,rest));}}]);return G;}(WebShape);exports.G=G;var Image=function(_WebShape6){(0,_inherits2.default)(Image,_WebShape6);var _super7=_createSuper(Image);function Image(){(0,_classCallCheck2.default)(this,Image);return _super7.apply(this,arguments);}(0,_createClass2.default)(Image,[{key:"render",value:function render(){return createElement('image',prepare(this));}}]);return Image;}(WebShape);exports.Image=Image;var Line=function(_WebShape7){(0,_inherits2.default)(Line,_WebShape7);var _super8=_createSuper(Line);function Line(){(0,_classCallCheck2.default)(this,Line);return _super8.apply(this,arguments);}(0,_createClass2.default)(Line,[{key:"render",value:function render(){return createElement('line',prepare(this));}}]);return Line;}(WebShape);exports.Line=Line;var LinearGradient=function(_WebShape8){(0,_inherits2.default)(LinearGradient,_WebShape8);var _super9=_createSuper(LinearGradient);function LinearGradient(){(0,_classCallCheck2.default)(this,LinearGradient);return _super9.apply(this,arguments);}(0,_createClass2.default)(LinearGradient,[{key:"render",value:function render(){return createElement('linearGradient',prepare(this));}}]);return LinearGradient;}(WebShape);exports.LinearGradient=LinearGradient;var Path=function(_WebShape9){(0,_inherits2.default)(Path,_WebShape9);var _super10=_createSuper(Path);function Path(){(0,_classCallCheck2.default)(this,Path);return _super10.apply(this,arguments);}(0,_createClass2.default)(Path,[{key:"render",value:function render(){return createElement('path',prepare(this));}}]);return Path;}(WebShape);exports.Path=Path;var Polygon=function(_WebShape10){(0,_inherits2.default)(Polygon,_WebShape10);var _super11=_createSuper(Polygon);function Polygon(){(0,_classCallCheck2.default)(this,Polygon);return _super11.apply(this,arguments);}(0,_createClass2.default)(Polygon,[{key:"render",value:function render(){return createElement('polygon',prepare(this));}}]);return Polygon;}(WebShape);exports.Polygon=Polygon;var Polyline=function(_WebShape11){(0,_inherits2.default)(Polyline,_WebShape11);var _super12=_createSuper(Polyline);function Polyline(){(0,_classCallCheck2.default)(this,Polyline);return _super12.apply(this,arguments);}(0,_createClass2.default)(Polyline,[{key:"render",value:function render(){return createElement('polyline',prepare(this));}}]);return Polyline;}(WebShape);exports.Polyline=Polyline;var RadialGradient=function(_WebShape12){(0,_inherits2.default)(RadialGradient,_WebShape12);var _super13=_createSuper(RadialGradient);function RadialGradient(){(0,_classCallCheck2.default)(this,RadialGradient);return _super13.apply(this,arguments);}(0,_createClass2.default)(RadialGradient,[{key:"render",value:function render(){return createElement('radialGradient',prepare(this));}}]);return RadialGradient;}(WebShape);exports.RadialGradient=RadialGradient;var Rect=function(_WebShape13){(0,_inherits2.default)(Rect,_WebShape13);var _super14=_createSuper(Rect);function Rect(){(0,_classCallCheck2.default)(this,Rect);return _super14.apply(this,arguments);}(0,_createClass2.default)(Rect,[{key:"render",value:function render(){return createElement('rect',prepare(this));}}]);return Rect;}(WebShape);exports.Rect=Rect;var Stop=function(_WebShape14){(0,_inherits2.default)(Stop,_WebShape14);var _super15=_createSuper(Stop);function Stop(){(0,_classCallCheck2.default)(this,Stop);return _super15.apply(this,arguments);}(0,_createClass2.default)(Stop,[{key:"render",value:function render(){return createElement('stop',prepare(this));}}]);return Stop;}(WebShape);exports.Stop=Stop;var Svg=function(_WebShape15){(0,_inherits2.default)(Svg,_WebShape15);var _super16=_createSuper(Svg);function Svg(){(0,_classCallCheck2.default)(this,Svg);return _super16.apply(this,arguments);}(0,_createClass2.default)(Svg,[{key:"render",value:function render(){return createElement('svg',prepare(this));}}]);return Svg;}(WebShape);exports.Svg=Svg;var Symbol=function(_WebShape16){(0,_inherits2.default)(Symbol,_WebShape16);var _super17=_createSuper(Symbol);function Symbol(){(0,_classCallCheck2.default)(this,Symbol);return _super17.apply(this,arguments);}(0,_createClass2.default)(Symbol,[{key:"render",value:function render(){return createElement('symbol',prepare(this));}}]);return Symbol;}(WebShape);exports.Symbol=Symbol;var Text=function(_WebShape17){(0,_inherits2.default)(Text,_WebShape17);var _super18=_createSuper(Text);function Text(){(0,_classCallCheck2.default)(this,Text);return _super18.apply(this,arguments);}(0,_createClass2.default)(Text,[{key:"render",value:function render(){return createElement('text',prepare(this));}}]);return Text;}(WebShape);exports.Text=Text;var TSpan=function(_WebShape18){(0,_inherits2.default)(TSpan,_WebShape18);var _super19=_createSuper(TSpan);function TSpan(){(0,_classCallCheck2.default)(this,TSpan);return _super19.apply(this,arguments);}(0,_createClass2.default)(TSpan,[{key:"render",value:function render(){return createElement('tspan',prepare(this));}}]);return TSpan;}(WebShape);exports.TSpan=TSpan;var TextPath=function(_WebShape19){(0,_inherits2.default)(TextPath,_WebShape19);var _super20=_createSuper(TextPath);function TextPath(){(0,_classCallCheck2.default)(this,TextPath);return _super20.apply(this,arguments);}(0,_createClass2.default)(TextPath,[{key:"render",value:function render(){return createElement('textPath',prepare(this));}}]);return TextPath;}(WebShape);exports.TextPath=TextPath;var Use=function(_WebShape20){(0,_inherits2.default)(Use,_WebShape20);var _super21=_createSuper(Use);function Use(){(0,_classCallCheck2.default)(this,Use);return _super21.apply(this,arguments);}(0,_createClass2.default)(Use,[{key:"render",value:function render(){return createElement('use',prepare(this));}}]);return Use;}(WebShape);exports.Use=Use;var Mask=function(_WebShape21){(0,_inherits2.default)(Mask,_WebShape21);var _super22=_createSuper(Mask);function Mask(){(0,_classCallCheck2.default)(this,Mask);return _super22.apply(this,arguments);}(0,_createClass2.default)(Mask,[{key:"render",value:function render(){return createElement('mask',prepare(this));}}]);return Mask;}(WebShape);exports.Mask=Mask;var ForeignObject=function(_WebShape22){(0,_inherits2.default)(ForeignObject,_WebShape22);var _super23=_createSuper(ForeignObject);function ForeignObject(){(0,_classCallCheck2.default)(this,ForeignObject);return _super23.apply(this,arguments);}(0,_createClass2.default)(ForeignObject,[{key:"render",value:function render(){return createElement('foreignObject',prepare(this));}}]);return ForeignObject;}(WebShape);exports.ForeignObject=ForeignObject;var Marker=function(_WebShape23){(0,_inherits2.default)(Marker,_WebShape23);var _super24=_createSuper(Marker);function Marker(){(0,_classCallCheck2.default)(this,Marker);return _super24.apply(this,arguments);}(0,_createClass2.default)(Marker,[{key:"render",value:function render(){return createElement('marker',prepare(this));}}]);return Marker;}(WebShape);exports.Marker=Marker;var Pattern=function(_WebShape24){(0,_inherits2.default)(Pattern,_WebShape24);var _super25=_createSuper(Pattern);function Pattern(){(0,_classCallCheck2.default)(this,Pattern);return _super25.apply(this,arguments);}(0,_createClass2.default)(Pattern,[{key:"render",value:function render(){return createElement('pattern',prepare(this));}}]);return Pattern;}(WebShape);exports.Pattern=Pattern;var _default=Svg;exports.default=_default;
//# sourceMappingURL=ReactNativeSVG.web.js.map
webpack://frontend-mybets/../../node_modules/react-native-svg/lib/module/lib/SvgTouchableMixin.js
Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _reactNative=require("react-native");var PRESS_RETENTION_OFFSET={top:20,left:20,right:20,bottom:30};var Mixin=_reactNative.Touchable.Mixin;var _touchableHandleStartShouldSetResponder=Mixin.touchableHandleStartShouldSetResponder,_touchableHandleResponderTerminationRequest=Mixin.touchableHandleResponderTerminationRequest,_touchableHandleResponderGrant=Mixin.touchableHandleResponderGrant,_touchableHandleResponderMove=Mixin.touchableHandleResponderMove,_touchableHandleResponderRelease=Mixin.touchableHandleResponderRelease,_touchableHandleResponderTerminate=Mixin.touchableHandleResponderTerminate,touchableGetInitialState=Mixin.touchableGetInitialState;var SvgTouchableMixin=Object.assign({},Mixin,{touchableHandleStartShouldSetResponder:function touchableHandleStartShouldSetResponder(e){var onStartShouldSetResponder=this.props.onStartShouldSetResponder;if(onStartShouldSetResponder){return onStartShouldSetResponder(e);}else{return _touchableHandleStartShouldSetResponder.call(this,e);}},touchableHandleResponderTerminationRequest:function touchableHandleResponderTerminationRequest(e){var onResponderTerminationRequest=this.props.onResponderTerminationRequest;if(onResponderTerminationRequest){return onResponderTerminationRequest(e);}else{return _touchableHandleResponderTerminationRequest.call(this,e);}},touchableHandleResponderGrant:function touchableHandleResponderGrant(e){var onResponderGrant=this.props.onResponderGrant;if(onResponderGrant){return onResponderGrant(e);}else{return _touchableHandleResponderGrant.call(this,e);}},touchableHandleResponderMove:function touchableHandleResponderMove(e){var onResponderMove=this.props.onResponderMove;if(onResponderMove){return onResponderMove(e);}else{return _touchableHandleResponderMove.call(this,e);}},touchableHandleResponderRelease:function touchableHandleResponderRelease(e){var onResponderRelease=this.props.onResponderRelease;if(onResponderRelease){return onResponderRelease(e);}else{return _touchableHandleResponderRelease.call(this,e);}},touchableHandleResponderTerminate:function touchableHandleResponderTerminate(e){var onResponderTerminate=this.props.onResponderTerminate;if(onResponderTerminate){return onResponderTerminate(e);}else{return _touchableHandleResponderTerminate.call(this,e);}},touchableHandlePress:function touchableHandlePress(e){var onPress=this.props.onPress;onPress&&onPress(e);},touchableHandleActivePressIn:function touchableHandleActivePressIn(e){var onPressIn=this.props.onPressIn;onPressIn&&onPressIn(e);},touchableHandleActivePressOut:function touchableHandleActivePressOut(e){var onPressOut=this.props.onPressOut;onPressOut&&onPressOut(e);},touchableHandleLongPress:function touchableHandleLongPress(e){var onLongPress=this.props.onLongPress;onLongPress&&onLongPress(e);},touchableGetPressRectOffset:function touchableGetPressRectOffset(){var pressRetentionOffset=this.props.pressRetentionOffset;return pressRetentionOffset||PRESS_RETENTION_OFFSET;},touchableGetHitSlop:function touchableGetHitSlop(){var hitSlop=this.props.hitSlop;return hitSlop;},touchableGetHighlightDelayMS:function touchableGetHighlightDelayMS(){var delayPressIn=this.props.delayPressIn;return delayPressIn||0;},touchableGetLongPressDelayMS:function touchableGetLongPressDelayMS(){var delayLongPress=this.props.delayLongPress;return delayLongPress===0?0:delayLongPress||500;},touchableGetPressOutDelayMS:function touchableGetPressOutDelayMS(){var delayPressOut=this.props.delayPressOut;return delayPressOut||0;}});var touchKeys=Object.keys(SvgTouchableMixin);var touchVals=touchKeys.map(function(key){return SvgTouchableMixin[key];});var numTouchKeys=touchKeys.length;var _default=function _default(target){for(var i=0;i<numTouchKeys;i++){var key=touchKeys[i];var val=touchVals[i];if(typeof val==='function'){target[key]=val.bind(target);}else{target[key]=val;}}target.state=touchableGetInitialState();};exports.default=_default;
//# sourceMappingURL=SvgTouchableMixin.js.map
webpack://frontend-mybets/../../node_modules/react-native-svg/lib/module/lib/resolve.js
var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.resolve=resolve;var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _reactNative=require("react-native");function resolve(styleProp,cleanedProps){if(styleProp){return _reactNative.StyleSheet?[styleProp,cleanedProps]:styleProp[Symbol.iterator]?Object.assign.apply(Object,[{}].concat((0,_toConsumableArray2.default)(styleProp),[cleanedProps])):Object.assign({},styleProp,cleanedProps);}else{return cleanedProps;}}
//# sourceMappingURL=resolve.js.map
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/AccessibilityInfo/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _canUseDom = _interopRequireDefault(require("../../modules/canUseDom"));
/**
* 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.
*
*
*/
function isScreenReaderEnabled() {
return new Promise((resolve, reject) => {
resolve(true);
});
}
var prefersReducedMotionMedia = _canUseDom.default && typeof window.matchMedia === 'function' ? window.matchMedia('(prefers-reduced-motion: reduce)') : null;
function isReduceMotionEnabled() {
return new Promise((resolve, reject) => {
resolve(prefersReducedMotionMedia ? prefersReducedMotionMedia.matches : true);
});
}
function addChangeListener(fn) {
if (prefersReducedMotionMedia != null) {
prefersReducedMotionMedia.addEventListener != null ? prefersReducedMotionMedia.addEventListener('change', fn) : prefersReducedMotionMedia.addListener(fn);
}
}
function removeChangeListener(fn) {
if (prefersReducedMotionMedia != null) {
prefersReducedMotionMedia.removeEventListener != null ? prefersReducedMotionMedia.removeEventListener('change', fn) : prefersReducedMotionMedia.removeListener(fn);
}
}
var handlers = {};
var AccessibilityInfo = {
/**
* Query whether a screen reader is currently enabled.
*
* Returns a promise which resolves to a boolean.
* The result is `true` when a screen reader is enabled and `false` otherwise.
*/
isScreenReaderEnabled,
/**
* Query whether the user prefers reduced motion.
*
* Returns a promise which resolves to a boolean.
* The result is `true` when a screen reader is enabled and `false` otherwise.
*/
isReduceMotionEnabled,
/**
* Deprecated
*/
fetch: isScreenReaderEnabled,
/**
* Add an event handler. Supported events: reduceMotionChanged
*/
addEventListener: function addEventListener(eventName, handler) {
if (eventName === 'reduceMotionChanged') {
if (!prefersReducedMotionMedia) {
return;
}
var listener = event => {
handler(event.matches);
};
addChangeListener(listener);
handlers[handler] = listener;
}
return {
remove: () => AccessibilityInfo.removeEventListener(eventName, handler)
};
},
/**
* Set accessibility focus to a react component.
*/
setAccessibilityFocus: function setAccessibilityFocus(reactTag) {},
/**
* Post a string to be announced by the screen reader.
*/
announceForAccessibility: function announceForAccessibility(announcement) {},
/**
* Remove an event handler.
*/
removeEventListener: function removeEventListener(eventName, handler) {
if (eventName === 'reduceMotionChanged') {
var listener = handlers[handler];
if (!listener || !prefersReducedMotionMedia) {
return;
}
removeChangeListener(listener);
}
return;
}
};
var _default = AccessibilityInfo;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/ActivityIndicator/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var React = _interopRequireWildcard(require("react"));
var _StyleSheet = _interopRequireDefault(require("../StyleSheet"));
var _View = _interopRequireDefault(require("../View"));
var _excluded = ["animating", "color", "hidesWhenStopped", "size", "style"];
var createSvgCircle = style => /*#__PURE__*/React.createElement("circle", {
cx: "16",
cy: "16",
fill: "none",
r: "14",
strokeWidth: "4",
style: style
});
var ActivityIndicator = /*#__PURE__*/React.forwardRef((props, forwardedRef) => {
var _props$animating = props.animating,
animating = _props$animating === void 0 ? true : _props$animating,
_props$color = props.color,
color = _props$color === void 0 ? '#1976D2' : _props$color,
_props$hidesWhenStopp = props.hidesWhenStopped,
hidesWhenStopped = _props$hidesWhenStopp === void 0 ? true : _props$hidesWhenStopp,
_props$size = props.size,
size = _props$size === void 0 ? 'small' : _props$size,
style = props.style,
other = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
var svg = /*#__PURE__*/React.createElement("svg", {
height: "100%",
viewBox: "0 0 32 32",
width: "100%"
}, createSvgCircle({
stroke: color,
opacity: 0.2
}), createSvgCircle({
stroke: color,
strokeDasharray: 80,
strokeDashoffset: 60
}));
return /*#__PURE__*/React.createElement(_View.default, (0, _extends2.default)({}, other, {
"aria-valuemax": 1,
"aria-valuemin": 0,
ref: forwardedRef,
role: "progressbar",
style: [styles.container, style]
}), /*#__PURE__*/React.createElement(_View.default, {
children: svg,
style: [typeof size === 'number' ? {
height: size,
width: size
} : indicatorSizes[size], styles.animation, !animating && styles.animationPause, !animating && hidesWhenStopped && styles.hidesWhenStopped]
}));
});
ActivityIndicator.displayName = 'ActivityIndicator';
var styles = _StyleSheet.default.create({
container: {
alignItems: 'center',
justifyContent: 'center'
},
hidesWhenStopped: {
visibility: 'hidden'
},
animation: {
animationDuration: '0.75s',
animationKeyframes: [{
'0%': {
transform: 'rotate(0deg)'
},
'100%': {
transform: 'rotate(360deg)'
}
}],
animationTimingFunction: 'linear',
animationIterationCount: 'infinite'
},
animationPause: {
animationPlayState: 'paused'
}
});
var indicatorSizes = _StyleSheet.default.create({
small: {
width: 20,
height: 20
},
large: {
width: 36,
height: 36
}
});
var _default = ActivityIndicator;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Alert/index.js
"use strict";
exports.__esModule = true;
exports.default = void 0;
/**
* 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.
*
*
*/
class Alert {
static alert() {}
}
var _default = Alert;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Animated/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _Animated = _interopRequireDefault(require("../../vendor/react-native/Animated/Animated"));
/**
* 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.
*
*
*/
var _default = _Animated.default;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/AppRegistry/AppContainer.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
var _StyleSheet = _interopRequireDefault(require("../StyleSheet"));
var _View = _interopRequireDefault(require("../View"));
/**
* 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.
*
*
*/
var RootTagContext = /*#__PURE__*/React.createContext(null);
var AppContainer = /*#__PURE__*/React.forwardRef((props, forwardedRef) => {
var children = props.children,
WrapperComponent = props.WrapperComponent;
var innerView = /*#__PURE__*/React.createElement(_View.default, {
children: children,
key: 1,
style: styles.appContainer
});
if (WrapperComponent) {
innerView = /*#__PURE__*/React.createElement(WrapperComponent, null, innerView);
}
return /*#__PURE__*/React.createElement(RootTagContext.Provider, {
value: props.rootTag
}, /*#__PURE__*/React.createElement(_View.default, {
ref: forwardedRef,
style: styles.appContainer
}, innerView));
});
AppContainer.displayName = 'AppContainer';
var _default = AppContainer;
exports.default = _default;
var styles = _StyleSheet.default.create({
appContainer: {
flex: 1,
pointerEvents: 'box-none'
}
});
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/AppRegistry/index.js
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
var _unmountComponentAtNode = _interopRequireDefault(require("../unmountComponentAtNode"));
var _renderApplication = _interopRequireWildcard(require("./renderApplication"));
/**
* 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.
*
*
*/
var emptyObject = {};
var runnables = {};
var componentProviderInstrumentationHook = component => component();
var wrapperComponentProvider;
/**
* `AppRegistry` is the JS entry point to running all React Native apps.
*/
class AppRegistry {
static getAppKeys() {
return Object.keys(runnables);
}
static getApplication(appKey, appParameters) {
(0, _invariant.default)(runnables[appKey] && runnables[appKey].getApplication, "Application " + appKey + " has not been registered. " + 'This is either due to an import error during initialization or failure to call AppRegistry.registerComponent.');
return runnables[appKey].getApplication(appParameters);
}
static registerComponent(appKey, componentProvider) {
runnables[appKey] = {
getApplication: appParameters => (0, _renderApplication.getApplication)(componentProviderInstrumentationHook(componentProvider), appParameters ? appParameters.initialProps : emptyObject, wrapperComponentProvider && wrapperComponentProvider(appParameters)),
run: appParameters => (0, _renderApplication.default)(componentProviderInstrumentationHook(componentProvider), wrapperComponentProvider && wrapperComponentProvider(appParameters), appParameters.callback, {
hydrate: appParameters.hydrate || false,
initialProps: appParameters.initialProps || emptyObject,
mode: appParameters.mode || 'concurrent',
rootTag: appParameters.rootTag
})
};
return appKey;
}
static registerConfig(config) {
config.forEach(_ref => {
var appKey = _ref.appKey,
component = _ref.component,
run = _ref.run;
if (run) {
AppRegistry.registerRunnable(appKey, run);
} else {
(0, _invariant.default)(component, 'No component provider passed in');
AppRegistry.registerComponent(appKey, component);
}
});
}
// TODO: fix style sheet creation when using this method
static registerRunnable(appKey, run) {
runnables[appKey] = {
run
};
return appKey;
}
static runApplication(appKey, appParameters) {
var isDevelopment = process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test';
if (isDevelopment) {
var params = (0, _objectSpread2.default)({}, appParameters);
params.rootTag = "#" + params.rootTag.id;
console.log("Running application \"" + appKey + "\" with appParams:\n", params, "\nDevelopment-level warnings: " + (isDevelopment ? 'ON' : 'OFF') + "." + ("\nPerformance optimizations: " + (isDevelopment ? 'OFF' : 'ON') + "."));
}
(0, _invariant.default)(runnables[appKey] && runnables[appKey].run, "Application \"" + appKey + "\" has not been registered. " + 'This is either due to an import error during initialization or failure to call AppRegistry.registerComponent.');
return runnables[appKey].run(appParameters);
}
static setComponentProviderInstrumentationHook(hook) {
componentProviderInstrumentationHook = hook;
}
static setWrapperComponentProvider(provider) {
wrapperComponentProvider = provider;
}
static unmountApplicationComponentAtRootTag(rootTag) {
(0, _unmountComponentAtNode.default)(rootTag);
}
}
exports.default = AppRegistry;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/AppRegistry/renderApplication.js
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = renderApplication;
exports.getApplication = getApplication;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _AppContainer = _interopRequireDefault(require("./AppContainer"));
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
var _render = _interopRequireWildcard(require("../render"));
var _StyleSheet = _interopRequireDefault(require("../StyleSheet"));
var _react = _interopRequireDefault(require("react"));
/**
* 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.
*
*
*/
function renderApplication(RootComponent, WrapperComponent, callback, options) {
var shouldHydrate = options.hydrate,
initialProps = options.initialProps,
mode = options.mode,
rootTag = options.rootTag;
var renderFn = shouldHydrate ? mode === 'concurrent' ? _render.hydrate : _render.hydrateLegacy : mode === 'concurrent' ? _render.render : _render.default;
(0, _invariant.default)(rootTag, 'Expect to have a valid rootTag, instead got ', rootTag);
return renderFn( /*#__PURE__*/_react.default.createElement(_AppContainer.default, {
WrapperComponent: WrapperComponent,
ref: callback,
rootTag: rootTag
}, /*#__PURE__*/_react.default.createElement(RootComponent, initialProps)), rootTag);
}
function getApplication(RootComponent, initialProps, WrapperComponent) {
var element = /*#__PURE__*/_react.default.createElement(_AppContainer.default, {
WrapperComponent: WrapperComponent,
rootTag: {}
}, /*#__PURE__*/_react.default.createElement(RootComponent, initialProps));
// Don't escape CSS text
var getStyleElement = props => {
var sheet = _StyleSheet.default.getSheet();
return /*#__PURE__*/_react.default.createElement("style", (0, _extends2.default)({}, props, {
dangerouslySetInnerHTML: {
__html: sheet.textContent
},
id: sheet.id
}));
};
return {
element,
getStyleElement
};
}
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/AppState/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
var _EventEmitter = _interopRequireDefault(require("../../vendor/react-native/vendor/emitter/EventEmitter"));
var _canUseDom = _interopRequireDefault(require("../../modules/canUseDom"));
/**
* 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.
*
*
*/
// Android 4.4 browser
var isPrefixed = _canUseDom.default && !document.hasOwnProperty('hidden') && document.hasOwnProperty('webkitHidden');
var EVENT_TYPES = ['change', 'memoryWarning'];
var VISIBILITY_CHANGE_EVENT = isPrefixed ? 'webkitvisibilitychange' : 'visibilitychange';
var VISIBILITY_STATE_PROPERTY = isPrefixed ? 'webkitVisibilityState' : 'visibilityState';
var AppStates = {
BACKGROUND: 'background',
ACTIVE: 'active'
};
var changeEmitter = null;
class AppState {
static get currentState() {
if (!AppState.isAvailable) {
return AppStates.ACTIVE;
}
switch (document[VISIBILITY_STATE_PROPERTY]) {
case 'hidden':
case 'prerender':
case 'unloaded':
return AppStates.BACKGROUND;
default:
return AppStates.ACTIVE;
}
}
static addEventListener(type, handler) {
if (AppState.isAvailable) {
(0, _invariant.default)(EVENT_TYPES.indexOf(type) !== -1, 'Trying to subscribe to unknown event: "%s"', type);
if (type === 'change') {
if (!changeEmitter) {
changeEmitter = new _EventEmitter.default();
document.addEventListener(VISIBILITY_CHANGE_EVENT, () => {
if (changeEmitter) {
changeEmitter.emit('change', AppState.currentState);
}
}, false);
}
return changeEmitter.addListener(type, handler);
}
}
}
}
exports.default = AppState;
AppState.isAvailable = _canUseDom.default && document[VISIBILITY_STATE_PROPERTY];
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Appearance/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _canUseDom = _interopRequireDefault(require("../../modules/canUseDom"));
/**
* 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.
*
*
*/
function getQuery() {
return _canUseDom.default && window.matchMedia != null ? window.matchMedia('(prefers-color-scheme: dark)') : null;
}
var query = getQuery();
var listenerMapping = new WeakMap();
var Appearance = {
getColorScheme() {
return query && query.matches ? 'dark' : 'light';
},
addChangeListener(listener) {
var mappedListener = listenerMapping.get(listener);
if (!mappedListener) {
mappedListener = _ref => {
var matches = _ref.matches;
listener({
colorScheme: matches ? 'dark' : 'light'
});
};
listenerMapping.set(listener, mappedListener);
}
if (query) {
query.addListener(mappedListener);
}
function remove() {
var mappedListener = listenerMapping.get(listener);
if (query && mappedListener) {
query.removeListener(mappedListener);
}
listenerMapping.delete(listener);
}
return {
remove
};
}
};
var _default = Appearance;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/BackHandler/index.js
"use strict";
exports.__esModule = true;
exports.default = void 0;
/**
* 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.
*
*
*/
function emptyFunction() {}
var BackHandler = {
exitApp: emptyFunction,
addEventListener() {
console.error('BackHandler is not supported on web and should not be used.');
return {
remove: emptyFunction
};
},
removeEventListener: emptyFunction
};
var _default = BackHandler;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Button/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
var _StyleSheet = _interopRequireDefault(require("../StyleSheet"));
var _TouchableOpacity = _interopRequireDefault(require("../TouchableOpacity"));
var _Text = _interopRequireDefault(require("../Text"));
var _warnOnce = require("../../modules/warnOnce");
/**
* 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.
*
*
*/
var Button = /*#__PURE__*/React.forwardRef((props, forwardedRef) => {
(0, _warnOnce.warnOnce)('Button', 'Button is deprecated. Please use Pressable.');
var accessibilityLabel = props.accessibilityLabel,
color = props.color,
disabled = props.disabled,
onPress = props.onPress,
testID = props.testID,
title = props.title;
return /*#__PURE__*/React.createElement(_TouchableOpacity.default, {
accessibilityLabel: accessibilityLabel,
accessibilityRole: "button",
disabled: disabled,
focusable: !disabled,
onPress: onPress,
ref: forwardedRef,
style: [styles.button, color && {
backgroundColor: color
}, disabled && styles.buttonDisabled],
testID: testID
}, /*#__PURE__*/React.createElement(_Text.default, {
style: [styles.text, disabled && styles.textDisabled]
}, title));
});
Button.displayName = 'Button';
var styles = _StyleSheet.default.create({
button: {
backgroundColor: '#2196F3',
borderRadius: 2
},
text: {
color: '#fff',
fontWeight: '500',
padding: 8,
textAlign: 'center',
textTransform: 'uppercase'
},
buttonDisabled: {
backgroundColor: '#dfdfdf'
},
textDisabled: {
color: '#a1a1a1'
}
});
var _default = Button;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/CheckBox/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var React = _interopRequireWildcard(require("react"));
var _createElement = _interopRequireDefault(require("../createElement"));
var _StyleSheet = _interopRequireDefault(require("../StyleSheet"));
var _View = _interopRequireDefault(require("../View"));
var _excluded = ["aria-readonly", "color", "disabled", "onChange", "onValueChange", "readOnly", "style", "value"];
var CheckBox = /*#__PURE__*/React.forwardRef((props, forwardedRef) => {
var ariaReadOnly = props['aria-readonly'],
color = props.color,
disabled = props.disabled,
onChange = props.onChange,
onValueChange = props.onValueChange,
readOnly = props.readOnly,
style = props.style,
value = props.value,
other = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
function handleChange(event) {
var value = event.nativeEvent.target.checked;
event.nativeEvent.value = value;
onChange && onChange(event);
onValueChange && onValueChange(value);
}
var fakeControl = /*#__PURE__*/React.createElement(_View.default, {
style: [styles.fakeControl, value && styles.fakeControlChecked,
// custom color
value && color && {
backgroundColor: color,
borderColor: color
}, disabled && styles.fakeControlDisabled, value && disabled && styles.fakeControlCheckedAndDisabled]
});
var nativeControl = (0, _createElement.default)('input', {
checked: value,
disabled: disabled,
onChange: handleChange,
readOnly: readOnly === true || ariaReadOnly === true || other.accessibilityReadOnly === true,
ref: forwardedRef,
style: [styles.nativeControl, styles.cursorInherit],
type: 'checkbox'
});
return /*#__PURE__*/React.createElement(_View.default, (0, _extends2.default)({}, other, {
"aria-disabled": disabled,
"aria-readonly": ariaReadOnly,
style: [styles.root, style, disabled && styles.cursorDefault]
}), fakeControl, nativeControl);
});
CheckBox.displayName = 'CheckBox';
var styles = _StyleSheet.default.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: (0, _objectSpread2.default)((0, _objectSpread2.default)({}, _StyleSheet.default.absoluteFillObject), {}, {
height: '100%',
margin: 0,
appearance: 'none',
padding: 0,
width: '100%'
})
});
var _default = CheckBox;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Clipboard/index.js
"use strict";
exports.__esModule = true;
exports.default = void 0;
/**
* 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.
*
*
*/
var clipboardAvailable;
class Clipboard {
static isAvailable() {
if (clipboardAvailable === undefined) {
clipboardAvailable = typeof document.queryCommandSupported === 'function' && document.queryCommandSupported('copy');
}
return clipboardAvailable;
}
static getString() {
return Promise.resolve('');
}
static setString(text) {
var success = false;
var body = document.body;
if (body) {
// add the text to a hidden node
var node = document.createElement('span');
node.textContent = text;
node.style.opacity = '0';
node.style.position = 'absolute';
node.style.whiteSpace = 'pre-wrap';
node.style.userSelect = 'auto';
body.appendChild(node);
// select the text
var selection = window.getSelection();
selection.removeAllRanges();
var range = document.createRange();
range.selectNodeContents(node);
selection.addRange(range);
// attempt to copy
try {
document.execCommand('copy');
success = true;
} catch (e) {}
// remove selection and node
selection.removeAllRanges();
body.removeChild(node);
}
return success;
}
}
exports.default = Clipboard;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/DeviceEventEmitter/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _RCTDeviceEventEmitter = _interopRequireDefault(require("../../vendor/react-native/EventEmitter/RCTDeviceEventEmitter"));
var _default = _RCTDeviceEventEmitter.default;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Dimensions/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
var _canUseDom = _interopRequireDefault(require("../../modules/canUseDom"));
/**
* 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.
*
*
*/
var dimensions = {
window: {
fontScale: 1,
height: 0,
scale: 1,
width: 0
},
screen: {
fontScale: 1,
height: 0,
scale: 1,
width: 0
}
};
var listeners = {};
var shouldInit = _canUseDom.default;
function update() {
if (!_canUseDom.default) {
return;
}
var win = window;
var height;
var width;
/**
* iOS does not update viewport dimensions on keyboard open/close.
* window.visualViewport(https://developer.mozilla.org/en-US/docs/Web/API/VisualViewport)
* is used instead of document.documentElement.clientHeight (which remains as a fallback)
*/
if (win.visualViewport) {
var visualViewport = win.visualViewport;
/**
* We are multiplying by scale because height and width from visual viewport
* also react to pinch zoom, and become smaller when zoomed. But it is not desired
* behaviour, since originally documentElement client height and width were used,
* and they do not react to pinch zoom.
*/
height = Math.round(visualViewport.height * visualViewport.scale);
width = Math.round(visualViewport.width * visualViewport.scale);
} else {
var docEl = win.document.documentElement;
height = docEl.clientHeight;
width = docEl.clientWidth;
}
dimensions.window = {
fontScale: 1,
height,
scale: win.devicePixelRatio || 1,
width
};
dimensions.screen = {
fontScale: 1,
height: win.screen.height,
scale: win.devicePixelRatio || 1,
width: win.screen.width
};
}
function handleResize() {
update();
if (Array.isArray(listeners['change'])) {
listeners['change'].forEach(handler => handler(dimensions));
}
}
class Dimensions {
static get(dimension) {
if (shouldInit) {
shouldInit = false;
update();
}
(0, _invariant.default)(dimensions[dimension], "No dimension set for key " + dimension);
return dimensions[dimension];
}
static set(initialDimensions) {
if (initialDimensions) {
if (_canUseDom.default) {
(0, _invariant.default)(false, 'Dimensions cannot be set in the browser');
} else {
if (initialDimensions.screen != null) {
dimensions.screen = initialDimensions.screen;
}
if (initialDimensions.window != null) {
dimensions.window = initialDimensions.window;
}
}
}
}
static addEventListener(type, handler) {
listeners[type] = listeners[type] || [];
listeners[type].push(handler);
return {
remove: () => {
this.removeEventListener(type, handler);
}
};
}
static removeEventListener(type, handler) {
if (Array.isArray(listeners[type])) {
listeners[type] = listeners[type].filter(_handler => _handler !== handler);
}
}
}
exports.default = Dimensions;
if (_canUseDom.default) {
if (window.visualViewport) {
window.visualViewport.addEventListener('resize', handleResize, false);
} else {
window.addEventListener('resize', handleResize, false);
}
}
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Easing/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _Easing = _interopRequireDefault(require("../../vendor/react-native/Animated/Easing"));
/**
* 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.
*
*
*/
var _default = _Easing.default;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/FlatList/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _FlatList = _interopRequireDefault(require("../../vendor/react-native/FlatList"));
/**
* 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.
*
*
*/
var _default = _FlatList.default;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/I18nManager/index.js
"use strict";
exports.__esModule = true;
exports.default = void 0;
/**
* 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.
*
*
*/
var I18nManager = {
allowRTL() {
return;
},
forceRTL() {
return;
},
getConstants() {
return {
isRTL: false
};
}
};
var _default = I18nManager;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Image/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var React = _interopRequireWildcard(require("react"));
var _createElement = _interopRequireDefault(require("../createElement"));
var _AssetRegistry = require("../../modules/AssetRegistry");
var _preprocess = require("../StyleSheet/preprocess");
var _ImageLoader = _interopRequireDefault(require("../../modules/ImageLoader"));
var _PixelRatio = _interopRequireDefault(require("../PixelRatio"));
var _StyleSheet = _interopRequireDefault(require("../StyleSheet"));
var _TextAncestorContext = _interopRequireDefault(require("../Text/TextAncestorContext"));
var _View = _interopRequireDefault(require("../View"));
var _warnOnce = require("../../modules/warnOnce");
var _excluded = ["aria-label", "blurRadius", "defaultSource", "draggable", "onError", "onLayout", "onLoad", "onLoadEnd", "onLoadStart", "pointerEvents", "source", "style"];
var ERRORED = 'ERRORED';
var LOADED = 'LOADED';
var LOADING = 'LOADING';
var IDLE = 'IDLE';
var _filterId = 0;
var svgDataUriPattern = /^(data:image\/svg\+xml;utf8,)(.*)/;
function createTintColorSVG(tintColor, id) {
return tintColor && id != null ? /*#__PURE__*/React.createElement("svg", {
style: {
position: 'absolute',
height: 0,
visibility: 'hidden',
width: 0
}
}, /*#__PURE__*/React.createElement("defs", null, /*#__PURE__*/React.createElement("filter", {
id: "tint-" + id,
suppressHydrationWarning: true
}, /*#__PURE__*/React.createElement("feFlood", {
floodColor: "" + tintColor,
key: tintColor
}), /*#__PURE__*/React.createElement("feComposite", {
in2: "SourceAlpha",
operator: "atop"
})))) : null;
}
function extractNonStandardStyleProps(style, blurRadius, filterId, tintColorProp) {
var flatStyle = _StyleSheet.default.flatten(style);
var filter = flatStyle.filter,
resizeMode = flatStyle.resizeMode,
shadowOffset = flatStyle.shadowOffset,
tintColor = flatStyle.tintColor;
if (flatStyle.resizeMode) {
(0, _warnOnce.warnOnce)('Image.style.resizeMode', 'Image: style.resizeMode is deprecated. Please use props.resizeMode.');
}
if (flatStyle.tintColor) {
(0, _warnOnce.warnOnce)('Image.style.tintColor', 'Image: style.tintColor is deprecated. Please use props.tintColor.');
}
// Add CSS filters
// React Native exposes these features as props and proprietary styles
var filters = [];
var _filter = null;
if (filter) {
filters.push(filter);
}
if (blurRadius) {
filters.push("blur(" + blurRadius + "px)");
}
if (shadowOffset) {
var shadowString = (0, _preprocess.createBoxShadowValue)(flatStyle);
if (shadowString) {
filters.push("drop-shadow(" + shadowString + ")");
}
}
if ((tintColorProp || tintColor) && filterId != null) {
filters.push("url(#tint-" + filterId + ")");
}
if (filters.length > 0) {
_filter = filters.join(' ');
}
return [resizeMode, _filter, tintColor];
}
function resolveAssetDimensions(source) {
if (typeof source === 'number') {
var _getAssetByID = (0, _AssetRegistry.getAssetByID)(source),
_height = _getAssetByID.height,
_width = _getAssetByID.width;
return {
height: _height,
width: _width
};
} else if (source != null && !Array.isArray(source) && typeof source === 'object') {
var _height2 = source.height,
_width2 = source.width;
return {
height: _height2,
width: _width2
};
}
}
function resolveAssetUri(source) {
var uri = null;
if (typeof source === 'number') {
// get the URI from the packager
var asset = (0, _AssetRegistry.getAssetByID)(source);
if (asset == null) {
throw new Error("Image: asset with ID \"" + source + "\" could not be found. Please check the image source or packager.");
}
var scale = asset.scales[0];
if (asset.scales.length > 1) {
var preferredScale = _PixelRatio.default.get();
// Get the scale which is closest to the preferred scale
scale = asset.scales.reduce((prev, curr) => Math.abs(curr - preferredScale) < Math.abs(prev - preferredScale) ? curr : prev);
}
var scaleSuffix = scale !== 1 ? "@" + scale + "x" : '';
uri = asset ? asset.httpServerLocation + "/" + asset.name + scaleSuffix + "." + asset.type : '';
} else if (typeof source === 'string') {
uri = source;
} else if (source && typeof source.uri === 'string') {
uri = source.uri;
}
if (uri) {
var match = uri.match(svgDataUriPattern);
// inline SVG markup may contain characters (e.g., #, ") that need to be escaped
if (match) {
var prefix = match[1],
svg = match[2];
var encodedSvg = encodeURIComponent(svg);
return "" + prefix + encodedSvg;
}
}
return uri;
}
var Image = /*#__PURE__*/React.forwardRef((props, ref) => {
var ariaLabel = props['aria-label'],
blurRadius = props.blurRadius,
defaultSource = props.defaultSource,
draggable = props.draggable,
onError = props.onError,
onLayout = props.onLayout,
onLoad = props.onLoad,
onLoadEnd = props.onLoadEnd,
onLoadStart = props.onLoadStart,
pointerEvents = props.pointerEvents,
source = props.source,
style = props.style,
rest = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
if (process.env.NODE_ENV !== 'production') {
if (props.children) {
throw new Error('The <Image> component cannot contain children. If you want to render content on top of the image, consider using the <ImageBackground> component or absolute positioning.');
}
}
var _React$useState = React.useState(() => {
var uri = resolveAssetUri(source);
if (uri != null) {
var isLoaded = _ImageLoader.default.has(uri);
if (isLoaded) {
return LOADED;
}
}
return IDLE;
}),
state = _React$useState[0],
updateState = _React$useState[1];
var _React$useState2 = React.useState({}),
layout = _React$useState2[0],
updateLayout = _React$useState2[1];
var hasTextAncestor = React.useContext(_TextAncestorContext.default);
var hiddenImageRef = React.useRef(null);
var filterRef = React.useRef(_filterId++);
var requestRef = React.useRef(null);
var shouldDisplaySource = state === LOADED || state === LOADING && defaultSource == null;
var _extractNonStandardSt = extractNonStandardStyleProps(style, blurRadius, filterRef.current, props.tintColor),
_resizeMode = _extractNonStandardSt[0],
filter = _extractNonStandardSt[1],
_tintColor = _extractNonStandardSt[2];
var resizeMode = props.resizeMode || _resizeMode || 'cover';
var tintColor = props.tintColor || _tintColor;
var selectedSource = shouldDisplaySource ? source : defaultSource;
var displayImageUri = resolveAssetUri(selectedSource);
var imageSizeStyle = resolveAssetDimensions(selectedSource);
var backgroundImage = displayImageUri ? "url(\"" + displayImageUri + "\")" : null;
var backgroundSize = getBackgroundSize();
// Accessibility image allows users to trigger the browser's image context menu
var hiddenImage = displayImageUri ? (0, _createElement.default)('img', {
alt: ariaLabel || '',
style: styles.accessibilityImage$raw,
draggable: draggable || false,
ref: hiddenImageRef,
src: displayImageUri
}) : null;
function getBackgroundSize() {
if (hiddenImageRef.current != null && (resizeMode === 'center' || resizeMode === 'repeat')) {
var _hiddenImageRef$curre = hiddenImageRef.current,
naturalHeight = _hiddenImageRef$curre.naturalHeight,
naturalWidth = _hiddenImageRef$curre.naturalWidth;
var _height3 = layout.height,
_width3 = layout.width;
if (naturalHeight && naturalWidth && _height3 && _width3) {
var scaleFactor = Math.min(1, _width3 / naturalWidth, _height3 / naturalHeight);
var x = Math.ceil(scaleFactor * naturalWidth);
var y = Math.ceil(scaleFactor * naturalHeight);
return x + "px " + y + "px";
}
}
}
function handleLayout(e) {
if (resizeMode === 'center' || resizeMode === 'repeat' || onLayout) {
var _layout = e.nativeEvent.layout;
onLayout && onLayout(e);
updateLayout(_layout);
}
}
// Image loading
var uri = resolveAssetUri(source);
React.useEffect(() => {
abortPendingRequest();
if (uri != null) {
updateState(LOADING);
if (onLoadStart) {
onLoadStart();
}
requestRef.current = _ImageLoader.default.load(uri, function load(e) {
updateState(LOADED);
if (onLoad) {
onLoad(e);
}
if (onLoadEnd) {
onLoadEnd();
}
}, function error() {
updateState(ERRORED);
if (onError) {
onError({
nativeEvent: {
error: "Failed to load resource " + uri + " (404)"
}
});
}
if (onLoadEnd) {
onLoadEnd();
}
});
}
function abortPendingRequest() {
if (requestRef.current != null) {
_ImageLoader.default.abort(requestRef.current);
requestRef.current = null;
}
}
return abortPendingRequest;
}, [uri, requestRef, updateState, onError, onLoad, onLoadEnd, onLoadStart]);
return /*#__PURE__*/React.createElement(_View.default, (0, _extends2.default)({}, rest, {
"aria-label": ariaLabel,
onLayout: handleLayout,
pointerEvents: pointerEvents,
ref: ref,
style: [styles.root, hasTextAncestor && styles.inline, imageSizeStyle, style, styles.undo,
// TEMP: avoid deprecated shadow props regression
// until Image refactored to use createElement.
{
boxShadow: null
}]
}), /*#__PURE__*/React.createElement(_View.default, {
style: [styles.image, resizeModeStyles[resizeMode], {
backgroundImage,
filter
}, backgroundSize != null && {
backgroundSize
}],
suppressHydrationWarning: true
}), hiddenImage, createTintColorSVG(tintColor, filterRef.current));
});
Image.displayName = 'Image';
// $FlowIgnore: This is the correct type, but casting makes it unhappy since the variables aren't defined yet
var ImageWithStatics = Image;
ImageWithStatics.getSize = function (uri, success, failure) {
_ImageLoader.default.getSize(uri, success, failure);
};
ImageWithStatics.prefetch = function (uri) {
return _ImageLoader.default.prefetch(uri);
};
ImageWithStatics.queryCache = function (uris) {
return _ImageLoader.default.queryCache(uris);
};
var styles = _StyleSheet.default.create({
root: {
flexBasis: 'auto',
overflow: 'hidden',
zIndex: 0
},
inline: {
display: 'inline-flex'
},
undo: {
// These styles are converted to CSS filters applied to the
// element displaying the background image.
blurRadius: null,
shadowColor: null,
shadowOpacity: null,
shadowOffset: null,
shadowRadius: null,
tintColor: null,
// These styles are not supported
overlayColor: null,
resizeMode: null
},
image: (0, _objectSpread2.default)((0, _objectSpread2.default)({}, _StyleSheet.default.absoluteFillObject), {}, {
backgroundColor: 'transparent',
backgroundPosition: 'center',
backgroundRepeat: 'no-repeat',
backgroundSize: 'cover',
height: '100%',
width: '100%',
zIndex: -1
}),
accessibilityImage$raw: (0, _objectSpread2.default)((0, _objectSpread2.default)({}, _StyleSheet.default.absoluteFillObject), {}, {
height: '100%',
opacity: 0,
width: '100%',
zIndex: -1
})
});
var resizeModeStyles = _StyleSheet.default.create({
center: {
backgroundSize: 'auto'
},
contain: {
backgroundSize: 'contain'
},
cover: {
backgroundSize: 'cover'
},
none: {
backgroundPosition: '0',
backgroundSize: 'auto'
},
repeat: {
backgroundPosition: '0',
backgroundRepeat: 'repeat',
backgroundSize: 'auto'
},
stretch: {
backgroundSize: '100% 100%'
}
});
var _default = ImageWithStatics;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/ImageBackground/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var React = _interopRequireWildcard(require("react"));
var _Image = _interopRequireDefault(require("../Image"));
var _StyleSheet = _interopRequireDefault(require("../StyleSheet"));
var _View = _interopRequireDefault(require("../View"));
var _excluded = ["children", "style", "imageStyle", "imageRef"];
var emptyObject = {};
/**
* Very simple drop-in replacement for <Image> which supports nesting views.
*/
var ImageBackground = /*#__PURE__*/(0, React.forwardRef)((props, forwardedRef) => {
var children = props.children,
_props$style = props.style,
style = _props$style === void 0 ? emptyObject : _props$style,
imageStyle = props.imageStyle,
imageRef = props.imageRef,
rest = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
var _StyleSheet$flatten = _StyleSheet.default.flatten(style),
height = _StyleSheet$flatten.height,
width = _StyleSheet$flatten.width;
return /*#__PURE__*/React.createElement(_View.default, {
ref: forwardedRef,
style: style
}, /*#__PURE__*/React.createElement(_Image.default, (0, _extends2.default)({}, rest, {
ref: imageRef,
style: [{
// 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,
height,
zIndex: -1
}, _StyleSheet.default.absoluteFill, imageStyle]
})), children);
});
ImageBackground.displayName = 'ImageBackground';
var _default = ImageBackground;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/InteractionManager/TaskQueue.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
/**
* 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.
*
*
*/
class TaskQueue {
constructor(_ref) {
var onMoreTasks = _ref.onMoreTasks;
this._onMoreTasks = onMoreTasks;
this._queueStack = [{
tasks: [],
popable: true
}];
}
enqueue(task) {
this._getCurrentQueue().push(task);
}
enqueueTasks(tasks) {
tasks.forEach(task => this.enqueue(task));
}
cancelTasks(tasksToCancel) {
this._queueStack = this._queueStack.map(queue => (0, _objectSpread2.default)((0, _objectSpread2.default)({}, queue), {}, {
tasks: queue.tasks.filter(task => tasksToCancel.indexOf(task) === -1)
})).filter((queue, idx) => queue.tasks.length > 0 || idx === 0);
}
hasTasksToProcess() {
return this._getCurrentQueue().length > 0;
}
/**
* Executes the next task in the queue.
*/
processNext() {
var queue = this._getCurrentQueue();
if (queue.length) {
var task = queue.shift();
try {
if (typeof task === 'object' && task.gen) {
this._genPromise(task);
} else if (typeof task === 'object' && task.run) {
task.run();
} else {
(0, _invariant.default)(typeof task === 'function', 'Expected Function, SimpleTask, or PromiseTask, but got:\n' + JSON.stringify(task, null, 2));
task();
}
} catch (e) {
e.message = 'TaskQueue: Error with task ' + (task.name || '') + ': ' + e.message;
throw e;
}
}
}
_getCurrentQueue() {
var stackIdx = this._queueStack.length - 1;
var queue = this._queueStack[stackIdx];
if (queue.popable && queue.tasks.length === 0 && stackIdx > 0) {
this._queueStack.pop();
return this._getCurrentQueue();
} else {
return queue.tasks;
}
}
_genPromise(task) {
var length = this._queueStack.push({
tasks: [],
popable: false
});
var stackIdx = length - 1;
var stackItem = this._queueStack[stackIdx];
task.gen().then(() => {
stackItem.popable = true;
this.hasTasksToProcess() && this._onMoreTasks();
}).catch(ex => {
setTimeout(() => {
ex.message = "TaskQueue: Error resolving Promise in task " + task.name + ": " + ex.message;
throw ex;
}, 0);
});
}
}
var _default = TaskQueue;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/InteractionManager/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
var _TaskQueue = _interopRequireDefault(require("./TaskQueue"));
var _EventEmitter = _interopRequireDefault(require("../../vendor/react-native/vendor/emitter/EventEmitter"));
var _requestIdleCallback = _interopRequireDefault(require("../../modules/requestIdleCallback"));
/**
* 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.
*
*
*/
var _emitter = new _EventEmitter.default();
var InteractionManager = {
Events: {
interactionStart: 'interactionStart',
interactionComplete: 'interactionComplete'
},
/**
* Schedule a function to run after all interactions have completed.
*/
runAfterInteractions(task) {
var tasks = [];
var promise = new Promise(resolve => {
_scheduleUpdate();
if (task) {
tasks.push(task);
}
tasks.push({
run: resolve,
name: 'resolve ' + (task && task.name || '?')
});
_taskQueue.enqueueTasks(tasks);
});
return {
then: promise.then.bind(promise),
done: promise.then.bind(promise),
cancel: () => {
_taskQueue.cancelTasks(tasks);
}
};
},
/**
* Notify manager that an interaction has started.
*/
createInteractionHandle() {
_scheduleUpdate();
var handle = ++_inc;
_addInteractionSet.add(handle);
return handle;
},
/**
* Notify manager that an interaction has completed.
*/
clearInteractionHandle(handle) {
(0, _invariant.default)(!!handle, 'Must provide a handle to clear.');
_scheduleUpdate();
_addInteractionSet.delete(handle);
_deleteInteractionSet.add(handle);
},
addListener: _emitter.addListener.bind(_emitter),
/**
*
* @param deadline
*/
setDeadline(deadline) {
_deadline = deadline;
}
};
var _interactionSet = new Set();
var _addInteractionSet = new Set();
var _deleteInteractionSet = new Set();
var _taskQueue = new _TaskQueue.default({
onMoreTasks: _scheduleUpdate
});
var _nextUpdateHandle = 0;
var _inc = 0;
var _deadline = -1;
/**
* Schedule an asynchronous update to the interaction state.
*/
function _scheduleUpdate() {
if (!_nextUpdateHandle) {
if (_deadline > 0) {
_nextUpdateHandle = setTimeout(_processUpdate);
} else {
_nextUpdateHandle = (0, _requestIdleCallback.default)(_processUpdate);
}
}
}
/**
* Notify listeners, process queue, etc
*/
function _processUpdate() {
_nextUpdateHandle = 0;
var interactionCount = _interactionSet.size;
_addInteractionSet.forEach(handle => _interactionSet.add(handle));
_deleteInteractionSet.forEach(handle => _interactionSet.delete(handle));
var nextInteractionCount = _interactionSet.size;
if (interactionCount !== 0 && nextInteractionCount === 0) {
_emitter.emit(InteractionManager.Events.interactionComplete);
} else if (interactionCount === 0 && nextInteractionCount !== 0) {
_emitter.emit(InteractionManager.Events.interactionStart);
}
if (nextInteractionCount === 0) {
// It seems that we can't know the running time of the current event loop,
// we can only calculate the running time of the current task queue.
var begin = Date.now();
while (_taskQueue.hasTasksToProcess()) {
_taskQueue.processNext();
if (_deadline > 0 && Date.now() - begin >= _deadline) {
_scheduleUpdate();
break;
}
}
}
_addInteractionSet.clear();
_deleteInteractionSet.clear();
}
var _default = InteractionManager;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Keyboard/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _dismissKeyboard = _interopRequireDefault(require("../../modules/dismissKeyboard"));
/**
* 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.
*
*
*/
// in the future we can use https://github.com/w3c/virtual-keyboard
var Keyboard = {
isVisible() {
return false;
},
addListener() {
return {
remove: () => {}
};
},
dismiss() {
(0, _dismissKeyboard.default)();
},
removeAllListeners() {},
removeListener() {}
};
var _default = Keyboard;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/KeyboardAvoidingView/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var React = _interopRequireWildcard(require("react"));
var _View = _interopRequireDefault(require("../View"));
var _excluded = ["behavior", "contentContainerStyle", "keyboardVerticalOffset"];
class KeyboardAvoidingView extends React.Component {
constructor() {
super(...arguments);
this.frame = null;
this.onLayout = event => {
this.frame = event.nativeEvent.layout;
};
}
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);
}
onKeyboardChange(event) {}
render() {
var _this$props = this.props,
behavior = _this$props.behavior,
contentContainerStyle = _this$props.contentContainerStyle,
keyboardVerticalOffset = _this$props.keyboardVerticalOffset,
rest = (0, _objectWithoutPropertiesLoose2.default)(_this$props, _excluded);
return /*#__PURE__*/React.createElement(_View.default, (0, _extends2.default)({
onLayout: this.onLayout
}, rest));
}
}
var _default = KeyboardAvoidingView;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/LayoutAnimation/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _LayoutAnimation = _interopRequireDefault(require("../../vendor/react-native/LayoutAnimation"));
/**
* 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.
*
*
*/
var _default = _LayoutAnimation.default;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Linking/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
var _canUseDom = _interopRequireDefault(require("../../modules/canUseDom"));
/**
* 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.
*
*
*/
var initialURL = _canUseDom.default ? window.location.href : '';
class Linking {
constructor() {
this._eventCallbacks = {};
}
_dispatchEvent(event) {
for (var _len = arguments.length, data = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
data[_key - 1] = arguments[_key];
}
var listeners = this._eventCallbacks[event];
if (listeners != null && Array.isArray(listeners)) {
listeners.map(listener => {
listener(...data);
});
}
}
/**
* Adds a event listener for the specified event. The callback will be called when the
* said event is dispatched.
*/
addEventListener(eventType, callback) {
var _this = this;
if (!_this._eventCallbacks[eventType]) {
_this._eventCallbacks[eventType] = [callback];
}
_this._eventCallbacks[eventType].push(callback);
return {
remove() {
var callbacks = _this._eventCallbacks[eventType];
var filteredCallbacks = callbacks.filter(c => c.toString() !== callback.toString());
_this._eventCallbacks[eventType] = filteredCallbacks;
}
};
}
/**
* Removes a previously added event listener for the specified event. The callback must
* be the same object as the one passed to `addEventListener`.
*/
removeEventListener(eventType, callback) {
console.error("Linking.removeEventListener('" + eventType + "', ...): Method has been " + 'deprecated. Please instead use `remove()` on the subscription ' + 'returned by `Linking.addEventListener`.');
var callbacks = this._eventCallbacks[eventType];
var filteredCallbacks = callbacks.filter(c => c.toString() !== callback.toString());
this._eventCallbacks[eventType] = filteredCallbacks;
}
canOpenURL() {
return Promise.resolve(true);
}
getInitialURL() {
return Promise.resolve(initialURL);
}
/**
* Try to open the given url in a secure fashion. The method returns a Promise object.
* If a target is passed (including undefined) that target will be used, otherwise '_blank'.
* If the url opens, the promise is resolved. If not, the promise is rejected.
* Dispatches the `onOpen` event if `url` is opened successfully.
*/
openURL(url, target) {
if (arguments.length === 1) {
target = '_blank';
}
try {
open(url, target);
this._dispatchEvent('onOpen', url);
return Promise.resolve();
} catch (e) {
return Promise.reject(e);
}
}
_validateURL(url) {
(0, _invariant.default)(typeof url === 'string', 'Invalid URL: should be a string. Was: ' + url);
(0, _invariant.default)(url, 'Invalid URL: cannot be empty');
}
}
var open = (url, target) => {
if (_canUseDom.default) {
var urlToOpen = new URL(url, window.location).toString();
if (urlToOpen.indexOf('tel:') === 0) {
window.location = urlToOpen;
} else {
window.open(urlToOpen, target, 'noopener');
}
}
};
var _default = new Linking();
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/LogBox/index.js
"use strict";
exports.__esModule = true;
exports.default = void 0;
/**
* Copyright (c) 2016-present, Nicolas Gallagher.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
var LogBox = {
ignoreLogs() {},
ignoreAllLogs() {},
uninstall() {},
install() {}
};
var _default = LogBox;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Modal/ModalAnimation.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
var _StyleSheet = _interopRequireDefault(require("../StyleSheet"));
var _createElement = _interopRequireDefault(require("../createElement"));
/**
* 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.
*
*
*/
var ANIMATION_DURATION = 300;
function getAnimationStyle(animationType, visible) {
if (animationType === 'slide') {
return visible ? animatedSlideInStyles : animatedSlideOutStyles;
}
if (animationType === 'fade') {
return visible ? animatedFadeInStyles : animatedFadeOutStyles;
}
return visible ? styles.container : styles.hidden;
}
function ModalAnimation(props) {
var animationType = props.animationType,
children = props.children,
onDismiss = props.onDismiss,
onShow = props.onShow,
visible = props.visible;
var _React$useState = React.useState(false),
isRendering = _React$useState[0],
setIsRendering = _React$useState[1];
var wasVisible = React.useRef(false);
var wasRendering = React.useRef(false);
var isAnimated = animationType && animationType !== 'none';
var animationEndCallback = React.useCallback(e => {
if (e && e.currentTarget !== e.target) {
// If the event was generated for something NOT this element we
// should ignore it as it's not relevant to us
return;
}
if (visible) {
if (onShow) {
onShow();
}
} else {
setIsRendering(false);
}
}, [onShow, visible]);
React.useEffect(() => {
if (wasRendering.current && !isRendering && onDismiss) {
onDismiss();
}
wasRendering.current = isRendering;
}, [isRendering, onDismiss]);
React.useEffect(() => {
if (visible) {
setIsRendering(true);
}
if (visible !== wasVisible.current && !isAnimated) {
// Manually call `animationEndCallback` if no animation is used
animationEndCallback();
}
wasVisible.current = visible;
}, [isAnimated, visible, animationEndCallback]);
return isRendering || visible ? (0, _createElement.default)('div', {
style: isRendering ? getAnimationStyle(animationType, visible) : styles.hidden,
onAnimationEnd: animationEndCallback,
children
}) : null;
}
var styles = _StyleSheet.default.create({
container: {
position: 'fixed',
top: 0,
right: 0,
bottom: 0,
left: 0,
zIndex: 9999
},
animatedIn: {
animationDuration: ANIMATION_DURATION + "ms",
animationTimingFunction: 'ease-in'
},
animatedOut: {
pointerEvents: 'none',
animationDuration: ANIMATION_DURATION + "ms",
animationTimingFunction: 'ease-out'
},
fadeIn: {
opacity: 1,
animationKeyframes: {
'0%': {
opacity: 0
},
'100%': {
opacity: 1
}
}
},
fadeOut: {
opacity: 0,
animationKeyframes: {
'0%': {
opacity: 1
},
'100%': {
opacity: 0
}
}
},
slideIn: {
transform: 'translateY(0%)',
animationKeyframes: {
'0%': {
transform: 'translateY(100%)'
},
'100%': {
transform: 'translateY(0%)'
}
}
},
slideOut: {
transform: 'translateY(100%)',
animationKeyframes: {
'0%': {
transform: 'translateY(0%)'
},
'100%': {
transform: 'translateY(100%)'
}
}
},
hidden: {
opacity: 0
}
});
var animatedSlideInStyles = [styles.container, styles.animatedIn, styles.slideIn];
var animatedSlideOutStyles = [styles.container, styles.animatedOut, styles.slideOut];
var animatedFadeInStyles = [styles.container, styles.animatedIn, styles.fadeIn];
var animatedFadeOutStyles = [styles.container, styles.animatedOut, styles.fadeOut];
var _default = ModalAnimation;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Modal/ModalContent.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var React = _interopRequireWildcard(require("react"));
var _View = _interopRequireDefault(require("../View"));
var _StyleSheet = _interopRequireDefault(require("../StyleSheet"));
var _canUseDom = _interopRequireDefault(require("../../modules/canUseDom"));
var _excluded = ["active", "children", "onRequestClose", "transparent"];
var ModalContent = /*#__PURE__*/React.forwardRef((props, forwardedRef) => {
var active = props.active,
children = props.children,
onRequestClose = props.onRequestClose,
transparent = props.transparent,
rest = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
React.useEffect(() => {
if (_canUseDom.default) {
var closeOnEscape = e => {
if (active && e.key === 'Escape') {
e.stopPropagation();
if (onRequestClose) {
onRequestClose();
}
}
};
document.addEventListener('keyup', closeOnEscape, false);
return () => document.removeEventListener('keyup', closeOnEscape, false);
}
}, [active, onRequestClose]);
var style = React.useMemo(() => {
return [styles.modal, transparent ? styles.modalTransparent : styles.modalOpaque];
}, [transparent]);
return /*#__PURE__*/React.createElement(_View.default, (0, _extends2.default)({}, rest, {
"aria-modal": true,
ref: forwardedRef,
role: active ? 'dialog' : null,
style: style
}), /*#__PURE__*/React.createElement(_View.default, {
style: styles.container
}, children));
});
var styles = _StyleSheet.default.create({
modal: {
position: 'fixed',
top: 0,
right: 0,
bottom: 0,
left: 0
},
modalTransparent: {
backgroundColor: 'transparent'
},
modalOpaque: {
backgroundColor: 'white'
},
container: {
top: 0,
flex: 1
}
});
var _default = ModalContent;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Modal/ModalFocusTrap.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
var _View = _interopRequireDefault(require("../View"));
var _createElement = _interopRequireDefault(require("../createElement"));
var _StyleSheet = _interopRequireDefault(require("../StyleSheet"));
var _UIManager = _interopRequireDefault(require("../UIManager"));
var _canUseDom = _interopRequireDefault(require("../../modules/canUseDom"));
/**
* 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.
*
*
*/
/**
* This Component is used to "wrap" the modal we're opening
* so that changing focus via tab will never leave the document.
*
* This allows us to properly trap the focus within a modal
* even if the modal is at the start or end of a document.
*/
var FocusBracket = () => {
return (0, _createElement.default)('div', {
role: 'none',
tabIndex: 0,
style: styles.focusBracket
});
};
function attemptFocus(element) {
if (!_canUseDom.default) {
return false;
}
try {
element.focus();
} catch (e) {
// Do nothing
}
return document.activeElement === element;
}
function focusFirstDescendant(element) {
for (var i = 0; i < element.childNodes.length; i++) {
var child = element.childNodes[i];
if (attemptFocus(child) || focusFirstDescendant(child)) {
return true;
}
}
return false;
}
function focusLastDescendant(element) {
for (var i = element.childNodes.length - 1; i >= 0; i--) {
var child = element.childNodes[i];
if (attemptFocus(child) || focusLastDescendant(child)) {
return true;
}
}
return false;
}
var ModalFocusTrap = _ref => {
var active = _ref.active,
children = _ref.children;
var trapElementRef = React.useRef();
var focusRef = React.useRef({
trapFocusInProgress: false,
lastFocusedElement: null
});
React.useEffect(() => {
if (_canUseDom.default) {
var trapFocus = () => {
// We should not trap focus if:
// - The modal hasn't fully initialized with an HTMLElement ref
// - Focus is already in the process of being trapped (e.g., we're refocusing)
// - isTrapActive prop being falsey tells us to do nothing
if (trapElementRef.current == null || focusRef.current.trapFocusInProgress || !active) {
return;
}
try {
focusRef.current.trapFocusInProgress = true;
if (document.activeElement instanceof Node && !trapElementRef.current.contains(document.activeElement)) {
// To handle keyboard focusing we can make an assumption here.
// If you're tabbing through the focusable elements, the previously
// active element will either be the first or the last.
// If the previously selected element is the "first" descendant
// and we're leaving it - this means that we should be looping
// around to the other side of the modal.
var hasFocused = focusFirstDescendant(trapElementRef.current);
if (focusRef.current.lastFocusedElement === document.activeElement) {
hasFocused = focusLastDescendant(trapElementRef.current);
}
// If we couldn't focus a new element then we need to focus onto the trap target
if (!hasFocused && trapElementRef.current != null && document.activeElement) {
_UIManager.default.focus(trapElementRef.current);
}
}
} finally {
focusRef.current.trapFocusInProgress = false;
}
focusRef.current.lastFocusedElement = document.activeElement;
};
// Call the trapFocus callback at least once when this modal has been activated.
trapFocus();
document.addEventListener('focus', trapFocus, true);
return () => document.removeEventListener('focus', trapFocus, true);
}
}, [active]);
// To be fully compliant with WCAG we need to refocus element that triggered opening modal
// after closing it
React.useEffect(function () {
if (_canUseDom.default) {
var lastFocusedElementOutsideTrap = document.activeElement;
return function () {
if (lastFocusedElementOutsideTrap && document.contains(lastFocusedElementOutsideTrap)) {
_UIManager.default.focus(lastFocusedElementOutsideTrap);
}
};
}
}, []);
return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(FocusBracket, null), /*#__PURE__*/React.createElement(_View.default, {
ref: trapElementRef
}, children), /*#__PURE__*/React.createElement(FocusBracket, null));
};
var _default = ModalFocusTrap;
exports.default = _default;
var styles = _StyleSheet.default.create({
focusBracket: {
outlineStyle: 'none'
}
});
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Modal/ModalPortal.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
var _reactDom = _interopRequireDefault(require("react-dom"));
var _canUseDom = _interopRequireDefault(require("../../modules/canUseDom"));
/**
* 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.
*
*
*/
function ModalPortal(props) {
var children = props.children;
var elementRef = React.useRef(null);
if (_canUseDom.default && !elementRef.current) {
var element = document.createElement('div');
if (element && document.body) {
document.body.appendChild(element);
elementRef.current = element;
}
}
React.useEffect(() => {
if (_canUseDom.default) {
return () => {
if (document.body && elementRef.current) {
document.body.removeChild(elementRef.current);
elementRef.current = null;
}
};
}
}, []);
return elementRef.current && _canUseDom.default ? /*#__PURE__*/_reactDom.default.createPortal(children, elementRef.current) : null;
}
var _default = ModalPortal;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Modal/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var React = _interopRequireWildcard(require("react"));
var _ModalPortal = _interopRequireDefault(require("./ModalPortal"));
var _ModalAnimation = _interopRequireDefault(require("./ModalAnimation"));
var _ModalContent = _interopRequireDefault(require("./ModalContent"));
var _ModalFocusTrap = _interopRequireDefault(require("./ModalFocusTrap"));
var _excluded = ["animationType", "children", "onDismiss", "onRequestClose", "onShow", "transparent", "visible"];
var uniqueModalIdentifier = 0;
var activeModalStack = [];
var activeModalListeners = {};
function notifyActiveModalListeners() {
if (activeModalStack.length === 0) {
return;
}
var activeModalId = activeModalStack[activeModalStack.length - 1];
activeModalStack.forEach(modalId => {
if (modalId in activeModalListeners) {
activeModalListeners[modalId](modalId === activeModalId);
}
});
}
function removeActiveModal(modalId) {
if (modalId in activeModalListeners) {
// Before removing this listener we should probably tell it
// that it's no longer the active modal for sure.
activeModalListeners[modalId](false);
delete activeModalListeners[modalId];
}
var index = activeModalStack.indexOf(modalId);
if (index !== -1) {
activeModalStack.splice(index, 1);
notifyActiveModalListeners();
}
}
function addActiveModal(modalId, listener) {
removeActiveModal(modalId);
activeModalStack.push(modalId);
activeModalListeners[modalId] = listener;
notifyActiveModalListeners();
}
var Modal = /*#__PURE__*/React.forwardRef((props, forwardedRef) => {
var animationType = props.animationType,
children = props.children,
onDismiss = props.onDismiss,
onRequestClose = props.onRequestClose,
onShow = props.onShow,
transparent = props.transparent,
_props$visible = props.visible,
visible = _props$visible === void 0 ? true : _props$visible,
rest = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
// Set a unique model identifier so we can correctly route
// dismissals and check the layering of modals.
var modalId = React.useMemo(() => uniqueModalIdentifier++, []);
var _React$useState = React.useState(false),
isActive = _React$useState[0],
setIsActive = _React$useState[1];
var onDismissCallback = React.useCallback(() => {
removeActiveModal(modalId);
if (onDismiss) {
onDismiss();
}
}, [modalId, onDismiss]);
var onShowCallback = React.useCallback(() => {
addActiveModal(modalId, setIsActive);
if (onShow) {
onShow();
}
}, [modalId, onShow]);
React.useEffect(() => {
return () => removeActiveModal(modalId);
}, [modalId]);
return /*#__PURE__*/React.createElement(_ModalPortal.default, null, /*#__PURE__*/React.createElement(_ModalAnimation.default, {
animationType: animationType,
onDismiss: onDismissCallback,
onShow: onShowCallback,
visible: visible
}, /*#__PURE__*/React.createElement(_ModalFocusTrap.default, {
active: isActive
}, /*#__PURE__*/React.createElement(_ModalContent.default, (0, _extends2.default)({}, rest, {
active: isActive,
onRequestClose: onRequestClose,
ref: forwardedRef,
transparent: transparent
}), children))));
});
var _default = Modal;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/NativeEventEmitter/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _NativeEventEmitter = _interopRequireDefault(require("../../vendor/react-native/EventEmitter/NativeEventEmitter"));
/**
* 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.
*
*
*/
var _default = _NativeEventEmitter.default;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/NativeModules/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _UIManager = _interopRequireDefault(require("../UIManager"));
/**
* 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.
*
*
*/
// NativeModules shim
var NativeModules = {
UIManager: _UIManager.default
};
var _default = NativeModules;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/PanResponder/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _PanResponder = _interopRequireDefault(require("../../vendor/react-native/PanResponder"));
var _default = _PanResponder.default;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Picker/PickerItem.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = PickerItem;
var _createElement = _interopRequireDefault(require("../createElement"));
/**
* 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.
*
*
*/
function PickerItem(props) {
var color = props.color,
label = props.label,
testID = props.testID,
value = props.value;
var style = {
color
};
return (0, _createElement.default)('option', {
children: label,
style,
testID,
value
});
}
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Picker/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var React = _interopRequireWildcard(require("react"));
var _createElement = _interopRequireDefault(require("../createElement"));
var _useMergeRefs = _interopRequireDefault(require("../../modules/useMergeRefs"));
var _usePlatformMethods = _interopRequireDefault(require("../../modules/usePlatformMethods"));
var _PickerItem = _interopRequireDefault(require("./PickerItem"));
var _StyleSheet = _interopRequireDefault(require("../StyleSheet"));
var _excluded = ["children", "enabled", "onValueChange", "selectedValue", "style", "testID", "itemStyle", "mode", "prompt"];
var Picker = /*#__PURE__*/React.forwardRef((props, forwardedRef) => {
var children = props.children,
enabled = props.enabled,
onValueChange = props.onValueChange,
selectedValue = props.selectedValue,
style = props.style,
testID = props.testID,
itemStyle = props.itemStyle,
mode = props.mode,
prompt = props.prompt,
other = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
var hostRef = React.useRef(null);
function handleChange(e) {
var _e$target = e.target,
selectedIndex = _e$target.selectedIndex,
value = _e$target.value;
if (onValueChange) {
onValueChange(value, selectedIndex);
}
}
// $FlowFixMe
var supportedProps = (0, _objectSpread2.default)({
children,
disabled: enabled === false ? true : undefined,
onChange: handleChange,
style: [styles.initial, style],
testID,
value: selectedValue
}, other);
var platformMethodsRef = (0, _usePlatformMethods.default)(supportedProps);
var setRef = (0, _useMergeRefs.default)(hostRef, platformMethodsRef, forwardedRef);
supportedProps.ref = setRef;
return (0, _createElement.default)('select', supportedProps);
});
// $FlowFixMe
Picker.Item = _PickerItem.default;
var styles = _StyleSheet.default.create({
initial: {
fontFamily: 'System',
fontSize: 'inherit',
margin: 0
}
});
var _default = Picker;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/PixelRatio/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _Dimensions = _interopRequireDefault(require("../Dimensions"));
/**
* 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.
*
*
*/
/**
* PixelRatio gives access to the device pixel density.
*/
class PixelRatio {
/**
* Returns the device pixel density.
*/
static get() {
return _Dimensions.default.get('window').scale;
}
/**
* No equivalent for Web
*/
static getFontScale() {
return _Dimensions.default.get('window').fontScale || PixelRatio.get();
}
/**
* Converts a layout size (dp) to pixel size (px).
* Guaranteed to return an integer number.
*/
static getPixelSizeForLayoutSize(layoutSize) {
return Math.round(layoutSize * PixelRatio.get());
}
/**
* Rounds a layout size (dp) to the nearest layout size that corresponds to
* an integer number of pixels. For example, on a device with a PixelRatio
* of 3, `PixelRatio.roundToNearestPixel(8.4) = 8.33`, which corresponds to
* exactly (8.33 * 3) = 25 pixels.
*/
static roundToNearestPixel(layoutSize) {
var ratio = PixelRatio.get();
return Math.round(layoutSize * ratio) / ratio;
}
}
exports.default = PixelRatio;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Platform/index.js
"use strict";
exports.__esModule = true;
exports.default = void 0;
/**
* 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.
*
*
*/
var Platform = {
OS: 'web',
select: obj => 'web' in obj ? obj.web : obj.default,
get isTesting() {
if (process.env.NODE_ENV === 'test') {
return true;
}
return false;
}
};
var _default = Platform;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Pressable/index.js
/**
* 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.
*
*
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var React = _interopRequireWildcard(require("react"));
var _useMergeRefs = _interopRequireDefault(require("../../modules/useMergeRefs"));
var _useHover = _interopRequireDefault(require("../../modules/useHover"));
var _usePressEvents = _interopRequireDefault(require("../../modules/usePressEvents"));
var _StyleSheet = _interopRequireDefault(require("../StyleSheet"));
var _View = _interopRequireDefault(require("../View"));
var _excluded = ["children", "delayLongPress", "delayPressIn", "delayPressOut", "disabled", "onBlur", "onContextMenu", "onFocus", "onHoverIn", "onHoverOut", "onKeyDown", "onLongPress", "onPress", "onPressMove", "onPressIn", "onPressOut", "style", "tabIndex", "testOnly_hovered", "testOnly_pressed"];
/**
* Component used to build display components that should respond to whether the
* component is currently pressed or not.
*/
function Pressable(props, forwardedRef) {
var children = props.children,
delayLongPress = props.delayLongPress,
delayPressIn = props.delayPressIn,
delayPressOut = props.delayPressOut,
disabled = props.disabled,
onBlur = props.onBlur,
onContextMenu = props.onContextMenu,
onFocus = props.onFocus,
onHoverIn = props.onHoverIn,
onHoverOut = props.onHoverOut,
onKeyDown = props.onKeyDown,
onLongPress = props.onLongPress,
onPress = props.onPress,
onPressMove = props.onPressMove,
onPressIn = props.onPressIn,
onPressOut = props.onPressOut,
style = props.style,
tabIndex = props.tabIndex,
testOnly_hovered = props.testOnly_hovered,
testOnly_pressed = props.testOnly_pressed,
rest = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
var _useForceableState = useForceableState(testOnly_hovered === true),
hovered = _useForceableState[0],
setHovered = _useForceableState[1];
var _useForceableState2 = useForceableState(false),
focused = _useForceableState2[0],
setFocused = _useForceableState2[1];
var _useForceableState3 = useForceableState(testOnly_pressed === true),
pressed = _useForceableState3[0],
setPressed = _useForceableState3[1];
var hostRef = (0, React.useRef)(null);
var setRef = (0, _useMergeRefs.default)(forwardedRef, hostRef);
var pressConfig = (0, React.useMemo)(() => ({
delayLongPress,
delayPressStart: delayPressIn,
delayPressEnd: delayPressOut,
disabled,
onLongPress,
onPress,
onPressChange: setPressed,
onPressStart: onPressIn,
onPressMove,
onPressEnd: onPressOut
}), [delayLongPress, delayPressIn, delayPressOut, disabled, onLongPress, onPress, onPressIn, onPressMove, onPressOut, setPressed]);
var pressEventHandlers = (0, _usePressEvents.default)(hostRef, pressConfig);
var onContextMenuPress = pressEventHandlers.onContextMenu,
onKeyDownPress = pressEventHandlers.onKeyDown;
(0, _useHover.default)(hostRef, {
contain: true,
disabled,
onHoverChange: setHovered,
onHoverStart: onHoverIn,
onHoverEnd: onHoverOut
});
var interactionState = {
hovered,
focused,
pressed
};
var blurHandler = React.useCallback(e => {
if (e.nativeEvent.target === hostRef.current) {
setFocused(false);
if (onBlur != null) {
onBlur(e);
}
}
}, [hostRef, setFocused, onBlur]);
var focusHandler = React.useCallback(e => {
if (e.nativeEvent.target === hostRef.current) {
setFocused(true);
if (onFocus != null) {
onFocus(e);
}
}
}, [hostRef, setFocused, onFocus]);
var contextMenuHandler = React.useCallback(e => {
if (onContextMenuPress != null) {
onContextMenuPress(e);
}
if (onContextMenu != null) {
onContextMenu(e);
}
}, [onContextMenu, onContextMenuPress]);
var keyDownHandler = React.useCallback(e => {
if (onKeyDownPress != null) {
onKeyDownPress(e);
}
if (onKeyDown != null) {
onKeyDown(e);
}
}, [onKeyDown, onKeyDownPress]);
var _tabIndex;
if (tabIndex !== undefined) {
_tabIndex = tabIndex;
} else {
_tabIndex = disabled ? -1 : 0;
}
return /*#__PURE__*/React.createElement(_View.default, (0, _extends2.default)({}, rest, pressEventHandlers, {
"aria-disabled": disabled,
onBlur: blurHandler,
onContextMenu: contextMenuHandler,
onFocus: focusHandler,
onKeyDown: keyDownHandler,
ref: setRef,
style: [disabled ? styles.disabled : styles.active, typeof style === 'function' ? style(interactionState) : style],
tabIndex: _tabIndex
}), typeof children === 'function' ? children(interactionState) : children);
}
function useForceableState(forced) {
var _useState = (0, React.useState)(false),
bool = _useState[0],
setBool = _useState[1];
return [bool || forced, setBool];
}
var styles = _StyleSheet.default.create({
active: {
cursor: 'pointer',
touchAction: 'manipulation'
},
disabled: {
pointerEvents: 'box-none'
}
});
var MemoedPressable = /*#__PURE__*/(0, React.memo)( /*#__PURE__*/(0, React.forwardRef)(Pressable));
MemoedPressable.displayName = 'Pressable';
var _default = MemoedPressable;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/ProgressBar/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var React = _interopRequireWildcard(require("react"));
var _StyleSheet = _interopRequireDefault(require("../StyleSheet"));
var _View = _interopRequireDefault(require("../View"));
var _excluded = ["color", "indeterminate", "progress", "trackColor", "style"];
var ProgressBar = /*#__PURE__*/React.forwardRef((props, ref) => {
var _props$color = props.color,
color = _props$color === void 0 ? '#1976D2' : _props$color,
_props$indeterminate = props.indeterminate,
indeterminate = _props$indeterminate === void 0 ? false : _props$indeterminate,
_props$progress = props.progress,
progress = _props$progress === void 0 ? 0 : _props$progress,
_props$trackColor = props.trackColor,
trackColor = _props$trackColor === void 0 ? 'transparent' : _props$trackColor,
style = props.style,
other = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
var percentageProgress = progress * 100;
var width = indeterminate ? '25%' : percentageProgress + "%";
return /*#__PURE__*/React.createElement(_View.default, (0, _extends2.default)({}, other, {
"aria-valuemax": 100,
"aria-valuemin": 0,
"aria-valuenow": indeterminate ? null : percentageProgress,
ref: ref,
role: "progressbar",
style: [styles.track, style, {
backgroundColor: trackColor
}]
}), /*#__PURE__*/React.createElement(_View.default, {
style: [{
backgroundColor: color,
width
}, styles.progress, indeterminate && styles.animation]
}));
});
ProgressBar.displayName = 'ProgressBar';
var styles = _StyleSheet.default.create({
track: {
forcedColorAdjust: 'none',
height: 5,
overflow: 'hidden',
userSelect: 'none',
zIndex: 0
},
progress: {
forcedColorAdjust: 'none',
height: '100%',
zIndex: -1
},
animation: {
animationDuration: '1s',
animationKeyframes: [{
'0%': {
transform: 'translateX(-100%)'
},
'100%': {
transform: 'translateX(400%)'
}
}],
animationTimingFunction: 'linear',
animationIterationCount: 'infinite'
}
});
var _default = ProgressBar;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/RefreshControl/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var _View = _interopRequireDefault(require("../View"));
var _react = _interopRequireDefault(require("react"));
var _excluded = ["colors", "enabled", "onRefresh", "progressBackgroundColor", "progressViewOffset", "refreshing", "size", "tintColor", "title", "titleColor"];
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 = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
return /*#__PURE__*/_react.default.createElement(_View.default, rest);
}
var _default = RefreshControl;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/SafeAreaView/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var React = _interopRequireWildcard(require("react"));
var _StyleSheet = _interopRequireDefault(require("../StyleSheet"));
var _View = _interopRequireDefault(require("../View"));
var _canUseDom = _interopRequireDefault(require("../../modules/canUseDom"));
var _excluded = ["style"];
var cssFunction = function () {
if (_canUseDom.default && window.CSS && window.CSS.supports && window.CSS.supports('top: constant(safe-area-inset-top)')) {
return 'constant';
}
return 'env';
}();
var SafeAreaView = /*#__PURE__*/React.forwardRef((props, ref) => {
var style = props.style,
rest = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
return /*#__PURE__*/React.createElement(_View.default, (0, _extends2.default)({}, rest, {
ref: ref,
style: [styles.root, style]
}));
});
SafeAreaView.displayName = 'SafeAreaView';
var styles = _StyleSheet.default.create({
root: {
paddingTop: cssFunction + "(safe-area-inset-top)",
paddingRight: cssFunction + "(safe-area-inset-right)",
paddingBottom: cssFunction + "(safe-area-inset-bottom)",
paddingLeft: cssFunction + "(safe-area-inset-left)"
}
});
var _default = SafeAreaView;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/ScrollView/ScrollViewBase.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var React = _interopRequireWildcard(require("react"));
var _StyleSheet = _interopRequireDefault(require("../StyleSheet"));
var _View = _interopRequireDefault(require("../View"));
var _useMergeRefs = _interopRequireDefault(require("../../modules/useMergeRefs"));
var _excluded = ["onScroll", "onTouchMove", "onWheel", "scrollEnabled", "scrollEventThrottle", "showsHorizontalScrollIndicator", "showsVerticalScrollIndicator", "style"];
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()
};
}
function shouldEmitScrollEvent(lastTick, eventThrottle) {
var timeSinceLastTick = Date.now() - lastTick;
return eventThrottle > 0 && timeSinceLastTick >= eventThrottle;
}
/**
* Encapsulates the Web-specific scroll throttling and disabling logic
*/
var ScrollViewBase = /*#__PURE__*/React.forwardRef((props, forwardedRef) => {
var onScroll = props.onScroll,
onTouchMove = props.onTouchMove,
onWheel = props.onWheel,
_props$scrollEnabled = props.scrollEnabled,
scrollEnabled = _props$scrollEnabled === void 0 ? true : _props$scrollEnabled,
_props$scrollEventThr = props.scrollEventThrottle,
scrollEventThrottle = _props$scrollEventThr === void 0 ? 0 : _props$scrollEventThr,
showsHorizontalScrollIndicator = props.showsHorizontalScrollIndicator,
showsVerticalScrollIndicator = props.showsVerticalScrollIndicator,
style = props.style,
rest = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
var scrollState = React.useRef({
isScrolling: false,
scrollLastTick: 0
});
var scrollTimeout = React.useRef(null);
var scrollRef = React.useRef(null);
function createPreventableScrollHandler(handler) {
return e => {
if (scrollEnabled) {
if (handler) {
handler(e);
}
}
};
}
function handleScroll(e) {
e.stopPropagation();
if (e.target === scrollRef.current) {
e.persist();
// A scroll happened, so the scroll resets the scrollend timeout.
if (scrollTimeout.current != null) {
clearTimeout(scrollTimeout.current);
}
scrollTimeout.current = setTimeout(() => {
handleScrollEnd(e);
}, 100);
if (scrollState.current.isScrolling) {
// Scroll last tick may have changed, check if we need to notify
if (shouldEmitScrollEvent(scrollState.current.scrollLastTick, scrollEventThrottle)) {
handleScrollTick(e);
}
} else {
// Weren't scrolling, so we must have just started
handleScrollStart(e);
}
}
}
function handleScrollStart(e) {
scrollState.current.isScrolling = true;
handleScrollTick(e);
}
function handleScrollTick(e) {
scrollState.current.scrollLastTick = Date.now();
if (onScroll) {
onScroll(normalizeScrollEvent(e));
}
}
function handleScrollEnd(e) {
scrollState.current.isScrolling = false;
if (onScroll) {
onScroll(normalizeScrollEvent(e));
}
}
var hideScrollbar = showsHorizontalScrollIndicator === false || showsVerticalScrollIndicator === false;
return /*#__PURE__*/React.createElement(_View.default, (0, _extends2.default)({}, rest, {
onScroll: handleScroll,
onTouchMove: createPreventableScrollHandler(onTouchMove),
onWheel: createPreventableScrollHandler(onWheel),
ref: (0, _useMergeRefs.default)(scrollRef, forwardedRef),
style: [style, !scrollEnabled && styles.scrollDisabled, hideScrollbar && styles.hideScrollbar]
}));
});
// 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
var styles = _StyleSheet.default.create({
scrollDisabled: {
overflowX: 'hidden',
overflowY: 'hidden',
touchAction: 'none'
},
hideScrollbar: {
scrollbarWidth: 'none'
}
});
var _default = ScrollViewBase;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/ScrollView/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var _Dimensions = _interopRequireDefault(require("../Dimensions"));
var _dismissKeyboard = _interopRequireDefault(require("../../modules/dismissKeyboard"));
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
var _mergeRefs = _interopRequireDefault(require("../../modules/mergeRefs"));
var _Platform = _interopRequireDefault(require("../Platform"));
var _ScrollViewBase = _interopRequireDefault(require("./ScrollViewBase"));
var _StyleSheet = _interopRequireDefault(require("../StyleSheet"));
var _TextInputState = _interopRequireDefault(require("../../modules/TextInputState"));
var _UIManager = _interopRequireDefault(require("../UIManager"));
var _View = _interopRequireDefault(require("../View"));
var _react = _interopRequireDefault(require("react"));
var _warning = _interopRequireDefault(require("fbjs/lib/warning"));
var _excluded = ["contentContainerStyle", "horizontal", "onContentSizeChange", "refreshControl", "stickyHeaderIndices", "pagingEnabled", "forwardedRef", "keyboardDismissMode", "onScroll", "centerContent"];
var emptyObject = {};
var IS_ANIMATING_TOUCH_START_THRESHOLD_MS = 16;
class ScrollView extends _react.default.Component {
constructor() {
super(...arguments);
this._scrollNodeRef = null;
this._innerViewRef = null;
this.isTouching = false;
this.lastMomentumScrollBeginTime = 0;
this.lastMomentumScrollEndTime = 0;
this.observedScrollSinceBecomingResponder = false;
this.becameResponderWhileAnimating = false;
this.scrollResponderHandleScrollShouldSetResponder = () => {
return this.isTouching;
};
this.scrollResponderHandleStartShouldSetResponderCapture = e => {
// First see if we want to eat taps while the keyboard is up
// var currentlyFocusedTextInput = TextInputState.currentlyFocusedField();
// if (!this.props.keyboardShouldPersistTaps &&
// currentlyFocusedTextInput != null &&
// e.target !== currentlyFocusedTextInput) {
// return true;
// }
return this.scrollResponderIsAnimating();
};
this.scrollResponderHandleTerminationRequest = () => {
return !this.observedScrollSinceBecomingResponder;
};
this.scrollResponderHandleTouchEnd = e => {
var nativeEvent = e.nativeEvent;
this.isTouching = nativeEvent.touches.length !== 0;
this.props.onTouchEnd && this.props.onTouchEnd(e);
};
this.scrollResponderHandleResponderRelease = e => {
this.props.onResponderRelease && this.props.onResponderRelease(e);
// By default scroll views will unfocus a textField
// if another touch occurs outside of it
var currentlyFocusedTextInput = _TextInputState.default.currentlyFocusedField();
if (!this.props.keyboardShouldPersistTaps && currentlyFocusedTextInput != null && e.target !== currentlyFocusedTextInput && !this.observedScrollSinceBecomingResponder && !this.becameResponderWhileAnimating) {
this.props.onScrollResponderKeyboardDismissed && this.props.onScrollResponderKeyboardDismissed(e);
_TextInputState.default.blurTextInput(currentlyFocusedTextInput);
}
};
this.scrollResponderHandleScroll = e => {
this.observedScrollSinceBecomingResponder = true;
this.props.onScroll && this.props.onScroll(e);
};
this.scrollResponderHandleResponderGrant = e => {
this.observedScrollSinceBecomingResponder = false;
this.props.onResponderGrant && this.props.onResponderGrant(e);
this.becameResponderWhileAnimating = this.scrollResponderIsAnimating();
};
this.scrollResponderHandleScrollBeginDrag = e => {
this.props.onScrollBeginDrag && this.props.onScrollBeginDrag(e);
};
this.scrollResponderHandleScrollEndDrag = e => {
this.props.onScrollEndDrag && this.props.onScrollEndDrag(e);
};
this.scrollResponderHandleMomentumScrollBegin = e => {
this.lastMomentumScrollBeginTime = Date.now();
this.props.onMomentumScrollBegin && this.props.onMomentumScrollBegin(e);
};
this.scrollResponderHandleMomentumScrollEnd = e => {
this.lastMomentumScrollEndTime = Date.now();
this.props.onMomentumScrollEnd && this.props.onMomentumScrollEnd(e);
};
this.scrollResponderHandleTouchStart = e => {
this.isTouching = true;
this.props.onTouchStart && this.props.onTouchStart(e);
};
this.scrollResponderHandleTouchMove = e => {
this.props.onTouchMove && this.props.onTouchMove(e);
};
this.scrollResponderIsAnimating = () => {
var now = Date.now();
var timeSinceLastMomentumScrollEnd = now - this.lastMomentumScrollEndTime;
var isAnimating = timeSinceLastMomentumScrollEnd < IS_ANIMATING_TOUCH_START_THRESHOLD_MS || this.lastMomentumScrollEndTime < this.lastMomentumScrollBeginTime;
return isAnimating;
};
this.scrollResponderScrollTo = (x, y, animated) => {
if (typeof x === 'number') {
console.warn('`scrollResponderScrollTo(x, y, animated)` is deprecated. Use `scrollResponderScrollTo({x: 5, y: 5, animated: true})` instead.');
} else {
var _ref = x || emptyObject;
x = _ref.x;
y = _ref.y;
animated = _ref.animated;
}
var node = this.getScrollableNode();
var left = x || 0;
var top = y || 0;
if (node != null) {
if (typeof node.scroll === 'function') {
node.scroll({
top,
left,
behavior: !animated ? 'auto' : 'smooth'
});
} else {
node.scrollLeft = left;
node.scrollTop = top;
}
}
};
this.scrollResponderZoomTo = (rect, animated) => {
if (_Platform.default.OS !== 'ios') {
(0, _invariant.default)('zoomToRect is not implemented');
}
};
this.scrollResponderScrollNativeHandleToKeyboard = (nodeHandle, additionalOffset, preventNegativeScrollOffset) => {
this.additionalScrollOffset = additionalOffset || 0;
this.preventNegativeScrollOffset = !!preventNegativeScrollOffset;
_UIManager.default.measureLayout(nodeHandle, this.getInnerViewNode(), this.scrollResponderTextInputFocusError, this.scrollResponderInputMeasureAndScrollToKeyboard);
};
this.scrollResponderInputMeasureAndScrollToKeyboard = (left, top, width, height) => {
var keyboardScreenY = _Dimensions.default.get('window').height;
if (this.keyboardWillOpenTo) {
keyboardScreenY = this.keyboardWillOpenTo.endCoordinates.screenY;
}
var scrollOffsetY = top - keyboardScreenY + height + this.additionalScrollOffset;
// By default, this can scroll with negative offset, pulling the content
// down so that the target component's bottom meets the keyboard's top.
// If requested otherwise, cap the offset at 0 minimum to avoid content
// shifting down.
if (this.preventNegativeScrollOffset) {
scrollOffsetY = Math.max(0, scrollOffsetY);
}
this.scrollResponderScrollTo({
x: 0,
y: scrollOffsetY,
animated: true
});
this.additionalOffset = 0;
this.preventNegativeScrollOffset = false;
};
this.scrollResponderKeyboardWillShow = e => {
this.keyboardWillOpenTo = e;
this.props.onKeyboardWillShow && this.props.onKeyboardWillShow(e);
};
this.scrollResponderKeyboardWillHide = e => {
this.keyboardWillOpenTo = null;
this.props.onKeyboardWillHide && this.props.onKeyboardWillHide(e);
};
this.scrollResponderKeyboardDidShow = e => {
// TODO(7693961): The event for DidShow is not available on iOS yet.
// Use the one from WillShow and do not assign.
if (e) {
this.keyboardWillOpenTo = e;
}
this.props.onKeyboardDidShow && this.props.onKeyboardDidShow(e);
};
this.scrollResponderKeyboardDidHide = e => {
this.keyboardWillOpenTo = null;
this.props.onKeyboardDidHide && this.props.onKeyboardDidHide(e);
};
this.flashScrollIndicators = () => {
this.scrollResponderFlashScrollIndicators();
};
this.getScrollResponder = () => {
return this;
};
this.getScrollableNode = () => {
return this._scrollNodeRef;
};
this.getInnerViewRef = () => {
return this._innerViewRef;
};
this.getInnerViewNode = () => {
return this._innerViewRef;
};
this.getNativeScrollRef = () => {
return this._scrollNodeRef;
};
this.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 _ref2 = y || emptyObject;
x = _ref2.x;
y = _ref2.y;
animated = _ref2.animated;
}
this.scrollResponderScrollTo({
x: x || 0,
y: y || 0,
animated: animated !== false
});
};
this.scrollToEnd = options => {
// Default to true
var animated = (options && options.animated) !== false;
var horizontal = this.props.horizontal;
var scrollResponderNode = this.getScrollableNode();
var x = horizontal ? scrollResponderNode.scrollWidth : 0;
var y = horizontal ? 0 : scrollResponderNode.scrollHeight;
this.scrollResponderScrollTo({
x,
y,
animated
});
};
this._handleContentOnLayout = e => {
var _e$nativeEvent$layout = e.nativeEvent.layout,
width = _e$nativeEvent$layout.width,
height = _e$nativeEvent$layout.height;
this.props.onContentSizeChange(width, height);
};
this._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') {
(0, _dismissKeyboard.default)();
}
this.scrollResponderHandleScroll(e);
};
this._setInnerViewRef = node => {
this._innerViewRef = node;
};
this._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 = (0, _mergeRefs.default)(this.props.forwardedRef);
ref(node);
};
}
/**
* Merely touch starting is not sufficient for a scroll view to become the
* responder. Being the "responder" means that the very next touch move/end
* event will result in an action/movement.
*
* Invoke this from an `onStartShouldSetResponder` event.
*
* `onStartShouldSetResponder` is used when the next move/end will trigger
* some UI movement/action, but when you want to yield priority to views
* nested inside of the view.
*
* There may be some cases where scroll views actually should return `true`
* from `onStartShouldSetResponder`: Any time we are detecting a standard tap
* that gives priority to nested views.
*
* - If a single tap on the scroll view triggers an action such as
* recentering a map style view yet wants to give priority to interaction
* views inside (such as dropped pins or labels), then we would return true
* from this method when there is a single touch.
*
* - Similar to the previous case, if a two finger "tap" should trigger a
* zoom, we would check the `touches` count, and if `>= 2`, we would return
* true.
*
*/
scrollResponderHandleStartShouldSetResponder() {
return false;
}
/**
* There are times when the scroll view wants to become the responder
* (meaning respond to the next immediate `touchStart/touchEnd`), in a way
* that *doesn't* give priority to nested views (hence the capture phase):
*
* - Currently animating.
* - Tapping anywhere that is not the focused input, while the keyboard is
* up (which should dismiss the keyboard).
*
* Invoke this from an `onStartShouldSetResponderCapture` event.
*/
/**
* Invoke this from an `onResponderReject` event.
*
* Some other element is not yielding its role as responder. Normally, we'd
* just disable the `UIScrollView`, but a touch has already began on it, the
* `UIScrollView` will not accept being disabled after that. The easiest
* solution for now is to accept the limitation of disallowing this
* altogether. To improve this, find a way to disable the `UIScrollView` after
* a touch has already started.
*/
scrollResponderHandleResponderReject() {
(0, _warning.default)(false, "ScrollView doesn't take rejection well - scrolls anyway");
}
/**
* We will allow the scroll view to give up its lock iff it acquired the lock
* during an animation. This is a very useful default that happens to satisfy
* many common user experiences.
*
* - Stop a scroll on the left edge, then turn that into an outer view's
* backswipe.
* - Stop a scroll mid-bounce at the top, continue pulling to have the outer
* view dismiss.
* - However, without catching the scroll view mid-bounce (while it is
* motionless), if you drag far enough for the scroll view to become
* responder (and therefore drag the scroll view a bit), any backswipe
* navigation of a swipe gesture higher in the view hierarchy, should be
* rejected.
*/
/**
* Displays the scroll indicators momentarily.
*/
scrollResponderFlashScrollIndicators() {}
/**
* This method should be used as the callback to onFocus in a TextInputs'
* parent view. Note that any module using this mixin needs to return
* the parent view's ref in getScrollViewRef() in order to use this method.
* @param {any} nodeHandle The TextInput node handle
* @param {number} additionalOffset The scroll view's top "contentInset".
* Default is 0.
* @param {bool} preventNegativeScrolling Whether to allow pulling the content
* down to make it meet the keyboard's top. Default is false.
*/
scrollResponderTextInputFocusError(e) {
console.error('Error measuring text field: ', e);
}
/**
* Warning, this may be called several times for a single keyboard opening.
* It's best to store the information in this method and then take any action
* at a later point (either in `keyboardDidShow` or other).
*
* Here's the order that events occur in:
* - focus
* - willShow {startCoordinates, endCoordinates} several times
* - didShow several times
* - blur
* - willHide {startCoordinates, endCoordinates} several times
* - didHide several times
*
* The `ScrollResponder` providesModule callbacks for each of these events.
* Even though any user could have easily listened to keyboard events
* themselves, using these `props` callbacks ensures that ordering of events
* is consistent - and not dependent on the order that the keyboard events are
* subscribed to. This matters when telling the scroll view to scroll to where
* the keyboard is headed - the scroll responder better have been notified of
* the keyboard destination before being instructed to scroll to where the
* keyboard will be. Stick to the `ScrollResponder` callbacks, and everything
* will work.
*
* WARNING: These callbacks will fire even if a keyboard is displayed in a
* different navigation pane. Filter out the events to determine if they are
* relevant to you. (For example, only if you receive these callbacks after
* you had explicitly focused a node etc).
*/
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,
centerContent = _this$props.centerContent,
other = (0, _objectWithoutPropertiesLoose2.default)(_this$props, _excluded);
if (process.env.NODE_ENV !== 'production' && this.props.style) {
var style = _StyleSheet.default.flatten(this.props.style);
var childLayoutProps = ['alignItems', 'justifyContent'].filter(prop => style && style[prop] !== undefined);
(0, _invariant.default)(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.default.Children.map(this.props.children, (child, i) => {
var isSticky = hasStickyHeaderIndices && stickyHeaderIndices.indexOf(i) > -1;
if (child != null && (isSticky || pagingEnabled)) {
return /*#__PURE__*/_react.default.createElement(_View.default, {
style: [isSticky && styles.stickyHeader, pagingEnabled && styles.pagingEnabledChild]
}, child);
} else {
return child;
}
}) : this.props.children;
var contentContainer = /*#__PURE__*/_react.default.createElement(_View.default, (0, _extends2.default)({}, contentSizeChangeProps, {
children: children,
collapsable: false,
ref: this._setInnerViewRef,
style: [horizontal && styles.contentContainerHorizontal, centerContent && styles.contentContainerCenterContent, contentContainerStyle]
}));
var baseStyle = horizontal ? styles.baseHorizontal : styles.baseVertical;
var pagingEnabledStyle = horizontal ? styles.pagingEnabledHorizontal : styles.pagingEnabledVertical;
var props = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, 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.default;
(0, _invariant.default)(ScrollViewClass !== undefined, 'ScrollViewClass must not be undefined');
var scrollView = /*#__PURE__*/_react.default.createElement(ScrollViewClass, (0, _extends2.default)({}, props, {
ref: this._setScrollNodeRef
}), contentContainer);
if (refreshControl) {
return /*#__PURE__*/_react.default.cloneElement(refreshControl, {
style: props.style
}, scrollView);
}
return scrollView;
}
}
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.default.create({
baseVertical: (0, _objectSpread2.default)((0, _objectSpread2.default)({}, commonStyle), {}, {
flexDirection: 'column',
overflowX: 'hidden',
overflowY: 'auto'
}),
baseHorizontal: (0, _objectSpread2.default)((0, _objectSpread2.default)({}, commonStyle), {}, {
flexDirection: 'row',
overflowX: 'auto',
overflowY: 'hidden'
}),
contentContainerHorizontal: {
flexDirection: 'row'
},
contentContainerCenterContent: {
justifyContent: 'center',
flexGrow: 1
},
stickyHeader: {
position: 'sticky',
top: 0,
zIndex: 10
},
pagingEnabledHorizontal: {
scrollSnapType: 'x mandatory'
},
pagingEnabledVertical: {
scrollSnapType: 'y mandatory'
},
pagingEnabledChild: {
scrollSnapAlign: 'start'
}
});
var ForwardedScrollView = /*#__PURE__*/_react.default.forwardRef((props, forwardedRef) => {
return /*#__PURE__*/_react.default.createElement(ScrollView, (0, _extends2.default)({}, props, {
forwardedRef: forwardedRef
}));
});
ForwardedScrollView.displayName = 'ScrollView';
var _default = ForwardedScrollView;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/SectionList/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _SectionList = _interopRequireDefault(require("../../vendor/react-native/SectionList"));
/**
* 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.
*
*
*/
var _default = _SectionList.default;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Share/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
/**
* 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.
*
*
*/
class Share {
static share(content, options) {
if (options === void 0) {
options = {};
}
(0, _invariant.default)(typeof content === 'object' && content !== null, 'Content to share must be a valid object');
(0, _invariant.default)(typeof content.url === 'string' || typeof content.message === 'string', 'At least one of URL and message is required');
(0, _invariant.default)(typeof options === 'object' && options !== null, 'Options must be a valid object');
(0, _invariant.default)(!content.title || typeof content.title === 'string', 'Invalid title: title should be a string.');
if (window.navigator.share !== undefined) {
return window.navigator.share({
title: content.title,
text: content.message,
url: content.url
});
} else {
return Promise.reject(new Error('Share is not supported in this browser'));
}
}
/**
* The content was successfully shared.
*/
static get sharedAction() {
return 'sharedAction';
}
/**
* The dialog has been dismissed.
* @platform ios
*/
static get dismissedAction() {
return 'dismissedAction';
}
}
var _default = Share;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/StatusBar/index.js
"use strict";
exports.__esModule = true;
exports.default = void 0;
/**
* 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.
*
*
*/
var emptyFunction = () => {};
function StatusBar() {
return null;
}
StatusBar.setBackgroundColor = emptyFunction;
StatusBar.setBarStyle = emptyFunction;
StatusBar.setHidden = emptyFunction;
StatusBar.setNetworkActivityIndicatorVisible = emptyFunction;
StatusBar.setTranslucent = emptyFunction;
var _default = StatusBar;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/StyleSheet/compiler/createReactDOMStyle.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _normalizeValueWithProperty = _interopRequireDefault(require("./normalizeValueWithProperty"));
var _canUseDom = _interopRequireDefault(require("../../../modules/canUseDom"));
/**
* 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.
*
*
*/
/**
* The browser implements the CSS cascade, where the order of properties is a
* factor in determining which styles to paint. React Native is different. It
* gives giving precedence to the more specific style property. For example,
* the value of `paddingTop` takes precedence over that of `padding`.
*
* This module creates mutally exclusive style declarations by expanding all of
* React Native's supported shortform properties (e.g. `padding`) to their
* longfrom equivalents.
*/
var emptyObject = {};
var supportsCSS3TextDecoration = !_canUseDom.default || window.CSS != null && window.CSS.supports != null && (window.CSS.supports('text-decoration-line', 'none') || window.CSS.supports('-webkit-text-decoration-line', 'none'));
var MONOSPACE_FONT_STACK = 'monospace,monospace';
var SYSTEM_FONT_STACK = '-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif';
var STYLE_SHORT_FORM_EXPANSIONS = {
borderColor: ['borderTopColor', 'borderRightColor', 'borderBottomColor', 'borderLeftColor'],
borderBlockColor: ['borderTopColor', 'borderBottomColor'],
borderInlineColor: ['borderRightColor', 'borderLeftColor'],
borderRadius: ['borderTopLeftRadius', 'borderTopRightRadius', 'borderBottomRightRadius', 'borderBottomLeftRadius'],
borderStyle: ['borderTopStyle', 'borderRightStyle', 'borderBottomStyle', 'borderLeftStyle'],
borderBlockStyle: ['borderTopStyle', 'borderBottomStyle'],
borderInlineStyle: ['borderRightStyle', 'borderLeftStyle'],
borderWidth: ['borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth'],
borderBlockWidth: ['borderTopWidth', 'borderBottomWidth'],
borderInlineWidth: ['borderRightWidth', 'borderLeftWidth'],
insetBlock: ['top', 'bottom'],
insetInline: ['left', 'right'],
marginBlock: ['marginTop', 'marginBottom'],
marginInline: ['marginRight', 'marginLeft'],
paddingBlock: ['paddingTop', 'paddingBottom'],
paddingInline: ['paddingRight', 'paddingLeft'],
overflow: ['overflowX', 'overflowY'],
overscrollBehavior: ['overscrollBehaviorX', 'overscrollBehaviorY'],
borderBlockStartColor: ['borderTopColor'],
borderBlockStartStyle: ['borderTopStyle'],
borderBlockStartWidth: ['borderTopWidth'],
borderBlockEndColor: ['borderBottomColor'],
borderBlockEndStyle: ['borderBottomStyle'],
borderBlockEndWidth: ['borderBottomWidth'],
//borderInlineStartColor: ['borderLeftColor'],
//borderInlineStartStyle: ['borderLeftStyle'],
//borderInlineStartWidth: ['borderLeftWidth'],
//borderInlineEndColor: ['borderRightColor'],
//borderInlineEndStyle: ['borderRightStyle'],
//borderInlineEndWidth: ['borderRightWidth'],
borderEndStartRadius: ['borderBottomLeftRadius'],
borderEndEndRadius: ['borderBottomRightRadius'],
borderStartStartRadius: ['borderTopLeftRadius'],
borderStartEndRadius: ['borderTopRightRadius'],
insetBlockEnd: ['bottom'],
insetBlockStart: ['top'],
//insetInlineEnd: ['right'],
//insetInlineStart: ['left'],
marginBlockStart: ['marginTop'],
marginBlockEnd: ['marginBottom'],
//marginInlineStart: ['marginLeft'],
//marginInlineEnd: ['marginRight'],
paddingBlockStart: ['paddingTop'],
paddingBlockEnd: ['paddingBottom']
//paddingInlineStart: ['marginLeft'],
//paddingInlineEnd: ['marginRight'],
};
/**
* Reducer
*/
var createReactDOMStyle = (style, isInline) => {
if (!style) {
return emptyObject;
}
var resolvedStyle = {};
var _loop = function _loop() {
var value = style[prop];
if (
// Ignore everything with a null value
value == null) {
return "continue";
}
if (prop === 'backgroundClip') {
// TODO: remove once this issue is fixed
// https://github.com/rofrischmann/inline-style-prefixer/issues/159
if (value === 'text') {
resolvedStyle.backgroundClip = value;
resolvedStyle.WebkitBackgroundClip = value;
}
} else if (prop === 'flex') {
if (value === -1) {
resolvedStyle.flexGrow = 0;
resolvedStyle.flexShrink = 1;
resolvedStyle.flexBasis = 'auto';
} else {
resolvedStyle.flex = value;
}
} else if (prop === 'font') {
resolvedStyle[prop] = value.replace('System', SYSTEM_FONT_STACK);
} else if (prop === 'fontFamily') {
if (value.indexOf('System') > -1) {
var stack = value.split(/,\s*/);
stack[stack.indexOf('System')] = SYSTEM_FONT_STACK;
resolvedStyle[prop] = stack.join(',');
} else if (value === 'monospace') {
resolvedStyle[prop] = MONOSPACE_FONT_STACK;
} else {
resolvedStyle[prop] = value;
}
} else if (prop === 'textDecorationLine') {
// use 'text-decoration' for browsers that only support CSS2
// text-decoration (e.g., IE, Edge)
if (!supportsCSS3TextDecoration) {
resolvedStyle.textDecoration = value;
} else {
resolvedStyle.textDecorationLine = value;
}
} else if (prop === 'writingDirection') {
resolvedStyle.direction = value;
} else {
var _value = (0, _normalizeValueWithProperty.default)(style[prop], prop);
var longFormProperties = STYLE_SHORT_FORM_EXPANSIONS[prop];
if (isInline && prop === 'inset') {
if (style.insetInline == null) {
resolvedStyle.left = _value;
resolvedStyle.right = _value;
}
if (style.insetBlock == null) {
resolvedStyle.top = _value;
resolvedStyle.bottom = _value;
}
} else if (isInline && prop === 'margin') {
if (style.marginInline == null) {
resolvedStyle.marginLeft = _value;
resolvedStyle.marginRight = _value;
}
if (style.marginBlock == null) {
resolvedStyle.marginTop = _value;
resolvedStyle.marginBottom = _value;
}
} else if (isInline && prop === 'padding') {
if (style.paddingInline == null) {
resolvedStyle.paddingLeft = _value;
resolvedStyle.paddingRight = _value;
}
if (style.paddingBlock == null) {
resolvedStyle.paddingTop = _value;
resolvedStyle.paddingBottom = _value;
}
} else if (longFormProperties) {
longFormProperties.forEach((longForm, i) => {
// The value of any longform property in the original styles takes
// precedence over the shortform's value.
if (style[longForm] == null) {
resolvedStyle[longForm] = _value;
}
});
} else {
resolvedStyle[prop] = _value;
}
}
};
for (var prop in style) {
var _ret = _loop();
if (_ret === "continue") continue;
}
return resolvedStyle;
};
var _default = createReactDOMStyle;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/StyleSheet/compiler/hash.js
"use strict"; exports.__esModule = true; exports.default = void 0; /* eslint-disable */ /** * JS Implementation of MurmurHash2 * * @author <a href="mailto:[email protected]">Gary Court</a> * @see http://github.com/garycourt/murmurhash-js * @author <a href="mailto:[email protected]">Austin Appleby</a> * @see http://sites.google.com/site/murmurhash/ * * @param {string} str ASCII only * @param {number} seed Positive integer only * @return {number} 32-bit positive integer hash * * */ function murmurhash2_32_gc(str, seed) { var l = str.length, h = seed ^ l, i = 0, k; while (l >= 4) { k = str.charCodeAt(i) & 0xff | (str.charCodeAt(++i) & 0xff) << 8 | (str.charCodeAt(++i) & 0xff) << 16 | (str.charCodeAt(++i) & 0xff) << 24; k = (k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0x5bd1e995 & 0xffff) << 16); k ^= k >>> 24; k = (k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0x5bd1e995 & 0xffff) << 16); h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16) ^ k; l -= 4; ++i; } switch (l) { case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16; case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8; case 1: h ^= str.charCodeAt(i) & 0xff; h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16); } h ^= h >>> 13; h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16); h ^= h >>> 15; return h >>> 0; } var hash = str => murmurhash2_32_gc(str, 1).toString(36); var _default = hash; exports.default = _default; module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/StyleSheet/compiler/hyphenateStyleName.js
"use strict";
exports.__esModule = true;
exports.default = void 0;
/**
* 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.
*
*
*/
var uppercasePattern = /[A-Z]/g;
var msPattern = /^ms-/;
var cache = {};
function toHyphenLower(match) {
return '-' + match.toLowerCase();
}
function hyphenateStyleName(name) {
if (name in cache) {
return cache[name];
}
var hName = name.replace(uppercasePattern, toHyphenLower);
return cache[name] = msPattern.test(hName) ? '-' + hName : hName;
}
var _default = hyphenateStyleName;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/StyleSheet/compiler/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.atomic = atomic;
exports.classic = classic;
exports.inline = inline;
exports.stringifyValueWithProperty = stringifyValueWithProperty;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var _createReactDOMStyle = _interopRequireDefault(require("./createReactDOMStyle"));
var _hash = _interopRequireDefault(require("./hash"));
var _hyphenateStyleName = _interopRequireDefault(require("./hyphenateStyleName"));
var _normalizeValueWithProperty = _interopRequireDefault(require("./normalizeValueWithProperty"));
var _prefixStyles = _interopRequireDefault(require("../../../modules/prefixStyles"));
var _excluded = ["animationKeyframes"];
var cache = new Map();
var emptyObject = {};
var classicGroup = 1;
var atomicGroup = 3;
var customGroup = {
borderColor: 2,
borderRadius: 2,
borderStyle: 2,
borderWidth: 2,
display: 2,
flex: 2,
inset: 2,
margin: 2,
overflow: 2,
overscrollBehavior: 2,
padding: 2,
insetBlock: 2.1,
insetInline: 2.1,
marginInline: 2.1,
marginBlock: 2.1,
paddingInline: 2.1,
paddingBlock: 2.1,
borderBlockStartColor: 2.2,
borderBlockStartStyle: 2.2,
borderBlockStartWidth: 2.2,
borderBlockEndColor: 2.2,
borderBlockEndStyle: 2.2,
borderBlockEndWidth: 2.2,
borderInlineStartColor: 2.2,
borderInlineStartStyle: 2.2,
borderInlineStartWidth: 2.2,
borderInlineEndColor: 2.2,
borderInlineEndStyle: 2.2,
borderInlineEndWidth: 2.2,
borderEndStartRadius: 2.2,
borderEndEndRadius: 2.2,
borderStartStartRadius: 2.2,
borderStartEndRadius: 2.2,
insetBlockEnd: 2.2,
insetBlockStart: 2.2,
insetInlineEnd: 2.2,
insetInlineStart: 2.2,
marginBlockStart: 2.2,
marginBlockEnd: 2.2,
marginInlineStart: 2.2,
marginInlineEnd: 2.2,
paddingBlockStart: 2.2,
paddingBlockEnd: 2.2,
paddingInlineStart: 2.2,
paddingInlineEnd: 2.2
};
var borderTopLeftRadius = 'borderTopLeftRadius';
var borderTopRightRadius = 'borderTopRightRadius';
var borderBottomLeftRadius = 'borderBottomLeftRadius';
var borderBottomRightRadius = 'borderBottomRightRadius';
var borderLeftColor = 'borderLeftColor';
var borderLeftStyle = 'borderLeftStyle';
var borderLeftWidth = 'borderLeftWidth';
var borderRightColor = 'borderRightColor';
var borderRightStyle = 'borderRightStyle';
var borderRightWidth = 'borderRightWidth';
var right = 'right';
var marginLeft = 'marginLeft';
var marginRight = 'marginRight';
var paddingLeft = 'paddingLeft';
var paddingRight = 'paddingRight';
var left = 'left';
// Map of LTR property names to their BiDi equivalent.
var PROPERTIES_FLIP = {
[borderTopLeftRadius]: borderTopRightRadius,
[borderTopRightRadius]: borderTopLeftRadius,
[borderBottomLeftRadius]: borderBottomRightRadius,
[borderBottomRightRadius]: borderBottomLeftRadius,
[borderLeftColor]: borderRightColor,
[borderLeftStyle]: borderRightStyle,
[borderLeftWidth]: borderRightWidth,
[borderRightColor]: borderLeftColor,
[borderRightStyle]: borderLeftStyle,
[borderRightWidth]: borderLeftWidth,
[left]: right,
[marginLeft]: marginRight,
[marginRight]: marginLeft,
[paddingLeft]: paddingRight,
[paddingRight]: paddingLeft,
[right]: left
};
// Map of I18N property names to their LTR equivalent.
var PROPERTIES_I18N = {
borderStartStartRadius: borderTopLeftRadius,
borderStartEndRadius: borderTopRightRadius,
borderEndStartRadius: borderBottomLeftRadius,
borderEndEndRadius: borderBottomRightRadius,
borderInlineStartColor: borderLeftColor,
borderInlineStartStyle: borderLeftStyle,
borderInlineStartWidth: borderLeftWidth,
borderInlineEndColor: borderRightColor,
borderInlineEndStyle: borderRightStyle,
borderInlineEndWidth: borderRightWidth,
insetInlineEnd: right,
insetInlineStart: left,
marginInlineStart: marginLeft,
marginInlineEnd: marginRight,
paddingInlineStart: paddingLeft,
paddingInlineEnd: paddingRight
};
var PROPERTIES_VALUE = ['clear', 'float', 'textAlign'];
function atomic(style) {
var compiledStyle = {
$$css: true
};
var compiledRules = [];
function atomicCompile(srcProp, prop, value) {
var valueString = stringifyValueWithProperty(value, prop);
var cacheKey = prop + valueString;
var cachedResult = cache.get(cacheKey);
var identifier;
if (cachedResult != null) {
identifier = cachedResult[0];
compiledRules.push(cachedResult[1]);
} else {
var v = srcProp !== prop ? cacheKey : valueString;
identifier = createIdentifier('r', srcProp, v);
var order = customGroup[srcProp] || atomicGroup;
var rules = createAtomicRules(identifier, prop, value);
var orderedRules = [rules, order];
compiledRules.push(orderedRules);
cache.set(cacheKey, [identifier, orderedRules]);
}
return identifier;
}
Object.keys(style).sort().forEach(srcProp => {
var value = style[srcProp];
if (value != null) {
var localizeableValue;
// BiDi flip values
if (PROPERTIES_VALUE.indexOf(srcProp) > -1) {
var _left = atomicCompile(srcProp, srcProp, 'left');
var _right = atomicCompile(srcProp, srcProp, 'right');
if (value === 'start') {
localizeableValue = [_left, _right];
} else if (value === 'end') {
localizeableValue = [_right, _left];
}
}
// BiDi flip properties
var propPolyfill = PROPERTIES_I18N[srcProp];
if (propPolyfill != null) {
var ltr = atomicCompile(srcProp, propPolyfill, value);
var rtl = atomicCompile(srcProp, PROPERTIES_FLIP[propPolyfill], value);
localizeableValue = [ltr, rtl];
}
// BiDi flip transitionProperty value
if (srcProp === 'transitionProperty') {
var values = Array.isArray(value) ? value : [value];
var polyfillIndices = [];
for (var i = 0; i < values.length; i++) {
var val = values[i];
if (typeof val === 'string' && PROPERTIES_I18N[val] != null) {
polyfillIndices.push(i);
}
}
if (polyfillIndices.length > 0) {
var ltrPolyfillValues = [...values];
var rtlPolyfillValues = [...values];
polyfillIndices.forEach(i => {
var ltrVal = ltrPolyfillValues[i];
if (typeof ltrVal === 'string') {
var ltrPolyfill = PROPERTIES_I18N[ltrVal];
var rtlPolyfill = PROPERTIES_FLIP[ltrPolyfill];
ltrPolyfillValues[i] = ltrPolyfill;
rtlPolyfillValues[i] = rtlPolyfill;
var _ltr = atomicCompile(srcProp, srcProp, ltrPolyfillValues);
var _rtl = atomicCompile(srcProp, srcProp, rtlPolyfillValues);
localizeableValue = [_ltr, _rtl];
}
});
}
}
if (localizeableValue == null) {
localizeableValue = atomicCompile(srcProp, srcProp, value);
} else {
compiledStyle['$$css$localize'] = true;
}
compiledStyle[srcProp] = localizeableValue;
}
});
return [compiledStyle, compiledRules];
}
/**
* Compile simple style object to classic CSS rules.
* No support for 'placeholderTextColor', 'scrollbarWidth', or 'pointerEvents'.
*/
function classic(style, name) {
var compiledStyle = {
$$css: true
};
var compiledRules = [];
var animationKeyframes = style.animationKeyframes,
rest = (0, _objectWithoutPropertiesLoose2.default)(style, _excluded);
var identifier = createIdentifier('css', name, JSON.stringify(style));
var selector = "." + identifier;
var animationName;
if (animationKeyframes != null) {
var _processKeyframesValu = processKeyframesValue(animationKeyframes),
animationNames = _processKeyframesValu[0],
keyframesRules = _processKeyframesValu[1];
animationName = animationNames.join(',');
compiledRules.push(...keyframesRules);
}
var block = createDeclarationBlock((0, _objectSpread2.default)((0, _objectSpread2.default)({}, rest), {}, {
animationName
}));
compiledRules.push("" + selector + block);
compiledStyle[identifier] = identifier;
return [compiledStyle, [[compiledRules, classicGroup]]];
}
/**
* Compile simple style object to inline DOM styles.
* No support for 'animationKeyframes', 'placeholderTextColor', 'scrollbarWidth', or 'pointerEvents'.
*/
function inline(originalStyle, isRTL) {
var style = originalStyle || emptyObject;
var frozenProps = {};
var nextStyle = {};
var _loop = function _loop() {
var originalValue = style[originalProp];
var prop = originalProp;
var value = originalValue;
if (!Object.prototype.hasOwnProperty.call(style, originalProp) || originalValue == null) {
return "continue";
}
// BiDi flip values
if (PROPERTIES_VALUE.indexOf(originalProp) > -1) {
if (originalValue === 'start') {
value = isRTL ? 'right' : 'left';
} else if (originalValue === 'end') {
value = isRTL ? 'left' : 'right';
}
}
// BiDi flip properties
var propPolyfill = PROPERTIES_I18N[originalProp];
if (propPolyfill != null) {
prop = isRTL ? PROPERTIES_FLIP[propPolyfill] : propPolyfill;
}
// BiDi flip transitionProperty value
if (originalProp === 'transitionProperty') {
// $FlowFixMe
var originalValues = Array.isArray(originalValue) ? originalValue : [originalValue];
originalValues.forEach((val, i) => {
if (typeof val === 'string') {
var valuePolyfill = PROPERTIES_I18N[val];
if (valuePolyfill != null) {
originalValues[i] = isRTL ? PROPERTIES_FLIP[valuePolyfill] : valuePolyfill;
value = originalValues.join(' ');
}
}
});
}
// Create finalized style
if (!frozenProps[prop]) {
nextStyle[prop] = value;
}
if (prop === originalProp) {
frozenProps[prop] = true;
}
// if (PROPERTIES_I18N.hasOwnProperty(originalProp)) {
// frozenProps[prop] = true;
//}
};
for (var originalProp in style) {
var _ret = _loop();
if (_ret === "continue") continue;
}
return (0, _createReactDOMStyle.default)(nextStyle, true);
}
/**
* Create a value string that normalizes different input values with a common
* output.
*/
function stringifyValueWithProperty(value, property) {
// e.g., 0 => '0px', 'black' => 'rgba(0,0,0,1)'
var normalizedValue = (0, _normalizeValueWithProperty.default)(value, property);
return typeof normalizedValue !== 'string' ? JSON.stringify(normalizedValue || '') : normalizedValue;
}
/**
* Create the Atomic CSS rules needed for a given StyleSheet rule.
* Translates StyleSheet declarations to CSS.
*/
function createAtomicRules(identifier, property, value) {
var rules = [];
var selector = "." + identifier;
// Handle non-standard properties and object values that require multiple
// CSS rules to be created.
switch (property) {
case 'animationKeyframes':
{
var _processKeyframesValu2 = processKeyframesValue(value),
animationNames = _processKeyframesValu2[0],
keyframesRules = _processKeyframesValu2[1];
var block = createDeclarationBlock({
animationName: animationNames.join(',')
});
rules.push("" + selector + block, ...keyframesRules);
break;
}
// Equivalent to using '::placeholder'
case 'placeholderTextColor':
{
var _block = createDeclarationBlock({
color: value,
opacity: 1
});
rules.push(selector + "::-webkit-input-placeholder" + _block, selector + "::-moz-placeholder" + _block, selector + ":-ms-input-placeholder" + _block, selector + "::placeholder" + _block);
break;
}
// Polyfill for additional 'pointer-events' values
// See d13f78622b233a0afc0c7a200c0a0792c8ca9e58
case 'pointerEvents':
{
var finalValue = value;
if (value === 'auto' || value === 'box-only') {
finalValue = 'auto!important';
if (value === 'box-only') {
var _block2 = createDeclarationBlock({
pointerEvents: 'none'
});
rules.push(selector + ">*" + _block2);
}
} else if (value === 'none' || value === 'box-none') {
finalValue = 'none!important';
if (value === 'box-none') {
var _block3 = createDeclarationBlock({
pointerEvents: 'auto'
});
rules.push(selector + ">*" + _block3);
}
}
var _block4 = createDeclarationBlock({
pointerEvents: finalValue
});
rules.push("" + selector + _block4);
break;
}
// Polyfill for draft spec
// https://drafts.csswg.org/css-scrollbars-1/
case 'scrollbarWidth':
{
if (value === 'none') {
rules.push(selector + "::-webkit-scrollbar{display:none}");
}
var _block5 = createDeclarationBlock({
scrollbarWidth: value
});
rules.push("" + selector + _block5);
break;
}
default:
{
var _block6 = createDeclarationBlock({
[property]: value
});
rules.push("" + selector + _block6);
break;
}
}
return rules;
}
/**
* Creates a CSS declaration block from a StyleSheet object.
*/
function createDeclarationBlock(style) {
var domStyle = (0, _prefixStyles.default)((0, _createReactDOMStyle.default)(style));
var declarationsString = Object.keys(domStyle).map(property => {
var value = domStyle[property];
var prop = (0, _hyphenateStyleName.default)(property);
// The prefixer may return an array of values:
// { display: [ '-webkit-flex', 'flex' ] }
// to represent "fallback" declarations
// { display: -webkit-flex; display: flex; }
if (Array.isArray(value)) {
return value.map(v => prop + ":" + v).join(';');
} else {
return prop + ":" + value;
}
})
// Once properties are hyphenated, this will put the vendor
// prefixed and short-form properties first in the list.
.sort().join(';');
return "{" + declarationsString + ";}";
}
/**
* An identifier is associated with a unique set of styles.
*/
function createIdentifier(prefix, name, key) {
var hashedString = (0, _hash.default)(name + key);
return process.env.NODE_ENV !== 'production' ? prefix + "-" + name + "-" + hashedString : prefix + "-" + hashedString;
}
/**
* Create individual CSS keyframes rules.
*/
function createKeyframes(keyframes) {
var prefixes = ['-webkit-', ''];
var identifier = createIdentifier('r', 'animation', JSON.stringify(keyframes));
var steps = '{' + Object.keys(keyframes).map(stepName => {
var rule = keyframes[stepName];
var block = createDeclarationBlock(rule);
return "" + stepName + block;
}).join('') + '}';
var rules = prefixes.map(prefix => {
return "@" + prefix + "keyframes " + identifier + steps;
});
return [identifier, rules];
}
/**
* Create CSS keyframes rules and names from a StyleSheet keyframes object.
*/
function processKeyframesValue(keyframesValue) {
if (typeof keyframesValue === 'number') {
throw new Error("Invalid CSS keyframes type: " + typeof keyframesValue);
}
var animationNames = [];
var rules = [];
var value = Array.isArray(keyframesValue) ? keyframesValue : [keyframesValue];
value.forEach(keyframes => {
if (typeof keyframes === 'string') {
// Support external animation libraries (identifiers only)
animationNames.push(keyframes);
} else {
// Create rules for each of the keyframes
var _createKeyframes = createKeyframes(keyframes),
identifier = _createKeyframes[0],
keyframesRules = _createKeyframes[1];
animationNames.push(identifier);
rules.push(...keyframesRules);
}
});
return [animationNames, rules];
}
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/StyleSheet/compiler/normalizeColor.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _isWebColor = _interopRequireDefault(require("../../../modules/isWebColor"));
var _processColor = _interopRequireDefault(require("../../../exports/processColor"));
/**
* 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.
*
*
*/
var normalizeColor = function normalizeColor(color, opacity) {
if (opacity === void 0) {
opacity = 1;
}
if (color == null) return;
if (typeof color === 'string' && (0, _isWebColor.default)(color)) {
return color;
}
var colorInt = (0, _processColor.default)(color);
if (colorInt != null) {
var r = colorInt >> 16 & 255;
var g = colorInt >> 8 & 255;
var b = colorInt & 255;
var a = (colorInt >> 24 & 255) / 255;
var alpha = (a * opacity).toFixed(2);
return "rgba(" + r + "," + g + "," + b + "," + alpha + ")";
}
};
var _default = normalizeColor;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/StyleSheet/compiler/normalizeValueWithProperty.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = normalizeValueWithProperty;
var _unitlessNumbers = _interopRequireDefault(require("./unitlessNumbers"));
var _normalizeColor = _interopRequireDefault(require("./normalizeColor"));
/**
* 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.
*
*
*/
var colorProps = {
backgroundColor: true,
borderColor: true,
borderTopColor: true,
borderRightColor: true,
borderBottomColor: true,
borderLeftColor: true,
color: true,
shadowColor: true,
textDecorationColor: true,
textShadowColor: true
};
function normalizeValueWithProperty(value, property) {
var returnValue = value;
if ((property == null || !_unitlessNumbers.default[property]) && typeof value === 'number') {
returnValue = value + "px";
} else if (property != null && colorProps[property]) {
returnValue = (0, _normalizeColor.default)(value);
}
return returnValue;
}
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/StyleSheet/compiler/unitlessNumbers.js
"use strict";
exports.__esModule = true;
exports.default = void 0;
/**
* 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.
*
*
*/
var unitlessNumbers = {
animationIterationCount: true,
aspectRatio: true,
borderImageOutset: true,
borderImageSlice: true,
borderImageWidth: true,
boxFlex: true,
boxFlexGroup: true,
boxOrdinalGroup: true,
columnCount: true,
flex: true,
flexGrow: true,
flexOrder: true,
flexPositive: true,
flexShrink: true,
flexNegative: true,
fontWeight: true,
gridRow: true,
gridRowEnd: true,
gridRowGap: true,
gridRowStart: true,
gridColumn: true,
gridColumnEnd: true,
gridColumnGap: true,
gridColumnStart: true,
lineClamp: true,
opacity: true,
order: true,
orphans: true,
tabSize: true,
widows: true,
zIndex: true,
zoom: true,
// SVG-related
fillOpacity: true,
floodOpacity: true,
stopOpacity: true,
strokeDasharray: true,
strokeDashoffset: true,
strokeMiterlimit: true,
strokeOpacity: true,
strokeWidth: true,
// transform types
scale: true,
scaleX: true,
scaleY: true,
scaleZ: true,
// RN properties
shadowOpacity: true
};
/**
* Support style names that may come passed in prefixed by adding permutations
* of vendor prefixes.
*/
var prefixes = ['ms', 'Moz', 'O', 'Webkit'];
var prefixKey = (prefix, key) => {
return prefix + key.charAt(0).toUpperCase() + key.substring(1);
};
Object.keys(unitlessNumbers).forEach(prop => {
prefixes.forEach(prefix => {
unitlessNumbers[prefixKey(prefix, prop)] = unitlessNumbers[prop];
});
});
var _default = unitlessNumbers;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/StyleSheet/dom/createCSSStyleSheet.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = createCSSStyleSheet;
var _canUseDom = _interopRequireDefault(require("../../../modules/canUseDom"));
/**
* 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.
*
*
*/
// $FlowFixMe: HTMLStyleElement is incorrectly typed - https://github.com/facebook/flow/issues/2696
function createCSSStyleSheet(id, rootNode, textContent) {
if (_canUseDom.default) {
var root = rootNode != null ? rootNode : document;
var element = root.getElementById(id);
if (element == null) {
element = document.createElement('style');
element.setAttribute('id', id);
if (typeof textContent === 'string') {
element.appendChild(document.createTextNode(textContent));
}
if (root instanceof ShadowRoot) {
root.insertBefore(element, root.firstChild);
} else {
var head = root.head;
if (head) {
head.insertBefore(element, head.firstChild);
}
}
}
// $FlowFixMe: HTMLElement is incorrectly typed
return element.sheet;
} else {
return null;
}
}
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/StyleSheet/dom/createOrderedCSSStyleSheet.js
"use strict";
exports.__esModule = true;
exports.default = createOrderedCSSStyleSheet;
/**
* 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.
*
*
*/
var slice = Array.prototype.slice;
/**
* Order-based insertion of CSS.
*
* Each rule is associated with a numerically defined group.
* Groups are ordered within the style sheet according to their number, with the
* lowest first.
*
* Groups are implemented using marker rules. The selector of the first rule of
* each group is used only to encode the group number for hydration. An
* alternative implementation could rely on CSSMediaRule, allowing groups to be
* treated as a sub-sheet, but the Edge implementation of CSSMediaRule is
* broken.
* https://developer.mozilla.org/en-US/docs/Web/API/CSSMediaRule
* https://gist.github.com/necolas/aa0c37846ad6bd3b05b727b959e82674
*/
function createOrderedCSSStyleSheet(sheet) {
var groups = {};
var selectors = {};
/**
* Hydrate approximate record from any existing rules in the sheet.
*/
if (sheet != null) {
var group;
slice.call(sheet.cssRules).forEach((cssRule, i) => {
var cssText = cssRule.cssText;
// Create record of existing selectors and rules
if (cssText.indexOf('stylesheet-group') > -1) {
group = decodeGroupRule(cssRule);
groups[group] = {
start: i,
rules: [cssText]
};
} else {
var selectorText = getSelectorText(cssText);
if (selectorText != null) {
selectors[selectorText] = true;
groups[group].rules.push(cssText);
}
}
});
}
function sheetInsert(sheet, group, text) {
var orderedGroups = getOrderedGroups(groups);
var groupIndex = orderedGroups.indexOf(group);
var nextGroupIndex = groupIndex + 1;
var nextGroup = orderedGroups[nextGroupIndex];
// Insert rule before the next group, or at the end of the stylesheet
var position = nextGroup != null && groups[nextGroup].start != null ? groups[nextGroup].start : sheet.cssRules.length;
var isInserted = insertRuleAt(sheet, text, position);
if (isInserted) {
// Set the starting index of the new group
if (groups[group].start == null) {
groups[group].start = position;
}
// Increment the starting index of all subsequent groups
for (var i = nextGroupIndex; i < orderedGroups.length; i += 1) {
var groupNumber = orderedGroups[i];
var previousStart = groups[groupNumber].start || 0;
groups[groupNumber].start = previousStart + 1;
}
}
return isInserted;
}
var OrderedCSSStyleSheet = {
/**
* The textContent of the style sheet.
*/
getTextContent() {
return getOrderedGroups(groups).map(group => {
var rules = groups[group].rules;
// Sorting provides deterministic order of styles in group for
// build-time extraction of the style sheet.
var marker = rules.shift();
rules.sort();
rules.unshift(marker);
return rules.join('\n');
}).join('\n');
},
/**
* Insert a rule into the style sheet
*/
insert(cssText, groupValue) {
var group = Number(groupValue);
// Create a new group.
if (groups[group] == null) {
var markerRule = encodeGroupRule(group);
// Create the internal record.
groups[group] = {
start: null,
rules: [markerRule]
};
// Update CSSOM.
if (sheet != null) {
sheetInsert(sheet, group, markerRule);
}
}
// selectorText is more reliable than cssText for insertion checks. The
// browser excludes vendor-prefixed properties and rewrites certain values
// making cssText more likely to be different from what was inserted.
var selectorText = getSelectorText(cssText);
if (selectorText != null && selectors[selectorText] == null) {
// Update the internal records.
selectors[selectorText] = true;
groups[group].rules.push(cssText);
// Update CSSOM.
if (sheet != null) {
var isInserted = sheetInsert(sheet, group, cssText);
if (!isInserted) {
// Revert internal record change if a rule was rejected (e.g.,
// unrecognized pseudo-selector)
groups[group].rules.pop();
}
}
}
}
};
return OrderedCSSStyleSheet;
}
/**
* Helper functions
*/
function encodeGroupRule(group) {
return "[stylesheet-group=\"" + group + "\"]{}";
}
var groupPattern = /["']/g;
function decodeGroupRule(cssRule) {
return Number(cssRule.selectorText.split(groupPattern)[1]);
}
function getOrderedGroups(obj) {
return Object.keys(obj).map(Number).sort((a, b) => a > b ? 1 : -1);
}
var selectorPattern = /\s*([,])\s*/g;
function getSelectorText(cssText) {
var selector = cssText.split('{')[0].trim();
return selector !== '' ? selector.replace(selectorPattern, '$1') : null;
}
function insertRuleAt(root, cssText, position) {
try {
// $FlowFixMe: Flow is missing CSSOM types needed to type 'root'.
root.insertRule(cssText, position);
return true;
} catch (e) {
// JSDOM doesn't support `CSSSMediaRule#insertRule`.
// Also ignore errors that occur from attempting to insert vendor-prefixed selectors.
return false;
}
}
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/StyleSheet/dom/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.createSheet = createSheet;
var _canUseDom = _interopRequireDefault(require("../../../modules/canUseDom"));
var _createCSSStyleSheet = _interopRequireDefault(require("./createCSSStyleSheet"));
var _createOrderedCSSStyleSheet = _interopRequireDefault(require("./createOrderedCSSStyleSheet"));
/**
* 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.
*
*
*/
var defaultId = 'react-native-stylesheet';
var roots = new WeakMap();
var sheets = [];
var initialRules = [
// minimal top-level reset
'html{-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:rgba(0,0,0,0);}', 'body{margin:0;}',
// minimal form pseudo-element reset
'button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0;}', 'input::-webkit-search-cancel-button,input::-webkit-search-decoration,input::-webkit-search-results-button,input::-webkit-search-results-decoration{display:none;}'];
function createSheet(root, id) {
if (id === void 0) {
id = defaultId;
}
var sheet;
if (_canUseDom.default) {
var rootNode = root != null ? root.getRootNode() : document;
// Create the initial style sheet
if (sheets.length === 0) {
sheet = (0, _createOrderedCSSStyleSheet.default)((0, _createCSSStyleSheet.default)(id));
initialRules.forEach(rule => {
sheet.insert(rule, 0);
});
roots.set(rootNode, sheets.length);
sheets.push(sheet);
} else {
var index = roots.get(rootNode);
if (index == null) {
var initialSheet = sheets[0];
// If we're creating a new sheet, populate it with existing styles
var textContent = initialSheet != null ? initialSheet.getTextContent() : '';
// Cast rootNode to 'any' because Flow types for getRootNode are wrong
sheet = (0, _createOrderedCSSStyleSheet.default)((0, _createCSSStyleSheet.default)(id, rootNode, textContent));
roots.set(rootNode, sheets.length);
sheets.push(sheet);
} else {
sheet = sheets[index];
}
}
} else {
// Create the initial style sheet
if (sheets.length === 0) {
sheet = (0, _createOrderedCSSStyleSheet.default)((0, _createCSSStyleSheet.default)(id));
initialRules.forEach(rule => {
sheet.insert(rule, 0);
});
sheets.push(sheet);
} else {
sheet = sheets[0];
}
}
return {
getTextContent() {
return sheet.getTextContent();
},
id,
insert(cssText, groupValue) {
sheets.forEach(s => {
s.insert(cssText, groupValue);
});
}
};
}
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/StyleSheet/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var _compiler = require("./compiler");
var _dom = require("./dom");
var _transformLocalizeStyle = require("styleq/transform-localize-style");
var _preprocess = require("./preprocess");
var _styleq = require("styleq");
var _validate = require("./validate");
var _canUseDom = _interopRequireDefault(require("../../modules/canUseDom"));
var _excluded = ["writingDirection"];
var staticStyleMap = new WeakMap();
var sheet = (0, _dom.createSheet)();
var defaultPreprocessOptions = {
shadow: true,
textShadow: true
};
function customStyleq(styles, options) {
if (options === void 0) {
options = {};
}
var _options = options,
writingDirection = _options.writingDirection,
preprocessOptions = (0, _objectWithoutPropertiesLoose2.default)(_options, _excluded);
var isRTL = writingDirection === 'rtl';
return _styleq.styleq.factory({
transform(style) {
var compiledStyle = staticStyleMap.get(style);
if (compiledStyle != null) {
return (0, _transformLocalizeStyle.localizeStyle)(compiledStyle, isRTL);
}
return (0, _preprocess.preprocess)(style, (0, _objectSpread2.default)((0, _objectSpread2.default)({}, defaultPreprocessOptions), preprocessOptions));
}
})(styles);
}
function insertRules(compiledOrderedRules) {
compiledOrderedRules.forEach(_ref => {
var rules = _ref[0],
order = _ref[1];
if (sheet != null) {
rules.forEach(rule => {
sheet.insert(rule, order);
});
}
});
}
function compileAndInsertAtomic(style) {
var _atomic = (0, _compiler.atomic)((0, _preprocess.preprocess)(style, defaultPreprocessOptions)),
compiledStyle = _atomic[0],
compiledOrderedRules = _atomic[1];
insertRules(compiledOrderedRules);
return compiledStyle;
}
function compileAndInsertReset(style, key) {
var _classic = (0, _compiler.classic)(style, key),
compiledStyle = _classic[0],
compiledOrderedRules = _classic[1];
insertRules(compiledOrderedRules);
return compiledStyle;
}
/* ----- API ----- */
var absoluteFillObject = {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0
};
var absoluteFill = create({
x: (0, _objectSpread2.default)({}, absoluteFillObject)
}).x;
/**
* create
*/
function create(styles) {
Object.keys(styles).forEach(key => {
var styleObj = styles[key];
// Only compile at runtime if the style is not already compiled
if (styleObj != null && styleObj.$$css !== true) {
var compiledStyles;
if (key.indexOf('$raw') > -1) {
compiledStyles = compileAndInsertReset(styleObj, key.split('$raw')[0]);
} else {
if (process.env.NODE_ENV !== 'production') {
(0, _validate.validate)(styleObj);
styles[key] = Object.freeze(styleObj);
}
compiledStyles = compileAndInsertAtomic(styleObj);
}
staticStyleMap.set(styleObj, compiledStyles);
}
});
return styles;
}
/**
* compose
*/
function compose(style1, style2) {
if (process.env.NODE_ENV !== 'production') {
/* eslint-disable prefer-rest-params */
var len = arguments.length;
if (len > 2) {
var readableStyles = [...arguments].map(a => flatten(a));
throw new Error("StyleSheet.compose() only accepts 2 arguments, received " + len + ": " + JSON.stringify(readableStyles));
}
/* eslint-enable prefer-rest-params */
console.warn('StyleSheet.compose(a, b) is deprecated; use array syntax, i.e., [a,b].');
}
return [style1, style2];
}
/**
* flatten
*/
function flatten() {
for (var _len = arguments.length, styles = new Array(_len), _key = 0; _key < _len; _key++) {
styles[_key] = arguments[_key];
}
var flatArray = styles.flat(Infinity);
var result = {};
for (var i = 0; i < flatArray.length; i++) {
var style = flatArray[i];
if (style != null && typeof style === 'object') {
// $FlowFixMe
Object.assign(result, style);
}
}
return result;
}
/**
* getSheet
*/
function getSheet() {
return {
id: sheet.id,
textContent: sheet.getTextContent()
};
}
/**
* resolve
*/
function StyleSheet(styles, options) {
if (options === void 0) {
options = {};
}
var isRTL = options.writingDirection === 'rtl';
var styleProps = customStyleq(styles, options);
if (Array.isArray(styleProps) && styleProps[1] != null) {
styleProps[1] = (0, _compiler.inline)(styleProps[1], isRTL);
}
return styleProps;
}
StyleSheet.absoluteFill = absoluteFill;
StyleSheet.absoluteFillObject = absoluteFillObject;
StyleSheet.create = create;
StyleSheet.compose = compose;
StyleSheet.flatten = flatten;
StyleSheet.getSheet = getSheet;
// `hairlineWidth` is not implemented using screen density as browsers may
// round sub-pixel values down to `0`, causing the line not to be rendered.
StyleSheet.hairlineWidth = 1;
if (_canUseDom.default && window.__REACT_DEVTOOLS_GLOBAL_HOOK__) {
window.__REACT_DEVTOOLS_GLOBAL_HOOK__.resolveRNStyle = StyleSheet.flatten;
}
var stylesheet = StyleSheet;
var _default = stylesheet;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/StyleSheet/preprocess.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.preprocess = exports.default = exports.createTransformValue = exports.createTextShadowValue = exports.createBoxShadowValue = void 0;
var _normalizeColor = _interopRequireDefault(require("./compiler/normalizeColor"));
var _normalizeValueWithProperty = _interopRequireDefault(require("./compiler/normalizeValueWithProperty"));
var _warnOnce = require("../../modules/warnOnce");
/**
* 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.
*
*
*/
var emptyObject = {};
/**
* Shadows
*/
var defaultOffset = {
height: 0,
width: 0
};
var createBoxShadowValue = style => {
var shadowColor = style.shadowColor,
shadowOffset = style.shadowOffset,
shadowOpacity = style.shadowOpacity,
shadowRadius = style.shadowRadius;
var _ref = shadowOffset || defaultOffset,
height = _ref.height,
width = _ref.width;
var offsetX = (0, _normalizeValueWithProperty.default)(width);
var offsetY = (0, _normalizeValueWithProperty.default)(height);
var blurRadius = (0, _normalizeValueWithProperty.default)(shadowRadius || 0);
var color = (0, _normalizeColor.default)(shadowColor || 'black', shadowOpacity);
if (color != null && offsetX != null && offsetY != null && blurRadius != null) {
return offsetX + " " + offsetY + " " + blurRadius + " " + color;
}
};
exports.createBoxShadowValue = createBoxShadowValue;
var createTextShadowValue = style => {
var textShadowColor = style.textShadowColor,
textShadowOffset = style.textShadowOffset,
textShadowRadius = style.textShadowRadius;
var _ref2 = textShadowOffset || defaultOffset,
height = _ref2.height,
width = _ref2.width;
var radius = textShadowRadius || 0;
var offsetX = (0, _normalizeValueWithProperty.default)(width);
var offsetY = (0, _normalizeValueWithProperty.default)(height);
var blurRadius = (0, _normalizeValueWithProperty.default)(radius);
var color = (0, _normalizeValueWithProperty.default)(textShadowColor, 'textShadowColor');
if (color && (height !== 0 || width !== 0 || radius !== 0) && offsetX != null && offsetY != null && blurRadius != null) {
return offsetX + " " + offsetY + " " + blurRadius + " " + color;
}
};
// { scale: 2 } => 'scale(2)'
// { translateX: 20 } => 'translateX(20px)'
// { matrix: [1,2,3,4,5,6] } => 'matrix(1,2,3,4,5,6)'
exports.createTextShadowValue = createTextShadowValue;
var mapTransform = transform => {
var type = Object.keys(transform)[0];
var value = transform[type];
if (type === 'matrix' || type === 'matrix3d') {
return type + "(" + value.join(',') + ")";
} else {
var normalizedValue = (0, _normalizeValueWithProperty.default)(value, type);
return type + "(" + normalizedValue + ")";
}
};
var createTransformValue = value => {
return value.map(mapTransform).join(' ');
};
exports.createTransformValue = createTransformValue;
var PROPERTIES_STANDARD = {
borderBottomEndRadius: 'borderEndEndRadius',
borderBottomStartRadius: 'borderEndStartRadius',
borderTopEndRadius: 'borderStartEndRadius',
borderTopStartRadius: 'borderStartStartRadius',
borderEndColor: 'borderInlineEndColor',
borderEndStyle: 'borderInlineEndStyle',
borderEndWidth: 'borderInlineEndWidth',
borderStartColor: 'borderInlineStartColor',
borderStartStyle: 'borderInlineStartStyle',
borderStartWidth: 'borderInlineStartWidth',
end: 'insetInlineEnd',
marginEnd: 'marginInlineEnd',
marginHorizontal: 'marginInline',
marginStart: 'marginInlineStart',
marginVertical: 'marginBlock',
paddingEnd: 'paddingInlineEnd',
paddingHorizontal: 'paddingInline',
paddingStart: 'paddingInlineStart',
paddingVertical: 'paddingBlock',
start: 'insetInlineStart'
};
var ignoredProps = {
elevation: true,
overlayColor: true,
resizeMode: true,
tintColor: true
};
/**
* Preprocess styles
*/
var preprocess = function preprocess(originalStyle, options) {
if (options === void 0) {
options = {};
}
var style = originalStyle || emptyObject;
var nextStyle = {};
// Convert shadow styles
if (options.shadow === true, style.shadowColor != null || style.shadowOffset != null || style.shadowOpacity != null || style.shadowRadius != null) {
(0, _warnOnce.warnOnce)('shadowStyles', "\"shadow*\" style props are deprecated. Use \"boxShadow\".");
var boxShadowValue = createBoxShadowValue(style);
if (boxShadowValue != null && nextStyle.boxShadow == null) {
var boxShadow = style.boxShadow;
var value = boxShadow ? boxShadow + ", " + boxShadowValue : boxShadowValue;
nextStyle.boxShadow = value;
}
}
// Convert text shadow styles
if (options.textShadow === true, style.textShadowColor != null || style.textShadowOffset != null || style.textShadowRadius != null) {
(0, _warnOnce.warnOnce)('textShadowStyles', "\"textShadow*\" style props are deprecated. Use \"textShadow\".");
var textShadowValue = createTextShadowValue(style);
if (textShadowValue != null && nextStyle.textShadow == null) {
var textShadow = style.textShadow;
var _value = textShadow ? textShadow + ", " + textShadowValue : textShadowValue;
nextStyle.textShadow = _value;
}
}
for (var originalProp in style) {
if (
// Ignore some React Native styles
ignoredProps[originalProp] != null || originalProp === 'shadowColor' || originalProp === 'shadowOffset' || originalProp === 'shadowOpacity' || originalProp === 'shadowRadius' || originalProp === 'textShadowColor' || originalProp === 'textShadowOffset' || originalProp === 'textShadowRadius') {
continue;
}
var originalValue = style[originalProp];
var prop = PROPERTIES_STANDARD[originalProp] || originalProp;
var _value2 = originalValue;
if (!Object.prototype.hasOwnProperty.call(style, originalProp) || prop !== originalProp && style[prop] != null) {
continue;
}
if (prop === 'aspectRatio' && typeof _value2 === 'number') {
nextStyle[prop] = _value2.toString();
} else if (prop === 'fontVariant') {
if (Array.isArray(_value2) && _value2.length > 0) {
(0, _warnOnce.warnOnce)('fontVariant', '"fontVariant" style array value is deprecated. Use space-separated values.');
_value2 = _value2.join(' ');
}
nextStyle[prop] = _value2;
} else if (prop === 'textAlignVertical') {
(0, _warnOnce.warnOnce)('textAlignVertical', '"textAlignVertical" style is deprecated. Use "verticalAlign".');
if (style.verticalAlign == null) {
nextStyle.verticalAlign = _value2 === 'center' ? 'middle' : _value2;
}
} else if (prop === 'transform') {
if (Array.isArray(_value2)) {
_value2 = createTransformValue(_value2);
}
nextStyle.transform = _value2;
} else {
nextStyle[prop] = _value2;
}
}
// $FlowIgnore
return nextStyle;
};
exports.preprocess = preprocess;
var _default = preprocess;
exports.default = _default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/StyleSheet/validate.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.validate = validate;
var _postcssValueParser = _interopRequireDefault(require("postcss-value-parser"));
/**
* 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.
*
*
*/
var invalidShortforms = {
background: true,
borderBottom: true,
borderLeft: true,
borderRight: true,
borderTop: true,
font: true,
grid: true,
outline: true,
textDecoration: true
};
var invalidMultiValueShortforms = {
flex: true,
margin: true,
padding: true,
borderColor: true,
borderRadius: true,
borderStyle: true,
borderWidth: true,
inset: true,
insetBlock: true,
insetInline: true,
marginBlock: true,
marginInline: true,
marginHorizontal: true,
marginVertical: true,
paddingBlock: true,
paddingInline: true,
paddingHorizontal: true,
paddingVertical: true,
overflow: true,
overscrollBehavior: true,
backgroundPosition: true
};
function error(message) {
console.error(message);
}
function validate(obj) {
for (var k in obj) {
var prop = k.trim();
var value = obj[prop];
var isInvalid = false;
if (value === null) {
continue;
}
if (typeof value === 'string' && value.indexOf('!important') > -1) {
error("Invalid style declaration \"" + prop + ":" + value + "\". Values cannot include \"!important\"");
isInvalid = true;
} else {
var suggestion = '';
if (prop === 'animation' || prop === 'animationName') {
suggestion = 'Did you mean "animationKeyframes"?';
isInvalid = true;
} else if (prop === 'direction') {
suggestion = 'Did you mean "writingDirection"?';
isInvalid = true;
} else if (invalidShortforms[prop]) {
suggestion = 'Please use long-form properties.';
isInvalid = true;
} else if (invalidMultiValueShortforms[prop]) {
if (typeof value === 'string' && (0, _postcssValueParser.default)(value).nodes.length > 1) {
suggestion = "Value is \"" + value + "\" but only single values are supported.";
isInvalid = true;
}
}
if (suggestion !== '') {
error("Invalid style property of \"" + prop + "\". " + suggestion);
}
}
if (isInvalid) {
delete obj[k];
}
}
}
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Switch/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var React = _interopRequireWildcard(require("react"));
var _createElement = _interopRequireDefault(require("../createElement"));
var _multiplyStyleLengthValue = _interopRequireDefault(require("../../modules/multiplyStyleLengthValue"));
var _StyleSheet = _interopRequireDefault(require("../StyleSheet"));
var _View = _interopRequireDefault(require("../View"));
var _excluded = ["aria-label", "accessibilityLabel", "activeThumbColor", "activeTrackColor", "disabled", "onValueChange", "style", "thumbColor", "trackColor", "value"];
var emptyObject = {};
var thumbDefaultBoxShadow = '0px 1px 3px rgba(0,0,0,0.5)';
var thumbFocusedBoxShadow = thumbDefaultBoxShadow + ", 0 0 0 10px rgba(0,0,0,0.1)";
var defaultActiveTrackColor = '#A3D3CF';
var defaultTrackColor = '#939393';
var defaultDisabledTrackColor = '#D5D5D5';
var defaultActiveThumbColor = '#009688';
var defaultThumbColor = '#FAFAFA';
var defaultDisabledThumbColor = '#BDBDBD';
var Switch = /*#__PURE__*/React.forwardRef((props, forwardedRef) => {
var ariaLabel = props['aria-label'],
accessibilityLabel = props.accessibilityLabel,
activeThumbColor = props.activeThumbColor,
activeTrackColor = props.activeTrackColor,
_props$disabled = props.disabled,
disabled = _props$disabled === void 0 ? false : _props$disabled,
onValueChange = props.onValueChange,
_props$style = props.style,
style = _props$style === void 0 ? emptyObject : _props$style,
thumbColor = props.thumbColor,
trackColor = props.trackColor,
_props$value = props.value,
value = _props$value === void 0 ? false : _props$value,
other = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
var thumbRef = React.useRef(null);
function handleChange(event) {
if (onValueChange != null) {
onValueChange(event.nativeEvent.target.checked);
}
}
function handleFocusState(event) {
var isFocused = event.nativeEvent.type === 'focus';
var boxShadow = isFocused ? thumbFocusedBoxShadow : thumbDefaultBoxShadow;
if (thumbRef.current != null) {
thumbRef.current.style.boxShadow = boxShadow;
}
}
var _StyleSheet$flatten = _StyleSheet.default.flatten(style),
styleHeight = _StyleSheet$flatten.height,
styleWidth = _StyleSheet$flatten.width;
var height = styleHeight || '20px';
var minWidth = (0, _multiplyStyleLengthValue.default)(height, 2);
var width = styleWidth > minWidth ? styleWidth : minWidth;
var trackBorderRadius = (0, _multiplyStyleLengthValue.default)(height, 0.5);
var trackCurrentColor = function () {
if (value === true) {
if (trackColor != null && typeof trackColor === 'object') {
return trackColor.true;
} else {
return activeTrackColor !== null && activeTrackColor !== void 0 ? activeTrackColor : defaultActiveTrackColor;
}
} else {
if (trackColor != null && typeof trackColor === 'object') {
return trackColor.false;
} else {
return trackColor !== null && trackColor !== void 0 ? trackColor : defaultTrackColor;
}
}
}();
var thumbCurrentColor = value ? activeThumbColor !== null && activeThumbColor !== void 0 ? activeThumbColor : defaultActiveThumbColor : thumbColor !== null && thumbColor !== void 0 ? thumbColor : defaultThumbColor;
var thumbHeight = height;
var thumbWidth = thumbHeight;
var rootStyle = [styles.root, style, disabled && styles.cursorDefault, {
height,
width
}];
var disabledTrackColor = function () {
if (value === true) {
if (typeof activeTrackColor === 'string' && activeTrackColor != null || typeof trackColor === 'object' && trackColor != null && trackColor.true) {
return trackCurrentColor;
} else {
return defaultDisabledTrackColor;
}
} else {
if (typeof trackColor === 'string' && trackColor != null || typeof trackColor === 'object' && trackColor != null && trackColor.false) {
return trackCurrentColor;
} else {
return defaultDisabledTrackColor;
}
}
}();
var disabledThumbColor = function () {
if (value === true) {
if (activeThumbColor == null) {
return defaultDisabledThumbColor;
} else {
return thumbCurrentColor;
}
} else {
if (thumbColor == null) {
return defaultDisabledThumbColor;
} else {
return thumbCurrentColor;
}
}
}();
var trackStyle = [styles.track, {
backgroundColor: disabled ? disabledTrackColor : trackCurrentColor,
borderRadius: trackBorderRadius
}];
var thumbStyle = [styles.thumb, value && styles.thumbActive, {
backgroundColor: disabled ? disabledThumbColor : thumbCurrentColor,
height: thumbHeight,
marginStart: value ? (0, _multiplyStyleLengthValue.default)(thumbWidth, -1) : 0,
width: thumbWidth
}];
var nativeControl = (0, _createElement.default)('input', {
'aria-label': ariaLabel || accessibilityLabel,
checked: value,
disabled: disabled,
onBlur: handleFocusState,
onChange: handleChange,
onFocus: handleFocusState,
ref: forwardedRef,
style: [styles.nativeControl, styles.cursorInherit],
type: 'checkbox',
role: 'switch'
});
return /*#__PURE__*/React.createElement(_View.default, (0, _extends2.default)({}, other, {
style: rootStyle
}), /*#__PURE__*/React.createElement(_View.default, {
style: trackStyle
}), /*#__PURE__*/React.createElement(_View.default, {
ref: thumbRef,
style: thumbStyle
}), nativeControl);
});
Switch.displayName = 'Switch';
var styles = _StyleSheet.default.create({
root: {
cursor: 'pointer',
userSelect: 'none'
},
cursorDefault: {
cursor: 'default'
},
cursorInherit: {
cursor: 'inherit'
},
track: (0, _objectSpread2.default)((0, _objectSpread2.default)({
forcedColorAdjust: 'none'
}, _StyleSheet.default.absoluteFillObject), {}, {
height: '70%',
margin: 'auto',
transitionDuration: '0.1s',
width: '100%'
}),
thumb: {
forcedColorAdjust: 'none',
alignSelf: 'flex-start',
borderRadius: '100%',
boxShadow: thumbDefaultBoxShadow,
start: '0%',
transform: 'translateZ(0)',
transitionDuration: '0.1s'
},
thumbActive: {
insetInlineStart: '100%'
},
nativeControl: (0, _objectSpread2.default)((0, _objectSpread2.default)({}, _StyleSheet.default.absoluteFillObject), {}, {
height: '100%',
margin: 0,
appearance: 'none',
padding: 0,
width: '100%'
})
});
var _default = Switch;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Text/TextAncestorContext.js
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _react = require("react");
/**
* 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.
*
*
*/
var TextAncestorContext = /*#__PURE__*/(0, _react.createContext)(false);
var _default = TextAncestorContext;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Text/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var React = _interopRequireWildcard(require("react"));
var _createElement = _interopRequireDefault(require("../createElement"));
var forwardedProps = _interopRequireWildcard(require("../../modules/forwardedProps"));
var _pick = _interopRequireDefault(require("../../modules/pick"));
var _useElementLayout = _interopRequireDefault(require("../../modules/useElementLayout"));
var _useMergeRefs = _interopRequireDefault(require("../../modules/useMergeRefs"));
var _usePlatformMethods = _interopRequireDefault(require("../../modules/usePlatformMethods"));
var _useResponderEvents = _interopRequireDefault(require("../../modules/useResponderEvents"));
var _StyleSheet = _interopRequireDefault(require("../StyleSheet"));
var _TextAncestorContext = _interopRequireDefault(require("./TextAncestorContext"));
var _useLocale = require("../../modules/useLocale");
var _warnOnce = require("../../modules/warnOnce");
var _excluded = ["hrefAttrs", "numberOfLines", "onClick", "onLayout", "onPress", "onMoveShouldSetResponder", "onMoveShouldSetResponderCapture", "onResponderEnd", "onResponderGrant", "onResponderMove", "onResponderReject", "onResponderRelease", "onResponderStart", "onResponderTerminate", "onResponderTerminationRequest", "onScrollShouldSetResponder", "onScrollShouldSetResponderCapture", "onSelectionChangeShouldSetResponder", "onSelectionChangeShouldSetResponderCapture", "onStartShouldSetResponder", "onStartShouldSetResponderCapture", "selectable"];
var forwardPropsList = Object.assign({}, forwardedProps.defaultProps, forwardedProps.accessibilityProps, forwardedProps.clickProps, forwardedProps.focusProps, forwardedProps.keyboardProps, forwardedProps.mouseProps, forwardedProps.touchProps, forwardedProps.styleProps, {
href: true,
lang: true,
pointerEvents: true
});
var pickProps = props => (0, _pick.default)(props, forwardPropsList);
var Text = /*#__PURE__*/React.forwardRef((props, forwardedRef) => {
var hrefAttrs = props.hrefAttrs,
numberOfLines = props.numberOfLines,
onClick = props.onClick,
onLayout = props.onLayout,
onPress = props.onPress,
onMoveShouldSetResponder = props.onMoveShouldSetResponder,
onMoveShouldSetResponderCapture = props.onMoveShouldSetResponderCapture,
onResponderEnd = props.onResponderEnd,
onResponderGrant = props.onResponderGrant,
onResponderMove = props.onResponderMove,
onResponderReject = props.onResponderReject,
onResponderRelease = props.onResponderRelease,
onResponderStart = props.onResponderStart,
onResponderTerminate = props.onResponderTerminate,
onResponderTerminationRequest = props.onResponderTerminationRequest,
onScrollShouldSetResponder = props.onScrollShouldSetResponder,
onScrollShouldSetResponderCapture = props.onScrollShouldSetResponderCapture,
onSelectionChangeShouldSetResponder = props.onSelectionChangeShouldSetResponder,
onSelectionChangeShouldSetResponderCapture = props.onSelectionChangeShouldSetResponderCapture,
onStartShouldSetResponder = props.onStartShouldSetResponder,
onStartShouldSetResponderCapture = props.onStartShouldSetResponderCapture,
selectable = props.selectable,
rest = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
if (selectable != null) {
(0, _warnOnce.warnOnce)('selectable', 'selectable prop is deprecated. Use styles.userSelect.');
}
var hasTextAncestor = React.useContext(_TextAncestorContext.default);
var hostRef = React.useRef(null);
var _useLocaleContext = (0, _useLocale.useLocaleContext)(),
contextDirection = _useLocaleContext.direction;
(0, _useElementLayout.default)(hostRef, onLayout);
(0, _useResponderEvents.default)(hostRef, {
onMoveShouldSetResponder,
onMoveShouldSetResponderCapture,
onResponderEnd,
onResponderGrant,
onResponderMove,
onResponderReject,
onResponderRelease,
onResponderStart,
onResponderTerminate,
onResponderTerminationRequest,
onScrollShouldSetResponder,
onScrollShouldSetResponderCapture,
onSelectionChangeShouldSetResponder,
onSelectionChangeShouldSetResponderCapture,
onStartShouldSetResponder,
onStartShouldSetResponderCapture
});
var handleClick = React.useCallback(e => {
if (onClick != null) {
onClick(e);
} else if (onPress != null) {
e.stopPropagation();
onPress(e);
}
}, [onClick, onPress]);
var component = hasTextAncestor ? 'span' : 'div';
var langDirection = props.lang != null ? (0, _useLocale.getLocaleDirection)(props.lang) : null;
var componentDirection = props.dir || langDirection;
var writingDirection = componentDirection || contextDirection;
var supportedProps = pickProps(rest);
supportedProps.dir = componentDirection;
// 'auto' by default allows browsers to infer writing direction (root elements only)
if (!hasTextAncestor) {
supportedProps.dir = componentDirection != null ? componentDirection : 'auto';
}
if (onClick || onPress) {
supportedProps.onClick = handleClick;
}
supportedProps.style = [numberOfLines != null && numberOfLines > 1 && {
WebkitLineClamp: numberOfLines
}, hasTextAncestor === true ? styles.textHasAncestor$raw : styles.text$raw, numberOfLines === 1 && styles.textOneLine, numberOfLines != null && numberOfLines > 1 && styles.textMultiLine, props.style, selectable === true && styles.selectable, selectable === false && styles.notSelectable, onPress && styles.pressable];
if (props.href != null) {
component = 'a';
if (hrefAttrs != null) {
var download = hrefAttrs.download,
rel = hrefAttrs.rel,
target = hrefAttrs.target;
if (download != null) {
supportedProps.download = download;
}
if (rel != null) {
supportedProps.rel = rel;
}
if (typeof target === 'string') {
supportedProps.target = target.charAt(0) !== '_' ? '_' + target : target;
}
}
}
var platformMethodsRef = (0, _usePlatformMethods.default)(supportedProps);
var setRef = (0, _useMergeRefs.default)(hostRef, platformMethodsRef, forwardedRef);
supportedProps.ref = setRef;
var element = (0, _createElement.default)(component, supportedProps, {
writingDirection
});
return hasTextAncestor ? element : /*#__PURE__*/React.createElement(_TextAncestorContext.default.Provider, {
value: true
}, element);
});
Text.displayName = 'Text';
var textStyle = {
backgroundColor: 'transparent',
border: '0 solid black',
boxSizing: 'border-box',
color: 'black',
display: 'inline',
font: '14px System',
listStyle: 'none',
margin: 0,
padding: 0,
position: 'relative',
textAlign: 'start',
textDecoration: 'none',
whiteSpace: 'pre-wrap',
wordWrap: 'break-word'
};
var styles = _StyleSheet.default.create({
text$raw: textStyle,
textHasAncestor$raw: (0, _objectSpread2.default)((0, _objectSpread2.default)({}, textStyle), {}, {
color: 'inherit',
font: 'inherit',
textAlign: 'inherit',
whiteSpace: 'inherit'
}),
textOneLine: {
maxWidth: '100%',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
wordWrap: 'normal'
},
// See #13
textMultiLine: {
display: '-webkit-box',
maxWidth: '100%',
overflow: 'hidden',
textOverflow: 'ellipsis',
WebkitBoxOrient: 'vertical'
},
notSelectable: {
userSelect: 'none'
},
selectable: {
userSelect: 'text'
},
pressable: {
cursor: 'pointer'
}
});
var _default = Text;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/TextInput/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
var _createElement = _interopRequireDefault(require("../createElement"));
var forwardedProps = _interopRequireWildcard(require("../../modules/forwardedProps"));
var _pick = _interopRequireDefault(require("../../modules/pick"));
var _useElementLayout = _interopRequireDefault(require("../../modules/useElementLayout"));
var _useLayoutEffect = _interopRequireDefault(require("../../modules/useLayoutEffect"));
var _useMergeRefs = _interopRequireDefault(require("../../modules/useMergeRefs"));
var _usePlatformMethods = _interopRequireDefault(require("../../modules/usePlatformMethods"));
var _useResponderEvents = _interopRequireDefault(require("../../modules/useResponderEvents"));
var _useLocale = require("../../modules/useLocale");
var _StyleSheet = _interopRequireDefault(require("../StyleSheet"));
var _TextInputState = _interopRequireDefault(require("../../modules/TextInputState"));
var _warnOnce = require("../../modules/warnOnce");
/**
* 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.
*
*
*/
/**
* Determines whether a 'selection' prop differs from a node's existing
* selection state.
*/
var isSelectionStale = (node, selection) => {
var selectionEnd = node.selectionEnd,
selectionStart = node.selectionStart;
var start = selection.start,
end = selection.end;
return start !== selectionStart || end !== selectionEnd;
};
/**
* Certain input types do no support 'selectSelectionRange' and will throw an
* error.
*/
var setSelection = (node, selection) => {
if (isSelectionStale(node, selection)) {
var start = selection.start,
end = selection.end;
try {
node.setSelectionRange(start, end || start);
} catch (e) {}
}
};
var forwardPropsList = Object.assign({}, forwardedProps.defaultProps, forwardedProps.accessibilityProps, forwardedProps.clickProps, forwardedProps.focusProps, forwardedProps.keyboardProps, forwardedProps.mouseProps, forwardedProps.touchProps, forwardedProps.styleProps, {
autoCapitalize: true,
autoComplete: true,
autoCorrect: true,
autoFocus: true,
defaultValue: true,
disabled: true,
lang: true,
maxLength: true,
onChange: true,
onScroll: true,
placeholder: true,
pointerEvents: true,
readOnly: true,
rows: true,
spellCheck: true,
value: true,
type: true
});
var pickProps = props => (0, _pick.default)(props, forwardPropsList);
// If an Input Method Editor is processing key input, the 'keyCode' is 229.
// https://www.w3.org/TR/uievents/#determine-keydown-keyup-keyCode
function isEventComposing(nativeEvent) {
return nativeEvent.isComposing || nativeEvent.keyCode === 229;
}
var focusTimeout = null;
var TextInput = /*#__PURE__*/React.forwardRef((props, forwardedRef) => {
var _props$autoCapitalize = props.autoCapitalize,
autoCapitalize = _props$autoCapitalize === void 0 ? 'sentences' : _props$autoCapitalize,
autoComplete = props.autoComplete,
autoCompleteType = props.autoCompleteType,
_props$autoCorrect = props.autoCorrect,
autoCorrect = _props$autoCorrect === void 0 ? true : _props$autoCorrect,
blurOnSubmit = props.blurOnSubmit,
caretHidden = props.caretHidden,
clearTextOnFocus = props.clearTextOnFocus,
dir = props.dir,
editable = props.editable,
enterKeyHint = props.enterKeyHint,
inputMode = props.inputMode,
keyboardType = props.keyboardType,
_props$multiline = props.multiline,
multiline = _props$multiline === void 0 ? false : _props$multiline,
numberOfLines = props.numberOfLines,
onBlur = props.onBlur,
onChange = props.onChange,
onChangeText = props.onChangeText,
onContentSizeChange = props.onContentSizeChange,
onFocus = props.onFocus,
onKeyPress = props.onKeyPress,
onLayout = props.onLayout,
onMoveShouldSetResponder = props.onMoveShouldSetResponder,
onMoveShouldSetResponderCapture = props.onMoveShouldSetResponderCapture,
onResponderEnd = props.onResponderEnd,
onResponderGrant = props.onResponderGrant,
onResponderMove = props.onResponderMove,
onResponderReject = props.onResponderReject,
onResponderRelease = props.onResponderRelease,
onResponderStart = props.onResponderStart,
onResponderTerminate = props.onResponderTerminate,
onResponderTerminationRequest = props.onResponderTerminationRequest,
onScrollShouldSetResponder = props.onScrollShouldSetResponder,
onScrollShouldSetResponderCapture = props.onScrollShouldSetResponderCapture,
onSelectionChange = props.onSelectionChange,
onSelectionChangeShouldSetResponder = props.onSelectionChangeShouldSetResponder,
onSelectionChangeShouldSetResponderCapture = props.onSelectionChangeShouldSetResponderCapture,
onStartShouldSetResponder = props.onStartShouldSetResponder,
onStartShouldSetResponderCapture = props.onStartShouldSetResponderCapture,
onSubmitEditing = props.onSubmitEditing,
placeholderTextColor = props.placeholderTextColor,
_props$readOnly = props.readOnly,
readOnly = _props$readOnly === void 0 ? false : _props$readOnly,
returnKeyType = props.returnKeyType,
rows = props.rows,
_props$secureTextEntr = props.secureTextEntry,
secureTextEntry = _props$secureTextEntr === void 0 ? false : _props$secureTextEntr,
selection = props.selection,
selectTextOnFocus = props.selectTextOnFocus,
spellCheck = props.spellCheck;
var type;
var _inputMode;
if (inputMode != null) {
_inputMode = inputMode;
if (inputMode === 'email') {
type = 'email';
} else if (inputMode === 'tel') {
type = 'tel';
} else if (inputMode === 'search') {
type = 'search';
} else if (inputMode === 'url') {
type = 'url';
} else {
type = 'text';
}
} else if (keyboardType != null) {
(0, _warnOnce.warnOnce)('keyboardType', 'keyboardType is deprecated. Use inputMode.');
switch (keyboardType) {
case 'email-address':
type = 'email';
break;
case 'number-pad':
case 'numeric':
_inputMode = 'numeric';
break;
case 'decimal-pad':
_inputMode = 'decimal';
break;
case 'phone-pad':
type = 'tel';
break;
case 'search':
case 'web-search':
type = 'search';
break;
case 'url':
type = 'url';
break;
default:
type = 'text';
}
}
if (secureTextEntry) {
type = 'password';
}
var dimensions = React.useRef({
height: null,
width: null
});
var hostRef = React.useRef(null);
var prevSelection = React.useRef(null);
var prevSecureTextEntry = React.useRef(false);
React.useEffect(() => {
if (hostRef.current && prevSelection.current) {
setSelection(hostRef.current, prevSelection.current);
}
prevSecureTextEntry.current = secureTextEntry;
}, [secureTextEntry]);
var handleContentSizeChange = React.useCallback(hostNode => {
if (multiline && onContentSizeChange && hostNode != null) {
var newHeight = hostNode.scrollHeight;
var newWidth = hostNode.scrollWidth;
if (newHeight !== dimensions.current.height || newWidth !== dimensions.current.width) {
dimensions.current.height = newHeight;
dimensions.current.width = newWidth;
onContentSizeChange({
nativeEvent: {
contentSize: {
height: dimensions.current.height,
width: dimensions.current.width
}
}
});
}
}
}, [multiline, onContentSizeChange]);
var imperativeRef = React.useMemo(() => hostNode => {
// TextInput needs to add more methods to the hostNode in addition to those
// added by `usePlatformMethods`. This is temporarily until an API like
// `TextInput.clear(hostRef)` is added to React Native.
if (hostNode != null) {
hostNode.clear = function () {
if (hostNode != null) {
hostNode.value = '';
}
};
hostNode.isFocused = function () {
return hostNode != null && _TextInputState.default.currentlyFocusedField() === hostNode;
};
handleContentSizeChange(hostNode);
}
}, [handleContentSizeChange]);
function handleBlur(e) {
_TextInputState.default._currentlyFocusedNode = null;
if (onBlur) {
e.nativeEvent.text = e.target.value;
onBlur(e);
}
}
function handleChange(e) {
var hostNode = e.target;
var text = hostNode.value;
e.nativeEvent.text = text;
handleContentSizeChange(hostNode);
if (onChange) {
onChange(e);
}
if (onChangeText) {
onChangeText(text);
}
}
function handleFocus(e) {
var hostNode = e.target;
if (onFocus) {
e.nativeEvent.text = hostNode.value;
onFocus(e);
}
if (hostNode != null) {
_TextInputState.default._currentlyFocusedNode = hostNode;
if (clearTextOnFocus) {
hostNode.value = '';
}
if (selectTextOnFocus) {
// Safari requires selection to occur in a setTimeout
if (focusTimeout != null) {
clearTimeout(focusTimeout);
}
focusTimeout = setTimeout(() => {
if (hostNode != null) {
hostNode.select();
}
}, 0);
}
}
}
function handleKeyDown(e) {
var hostNode = e.target;
// Prevent key events bubbling (see #612)
e.stopPropagation();
var blurOnSubmitDefault = !multiline;
var shouldBlurOnSubmit = blurOnSubmit == null ? blurOnSubmitDefault : blurOnSubmit;
var nativeEvent = e.nativeEvent;
var isComposing = isEventComposing(nativeEvent);
if (onKeyPress) {
onKeyPress(e);
}
if (e.key === 'Enter' && !e.shiftKey &&
// Do not call submit if composition is occuring.
!isComposing && !e.isDefaultPrevented()) {
if ((blurOnSubmit || !multiline) && onSubmitEditing) {
// prevent "Enter" from inserting a newline or submitting a form
e.preventDefault();
nativeEvent.text = e.target.value;
onSubmitEditing(e);
}
if (shouldBlurOnSubmit && hostNode != null) {
setTimeout(() => hostNode.blur(), 0);
}
}
}
function handleSelectionChange(e) {
try {
var _e$target = e.target,
selectionStart = _e$target.selectionStart,
selectionEnd = _e$target.selectionEnd;
var _selection = {
start: selectionStart,
end: selectionEnd
};
if (onSelectionChange) {
e.nativeEvent.selection = _selection;
e.nativeEvent.text = e.target.value;
onSelectionChange(e);
}
if (prevSecureTextEntry.current === secureTextEntry) {
prevSelection.current = _selection;
}
} catch (e) {}
}
(0, _useLayoutEffect.default)(() => {
var node = hostRef.current;
if (node != null && selection != null) {
setSelection(node, selection);
}
if (document.activeElement === node) {
_TextInputState.default._currentlyFocusedNode = node;
}
}, [hostRef, selection]);
var component = multiline ? 'textarea' : 'input';
(0, _useElementLayout.default)(hostRef, onLayout);
(0, _useResponderEvents.default)(hostRef, {
onMoveShouldSetResponder,
onMoveShouldSetResponderCapture,
onResponderEnd,
onResponderGrant,
onResponderMove,
onResponderReject,
onResponderRelease,
onResponderStart,
onResponderTerminate,
onResponderTerminationRequest,
onScrollShouldSetResponder,
onScrollShouldSetResponderCapture,
onSelectionChangeShouldSetResponder,
onSelectionChangeShouldSetResponderCapture,
onStartShouldSetResponder,
onStartShouldSetResponderCapture
});
var _useLocaleContext = (0, _useLocale.useLocaleContext)(),
contextDirection = _useLocaleContext.direction;
var supportedProps = pickProps(props);
supportedProps.autoCapitalize = autoCapitalize;
supportedProps.autoComplete = autoComplete || autoCompleteType || 'on';
supportedProps.autoCorrect = autoCorrect ? 'on' : 'off';
// 'auto' by default allows browsers to infer writing direction
supportedProps.dir = dir !== undefined ? dir : 'auto';
if (returnKeyType != null) {
(0, _warnOnce.warnOnce)('returnKeyType', 'returnKeyType is deprecated. Use enterKeyHint.');
}
supportedProps.enterKeyHint = enterKeyHint || returnKeyType;
supportedProps.inputMode = _inputMode;
supportedProps.onBlur = handleBlur;
supportedProps.onChange = handleChange;
supportedProps.onFocus = handleFocus;
supportedProps.onKeyDown = handleKeyDown;
supportedProps.onSelect = handleSelectionChange;
if (editable != null) {
(0, _warnOnce.warnOnce)('editable', 'editable is deprecated. Use readOnly.');
}
supportedProps.readOnly = readOnly === true || editable === false;
if (numberOfLines != null) {
(0, _warnOnce.warnOnce)('numberOfLines', 'TextInput numberOfLines is deprecated. Use rows.');
}
supportedProps.rows = multiline ? rows != null ? rows : numberOfLines : 1;
supportedProps.spellCheck = spellCheck != null ? spellCheck : autoCorrect;
supportedProps.style = [{
'--placeholderTextColor': placeholderTextColor
}, styles.textinput$raw, styles.placeholder, props.style, caretHidden && styles.caretHidden];
supportedProps.type = multiline ? undefined : type;
var platformMethodsRef = (0, _usePlatformMethods.default)(supportedProps);
var setRef = (0, _useMergeRefs.default)(hostRef, platformMethodsRef, imperativeRef, forwardedRef);
supportedProps.ref = setRef;
var langDirection = props.lang != null ? (0, _useLocale.getLocaleDirection)(props.lang) : null;
var componentDirection = props.dir || langDirection;
var writingDirection = componentDirection || contextDirection;
var element = (0, _createElement.default)(component, supportedProps, {
writingDirection
});
return element;
});
TextInput.displayName = 'TextInput';
// $FlowFixMe
TextInput.State = _TextInputState.default;
var styles = _StyleSheet.default.create({
textinput$raw: {
MozAppearance: 'textfield',
WebkitAppearance: 'none',
backgroundColor: 'transparent',
border: '0 solid black',
borderRadius: 0,
boxSizing: 'border-box',
font: '14px System',
margin: 0,
padding: 0,
resize: 'none'
},
placeholder: {
placeholderTextColor: 'var(--placeholderTextColor)'
},
caretHidden: {
caretColor: 'transparent'
}
});
var _default = TextInput;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Touchable/BoundingDimensions.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _PooledClass = _interopRequireDefault(require("../../vendor/react-native/PooledClass"));
/**
* 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.
*
*
*/
var twoArgumentPooler = _PooledClass.default.twoArgumentPooler;
/**
* PooledClass representing the bounding rectangle of a region.
*/
function BoundingDimensions(width, height) {
this.width = width;
this.height = height;
}
BoundingDimensions.prototype.destructor = function () {
this.width = null;
this.height = null;
};
BoundingDimensions.getPooledFromElement = function (element) {
return BoundingDimensions.getPooled(element.offsetWidth, element.offsetHeight);
};
_PooledClass.default.addPoolingTo(BoundingDimensions, twoArgumentPooler);
var _default = BoundingDimensions;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Touchable/Position.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _PooledClass = _interopRequireDefault(require("../../vendor/react-native/PooledClass"));
/**
* 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.
*
*
*/
var twoArgumentPooler = _PooledClass.default.twoArgumentPooler;
function Position(left, top) {
this.left = left;
this.top = top;
}
Position.prototype.destructor = function () {
this.left = null;
this.top = null;
};
_PooledClass.default.addPoolingTo(Position, twoArgumentPooler);
var _default = Position;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Touchable/index.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _AccessibilityUtil = _interopRequireDefault(require("../../modules/AccessibilityUtil"));
var _BoundingDimensions = _interopRequireDefault(require("./BoundingDimensions"));
var _normalizeColors = _interopRequireDefault(require("@react-native/normalize-colors"));
var _Position = _interopRequireDefault(require("./Position"));
var _react = _interopRequireDefault(require("react"));
var _UIManager = _interopRequireDefault(require("../UIManager"));
var _View = _interopRequireDefault(require("../View"));
var _warnOnce = require("../../modules/warnOnce");
var 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);
* }
*
* - Add a method to get your touchable component's node.
* getTouchableNode: function() {
* return this.touchableRef.current
* }
*
* - 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
* ref={this.touchableRef}
* 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 = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, 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 = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, baseStatesConditions), {}, {
RESPONDER_INACTIVE_PRESS_IN: true,
RESPONDER_ACTIVE_PRESS_IN: true,
RESPONDER_ACTIVE_LONG_PRESS_IN: true
});
var IsLongPressingIn = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, 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() {
(0, _warnOnce.warnOnce)('TouchableMixin', 'TouchableMixin is deprecated. Please use Pressable.');
var touchableNode = this.getTouchableNode && this.getTouchableNode();
if (touchableNode && touchableNode.addEventListener) {
this._touchableBlurListener = e => {
if (this._isTouchableKeyboardActive) {
if (this.state.touchable.touchState && this.state.touchable.touchState !== States.NOT_RESPONDER) {
this.touchableHandleResponderTerminate({
nativeEvent: e
});
}
this._isTouchableKeyboardActive = false;
}
};
touchableNode.addEventListener('blur', this._touchableBlurListener);
}
},
/**
* Clear all timeouts on unmount
*/
componentWillUnmount: function componentWillUnmount() {
var touchableNode = this.getTouchableNode && this.getTouchableNode();
if (touchableNode && touchableNode.addEventListener) {
touchableNode.removeEventListener('blur', this._touchableBlurListener);
}
this.touchableDelayTimeout && clearTimeout(this.touchableDelayTimeout);
this.longPressDelayTimeout && clearTimeout(this.longPressDelayTimeout);
this.pressOutDelayTimeout && clearTimeout(this.pressOutDelayTimeout);
// Clear DOM nodes
this.pressInLocation = null;
this.state.touchable.responderID = null;
},
/**
* 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.default.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.default.release(this.state.touchable.positionOnActivate);
this.state.touchable.dimensionsOnActivate &&
// $FlowFixMe
_BoundingDimensions.default.release(this.state.touchable.dimensionsOnActivate);
this.state.touchable.positionOnActivate = _Position.default.getPooled(globalX, globalY);
// $FlowFixMe
this.state.touchable.dimensionsOnActivate = _BoundingDimensions.default.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,
pageY,
locationX,
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.default.playTouchSound();
},
_startHighlight: function _startHighlight(e) {
this._savePressInLocation(e);
this.touchableHandleActivePressIn && this.touchableHandleActivePressIn(e);
},
_endHighlight: function _endHighlight(e) {
if (this.touchableHandleActivePressOut) {
if (this.touchableGetPressOutDelayMS && this.touchableGetPressOutDelayMS()) {
this.pressOutDelayTimeout = setTimeout(() => {
this.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.default.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 = (0, _objectWithoutPropertiesLoose2.default)(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: _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 = (0, _normalizeColors.default)(color);
if (typeof normalizedColor !== 'number') {
return null;
}
var hexColor = '#' + ('00000000' + normalizedColor.toString(16)).substr(-8);
return /*#__PURE__*/_react.default.createElement(_View.default, {
pointerEvents: "none",
style: (0, _objectSpread2.default)({
position: 'absolute',
borderColor: hexColor.slice(0, -2) + '55',
// More opaque
borderWidth: 1,
borderStyle: 'dashed',
backgroundColor: hexColor.slice(0, -2) + '0F'
}, debugHitSlopStyle)
});
}
};
var _default = Touchable;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/TouchableHighlight/index.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var React = _interopRequireWildcard(require("react"));
var _useMergeRefs = _interopRequireDefault(require("../../modules/useMergeRefs"));
var _usePressEvents = _interopRequireDefault(require("../../modules/usePressEvents"));
var _StyleSheet = _interopRequireDefault(require("../StyleSheet"));
var _View = _interopRequireDefault(require("../View"));
var _warnOnce = require("../../modules/warnOnce");
var _excluded = ["activeOpacity", "children", "delayPressIn", "delayPressOut", "delayLongPress", "disabled", "focusable", "onHideUnderlay", "onLongPress", "onPress", "onPressIn", "onPressOut", "onShowUnderlay", "rejectResponderTermination", "style", "testOnly_pressed", "underlayColor"];
function createExtraStyles(activeOpacity, underlayColor) {
return {
child: {
opacity: activeOpacity !== null && activeOpacity !== void 0 ? activeOpacity : 0.85
},
underlay: {
backgroundColor: underlayColor === undefined ? 'black' : underlayColor
}
};
}
function hasPressHandler(props) {
return props.onPress != null || props.onPressIn != null || props.onPressOut != null || props.onLongPress != null;
}
/**
* A wrapper for making views respond properly to touches.
* On press down, the opacity of the wrapped view is decreased, which allows
* the underlay color to show through, darkening or tinting the view.
*
* The underlay comes from wrapping the child in a new View, which can affect
* layout, and sometimes cause unwanted visual artifacts if not used correctly,
* for example if the backgroundColor of the wrapped view isn't explicitly set
* to an opaque color.
*
* TouchableHighlight must have one child (not zero or more than one).
* If you wish to have several child components, wrap them in a View.
*/
function TouchableHighlight(props, forwardedRef) {
(0, _warnOnce.warnOnce)('TouchableHighlight', 'TouchableHighlight is deprecated. Please use Pressable.');
var activeOpacity = props.activeOpacity,
children = props.children,
delayPressIn = props.delayPressIn,
delayPressOut = props.delayPressOut,
delayLongPress = props.delayLongPress,
disabled = props.disabled,
focusable = props.focusable,
onHideUnderlay = props.onHideUnderlay,
onLongPress = props.onLongPress,
onPress = props.onPress,
onPressIn = props.onPressIn,
onPressOut = props.onPressOut,
onShowUnderlay = props.onShowUnderlay,
rejectResponderTermination = props.rejectResponderTermination,
style = props.style,
testOnly_pressed = props.testOnly_pressed,
underlayColor = props.underlayColor,
rest = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
var hostRef = (0, React.useRef)(null);
var setRef = (0, _useMergeRefs.default)(forwardedRef, hostRef);
var _useState = (0, React.useState)(testOnly_pressed === true ? createExtraStyles(activeOpacity, underlayColor) : null),
extraStyles = _useState[0],
setExtraStyles = _useState[1];
var showUnderlay = (0, React.useCallback)(() => {
if (!hasPressHandler(props)) {
return;
}
setExtraStyles(createExtraStyles(activeOpacity, underlayColor));
if (onShowUnderlay != null) {
onShowUnderlay();
}
}, [activeOpacity, onShowUnderlay, props, underlayColor]);
var hideUnderlay = (0, React.useCallback)(() => {
if (testOnly_pressed === true) {
return;
}
if (hasPressHandler(props)) {
setExtraStyles(null);
if (onHideUnderlay != null) {
onHideUnderlay();
}
}
}, [onHideUnderlay, props, testOnly_pressed]);
var pressConfig = (0, React.useMemo)(() => ({
cancelable: !rejectResponderTermination,
disabled,
delayLongPress,
delayPressStart: delayPressIn,
delayPressEnd: delayPressOut,
onLongPress,
onPress,
onPressStart(event) {
showUnderlay();
if (onPressIn != null) {
onPressIn(event);
}
},
onPressEnd(event) {
hideUnderlay();
if (onPressOut != null) {
onPressOut(event);
}
}
}), [delayLongPress, delayPressIn, delayPressOut, disabled, onLongPress, onPress, onPressIn, onPressOut, rejectResponderTermination, showUnderlay, hideUnderlay]);
var pressEventHandlers = (0, _usePressEvents.default)(hostRef, pressConfig);
var child = React.Children.only(children);
return /*#__PURE__*/React.createElement(_View.default, (0, _extends2.default)({}, rest, pressEventHandlers, {
accessibilityDisabled: disabled,
focusable: !disabled && focusable !== false,
pointerEvents: disabled ? 'box-none' : undefined,
ref: setRef,
style: [styles.root, style, !disabled && styles.actionable, extraStyles && extraStyles.underlay]
}), /*#__PURE__*/React.cloneElement(child, {
style: [child.props.style, extraStyles && extraStyles.child]
}));
}
var styles = _StyleSheet.default.create({
root: {
userSelect: 'none'
},
actionable: {
cursor: 'pointer',
touchAction: 'manipulation'
}
});
var MemoedTouchableHighlight = /*#__PURE__*/React.memo( /*#__PURE__*/React.forwardRef(TouchableHighlight));
MemoedTouchableHighlight.displayName = 'TouchableHighlight';
var _default = MemoedTouchableHighlight;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/TouchableNativeFeedback/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _UnimplementedView = _interopRequireDefault(require("../../modules/UnimplementedView"));
/**
* 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.
*
*
*/
var _default = _UnimplementedView.default;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/TouchableOpacity/index.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var React = _interopRequireWildcard(require("react"));
var _useMergeRefs = _interopRequireDefault(require("../../modules/useMergeRefs"));
var _usePressEvents = _interopRequireDefault(require("../../modules/usePressEvents"));
var _StyleSheet = _interopRequireDefault(require("../StyleSheet"));
var _View = _interopRequireDefault(require("../View"));
var _warnOnce = require("../../modules/warnOnce");
var _excluded = ["activeOpacity", "delayPressIn", "delayPressOut", "delayLongPress", "disabled", "focusable", "onLongPress", "onPress", "onPressIn", "onPressOut", "rejectResponderTermination", "style"];
/**
* A wrapper for making views respond properly to touches.
* On press down, the opacity of the wrapped view is decreased, dimming it.
*/
function TouchableOpacity(props, forwardedRef) {
(0, _warnOnce.warnOnce)('TouchableOpacity', 'TouchableOpacity is deprecated. Please use Pressable.');
var activeOpacity = props.activeOpacity,
delayPressIn = props.delayPressIn,
delayPressOut = props.delayPressOut,
delayLongPress = props.delayLongPress,
disabled = props.disabled,
focusable = props.focusable,
onLongPress = props.onLongPress,
onPress = props.onPress,
onPressIn = props.onPressIn,
onPressOut = props.onPressOut,
rejectResponderTermination = props.rejectResponderTermination,
style = props.style,
rest = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
var hostRef = (0, React.useRef)(null);
var setRef = (0, _useMergeRefs.default)(forwardedRef, hostRef);
var _useState = (0, React.useState)('0s'),
duration = _useState[0],
setDuration = _useState[1];
var _useState2 = (0, React.useState)(null),
opacityOverride = _useState2[0],
setOpacityOverride = _useState2[1];
var setOpacityTo = (0, React.useCallback)((value, duration) => {
setOpacityOverride(value);
setDuration(duration ? duration / 1000 + "s" : '0s');
}, [setOpacityOverride, setDuration]);
var setOpacityActive = (0, React.useCallback)(duration => {
setOpacityTo(activeOpacity !== null && activeOpacity !== void 0 ? activeOpacity : 0.2, duration);
}, [activeOpacity, setOpacityTo]);
var setOpacityInactive = (0, React.useCallback)(duration => {
setOpacityTo(null, duration);
}, [setOpacityTo]);
var pressConfig = (0, React.useMemo)(() => ({
cancelable: !rejectResponderTermination,
disabled,
delayLongPress,
delayPressStart: delayPressIn,
delayPressEnd: delayPressOut,
onLongPress,
onPress,
onPressStart(event) {
var isGrant = event.dispatchConfig != null ? event.dispatchConfig.registrationName === 'onResponderGrant' : event.type === 'keydown';
setOpacityActive(isGrant ? 0 : 150);
if (onPressIn != null) {
onPressIn(event);
}
},
onPressEnd(event) {
setOpacityInactive(250);
if (onPressOut != null) {
onPressOut(event);
}
}
}), [delayLongPress, delayPressIn, delayPressOut, disabled, onLongPress, onPress, onPressIn, onPressOut, rejectResponderTermination, setOpacityActive, setOpacityInactive]);
var pressEventHandlers = (0, _usePressEvents.default)(hostRef, pressConfig);
return /*#__PURE__*/React.createElement(_View.default, (0, _extends2.default)({}, rest, pressEventHandlers, {
accessibilityDisabled: disabled,
focusable: !disabled && focusable !== false,
pointerEvents: disabled ? 'box-none' : undefined,
ref: setRef,
style: [styles.root, !disabled && styles.actionable, style, opacityOverride != null && {
opacity: opacityOverride
}, {
transitionDuration: duration
}]
}));
}
var styles = _StyleSheet.default.create({
root: {
transitionProperty: 'opacity',
transitionDuration: '0.15s',
userSelect: 'none'
},
actionable: {
cursor: 'pointer',
touchAction: 'manipulation'
}
});
var MemoedTouchableOpacity = /*#__PURE__*/React.memo( /*#__PURE__*/React.forwardRef(TouchableOpacity));
MemoedTouchableOpacity.displayName = 'TouchableOpacity';
var _default = MemoedTouchableOpacity;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/TouchableWithoutFeedback/index.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
var _pick = _interopRequireDefault(require("../../modules/pick"));
var _useMergeRefs = _interopRequireDefault(require("../../modules/useMergeRefs"));
var _usePressEvents = _interopRequireDefault(require("../../modules/usePressEvents"));
var _warnOnce = require("../../modules/warnOnce");
var forwardPropsList = {
accessibilityDisabled: true,
accessibilityLabel: true,
accessibilityLiveRegion: true,
accessibilityRole: true,
accessibilityState: true,
accessibilityValue: true,
children: true,
disabled: true,
focusable: true,
nativeID: true,
onBlur: true,
onFocus: true,
onLayout: true,
testID: true
};
var pickProps = props => (0, _pick.default)(props, forwardPropsList);
function TouchableWithoutFeedback(props, forwardedRef) {
(0, _warnOnce.warnOnce)('TouchableWithoutFeedback', 'TouchableWithoutFeedback is deprecated. Please use Pressable.');
var delayPressIn = props.delayPressIn,
delayPressOut = props.delayPressOut,
delayLongPress = props.delayLongPress,
disabled = props.disabled,
focusable = props.focusable,
onLongPress = props.onLongPress,
onPress = props.onPress,
onPressIn = props.onPressIn,
onPressOut = props.onPressOut,
rejectResponderTermination = props.rejectResponderTermination;
var hostRef = (0, React.useRef)(null);
var pressConfig = (0, React.useMemo)(() => ({
cancelable: !rejectResponderTermination,
disabled,
delayLongPress,
delayPressStart: delayPressIn,
delayPressEnd: delayPressOut,
onLongPress,
onPress,
onPressStart: onPressIn,
onPressEnd: onPressOut
}), [disabled, delayPressIn, delayPressOut, delayLongPress, onLongPress, onPress, onPressIn, onPressOut, rejectResponderTermination]);
var pressEventHandlers = (0, _usePressEvents.default)(hostRef, pressConfig);
var element = React.Children.only(props.children);
var children = [element.props.children];
var supportedProps = pickProps(props);
supportedProps.accessibilityDisabled = disabled;
supportedProps.focusable = !disabled && focusable !== false;
supportedProps.ref = (0, _useMergeRefs.default)(forwardedRef, hostRef, element.ref);
var elementProps = Object.assign(supportedProps, pressEventHandlers);
return /*#__PURE__*/React.cloneElement(element, elementProps, ...children);
}
var MemoedTouchableWithoutFeedback = /*#__PURE__*/React.memo( /*#__PURE__*/React.forwardRef(TouchableWithoutFeedback));
MemoedTouchableWithoutFeedback.displayName = 'TouchableWithoutFeedback';
var _default = MemoedTouchableWithoutFeedback;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/UIManager/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _getBoundingClientRect = _interopRequireDefault(require("../../modules/getBoundingClientRect"));
var _setValueForStyles = _interopRequireDefault(require("../../modules/setValueForStyles"));
/**
* 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.
*
*
*/
var getRect = node => {
var height = node.offsetHeight;
var width = node.offsetWidth;
var left = node.offsetLeft;
var top = node.offsetTop;
node = node.offsetParent;
while (node && node.nodeType === 1 /* Node.ELEMENT_NODE */) {
left += node.offsetLeft + node.clientLeft - node.scrollLeft;
top += node.offsetTop + node.clientTop - node.scrollTop;
node = node.offsetParent;
}
top -= window.scrollY;
left -= window.scrollX;
return {
width,
height,
top,
left
};
};
var measureLayout = (node, relativeToNativeNode, callback) => {
var relativeNode = relativeToNativeNode || node && node.parentNode;
if (node && relativeNode) {
setTimeout(() => {
if (node.isConnected && relativeNode.isConnected) {
var relativeRect = getRect(relativeNode);
var _getRect = getRect(node),
height = _getRect.height,
left = _getRect.left,
top = _getRect.top,
width = _getRect.width;
var x = left - relativeRect.left;
var y = top - relativeRect.top;
callback(x, y, width, height, left, top);
}
}, 0);
}
};
var elementsToIgnore = {
A: true,
BODY: true,
INPUT: true,
SELECT: true,
TEXTAREA: true
};
var UIManager = {
blur(node) {
try {
node.blur();
} catch (err) {}
},
focus(node) {
try {
var name = node.nodeName;
// A tabIndex of -1 allows element to be programmatically focused but
// prevents keyboard focus. We don't want to set the tabindex value on
// elements that should not prevent keyboard focus.
if (node.getAttribute('tabIndex') == null && node.isContentEditable !== true && elementsToIgnore[name] == null) {
node.setAttribute('tabIndex', '-1');
}
node.focus();
} catch (err) {}
},
measure(node, callback) {
measureLayout(node, null, callback);
},
measureInWindow(node, callback) {
if (node) {
setTimeout(() => {
var _getBoundingClientRec = (0, _getBoundingClientRect.default)(node),
height = _getBoundingClientRec.height,
left = _getBoundingClientRec.left,
top = _getBoundingClientRec.top,
width = _getBoundingClientRec.width;
callback(left, top, width, height);
}, 0);
}
},
measureLayout(node, relativeToNativeNode, onFail, onSuccess) {
measureLayout(node, relativeToNativeNode, onSuccess);
},
updateView(node, props) {
for (var prop in props) {
if (!Object.prototype.hasOwnProperty.call(props, prop)) {
continue;
}
var value = props[prop];
switch (prop) {
case 'style':
{
(0, _setValueForStyles.default)(node, value);
break;
}
case 'class':
case 'className':
{
node.setAttribute('class', value);
break;
}
case 'text':
case 'value':
// native platforms use `text` prop to replace text input value
node.value = value;
break;
default:
node.setAttribute(prop, value);
}
}
},
configureNextLayoutAnimation(config, onAnimationDidEnd) {
onAnimationDidEnd();
},
// mocks
setLayoutAnimationEnabledExperimental() {}
};
var _default = UIManager;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/Vibration/index.js
"use strict";
exports.__esModule = true;
exports.default = void 0;
/**
* 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.
*
*
*/
var vibrate = pattern => {
if ('vibrate' in window.navigator) {
window.navigator.vibrate(pattern);
}
};
var Vibration = {
cancel() {
vibrate(0);
},
vibrate(pattern) {
if (pattern === void 0) {
pattern = 400;
}
vibrate(pattern);
}
};
var _default = Vibration;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/View/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var React = _interopRequireWildcard(require("react"));
var _createElement = _interopRequireDefault(require("../createElement"));
var forwardedProps = _interopRequireWildcard(require("../../modules/forwardedProps"));
var _pick = _interopRequireDefault(require("../../modules/pick"));
var _useElementLayout = _interopRequireDefault(require("../../modules/useElementLayout"));
var _useMergeRefs = _interopRequireDefault(require("../../modules/useMergeRefs"));
var _usePlatformMethods = _interopRequireDefault(require("../../modules/usePlatformMethods"));
var _useResponderEvents = _interopRequireDefault(require("../../modules/useResponderEvents"));
var _StyleSheet = _interopRequireDefault(require("../StyleSheet"));
var _TextAncestorContext = _interopRequireDefault(require("../Text/TextAncestorContext"));
var _useLocale = require("../../modules/useLocale");
var _excluded = ["hrefAttrs", "onLayout", "onMoveShouldSetResponder", "onMoveShouldSetResponderCapture", "onResponderEnd", "onResponderGrant", "onResponderMove", "onResponderReject", "onResponderRelease", "onResponderStart", "onResponderTerminate", "onResponderTerminationRequest", "onScrollShouldSetResponder", "onScrollShouldSetResponderCapture", "onSelectionChangeShouldSetResponder", "onSelectionChangeShouldSetResponderCapture", "onStartShouldSetResponder", "onStartShouldSetResponderCapture"];
var forwardPropsList = Object.assign({}, forwardedProps.defaultProps, forwardedProps.accessibilityProps, forwardedProps.clickProps, forwardedProps.focusProps, forwardedProps.keyboardProps, forwardedProps.mouseProps, forwardedProps.touchProps, forwardedProps.styleProps, {
href: true,
lang: true,
onScroll: true,
onWheel: true,
pointerEvents: true
});
var pickProps = props => (0, _pick.default)(props, forwardPropsList);
var View = /*#__PURE__*/React.forwardRef((props, forwardedRef) => {
var hrefAttrs = props.hrefAttrs,
onLayout = props.onLayout,
onMoveShouldSetResponder = props.onMoveShouldSetResponder,
onMoveShouldSetResponderCapture = props.onMoveShouldSetResponderCapture,
onResponderEnd = props.onResponderEnd,
onResponderGrant = props.onResponderGrant,
onResponderMove = props.onResponderMove,
onResponderReject = props.onResponderReject,
onResponderRelease = props.onResponderRelease,
onResponderStart = props.onResponderStart,
onResponderTerminate = props.onResponderTerminate,
onResponderTerminationRequest = props.onResponderTerminationRequest,
onScrollShouldSetResponder = props.onScrollShouldSetResponder,
onScrollShouldSetResponderCapture = props.onScrollShouldSetResponderCapture,
onSelectionChangeShouldSetResponder = props.onSelectionChangeShouldSetResponder,
onSelectionChangeShouldSetResponderCapture = props.onSelectionChangeShouldSetResponderCapture,
onStartShouldSetResponder = props.onStartShouldSetResponder,
onStartShouldSetResponderCapture = props.onStartShouldSetResponderCapture,
rest = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
if (process.env.NODE_ENV !== 'production') {
React.Children.toArray(props.children).forEach(item => {
if (typeof item === 'string') {
console.error("Unexpected text node: " + item + ". A text node cannot be a child of a <View>.");
}
});
}
var hasTextAncestor = React.useContext(_TextAncestorContext.default);
var hostRef = React.useRef(null);
var _useLocaleContext = (0, _useLocale.useLocaleContext)(),
contextDirection = _useLocaleContext.direction;
(0, _useElementLayout.default)(hostRef, onLayout);
(0, _useResponderEvents.default)(hostRef, {
onMoveShouldSetResponder,
onMoveShouldSetResponderCapture,
onResponderEnd,
onResponderGrant,
onResponderMove,
onResponderReject,
onResponderRelease,
onResponderStart,
onResponderTerminate,
onResponderTerminationRequest,
onScrollShouldSetResponder,
onScrollShouldSetResponderCapture,
onSelectionChangeShouldSetResponder,
onSelectionChangeShouldSetResponderCapture,
onStartShouldSetResponder,
onStartShouldSetResponderCapture
});
var component = 'div';
var langDirection = props.lang != null ? (0, _useLocale.getLocaleDirection)(props.lang) : null;
var componentDirection = props.dir || langDirection;
var writingDirection = componentDirection || contextDirection;
var supportedProps = pickProps(rest);
supportedProps.dir = componentDirection;
supportedProps.style = [styles.view$raw, hasTextAncestor && styles.inline, props.style];
if (props.href != null) {
component = 'a';
if (hrefAttrs != null) {
var download = hrefAttrs.download,
rel = hrefAttrs.rel,
target = hrefAttrs.target;
if (download != null) {
supportedProps.download = download;
}
if (rel != null) {
supportedProps.rel = rel;
}
if (typeof target === 'string') {
supportedProps.target = target.charAt(0) !== '_' ? '_' + target : target;
}
}
}
var platformMethodsRef = (0, _usePlatformMethods.default)(supportedProps);
var setRef = (0, _useMergeRefs.default)(hostRef, platformMethodsRef, forwardedRef);
supportedProps.ref = setRef;
return (0, _createElement.default)(component, supportedProps, {
writingDirection
});
});
View.displayName = 'View';
var styles = _StyleSheet.default.create({
view$raw: {
alignItems: 'stretch',
backgroundColor: 'transparent',
border: '0 solid black',
boxSizing: 'border-box',
display: 'flex',
flexBasis: 'auto',
flexDirection: 'column',
flexShrink: 0,
listStyle: 'none',
margin: 0,
minHeight: 0,
minWidth: 0,
padding: 0,
position: 'relative',
textDecoration: 'none',
zIndex: 0
},
inline: {
display: 'inline-flex'
}
});
var _default = View;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/VirtualizedList/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _VirtualizedList = _interopRequireDefault(require("../../vendor/react-native/VirtualizedList"));
/**
* 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.
*
*
*/
var _default = _VirtualizedList.default;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/YellowBox/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _react = _interopRequireDefault(require("react"));
var _UnimplementedView = _interopRequireDefault(require("../../modules/UnimplementedView"));
/**
* 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.
*
*
*/
function YellowBox(props) {
return /*#__PURE__*/_react.default.createElement(_UnimplementedView.default, props);
}
YellowBox.ignoreWarnings = () => {};
var _default = YellowBox;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/createElement/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _AccessibilityUtil = _interopRequireDefault(require("../../modules/AccessibilityUtil"));
var _createDOMProps = _interopRequireDefault(require("../../modules/createDOMProps"));
var _react = _interopRequireDefault(require("react"));
var _useLocale = require("../../modules/useLocale");
/**
* 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.
*
*
*/
var createElement = (component, props, options) => {
// Use equivalent platform elements where possible.
var accessibilityComponent;
if (component && component.constructor === String) {
accessibilityComponent = _AccessibilityUtil.default.propsToAccessibilityComponent(props);
}
var Component = accessibilityComponent || component;
var domProps = (0, _createDOMProps.default)(Component, props, options);
var element = /*#__PURE__*/_react.default.createElement(Component, domProps);
// Update locale context if element's writing direction prop changes
var elementWithLocaleProvider = domProps.dir ? /*#__PURE__*/_react.default.createElement(_useLocale.LocaleProvider, {
children: element,
direction: domProps.dir,
locale: domProps.lang
}) : element;
return elementWithLocaleProvider;
};
var _default = createElement;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/findNodeHandle/index.js
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _reactDom = require("react-dom");
/**
* 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.
*
*
*/
/**
* @deprecated imperatively finding the DOM element of a react component has been deprecated in React 18.
* You should use ref properties on the component instead.
*/
var findNodeHandle = component => {
var node;
try {
node = (0, _reactDom.findDOMNode)(component);
} catch (e) {}
return node;
};
var _default = findNodeHandle;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/processColor/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _normalizeColors = _interopRequireDefault(require("@react-native/normalize-colors"));
/**
* 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.
*
*
*/
var processColor = color => {
if (color === undefined || color === null) {
return color;
}
// convert number and hex
var int32Color = (0, _normalizeColors.default)(color);
if (int32Color === undefined || int32Color === null) {
return undefined;
}
int32Color = (int32Color << 24 | int32Color >>> 8) >>> 0;
return int32Color;
};
var _default = processColor;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/render/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = renderLegacy;
exports.hydrate = hydrate;
exports.hydrateLegacy = hydrateLegacy;
exports.render = render;
var _reactDom = require("react-dom");
var _client = require("react-dom/client");
var _unmountComponentAtNode = _interopRequireDefault(require("../unmountComponentAtNode"));
var _dom = require("../StyleSheet/dom");
/**
* 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.
*
*
*/
function hydrate(element, root) {
(0, _dom.createSheet)(root);
return (0, _client.hydrateRoot)(root, element);
}
function render(element, root) {
(0, _dom.createSheet)(root);
var reactRoot = (0, _client.createRoot)(root);
reactRoot.render(element);
return reactRoot;
}
function hydrateLegacy(element, root, callback) {
(0, _dom.createSheet)(root);
(0, _reactDom.hydrate)(element, root, callback);
return {
unmount: function unmount() {
return (0, _unmountComponentAtNode.default)(root);
}
};
}
function renderLegacy(element, root, callback) {
(0, _dom.createSheet)(root);
(0, _reactDom.render)(element, root, callback);
return {
unmount: function unmount() {
return (0, _unmountComponentAtNode.default)(root);
}
};
}
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/unmountComponentAtNode/index.js
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _reactDom = require("react-dom");
/**
* 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.
*
*
*/
var _default = _reactDom.unmountComponentAtNode;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/useColorScheme/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = useColorScheme;
var React = _interopRequireWildcard(require("react"));
var _Appearance = _interopRequireDefault(require("../Appearance"));
/**
* 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.
*
*
*/
function useColorScheme() {
var _React$useState = React.useState(_Appearance.default.getColorScheme()),
colorScheme = _React$useState[0],
setColorScheme = _React$useState[1];
React.useEffect(() => {
function listener(appearance) {
setColorScheme(appearance.colorScheme);
}
var _Appearance$addChange = _Appearance.default.addChangeListener(listener),
remove = _Appearance$addChange.remove;
return remove;
});
return colorScheme;
}
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/useLocaleContext/index.js
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _useLocale = require("../../modules/useLocale");
/**
* 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.
*
*
*/
var _default = _useLocale.useLocaleContext;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/exports/useWindowDimensions/index.js
/**
* 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.
*
* @format
*
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = useWindowDimensions;
var _Dimensions = _interopRequireDefault(require("../Dimensions"));
var _react = require("react");
function useWindowDimensions() {
var _useState = (0, _react.useState)(() => _Dimensions.default.get('window')),
dims = _useState[0],
setDims = _useState[1];
(0, _react.useEffect)(() => {
function handleChange(_ref) {
var window = _ref.window;
if (window != null) {
setDims(window);
}
}
_Dimensions.default.addEventListener('change', handleChange);
// We might have missed an update between calling `get` in render and
// `addEventListener` in this handler, so we set it here. If there was
// no change, React will filter out this update as a no-op.
setDims(_Dimensions.default.get('window'));
return () => {
_Dimensions.default.removeEventListener('change', handleChange);
};
}, []);
return dims;
}
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.useWindowDimensions = exports.useLocaleContext = exports.useColorScheme = exports.unstable_createElement = exports.unmountComponentAtNode = exports.render = exports.processColor = exports.findNodeHandle = exports.YellowBox = exports.VirtualizedList = exports.View = exports.Vibration = exports.UIManager = exports.TouchableWithoutFeedback = exports.TouchableOpacity = exports.TouchableNativeFeedback = exports.TouchableHighlight = exports.Touchable = exports.TextInput = exports.Text = exports.Switch = exports.StyleSheet = exports.StatusBar = exports.Share = exports.SectionList = exports.ScrollView = exports.SafeAreaView = exports.RefreshControl = exports.ProgressBar = exports.Pressable = exports.Platform = exports.PixelRatio = exports.Picker = exports.PanResponder = exports.NativeModules = exports.NativeEventEmitter = exports.Modal = exports.LogBox = exports.Linking = exports.LayoutAnimation = exports.KeyboardAvoidingView = exports.Keyboard = exports.InteractionManager = exports.ImageBackground = exports.Image = exports.I18nManager = exports.FlatList = exports.Easing = exports.Dimensions = exports.DeviceEventEmitter = exports.Clipboard = exports.CheckBox = exports.Button = exports.BackHandler = exports.Appearance = exports.AppState = exports.AppRegistry = exports.Animated = exports.Alert = exports.ActivityIndicator = exports.AccessibilityInfo = void 0;
var _createElement = _interopRequireDefault(require("./exports/createElement"));
exports.unstable_createElement = _createElement.default;
var _findNodeHandle = _interopRequireDefault(require("./exports/findNodeHandle"));
exports.findNodeHandle = _findNodeHandle.default;
var _processColor = _interopRequireDefault(require("./exports/processColor"));
exports.processColor = _processColor.default;
var _render = _interopRequireDefault(require("./exports/render"));
exports.render = _render.default;
var _unmountComponentAtNode = _interopRequireDefault(require("./exports/unmountComponentAtNode"));
exports.unmountComponentAtNode = _unmountComponentAtNode.default;
var _NativeModules = _interopRequireDefault(require("./exports/NativeModules"));
exports.NativeModules = _NativeModules.default;
var _AccessibilityInfo = _interopRequireDefault(require("./exports/AccessibilityInfo"));
exports.AccessibilityInfo = _AccessibilityInfo.default;
var _Alert = _interopRequireDefault(require("./exports/Alert"));
exports.Alert = _Alert.default;
var _Animated = _interopRequireDefault(require("./exports/Animated"));
exports.Animated = _Animated.default;
var _Appearance = _interopRequireDefault(require("./exports/Appearance"));
exports.Appearance = _Appearance.default;
var _AppRegistry = _interopRequireDefault(require("./exports/AppRegistry"));
exports.AppRegistry = _AppRegistry.default;
var _AppState = _interopRequireDefault(require("./exports/AppState"));
exports.AppState = _AppState.default;
var _BackHandler = _interopRequireDefault(require("./exports/BackHandler"));
exports.BackHandler = _BackHandler.default;
var _Clipboard = _interopRequireDefault(require("./exports/Clipboard"));
exports.Clipboard = _Clipboard.default;
var _Dimensions = _interopRequireDefault(require("./exports/Dimensions"));
exports.Dimensions = _Dimensions.default;
var _Easing = _interopRequireDefault(require("./exports/Easing"));
exports.Easing = _Easing.default;
var _I18nManager = _interopRequireDefault(require("./exports/I18nManager"));
exports.I18nManager = _I18nManager.default;
var _Keyboard = _interopRequireDefault(require("./exports/Keyboard"));
exports.Keyboard = _Keyboard.default;
var _InteractionManager = _interopRequireDefault(require("./exports/InteractionManager"));
exports.InteractionManager = _InteractionManager.default;
var _LayoutAnimation = _interopRequireDefault(require("./exports/LayoutAnimation"));
exports.LayoutAnimation = _LayoutAnimation.default;
var _Linking = _interopRequireDefault(require("./exports/Linking"));
exports.Linking = _Linking.default;
var _NativeEventEmitter = _interopRequireDefault(require("./exports/NativeEventEmitter"));
exports.NativeEventEmitter = _NativeEventEmitter.default;
var _PanResponder = _interopRequireDefault(require("./exports/PanResponder"));
exports.PanResponder = _PanResponder.default;
var _PixelRatio = _interopRequireDefault(require("./exports/PixelRatio"));
exports.PixelRatio = _PixelRatio.default;
var _Platform = _interopRequireDefault(require("./exports/Platform"));
exports.Platform = _Platform.default;
var _Share = _interopRequireDefault(require("./exports/Share"));
exports.Share = _Share.default;
var _StyleSheet = _interopRequireDefault(require("./exports/StyleSheet"));
exports.StyleSheet = _StyleSheet.default;
var _UIManager = _interopRequireDefault(require("./exports/UIManager"));
exports.UIManager = _UIManager.default;
var _Vibration = _interopRequireDefault(require("./exports/Vibration"));
exports.Vibration = _Vibration.default;
var _ActivityIndicator = _interopRequireDefault(require("./exports/ActivityIndicator"));
exports.ActivityIndicator = _ActivityIndicator.default;
var _Button = _interopRequireDefault(require("./exports/Button"));
exports.Button = _Button.default;
var _CheckBox = _interopRequireDefault(require("./exports/CheckBox"));
exports.CheckBox = _CheckBox.default;
var _FlatList = _interopRequireDefault(require("./exports/FlatList"));
exports.FlatList = _FlatList.default;
var _Image = _interopRequireDefault(require("./exports/Image"));
exports.Image = _Image.default;
var _ImageBackground = _interopRequireDefault(require("./exports/ImageBackground"));
exports.ImageBackground = _ImageBackground.default;
var _KeyboardAvoidingView = _interopRequireDefault(require("./exports/KeyboardAvoidingView"));
exports.KeyboardAvoidingView = _KeyboardAvoidingView.default;
var _Modal = _interopRequireDefault(require("./exports/Modal"));
exports.Modal = _Modal.default;
var _Picker = _interopRequireDefault(require("./exports/Picker"));
exports.Picker = _Picker.default;
var _Pressable = _interopRequireDefault(require("./exports/Pressable"));
exports.Pressable = _Pressable.default;
var _ProgressBar = _interopRequireDefault(require("./exports/ProgressBar"));
exports.ProgressBar = _ProgressBar.default;
var _RefreshControl = _interopRequireDefault(require("./exports/RefreshControl"));
exports.RefreshControl = _RefreshControl.default;
var _SafeAreaView = _interopRequireDefault(require("./exports/SafeAreaView"));
exports.SafeAreaView = _SafeAreaView.default;
var _ScrollView = _interopRequireDefault(require("./exports/ScrollView"));
exports.ScrollView = _ScrollView.default;
var _SectionList = _interopRequireDefault(require("./exports/SectionList"));
exports.SectionList = _SectionList.default;
var _StatusBar = _interopRequireDefault(require("./exports/StatusBar"));
exports.StatusBar = _StatusBar.default;
var _Switch = _interopRequireDefault(require("./exports/Switch"));
exports.Switch = _Switch.default;
var _Text = _interopRequireDefault(require("./exports/Text"));
exports.Text = _Text.default;
var _TextInput = _interopRequireDefault(require("./exports/TextInput"));
exports.TextInput = _TextInput.default;
var _Touchable = _interopRequireDefault(require("./exports/Touchable"));
exports.Touchable = _Touchable.default;
var _TouchableHighlight = _interopRequireDefault(require("./exports/TouchableHighlight"));
exports.TouchableHighlight = _TouchableHighlight.default;
var _TouchableNativeFeedback = _interopRequireDefault(require("./exports/TouchableNativeFeedback"));
exports.TouchableNativeFeedback = _TouchableNativeFeedback.default;
var _TouchableOpacity = _interopRequireDefault(require("./exports/TouchableOpacity"));
exports.TouchableOpacity = _TouchableOpacity.default;
var _TouchableWithoutFeedback = _interopRequireDefault(require("./exports/TouchableWithoutFeedback"));
exports.TouchableWithoutFeedback = _TouchableWithoutFeedback.default;
var _View = _interopRequireDefault(require("./exports/View"));
exports.View = _View.default;
var _VirtualizedList = _interopRequireDefault(require("./exports/VirtualizedList"));
exports.VirtualizedList = _VirtualizedList.default;
var _YellowBox = _interopRequireDefault(require("./exports/YellowBox"));
exports.YellowBox = _YellowBox.default;
var _LogBox = _interopRequireDefault(require("./exports/LogBox"));
exports.LogBox = _LogBox.default;
var _DeviceEventEmitter = _interopRequireDefault(require("./exports/DeviceEventEmitter"));
exports.DeviceEventEmitter = _DeviceEventEmitter.default;
var _useColorScheme = _interopRequireDefault(require("./exports/useColorScheme"));
exports.useColorScheme = _useColorScheme.default;
var _useLocaleContext = _interopRequireDefault(require("./exports/useLocaleContext"));
exports.useLocaleContext = _useLocaleContext.default;
var _useWindowDimensions = _interopRequireDefault(require("./exports/useWindowDimensions"));
exports.useWindowDimensions = _useWindowDimensions.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/AccessibilityUtil/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _isDisabled = _interopRequireDefault(require("./isDisabled"));
var _propsToAccessibilityComponent = _interopRequireDefault(require("./propsToAccessibilityComponent"));
var _propsToAriaRole = _interopRequireDefault(require("./propsToAriaRole"));
/**
* 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.
*
*
*/
var AccessibilityUtil = {
isDisabled: _isDisabled.default,
propsToAccessibilityComponent: _propsToAccessibilityComponent.default,
propsToAriaRole: _propsToAriaRole.default
};
var _default = AccessibilityUtil;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/AccessibilityUtil/isDisabled.js
"use strict";
exports.__esModule = true;
exports.default = void 0;
/**
* 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.
*
*
*/
var isDisabled = props => props.disabled || Array.isArray(props.accessibilityStates) && props.accessibilityStates.indexOf('disabled') > -1;
var _default = isDisabled;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/AccessibilityUtil/propsToAccessibilityComponent.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _propsToAriaRole = _interopRequireDefault(require("./propsToAriaRole"));
/**
* 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.
*
*
*/
var roleComponents = {
article: 'article',
banner: 'header',
blockquote: 'blockquote',
button: 'button',
code: 'code',
complementary: 'aside',
contentinfo: 'footer',
deletion: 'del',
emphasis: 'em',
figure: 'figure',
insertion: 'ins',
form: 'form',
list: 'ul',
listitem: 'li',
main: 'main',
navigation: 'nav',
paragraph: 'p',
region: 'section',
strong: 'strong'
};
var emptyObject = {};
var propsToAccessibilityComponent = function propsToAccessibilityComponent(props) {
if (props === void 0) {
props = emptyObject;
}
// special-case for "label" role which doesn't map to an ARIA role
if (props.accessibilityRole === 'label') {
return 'label';
}
var role = (0, _propsToAriaRole.default)(props);
if (role) {
if (role === 'heading') {
var level = props.accessibilityLevel || props['aria-level'];
if (level != null) {
return "h" + level;
}
return 'h1';
}
return roleComponents[role];
}
};
var _default = propsToAccessibilityComponent;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/AccessibilityUtil/propsToAriaRole.js
"use strict";
exports.__esModule = true;
exports.default = void 0;
/**
* 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.
*
*
*/
var accessibilityRoleToWebRole = {
adjustable: 'slider',
button: 'button',
header: 'heading',
image: 'img',
imagebutton: null,
keyboardkey: null,
label: null,
link: 'link',
none: 'presentation',
search: 'search',
summary: 'region',
text: null
};
var propsToAriaRole = _ref => {
var accessibilityRole = _ref.accessibilityRole,
role = _ref.role;
var _role = role || accessibilityRole;
if (_role) {
var inferredRole = accessibilityRoleToWebRole[_role];
if (inferredRole !== null) {
// ignore roles that don't map to web
return inferredRole || _role;
}
}
};
var _default = propsToAriaRole;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/AssetRegistry/index.js
"use strict";
exports.__esModule = true;
exports.getAssetByID = getAssetByID;
exports.registerAsset = registerAsset;
/**
* 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.
*
*
*/
var assets = [];
function registerAsset(asset) {
// `push` returns new array length, so the first asset will
// get id 1 (not 0) to make the value truthy
return assets.push(asset);
}
function getAssetByID(assetId) {
return assets[assetId - 1];
}
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/ImageLoader/index.js
"use strict";
exports.__esModule = true;
exports.default = exports.ImageUriCache = void 0;
/**
* 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.
*
*
*/
var dataUriPattern = /^data:/;
class ImageUriCache {
static has(uri) {
var entries = ImageUriCache._entries;
var isDataUri = dataUriPattern.test(uri);
return isDataUri || Boolean(entries[uri]);
}
static add(uri) {
var entries = ImageUriCache._entries;
var lastUsedTimestamp = Date.now();
if (entries[uri]) {
entries[uri].lastUsedTimestamp = lastUsedTimestamp;
entries[uri].refCount += 1;
} else {
entries[uri] = {
lastUsedTimestamp,
refCount: 1
};
}
}
static remove(uri) {
var entries = ImageUriCache._entries;
if (entries[uri]) {
entries[uri].refCount -= 1;
}
// Free up entries when the cache is "full"
ImageUriCache._cleanUpIfNeeded();
}
static _cleanUpIfNeeded() {
var entries = ImageUriCache._entries;
var imageUris = Object.keys(entries);
if (imageUris.length + 1 > ImageUriCache._maximumEntries) {
var leastRecentlyUsedKey;
var leastRecentlyUsedEntry;
imageUris.forEach(uri => {
var entry = entries[uri];
if ((!leastRecentlyUsedEntry || entry.lastUsedTimestamp < leastRecentlyUsedEntry.lastUsedTimestamp) && entry.refCount === 0) {
leastRecentlyUsedKey = uri;
leastRecentlyUsedEntry = entry;
}
});
if (leastRecentlyUsedKey) {
delete entries[leastRecentlyUsedKey];
}
}
}
}
exports.ImageUriCache = ImageUriCache;
ImageUriCache._maximumEntries = 256;
ImageUriCache._entries = {};
var id = 0;
var requests = {};
var ImageLoader = {
abort(requestId) {
var image = requests["" + requestId];
if (image) {
image.onerror = null;
image.onload = null;
image = null;
delete requests["" + requestId];
}
},
getSize(uri, success, failure) {
var complete = false;
var interval = setInterval(callback, 16);
var requestId = ImageLoader.load(uri, callback, errorCallback);
function callback() {
var image = requests["" + requestId];
if (image) {
var naturalHeight = image.naturalHeight,
naturalWidth = image.naturalWidth;
if (naturalHeight && naturalWidth) {
success(naturalWidth, naturalHeight);
complete = true;
}
}
if (complete) {
ImageLoader.abort(requestId);
clearInterval(interval);
}
}
function errorCallback() {
if (typeof failure === 'function') {
failure();
}
ImageLoader.abort(requestId);
clearInterval(interval);
}
},
has(uri) {
return ImageUriCache.has(uri);
},
load(uri, onLoad, onError) {
id += 1;
var image = new window.Image();
image.onerror = onError;
image.onload = e => {
// avoid blocking the main thread
var onDecode = () => onLoad({
nativeEvent: e
});
if (typeof image.decode === 'function') {
// Safari currently throws exceptions when decoding svgs.
// We want to catch that error and allow the load handler
// to be forwarded to the onLoad handler in this case
image.decode().then(onDecode, onDecode);
} else {
setTimeout(onDecode, 0);
}
};
image.src = uri;
requests["" + id] = image;
return id;
},
prefetch(uri) {
return new Promise((resolve, reject) => {
ImageLoader.load(uri, () => {
// Add the uri to the cache so it can be immediately displayed when used
// but also immediately remove it to correctly reflect that it has no active references
ImageUriCache.add(uri);
ImageUriCache.remove(uri);
resolve();
}, reject);
});
},
queryCache(uris) {
var result = {};
uris.forEach(u => {
if (ImageUriCache.has(u)) {
result[u] = 'disk/memory';
}
});
return Promise.resolve(result);
}
};
var _default = ImageLoader;
exports.default = _default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/TextInputState/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _UIManager = _interopRequireDefault(require("../../exports/UIManager"));
/**
* 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.
*
*
*/
/**
* This class is responsible for coordinating the "focused"
* state for TextInputs. All calls relating to the keyboard
* should be funneled through here
*/
var TextInputState = {
/**
* Internal state
*/
_currentlyFocusedNode: null,
/**
* Returns the ID of the currently focused text field, if one exists
* If no text field is focused it returns null
*/
currentlyFocusedField() {
if (document.activeElement !== this._currentlyFocusedNode) {
this._currentlyFocusedNode = null;
}
return this._currentlyFocusedNode;
},
/**
* @param {Object} TextInputID id of the text field to focus
* Focuses the specified text field
* noop if the text field was already focused
*/
focusTextInput(textFieldNode) {
if (textFieldNode !== null) {
this._currentlyFocusedNode = textFieldNode;
if (document.activeElement !== textFieldNode) {
_UIManager.default.focus(textFieldNode);
}
}
},
/**
* @param {Object} textFieldNode id of the text field to focus
* Unfocuses the specified text field
* noop if it wasn't focused
*/
blurTextInput(textFieldNode) {
if (textFieldNode !== null) {
this._currentlyFocusedNode = null;
if (document.activeElement === textFieldNode) {
_UIManager.default.blur(textFieldNode);
}
}
}
};
var _default = TextInputState;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/UnimplementedView/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _View = _interopRequireDefault(require("../../exports/View"));
var _react = _interopRequireDefault(require("react"));
/**
* 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.
*
*
*/
/**
* Common implementation for a simple stubbed view.
*/
class UnimplementedView extends _react.default.Component {
render() {
return /*#__PURE__*/_react.default.createElement(_View.default, {
style: [unimplementedViewStyles, this.props.style]
}, this.props.children);
}
}
var unimplementedViewStyles = process.env.NODE_ENV !== 'production' ? {
alignSelf: 'flex-start',
borderColor: 'red',
borderWidth: 1
} : {};
var _default = UnimplementedView;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/addEventListener/index.js
/**
* 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.
*
*
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.addEventListener = addEventListener;
var _canUseDom = _interopRequireDefault(require("../canUseDom"));
var emptyFunction = () => {};
function supportsPassiveEvents() {
var supported = false;
// Check if browser supports event with passive listeners
// https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
if (_canUseDom.default) {
try {
var options = {};
Object.defineProperty(options, 'passive', {
get() {
supported = true;
return false;
}
});
window.addEventListener('test', null, options);
window.removeEventListener('test', null, options);
} catch (e) {}
}
return supported;
}
var canUsePassiveEvents = supportsPassiveEvents();
function getOptions(options) {
if (options == null) {
return false;
}
return canUsePassiveEvents ? options : Boolean(options.capture);
}
/**
* Shim generic API compatibility with ReactDOM's synthetic events, without needing the
* large amount of code ReactDOM uses to do this. Ideally we wouldn't use a synthetic
* event wrapper at all.
*/
function isPropagationStopped() {
return this.cancelBubble;
}
function isDefaultPrevented() {
return this.defaultPrevented;
}
function normalizeEvent(event) {
event.nativeEvent = event;
event.persist = emptyFunction;
event.isDefaultPrevented = isDefaultPrevented;
event.isPropagationStopped = isPropagationStopped;
return event;
}
/**
*
*/
function addEventListener(target, type, listener, options) {
var opts = getOptions(options);
var compatListener = e => listener(normalizeEvent(e));
target.addEventListener(type, compatListener, opts);
return function removeEventListener() {
if (target != null) {
target.removeEventListener(type, compatListener, opts);
}
};
}
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/canUseDom/index.js
"use strict"; exports.__esModule = true; exports.default = void 0; /** * 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. * * */ var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); var _default = canUseDOM; exports.default = _default; module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/createDOMProps/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var _AccessibilityUtil = _interopRequireDefault(require("../AccessibilityUtil"));
var _StyleSheet2 = _interopRequireDefault(require("../../exports/StyleSheet"));
var _warnOnce = require("../warnOnce");
var _excluded = ["aria-activedescendant", "accessibilityActiveDescendant", "aria-atomic", "accessibilityAtomic", "aria-autocomplete", "accessibilityAutoComplete", "aria-busy", "accessibilityBusy", "aria-checked", "accessibilityChecked", "aria-colcount", "accessibilityColumnCount", "aria-colindex", "accessibilityColumnIndex", "aria-colspan", "accessibilityColumnSpan", "aria-controls", "accessibilityControls", "aria-current", "accessibilityCurrent", "aria-describedby", "accessibilityDescribedBy", "aria-details", "accessibilityDetails", "aria-disabled", "accessibilityDisabled", "aria-errormessage", "accessibilityErrorMessage", "aria-expanded", "accessibilityExpanded", "aria-flowto", "accessibilityFlowTo", "aria-haspopup", "accessibilityHasPopup", "aria-hidden", "accessibilityHidden", "aria-invalid", "accessibilityInvalid", "aria-keyshortcuts", "accessibilityKeyShortcuts", "aria-label", "accessibilityLabel", "aria-labelledby", "accessibilityLabelledBy", "aria-level", "accessibilityLevel", "aria-live", "accessibilityLiveRegion", "aria-modal", "accessibilityModal", "aria-multiline", "accessibilityMultiline", "aria-multiselectable", "accessibilityMultiSelectable", "aria-orientation", "accessibilityOrientation", "aria-owns", "accessibilityOwns", "aria-placeholder", "accessibilityPlaceholder", "aria-posinset", "accessibilityPosInSet", "aria-pressed", "accessibilityPressed", "aria-readonly", "accessibilityReadOnly", "aria-required", "accessibilityRequired", "role", "accessibilityRole", "aria-roledescription", "accessibilityRoleDescription", "aria-rowcount", "accessibilityRowCount", "aria-rowindex", "accessibilityRowIndex", "aria-rowspan", "accessibilityRowSpan", "aria-selected", "accessibilitySelected", "aria-setsize", "accessibilitySetSize", "aria-sort", "accessibilitySort", "aria-valuemax", "accessibilityValueMax", "aria-valuemin", "accessibilityValueMin", "aria-valuenow", "accessibilityValueNow", "aria-valuetext", "accessibilityValueText", "dataSet", "focusable", "id", "nativeID", "pointerEvents", "style", "tabIndex", "testID"];
var emptyObject = {};
var hasOwnProperty = Object.prototype.hasOwnProperty;
var isArray = Array.isArray;
var uppercasePattern = /[A-Z]/g;
function toHyphenLower(match) {
return '-' + match.toLowerCase();
}
function hyphenateString(str) {
return str.replace(uppercasePattern, toHyphenLower);
}
function processIDRefList(idRefList) {
return isArray(idRefList) ? idRefList.join(' ') : idRefList;
}
var pointerEventsStyles = _StyleSheet2.default.create({
auto: {
pointerEvents: 'auto'
},
'box-none': {
pointerEvents: 'box-none'
},
'box-only': {
pointerEvents: 'box-only'
},
none: {
pointerEvents: 'none'
}
});
var createDOMProps = (elementType, props, options) => {
if (!props) {
props = emptyObject;
}
var _props = props,
ariaActiveDescendant = _props['aria-activedescendant'],
accessibilityActiveDescendant = _props.accessibilityActiveDescendant,
ariaAtomic = _props['aria-atomic'],
accessibilityAtomic = _props.accessibilityAtomic,
ariaAutoComplete = _props['aria-autocomplete'],
accessibilityAutoComplete = _props.accessibilityAutoComplete,
ariaBusy = _props['aria-busy'],
accessibilityBusy = _props.accessibilityBusy,
ariaChecked = _props['aria-checked'],
accessibilityChecked = _props.accessibilityChecked,
ariaColumnCount = _props['aria-colcount'],
accessibilityColumnCount = _props.accessibilityColumnCount,
ariaColumnIndex = _props['aria-colindex'],
accessibilityColumnIndex = _props.accessibilityColumnIndex,
ariaColumnSpan = _props['aria-colspan'],
accessibilityColumnSpan = _props.accessibilityColumnSpan,
ariaControls = _props['aria-controls'],
accessibilityControls = _props.accessibilityControls,
ariaCurrent = _props['aria-current'],
accessibilityCurrent = _props.accessibilityCurrent,
ariaDescribedBy = _props['aria-describedby'],
accessibilityDescribedBy = _props.accessibilityDescribedBy,
ariaDetails = _props['aria-details'],
accessibilityDetails = _props.accessibilityDetails,
ariaDisabled = _props['aria-disabled'],
accessibilityDisabled = _props.accessibilityDisabled,
ariaErrorMessage = _props['aria-errormessage'],
accessibilityErrorMessage = _props.accessibilityErrorMessage,
ariaExpanded = _props['aria-expanded'],
accessibilityExpanded = _props.accessibilityExpanded,
ariaFlowTo = _props['aria-flowto'],
accessibilityFlowTo = _props.accessibilityFlowTo,
ariaHasPopup = _props['aria-haspopup'],
accessibilityHasPopup = _props.accessibilityHasPopup,
ariaHidden = _props['aria-hidden'],
accessibilityHidden = _props.accessibilityHidden,
ariaInvalid = _props['aria-invalid'],
accessibilityInvalid = _props.accessibilityInvalid,
ariaKeyShortcuts = _props['aria-keyshortcuts'],
accessibilityKeyShortcuts = _props.accessibilityKeyShortcuts,
ariaLabel = _props['aria-label'],
accessibilityLabel = _props.accessibilityLabel,
ariaLabelledBy = _props['aria-labelledby'],
accessibilityLabelledBy = _props.accessibilityLabelledBy,
ariaLevel = _props['aria-level'],
accessibilityLevel = _props.accessibilityLevel,
ariaLive = _props['aria-live'],
accessibilityLiveRegion = _props.accessibilityLiveRegion,
ariaModal = _props['aria-modal'],
accessibilityModal = _props.accessibilityModal,
ariaMultiline = _props['aria-multiline'],
accessibilityMultiline = _props.accessibilityMultiline,
ariaMultiSelectable = _props['aria-multiselectable'],
accessibilityMultiSelectable = _props.accessibilityMultiSelectable,
ariaOrientation = _props['aria-orientation'],
accessibilityOrientation = _props.accessibilityOrientation,
ariaOwns = _props['aria-owns'],
accessibilityOwns = _props.accessibilityOwns,
ariaPlaceholder = _props['aria-placeholder'],
accessibilityPlaceholder = _props.accessibilityPlaceholder,
ariaPosInSet = _props['aria-posinset'],
accessibilityPosInSet = _props.accessibilityPosInSet,
ariaPressed = _props['aria-pressed'],
accessibilityPressed = _props.accessibilityPressed,
ariaReadOnly = _props['aria-readonly'],
accessibilityReadOnly = _props.accessibilityReadOnly,
ariaRequired = _props['aria-required'],
accessibilityRequired = _props.accessibilityRequired,
ariaRole = _props.role,
accessibilityRole = _props.accessibilityRole,
ariaRoleDescription = _props['aria-roledescription'],
accessibilityRoleDescription = _props.accessibilityRoleDescription,
ariaRowCount = _props['aria-rowcount'],
accessibilityRowCount = _props.accessibilityRowCount,
ariaRowIndex = _props['aria-rowindex'],
accessibilityRowIndex = _props.accessibilityRowIndex,
ariaRowSpan = _props['aria-rowspan'],
accessibilityRowSpan = _props.accessibilityRowSpan,
ariaSelected = _props['aria-selected'],
accessibilitySelected = _props.accessibilitySelected,
ariaSetSize = _props['aria-setsize'],
accessibilitySetSize = _props.accessibilitySetSize,
ariaSort = _props['aria-sort'],
accessibilitySort = _props.accessibilitySort,
ariaValueMax = _props['aria-valuemax'],
accessibilityValueMax = _props.accessibilityValueMax,
ariaValueMin = _props['aria-valuemin'],
accessibilityValueMin = _props.accessibilityValueMin,
ariaValueNow = _props['aria-valuenow'],
accessibilityValueNow = _props.accessibilityValueNow,
ariaValueText = _props['aria-valuetext'],
accessibilityValueText = _props.accessibilityValueText,
dataSet = _props.dataSet,
focusable = _props.focusable,
id = _props.id,
nativeID = _props.nativeID,
pointerEvents = _props.pointerEvents,
style = _props.style,
tabIndex = _props.tabIndex,
testID = _props.testID,
domProps = (0, _objectWithoutPropertiesLoose2.default)(_props, _excluded);
if (accessibilityDisabled != null) {
(0, _warnOnce.warnOnce)('accessibilityDisabled', "accessibilityDisabled is deprecated.");
}
var disabled = ariaDisabled || accessibilityDisabled;
var role = _AccessibilityUtil.default.propsToAriaRole(props);
// ACCESSIBILITY
if (accessibilityActiveDescendant != null) {
(0, _warnOnce.warnOnce)('accessibilityActiveDescendant', "accessibilityActiveDescendant is deprecated. Use aria-activedescendant.");
}
var _ariaActiveDescendant = ariaActiveDescendant != null ? ariaActiveDescendant : accessibilityActiveDescendant;
if (_ariaActiveDescendant != null) {
domProps['aria-activedescendant'] = _ariaActiveDescendant;
}
if (accessibilityAtomic != null) {
(0, _warnOnce.warnOnce)('accessibilityAtomic', "accessibilityAtomic is deprecated. Use aria-atomic.");
}
var _ariaAtomic = ariaAtomic != null ? ariaActiveDescendant : accessibilityAtomic;
if (_ariaAtomic != null) {
domProps['aria-atomic'] = _ariaAtomic;
}
if (accessibilityAutoComplete != null) {
(0, _warnOnce.warnOnce)('accessibilityAutoComplete', "accessibilityAutoComplete is deprecated. Use aria-autocomplete.");
}
var _ariaAutoComplete = ariaAutoComplete != null ? ariaAutoComplete : accessibilityAutoComplete;
if (_ariaAutoComplete != null) {
domProps['aria-autocomplete'] = _ariaAutoComplete;
}
if (accessibilityBusy != null) {
(0, _warnOnce.warnOnce)('accessibilityBusy', "accessibilityBusy is deprecated. Use aria-busy.");
}
var _ariaBusy = ariaBusy != null ? ariaBusy : accessibilityBusy;
if (_ariaBusy != null) {
domProps['aria-busy'] = _ariaBusy;
}
if (accessibilityChecked != null) {
(0, _warnOnce.warnOnce)('accessibilityChecked', "accessibilityChecked is deprecated. Use aria-checked.");
}
var _ariaChecked = ariaChecked != null ? ariaChecked : accessibilityChecked;
if (_ariaChecked != null) {
domProps['aria-checked'] = _ariaChecked;
}
if (accessibilityColumnCount != null) {
(0, _warnOnce.warnOnce)('accessibilityColumnCount', "accessibilityColumnCount is deprecated. Use aria-colcount.");
}
var _ariaColumnCount = ariaColumnCount != null ? ariaColumnCount : accessibilityColumnCount;
if (_ariaColumnCount != null) {
domProps['aria-colcount'] = _ariaColumnCount;
}
if (accessibilityColumnIndex != null) {
(0, _warnOnce.warnOnce)('accessibilityColumnIndex', "accessibilityColumnIndex is deprecated. Use aria-colindex.");
}
var _ariaColumnIndex = ariaColumnIndex != null ? ariaColumnIndex : accessibilityColumnIndex;
if (_ariaColumnIndex != null) {
domProps['aria-colindex'] = _ariaColumnIndex;
}
if (accessibilityColumnSpan != null) {
(0, _warnOnce.warnOnce)('accessibilityColumnSpan', "accessibilityColumnSpan is deprecated. Use aria-colspan.");
}
var _ariaColumnSpan = ariaColumnSpan != null ? ariaColumnSpan : accessibilityColumnSpan;
if (_ariaColumnSpan != null) {
domProps['aria-colspan'] = _ariaColumnSpan;
}
if (accessibilityControls != null) {
(0, _warnOnce.warnOnce)('accessibilityControls', "accessibilityControls is deprecated. Use aria-controls.");
}
var _ariaControls = ariaControls != null ? ariaControls : accessibilityControls;
if (_ariaControls != null) {
domProps['aria-controls'] = processIDRefList(_ariaControls);
}
if (accessibilityCurrent != null) {
(0, _warnOnce.warnOnce)('accessibilityCurrent', "accessibilityCurrent is deprecated. Use aria-current.");
}
var _ariaCurrent = ariaCurrent != null ? ariaCurrent : accessibilityCurrent;
if (_ariaCurrent != null) {
domProps['aria-current'] = _ariaCurrent;
}
if (accessibilityDescribedBy != null) {
(0, _warnOnce.warnOnce)('accessibilityDescribedBy', "accessibilityDescribedBy is deprecated. Use aria-describedby.");
}
var _ariaDescribedBy = ariaDescribedBy != null ? ariaDescribedBy : accessibilityDescribedBy;
if (_ariaDescribedBy != null) {
domProps['aria-describedby'] = processIDRefList(_ariaDescribedBy);
}
if (accessibilityDetails != null) {
(0, _warnOnce.warnOnce)('accessibilityDetails', "accessibilityDetails is deprecated. Use aria-details.");
}
var _ariaDetails = ariaDetails != null ? ariaDetails : accessibilityDetails;
if (_ariaDetails != null) {
domProps['aria-details'] = _ariaDetails;
}
if (disabled === true) {
domProps['aria-disabled'] = true;
// Enhance with native semantics
if (elementType === 'button' || elementType === 'form' || elementType === 'input' || elementType === 'select' || elementType === 'textarea') {
domProps.disabled = true;
}
}
if (accessibilityErrorMessage != null) {
(0, _warnOnce.warnOnce)('accessibilityErrorMessage', "accessibilityErrorMessage is deprecated. Use aria-errormessage.");
}
var _ariaErrorMessage = ariaErrorMessage != null ? ariaErrorMessage : accessibilityErrorMessage;
if (_ariaErrorMessage != null) {
domProps['aria-errormessage'] = _ariaErrorMessage;
}
if (accessibilityExpanded != null) {
(0, _warnOnce.warnOnce)('accessibilityExpanded', "accessibilityExpanded is deprecated. Use aria-expanded.");
}
var _ariaExpanded = ariaExpanded != null ? ariaExpanded : accessibilityExpanded;
if (_ariaExpanded != null) {
domProps['aria-expanded'] = _ariaExpanded;
}
if (accessibilityFlowTo != null) {
(0, _warnOnce.warnOnce)('accessibilityFlowTo', "accessibilityFlowTo is deprecated. Use aria-flowto.");
}
var _ariaFlowTo = ariaFlowTo != null ? ariaFlowTo : accessibilityFlowTo;
if (_ariaFlowTo != null) {
domProps['aria-flowto'] = processIDRefList(_ariaFlowTo);
}
if (accessibilityHasPopup != null) {
(0, _warnOnce.warnOnce)('accessibilityHasPopup', "accessibilityHasPopup is deprecated. Use aria-haspopup.");
}
var _ariaHasPopup = ariaHasPopup != null ? ariaHasPopup : accessibilityHasPopup;
if (_ariaHasPopup != null) {
domProps['aria-haspopup'] = _ariaHasPopup;
}
if (accessibilityHidden != null) {
(0, _warnOnce.warnOnce)('accessibilityHidden', "accessibilityHidden is deprecated. Use aria-hidden.");
}
var _ariaHidden = ariaHidden != null ? ariaHidden : accessibilityHidden;
if (_ariaHidden === true) {
domProps['aria-hidden'] = _ariaHidden;
}
if (accessibilityInvalid != null) {
(0, _warnOnce.warnOnce)('accessibilityInvalid', "accessibilityInvalid is deprecated. Use aria-invalid.");
}
var _ariaInvalid = ariaInvalid != null ? ariaInvalid : accessibilityInvalid;
if (_ariaInvalid != null) {
domProps['aria-invalid'] = _ariaInvalid;
}
if (accessibilityKeyShortcuts != null) {
(0, _warnOnce.warnOnce)('accessibilityKeyShortcuts', "accessibilityKeyShortcuts is deprecated. Use aria-keyshortcuts.");
}
var _ariaKeyShortcuts = ariaKeyShortcuts != null ? ariaKeyShortcuts : accessibilityKeyShortcuts;
if (_ariaKeyShortcuts != null) {
domProps['aria-keyshortcuts'] = processIDRefList(_ariaKeyShortcuts);
}
if (accessibilityLabel != null) {
(0, _warnOnce.warnOnce)('accessibilityLabel', "accessibilityLabel is deprecated. Use aria-label.");
}
var _ariaLabel = ariaLabel != null ? ariaLabel : accessibilityLabel;
if (_ariaLabel != null) {
domProps['aria-label'] = _ariaLabel;
}
if (accessibilityLabelledBy != null) {
(0, _warnOnce.warnOnce)('accessibilityLabelledBy', "accessibilityLabelledBy is deprecated. Use aria-labelledby.");
}
var _ariaLabelledBy = ariaLabelledBy != null ? ariaLabelledBy : accessibilityLabelledBy;
if (_ariaLabelledBy != null) {
domProps['aria-labelledby'] = processIDRefList(_ariaLabelledBy);
}
if (accessibilityLevel != null) {
(0, _warnOnce.warnOnce)('accessibilityLevel', "accessibilityLevel is deprecated. Use aria-level.");
}
var _ariaLevel = ariaLevel != null ? ariaLevel : accessibilityLevel;
if (_ariaLevel != null) {
domProps['aria-level'] = _ariaLevel;
}
if (accessibilityLiveRegion != null) {
(0, _warnOnce.warnOnce)('accessibilityLiveRegion', "accessibilityLiveRegion is deprecated. Use aria-live.");
}
var _ariaLive = ariaLive != null ? ariaLive : accessibilityLiveRegion;
if (_ariaLive != null) {
domProps['aria-live'] = _ariaLive === 'none' ? 'off' : _ariaLive;
}
if (accessibilityModal != null) {
(0, _warnOnce.warnOnce)('accessibilityModal', "accessibilityModal is deprecated. Use aria-modal.");
}
var _ariaModal = ariaModal != null ? ariaModal : accessibilityModal;
if (_ariaModal != null) {
domProps['aria-modal'] = _ariaModal;
}
if (accessibilityMultiline != null) {
(0, _warnOnce.warnOnce)('accessibilityMultiline', "accessibilityMultiline is deprecated. Use aria-multiline.");
}
var _ariaMultiline = ariaMultiline != null ? ariaMultiline : accessibilityMultiline;
if (_ariaMultiline != null) {
domProps['aria-multiline'] = _ariaMultiline;
}
if (accessibilityMultiSelectable != null) {
(0, _warnOnce.warnOnce)('accessibilityMultiSelectable', "accessibilityMultiSelectable is deprecated. Use aria-multiselectable.");
}
var _ariaMultiSelectable = ariaMultiSelectable != null ? ariaMultiSelectable : accessibilityMultiSelectable;
if (_ariaMultiSelectable != null) {
domProps['aria-multiselectable'] = _ariaMultiSelectable;
}
if (accessibilityOrientation != null) {
(0, _warnOnce.warnOnce)('accessibilityOrientation', "accessibilityOrientation is deprecated. Use aria-orientation.");
}
var _ariaOrientation = ariaOrientation != null ? ariaOrientation : accessibilityOrientation;
if (_ariaOrientation != null) {
domProps['aria-orientation'] = _ariaOrientation;
}
if (accessibilityOwns != null) {
(0, _warnOnce.warnOnce)('accessibilityOwns', "accessibilityOwns is deprecated. Use aria-owns.");
}
var _ariaOwns = ariaOwns != null ? ariaOwns : accessibilityOwns;
if (_ariaOwns != null) {
domProps['aria-owns'] = processIDRefList(_ariaOwns);
}
if (accessibilityPlaceholder != null) {
(0, _warnOnce.warnOnce)('accessibilityPlaceholder', "accessibilityPlaceholder is deprecated. Use aria-placeholder.");
}
var _ariaPlaceholder = ariaPlaceholder != null ? ariaPlaceholder : accessibilityPlaceholder;
if (_ariaPlaceholder != null) {
domProps['aria-placeholder'] = _ariaPlaceholder;
}
if (accessibilityPosInSet != null) {
(0, _warnOnce.warnOnce)('accessibilityPosInSet', "accessibilityPosInSet is deprecated. Use aria-posinset.");
}
var _ariaPosInSet = ariaPosInSet != null ? ariaPosInSet : accessibilityPosInSet;
if (_ariaPosInSet != null) {
domProps['aria-posinset'] = _ariaPosInSet;
}
if (accessibilityPressed != null) {
(0, _warnOnce.warnOnce)('accessibilityPressed', "accessibilityPressed is deprecated. Use aria-pressed.");
}
var _ariaPressed = ariaPressed != null ? ariaPressed : accessibilityPressed;
if (_ariaPressed != null) {
domProps['aria-pressed'] = _ariaPressed;
}
if (accessibilityReadOnly != null) {
(0, _warnOnce.warnOnce)('accessibilityReadOnly', "accessibilityReadOnly is deprecated. Use aria-readonly.");
}
var _ariaReadOnly = ariaReadOnly != null ? ariaReadOnly : accessibilityReadOnly;
if (_ariaReadOnly != null) {
domProps['aria-readonly'] = _ariaReadOnly;
// Enhance with native semantics
if (elementType === 'input' || elementType === 'select' || elementType === 'textarea') {
domProps.readOnly = true;
}
}
if (accessibilityRequired != null) {
(0, _warnOnce.warnOnce)('accessibilityRequired', "accessibilityRequired is deprecated. Use aria-required.");
}
var _ariaRequired = ariaRequired != null ? ariaRequired : accessibilityRequired;
if (_ariaRequired != null) {
domProps['aria-required'] = _ariaRequired;
// Enhance with native semantics
if (elementType === 'input' || elementType === 'select' || elementType === 'textarea') {
domProps.required = accessibilityRequired;
}
}
if (accessibilityRole != null) {
(0, _warnOnce.warnOnce)('accessibilityRole', "accessibilityRole is deprecated. Use role.");
}
if (role != null) {
// 'presentation' synonym has wider browser support
domProps['role'] = role === 'none' ? 'presentation' : role;
}
if (accessibilityRoleDescription != null) {
(0, _warnOnce.warnOnce)('accessibilityRoleDescription', "accessibilityRoleDescription is deprecated. Use aria-roledescription.");
}
var _ariaRoleDescription = ariaRoleDescription != null ? ariaRoleDescription : accessibilityRoleDescription;
if (_ariaRoleDescription != null) {
domProps['aria-roledescription'] = _ariaRoleDescription;
}
if (accessibilityRowCount != null) {
(0, _warnOnce.warnOnce)('accessibilityRowCount', "accessibilityRowCount is deprecated. Use aria-rowcount.");
}
var _ariaRowCount = ariaRowCount != null ? ariaRowCount : accessibilityRowCount;
if (_ariaRowCount != null) {
domProps['aria-rowcount'] = _ariaRowCount;
}
if (accessibilityRowIndex != null) {
(0, _warnOnce.warnOnce)('accessibilityRowIndex', "accessibilityRowIndex is deprecated. Use aria-rowindex.");
}
var _ariaRowIndex = ariaRowIndex != null ? ariaRowIndex : accessibilityRowIndex;
if (_ariaRowIndex != null) {
domProps['aria-rowindex'] = _ariaRowIndex;
}
if (accessibilityRowSpan != null) {
(0, _warnOnce.warnOnce)('accessibilityRowSpan', "accessibilityRowSpan is deprecated. Use aria-rowspan.");
}
var _ariaRowSpan = ariaRowSpan != null ? ariaRowSpan : accessibilityRowSpan;
if (_ariaRowSpan != null) {
domProps['aria-rowspan'] = _ariaRowSpan;
}
if (accessibilitySelected != null) {
(0, _warnOnce.warnOnce)('accessibilitySelected', "accessibilitySelected is deprecated. Use aria-selected.");
}
var _ariaSelected = ariaSelected != null ? ariaSelected : accessibilitySelected;
if (_ariaSelected != null) {
domProps['aria-selected'] = _ariaSelected;
}
if (accessibilitySetSize != null) {
(0, _warnOnce.warnOnce)('accessibilitySetSize', "accessibilitySetSize is deprecated. Use aria-setsize.");
}
var _ariaSetSize = ariaSetSize != null ? ariaSetSize : accessibilitySetSize;
if (_ariaSetSize != null) {
domProps['aria-setsize'] = _ariaSetSize;
}
if (accessibilitySort != null) {
(0, _warnOnce.warnOnce)('accessibilitySort', "accessibilitySort is deprecated. Use aria-sort.");
}
var _ariaSort = ariaSort != null ? ariaSort : accessibilitySort;
if (_ariaSort != null) {
domProps['aria-sort'] = _ariaSort;
}
if (accessibilityValueMax != null) {
(0, _warnOnce.warnOnce)('accessibilityValueMax', "accessibilityValueMax is deprecated. Use aria-valuemax.");
}
var _ariaValueMax = ariaValueMax != null ? ariaValueMax : accessibilityValueMax;
if (_ariaValueMax != null) {
domProps['aria-valuemax'] = _ariaValueMax;
}
if (accessibilityValueMin != null) {
(0, _warnOnce.warnOnce)('accessibilityValueMin', "accessibilityValueMin is deprecated. Use aria-valuemin.");
}
var _ariaValueMin = ariaValueMin != null ? ariaValueMin : accessibilityValueMin;
if (_ariaValueMin != null) {
domProps['aria-valuemin'] = _ariaValueMin;
}
if (accessibilityValueNow != null) {
(0, _warnOnce.warnOnce)('accessibilityValueNow', "accessibilityValueNow is deprecated. Use aria-valuenow.");
}
var _ariaValueNow = ariaValueNow != null ? ariaValueNow : accessibilityValueNow;
if (_ariaValueNow != null) {
domProps['aria-valuenow'] = _ariaValueNow;
}
if (accessibilityValueText != null) {
(0, _warnOnce.warnOnce)('accessibilityValueText', "accessibilityValueText is deprecated. Use aria-valuetext.");
}
var _ariaValueText = ariaValueText != null ? ariaValueText : accessibilityValueText;
if (_ariaValueText != null) {
domProps['aria-valuetext'] = _ariaValueText;
}
// "dataSet" replaced with "data-*"
if (dataSet != null) {
for (var dataProp in dataSet) {
if (hasOwnProperty.call(dataSet, dataProp)) {
var dataName = hyphenateString(dataProp);
var dataValue = dataSet[dataProp];
if (dataValue != null) {
domProps["data-" + dataName] = dataValue;
}
}
}
}
// FOCUS
if (tabIndex === 0 || tabIndex === '0' || tabIndex === -1 || tabIndex === '-1') {
domProps.tabIndex = tabIndex;
} else {
if (focusable != null) {
(0, _warnOnce.warnOnce)('focusable', "focusable is deprecated.");
}
// "focusable" indicates that an element may be a keyboard tab-stop.
if (focusable === false) {
domProps.tabIndex = '-1';
}
if (
// These native elements are keyboard focusable by default
elementType === 'a' || elementType === 'button' || elementType === 'input' || elementType === 'select' || elementType === 'textarea') {
if (focusable === false || accessibilityDisabled === true) {
domProps.tabIndex = '-1';
}
} else if (
// These roles are made keyboard focusable by default
role === 'button' || role === 'checkbox' || role === 'link' || role === 'radio' || role === 'textbox' || role === 'switch') {
if (focusable !== false) {
domProps.tabIndex = '0';
}
} else {
// Everything else must explicitly set the prop
if (focusable === true) {
domProps.tabIndex = '0';
}
}
}
// Resolve styles
if (pointerEvents != null) {
(0, _warnOnce.warnOnce)('pointerEvents', "props.pointerEvents is deprecated. Use style.pointerEvents");
}
var _StyleSheet = (0, _StyleSheet2.default)([style, pointerEvents && pointerEventsStyles[pointerEvents]], (0, _objectSpread2.default)({
writingDirection: 'ltr'
}, options)),
className = _StyleSheet[0],
inlineStyle = _StyleSheet[1];
if (className) {
domProps.className = className;
}
if (inlineStyle) {
domProps.style = inlineStyle;
}
// OTHER
// Native element ID
if (nativeID != null) {
(0, _warnOnce.warnOnce)('nativeID', "nativeID is deprecated. Use id.");
}
var _id = id != null ? id : nativeID;
if (_id != null) {
domProps.id = _id;
}
// Automated test IDs
if (testID != null) {
domProps['data-testid'] = testID;
}
if (domProps.type == null && elementType === 'button') {
domProps.type = 'button';
}
return domProps;
};
var _default = createDOMProps;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/dismissKeyboard/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _TextInputState = _interopRequireDefault(require("../TextInputState"));
/**
* 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.
*
*
*/
var dismissKeyboard = () => {
_TextInputState.default.blurTextInput(_TextInputState.default.currentlyFocusedField());
};
var _default = dismissKeyboard;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/forwardedProps/index.js
"use strict";
exports.__esModule = true;
exports.touchProps = exports.styleProps = exports.mouseProps = exports.keyboardProps = exports.focusProps = exports.defaultProps = exports.clickProps = exports.accessibilityProps = void 0;
/**
* 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.
*
*
*/
var defaultProps = {
children: true,
dataSet: true,
dir: true,
id: true,
ref: true,
suppressHydrationWarning: true,
tabIndex: true,
testID: true,
// @deprecated
focusable: true,
nativeID: true
};
exports.defaultProps = defaultProps;
var accessibilityProps = {
'aria-activedescendant': true,
'aria-atomic': true,
'aria-autocomplete': true,
'aria-busy': true,
'aria-checked': true,
'aria-colcount': true,
'aria-colindex': true,
'aria-colspan': true,
'aria-controls': true,
'aria-current': true,
'aria-describedby': true,
'aria-details': true,
'aria-disabled': true,
'aria-errormessage': true,
'aria-expanded': true,
'aria-flowto': true,
'aria-haspopup': true,
'aria-hidden': true,
'aria-invalid': true,
'aria-keyshortcuts': true,
'aria-label': true,
'aria-labelledby': true,
'aria-level': true,
'aria-live': true,
'aria-modal': true,
'aria-multiline': true,
'aria-multiselectable': true,
'aria-orientation': true,
'aria-owns': true,
'aria-placeholder': true,
'aria-posinset': true,
'aria-pressed': true,
'aria-readonly': true,
'aria-required': true,
role: true,
'aria-roledescription': true,
'aria-rowcount': true,
'aria-rowindex': true,
'aria-rowspan': true,
'aria-selected': true,
'aria-setsize': true,
'aria-sort': true,
'aria-valuemax': true,
'aria-valuemin': true,
'aria-valuenow': true,
'aria-valuetext': true,
// @deprecated
accessibilityActiveDescendant: true,
accessibilityAtomic: true,
accessibilityAutoComplete: true,
accessibilityBusy: true,
accessibilityChecked: true,
accessibilityColumnCount: true,
accessibilityColumnIndex: true,
accessibilityColumnSpan: true,
accessibilityControls: true,
accessibilityCurrent: true,
accessibilityDescribedBy: true,
accessibilityDetails: true,
accessibilityDisabled: true,
accessibilityErrorMessage: true,
accessibilityExpanded: true,
accessibilityFlowTo: true,
accessibilityHasPopup: true,
accessibilityHidden: true,
accessibilityInvalid: true,
accessibilityKeyShortcuts: true,
accessibilityLabel: true,
accessibilityLabelledBy: true,
accessibilityLevel: true,
accessibilityLiveRegion: true,
accessibilityModal: true,
accessibilityMultiline: true,
accessibilityMultiSelectable: true,
accessibilityOrientation: true,
accessibilityOwns: true,
accessibilityPlaceholder: true,
accessibilityPosInSet: true,
accessibilityPressed: true,
accessibilityReadOnly: true,
accessibilityRequired: true,
accessibilityRole: true,
accessibilityRoleDescription: true,
accessibilityRowCount: true,
accessibilityRowIndex: true,
accessibilityRowSpan: true,
accessibilitySelected: true,
accessibilitySetSize: true,
accessibilitySort: true,
accessibilityValueMax: true,
accessibilityValueMin: true,
accessibilityValueNow: true,
accessibilityValueText: true
};
exports.accessibilityProps = accessibilityProps;
var clickProps = {
onClick: true,
onAuxClick: true,
onContextMenu: true,
onGotPointerCapture: true,
onLostPointerCapture: true,
onPointerCancel: true,
onPointerDown: true,
onPointerEnter: true,
onPointerMove: true,
onPointerLeave: true,
onPointerOut: true,
onPointerOver: true,
onPointerUp: true
};
exports.clickProps = clickProps;
var focusProps = {
onBlur: true,
onFocus: true
};
exports.focusProps = focusProps;
var keyboardProps = {
onKeyDown: true,
onKeyDownCapture: true,
onKeyUp: true,
onKeyUpCapture: true
};
exports.keyboardProps = keyboardProps;
var mouseProps = {
onMouseDown: true,
onMouseEnter: true,
onMouseLeave: true,
onMouseMove: true,
onMouseOver: true,
onMouseOut: true,
onMouseUp: true
};
exports.mouseProps = mouseProps;
var touchProps = {
onTouchCancel: true,
onTouchCancelCapture: true,
onTouchEnd: true,
onTouchEndCapture: true,
onTouchMove: true,
onTouchMoveCapture: true,
onTouchStart: true,
onTouchStartCapture: true
};
exports.touchProps = touchProps;
var styleProps = {
style: true
};
exports.styleProps = styleProps;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/getBoundingClientRect/index.js
"use strict";
exports.__esModule = true;
exports.default = void 0;
/**
* 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.
*
*
*/
var getBoundingClientRect = node => {
if (node != null) {
var isElement = node.nodeType === 1; /* Node.ELEMENT_NODE */
if (isElement && typeof node.getBoundingClientRect === 'function') {
return node.getBoundingClientRect();
}
}
};
var _default = getBoundingClientRect;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/isSelectionValid/index.js
"use strict";
exports.__esModule = true;
exports.default = isSelectionValid;
/**
* 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.
*
*
*/
function isSelectionValid() {
var selection = window.getSelection();
var string = selection.toString();
var anchorNode = selection.anchorNode;
var focusNode = selection.focusNode;
var isTextNode = anchorNode && anchorNode.nodeType === window.Node.TEXT_NODE || focusNode && focusNode.nodeType === window.Node.TEXT_NODE;
return string.length >= 1 && string !== '\n' && isTextNode;
}
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/isWebColor/index.js
"use strict";
exports.__esModule = true;
exports.default = void 0;
/**
* 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.
*
*
*/
var isWebColor = color => color === 'currentcolor' || color === 'currentColor' || color === 'inherit' || color.indexOf('var(') === 0;
var _default = isWebColor;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/mergeRefs/index.js
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = mergeRefs;
var React = _interopRequireWildcard(require("react"));
/**
* 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.
*
*
*/
function mergeRefs() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return function forwardRef(node) {
args.forEach(ref => {
if (ref == null) {
return;
}
if (typeof ref === 'function') {
ref(node);
return;
}
if (typeof ref === 'object') {
ref.current = node;
return;
}
console.error("mergeRefs cannot handle Refs of type boolean, number or string, received ref " + String(ref));
});
};
}
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/modality/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.addModalityListener = addModalityListener;
exports.getActiveModality = getActiveModality;
exports.getModality = getModality;
exports.testOnly_resetActiveModality = testOnly_resetActiveModality;
var _addEventListener = require("../addEventListener");
var _canUseDom = _interopRequireDefault(require("../canUseDom"));
/**
* 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.
*
*
*/
var supportsPointerEvent = () => !!(typeof window !== 'undefined' && window.PointerEvent != null);
var activeModality = 'keyboard';
var modality = 'keyboard';
var previousModality;
var previousActiveModality;
var isEmulatingMouseEvents = false;
var listeners = new Set();
var KEYBOARD = 'keyboard';
var MOUSE = 'mouse';
var TOUCH = 'touch';
var BLUR = 'blur';
var CONTEXTMENU = 'contextmenu';
var FOCUS = 'focus';
var KEYDOWN = 'keydown';
var MOUSEDOWN = 'mousedown';
var MOUSEMOVE = 'mousemove';
var MOUSEUP = 'mouseup';
var POINTERDOWN = 'pointerdown';
var POINTERMOVE = 'pointermove';
var SCROLL = 'scroll';
var SELECTIONCHANGE = 'selectionchange';
var TOUCHCANCEL = 'touchcancel';
var TOUCHMOVE = 'touchmove';
var TOUCHSTART = 'touchstart';
var VISIBILITYCHANGE = 'visibilitychange';
var bubbleOptions = {
passive: true
};
var captureOptions = {
capture: true,
passive: true
};
function restoreModality() {
if (previousModality != null || previousActiveModality != null) {
if (previousModality != null) {
modality = previousModality;
previousModality = null;
}
if (previousActiveModality != null) {
activeModality = previousActiveModality;
previousActiveModality = null;
}
callListeners();
}
}
function onBlurWindow() {
previousModality = modality;
previousActiveModality = activeModality;
activeModality = KEYBOARD;
modality = KEYBOARD;
callListeners();
// for fallback events
isEmulatingMouseEvents = false;
}
function onFocusWindow() {
restoreModality();
}
function onKeyDown(event) {
if (event.metaKey || event.altKey || event.ctrlKey) {
return;
}
if (modality !== KEYBOARD) {
modality = KEYBOARD;
activeModality = KEYBOARD;
callListeners();
}
}
function onVisibilityChange() {
if (document.visibilityState !== 'hidden') {
restoreModality();
}
}
function onPointerish(event) {
var eventType = event.type;
if (supportsPointerEvent()) {
if (eventType === POINTERDOWN) {
if (activeModality !== event.pointerType) {
modality = event.pointerType;
activeModality = event.pointerType;
callListeners();
}
return;
}
if (eventType === POINTERMOVE) {
if (modality !== event.pointerType) {
modality = event.pointerType;
callListeners();
}
return;
}
}
// Fallback for non-PointerEvent environment
else {
if (!isEmulatingMouseEvents) {
if (eventType === MOUSEDOWN) {
if (activeModality !== MOUSE) {
modality = MOUSE;
activeModality = MOUSE;
callListeners();
}
}
if (eventType === MOUSEMOVE) {
if (modality !== MOUSE) {
modality = MOUSE;
callListeners();
}
}
}
// Flag when browser may produce emulated events
if (eventType === TOUCHSTART) {
isEmulatingMouseEvents = true;
if (event.touches && event.touches.length > 1) {
isEmulatingMouseEvents = false;
}
if (activeModality !== TOUCH) {
modality = TOUCH;
activeModality = TOUCH;
callListeners();
}
return;
}
// Remove flag after emulated events are finished or cancelled, and if an
// event occurs that cuts short a touch event sequence.
if (eventType === CONTEXTMENU || eventType === MOUSEUP || eventType === SELECTIONCHANGE || eventType === SCROLL || eventType === TOUCHCANCEL || eventType === TOUCHMOVE) {
isEmulatingMouseEvents = false;
}
}
}
if (_canUseDom.default) {
// Window events
(0, _addEventListener.addEventListener)(window, BLUR, onBlurWindow, bubbleOptions);
(0, _addEventListener.addEventListener)(window, FOCUS, onFocusWindow, bubbleOptions);
// Must be capture phase because 'stopPropagation' might prevent these
// events bubbling to the document.
(0, _addEventListener.addEventListener)(document, KEYDOWN, onKeyDown, captureOptions);
(0, _addEventListener.addEventListener)(document, VISIBILITYCHANGE, onVisibilityChange, captureOptions);
(0, _addEventListener.addEventListener)(document, POINTERDOWN, onPointerish, captureOptions);
(0, _addEventListener.addEventListener)(document, POINTERMOVE, onPointerish, captureOptions);
// Fallback events
(0, _addEventListener.addEventListener)(document, CONTEXTMENU, onPointerish, captureOptions);
(0, _addEventListener.addEventListener)(document, MOUSEDOWN, onPointerish, captureOptions);
(0, _addEventListener.addEventListener)(document, MOUSEMOVE, onPointerish, captureOptions);
(0, _addEventListener.addEventListener)(document, MOUSEUP, onPointerish, captureOptions);
(0, _addEventListener.addEventListener)(document, TOUCHCANCEL, onPointerish, captureOptions);
(0, _addEventListener.addEventListener)(document, TOUCHMOVE, onPointerish, captureOptions);
(0, _addEventListener.addEventListener)(document, TOUCHSTART, onPointerish, captureOptions);
(0, _addEventListener.addEventListener)(document, SELECTIONCHANGE, onPointerish, captureOptions);
(0, _addEventListener.addEventListener)(document, SCROLL, onPointerish, captureOptions);
}
function callListeners() {
var value = {
activeModality,
modality
};
listeners.forEach(listener => {
listener(value);
});
}
function getActiveModality() {
return activeModality;
}
function getModality() {
return modality;
}
function addModalityListener(listener) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
function testOnly_resetActiveModality() {
isEmulatingMouseEvents = false;
activeModality = KEYBOARD;
modality = KEYBOARD;
}
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/multiplyStyleLengthValue/index.js
"use strict";
exports.__esModule = true;
exports.default = void 0;
/**
* 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.
*
*
*/
var CSS_UNIT_RE = /^[+-]?\d*(?:\.\d+)?(?:[Ee][+-]?\d+)?(%|\w*)/;
var getUnit = str => str.match(CSS_UNIT_RE)[1];
var isNumeric = n => {
return !isNaN(parseFloat(n)) && isFinite(n);
};
var multiplyStyleLengthValue = (value, multiple) => {
if (typeof value === 'string') {
var number = parseFloat(value) * multiple;
var unit = getUnit(value);
return "" + number + unit;
} else if (isNumeric(value)) {
return value * multiple;
}
};
var _default = multiplyStyleLengthValue;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/pick/index.js
"use strict";
exports.__esModule = true;
exports.default = pick;
/**
* 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.
*
*
*/
function pick(obj, list) {
var nextObj = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (list[key] === true) {
nextObj[key] = obj[key];
}
}
}
return nextObj;
}
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/prefixStyles/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _createPrefixer = _interopRequireDefault(require("inline-style-prefixer/lib/createPrefixer"));
var _static = _interopRequireDefault(require("./static"));
/**
* 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.
*
*
*/
var prefixAll = (0, _createPrefixer.default)(_static.default);
var _default = prefixAll;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/prefixStyles/static.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _backgroundClip = _interopRequireDefault(require("inline-style-prefixer/lib/plugins/backgroundClip"));
var _crossFade = _interopRequireDefault(require("inline-style-prefixer/lib/plugins/crossFade"));
var _cursor = _interopRequireDefault(require("inline-style-prefixer/lib/plugins/cursor"));
var _filter = _interopRequireDefault(require("inline-style-prefixer/lib/plugins/filter"));
var _imageSet = _interopRequireDefault(require("inline-style-prefixer/lib/plugins/imageSet"));
var _logical = _interopRequireDefault(require("inline-style-prefixer/lib/plugins/logical"));
var _position = _interopRequireDefault(require("inline-style-prefixer/lib/plugins/position"));
var _sizing = _interopRequireDefault(require("inline-style-prefixer/lib/plugins/sizing"));
var _transition = _interopRequireDefault(require("inline-style-prefixer/lib/plugins/transition"));
var w = ['Webkit'];
var m = ['Moz'];
var wm = ['Webkit', 'Moz'];
var wms = ['Webkit', 'ms'];
var wmms = ['Webkit', 'Moz', 'ms'];
var _default = {
plugins: [_backgroundClip.default, _crossFade.default, _cursor.default, _filter.default, _imageSet.default, _logical.default, _position.default, _sizing.default, _transition.default],
prefixMap: {
appearance: wmms,
userSelect: wm,
textEmphasisPosition: wms,
textEmphasis: wms,
textEmphasisStyle: wms,
textEmphasisColor: wms,
boxDecorationBreak: wms,
clipPath: w,
maskImage: wms,
maskMode: wms,
maskRepeat: wms,
maskPosition: wms,
maskClip: wms,
maskOrigin: wms,
maskSize: wms,
maskComposite: wms,
mask: wms,
maskBorderSource: wms,
maskBorderMode: wms,
maskBorderSlice: wms,
maskBorderWidth: wms,
maskBorderOutset: wms,
maskBorderRepeat: wms,
maskBorder: wms,
maskType: wms,
textDecorationStyle: w,
textDecorationSkip: w,
textDecorationLine: w,
textDecorationColor: w,
filter: w,
breakAfter: w,
breakBefore: w,
breakInside: w,
columnCount: w,
columnFill: w,
columnGap: w,
columnRule: w,
columnRuleColor: w,
columnRuleStyle: w,
columnRuleWidth: w,
columns: w,
columnSpan: w,
columnWidth: w,
backdropFilter: w,
hyphens: w,
flowInto: w,
flowFrom: w,
regionFragment: w,
textOrientation: w,
tabSize: m,
fontKerning: w,
textSizeAdjust: w
}
};
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/requestIdleCallback/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = exports.cancelIdleCallback = void 0;
var _canUseDom = _interopRequireDefault(require("../canUseDom"));
/**
* 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.
*
*
*/
var _requestIdleCallback = function _requestIdleCallback(cb, options) {
return setTimeout(() => {
var start = Date.now();
cb({
didTimeout: false,
timeRemaining() {
return Math.max(0, 50 - (Date.now() - start));
}
});
}, 1);
};
var _cancelIdleCallback = function _cancelIdleCallback(id) {
clearTimeout(id);
};
var isSupported = _canUseDom.default && typeof window.requestIdleCallback !== 'undefined';
var requestIdleCallback = isSupported ? window.requestIdleCallback : _requestIdleCallback;
var cancelIdleCallback = isSupported ? window.cancelIdleCallback : _cancelIdleCallback;
exports.cancelIdleCallback = cancelIdleCallback;
var _default = requestIdleCallback;
exports.default = _default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/setValueForStyles/dangerousStyleValue.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _unitlessNumbers = _interopRequireDefault(require("../unitlessNumbers"));
/* eslint-disable */
/**
* 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.
*
* From React 16.0.0
*
*/
/**
* Convert a value into the proper css writable value. The style name `name`
* should be logical (no hyphens), as specified
* in `CSSProperty.isUnitlessNumber`.
*
* @param {string} name CSS property name such as `topMargin`.
* @param {*} value CSS property value such as `10px`.
* @return {string} Normalized style value with dimensions applied.
*/
function dangerousStyleValue(name, value, isCustomProperty) {
// Note that we've removed escapeTextForBrowser() calls here since the
// whole string will be escaped when the attribute is injected into
// the markup. If you provide unsafe user data here they can inject
// arbitrary CSS which may be problematic (I couldn't repro this):
// https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
// http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
// This is not an XSS hole but instead a potential CSS injection issue
// which has lead to a greater discussion about how we're going to
// trust URLs moving forward. See #2115901
var isEmpty = value == null || typeof value === 'boolean' || value === '';
if (isEmpty) {
return '';
}
if (!isCustomProperty && typeof value === 'number' && value !== 0 && !(_unitlessNumbers.default.hasOwnProperty(name) && _unitlessNumbers.default[name])) {
return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers
}
return ('' + value).trim();
}
var _default = dangerousStyleValue;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/setValueForStyles/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _dangerousStyleValue = _interopRequireDefault(require("./dangerousStyleValue"));
/* eslint-disable */
/**
* 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.
*
* From React 16.3.0
*
*/
/**
* Sets the value for multiple styles on a node. If a value is specified as
* '' (empty string), the corresponding style property will be unset.
*
* @param {DOMElement} node
* @param {object} styles
*/
function setValueForStyles(node, styles) {
var style = node.style;
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
var isCustomProperty = styleName.indexOf('--') === 0;
var styleValue = (0, _dangerousStyleValue.default)(styleName, styles[styleName], isCustomProperty);
if (styleName === 'float') {
styleName = 'cssFloat';
}
if (isCustomProperty) {
style.setProperty(styleName, styleValue);
} else {
style[styleName] = styleValue;
}
}
}
var _default = setValueForStyles;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/unitlessNumbers/index.js
"use strict";
exports.__esModule = true;
exports.default = void 0;
/**
* 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.
*
*
*/
var unitlessNumbers = {
animationIterationCount: true,
aspectRatio: true,
borderImageOutset: true,
borderImageSlice: true,
borderImageWidth: true,
boxFlex: true,
boxFlexGroup: true,
boxOrdinalGroup: true,
columnCount: true,
flex: true,
flexGrow: true,
flexOrder: true,
flexPositive: true,
flexShrink: true,
flexNegative: true,
fontWeight: true,
gridRow: true,
gridRowEnd: true,
gridRowGap: true,
gridRowStart: true,
gridColumn: true,
gridColumnEnd: true,
gridColumnGap: true,
gridColumnStart: true,
lineClamp: true,
opacity: true,
order: true,
orphans: true,
tabSize: true,
widows: true,
zIndex: true,
zoom: true,
// SVG-related
fillOpacity: true,
floodOpacity: true,
stopOpacity: true,
strokeDasharray: true,
strokeDashoffset: true,
strokeMiterlimit: true,
strokeOpacity: true,
strokeWidth: true,
// transform types
scale: true,
scaleX: true,
scaleY: true,
scaleZ: true,
// RN properties
shadowOpacity: true
};
/**
* Support style names that may come passed in prefixed by adding permutations
* of vendor prefixes.
*/
var prefixes = ['ms', 'Moz', 'O', 'Webkit'];
var prefixKey = (prefix, key) => {
return prefix + key.charAt(0).toUpperCase() + key.substring(1);
};
Object.keys(unitlessNumbers).forEach(prop => {
prefixes.forEach(prefix => {
unitlessNumbers[prefixKey(prefix, prop)] = unitlessNumbers[prop];
});
});
var _default = unitlessNumbers;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/useElementLayout/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = useElementLayout;
var _useLayoutEffect = _interopRequireDefault(require("../useLayoutEffect"));
var _UIManager = _interopRequireDefault(require("../../exports/UIManager"));
var _canUseDom = _interopRequireDefault(require("../canUseDom"));
/**
* 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.
*
*
*/
var DOM_LAYOUT_HANDLER_NAME = '__reactLayoutHandler';
var didWarn = !_canUseDom.default;
var resizeObserver = null;
function getResizeObserver() {
if (_canUseDom.default && typeof window.ResizeObserver !== 'undefined') {
if (resizeObserver == null) {
resizeObserver = new window.ResizeObserver(function (entries) {
entries.forEach(entry => {
var node = entry.target;
var onLayout = node[DOM_LAYOUT_HANDLER_NAME];
if (typeof onLayout === 'function') {
// We still need to measure the view because browsers don't yet provide
// border-box dimensions in the entry
_UIManager.default.measure(node, (x, y, width, height, left, top) => {
var event = {
// $FlowFixMe
nativeEvent: {
layout: {
x,
y,
width,
height,
left,
top
}
},
timeStamp: Date.now()
};
Object.defineProperty(event.nativeEvent, 'target', {
enumerable: true,
get: () => entry.target
});
onLayout(event);
});
}
});
});
}
} else if (!didWarn) {
if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test') {
console.warn('onLayout relies on ResizeObserver which is not supported by your browser. ' + 'Please include a polyfill, e.g., https://github.com/que-etc/resize-observer-polyfill.');
didWarn = true;
}
}
return resizeObserver;
}
function useElementLayout(ref, onLayout) {
var observer = getResizeObserver();
(0, _useLayoutEffect.default)(() => {
var node = ref.current;
if (node != null) {
node[DOM_LAYOUT_HANDLER_NAME] = onLayout;
}
}, [ref, onLayout]);
// Observing is done in a separate effect to avoid this effect running
// when 'onLayout' changes.
(0, _useLayoutEffect.default)(() => {
var node = ref.current;
if (node != null && observer != null) {
if (typeof node[DOM_LAYOUT_HANDLER_NAME] === 'function') {
observer.observe(node);
} else {
observer.unobserve(node);
}
}
return () => {
if (node != null && observer != null) {
observer.unobserve(node);
}
};
}, [ref, observer]);
}
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/useEvent/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = useEvent;
var _addEventListener = require("../addEventListener");
var _useLayoutEffect = _interopRequireDefault(require("../useLayoutEffect"));
var _useStable = _interopRequireDefault(require("../useStable"));
/**
* 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.
*
*
*/
/**
* This can be used with any event type include custom events.
*
* const click = useEvent('click', options);
* useEffect(() => {
* click.setListener(target, onClick);
* return () => click.clear();
* }).
*/
function useEvent(eventType, options) {
var targetListeners = (0, _useStable.default)(() => new Map());
var addListener = (0, _useStable.default)(() => {
return (target, callback) => {
var removeTargetListener = targetListeners.get(target);
if (removeTargetListener != null) {
removeTargetListener();
}
if (callback == null) {
targetListeners.delete(target);
callback = () => {};
}
var removeEventListener = (0, _addEventListener.addEventListener)(target, eventType, callback, options);
targetListeners.set(target, removeEventListener);
return removeEventListener;
};
});
(0, _useLayoutEffect.default)(() => {
return () => {
targetListeners.forEach(removeListener => {
removeListener();
});
targetListeners.clear();
};
}, [targetListeners]);
return addListener;
}
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/useHover/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = useHover;
var _modality = require("../modality");
var _useEvent = _interopRequireDefault(require("../useEvent"));
var _useLayoutEffect = _interopRequireDefault(require("../useLayoutEffect"));
/**
* 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.
*
*
*/
/**
* Implementation
*/
var emptyObject = {};
var opts = {
passive: true
};
var lockEventType = 'react-gui:hover:lock';
var unlockEventType = 'react-gui:hover:unlock';
var supportsPointerEvent = () => !!(typeof window !== 'undefined' && window.PointerEvent != null);
function dispatchCustomEvent(target, type, payload) {
var event = document.createEvent('CustomEvent');
var _ref = payload || emptyObject,
_ref$bubbles = _ref.bubbles,
bubbles = _ref$bubbles === void 0 ? true : _ref$bubbles,
_ref$cancelable = _ref.cancelable,
cancelable = _ref$cancelable === void 0 ? true : _ref$cancelable,
detail = _ref.detail;
event.initCustomEvent(type, bubbles, cancelable, detail);
target.dispatchEvent(event);
}
// This accounts for the non-PointerEvent fallback events.
function getPointerType(event) {
var pointerType = event.pointerType;
return pointerType != null ? pointerType : (0, _modality.getModality)();
}
function useHover(targetRef, config) {
var contain = config.contain,
disabled = config.disabled,
onHoverStart = config.onHoverStart,
onHoverChange = config.onHoverChange,
onHoverUpdate = config.onHoverUpdate,
onHoverEnd = config.onHoverEnd;
var canUsePE = supportsPointerEvent();
var addMoveListener = (0, _useEvent.default)(canUsePE ? 'pointermove' : 'mousemove', opts);
var addEnterListener = (0, _useEvent.default)(canUsePE ? 'pointerenter' : 'mouseenter', opts);
var addLeaveListener = (0, _useEvent.default)(canUsePE ? 'pointerleave' : 'mouseleave', opts);
// These custom events are used to implement the "contain" prop.
var addLockListener = (0, _useEvent.default)(lockEventType, opts);
var addUnlockListener = (0, _useEvent.default)(unlockEventType, opts);
(0, _useLayoutEffect.default)(() => {
var target = targetRef.current;
if (target !== null) {
/**
* End the hover gesture
*/
var hoverEnd = function hoverEnd(e) {
if (onHoverEnd != null) {
onHoverEnd(e);
}
if (onHoverChange != null) {
onHoverChange(false);
}
// Remove the listeners once finished.
addMoveListener(target, null);
addLeaveListener(target, null);
};
/**
* Leave element
*/
var leaveListener = function leaveListener(e) {
var target = targetRef.current;
if (target != null && getPointerType(e) !== 'touch') {
if (contain) {
dispatchCustomEvent(target, unlockEventType);
}
hoverEnd(e);
}
};
/**
* Move within element
*/
var moveListener = function moveListener(e) {
if (getPointerType(e) !== 'touch') {
if (onHoverUpdate != null) {
// Not all browsers have these properties
if (e.x == null) {
e.x = e.clientX;
}
if (e.y == null) {
e.y = e.clientY;
}
onHoverUpdate(e);
}
}
};
/**
* Start the hover gesture
*/
var hoverStart = function hoverStart(e) {
if (onHoverStart != null) {
onHoverStart(e);
}
if (onHoverChange != null) {
onHoverChange(true);
}
// Set the listeners needed for the rest of the hover gesture.
if (onHoverUpdate != null) {
addMoveListener(target, !disabled ? moveListener : null);
}
addLeaveListener(target, !disabled ? leaveListener : null);
};
/**
* Enter element
*/
var enterListener = function enterListener(e) {
var target = targetRef.current;
if (target != null && getPointerType(e) !== 'touch') {
if (contain) {
dispatchCustomEvent(target, lockEventType);
}
hoverStart(e);
var lockListener = function lockListener(lockEvent) {
if (lockEvent.target !== target) {
hoverEnd(e);
}
};
var unlockListener = function unlockListener(lockEvent) {
if (lockEvent.target !== target) {
hoverStart(e);
}
};
addLockListener(target, !disabled ? lockListener : null);
addUnlockListener(target, !disabled ? unlockListener : null);
}
};
addEnterListener(target, !disabled ? enterListener : null);
}
}, [addEnterListener, addMoveListener, addLeaveListener, addLockListener, addUnlockListener, contain, disabled, onHoverStart, onHoverChange, onHoverUpdate, onHoverEnd, targetRef]);
}
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/useLayoutEffect/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _react = require("react");
var _canUseDom = _interopRequireDefault(require("../canUseDom"));
/**
* 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.
*
* useLayoutEffect throws an error on the server. On the few occasions where is
* problematic, use this hook.
*
*
*/
var useLayoutEffectImpl = _canUseDom.default ? _react.useLayoutEffect : _react.useEffect;
var _default = useLayoutEffectImpl;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/useLocale/index.js
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.LocaleProvider = LocaleProvider;
exports.getLocaleDirection = getLocaleDirection;
exports.useLocaleContext = useLocaleContext;
var _react = _interopRequireWildcard(require("react"));
var _isLocaleRTL = require("./isLocaleRTL");
/**
* 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.
*
*
*/
var defaultLocale = {
direction: 'ltr',
locale: 'en-US'
};
var LocaleContext = /*#__PURE__*/(0, _react.createContext)(defaultLocale);
function getLocaleDirection(locale) {
return (0, _isLocaleRTL.isLocaleRTL)(locale) ? 'rtl' : 'ltr';
}
function LocaleProvider(props) {
var direction = props.direction,
locale = props.locale,
children = props.children;
var needsContext = direction || locale;
return needsContext ? /*#__PURE__*/_react.default.createElement(LocaleContext.Provider, {
children: children,
value: {
direction: locale ? getLocaleDirection(locale) : direction,
locale
}
}) : children;
}
function useLocaleContext() {
return (0, _react.useContext)(LocaleContext);
}
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/useLocale/isLocaleRTL.js
"use strict";
exports.__esModule = true;
exports.isLocaleRTL = isLocaleRTL;
/**
* 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.
*
*
*/
var rtlScripts = new Set(['Arab', 'Syrc', 'Samr', 'Mand', 'Thaa', 'Mend', 'Nkoo', 'Adlm', 'Rohg', 'Hebr']);
var rtlLangs = new Set(['ae',
// Avestan
'ar',
// Arabic
'arc',
// Aramaic
'bcc',
// Southern Balochi
'bqi',
// Bakthiari
'ckb',
// Sorani
'dv',
// Dhivehi
'fa', 'far',
// Persian
'glk',
// Gilaki
'he', 'iw',
// Hebrew
'khw',
// Khowar
'ks',
// Kashmiri
'ku',
// Kurdish
'mzn',
// Mazanderani
'nqo',
// N'Ko
'pnb',
// Western Punjabi
'ps',
// Pashto
'sd',
// Sindhi
'ug',
// Uyghur
'ur',
// Urdu
'yi' // Yiddish
]);
var cache = new Map();
/**
* Determine the writing direction of a locale
*/
function isLocaleRTL(locale) {
var cachedRTL = cache.get(locale);
if (cachedRTL) {
return cachedRTL;
}
var isRTL = false;
// $FlowFixMe
if (Intl.Locale) {
// $FlowFixMe
var script = new Intl.Locale(locale).maximize().script;
isRTL = rtlScripts.has(script);
} else {
// Fallback to inferring from language
var lang = locale.split('-')[0];
isRTL = rtlLangs.has(lang);
}
cache.set(locale, isRTL);
return isRTL;
}
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/useMergeRefs/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = useMergeRefs;
var React = _interopRequireWildcard(require("react"));
var _mergeRefs = _interopRequireDefault(require("../mergeRefs"));
/**
* 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.
*
*
*/
function useMergeRefs() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return React.useMemo(() => (0, _mergeRefs.default)(...args),
// eslint-disable-next-line
[...args]);
}
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/usePlatformMethods/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = usePlatformMethods;
var _UIManager = _interopRequireDefault(require("../../exports/UIManager"));
var _useStable = _interopRequireDefault(require("../useStable"));
/**
* 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.
*
*
*/
/**
* Adds non-standard methods to the hode element. This is temporarily until an
* API like `ReactNative.measure(hostRef, callback)` is added to React Native.
*/
function usePlatformMethods(_ref) {
var pointerEvents = _ref.pointerEvents,
style = _ref.style;
// Avoid creating a new ref on every render.
var ref = (0, _useStable.default)(() => hostNode => {
if (hostNode != null) {
hostNode.measure = callback => _UIManager.default.measure(hostNode, callback);
hostNode.measureLayout = (relativeToNode, success, failure) => _UIManager.default.measureLayout(hostNode, relativeToNode, failure, success);
hostNode.measureInWindow = callback => _UIManager.default.measureInWindow(hostNode, callback);
}
});
return ref;
}
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/usePressEvents/PressResponder.js
/**
* 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.
*
*
* @format
*/
'use strict';
exports.__esModule = true;
exports.default = void 0;
var DELAY = 'DELAY';
var ERROR = 'ERROR';
var LONG_PRESS_DETECTED = 'LONG_PRESS_DETECTED';
var NOT_RESPONDER = 'NOT_RESPONDER';
var RESPONDER_ACTIVE_LONG_PRESS_START = 'RESPONDER_ACTIVE_LONG_PRESS_START';
var RESPONDER_ACTIVE_PRESS_START = 'RESPONDER_ACTIVE_PRESS_START';
var RESPONDER_INACTIVE_PRESS_START = 'RESPONDER_INACTIVE_PRESS_START';
var RESPONDER_GRANT = 'RESPONDER_GRANT';
var RESPONDER_RELEASE = 'RESPONDER_RELEASE';
var RESPONDER_TERMINATED = 'RESPONDER_TERMINATED';
var Transitions = Object.freeze({
NOT_RESPONDER: {
DELAY: ERROR,
RESPONDER_GRANT: RESPONDER_INACTIVE_PRESS_START,
RESPONDER_RELEASE: ERROR,
RESPONDER_TERMINATED: ERROR,
LONG_PRESS_DETECTED: ERROR
},
RESPONDER_INACTIVE_PRESS_START: {
DELAY: RESPONDER_ACTIVE_PRESS_START,
RESPONDER_GRANT: ERROR,
RESPONDER_RELEASE: NOT_RESPONDER,
RESPONDER_TERMINATED: NOT_RESPONDER,
LONG_PRESS_DETECTED: ERROR
},
RESPONDER_ACTIVE_PRESS_START: {
DELAY: ERROR,
RESPONDER_GRANT: ERROR,
RESPONDER_RELEASE: NOT_RESPONDER,
RESPONDER_TERMINATED: NOT_RESPONDER,
LONG_PRESS_DETECTED: RESPONDER_ACTIVE_LONG_PRESS_START
},
RESPONDER_ACTIVE_LONG_PRESS_START: {
DELAY: ERROR,
RESPONDER_GRANT: ERROR,
RESPONDER_RELEASE: NOT_RESPONDER,
RESPONDER_TERMINATED: NOT_RESPONDER,
LONG_PRESS_DETECTED: RESPONDER_ACTIVE_LONG_PRESS_START
},
ERROR: {
DELAY: NOT_RESPONDER,
RESPONDER_GRANT: RESPONDER_INACTIVE_PRESS_START,
RESPONDER_RELEASE: NOT_RESPONDER,
RESPONDER_TERMINATED: NOT_RESPONDER,
LONG_PRESS_DETECTED: NOT_RESPONDER
}
});
var getElementRole = element => element.getAttribute('role');
var getElementType = element => element.tagName.toLowerCase();
var isActiveSignal = signal => signal === RESPONDER_ACTIVE_PRESS_START || signal === RESPONDER_ACTIVE_LONG_PRESS_START;
var isButtonRole = element => getElementRole(element) === 'button';
var isPressStartSignal = signal => signal === RESPONDER_INACTIVE_PRESS_START || signal === RESPONDER_ACTIVE_PRESS_START || signal === RESPONDER_ACTIVE_LONG_PRESS_START;
var isTerminalSignal = signal => signal === RESPONDER_TERMINATED || signal === RESPONDER_RELEASE;
var isValidKeyPress = event => {
var key = event.key,
target = event.target;
var isSpacebar = key === ' ' || key === 'Spacebar';
var isButtonish = getElementType(target) === 'button' || isButtonRole(target);
return key === 'Enter' || isSpacebar && isButtonish;
};
var DEFAULT_LONG_PRESS_DELAY_MS = 450; // 500 - 50
var DEFAULT_PRESS_DELAY_MS = 50;
/**
* =========================== PressResponder Tutorial ===========================
*
* The `PressResponder` class helps you create press interactions by analyzing the
* geometry of elements and observing when another responder (e.g. ScrollView)
* has stolen the touch lock. It offers hooks for your component to provide
* interaction feedback to the user:
*
* - When a press has activated (e.g. highlight an element)
* - When a press has deactivated (e.g. un-highlight an element)
* - When a press sould trigger an action, meaning it activated and deactivated
* while within the geometry of the element without the lock being stolen.
*
* A high quality interaction isn't as simple as you might think. There should
* be a slight delay before activation. Moving your finger beyond an element's
* bounds should trigger deactivation, but moving the same finger back within an
* element's bounds should trigger reactivation.
*
* In order to use `PressResponder`, do the following:
*
* const pressResponder = new PressResponder(config);
*
* 2. Choose the rendered component who should collect the press events. On that
* element, spread `pressability.getEventHandlers()` into its props.
*
* return (
* <View {...this.state.pressResponder.getEventHandlers()} />
* );
*
* 3. Reset `PressResponder` when your component unmounts.
*
* componentWillUnmount() {
* this.state.pressResponder.reset();
* }
*
* ==================== Implementation Details ====================
*
* `PressResponder` only assumes that there exists a `HitRect` node. The `PressRect`
* is an abstract box that is extended beyond the `HitRect`.
*
* # Geometry
*
* ┌────────────────────────┐
* │ ┌──────────────────┐ │ - Presses start anywhere within `HitRect`.
* │ │ ┌────────────┐ │ │
* │ │ │ VisualRect │ │ │
* │ │ └────────────┘ │ │ - When pressed down for sufficient amount of time
* │ │ HitRect │ │ before letting up, `VisualRect` activates.
* │ └──────────────────┘ │
* │ Out Region o │
* └────────────────────│───┘
* └────── When the press is released outside the `HitRect`,
* the responder is NOT eligible for a "press".
*
* # State Machine
*
* ┌───────────────┐ ◀──── RESPONDER_RELEASE
* │ NOT_RESPONDER │
* └───┬───────────┘ ◀──── RESPONDER_TERMINATED
* │
* │ RESPONDER_GRANT (HitRect)
* │
* ▼
* ┌─────────────────────┐ ┌───────────────────┐ ┌───────────────────┐
* │ RESPONDER_INACTIVE_ │ DELAY │ RESPONDER_ACTIVE_ │ T + DELAY │ RESPONDER_ACTIVE_ │
* │ PRESS_START ├────────▶ │ PRESS_START ├────────────▶ │ LONG_PRESS_START │
* └─────────────────────┘ └───────────────────┘ └───────────────────┘
*
* T + DELAY => LONG_PRESS_DELAY + DELAY
*
* Not drawn are the side effects of each transition. The most important side
* effect is the invocation of `onLongPress`. Only when the browser produces a
* `click` event is `onPress` invoked.
*/
class PressResponder {
constructor(config) {
this._eventHandlers = null;
this._isPointerTouch = false;
this._longPressDelayTimeout = null;
this._longPressDispatched = false;
this._pressDelayTimeout = null;
this._pressOutDelayTimeout = null;
this._touchState = NOT_RESPONDER;
this._responderElement = null;
this.configure(config);
}
configure(config) {
this._config = config;
}
/**
* Resets any pending timers. This should be called on unmount.
*/
reset() {
this._cancelLongPressDelayTimeout();
this._cancelPressDelayTimeout();
this._cancelPressOutDelayTimeout();
}
/**
* Returns a set of props to spread into the interactive element.
*/
getEventHandlers() {
if (this._eventHandlers == null) {
this._eventHandlers = this._createEventHandlers();
}
return this._eventHandlers;
}
_createEventHandlers() {
var start = (event, shouldDelay) => {
event.persist();
this._cancelPressOutDelayTimeout();
this._longPressDispatched = false;
this._selectionTerminated = false;
this._touchState = NOT_RESPONDER;
this._isPointerTouch = event.nativeEvent.type === 'touchstart';
this._receiveSignal(RESPONDER_GRANT, event);
var delayPressStart = normalizeDelay(this._config.delayPressStart, 0, DEFAULT_PRESS_DELAY_MS);
if (shouldDelay !== false && delayPressStart > 0) {
this._pressDelayTimeout = setTimeout(() => {
this._receiveSignal(DELAY, event);
}, delayPressStart);
} else {
this._receiveSignal(DELAY, event);
}
var delayLongPress = normalizeDelay(this._config.delayLongPress, 10, DEFAULT_LONG_PRESS_DELAY_MS);
this._longPressDelayTimeout = setTimeout(() => {
this._handleLongPress(event);
}, delayLongPress + delayPressStart);
};
var end = event => {
this._receiveSignal(RESPONDER_RELEASE, event);
};
var keyupHandler = event => {
var onPress = this._config.onPress;
var target = event.target;
if (this._touchState !== NOT_RESPONDER && isValidKeyPress(event)) {
end(event);
document.removeEventListener('keyup', keyupHandler);
var role = target.getAttribute('role');
var elementType = getElementType(target);
var isNativeInteractiveElement = role === 'link' || elementType === 'a' || elementType === 'button' || elementType === 'input' || elementType === 'select' || elementType === 'textarea';
var isActiveElement = this._responderElement === target;
if (onPress != null && !isNativeInteractiveElement && isActiveElement) {
onPress(event);
}
this._responderElement = null;
}
};
return {
onStartShouldSetResponder: event => {
var disabled = this._config.disabled;
if (disabled && isButtonRole(event.currentTarget)) {
event.stopPropagation();
}
if (disabled == null) {
return true;
}
return !disabled;
},
onKeyDown: event => {
var disabled = this._config.disabled;
var key = event.key,
target = event.target;
if (!disabled && isValidKeyPress(event)) {
if (this._touchState === NOT_RESPONDER) {
start(event, false);
this._responderElement = target;
// Listen to 'keyup' on document to account for situations where
// focus is moved to another element during 'keydown'.
document.addEventListener('keyup', keyupHandler);
}
var isSpacebarKey = key === ' ' || key === 'Spacebar';
var role = getElementRole(target);
var isButtonLikeRole = role === 'button' || role === 'menuitem';
if (isSpacebarKey && isButtonLikeRole && getElementType(target) !== 'button') {
// Prevent spacebar scrolling the window if using non-native button
event.preventDefault();
}
event.stopPropagation();
}
},
onResponderGrant: event => start(event),
onResponderMove: event => {
if (this._config.onPressMove != null) {
this._config.onPressMove(event);
}
var touch = getTouchFromResponderEvent(event);
if (this._touchActivatePosition != null) {
var deltaX = this._touchActivatePosition.pageX - touch.pageX;
var deltaY = this._touchActivatePosition.pageY - touch.pageY;
if (Math.hypot(deltaX, deltaY) > 10) {
this._cancelLongPressDelayTimeout();
}
}
},
onResponderRelease: event => end(event),
onResponderTerminate: event => {
if (event.nativeEvent.type === 'selectionchange') {
this._selectionTerminated = true;
}
this._receiveSignal(RESPONDER_TERMINATED, event);
},
onResponderTerminationRequest: event => {
var _this$_config = this._config,
cancelable = _this$_config.cancelable,
disabled = _this$_config.disabled,
onLongPress = _this$_config.onLongPress;
// If `onLongPress` is provided, don't terminate on `contextmenu` as default
// behavior will be prevented for non-mouse pointers.
if (!disabled && onLongPress != null && this._isPointerTouch && event.nativeEvent.type === 'contextmenu') {
return false;
}
if (cancelable == null) {
return true;
}
return cancelable;
},
// NOTE: this diverges from react-native in 3 significant ways:
// * The `onPress` callback is not connected to the responder system (the native
// `click` event must be used but is dispatched in many scenarios where no pointers
// are on the screen.) Therefore, it's possible for `onPress` to be called without
// `onPress{Start,End}` being called first.
// * The `onPress` callback is only be called on the first ancestor of the native
// `click` target that is using the PressResponder.
// * The event's `nativeEvent` is a `MouseEvent` not a `TouchEvent`.
onClick: event => {
var _this$_config2 = this._config,
disabled = _this$_config2.disabled,
onPress = _this$_config2.onPress;
if (!disabled) {
// If long press dispatched, cancel default click behavior.
// If the responder terminated because text was selected during the gesture,
// cancel the default click behavior.
event.stopPropagation();
if (this._longPressDispatched || this._selectionTerminated) {
event.preventDefault();
} else if (onPress != null && event.altKey === false) {
onPress(event);
}
} else {
if (isButtonRole(event.currentTarget)) {
event.stopPropagation();
}
}
},
// If `onLongPress` is provided and a touch pointer is being used, prevent the
// default context menu from opening.
onContextMenu: event => {
var _this$_config3 = this._config,
disabled = _this$_config3.disabled,
onLongPress = _this$_config3.onLongPress;
if (!disabled) {
if (onLongPress != null && this._isPointerTouch && !event.defaultPrevented) {
event.preventDefault();
event.stopPropagation();
}
} else {
if (isButtonRole(event.currentTarget)) {
event.stopPropagation();
}
}
}
};
}
/**
* Receives a state machine signal, performs side effects of the transition
* and stores the new state. Validates the transition as well.
*/
_receiveSignal(signal, event) {
var prevState = this._touchState;
var nextState = null;
if (Transitions[prevState] != null) {
nextState = Transitions[prevState][signal];
}
if (this._touchState === NOT_RESPONDER && signal === RESPONDER_RELEASE) {
return;
}
if (nextState == null || nextState === ERROR) {
console.error("PressResponder: Invalid signal " + signal + " for state " + prevState + " on responder");
} else if (prevState !== nextState) {
this._performTransitionSideEffects(prevState, nextState, signal, event);
this._touchState = nextState;
}
}
/**
* Performs a transition between touchable states and identify any activations
* or deactivations (and callback invocations).
*/
_performTransitionSideEffects(prevState, nextState, signal, event) {
if (isTerminalSignal(signal)) {
// Pressable suppression of contextmenu on windows.
// On Windows, the contextmenu is displayed after pointerup.
// https://github.com/necolas/react-native-web/issues/2296
setTimeout(() => {
this._isPointerTouch = false;
}, 0);
this._touchActivatePosition = null;
this._cancelLongPressDelayTimeout();
}
if (isPressStartSignal(prevState) && signal === LONG_PRESS_DETECTED) {
var onLongPress = this._config.onLongPress;
// Long press is not supported for keyboards because 'click' can be dispatched
// immediately (and multiple times) after 'keydown'.
if (onLongPress != null && event.nativeEvent.key == null) {
onLongPress(event);
this._longPressDispatched = true;
}
}
var isPrevActive = isActiveSignal(prevState);
var isNextActive = isActiveSignal(nextState);
if (!isPrevActive && isNextActive) {
this._activate(event);
} else if (isPrevActive && !isNextActive) {
this._deactivate(event);
}
if (isPressStartSignal(prevState) && signal === RESPONDER_RELEASE) {
var _this$_config4 = this._config,
_onLongPress = _this$_config4.onLongPress,
onPress = _this$_config4.onPress;
if (onPress != null) {
var isPressCanceledByLongPress = _onLongPress != null && prevState === RESPONDER_ACTIVE_LONG_PRESS_START;
if (!isPressCanceledByLongPress) {
// If we never activated (due to delays), activate and deactivate now.
if (!isNextActive && !isPrevActive) {
this._activate(event);
this._deactivate(event);
}
}
}
}
this._cancelPressDelayTimeout();
}
_activate(event) {
var _this$_config5 = this._config,
onPressChange = _this$_config5.onPressChange,
onPressStart = _this$_config5.onPressStart;
var touch = getTouchFromResponderEvent(event);
this._touchActivatePosition = {
pageX: touch.pageX,
pageY: touch.pageY
};
if (onPressStart != null) {
onPressStart(event);
}
if (onPressChange != null) {
onPressChange(true);
}
}
_deactivate(event) {
var _this$_config6 = this._config,
onPressChange = _this$_config6.onPressChange,
onPressEnd = _this$_config6.onPressEnd;
function end() {
if (onPressEnd != null) {
onPressEnd(event);
}
if (onPressChange != null) {
onPressChange(false);
}
}
var delayPressEnd = normalizeDelay(this._config.delayPressEnd);
if (delayPressEnd > 0) {
this._pressOutDelayTimeout = setTimeout(() => {
end();
}, delayPressEnd);
} else {
end();
}
}
_handleLongPress(event) {
if (this._touchState === RESPONDER_ACTIVE_PRESS_START || this._touchState === RESPONDER_ACTIVE_LONG_PRESS_START) {
this._receiveSignal(LONG_PRESS_DETECTED, event);
}
}
_cancelLongPressDelayTimeout() {
if (this._longPressDelayTimeout != null) {
clearTimeout(this._longPressDelayTimeout);
this._longPressDelayTimeout = null;
}
}
_cancelPressDelayTimeout() {
if (this._pressDelayTimeout != null) {
clearTimeout(this._pressDelayTimeout);
this._pressDelayTimeout = null;
}
}
_cancelPressOutDelayTimeout() {
if (this._pressOutDelayTimeout != null) {
clearTimeout(this._pressOutDelayTimeout);
this._pressOutDelayTimeout = null;
}
}
}
exports.default = PressResponder;
function normalizeDelay(delay, min, fallback) {
if (min === void 0) {
min = 0;
}
if (fallback === void 0) {
fallback = 0;
}
return Math.max(min, delay !== null && delay !== void 0 ? delay : fallback);
}
function getTouchFromResponderEvent(event) {
var _event$nativeEvent = event.nativeEvent,
changedTouches = _event$nativeEvent.changedTouches,
touches = _event$nativeEvent.touches;
if (touches != null && touches.length > 0) {
return touches[0];
}
if (changedTouches != null && changedTouches.length > 0) {
return changedTouches[0];
}
return event.nativeEvent;
}
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/usePressEvents/index.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = usePressEvents;
var _PressResponder = _interopRequireDefault(require("./PressResponder"));
var _react = require("react");
function usePressEvents(hostRef, config) {
var pressResponderRef = (0, _react.useRef)(null);
if (pressResponderRef.current == null) {
pressResponderRef.current = new _PressResponder.default(config);
}
var pressResponder = pressResponderRef.current;
// Re-configure to use the current node and configuration.
(0, _react.useEffect)(() => {
pressResponder.configure(config);
}, [config, pressResponder]);
// Reset the `pressResponder` when cleanup needs to occur. This is
// a separate effect because we do not want to rest the responder when `config` changes.
(0, _react.useEffect)(() => {
return () => {
pressResponder.reset();
};
}, [pressResponder]);
(0, _react.useDebugValue)(config);
return pressResponder.getEventHandlers();
}
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/useResponderEvents/ResponderEventTypes.js
"use strict";
exports.__esModule = true;
exports.TOUCH_START = exports.TOUCH_MOVE = exports.TOUCH_END = exports.TOUCH_CANCEL = exports.SELECTION_CHANGE = exports.SELECT = exports.SCROLL = exports.MOUSE_UP = exports.MOUSE_MOVE = exports.MOUSE_DOWN = exports.MOUSE_CANCEL = exports.FOCUS_OUT = exports.CONTEXT_MENU = exports.BLUR = void 0;
exports.isCancelish = isCancelish;
exports.isEndish = isEndish;
exports.isMoveish = isMoveish;
exports.isScroll = isScroll;
exports.isSelectionChange = isSelectionChange;
exports.isStartish = isStartish;
/**
* 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.
*
*
*/
var BLUR = 'blur';
exports.BLUR = BLUR;
var CONTEXT_MENU = 'contextmenu';
exports.CONTEXT_MENU = CONTEXT_MENU;
var FOCUS_OUT = 'focusout';
exports.FOCUS_OUT = FOCUS_OUT;
var MOUSE_DOWN = 'mousedown';
exports.MOUSE_DOWN = MOUSE_DOWN;
var MOUSE_MOVE = 'mousemove';
exports.MOUSE_MOVE = MOUSE_MOVE;
var MOUSE_UP = 'mouseup';
exports.MOUSE_UP = MOUSE_UP;
var MOUSE_CANCEL = 'dragstart';
exports.MOUSE_CANCEL = MOUSE_CANCEL;
var TOUCH_START = 'touchstart';
exports.TOUCH_START = TOUCH_START;
var TOUCH_MOVE = 'touchmove';
exports.TOUCH_MOVE = TOUCH_MOVE;
var TOUCH_END = 'touchend';
exports.TOUCH_END = TOUCH_END;
var TOUCH_CANCEL = 'touchcancel';
exports.TOUCH_CANCEL = TOUCH_CANCEL;
var SCROLL = 'scroll';
exports.SCROLL = SCROLL;
var SELECT = 'select';
exports.SELECT = SELECT;
var SELECTION_CHANGE = 'selectionchange';
exports.SELECTION_CHANGE = SELECTION_CHANGE;
function isStartish(eventType) {
return eventType === TOUCH_START || eventType === MOUSE_DOWN;
}
function isMoveish(eventType) {
return eventType === TOUCH_MOVE || eventType === MOUSE_MOVE;
}
function isEndish(eventType) {
return eventType === TOUCH_END || eventType === MOUSE_UP || isCancelish(eventType);
}
function isCancelish(eventType) {
return eventType === TOUCH_CANCEL || eventType === MOUSE_CANCEL;
}
function isScroll(eventType) {
return eventType === SCROLL;
}
function isSelectionChange(eventType) {
return eventType === SELECT || eventType === SELECTION_CHANGE;
}
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/useResponderEvents/ResponderSystem.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.addNode = addNode;
exports.attachListeners = attachListeners;
exports.getResponderNode = getResponderNode;
exports.removeNode = removeNode;
exports.terminateResponder = terminateResponder;
var _createResponderEvent = _interopRequireDefault(require("./createResponderEvent"));
var _ResponderEventTypes = require("./ResponderEventTypes");
var _utils = require("./utils");
var _ResponderTouchHistoryStore = require("./ResponderTouchHistoryStore");
var _canUseDom = _interopRequireDefault(require("../canUseDom"));
/**
* 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.
*
*
*/
/**
* RESPONDER EVENT SYSTEM
*
* A single, global "interaction lock" on views. For a view to be the "responder" means
* that pointer interactions are exclusive to that view and none other. The "interaction
* lock" can be transferred (only) to ancestors of the current "responder" as long as
* pointers continue to be active.
*
* Responder being granted:
*
* A view can become the "responder" after the following events:
* * "pointerdown" (implemented using "touchstart", "mousedown")
* * "pointermove" (implemented using "touchmove", "mousemove")
* * "scroll" (while a pointer is down)
* * "selectionchange" (while a pointer is down)
*
* If nothing is already the "responder", the event propagates to (capture) and from
* (bubble) the event target until a view returns `true` for
* `on*ShouldSetResponder(Capture)`.
*
* If something is already the responder, the event propagates to (capture) and from
* (bubble) the lowest common ancestor of the event target and the current "responder".
* Then negotiation happens between the current "responder" and a view that wants to
* become the "responder": see the timing diagram below.
*
* (NOTE: Scrolled views either automatically become the "responder" or release the
* "interaction lock". A native scroll view that isn't built on top of the responder
* system must result in the current "responder" being notified that it no longer has
* the "interaction lock" - the native system has taken over.
*
* Responder being released:
*
* As soon as there are no more active pointers that *started* inside descendants
* of the *current* "responder", an `onResponderRelease` event is dispatched to the
* current "responder", and the responder lock is released.
*
* Typical sequence of events:
* * startShouldSetResponder
* * responderGrant/Reject
* * responderStart
* * responderMove
* * responderEnd
* * responderRelease
*/
/* Negotiation Performed
+-----------------------+
/ \
Process low level events to + Current Responder + wantsResponderID
determine who to perform negot-| (if any exists at all) |
iation/transition | Otherwise just pass through|
-------------------------------+----------------------------+------------------+
Bubble to find first ID | |
to return true:wantsResponderID| |
| |
+--------------+ | |
| onTouchStart | | |
+------+-------+ none | |
| return| |
+-----------v-------------+true| +------------------------+ |
|onStartShouldSetResponder|----->| onResponderStart (cur) |<-----------+
+-----------+-------------+ | +------------------------+ | |
| | | +--------+-------+
| returned true for| false:REJECT +-------->|onResponderReject
| wantsResponderID | | | +----------------+
| (now attempt | +------------------+-----+ |
| handoff) | | onResponder | |
+------------------->| TerminationRequest | |
| +------------------+-----+ |
| | | +----------------+
| true:GRANT +-------->|onResponderGrant|
| | +--------+-------+
| +------------------------+ | |
| | onResponderTerminate |<-----------+
| +------------------+-----+ |
| | | +----------------+
| +-------->|onResponderStart|
| | +----------------+
Bubble to find first ID | |
to return true:wantsResponderID| |
| |
+-------------+ | |
| onTouchMove | | |
+------+------+ none | |
| return| |
+-----------v-------------+true| +------------------------+ |
|onMoveShouldSetResponder |----->| onResponderMove (cur) |<-----------+
+-----------+-------------+ | +------------------------+ | |
| | | +--------+-------+
| returned true for| false:REJECT +-------->|onResponderReject
| wantsResponderID | | | +----------------+
| (now attempt | +------------------+-----+ |
| handoff) | | onResponder | |
+------------------->| TerminationRequest| |
| +------------------+-----+ |
| | | +----------------+
| true:GRANT +-------->|onResponderGrant|
| | +--------+-------+
| +------------------------+ | |
| | onResponderTerminate |<-----------+
| +------------------+-----+ |
| | | +----------------+
| +-------->|onResponderMove |
| | +----------------+
| |
| |
Some active touch started| |
inside current responder | +------------------------+ |
+------------------------->| onResponderEnd | |
| | +------------------------+ |
+---+---------+ | |
| onTouchEnd | | |
+---+---------+ | |
| | +------------------------+ |
+------------------------->| onResponderEnd | |
No active touches started| +-----------+------------+ |
inside current responder | | |
| v |
| +------------------------+ |
| | onResponderRelease | |
| +------------------------+ |
| |
+ + */
var emptyObject = {};
/* ------------ IMPLEMENTATION ------------ */
var startRegistration = ['onStartShouldSetResponderCapture', 'onStartShouldSetResponder', {
bubbles: true
}];
var moveRegistration = ['onMoveShouldSetResponderCapture', 'onMoveShouldSetResponder', {
bubbles: true
}];
var scrollRegistration = ['onScrollShouldSetResponderCapture', 'onScrollShouldSetResponder', {
bubbles: false
}];
var shouldSetResponderEvents = {
touchstart: startRegistration,
mousedown: startRegistration,
touchmove: moveRegistration,
mousemove: moveRegistration,
scroll: scrollRegistration
};
var emptyResponder = {
id: null,
idPath: null,
node: null
};
var responderListenersMap = new Map();
var isEmulatingMouseEvents = false;
var trackedTouchCount = 0;
var currentResponder = {
id: null,
node: null,
idPath: null
};
var responderTouchHistoryStore = new _ResponderTouchHistoryStore.ResponderTouchHistoryStore();
function changeCurrentResponder(responder) {
currentResponder = responder;
}
function getResponderConfig(id) {
var config = responderListenersMap.get(id);
return config != null ? config : emptyObject;
}
/**
* Process native events
*
* A single event listener is used to manage the responder system.
* All pointers are tracked in the ResponderTouchHistoryStore. Native events
* are interpreted in terms of the Responder System and checked to see if
* the responder should be transferred. Each host node that is attached to
* the Responder System has an ID, which is used to look up its associated
* callbacks.
*/
function eventListener(domEvent) {
var eventType = domEvent.type;
var eventTarget = domEvent.target;
/**
* Manage emulated events and early bailout.
* Since PointerEvent is not used yet (lack of support in older Safari), it's
* necessary to manually manage the mess of browser touch/mouse events.
* And bailout early for termination events when there is no active responder.
*/
// Flag when browser may produce emulated events
if (eventType === 'touchstart') {
isEmulatingMouseEvents = true;
}
// Remove flag when browser will not produce emulated events
if (eventType === 'touchmove' || trackedTouchCount > 1) {
isEmulatingMouseEvents = false;
}
// Ignore various events in particular circumstances
if (
// Ignore browser emulated mouse events
eventType === 'mousedown' && isEmulatingMouseEvents || eventType === 'mousemove' && isEmulatingMouseEvents ||
// Ignore mousemove if a mousedown didn't occur first
eventType === 'mousemove' && trackedTouchCount < 1) {
return;
}
// Remove flag after emulated events are finished
if (isEmulatingMouseEvents && eventType === 'mouseup') {
if (trackedTouchCount === 0) {
isEmulatingMouseEvents = false;
}
return;
}
var isStartEvent = (0, _ResponderEventTypes.isStartish)(eventType) && (0, _utils.isPrimaryPointerDown)(domEvent);
var isMoveEvent = (0, _ResponderEventTypes.isMoveish)(eventType);
var isEndEvent = (0, _ResponderEventTypes.isEndish)(eventType);
var isScrollEvent = (0, _ResponderEventTypes.isScroll)(eventType);
var isSelectionChangeEvent = (0, _ResponderEventTypes.isSelectionChange)(eventType);
var responderEvent = (0, _createResponderEvent.default)(domEvent, responderTouchHistoryStore);
/**
* Record the state of active pointers
*/
if (isStartEvent || isMoveEvent || isEndEvent) {
if (domEvent.touches) {
trackedTouchCount = domEvent.touches.length;
} else {
if (isStartEvent) {
trackedTouchCount = 1;
} else if (isEndEvent) {
trackedTouchCount = 0;
}
}
responderTouchHistoryStore.recordTouchTrack(eventType, responderEvent.nativeEvent);
}
/**
* Responder System logic
*/
var eventPaths = (0, _utils.getResponderPaths)(domEvent);
var wasNegotiated = false;
var wantsResponder;
// If an event occured that might change the current responder...
if (isStartEvent || isMoveEvent || isScrollEvent && trackedTouchCount > 0) {
// If there is already a responder, prune the event paths to the lowest common ancestor
// of the existing responder and deepest target of the event.
var currentResponderIdPath = currentResponder.idPath;
var eventIdPath = eventPaths.idPath;
if (currentResponderIdPath != null && eventIdPath != null) {
var lowestCommonAncestor = (0, _utils.getLowestCommonAncestor)(currentResponderIdPath, eventIdPath);
if (lowestCommonAncestor != null) {
var indexOfLowestCommonAncestor = eventIdPath.indexOf(lowestCommonAncestor);
// Skip the current responder so it doesn't receive unexpected "shouldSet" events.
var index = indexOfLowestCommonAncestor + (lowestCommonAncestor === currentResponder.id ? 1 : 0);
eventPaths = {
idPath: eventIdPath.slice(index),
nodePath: eventPaths.nodePath.slice(index)
};
} else {
eventPaths = null;
}
}
if (eventPaths != null) {
// If a node wants to become the responder, attempt to transfer.
wantsResponder = findWantsResponder(eventPaths, domEvent, responderEvent);
if (wantsResponder != null) {
// Sets responder if none exists, or negotates with existing responder.
attemptTransfer(responderEvent, wantsResponder);
wasNegotiated = true;
}
}
}
// If there is now a responder, invoke its callbacks for the lifecycle of the gesture.
if (currentResponder.id != null && currentResponder.node != null) {
var _currentResponder = currentResponder,
id = _currentResponder.id,
node = _currentResponder.node;
var _getResponderConfig = getResponderConfig(id),
onResponderStart = _getResponderConfig.onResponderStart,
onResponderMove = _getResponderConfig.onResponderMove,
onResponderEnd = _getResponderConfig.onResponderEnd,
onResponderRelease = _getResponderConfig.onResponderRelease,
onResponderTerminate = _getResponderConfig.onResponderTerminate,
onResponderTerminationRequest = _getResponderConfig.onResponderTerminationRequest;
responderEvent.bubbles = false;
responderEvent.cancelable = false;
responderEvent.currentTarget = node;
// Start
if (isStartEvent) {
if (onResponderStart != null) {
responderEvent.dispatchConfig.registrationName = 'onResponderStart';
onResponderStart(responderEvent);
}
}
// Move
else if (isMoveEvent) {
if (onResponderMove != null) {
responderEvent.dispatchConfig.registrationName = 'onResponderMove';
onResponderMove(responderEvent);
}
} else {
var isTerminateEvent = (0, _ResponderEventTypes.isCancelish)(eventType) ||
// native context menu
eventType === 'contextmenu' ||
// window blur
eventType === 'blur' && eventTarget === window ||
// responder (or ancestors) blur
eventType === 'blur' && eventTarget.contains(node) && domEvent.relatedTarget !== node ||
// native scroll without using a pointer
isScrollEvent && trackedTouchCount === 0 ||
// native scroll on node that is parent of the responder (allow siblings to scroll)
isScrollEvent && eventTarget.contains(node) && eventTarget !== node ||
// native select/selectionchange on node
isSelectionChangeEvent && (0, _utils.hasValidSelection)(domEvent);
var isReleaseEvent = isEndEvent && !isTerminateEvent && !(0, _utils.hasTargetTouches)(node, domEvent.touches);
// End
if (isEndEvent) {
if (onResponderEnd != null) {
responderEvent.dispatchConfig.registrationName = 'onResponderEnd';
onResponderEnd(responderEvent);
}
}
// Release
if (isReleaseEvent) {
if (onResponderRelease != null) {
responderEvent.dispatchConfig.registrationName = 'onResponderRelease';
onResponderRelease(responderEvent);
}
changeCurrentResponder(emptyResponder);
}
// Terminate
if (isTerminateEvent) {
var shouldTerminate = true;
// Responders can still avoid termination but only for these events.
if (eventType === 'contextmenu' || eventType === 'scroll' || eventType === 'selectionchange') {
// Only call this function is it wasn't already called during negotiation.
if (wasNegotiated) {
shouldTerminate = false;
} else if (onResponderTerminationRequest != null) {
responderEvent.dispatchConfig.registrationName = 'onResponderTerminationRequest';
if (onResponderTerminationRequest(responderEvent) === false) {
shouldTerminate = false;
}
}
}
if (shouldTerminate) {
if (onResponderTerminate != null) {
responderEvent.dispatchConfig.registrationName = 'onResponderTerminate';
onResponderTerminate(responderEvent);
}
changeCurrentResponder(emptyResponder);
isEmulatingMouseEvents = false;
trackedTouchCount = 0;
}
}
}
}
}
/**
* Walk the event path to/from the target node. At each node, stop and call the
* relevant "shouldSet" functions for the given event type. If any of those functions
* call "stopPropagation" on the event, stop searching for a responder.
*/
function findWantsResponder(eventPaths, domEvent, responderEvent) {
var shouldSetCallbacks = shouldSetResponderEvents[domEvent.type]; // for Flow
if (shouldSetCallbacks != null) {
var idPath = eventPaths.idPath,
nodePath = eventPaths.nodePath;
var shouldSetCallbackCaptureName = shouldSetCallbacks[0];
var shouldSetCallbackBubbleName = shouldSetCallbacks[1];
var bubbles = shouldSetCallbacks[2].bubbles;
var check = function check(id, node, callbackName) {
var config = getResponderConfig(id);
var shouldSetCallback = config[callbackName];
if (shouldSetCallback != null) {
responderEvent.currentTarget = node;
if (shouldSetCallback(responderEvent) === true) {
// Start the path from the potential responder
var prunedIdPath = idPath.slice(idPath.indexOf(id));
return {
id,
node,
idPath: prunedIdPath
};
}
}
};
// capture
for (var i = idPath.length - 1; i >= 0; i--) {
var id = idPath[i];
var node = nodePath[i];
var result = check(id, node, shouldSetCallbackCaptureName);
if (result != null) {
return result;
}
if (responderEvent.isPropagationStopped() === true) {
return;
}
}
// bubble
if (bubbles) {
for (var _i = 0; _i < idPath.length; _i++) {
var _id = idPath[_i];
var _node = nodePath[_i];
var _result = check(_id, _node, shouldSetCallbackBubbleName);
if (_result != null) {
return _result;
}
if (responderEvent.isPropagationStopped() === true) {
return;
}
}
} else {
var _id2 = idPath[0];
var _node2 = nodePath[0];
var target = domEvent.target;
if (target === _node2) {
return check(_id2, _node2, shouldSetCallbackBubbleName);
}
}
}
}
/**
* Attempt to transfer the responder.
*/
function attemptTransfer(responderEvent, wantsResponder) {
var _currentResponder2 = currentResponder,
currentId = _currentResponder2.id,
currentNode = _currentResponder2.node;
var id = wantsResponder.id,
node = wantsResponder.node;
var _getResponderConfig2 = getResponderConfig(id),
onResponderGrant = _getResponderConfig2.onResponderGrant,
onResponderReject = _getResponderConfig2.onResponderReject;
responderEvent.bubbles = false;
responderEvent.cancelable = false;
responderEvent.currentTarget = node;
// Set responder
if (currentId == null) {
if (onResponderGrant != null) {
responderEvent.currentTarget = node;
responderEvent.dispatchConfig.registrationName = 'onResponderGrant';
onResponderGrant(responderEvent);
}
changeCurrentResponder(wantsResponder);
}
// Negotiate with current responder
else {
var _getResponderConfig3 = getResponderConfig(currentId),
onResponderTerminate = _getResponderConfig3.onResponderTerminate,
onResponderTerminationRequest = _getResponderConfig3.onResponderTerminationRequest;
var allowTransfer = true;
if (onResponderTerminationRequest != null) {
responderEvent.currentTarget = currentNode;
responderEvent.dispatchConfig.registrationName = 'onResponderTerminationRequest';
if (onResponderTerminationRequest(responderEvent) === false) {
allowTransfer = false;
}
}
if (allowTransfer) {
// Terminate existing responder
if (onResponderTerminate != null) {
responderEvent.currentTarget = currentNode;
responderEvent.dispatchConfig.registrationName = 'onResponderTerminate';
onResponderTerminate(responderEvent);
}
// Grant next responder
if (onResponderGrant != null) {
responderEvent.currentTarget = node;
responderEvent.dispatchConfig.registrationName = 'onResponderGrant';
onResponderGrant(responderEvent);
}
changeCurrentResponder(wantsResponder);
} else {
// Reject responder request
if (onResponderReject != null) {
responderEvent.currentTarget = node;
responderEvent.dispatchConfig.registrationName = 'onResponderReject';
onResponderReject(responderEvent);
}
}
}
}
/* ------------ PUBLIC API ------------ */
/**
* Attach Listeners
*
* Use native events as ReactDOM doesn't have a non-plugin API to implement
* this system.
*/
var documentEventsCapturePhase = ['blur', 'scroll'];
var documentEventsBubblePhase = [
// mouse
'mousedown', 'mousemove', 'mouseup', 'dragstart',
// touch
'touchstart', 'touchmove', 'touchend', 'touchcancel',
// other
'contextmenu', 'select', 'selectionchange'];
function attachListeners() {
if (_canUseDom.default && window.__reactResponderSystemActive == null) {
window.addEventListener('blur', eventListener);
documentEventsBubblePhase.forEach(eventType => {
document.addEventListener(eventType, eventListener);
});
documentEventsCapturePhase.forEach(eventType => {
document.addEventListener(eventType, eventListener, true);
});
window.__reactResponderSystemActive = true;
}
}
/**
* Register a node with the ResponderSystem.
*/
function addNode(id, node, config) {
(0, _utils.setResponderId)(node, id);
responderListenersMap.set(id, config);
}
/**
* Unregister a node with the ResponderSystem.
*/
function removeNode(id) {
if (currentResponder.id === id) {
terminateResponder();
}
if (responderListenersMap.has(id)) {
responderListenersMap.delete(id);
}
}
/**
* Allow the current responder to be terminated from within components to support
* more complex requirements, such as use with other React libraries for working
* with scroll views, input views, etc.
*/
function terminateResponder() {
var _currentResponder3 = currentResponder,
id = _currentResponder3.id,
node = _currentResponder3.node;
if (id != null && node != null) {
var _getResponderConfig4 = getResponderConfig(id),
onResponderTerminate = _getResponderConfig4.onResponderTerminate;
if (onResponderTerminate != null) {
var event = (0, _createResponderEvent.default)({}, responderTouchHistoryStore);
event.currentTarget = node;
onResponderTerminate(event);
}
changeCurrentResponder(emptyResponder);
}
isEmulatingMouseEvents = false;
trackedTouchCount = 0;
}
/**
* Allow unit tests to inspect the current responder in the system.
* FOR TESTING ONLY.
*/
function getResponderNode() {
return currentResponder.node;
}
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/useResponderEvents/ResponderTouchHistoryStore.js
"use strict";
exports.__esModule = true;
exports.ResponderTouchHistoryStore = void 0;
var _ResponderEventTypes = require("./ResponderEventTypes");
/**
* 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.
*
*
*/
/**
* Tracks the position and time of each active touch by `touch.identifier`. We
* should typically only see IDs in the range of 1-20 because IDs get recycled
* when touches end and start again.
*/
var __DEV__ = process.env.NODE_ENV !== 'production';
var MAX_TOUCH_BANK = 20;
function timestampForTouch(touch) {
// The legacy internal implementation provides "timeStamp", which has been
// renamed to "timestamp".
return touch.timeStamp || touch.timestamp;
}
/**
* TODO: Instead of making gestures recompute filtered velocity, we could
* include a built in velocity computation that can be reused globally.
*/
function createTouchRecord(touch) {
return {
touchActive: true,
startPageX: touch.pageX,
startPageY: touch.pageY,
startTimeStamp: timestampForTouch(touch),
currentPageX: touch.pageX,
currentPageY: touch.pageY,
currentTimeStamp: timestampForTouch(touch),
previousPageX: touch.pageX,
previousPageY: touch.pageY,
previousTimeStamp: timestampForTouch(touch)
};
}
function resetTouchRecord(touchRecord, touch) {
touchRecord.touchActive = true;
touchRecord.startPageX = touch.pageX;
touchRecord.startPageY = touch.pageY;
touchRecord.startTimeStamp = timestampForTouch(touch);
touchRecord.currentPageX = touch.pageX;
touchRecord.currentPageY = touch.pageY;
touchRecord.currentTimeStamp = timestampForTouch(touch);
touchRecord.previousPageX = touch.pageX;
touchRecord.previousPageY = touch.pageY;
touchRecord.previousTimeStamp = timestampForTouch(touch);
}
function getTouchIdentifier(_ref) {
var identifier = _ref.identifier;
if (identifier == null) {
console.error('Touch object is missing identifier.');
}
if (__DEV__) {
if (identifier > MAX_TOUCH_BANK) {
console.error('Touch identifier %s is greater than maximum supported %s which causes ' + 'performance issues backfilling array locations for all of the indices.', identifier, MAX_TOUCH_BANK);
}
}
return identifier;
}
function recordTouchStart(touch, touchHistory) {
var identifier = getTouchIdentifier(touch);
var touchRecord = touchHistory.touchBank[identifier];
if (touchRecord) {
resetTouchRecord(touchRecord, touch);
} else {
touchHistory.touchBank[identifier] = createTouchRecord(touch);
}
touchHistory.mostRecentTimeStamp = timestampForTouch(touch);
}
function recordTouchMove(touch, touchHistory) {
var touchRecord = touchHistory.touchBank[getTouchIdentifier(touch)];
if (touchRecord) {
touchRecord.touchActive = true;
touchRecord.previousPageX = touchRecord.currentPageX;
touchRecord.previousPageY = touchRecord.currentPageY;
touchRecord.previousTimeStamp = touchRecord.currentTimeStamp;
touchRecord.currentPageX = touch.pageX;
touchRecord.currentPageY = touch.pageY;
touchRecord.currentTimeStamp = timestampForTouch(touch);
touchHistory.mostRecentTimeStamp = timestampForTouch(touch);
} else {
console.warn('Cannot record touch move without a touch start.\n', "Touch Move: " + printTouch(touch) + "\n", "Touch Bank: " + printTouchBank(touchHistory));
}
}
function recordTouchEnd(touch, touchHistory) {
var touchRecord = touchHistory.touchBank[getTouchIdentifier(touch)];
if (touchRecord) {
touchRecord.touchActive = false;
touchRecord.previousPageX = touchRecord.currentPageX;
touchRecord.previousPageY = touchRecord.currentPageY;
touchRecord.previousTimeStamp = touchRecord.currentTimeStamp;
touchRecord.currentPageX = touch.pageX;
touchRecord.currentPageY = touch.pageY;
touchRecord.currentTimeStamp = timestampForTouch(touch);
touchHistory.mostRecentTimeStamp = timestampForTouch(touch);
} else {
console.warn('Cannot record touch end without a touch start.\n', "Touch End: " + printTouch(touch) + "\n", "Touch Bank: " + printTouchBank(touchHistory));
}
}
function printTouch(touch) {
return JSON.stringify({
identifier: touch.identifier,
pageX: touch.pageX,
pageY: touch.pageY,
timestamp: timestampForTouch(touch)
});
}
function printTouchBank(touchHistory) {
var touchBank = touchHistory.touchBank;
var printed = JSON.stringify(touchBank.slice(0, MAX_TOUCH_BANK));
if (touchBank.length > MAX_TOUCH_BANK) {
printed += ' (original size: ' + touchBank.length + ')';
}
return printed;
}
class ResponderTouchHistoryStore {
constructor() {
this._touchHistory = {
touchBank: [],
//Array<TouchRecord>
numberActiveTouches: 0,
// If there is only one active touch, we remember its location. This prevents
// us having to loop through all of the touches all the time in the most
// common case.
indexOfSingleActiveTouch: -1,
mostRecentTimeStamp: 0
};
}
recordTouchTrack(topLevelType, nativeEvent) {
var touchHistory = this._touchHistory;
if ((0, _ResponderEventTypes.isMoveish)(topLevelType)) {
nativeEvent.changedTouches.forEach(touch => recordTouchMove(touch, touchHistory));
} else if ((0, _ResponderEventTypes.isStartish)(topLevelType)) {
nativeEvent.changedTouches.forEach(touch => recordTouchStart(touch, touchHistory));
touchHistory.numberActiveTouches = nativeEvent.touches.length;
if (touchHistory.numberActiveTouches === 1) {
touchHistory.indexOfSingleActiveTouch = nativeEvent.touches[0].identifier;
}
} else if ((0, _ResponderEventTypes.isEndish)(topLevelType)) {
nativeEvent.changedTouches.forEach(touch => recordTouchEnd(touch, touchHistory));
touchHistory.numberActiveTouches = nativeEvent.touches.length;
if (touchHistory.numberActiveTouches === 1) {
var touchBank = touchHistory.touchBank;
for (var i = 0; i < touchBank.length; i++) {
var touchTrackToCheck = touchBank[i];
if (touchTrackToCheck != null && touchTrackToCheck.touchActive) {
touchHistory.indexOfSingleActiveTouch = i;
break;
}
}
if (__DEV__) {
var activeRecord = touchBank[touchHistory.indexOfSingleActiveTouch];
if (!(activeRecord != null && activeRecord.touchActive)) {
console.error('Cannot find single active touch.');
}
}
}
}
}
get touchHistory() {
return this._touchHistory;
}
}
exports.ResponderTouchHistoryStore = ResponderTouchHistoryStore;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/useResponderEvents/createResponderEvent.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = createResponderEvent;
var _getBoundingClientRect = _interopRequireDefault(require("../../modules/getBoundingClientRect"));
/**
* 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.
*
*
*/
var emptyFunction = () => {};
var emptyObject = {};
var emptyArray = [];
/**
* Safari produces very large identifiers that would cause the `touchBank` array
* length to be so large as to crash the browser, if not normalized like this.
* In the future the `touchBank` should use an object/map instead.
*/
function normalizeIdentifier(identifier) {
return identifier > 20 ? identifier % 20 : identifier;
}
/**
* Converts a native DOM event to a ResponderEvent.
* Mouse events are transformed into fake touch events.
*/
function createResponderEvent(domEvent, responderTouchHistoryStore) {
var rect;
var propagationWasStopped = false;
var changedTouches;
var touches;
var domEventChangedTouches = domEvent.changedTouches;
var domEventType = domEvent.type;
var metaKey = domEvent.metaKey === true;
var shiftKey = domEvent.shiftKey === true;
var force = domEventChangedTouches && domEventChangedTouches[0].force || 0;
var identifier = normalizeIdentifier(domEventChangedTouches && domEventChangedTouches[0].identifier || 0);
var clientX = domEventChangedTouches && domEventChangedTouches[0].clientX || domEvent.clientX;
var clientY = domEventChangedTouches && domEventChangedTouches[0].clientY || domEvent.clientY;
var pageX = domEventChangedTouches && domEventChangedTouches[0].pageX || domEvent.pageX;
var pageY = domEventChangedTouches && domEventChangedTouches[0].pageY || domEvent.pageY;
var preventDefault = typeof domEvent.preventDefault === 'function' ? domEvent.preventDefault.bind(domEvent) : emptyFunction;
var timestamp = domEvent.timeStamp;
function normalizeTouches(touches) {
return Array.prototype.slice.call(touches).map(touch => {
return {
force: touch.force,
identifier: normalizeIdentifier(touch.identifier),
get locationX() {
return locationX(touch.clientX);
},
get locationY() {
return locationY(touch.clientY);
},
pageX: touch.pageX,
pageY: touch.pageY,
target: touch.target,
timestamp
};
});
}
if (domEventChangedTouches != null) {
changedTouches = normalizeTouches(domEventChangedTouches);
touches = normalizeTouches(domEvent.touches);
} else {
var emulatedTouches = [{
force,
identifier,
get locationX() {
return locationX(clientX);
},
get locationY() {
return locationY(clientY);
},
pageX,
pageY,
target: domEvent.target,
timestamp
}];
changedTouches = emulatedTouches;
touches = domEventType === 'mouseup' || domEventType === 'dragstart' ? emptyArray : emulatedTouches;
}
var responderEvent = {
bubbles: true,
cancelable: true,
// `currentTarget` is set before dispatch
currentTarget: null,
defaultPrevented: domEvent.defaultPrevented,
dispatchConfig: emptyObject,
eventPhase: domEvent.eventPhase,
isDefaultPrevented() {
return domEvent.defaultPrevented;
},
isPropagationStopped() {
return propagationWasStopped;
},
isTrusted: domEvent.isTrusted,
nativeEvent: {
altKey: false,
ctrlKey: false,
metaKey,
shiftKey,
changedTouches,
force,
identifier,
get locationX() {
return locationX(clientX);
},
get locationY() {
return locationY(clientY);
},
pageX,
pageY,
target: domEvent.target,
timestamp,
touches,
type: domEventType
},
persist: emptyFunction,
preventDefault,
stopPropagation() {
propagationWasStopped = true;
},
target: domEvent.target,
timeStamp: timestamp,
touchHistory: responderTouchHistoryStore.touchHistory
};
// Using getters and functions serves two purposes:
// 1) The value of `currentTarget` is not initially available.
// 2) Measuring the clientRect may cause layout jank and should only be done on-demand.
function locationX(x) {
rect = rect || (0, _getBoundingClientRect.default)(responderEvent.currentTarget);
if (rect) {
return x - rect.left;
}
}
function locationY(y) {
rect = rect || (0, _getBoundingClientRect.default)(responderEvent.currentTarget);
if (rect) {
return y - rect.top;
}
}
return responderEvent;
}
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/useResponderEvents/index.js
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = useResponderEvents;
var React = _interopRequireWildcard(require("react"));
var ResponderSystem = _interopRequireWildcard(require("./ResponderSystem"));
/**
* 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.
*
*
*/
/**
* Hook for integrating the Responder System into React
*
* function SomeComponent({ onStartShouldSetResponder }) {
* const ref = useRef(null);
* useResponderEvents(ref, { onStartShouldSetResponder });
* return <div ref={ref} />
* }
*/
var emptyObject = {};
var idCounter = 0;
function useStable(getInitialValue) {
var ref = React.useRef(null);
if (ref.current == null) {
ref.current = getInitialValue();
}
return ref.current;
}
function useResponderEvents(hostRef, config) {
if (config === void 0) {
config = emptyObject;
}
var id = useStable(() => idCounter++);
var isAttachedRef = React.useRef(false);
// This is a separate effects so it doesn't run when the config changes.
// On initial mount, attach global listeners if needed.
// On unmount, remove node potentially attached to the Responder System.
React.useEffect(() => {
ResponderSystem.attachListeners();
return () => {
ResponderSystem.removeNode(id);
};
}, [id]);
// Register and unregister with the Responder System as necessary
React.useEffect(() => {
var _config = config,
onMoveShouldSetResponder = _config.onMoveShouldSetResponder,
onMoveShouldSetResponderCapture = _config.onMoveShouldSetResponderCapture,
onScrollShouldSetResponder = _config.onScrollShouldSetResponder,
onScrollShouldSetResponderCapture = _config.onScrollShouldSetResponderCapture,
onSelectionChangeShouldSetResponder = _config.onSelectionChangeShouldSetResponder,
onSelectionChangeShouldSetResponderCapture = _config.onSelectionChangeShouldSetResponderCapture,
onStartShouldSetResponder = _config.onStartShouldSetResponder,
onStartShouldSetResponderCapture = _config.onStartShouldSetResponderCapture;
var requiresResponderSystem = onMoveShouldSetResponder != null || onMoveShouldSetResponderCapture != null || onScrollShouldSetResponder != null || onScrollShouldSetResponderCapture != null || onSelectionChangeShouldSetResponder != null || onSelectionChangeShouldSetResponderCapture != null || onStartShouldSetResponder != null || onStartShouldSetResponderCapture != null;
var node = hostRef.current;
if (requiresResponderSystem) {
ResponderSystem.addNode(id, node, config);
isAttachedRef.current = true;
} else if (isAttachedRef.current) {
ResponderSystem.removeNode(id);
isAttachedRef.current = false;
}
}, [config, hostRef, id]);
React.useDebugValue({
isResponder: hostRef.current === ResponderSystem.getResponderNode()
});
React.useDebugValue(config);
}
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/useResponderEvents/utils.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.getLowestCommonAncestor = getLowestCommonAncestor;
exports.getResponderPaths = getResponderPaths;
exports.hasTargetTouches = hasTargetTouches;
exports.hasValidSelection = hasValidSelection;
exports.isPrimaryPointerDown = isPrimaryPointerDown;
exports.setResponderId = setResponderId;
var _isSelectionValid = _interopRequireDefault(require("../../modules/isSelectionValid"));
/**
* 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.
*
*
*/
var keyName = '__reactResponderId';
function getEventPath(domEvent) {
// The 'selectionchange' event always has the 'document' as the target.
// Use the anchor node as the initial target to reconstruct a path.
// (We actually only need the first "responder" node in practice.)
if (domEvent.type === 'selectionchange') {
var target = window.getSelection().anchorNode;
return composedPathFallback(target);
} else {
var path = domEvent.composedPath != null ? domEvent.composedPath() : composedPathFallback(domEvent.target);
return path;
}
}
function composedPathFallback(target) {
var path = [];
while (target != null && target !== document.body) {
path.push(target);
target = target.parentNode;
}
return path;
}
/**
* Retrieve the responderId from a host node
*/
function getResponderId(node) {
if (node != null) {
return node[keyName];
}
return null;
}
/**
* Store the responderId on a host node
*/
function setResponderId(node, id) {
if (node != null) {
node[keyName] = id;
}
}
/**
* Filter the event path to contain only the nodes attached to the responder system
*/
function getResponderPaths(domEvent) {
var idPath = [];
var nodePath = [];
var eventPath = getEventPath(domEvent);
for (var i = 0; i < eventPath.length; i++) {
var node = eventPath[i];
var id = getResponderId(node);
if (id != null) {
idPath.push(id);
nodePath.push(node);
}
}
return {
idPath,
nodePath
};
}
/**
* Walk the paths and find the first common ancestor
*/
function getLowestCommonAncestor(pathA, pathB) {
var pathALength = pathA.length;
var pathBLength = pathB.length;
if (
// If either path is empty
pathALength === 0 || pathBLength === 0 ||
// If the last elements aren't the same there can't be a common ancestor
// that is connected to the responder system
pathA[pathALength - 1] !== pathB[pathBLength - 1]) {
return null;
}
var itemA = pathA[0];
var indexA = 0;
var itemB = pathB[0];
var indexB = 0;
// If A is deeper, skip indices that can't match.
if (pathALength - pathBLength > 0) {
indexA = pathALength - pathBLength;
itemA = pathA[indexA];
pathALength = pathBLength;
}
// If B is deeper, skip indices that can't match
if (pathBLength - pathALength > 0) {
indexB = pathBLength - pathALength;
itemB = pathB[indexB];
pathBLength = pathALength;
}
// Walk in lockstep until a match is found
var depth = pathALength;
while (depth--) {
if (itemA === itemB) {
return itemA;
}
itemA = pathA[indexA++];
itemB = pathB[indexB++];
}
return null;
}
/**
* Determine whether any of the active touches are within the current responder.
* This cannot rely on W3C `targetTouches`, as neither IE11 nor Safari implement it.
*/
function hasTargetTouches(target, touches) {
if (!touches || touches.length === 0) {
return false;
}
for (var i = 0; i < touches.length; i++) {
var node = touches[i].target;
if (node != null) {
if (target.contains(node)) {
return true;
}
}
}
return false;
}
/**
* Ignore 'selectionchange' events that don't correspond with a person's intent to
* select text.
*/
function hasValidSelection(domEvent) {
if (domEvent.type === 'selectionchange') {
return (0, _isSelectionValid.default)();
}
return domEvent.type === 'select';
}
/**
* Events are only valid if the primary button was used without specific modifier keys.
*/
function isPrimaryPointerDown(domEvent) {
var altKey = domEvent.altKey,
button = domEvent.button,
buttons = domEvent.buttons,
ctrlKey = domEvent.ctrlKey,
type = domEvent.type;
var isTouch = type === 'touchstart' || type === 'touchmove';
var isPrimaryMouseDown = type === 'mousedown' && (button === 0 || buttons === 1);
var isPrimaryMouseMove = type === 'mousemove' && buttons === 1;
var noModifiers = altKey === false && ctrlKey === false;
if (isTouch || isPrimaryMouseDown && noModifiers || isPrimaryMouseMove && noModifiers) {
return true;
}
return false;
}
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/useStable/index.js
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = useStable;
var React = _interopRequireWildcard(require("react"));
/**
* 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.
*
*
*/
var UNINITIALIZED = typeof Symbol === 'function' && typeof Symbol() === 'symbol' ? Symbol() : Object.freeze({});
function useStable(getInitialValue) {
var ref = React.useRef(UNINITIALIZED);
if (ref.current === UNINITIALIZED) {
ref.current = getInitialValue();
}
// $FlowFixMe (#64650789) Trouble refining types where `Symbol` is concerned.
return ref.current;
}
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/modules/warnOnce/index.js
"use strict";
exports.__esModule = true;
exports.warnOnce = warnOnce;
/**
* 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.
*
*
*/
var warnedKeys = {};
/**
* A simple function that prints a warning message once per session.
*
* @param {string} key - The key used to ensure the message is printed once.
* This should be unique to the callsite.
* @param {string} message - The message to print
*/
function warnOnce(key, message) {
if (process.env.NODE_ENV !== 'production') {
if (warnedKeys[key]) {
return;
}
console.warn(message);
warnedKeys[key] = true;
}
}
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/Animated.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _Platform = _interopRequireDefault(require("../../../exports/Platform"));
var _AnimatedFlatList = _interopRequireDefault(require("./components/AnimatedFlatList"));
var _AnimatedImage = _interopRequireDefault(require("./components/AnimatedImage"));
var _AnimatedScrollView = _interopRequireDefault(require("./components/AnimatedScrollView"));
var _AnimatedSectionList = _interopRequireDefault(require("./components/AnimatedSectionList"));
var _AnimatedText = _interopRequireDefault(require("./components/AnimatedText"));
var _AnimatedView = _interopRequireDefault(require("./components/AnimatedView"));
var _AnimatedMock = _interopRequireDefault(require("./AnimatedMock"));
var _AnimatedImplementation = _interopRequireDefault(require("./AnimatedImplementation"));
/**
* 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.
*
*
* @format
*/
var Animated = _Platform.default.isTesting ? _AnimatedMock.default : _AnimatedImplementation.default;
var _default = (0, _objectSpread2.default)({
FlatList: _AnimatedFlatList.default,
Image: _AnimatedImage.default,
ScrollView: _AnimatedScrollView.default,
SectionList: _AnimatedSectionList.default,
Text: _AnimatedText.default,
View: _AnimatedView.default
}, Animated);
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/AnimatedEvent.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.AnimatedEvent = void 0;
exports.attachNativeEvent = attachNativeEvent;
var _AnimatedValue = _interopRequireDefault(require("./nodes/AnimatedValue"));
var _NativeAnimatedHelper = _interopRequireWildcard(require("./NativeAnimatedHelper"));
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
var __DEV__ = process.env.NODE_ENV !== 'production';
function attachNativeEvent(viewRef, eventName, argMapping) {
// Find animated values in `argMapping` and create an array representing their
// key path inside the `nativeEvent` object. Ex.: ['contentOffset', 'x'].
var eventMappings = [];
var traverse = (value, path) => {
if (value instanceof _AnimatedValue.default) {
value.__makeNative();
eventMappings.push({
nativeEventPath: path,
animatedValueTag: value.__getNativeTag()
});
} else if (typeof value === 'object') {
for (var _key in value) {
traverse(value[_key], path.concat(_key));
}
}
};
(0, _invariant.default)(argMapping[0] && argMapping[0].nativeEvent, 'Native driven events only support animated values contained inside `nativeEvent`.');
// Assume that the event containing `nativeEvent` is always the first argument.
traverse(argMapping[0].nativeEvent, []);
if (viewRef != null) {
eventMappings.forEach(mapping => {
_NativeAnimatedHelper.default.API.addAnimatedEventToView(viewRef, eventName, mapping);
});
}
return {
detach() {
if (viewRef != null) {
eventMappings.forEach(mapping => {
_NativeAnimatedHelper.default.API.removeAnimatedEventFromView(viewRef, eventName,
// $FlowFixMe[incompatible-call]
mapping.animatedValueTag);
});
}
}
};
}
function validateMapping(argMapping, args) {
var validate = (recMapping, recEvt, key) => {
if (recMapping instanceof _AnimatedValue.default) {
(0, _invariant.default)(typeof recEvt === 'number', 'Bad mapping of event key ' + key + ', should be number but got ' + typeof recEvt);
return;
}
if (typeof recEvt === 'number') {
(0, _invariant.default)(recMapping instanceof _AnimatedValue.default, 'Bad mapping of type ' + typeof recMapping + ' for key ' + key + ', event value must map to AnimatedValue');
return;
}
(0, _invariant.default)(typeof recMapping === 'object', 'Bad mapping of type ' + typeof recMapping + ' for key ' + key);
(0, _invariant.default)(typeof recEvt === 'object', 'Bad event of type ' + typeof recEvt + ' for key ' + key);
for (var mappingKey in recMapping) {
validate(recMapping[mappingKey], recEvt[mappingKey], mappingKey);
}
};
(0, _invariant.default)(args.length >= argMapping.length, 'Event has less arguments than mapping');
argMapping.forEach((mapping, idx) => {
validate(mapping, args[idx], 'arg' + idx);
});
}
class AnimatedEvent {
constructor(argMapping, config) {
this._listeners = [];
this._argMapping = argMapping;
if (config == null) {
console.warn('Animated.event now requires a second argument for options');
config = {
useNativeDriver: false
};
}
if (config.listener) {
this.__addListener(config.listener);
}
this._callListeners = this._callListeners.bind(this);
this._attachedEvent = null;
this.__isNative = (0, _NativeAnimatedHelper.shouldUseNativeDriver)(config);
}
__addListener(callback) {
this._listeners.push(callback);
}
__removeListener(callback) {
this._listeners = this._listeners.filter(listener => listener !== callback);
}
__attach(viewRef, eventName) {
(0, _invariant.default)(this.__isNative, 'Only native driven events need to be attached.');
this._attachedEvent = attachNativeEvent(viewRef, eventName, this._argMapping);
}
__detach(viewTag, eventName) {
(0, _invariant.default)(this.__isNative, 'Only native driven events need to be detached.');
this._attachedEvent && this._attachedEvent.detach();
}
__getHandler() {
var _this = this;
if (this.__isNative) {
if (__DEV__) {
var _validatedMapping = false;
return function () {
for (var _len = arguments.length, args = new Array(_len), _key2 = 0; _key2 < _len; _key2++) {
args[_key2] = arguments[_key2];
}
if (!_validatedMapping) {
validateMapping(_this._argMapping, args);
_validatedMapping = true;
}
_this._callListeners(...args);
};
} else {
return this._callListeners;
}
}
var validatedMapping = false;
return function () {
for (var _len2 = arguments.length, args = new Array(_len2), _key3 = 0; _key3 < _len2; _key3++) {
args[_key3] = arguments[_key3];
}
if (__DEV__ && !validatedMapping) {
validateMapping(_this._argMapping, args);
validatedMapping = true;
}
var traverse = (recMapping, recEvt, key) => {
if (recMapping instanceof _AnimatedValue.default) {
if (typeof recEvt === 'number') {
recMapping.setValue(recEvt);
}
} else if (typeof recMapping === 'object') {
for (var mappingKey in recMapping) {
/* $FlowFixMe(>=0.120.0) This comment suppresses an error found
* when Flow v0.120 was deployed. To see the error, delete this
* comment and run Flow. */
traverse(recMapping[mappingKey], recEvt[mappingKey], mappingKey);
}
}
};
_this._argMapping.forEach((mapping, idx) => {
traverse(mapping, args[idx], 'arg' + idx);
});
_this._callListeners(...args);
};
}
_callListeners() {
for (var _len3 = arguments.length, args = new Array(_len3), _key4 = 0; _key4 < _len3; _key4++) {
args[_key4] = arguments[_key4];
}
this._listeners.forEach(listener => listener(...args));
}
}
exports.AnimatedEvent = AnimatedEvent;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/AnimatedImplementation.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _AnimatedEvent = require("./AnimatedEvent");
var _AnimatedAddition = _interopRequireDefault(require("./nodes/AnimatedAddition"));
var _AnimatedDiffClamp = _interopRequireDefault(require("./nodes/AnimatedDiffClamp"));
var _AnimatedDivision = _interopRequireDefault(require("./nodes/AnimatedDivision"));
var _AnimatedInterpolation = _interopRequireDefault(require("./nodes/AnimatedInterpolation"));
var _AnimatedModulo = _interopRequireDefault(require("./nodes/AnimatedModulo"));
var _AnimatedMultiplication = _interopRequireDefault(require("./nodes/AnimatedMultiplication"));
var _AnimatedNode = _interopRequireDefault(require("./nodes/AnimatedNode"));
var _AnimatedProps = _interopRequireDefault(require("./nodes/AnimatedProps"));
var _AnimatedSubtraction = _interopRequireDefault(require("./nodes/AnimatedSubtraction"));
var _AnimatedTracking = _interopRequireDefault(require("./nodes/AnimatedTracking"));
var _AnimatedValue = _interopRequireDefault(require("./nodes/AnimatedValue"));
var _AnimatedValueXY = _interopRequireDefault(require("./nodes/AnimatedValueXY"));
var _DecayAnimation = _interopRequireDefault(require("./animations/DecayAnimation"));
var _SpringAnimation = _interopRequireDefault(require("./animations/SpringAnimation"));
var _TimingAnimation = _interopRequireDefault(require("./animations/TimingAnimation"));
var _createAnimatedComponent = _interopRequireDefault(require("./createAnimatedComponent"));
var _AnimatedColor = _interopRequireDefault(require("./nodes/AnimatedColor"));
var add = function add(a, b) {
return new _AnimatedAddition.default(a, b);
};
var subtract = function subtract(a, b) {
return new _AnimatedSubtraction.default(a, b);
};
var divide = function divide(a, b) {
return new _AnimatedDivision.default(a, b);
};
var multiply = function multiply(a, b) {
return new _AnimatedMultiplication.default(a, b);
};
var modulo = function modulo(a, modulus) {
return new _AnimatedModulo.default(a, modulus);
};
var diffClamp = function diffClamp(a, min, max) {
return new _AnimatedDiffClamp.default(a, min, max);
};
var _combineCallbacks = function _combineCallbacks(callback, config) {
if (callback && config.onComplete) {
return function () {
config.onComplete && config.onComplete(...arguments);
callback && callback(...arguments);
};
} else {
return callback || config.onComplete;
}
};
var maybeVectorAnim = function maybeVectorAnim(value, config, anim) {
if (value instanceof _AnimatedValueXY.default) {
var configX = (0, _objectSpread2.default)({}, config);
var configY = (0, _objectSpread2.default)({}, config);
for (var key in config) {
var _config$key = config[key],
x = _config$key.x,
y = _config$key.y;
if (x !== undefined && y !== undefined) {
configX[key] = x;
configY[key] = y;
}
}
var aX = anim(value.x, configX);
var aY = anim(value.y, configY);
// We use `stopTogether: false` here because otherwise tracking will break
// because the second animation will get stopped before it can update.
return parallel([aX, aY], {
stopTogether: false
});
} else if (value instanceof _AnimatedColor.default) {
var configR = (0, _objectSpread2.default)({}, config);
var configG = (0, _objectSpread2.default)({}, config);
var configB = (0, _objectSpread2.default)({}, config);
var configA = (0, _objectSpread2.default)({}, config);
for (var _key in config) {
var _config$_key = config[_key],
r = _config$_key.r,
g = _config$_key.g,
b = _config$_key.b,
a = _config$_key.a;
if (r !== undefined && g !== undefined && b !== undefined && a !== undefined) {
configR[_key] = r;
configG[_key] = g;
configB[_key] = b;
configA[_key] = a;
}
}
var aR = anim(value.r, configR);
var aG = anim(value.g, configG);
var aB = anim(value.b, configB);
var aA = anim(value.a, configA);
// We use `stopTogether: false` here because otherwise tracking will break
// because the second animation will get stopped before it can update.
return parallel([aR, aG, aB, aA], {
stopTogether: false
});
}
return null;
};
var spring = function spring(value, config) {
var _start = function start(animatedValue, configuration, callback) {
callback = _combineCallbacks(callback, configuration);
var singleValue = animatedValue;
var singleConfig = configuration;
singleValue.stopTracking();
if (configuration.toValue instanceof _AnimatedNode.default) {
singleValue.track(new _AnimatedTracking.default(singleValue, configuration.toValue, _SpringAnimation.default, singleConfig, callback));
} else {
singleValue.animate(new _SpringAnimation.default(singleConfig), callback);
}
};
return maybeVectorAnim(value, config, spring) || {
start: function start(callback) {
_start(value, config, callback);
},
stop: function stop() {
value.stopAnimation();
},
reset: function reset() {
value.resetAnimation();
},
_startNativeLoop: function _startNativeLoop(iterations) {
var singleConfig = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, config), {}, {
iterations
});
_start(value, singleConfig);
},
_isUsingNativeDriver: function _isUsingNativeDriver() {
return config.useNativeDriver || false;
}
};
};
var timing = function timing(value, config) {
var _start2 = function start(animatedValue, configuration, callback) {
callback = _combineCallbacks(callback, configuration);
var singleValue = animatedValue;
var singleConfig = configuration;
singleValue.stopTracking();
if (configuration.toValue instanceof _AnimatedNode.default) {
singleValue.track(new _AnimatedTracking.default(singleValue, configuration.toValue, _TimingAnimation.default, singleConfig, callback));
} else {
singleValue.animate(new _TimingAnimation.default(singleConfig), callback);
}
};
return maybeVectorAnim(value, config, timing) || {
start: function start(callback) {
_start2(value, config, callback);
},
stop: function stop() {
value.stopAnimation();
},
reset: function reset() {
value.resetAnimation();
},
_startNativeLoop: function _startNativeLoop(iterations) {
var singleConfig = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, config), {}, {
iterations
});
_start2(value, singleConfig);
},
_isUsingNativeDriver: function _isUsingNativeDriver() {
return config.useNativeDriver || false;
}
};
};
var decay = function decay(value, config) {
var _start3 = function start(animatedValue, configuration, callback) {
callback = _combineCallbacks(callback, configuration);
var singleValue = animatedValue;
var singleConfig = configuration;
singleValue.stopTracking();
singleValue.animate(new _DecayAnimation.default(singleConfig), callback);
};
return maybeVectorAnim(value, config, decay) || {
start: function start(callback) {
_start3(value, config, callback);
},
stop: function stop() {
value.stopAnimation();
},
reset: function reset() {
value.resetAnimation();
},
_startNativeLoop: function _startNativeLoop(iterations) {
var singleConfig = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, config), {}, {
iterations
});
_start3(value, singleConfig);
},
_isUsingNativeDriver: function _isUsingNativeDriver() {
return config.useNativeDriver || false;
}
};
};
var sequence = function sequence(animations) {
var current = 0;
return {
start: function start(callback) {
var onComplete = function onComplete(result) {
if (!result.finished) {
callback && callback(result);
return;
}
current++;
if (current === animations.length) {
callback && callback(result);
return;
}
animations[current].start(onComplete);
};
if (animations.length === 0) {
callback && callback({
finished: true
});
} else {
animations[current].start(onComplete);
}
},
stop: function stop() {
if (current < animations.length) {
animations[current].stop();
}
},
reset: function reset() {
animations.forEach((animation, idx) => {
if (idx <= current) {
animation.reset();
}
});
current = 0;
},
_startNativeLoop: function _startNativeLoop() {
throw new Error('Loops run using the native driver cannot contain Animated.sequence animations');
},
_isUsingNativeDriver: function _isUsingNativeDriver() {
return false;
}
};
};
var parallel = function parallel(animations, config) {
var doneCount = 0;
// Make sure we only call stop() at most once for each animation
var hasEnded = {};
var stopTogether = !(config && config.stopTogether === false);
var result = {
start: function start(callback) {
if (doneCount === animations.length) {
callback && callback({
finished: true
});
return;
}
animations.forEach((animation, idx) => {
var cb = function cb(endResult) {
hasEnded[idx] = true;
doneCount++;
if (doneCount === animations.length) {
doneCount = 0;
callback && callback(endResult);
return;
}
if (!endResult.finished && stopTogether) {
result.stop();
}
};
if (!animation) {
cb({
finished: true
});
} else {
animation.start(cb);
}
});
},
stop: function stop() {
animations.forEach((animation, idx) => {
!hasEnded[idx] && animation.stop();
hasEnded[idx] = true;
});
},
reset: function reset() {
animations.forEach((animation, idx) => {
animation.reset();
hasEnded[idx] = false;
doneCount = 0;
});
},
_startNativeLoop: function _startNativeLoop() {
throw new Error('Loops run using the native driver cannot contain Animated.parallel animations');
},
_isUsingNativeDriver: function _isUsingNativeDriver() {
return false;
}
};
return result;
};
var delay = function delay(time) {
// Would be nice to make a specialized implementation
return timing(new _AnimatedValue.default(0), {
toValue: 0,
delay: time,
duration: 0,
useNativeDriver: false
});
};
var stagger = function stagger(time, animations) {
return parallel(animations.map((animation, i) => {
return sequence([delay(time * i), animation]);
}));
};
var loop = function loop(animation, // $FlowFixMe[prop-missing]
_temp) {
var _ref = _temp === void 0 ? {} : _temp,
_ref$iterations = _ref.iterations,
iterations = _ref$iterations === void 0 ? -1 : _ref$iterations,
_ref$resetBeforeItera = _ref.resetBeforeIteration,
resetBeforeIteration = _ref$resetBeforeItera === void 0 ? true : _ref$resetBeforeItera;
var isFinished = false;
var iterationsSoFar = 0;
return {
start: function start(callback) {
var restart = function restart(result) {
if (result === void 0) {
result = {
finished: true
};
}
if (isFinished || iterationsSoFar === iterations || result.finished === false) {
callback && callback(result);
} else {
iterationsSoFar++;
resetBeforeIteration && animation.reset();
animation.start(restart);
}
};
if (!animation || iterations === 0) {
callback && callback({
finished: true
});
} else {
if (animation._isUsingNativeDriver()) {
animation._startNativeLoop(iterations);
} else {
restart(); // Start looping recursively on the js thread
}
}
},
stop: function stop() {
isFinished = true;
animation.stop();
},
reset: function reset() {
iterationsSoFar = 0;
isFinished = false;
animation.reset();
},
_startNativeLoop: function _startNativeLoop() {
throw new Error('Loops run using the native driver cannot contain Animated.loop animations');
},
_isUsingNativeDriver: function _isUsingNativeDriver() {
return animation._isUsingNativeDriver();
}
};
};
function forkEvent(event, listener) {
if (!event) {
return listener;
} else if (event instanceof _AnimatedEvent.AnimatedEvent) {
event.__addListener(listener);
return event;
} else {
return function () {
typeof event === 'function' && event(...arguments);
listener(...arguments);
};
}
}
function unforkEvent(event, listener) {
if (event && event instanceof _AnimatedEvent.AnimatedEvent) {
event.__removeListener(listener);
}
}
var event = function event(argMapping, config) {
var animatedEvent = new _AnimatedEvent.AnimatedEvent(argMapping, config);
if (animatedEvent.__isNative) {
return animatedEvent;
} else {
return animatedEvent.__getHandler();
}
};
// All types of animated nodes that represent scalar numbers and can be interpolated (etc)
/**
* The `Animated` library is designed to make animations fluid, powerful, and
* easy to build and maintain. `Animated` focuses on declarative relationships
* between inputs and outputs, with configurable transforms in between, and
* simple `start`/`stop` methods to control time-based animation execution.
* If additional transforms are added, be sure to include them in
* AnimatedMock.js as well.
*
* See https://reactnative.dev/docs/animated
*/
var _default = {
/**
* Standard value class for driving animations. Typically initialized with
* `new Animated.Value(0);`
*
* See https://reactnative.dev/docs/animated#value
*/
Value: _AnimatedValue.default,
/**
* 2D value class for driving 2D animations, such as pan gestures.
*
* See https://reactnative.dev/docs/animatedvaluexy
*/
ValueXY: _AnimatedValueXY.default,
/**
* Value class for driving color animations.
*/
Color: _AnimatedColor.default,
/**
* Exported to use the Interpolation type in flow.
*
* See https://reactnative.dev/docs/animated#interpolation
*/
Interpolation: _AnimatedInterpolation.default,
/**
* Exported for ease of type checking. All animated values derive from this
* class.
*
* See https://reactnative.dev/docs/animated#node
*/
Node: _AnimatedNode.default,
/**
* Animates a value from an initial velocity to zero based on a decay
* coefficient.
*
* See https://reactnative.dev/docs/animated#decay
*/
decay,
/**
* Animates a value along a timed easing curve. The Easing module has tons of
* predefined curves, or you can use your own function.
*
* See https://reactnative.dev/docs/animated#timing
*/
timing,
/**
* Animates a value according to an analytical spring model based on
* damped harmonic oscillation.
*
* See https://reactnative.dev/docs/animated#spring
*/
spring,
/**
* Creates a new Animated value composed from two Animated values added
* together.
*
* See https://reactnative.dev/docs/animated#add
*/
add,
/**
* Creates a new Animated value composed by subtracting the second Animated
* value from the first Animated value.
*
* See https://reactnative.dev/docs/animated#subtract
*/
subtract,
/**
* Creates a new Animated value composed by dividing the first Animated value
* by the second Animated value.
*
* See https://reactnative.dev/docs/animated#divide
*/
divide,
/**
* Creates a new Animated value composed from two Animated values multiplied
* together.
*
* See https://reactnative.dev/docs/animated#multiply
*/
multiply,
/**
* Creates a new Animated value that is the (non-negative) modulo of the
* provided Animated value.
*
* See https://reactnative.dev/docs/animated#modulo
*/
modulo,
/**
* Create a new Animated value that is limited between 2 values. It uses the
* difference between the last value so even if the value is far from the
* bounds it will start changing when the value starts getting closer again.
*
* See https://reactnative.dev/docs/animated#diffclamp
*/
diffClamp,
/**
* Starts an animation after the given delay.
*
* See https://reactnative.dev/docs/animated#delay
*/
delay,
/**
* Starts an array of animations in order, waiting for each to complete
* before starting the next. If the current running animation is stopped, no
* following animations will be started.
*
* See https://reactnative.dev/docs/animated#sequence
*/
sequence,
/**
* Starts an array of animations all at the same time. By default, if one
* of the animations is stopped, they will all be stopped. You can override
* this with the `stopTogether` flag.
*
* See https://reactnative.dev/docs/animated#parallel
*/
parallel,
/**
* Array of animations may run in parallel (overlap), but are started in
* sequence with successive delays. Nice for doing trailing effects.
*
* See https://reactnative.dev/docs/animated#stagger
*/
stagger,
/**
* Loops a given animation continuously, so that each time it reaches the
* end, it resets and begins again from the start.
*
* See https://reactnative.dev/docs/animated#loop
*/
loop,
/**
* Takes an array of mappings and extracts values from each arg accordingly,
* then calls `setValue` on the mapped outputs.
*
* See https://reactnative.dev/docs/animated#event
*/
event,
/**
* Make any React component Animatable. Used to create `Animated.View`, etc.
*
* See https://reactnative.dev/docs/animated#createanimatedcomponent
*/
createAnimatedComponent: _createAnimatedComponent.default,
/**
* Imperative API to attach an animated value to an event on a view. Prefer
* using `Animated.event` with `useNativeDrive: true` if possible.
*
* See https://reactnative.dev/docs/animated#attachnativeevent
*/
attachNativeEvent: _AnimatedEvent.attachNativeEvent,
/**
* Advanced imperative API for snooping on animated events that are passed in
* through props. Use values directly where possible.
*
* See https://reactnative.dev/docs/animated#forkevent
*/
forkEvent,
unforkEvent,
/**
* Expose Event class, so it can be used as a type for type checkers.
*/
Event: _AnimatedEvent.AnimatedEvent
};
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/AnimatedMock.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _AnimatedEvent = require("./AnimatedEvent");
var _AnimatedImplementation = _interopRequireDefault(require("./AnimatedImplementation"));
var _AnimatedInterpolation = _interopRequireDefault(require("./nodes/AnimatedInterpolation"));
var _AnimatedNode = _interopRequireDefault(require("./nodes/AnimatedNode"));
var _AnimatedValue = _interopRequireDefault(require("./nodes/AnimatedValue"));
var _AnimatedValueXY = _interopRequireDefault(require("./nodes/AnimatedValueXY"));
var _createAnimatedComponent = _interopRequireDefault(require("./createAnimatedComponent"));
var _AnimatedColor = _interopRequireDefault(require("./nodes/AnimatedColor"));
/**
* Animations are a source of flakiness in snapshot testing. This mock replaces
* animation functions from AnimatedImplementation with empty animations for
* predictability in tests. When possible the animation will run immediately
* to the final state.
*/
// Prevent any callback invocation from recursively triggering another
// callback, which may trigger another animation
var inAnimationCallback = false;
function mockAnimationStart(start) {
return callback => {
var guardedCallback = callback == null ? callback : function () {
if (inAnimationCallback) {
console.warn('Ignoring recursive animation callback when running mock animations');
return;
}
inAnimationCallback = true;
try {
callback(...arguments);
} finally {
inAnimationCallback = false;
}
};
start(guardedCallback);
};
}
var emptyAnimation = {
start: () => {},
stop: () => {},
reset: () => {},
_startNativeLoop: () => {},
_isUsingNativeDriver: () => {
return false;
}
};
var mockCompositeAnimation = animations => (0, _objectSpread2.default)((0, _objectSpread2.default)({}, emptyAnimation), {}, {
start: mockAnimationStart(callback => {
animations.forEach(animation => animation.start());
callback == null ? void 0 : callback({
finished: true
});
})
});
var spring = function spring(value, config) {
var anyValue = value;
return (0, _objectSpread2.default)((0, _objectSpread2.default)({}, emptyAnimation), {}, {
start: mockAnimationStart(callback => {
anyValue.setValue(config.toValue);
callback == null ? void 0 : callback({
finished: true
});
})
});
};
var timing = function timing(value, config) {
var anyValue = value;
return (0, _objectSpread2.default)((0, _objectSpread2.default)({}, emptyAnimation), {}, {
start: mockAnimationStart(callback => {
anyValue.setValue(config.toValue);
callback == null ? void 0 : callback({
finished: true
});
})
});
};
var decay = function decay(value, config) {
return emptyAnimation;
};
var sequence = function sequence(animations) {
return mockCompositeAnimation(animations);
};
var parallel = function parallel(animations, config) {
return mockCompositeAnimation(animations);
};
var delay = function delay(time) {
return emptyAnimation;
};
var stagger = function stagger(time, animations) {
return mockCompositeAnimation(animations);
};
var loop = function loop(animation, // $FlowFixMe[prop-missing]
_temp) {
var _ref = _temp === void 0 ? {} : _temp,
_ref$iterations = _ref.iterations,
iterations = _ref$iterations === void 0 ? -1 : _ref$iterations;
return emptyAnimation;
};
var _default = {
Value: _AnimatedValue.default,
ValueXY: _AnimatedValueXY.default,
Color: _AnimatedColor.default,
Interpolation: _AnimatedInterpolation.default,
Node: _AnimatedNode.default,
decay,
timing,
spring,
add: _AnimatedImplementation.default.add,
subtract: _AnimatedImplementation.default.subtract,
divide: _AnimatedImplementation.default.divide,
multiply: _AnimatedImplementation.default.multiply,
modulo: _AnimatedImplementation.default.modulo,
diffClamp: _AnimatedImplementation.default.diffClamp,
delay,
sequence,
parallel,
stagger,
loop,
event: _AnimatedImplementation.default.event,
createAnimatedComponent: _createAnimatedComponent.default,
attachNativeEvent: _AnimatedEvent.attachNativeEvent,
forkEvent: _AnimatedImplementation.default.forkEvent,
unforkEvent: _AnimatedImplementation.default.unforkEvent,
Event: _AnimatedEvent.AnimatedEvent
};
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/Easing.js
/**
* 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.
*
* @format
*
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _bezier2 = _interopRequireDefault(require("./bezier"));
var ease;
/**
* The `Easing` module implements common easing functions. This module is used
* by [Animate.timing()](docs/animate.html#timing) to convey physically
* believable motion in animations.
*
* You can find a visualization of some common easing functions at
* http://easings.net/
*
* ### Predefined animations
*
* The `Easing` module provides several predefined animations through the
* following methods:
*
* - [`back`](docs/easing.html#back) provides a simple animation where the
* object goes slightly back before moving forward
* - [`bounce`](docs/easing.html#bounce) provides a bouncing animation
* - [`ease`](docs/easing.html#ease) provides a simple inertial animation
* - [`elastic`](docs/easing.html#elastic) provides a simple spring interaction
*
* ### Standard functions
*
* Three standard easing functions are provided:
*
* - [`linear`](docs/easing.html#linear)
* - [`quad`](docs/easing.html#quad)
* - [`cubic`](docs/easing.html#cubic)
*
* The [`poly`](docs/easing.html#poly) function can be used to implement
* quartic, quintic, and other higher power functions.
*
* ### Additional functions
*
* Additional mathematical functions are provided by the following methods:
*
* - [`bezier`](docs/easing.html#bezier) provides a cubic bezier curve
* - [`circle`](docs/easing.html#circle) provides a circular function
* - [`sin`](docs/easing.html#sin) provides a sinusoidal function
* - [`exp`](docs/easing.html#exp) provides an exponential function
*
* The following helpers are used to modify other easing functions.
*
* - [`in`](docs/easing.html#in) runs an easing function forwards
* - [`inOut`](docs/easing.html#inout) makes any easing function symmetrical
* - [`out`](docs/easing.html#out) runs an easing function backwards
*/
class Easing {
/**
* A stepping function, returns 1 for any positive value of `n`.
*/
static step0(n) {
return n > 0 ? 1 : 0;
}
/**
* A stepping function, returns 1 if `n` is greater than or equal to 1.
*/
static step1(n) {
return n >= 1 ? 1 : 0;
}
/**
* A linear function, `f(t) = t`. Position correlates to elapsed time one to
* one.
*
* http://cubic-bezier.com/#0,0,1,1
*/
static linear(t) {
return t;
}
/**
* A simple inertial interaction, similar to an object slowly accelerating to
* speed.
*
* http://cubic-bezier.com/#.42,0,1,1
*/
static ease(t) {
if (!ease) {
ease = Easing.bezier(0.42, 0, 1, 1);
}
return ease(t);
}
/**
* A quadratic function, `f(t) = t * t`. Position equals the square of elapsed
* time.
*
* http://easings.net/#easeInQuad
*/
static quad(t) {
return t * t;
}
/**
* A cubic function, `f(t) = t * t * t`. Position equals the cube of elapsed
* time.
*
* http://easings.net/#easeInCubic
*/
static cubic(t) {
return t * t * t;
}
/**
* A power function. Position is equal to the Nth power of elapsed time.
*
* n = 4: http://easings.net/#easeInQuart
* n = 5: http://easings.net/#easeInQuint
*/
static poly(n) {
return t => Math.pow(t, n);
}
/**
* A sinusoidal function.
*
* http://easings.net/#easeInSine
*/
static sin(t) {
return 1 - Math.cos(t * Math.PI / 2);
}
/**
* A circular function.
*
* http://easings.net/#easeInCirc
*/
static circle(t) {
return 1 - Math.sqrt(1 - t * t);
}
/**
* An exponential function.
*
* http://easings.net/#easeInExpo
*/
static exp(t) {
return Math.pow(2, 10 * (t - 1));
}
/**
* A simple elastic interaction, similar to a spring oscillating back and
* forth.
*
* Default bounciness is 1, which overshoots a little bit once. 0 bounciness
* doesn't overshoot at all, and bounciness of N > 1 will overshoot about N
* times.
*
* http://easings.net/#easeInElastic
*/
static elastic(bounciness) {
if (bounciness === void 0) {
bounciness = 1;
}
var p = bounciness * Math.PI;
return t => 1 - Math.pow(Math.cos(t * Math.PI / 2), 3) * Math.cos(t * p);
}
/**
* Use with `Animated.parallel()` to create a simple effect where the object
* animates back slightly as the animation starts.
*
* Wolfram Plot:
*
* - http://tiny.cc/back_default (s = 1.70158, default)
*/
static back(s) {
if (s === void 0) {
s = 1.70158;
}
return t => t * t * ((s + 1) * t - s);
}
/**
* Provides a simple bouncing effect.
*
* http://easings.net/#easeInBounce
*/
static bounce(t) {
if (t < 1 / 2.75) {
return 7.5625 * t * t;
}
if (t < 2 / 2.75) {
var _t = t - 1.5 / 2.75;
return 7.5625 * _t * _t + 0.75;
}
if (t < 2.5 / 2.75) {
var _t2 = t - 2.25 / 2.75;
return 7.5625 * _t2 * _t2 + 0.9375;
}
var t2 = t - 2.625 / 2.75;
return 7.5625 * t2 * t2 + 0.984375;
}
/**
* Provides a cubic bezier curve, equivalent to CSS Transitions'
* `transition-timing-function`.
*
* A useful tool to visualize cubic bezier curves can be found at
* http://cubic-bezier.com/
*/
static bezier(x1, y1, x2, y2) {
return (0, _bezier2.default)(x1, y1, x2, y2);
}
/**
* Runs an easing function forwards.
*/
static in(easing) {
return easing;
}
/**
* Runs an easing function backwards.
*/
static out(easing) {
return t => 1 - easing(1 - t);
}
/**
* Makes any easing function symmetrical. The easing function will run
* forwards for half of the duration, then backwards for the rest of the
* duration.
*/
static inOut(easing) {
return t => {
if (t < 0.5) {
return easing(t * 2) / 2;
}
return 1 - easing((1 - t) * 2) / 2;
};
}
}
var _default = Easing;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/NativeAnimatedHelper.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.API = void 0;
exports.addWhitelistedInterpolationParam = addWhitelistedInterpolationParam;
exports.addWhitelistedStyleProp = addWhitelistedStyleProp;
exports.addWhitelistedTransformProp = addWhitelistedTransformProp;
exports.assertNativeAnimatedModule = assertNativeAnimatedModule;
exports.default = void 0;
exports.generateNewAnimationId = generateNewAnimationId;
exports.generateNewNodeTag = generateNewNodeTag;
exports.isSupportedColorStyleProp = isSupportedColorStyleProp;
exports.isSupportedInterpolationParam = isSupportedInterpolationParam;
exports.isSupportedStyleProp = isSupportedStyleProp;
exports.isSupportedTransformProp = isSupportedTransformProp;
exports.shouldUseNativeDriver = shouldUseNativeDriver;
exports.transformDataType = transformDataType;
exports.validateInterpolation = validateInterpolation;
exports.validateStyles = validateStyles;
exports.validateTransform = validateTransform;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _NativeAnimatedModule = _interopRequireDefault(require("./NativeAnimatedModule"));
var _NativeAnimatedTurboModule = _interopRequireDefault(require("./NativeAnimatedTurboModule"));
var _NativeEventEmitter = _interopRequireDefault(require("../EventEmitter/NativeEventEmitter"));
var _Platform = _interopRequireDefault(require("../Utilities/Platform"));
var _ReactNativeFeatureFlags = _interopRequireDefault(require("../ReactNative/ReactNativeFeatureFlags"));
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
var _RCTDeviceEventEmitter = _interopRequireDefault(require("../EventEmitter/RCTDeviceEventEmitter"));
/**
* 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.
*
*
* @format
*/
// TODO T69437152 @petetheheat - Delete this fork when Fabric ships to 100%.
var NativeAnimatedModule = _Platform.default.OS === 'ios' && global.RN$Bridgeless === true ? _NativeAnimatedTurboModule.default : _NativeAnimatedModule.default;
var __nativeAnimatedNodeTagCount = 1; /* used for animated nodes */
var __nativeAnimationIdCount = 1; /* used for started animations */
var nativeEventEmitter;
var waitingForQueuedOperations = new Set();
var queueOperations = false;
var queue = [];
// $FlowFixMe
var singleOpQueue = [];
var useSingleOpBatching = false;
_Platform.default.OS === 'android' && !!(NativeAnimatedModule != null && NativeAnimatedModule.queueAndExecuteBatchedOperations) && _ReactNativeFeatureFlags.default.animatedShouldUseSingleOp();
var flushQueueTimeout = null;
var eventListenerGetValueCallbacks = {};
var eventListenerAnimationFinishedCallbacks = {};
var globalEventEmitterGetValueListener = null;
var globalEventEmitterAnimationFinishedListener = null;
var nativeOps = useSingleOpBatching ? function () {
var apis = ['createAnimatedNode',
// 1
'updateAnimatedNodeConfig',
// 2
'getValue',
// 3
'startListeningToAnimatedNodeValue',
// 4
'stopListeningToAnimatedNodeValue',
// 5
'connectAnimatedNodes',
// 6
'disconnectAnimatedNodes',
// 7
'startAnimatingNode',
// 8
'stopAnimation',
// 9
'setAnimatedNodeValue',
// 10
'setAnimatedNodeOffset',
// 11
'flattenAnimatedNodeOffset',
// 12
'extractAnimatedNodeOffset',
// 13
'connectAnimatedNodeToView',
// 14
'disconnectAnimatedNodeFromView',
// 15
'restoreDefaultValues',
// 16
'dropAnimatedNode',
// 17
'addAnimatedEventToView',
// 18
'removeAnimatedEventFromView',
// 19
'addListener',
// 20
'removeListener' // 21
];
return apis.reduce((acc, functionName, i) => {
// These indices need to be kept in sync with the indices in native (see NativeAnimatedModule in Java, or the equivalent for any other native platform).
// $FlowFixMe[prop-missing]
acc[functionName] = i + 1;
return acc;
}, {});
}() : NativeAnimatedModule;
/**
* Wrappers around NativeAnimatedModule to provide flow and autocomplete support for
* the native module methods, and automatic queue management on Android
*/
var API = {
getValue: function getValue(tag, saveValueCallback) {
(0, _invariant.default)(nativeOps, 'Native animated module is not available');
if (useSingleOpBatching) {
if (saveValueCallback) {
eventListenerGetValueCallbacks[tag] = saveValueCallback;
}
// $FlowFixMe
API.queueOperation(nativeOps.getValue, tag);
} else {
API.queueOperation(nativeOps.getValue, tag, saveValueCallback);
}
},
setWaitingForIdentifier: function setWaitingForIdentifier(id) {
waitingForQueuedOperations.add(id);
queueOperations = true;
if (_ReactNativeFeatureFlags.default.animatedShouldDebounceQueueFlush() && flushQueueTimeout) {
clearTimeout(flushQueueTimeout);
}
},
unsetWaitingForIdentifier: function unsetWaitingForIdentifier(id) {
waitingForQueuedOperations.delete(id);
if (waitingForQueuedOperations.size === 0) {
queueOperations = false;
API.disableQueue();
}
},
disableQueue: function disableQueue() {
(0, _invariant.default)(nativeOps, 'Native animated module is not available');
if (_ReactNativeFeatureFlags.default.animatedShouldDebounceQueueFlush()) {
var prevTimeout = flushQueueTimeout;
clearImmediate(prevTimeout);
flushQueueTimeout = setImmediate(API.flushQueue);
} else {
API.flushQueue();
}
},
flushQueue: function flushQueue() {
/*
invariant(NativeAnimatedModule, 'Native animated module is not available');
flushQueueTimeout = null;
// Early returns before calling any APIs
if (useSingleOpBatching && singleOpQueue.length === 0) {
return;
}
if (!useSingleOpBatching && queue.length === 0) {
return;
}
if (useSingleOpBatching) {
// Set up event listener for callbacks if it's not set up
if (
!globalEventEmitterGetValueListener ||
!globalEventEmitterAnimationFinishedListener
) {
setupGlobalEventEmitterListeners();
}
// Single op batching doesn't use callback functions, instead we
// use RCTDeviceEventEmitter. This reduces overhead of sending lots of
// JSI functions across to native code; but also, TM infrastructure currently
// does not support packing a function into native arrays.
NativeAnimatedModule.queueAndExecuteBatchedOperations?.(singleOpQueue);
singleOpQueue.length = 0;
} else {
Platform.OS === 'android' && NativeAnimatedModule.startOperationBatch?.();
for (let q = 0, l = queue.length; q < l; q++) {
queue[q]();
}
queue.length = 0;
Platform.OS === 'android' &&
NativeAnimatedModule.finishOperationBatch?.();
}
*/
},
queueOperation: function queueOperation(fn) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
if (useSingleOpBatching) {
// Get the command ID from the queued function, and push that ID and any arguments needed to execute the operation
// $FlowFixMe: surprise, fn is actually a number
singleOpQueue.push(fn, ...args);
return;
}
// If queueing is explicitly on, *or* the queue has not yet
// been flushed, use the queue. This is to prevent operations
// from being executed out of order.
if (queueOperations || queue.length !== 0) {
queue.push(() => fn(...args));
} else {
fn(...args);
}
},
createAnimatedNode: function createAnimatedNode(tag, config) {
(0, _invariant.default)(nativeOps, 'Native animated module is not available');
API.queueOperation(nativeOps.createAnimatedNode, tag, config);
},
updateAnimatedNodeConfig: function updateAnimatedNodeConfig(tag, config) {
(0, _invariant.default)(nativeOps, 'Native animated module is not available');
//if (nativeOps.updateAnimatedNodeConfig) {
// API.queueOperation(nativeOps.updateAnimatedNodeConfig, tag, config);
//}
},
startListeningToAnimatedNodeValue: function startListeningToAnimatedNodeValue(tag) {
(0, _invariant.default)(nativeOps, 'Native animated module is not available');
API.queueOperation(nativeOps.startListeningToAnimatedNodeValue, tag);
},
stopListeningToAnimatedNodeValue: function stopListeningToAnimatedNodeValue(tag) {
(0, _invariant.default)(nativeOps, 'Native animated module is not available');
API.queueOperation(nativeOps.stopListeningToAnimatedNodeValue, tag);
},
connectAnimatedNodes: function connectAnimatedNodes(parentTag, childTag) {
(0, _invariant.default)(nativeOps, 'Native animated module is not available');
API.queueOperation(nativeOps.connectAnimatedNodes, parentTag, childTag);
},
disconnectAnimatedNodes: function disconnectAnimatedNodes(parentTag, childTag) {
(0, _invariant.default)(nativeOps, 'Native animated module is not available');
API.queueOperation(nativeOps.disconnectAnimatedNodes, parentTag, childTag);
},
startAnimatingNode: function startAnimatingNode(animationId, nodeTag, config, endCallback) {
(0, _invariant.default)(nativeOps, 'Native animated module is not available');
if (useSingleOpBatching) {
if (endCallback) {
eventListenerAnimationFinishedCallbacks[animationId] = endCallback;
}
// $FlowFixMe
API.queueOperation(nativeOps.startAnimatingNode, animationId, nodeTag, config);
} else {
API.queueOperation(nativeOps.startAnimatingNode, animationId, nodeTag, config, endCallback);
}
},
stopAnimation: function stopAnimation(animationId) {
(0, _invariant.default)(nativeOps, 'Native animated module is not available');
API.queueOperation(nativeOps.stopAnimation, animationId);
},
setAnimatedNodeValue: function setAnimatedNodeValue(nodeTag, value) {
(0, _invariant.default)(nativeOps, 'Native animated module is not available');
API.queueOperation(nativeOps.setAnimatedNodeValue, nodeTag, value);
},
setAnimatedNodeOffset: function setAnimatedNodeOffset(nodeTag, offset) {
(0, _invariant.default)(nativeOps, 'Native animated module is not available');
API.queueOperation(nativeOps.setAnimatedNodeOffset, nodeTag, offset);
},
flattenAnimatedNodeOffset: function flattenAnimatedNodeOffset(nodeTag) {
(0, _invariant.default)(nativeOps, 'Native animated module is not available');
API.queueOperation(nativeOps.flattenAnimatedNodeOffset, nodeTag);
},
extractAnimatedNodeOffset: function extractAnimatedNodeOffset(nodeTag) {
(0, _invariant.default)(nativeOps, 'Native animated module is not available');
API.queueOperation(nativeOps.extractAnimatedNodeOffset, nodeTag);
},
connectAnimatedNodeToView: function connectAnimatedNodeToView(nodeTag, viewTag) {
(0, _invariant.default)(nativeOps, 'Native animated module is not available');
API.queueOperation(nativeOps.connectAnimatedNodeToView, nodeTag, viewTag);
},
disconnectAnimatedNodeFromView: function disconnectAnimatedNodeFromView(nodeTag, viewTag) {
(0, _invariant.default)(nativeOps, 'Native animated module is not available');
API.queueOperation(nativeOps.disconnectAnimatedNodeFromView, nodeTag, viewTag);
},
restoreDefaultValues: function restoreDefaultValues(nodeTag) {
(0, _invariant.default)(nativeOps, 'Native animated module is not available');
// Backwards compat with older native runtimes, can be removed later.
if (nativeOps.restoreDefaultValues != null) {
API.queueOperation(nativeOps.restoreDefaultValues, nodeTag);
}
},
dropAnimatedNode: function dropAnimatedNode(tag) {
(0, _invariant.default)(nativeOps, 'Native animated module is not available');
API.queueOperation(nativeOps.dropAnimatedNode, tag);
},
addAnimatedEventToView: function addAnimatedEventToView(viewTag, eventName, eventMapping) {
(0, _invariant.default)(nativeOps, 'Native animated module is not available');
API.queueOperation(nativeOps.addAnimatedEventToView, viewTag, eventName, eventMapping);
},
removeAnimatedEventFromView(viewTag, eventName, animatedNodeTag) {
(0, _invariant.default)(nativeOps, 'Native animated module is not available');
API.queueOperation(nativeOps.removeAnimatedEventFromView, viewTag, eventName, animatedNodeTag);
}
};
exports.API = API;
function setupGlobalEventEmitterListeners() {
globalEventEmitterGetValueListener = _RCTDeviceEventEmitter.default.addListener('onNativeAnimatedModuleGetValue', function (params) {
var tag = params.tag;
var callback = eventListenerGetValueCallbacks[tag];
if (!callback) {
return;
}
callback(params.value);
delete eventListenerGetValueCallbacks[tag];
});
globalEventEmitterAnimationFinishedListener = _RCTDeviceEventEmitter.default.addListener('onNativeAnimatedModuleAnimationFinished', function (params) {
var animationId = params.animationId;
var callback = eventListenerAnimationFinishedCallbacks[animationId];
if (!callback) {
return;
}
callback(params);
delete eventListenerAnimationFinishedCallbacks[animationId];
});
}
/**
* Styles allowed by the native animated implementation.
*
* In general native animated implementation should support any numeric or color property that
* doesn't need to be updated through the shadow view hierarchy (all non-layout properties).
*/
var SUPPORTED_COLOR_STYLES = {
backgroundColor: true,
borderBottomColor: true,
borderColor: true,
borderEndColor: true,
borderLeftColor: true,
borderRightColor: true,
borderStartColor: true,
borderTopColor: true,
color: true,
tintColor: true
};
var SUPPORTED_STYLES = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, SUPPORTED_COLOR_STYLES), {}, {
borderBottomEndRadius: true,
borderBottomLeftRadius: true,
borderBottomRightRadius: true,
borderBottomStartRadius: true,
borderRadius: true,
borderTopEndRadius: true,
borderTopLeftRadius: true,
borderTopRightRadius: true,
borderTopStartRadius: true,
elevation: true,
opacity: true,
transform: true,
zIndex: true,
/* ios styles */
shadowOpacity: true,
shadowRadius: true,
/* legacy android transform properties */
scaleX: true,
scaleY: true,
translateX: true,
translateY: true
});
var SUPPORTED_TRANSFORMS = {
translateX: true,
translateY: true,
scale: true,
scaleX: true,
scaleY: true,
rotate: true,
rotateX: true,
rotateY: true,
rotateZ: true,
perspective: true
};
var SUPPORTED_INTERPOLATION_PARAMS = {
inputRange: true,
outputRange: true,
extrapolate: true,
extrapolateRight: true,
extrapolateLeft: true
};
function addWhitelistedStyleProp(prop) {
SUPPORTED_STYLES[prop] = true;
}
function addWhitelistedTransformProp(prop) {
SUPPORTED_TRANSFORMS[prop] = true;
}
function addWhitelistedInterpolationParam(param) {
SUPPORTED_INTERPOLATION_PARAMS[param] = true;
}
function isSupportedColorStyleProp(prop) {
return SUPPORTED_COLOR_STYLES.hasOwnProperty(prop);
}
function isSupportedStyleProp(prop) {
return SUPPORTED_STYLES.hasOwnProperty(prop);
}
function isSupportedTransformProp(prop) {
return SUPPORTED_TRANSFORMS.hasOwnProperty(prop);
}
function isSupportedInterpolationParam(param) {
return SUPPORTED_INTERPOLATION_PARAMS.hasOwnProperty(param);
}
function validateTransform(configs) {
configs.forEach(config => {
if (!isSupportedTransformProp(config.property)) {
throw new Error("Property '" + config.property + "' is not supported by native animated module");
}
});
}
function validateStyles(styles) {
for (var _key2 in styles) {
if (!isSupportedStyleProp(_key2)) {
throw new Error("Style property '" + _key2 + "' is not supported by native animated module");
}
}
}
function validateInterpolation(config) {
for (var _key3 in config) {
if (!isSupportedInterpolationParam(_key3)) {
throw new Error("Interpolation property '" + _key3 + "' is not supported by native animated module");
}
}
}
function generateNewNodeTag() {
return __nativeAnimatedNodeTagCount++;
}
function generateNewAnimationId() {
return __nativeAnimationIdCount++;
}
function assertNativeAnimatedModule() {
(0, _invariant.default)(NativeAnimatedModule, 'Native animated module is not available');
}
var _warnedMissingNativeAnimated = false;
function shouldUseNativeDriver(config) {
if (config.useNativeDriver == null) {
console.warn('Animated: `useNativeDriver` was not specified. This is a required ' + 'option and must be explicitly set to `true` or `false`');
}
if (config.useNativeDriver === true && !NativeAnimatedModule) {
if (!_warnedMissingNativeAnimated) {
console.warn('Animated: `useNativeDriver` is not supported because the native ' + 'animated module is missing. Falling back to JS-based animation. To ' + 'resolve this, add `RCTAnimation` module to this app, or remove ' + '`useNativeDriver`. ' + 'Make sure to run `bundle exec pod install` first. Read more about autolinking: https://github.com/react-native-community/cli/blob/master/docs/autolinking.md');
_warnedMissingNativeAnimated = true;
}
return false;
}
return config.useNativeDriver || false;
}
function transformDataType(value) {
// Change the string type to number type so we can reuse the same logic in
// iOS and Android platform
if (typeof value !== 'string') {
return value;
}
if (/deg$/.test(value)) {
var degrees = parseFloat(value) || 0;
var radians = degrees * Math.PI / 180.0;
return radians;
} else {
return value;
}
}
var _default = {
API,
isSupportedColorStyleProp,
isSupportedStyleProp,
isSupportedTransformProp,
isSupportedInterpolationParam,
addWhitelistedStyleProp,
addWhitelistedTransformProp,
addWhitelistedInterpolationParam,
validateStyles,
validateTransform,
validateInterpolation,
generateNewNodeTag,
generateNewAnimationId,
assertNativeAnimatedModule,
shouldUseNativeDriver,
transformDataType,
// $FlowExpectedError[unsafe-getters-setters] - unsafe getter lint suppresion
// $FlowExpectedError[missing-type-arg] - unsafe getter lint suppresion
get nativeEventEmitter() {
if (!nativeEventEmitter) {
nativeEventEmitter = new _NativeEventEmitter.default(
// T88715063: NativeEventEmitter only used this parameter on iOS. Now it uses it on all platforms, so this code was modified automatically to preserve its behavior
// If you want to use the native module on other platforms, please remove this condition and test its behavior
_Platform.default.OS !== 'ios' ? null : NativeAnimatedModule);
}
return nativeEventEmitter;
}
};
exports.default = _default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/NativeAnimatedModule.js
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var TurboModuleRegistry = _interopRequireWildcard(require("../TurboModule/TurboModuleRegistry"));
/**
* 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.
*
*
* @format
*/
var _default = TurboModuleRegistry.get('NativeAnimatedModule');
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/NativeAnimatedTurboModule.js
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var TurboModuleRegistry = _interopRequireWildcard(require("../TurboModule/TurboModuleRegistry"));
/**
* 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.
*
*
* @format
*/
var _default = TurboModuleRegistry.get('NativeAnimatedTurboModule');
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/SpringConfig.js
/**
* 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.
*
* @format
*
*/
'use strict';
exports.__esModule = true;
exports.default = void 0;
function stiffnessFromOrigamiValue(oValue) {
return (oValue - 30) * 3.62 + 194;
}
function dampingFromOrigamiValue(oValue) {
return (oValue - 8) * 3 + 25;
}
function fromOrigamiTensionAndFriction(tension, friction) {
return {
stiffness: stiffnessFromOrigamiValue(tension),
damping: dampingFromOrigamiValue(friction)
};
}
function fromBouncinessAndSpeed(bounciness, speed) {
function normalize(value, startValue, endValue) {
return (value - startValue) / (endValue - startValue);
}
function projectNormal(n, start, end) {
return start + n * (end - start);
}
function linearInterpolation(t, start, end) {
return t * end + (1 - t) * start;
}
function quadraticOutInterpolation(t, start, end) {
return linearInterpolation(2 * t - t * t, start, end);
}
function b3Friction1(x) {
return 0.0007 * Math.pow(x, 3) - 0.031 * Math.pow(x, 2) + 0.64 * x + 1.28;
}
function b3Friction2(x) {
return 0.000044 * Math.pow(x, 3) - 0.006 * Math.pow(x, 2) + 0.36 * x + 2;
}
function b3Friction3(x) {
return 0.00000045 * Math.pow(x, 3) - 0.000332 * Math.pow(x, 2) + 0.1078 * x + 5.84;
}
function b3Nobounce(tension) {
if (tension <= 18) {
return b3Friction1(tension);
} else if (tension > 18 && tension <= 44) {
return b3Friction2(tension);
} else {
return b3Friction3(tension);
}
}
var b = normalize(bounciness / 1.7, 0, 20);
b = projectNormal(b, 0, 0.8);
var s = normalize(speed / 1.7, 0, 20);
var bouncyTension = projectNormal(s, 0.5, 200);
var bouncyFriction = quadraticOutInterpolation(b, b3Nobounce(bouncyTension), 0.01);
return {
stiffness: stiffnessFromOrigamiValue(bouncyTension),
damping: dampingFromOrigamiValue(bouncyFriction)
};
}
var _default = {
fromOrigamiTensionAndFriction,
fromBouncinessAndSpeed
};
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/animations/Animation.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _NativeAnimatedHelper = _interopRequireDefault(require("../NativeAnimatedHelper"));
var startNativeAnimationNextId = 1;
// Important note: start() and stop() will only be called at most once.
// Once an animation has been stopped or finished its course, it will
// not be reused.
class Animation {
start(fromValue, onUpdate, onEnd, previousAnimation, animatedValue) {}
stop() {
if (this.__nativeId) {
_NativeAnimatedHelper.default.API.stopAnimation(this.__nativeId);
}
}
__getNativeAnimationConfig() {
// Subclasses that have corresponding animation implementation done in native
// should override this method
throw new Error('This animation type cannot be offloaded to native');
}
// Helper function for subclasses to make sure onEnd is only called once.
__debouncedOnEnd(result) {
var onEnd = this.__onEnd;
this.__onEnd = null;
onEnd && onEnd(result);
}
__startNativeAnimation(animatedValue) {
var startNativeAnimationWaitId = startNativeAnimationNextId + ":startAnimation";
startNativeAnimationNextId += 1;
_NativeAnimatedHelper.default.API.setWaitingForIdentifier(startNativeAnimationWaitId);
try {
var config = this.__getNativeAnimationConfig();
animatedValue.__makeNative(config.platformConfig);
this.__nativeId = _NativeAnimatedHelper.default.generateNewAnimationId();
_NativeAnimatedHelper.default.API.startAnimatingNode(this.__nativeId, animatedValue.__getNativeTag(), config,
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
this.__debouncedOnEnd.bind(this));
} catch (e) {
throw e;
} finally {
_NativeAnimatedHelper.default.API.unsetWaitingForIdentifier(startNativeAnimationWaitId);
}
}
}
var _default = Animation;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/animations/DecayAnimation.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _Animation = _interopRequireDefault(require("./Animation"));
var _NativeAnimatedHelper = require("../NativeAnimatedHelper");
class DecayAnimation extends _Animation.default {
constructor(config) {
var _config$deceleration, _config$isInteraction, _config$iterations;
super();
this._deceleration = (_config$deceleration = config.deceleration) !== null && _config$deceleration !== void 0 ? _config$deceleration : 0.998;
this._velocity = config.velocity;
this._useNativeDriver = (0, _NativeAnimatedHelper.shouldUseNativeDriver)(config);
this.__isInteraction = (_config$isInteraction = config.isInteraction) !== null && _config$isInteraction !== void 0 ? _config$isInteraction : !this._useNativeDriver;
this.__iterations = (_config$iterations = config.iterations) !== null && _config$iterations !== void 0 ? _config$iterations : 1;
}
__getNativeAnimationConfig() {
return {
type: 'decay',
deceleration: this._deceleration,
velocity: this._velocity,
iterations: this.__iterations
};
}
start(fromValue, onUpdate, onEnd, previousAnimation, animatedValue) {
this.__active = true;
this._lastValue = fromValue;
this._fromValue = fromValue;
this._onUpdate = onUpdate;
this.__onEnd = onEnd;
this._startTime = Date.now();
if (this._useNativeDriver) {
this.__startNativeAnimation(animatedValue);
} else {
this._animationFrame = requestAnimationFrame(this.onUpdate.bind(this));
}
}
onUpdate() {
var now = Date.now();
var value = this._fromValue + this._velocity / (1 - this._deceleration) * (1 - Math.exp(-(1 - this._deceleration) * (now - this._startTime)));
this._onUpdate(value);
if (Math.abs(this._lastValue - value) < 0.1) {
this.__debouncedOnEnd({
finished: true
});
return;
}
this._lastValue = value;
if (this.__active) {
this._animationFrame = requestAnimationFrame(this.onUpdate.bind(this));
}
}
stop() {
super.stop();
this.__active = false;
global.cancelAnimationFrame(this._animationFrame);
this.__debouncedOnEnd({
finished: false
});
}
}
var _default = DecayAnimation;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/animations/SpringAnimation.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _Animation = _interopRequireDefault(require("./Animation"));
var _SpringConfig = _interopRequireDefault(require("../SpringConfig"));
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
var _NativeAnimatedHelper = require("../NativeAnimatedHelper");
var _AnimatedColor = _interopRequireDefault(require("../nodes/AnimatedColor"));
class SpringAnimation extends _Animation.default {
constructor(config) {
var _config$overshootClam, _config$restDisplacem, _config$restSpeedThre, _config$velocity, _config$velocity2, _config$delay, _config$isInteraction, _config$iterations;
super();
this._overshootClamping = (_config$overshootClam = config.overshootClamping) !== null && _config$overshootClam !== void 0 ? _config$overshootClam : false;
this._restDisplacementThreshold = (_config$restDisplacem = config.restDisplacementThreshold) !== null && _config$restDisplacem !== void 0 ? _config$restDisplacem : 0.001;
this._restSpeedThreshold = (_config$restSpeedThre = config.restSpeedThreshold) !== null && _config$restSpeedThre !== void 0 ? _config$restSpeedThre : 0.001;
this._initialVelocity = (_config$velocity = config.velocity) !== null && _config$velocity !== void 0 ? _config$velocity : 0;
this._lastVelocity = (_config$velocity2 = config.velocity) !== null && _config$velocity2 !== void 0 ? _config$velocity2 : 0;
this._toValue = config.toValue;
this._delay = (_config$delay = config.delay) !== null && _config$delay !== void 0 ? _config$delay : 0;
this._useNativeDriver = (0, _NativeAnimatedHelper.shouldUseNativeDriver)(config);
this._platformConfig = config.platformConfig;
this.__isInteraction = (_config$isInteraction = config.isInteraction) !== null && _config$isInteraction !== void 0 ? _config$isInteraction : !this._useNativeDriver;
this.__iterations = (_config$iterations = config.iterations) !== null && _config$iterations !== void 0 ? _config$iterations : 1;
if (config.stiffness !== undefined || config.damping !== undefined || config.mass !== undefined) {
var _config$stiffness, _config$damping, _config$mass;
(0, _invariant.default)(config.bounciness === undefined && config.speed === undefined && config.tension === undefined && config.friction === undefined, 'You can define one of bounciness/speed, tension/friction, or stiffness/damping/mass, but not more than one');
this._stiffness = (_config$stiffness = config.stiffness) !== null && _config$stiffness !== void 0 ? _config$stiffness : 100;
this._damping = (_config$damping = config.damping) !== null && _config$damping !== void 0 ? _config$damping : 10;
this._mass = (_config$mass = config.mass) !== null && _config$mass !== void 0 ? _config$mass : 1;
} else if (config.bounciness !== undefined || config.speed !== undefined) {
var _config$bounciness, _config$speed;
// Convert the origami bounciness/speed values to stiffness/damping
// We assume mass is 1.
(0, _invariant.default)(config.tension === undefined && config.friction === undefined && config.stiffness === undefined && config.damping === undefined && config.mass === undefined, 'You can define one of bounciness/speed, tension/friction, or stiffness/damping/mass, but not more than one');
var springConfig = _SpringConfig.default.fromBouncinessAndSpeed((_config$bounciness = config.bounciness) !== null && _config$bounciness !== void 0 ? _config$bounciness : 8, (_config$speed = config.speed) !== null && _config$speed !== void 0 ? _config$speed : 12);
this._stiffness = springConfig.stiffness;
this._damping = springConfig.damping;
this._mass = 1;
} else {
var _config$tension, _config$friction;
// Convert the origami tension/friction values to stiffness/damping
// We assume mass is 1.
var _springConfig = _SpringConfig.default.fromOrigamiTensionAndFriction((_config$tension = config.tension) !== null && _config$tension !== void 0 ? _config$tension : 40, (_config$friction = config.friction) !== null && _config$friction !== void 0 ? _config$friction : 7);
this._stiffness = _springConfig.stiffness;
this._damping = _springConfig.damping;
this._mass = 1;
}
(0, _invariant.default)(this._stiffness > 0, 'Stiffness value must be greater than 0');
(0, _invariant.default)(this._damping > 0, 'Damping value must be greater than 0');
(0, _invariant.default)(this._mass > 0, 'Mass value must be greater than 0');
}
__getNativeAnimationConfig() {
var _this$_initialVelocit;
return {
type: 'spring',
overshootClamping: this._overshootClamping,
restDisplacementThreshold: this._restDisplacementThreshold,
restSpeedThreshold: this._restSpeedThreshold,
stiffness: this._stiffness,
damping: this._damping,
mass: this._mass,
initialVelocity: (_this$_initialVelocit = this._initialVelocity) !== null && _this$_initialVelocit !== void 0 ? _this$_initialVelocit : this._lastVelocity,
toValue: this._toValue,
iterations: this.__iterations,
platformConfig: this._platformConfig
};
}
start(fromValue, onUpdate, onEnd, previousAnimation, animatedValue) {
this.__active = true;
this._startPosition = fromValue;
this._lastPosition = this._startPosition;
this._onUpdate = onUpdate;
this.__onEnd = onEnd;
this._lastTime = Date.now();
this._frameTime = 0.0;
if (previousAnimation instanceof SpringAnimation) {
var internalState = previousAnimation.getInternalState();
this._lastPosition = internalState.lastPosition;
this._lastVelocity = internalState.lastVelocity;
// Set the initial velocity to the last velocity
this._initialVelocity = this._lastVelocity;
this._lastTime = internalState.lastTime;
}
var start = () => {
if (this._useNativeDriver) {
this.__startNativeAnimation(animatedValue);
} else {
this.onUpdate();
}
};
// If this._delay is more than 0, we start after the timeout.
if (this._delay) {
this._timeout = setTimeout(start, this._delay);
} else {
start();
}
}
getInternalState() {
return {
lastPosition: this._lastPosition,
lastVelocity: this._lastVelocity,
lastTime: this._lastTime
};
}
/**
* This spring model is based off of a damped harmonic oscillator
* (https://en.wikipedia.org/wiki/Harmonic_oscillator#Damped_harmonic_oscillator).
*
* We use the closed form of the second order differential equation:
*
* x'' + (2ζ⍵_0)x' + ⍵^2x = 0
*
* where
* ⍵_0 = √(k / m) (undamped angular frequency of the oscillator),
* ζ = c / 2√mk (damping ratio),
* c = damping constant
* k = stiffness
* m = mass
*
* The derivation of the closed form is described in detail here:
* http://planetmath.org/sites/default/files/texpdf/39745.pdf
*
* This algorithm happens to match the algorithm used by CASpringAnimation,
* a QuartzCore (iOS) API that creates spring animations.
*/
onUpdate() {
// If for some reason we lost a lot of frames (e.g. process large payload or
// stopped in the debugger), we only advance by 4 frames worth of
// computation and will continue on the next frame. It's better to have it
// running at faster speed than jumping to the end.
var MAX_STEPS = 64;
var now = Date.now();
if (now > this._lastTime + MAX_STEPS) {
now = this._lastTime + MAX_STEPS;
}
var deltaTime = (now - this._lastTime) / 1000;
this._frameTime += deltaTime;
var c = this._damping;
var m = this._mass;
var k = this._stiffness;
var v0 = -this._initialVelocity;
var zeta = c / (2 * Math.sqrt(k * m)); // damping ratio
var omega0 = Math.sqrt(k / m); // undamped angular frequency of the oscillator (rad/ms)
var omega1 = omega0 * Math.sqrt(1.0 - zeta * zeta); // exponential decay
var x0 = this._toValue - this._startPosition; // calculate the oscillation from x0 = 1 to x = 0
var position = 0.0;
var velocity = 0.0;
var t = this._frameTime;
if (zeta < 1) {
// Under damped
var envelope = Math.exp(-zeta * omega0 * t);
position = this._toValue - envelope * ((v0 + zeta * omega0 * x0) / omega1 * Math.sin(omega1 * t) + x0 * Math.cos(omega1 * t));
// This looks crazy -- it's actually just the derivative of the
// oscillation function
velocity = zeta * omega0 * envelope * (Math.sin(omega1 * t) * (v0 + zeta * omega0 * x0) / omega1 + x0 * Math.cos(omega1 * t)) - envelope * (Math.cos(omega1 * t) * (v0 + zeta * omega0 * x0) - omega1 * x0 * Math.sin(omega1 * t));
} else {
// Critically damped
var _envelope = Math.exp(-omega0 * t);
position = this._toValue - _envelope * (x0 + (v0 + omega0 * x0) * t);
velocity = _envelope * (v0 * (t * omega0 - 1) + t * x0 * (omega0 * omega0));
}
this._lastTime = now;
this._lastPosition = position;
this._lastVelocity = velocity;
this._onUpdate(position);
if (!this.__active) {
// a listener might have stopped us in _onUpdate
return;
}
// Conditions for stopping the spring animation
var isOvershooting = false;
if (this._overshootClamping && this._stiffness !== 0) {
if (this._startPosition < this._toValue) {
isOvershooting = position > this._toValue;
} else {
isOvershooting = position < this._toValue;
}
}
var isVelocity = Math.abs(velocity) <= this._restSpeedThreshold;
var isDisplacement = true;
if (this._stiffness !== 0) {
isDisplacement = Math.abs(this._toValue - position) <= this._restDisplacementThreshold;
}
if (isOvershooting || isVelocity && isDisplacement) {
if (this._stiffness !== 0) {
// Ensure that we end up with a round value
this._lastPosition = this._toValue;
this._lastVelocity = 0;
this._onUpdate(this._toValue);
}
this.__debouncedOnEnd({
finished: true
});
return;
}
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
this._animationFrame = requestAnimationFrame(this.onUpdate.bind(this));
}
stop() {
super.stop();
this.__active = false;
clearTimeout(this._timeout);
global.cancelAnimationFrame(this._animationFrame);
this.__debouncedOnEnd({
finished: false
});
}
}
var _default = SpringAnimation;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/animations/TimingAnimation.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _AnimatedValue = _interopRequireDefault(require("../nodes/AnimatedValue"));
var _AnimatedValueXY = _interopRequireDefault(require("../nodes/AnimatedValueXY"));
var _AnimatedInterpolation = _interopRequireDefault(require("../nodes/AnimatedInterpolation"));
var _Easing = _interopRequireDefault(require("../../../../exports/Easing"));
var _Animation = _interopRequireDefault(require("./Animation"));
var _NativeAnimatedHelper = require("../NativeAnimatedHelper");
var _AnimatedColor = _interopRequireDefault(require("../nodes/AnimatedColor"));
var _easeInOut;
function easeInOut() {
if (!_easeInOut) {
_easeInOut = _Easing.default.inOut(_Easing.default.ease);
}
return _easeInOut;
}
class TimingAnimation extends _Animation.default {
constructor(config) {
var _config$easing, _config$duration, _config$delay, _config$iterations, _config$isInteraction;
super();
this._toValue = config.toValue;
this._easing = (_config$easing = config.easing) !== null && _config$easing !== void 0 ? _config$easing : easeInOut();
this._duration = (_config$duration = config.duration) !== null && _config$duration !== void 0 ? _config$duration : 500;
this._delay = (_config$delay = config.delay) !== null && _config$delay !== void 0 ? _config$delay : 0;
this.__iterations = (_config$iterations = config.iterations) !== null && _config$iterations !== void 0 ? _config$iterations : 1;
this._useNativeDriver = (0, _NativeAnimatedHelper.shouldUseNativeDriver)(config);
this._platformConfig = config.platformConfig;
this.__isInteraction = (_config$isInteraction = config.isInteraction) !== null && _config$isInteraction !== void 0 ? _config$isInteraction : !this._useNativeDriver;
}
__getNativeAnimationConfig() {
var frameDuration = 1000.0 / 60.0;
var frames = [];
var numFrames = Math.round(this._duration / frameDuration);
for (var frame = 0; frame < numFrames; frame++) {
frames.push(this._easing(frame / numFrames));
}
frames.push(this._easing(1));
return {
type: 'frames',
frames,
toValue: this._toValue,
iterations: this.__iterations,
platformConfig: this._platformConfig
};
}
start(fromValue, onUpdate, onEnd, previousAnimation, animatedValue) {
this.__active = true;
this._fromValue = fromValue;
this._onUpdate = onUpdate;
this.__onEnd = onEnd;
var start = () => {
// Animations that sometimes have 0 duration and sometimes do not
// still need to use the native driver when duration is 0 so as to
// not cause intermixed JS and native animations.
if (this._duration === 0 && !this._useNativeDriver) {
this._onUpdate(this._toValue);
this.__debouncedOnEnd({
finished: true
});
} else {
this._startTime = Date.now();
if (this._useNativeDriver) {
this.__startNativeAnimation(animatedValue);
} else {
this._animationFrame = requestAnimationFrame(
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
this.onUpdate.bind(this));
}
}
};
if (this._delay) {
this._timeout = setTimeout(start, this._delay);
} else {
start();
}
}
onUpdate() {
var now = Date.now();
if (now >= this._startTime + this._duration) {
if (this._duration === 0) {
this._onUpdate(this._toValue);
} else {
this._onUpdate(this._fromValue + this._easing(1) * (this._toValue - this._fromValue));
}
this.__debouncedOnEnd({
finished: true
});
return;
}
this._onUpdate(this._fromValue + this._easing((now - this._startTime) / this._duration) * (this._toValue - this._fromValue));
if (this.__active) {
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
this._animationFrame = requestAnimationFrame(this.onUpdate.bind(this));
}
}
stop() {
super.stop();
this.__active = false;
clearTimeout(this._timeout);
global.cancelAnimationFrame(this._animationFrame);
this.__debouncedOnEnd({
finished: false
});
}
}
var _default = TimingAnimation;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/bezier.js
/**
* Portions 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.
*
*
* @format
*/
/**
* BezierEasing - use bezier curve for transition easing function
* https://github.com/gre/bezier-easing
* @copyright 2014-2015 Gaëtan Renaudeau. MIT License.
*/
'use strict';
// These values are established by empiricism with tests (tradeoff: performance VS precision)
exports.__esModule = true;
exports.default = bezier;
var NEWTON_ITERATIONS = 4;
var NEWTON_MIN_SLOPE = 0.001;
var SUBDIVISION_PRECISION = 0.0000001;
var SUBDIVISION_MAX_ITERATIONS = 10;
var kSplineTableSize = 11;
var kSampleStepSize = 1.0 / (kSplineTableSize - 1.0);
var float32ArraySupported = typeof Float32Array === 'function';
function A(aA1, aA2) {
return 1.0 - 3.0 * aA2 + 3.0 * aA1;
}
function B(aA1, aA2) {
return 3.0 * aA2 - 6.0 * aA1;
}
function C(aA1) {
return 3.0 * aA1;
}
// Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2.
function calcBezier(aT, aA1, aA2) {
return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;
}
// Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2.
function getSlope(aT, aA1, aA2) {
return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1);
}
function binarySubdivide(aX, _aA, _aB, mX1, mX2) {
var currentX,
currentT,
i = 0,
aA = _aA,
aB = _aB;
do {
currentT = aA + (aB - aA) / 2.0;
currentX = calcBezier(currentT, mX1, mX2) - aX;
if (currentX > 0.0) {
aB = currentT;
} else {
aA = currentT;
}
} while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS);
return currentT;
}
function newtonRaphsonIterate(aX, _aGuessT, mX1, mX2) {
var aGuessT = _aGuessT;
for (var i = 0; i < NEWTON_ITERATIONS; ++i) {
var currentSlope = getSlope(aGuessT, mX1, mX2);
if (currentSlope === 0.0) {
return aGuessT;
}
var currentX = calcBezier(aGuessT, mX1, mX2) - aX;
aGuessT -= currentX / currentSlope;
}
return aGuessT;
}
function bezier(mX1, mY1, mX2, mY2) {
if (!(mX1 >= 0 && mX1 <= 1 && mX2 >= 0 && mX2 <= 1)) {
throw new Error('bezier x values must be in [0, 1] range');
}
// Precompute samples table
var sampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize);
if (mX1 !== mY1 || mX2 !== mY2) {
for (var i = 0; i < kSplineTableSize; ++i) {
sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);
}
}
function getTForX(aX) {
var intervalStart = 0.0;
var currentSample = 1;
var lastSample = kSplineTableSize - 1;
for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample) {
intervalStart += kSampleStepSize;
}
--currentSample;
// Interpolate to provide an initial guess for t
var dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]);
var guessForT = intervalStart + dist * kSampleStepSize;
var initialSlope = getSlope(guessForT, mX1, mX2);
if (initialSlope >= NEWTON_MIN_SLOPE) {
return newtonRaphsonIterate(aX, guessForT, mX1, mX2);
} else if (initialSlope === 0.0) {
return guessForT;
} else {
return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2);
}
}
return function BezierEasing(x) {
if (mX1 === mY1 && mX2 === mY2) {
return x; // linear
}
// Because JavaScript number are imprecise, we should guarantee the extremes are right.
if (x === 0) {
return 0;
}
if (x === 1) {
return 1;
}
return calcBezier(getTForX(x), mY1, mY2);
};
}
;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/components/AnimatedFlatList.js
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var React = _interopRequireWildcard(require("react"));
var _FlatList = _interopRequireDefault(require("../../../../exports/FlatList"));
var _createAnimatedComponent = _interopRequireDefault(require("../createAnimatedComponent"));
/**
* 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.
*
*
* @format
*/
/**
* @see https://github.com/facebook/react-native/commit/b8c8562
*/
var FlatListWithEventThrottle = /*#__PURE__*/React.forwardRef((props, ref) => /*#__PURE__*/React.createElement(_FlatList.default, (0, _extends2.default)({
scrollEventThrottle: 0.0001
}, props, {
ref: ref
})));
var _default = (0, _createAnimatedComponent.default)(FlatListWithEventThrottle);
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/components/AnimatedImage.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
var _Image = _interopRequireDefault(require("../../../../exports/Image"));
var _createAnimatedComponent = _interopRequireDefault(require("../createAnimatedComponent"));
/**
* 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.
*
*
* @format
*/
var _default = (0, _createAnimatedComponent.default)(_Image.default);
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/components/AnimatedScrollView.js
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var React = _interopRequireWildcard(require("react"));
var _ScrollView = _interopRequireDefault(require("../../../../exports/ScrollView"));
var _createAnimatedComponent = _interopRequireDefault(require("../createAnimatedComponent"));
/**
* 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.
*
*
* @format
*/
/**
* @see https://github.com/facebook/react-native/commit/b8c8562
*/
var ScrollViewWithEventThrottle = /*#__PURE__*/React.forwardRef((props, ref) => /*#__PURE__*/React.createElement(_ScrollView.default, (0, _extends2.default)({
scrollEventThrottle: 0.0001
}, props, {
ref: ref
})));
var _default = (0, _createAnimatedComponent.default)(ScrollViewWithEventThrottle);
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/components/AnimatedSectionList.js
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var React = _interopRequireWildcard(require("react"));
var _SectionList = _interopRequireDefault(require("../../../../exports/SectionList"));
var _createAnimatedComponent = _interopRequireDefault(require("../createAnimatedComponent"));
/**
* 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.
*
*
* @format
*/
/**
* @see https://github.com/facebook/react-native/commit/b8c8562
*/
var SectionListWithEventThrottle = /*#__PURE__*/React.forwardRef((props, ref) => /*#__PURE__*/React.createElement(_SectionList.default, (0, _extends2.default)({
scrollEventThrottle: 0.0001
}, props, {
ref: ref
})));
var _default = (0, _createAnimatedComponent.default)(SectionListWithEventThrottle);
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/components/AnimatedText.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
var _Text = _interopRequireDefault(require("../../../../exports/Text"));
var _createAnimatedComponent = _interopRequireDefault(require("../createAnimatedComponent"));
/**
* 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.
*
*
* @format
*/
var _default = (0, _createAnimatedComponent.default)(_Text.default);
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/components/AnimatedView.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
var _View = _interopRequireDefault(require("../../../../exports/View"));
var _createAnimatedComponent = _interopRequireDefault(require("../createAnimatedComponent"));
/**
* 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.
*
*
* @format
*/
var _default = (0, _createAnimatedComponent.default)(_View.default);
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/createAnimatedComponent.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = createAnimatedComponent;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var _useAnimatedProps2 = _interopRequireDefault(require("./useAnimatedProps"));
var _useMergeRefs = _interopRequireDefault(require("../Utilities/useMergeRefs"));
var _StyleSheet = _interopRequireDefault(require("../../../exports/StyleSheet"));
var _View = _interopRequireDefault(require("../../../exports/View"));
var React = _interopRequireWildcard(require("react"));
var _excluded = ["style"];
/**
* Experimental implementation of `createAnimatedComponent` that is intended to
* be compatible with concurrent rendering.
*/
function createAnimatedComponent(Component) {
return /*#__PURE__*/React.forwardRef((props, forwardedRef) => {
var _useAnimatedProps = (0, _useAnimatedProps2.default)(props),
reducedProps = _useAnimatedProps[0],
callbackRef = _useAnimatedProps[1];
var ref = (0, _useMergeRefs.default)(callbackRef, forwardedRef);
// Some components require explicit passthrough values for animation
// to work properly. For example, if an animated component is
// transformed and Pressable, onPress will not work after transform
// without these passthrough values.
// $FlowFixMe[prop-missing]
var passthroughAnimatedPropExplicitValues = reducedProps.passthroughAnimatedPropExplicitValues,
style = reducedProps.style;
var _ref = passthroughAnimatedPropExplicitValues !== null && passthroughAnimatedPropExplicitValues !== void 0 ? passthroughAnimatedPropExplicitValues : {},
passthroughStyle = _ref.style,
passthroughProps = (0, _objectWithoutPropertiesLoose2.default)(_ref, _excluded);
var mergedStyle = [style, passthroughStyle];
return /*#__PURE__*/React.createElement(Component, (0, _extends2.default)({}, reducedProps, passthroughProps, {
style: mergedStyle,
ref: ref
}));
});
}
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/nodes/AnimatedAddition.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _AnimatedInterpolation = _interopRequireDefault(require("./AnimatedInterpolation"));
var _AnimatedValue = _interopRequireDefault(require("./AnimatedValue"));
var _AnimatedWithChildren = _interopRequireDefault(require("./AnimatedWithChildren"));
class AnimatedAddition extends _AnimatedWithChildren.default {
constructor(a, b) {
super();
this._a = typeof a === 'number' ? new _AnimatedValue.default(a) : a;
this._b = typeof b === 'number' ? new _AnimatedValue.default(b) : b;
}
__makeNative(platformConfig) {
this._a.__makeNative(platformConfig);
this._b.__makeNative(platformConfig);
super.__makeNative(platformConfig);
}
__getValue() {
return this._a.__getValue() + this._b.__getValue();
}
interpolate(config) {
return new _AnimatedInterpolation.default(this, config);
}
__attach() {
this._a.__addChild(this);
this._b.__addChild(this);
}
__detach() {
this._a.__removeChild(this);
this._b.__removeChild(this);
super.__detach();
}
__getNativeConfig() {
return {
type: 'addition',
input: [this._a.__getNativeTag(), this._b.__getNativeTag()]
};
}
}
var _default = AnimatedAddition;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/nodes/AnimatedColor.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _AnimatedValue = _interopRequireDefault(require("./AnimatedValue"));
var _AnimatedWithChildren = _interopRequireDefault(require("./AnimatedWithChildren"));
var _normalizeColors = _interopRequireDefault(require("@react-native/normalize-colors"));
var _NativeAnimatedHelper = _interopRequireDefault(require("../NativeAnimatedHelper"));
var NativeAnimatedAPI = _NativeAnimatedHelper.default.API;
var defaultColor = {
r: 0,
g: 0,
b: 0,
a: 1.0
};
var _uniqueId = 1;
var processColorObject = color => {
return color;
};
/* eslint no-bitwise: 0 */
function processColor(color) {
if (color === undefined || color === null) {
return null;
}
if (isRgbaValue(color)) {
// $FlowIgnore[incompatible-cast] - Type is verified above
return color;
}
var normalizedColor = (0, _normalizeColors.default)(
// $FlowIgnore[incompatible-cast] - Type is verified above
color);
if (normalizedColor === undefined || normalizedColor === null) {
return null;
}
if (typeof normalizedColor === 'object') {
var processedColorObj = processColorObject(normalizedColor);
if (processedColorObj != null) {
return processedColorObj;
}
} else if (typeof normalizedColor === 'number') {
var r = (normalizedColor & 0xff000000) >>> 24;
var g = (normalizedColor & 0x00ff0000) >>> 16;
var b = (normalizedColor & 0x0000ff00) >>> 8;
var a = (normalizedColor & 0x000000ff) / 255;
return {
r,
g,
b,
a
};
}
return null;
}
function isRgbaValue(value) {
return value && typeof value.r === 'number' && typeof value.g === 'number' && typeof value.b === 'number' && typeof value.a === 'number';
}
function isRgbaAnimatedValue(value) {
return value && value.r instanceof _AnimatedValue.default && value.g instanceof _AnimatedValue.default && value.b instanceof _AnimatedValue.default && value.a instanceof _AnimatedValue.default;
}
class AnimatedColor extends _AnimatedWithChildren.default {
constructor(valueIn, config) {
super();
this._listeners = {};
var value = valueIn !== null && valueIn !== void 0 ? valueIn : defaultColor;
if (isRgbaAnimatedValue(value)) {
// $FlowIgnore[incompatible-cast] - Type is verified above
var rgbaAnimatedValue = value;
this.r = rgbaAnimatedValue.r;
this.g = rgbaAnimatedValue.g;
this.b = rgbaAnimatedValue.b;
this.a = rgbaAnimatedValue.a;
} else {
var _processColor;
var processedColor = // $FlowIgnore[incompatible-cast] - Type is verified above
(_processColor = processColor(value)) !== null && _processColor !== void 0 ? _processColor : defaultColor;
var initColor = defaultColor;
if (isRgbaValue(processedColor)) {
// $FlowIgnore[incompatible-cast] - Type is verified above
initColor = processedColor;
} else {
// $FlowIgnore[incompatible-cast] - Type is verified above
this.nativeColor = processedColor;
}
this.r = new _AnimatedValue.default(initColor.r);
this.g = new _AnimatedValue.default(initColor.g);
this.b = new _AnimatedValue.default(initColor.b);
this.a = new _AnimatedValue.default(initColor.a);
}
if (this.nativeColor || config && config.useNativeDriver) {
this.__makeNative();
}
}
/**
* Directly set the value. This will stop any animations running on the value
* and update all the bound properties.
*/
setValue(value) {
var _processColor2;
var shouldUpdateNodeConfig = false;
if (this.__isNative) {
var nativeTag = this.__getNativeTag();
NativeAnimatedAPI.setWaitingForIdentifier(nativeTag.toString());
}
var processedColor = (_processColor2 = processColor(value)) !== null && _processColor2 !== void 0 ? _processColor2 : defaultColor;
if (isRgbaValue(processedColor)) {
// $FlowIgnore[incompatible-type] - Type is verified above
var rgbaValue = processedColor;
this.r.setValue(rgbaValue.r);
this.g.setValue(rgbaValue.g);
this.b.setValue(rgbaValue.b);
this.a.setValue(rgbaValue.a);
if (this.nativeColor != null) {
this.nativeColor = null;
shouldUpdateNodeConfig = true;
}
} else {
// $FlowIgnore[incompatible-type] - Type is verified above
var nativeColor = processedColor;
if (this.nativeColor !== nativeColor) {
this.nativeColor = nativeColor;
shouldUpdateNodeConfig = true;
}
}
if (this.__isNative) {
var _nativeTag = this.__getNativeTag();
if (shouldUpdateNodeConfig) {
NativeAnimatedAPI.updateAnimatedNodeConfig(_nativeTag, this.__getNativeConfig());
}
NativeAnimatedAPI.unsetWaitingForIdentifier(_nativeTag.toString());
}
}
/**
* Sets an offset that is applied on top of whatever value is set, whether
* via `setValue`, an animation, or `Animated.event`. Useful for compensating
* things like the start of a pan gesture.
*/
setOffset(offset) {
this.r.setOffset(offset.r);
this.g.setOffset(offset.g);
this.b.setOffset(offset.b);
this.a.setOffset(offset.a);
}
/**
* Merges the offset value into the base value and resets the offset to zero.
* The final output of the value is unchanged.
*/
flattenOffset() {
this.r.flattenOffset();
this.g.flattenOffset();
this.b.flattenOffset();
this.a.flattenOffset();
}
/**
* Sets the offset value to the base value, and resets the base value to
* zero. The final output of the value is unchanged.
*/
extractOffset() {
this.r.extractOffset();
this.g.extractOffset();
this.b.extractOffset();
this.a.extractOffset();
}
/**
* Adds an asynchronous listener to the value so you can observe updates from
* animations. This is useful because there is no way to synchronously read
* the value because it might be driven natively.
*
* Returns a string that serves as an identifier for the listener.
*/
addListener(callback) {
var id = String(_uniqueId++);
var jointCallback = _ref => {
var number = _ref.value;
callback(this.__getValue());
};
this._listeners[id] = {
r: this.r.addListener(jointCallback),
g: this.g.addListener(jointCallback),
b: this.b.addListener(jointCallback),
a: this.a.addListener(jointCallback)
};
return id;
}
/**
* Unregister a listener. The `id` param shall match the identifier
* previously returned by `addListener()`.
*/
removeListener(id) {
this.r.removeListener(this._listeners[id].r);
this.g.removeListener(this._listeners[id].g);
this.b.removeListener(this._listeners[id].b);
this.a.removeListener(this._listeners[id].a);
delete this._listeners[id];
}
/**
* Remove all registered listeners.
*/
removeAllListeners() {
this.r.removeAllListeners();
this.g.removeAllListeners();
this.b.removeAllListeners();
this.a.removeAllListeners();
this._listeners = {};
}
/**
* Stops any running animation or tracking. `callback` is invoked with the
* final value after stopping the animation, which is useful for updating
* state to match the animation position with layout.
*/
stopAnimation(callback) {
this.r.stopAnimation();
this.g.stopAnimation();
this.b.stopAnimation();
this.a.stopAnimation();
callback && callback(this.__getValue());
}
/**
* Stops any animation and resets the value to its original.
*/
resetAnimation(callback) {
this.r.resetAnimation();
this.g.resetAnimation();
this.b.resetAnimation();
this.a.resetAnimation();
callback && callback(this.__getValue());
}
__getValue() {
if (this.nativeColor != null) {
return this.nativeColor;
} else {
return "rgba(" + this.r.__getValue() + ", " + this.g.__getValue() + ", " + this.b.__getValue() + ", " + this.a.__getValue() + ")";
}
}
__attach() {
this.r.__addChild(this);
this.g.__addChild(this);
this.b.__addChild(this);
this.a.__addChild(this);
super.__attach();
}
__detach() {
this.r.__removeChild(this);
this.g.__removeChild(this);
this.b.__removeChild(this);
this.a.__removeChild(this);
super.__detach();
}
__makeNative(platformConfig) {
this.r.__makeNative(platformConfig);
this.g.__makeNative(platformConfig);
this.b.__makeNative(platformConfig);
this.a.__makeNative(platformConfig);
super.__makeNative(platformConfig);
}
__getNativeConfig() {
return {
type: 'color',
r: this.r.__getNativeTag(),
g: this.g.__getNativeTag(),
b: this.b.__getNativeTag(),
a: this.a.__getNativeTag(),
nativeColor: this.nativeColor
};
}
}
exports.default = AnimatedColor;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/nodes/AnimatedDiffClamp.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _AnimatedInterpolation = _interopRequireDefault(require("./AnimatedInterpolation"));
var _AnimatedWithChildren = _interopRequireDefault(require("./AnimatedWithChildren"));
class AnimatedDiffClamp extends _AnimatedWithChildren.default {
constructor(a, min, max) {
super();
this._a = a;
this._min = min;
this._max = max;
this._value = this._lastValue = this._a.__getValue();
}
__makeNative(platformConfig) {
this._a.__makeNative(platformConfig);
super.__makeNative(platformConfig);
}
interpolate(config) {
return new _AnimatedInterpolation.default(this, config);
}
__getValue() {
var value = this._a.__getValue();
var diff = value - this._lastValue;
this._lastValue = value;
this._value = Math.min(Math.max(this._value + diff, this._min), this._max);
return this._value;
}
__attach() {
this._a.__addChild(this);
}
__detach() {
this._a.__removeChild(this);
super.__detach();
}
__getNativeConfig() {
return {
type: 'diffclamp',
input: this._a.__getNativeTag(),
min: this._min,
max: this._max
};
}
}
var _default = AnimatedDiffClamp;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/nodes/AnimatedDivision.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _AnimatedInterpolation = _interopRequireDefault(require("./AnimatedInterpolation"));
var _AnimatedNode = _interopRequireDefault(require("./AnimatedNode"));
var _AnimatedValue = _interopRequireDefault(require("./AnimatedValue"));
var _AnimatedWithChildren = _interopRequireDefault(require("./AnimatedWithChildren"));
class AnimatedDivision extends _AnimatedWithChildren.default {
constructor(a, b) {
super();
this._warnedAboutDivideByZero = false;
if (b === 0 || b instanceof _AnimatedNode.default && b.__getValue() === 0) {
console.error('Detected potential division by zero in AnimatedDivision');
}
this._a = typeof a === 'number' ? new _AnimatedValue.default(a) : a;
this._b = typeof b === 'number' ? new _AnimatedValue.default(b) : b;
}
__makeNative(platformConfig) {
this._a.__makeNative(platformConfig);
this._b.__makeNative(platformConfig);
super.__makeNative(platformConfig);
}
__getValue() {
var a = this._a.__getValue();
var b = this._b.__getValue();
if (b === 0) {
// Prevent spamming the console/LogBox
if (!this._warnedAboutDivideByZero) {
console.error('Detected division by zero in AnimatedDivision');
this._warnedAboutDivideByZero = true;
}
// Passing infinity/NaN to Fabric will cause a native crash
return 0;
}
this._warnedAboutDivideByZero = false;
return a / b;
}
interpolate(config) {
return new _AnimatedInterpolation.default(this, config);
}
__attach() {
this._a.__addChild(this);
this._b.__addChild(this);
}
__detach() {
this._a.__removeChild(this);
this._b.__removeChild(this);
super.__detach();
}
__getNativeConfig() {
return {
type: 'division',
input: [this._a.__getNativeTag(), this._b.__getNativeTag()]
};
}
}
var _default = AnimatedDivision;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/nodes/AnimatedInterpolation.js
/**
* 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.
*
*
* @format
*/
/* eslint no-bitwise: 0 */
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _AnimatedWithChildren = _interopRequireDefault(require("./AnimatedWithChildren"));
var _NativeAnimatedHelper = _interopRequireDefault(require("../NativeAnimatedHelper"));
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
var _normalizeColors = _interopRequireDefault(require("@react-native/normalize-colors"));
var __DEV__ = process.env.NODE_ENV !== 'production';
var linear = t => t;
/**
* Very handy helper to map input ranges to output ranges with an easing
* function and custom behavior outside of the ranges.
*/
function createInterpolation(config) {
if (config.outputRange && typeof config.outputRange[0] === 'string') {
return createInterpolationFromStringOutputRange(config);
}
var outputRange = config.outputRange;
var inputRange = config.inputRange;
if (__DEV__) {
checkInfiniteRange('outputRange', outputRange);
checkInfiniteRange('inputRange', inputRange);
checkValidInputRange(inputRange);
(0, _invariant.default)(inputRange.length === outputRange.length, 'inputRange (' + inputRange.length + ') and outputRange (' + outputRange.length + ') must have the same length');
}
var easing = config.easing || linear;
var extrapolateLeft = 'extend';
if (config.extrapolateLeft !== undefined) {
extrapolateLeft = config.extrapolateLeft;
} else if (config.extrapolate !== undefined) {
extrapolateLeft = config.extrapolate;
}
var extrapolateRight = 'extend';
if (config.extrapolateRight !== undefined) {
extrapolateRight = config.extrapolateRight;
} else if (config.extrapolate !== undefined) {
extrapolateRight = config.extrapolate;
}
return input => {
(0, _invariant.default)(typeof input === 'number', 'Cannot interpolation an input which is not a number');
var range = findRange(input, inputRange);
return interpolate(input, inputRange[range], inputRange[range + 1], outputRange[range], outputRange[range + 1], easing, extrapolateLeft, extrapolateRight);
};
}
function interpolate(input, inputMin, inputMax, outputMin, outputMax, easing, extrapolateLeft, extrapolateRight) {
var result = input;
// Extrapolate
if (result < inputMin) {
if (extrapolateLeft === 'identity') {
return result;
} else if (extrapolateLeft === 'clamp') {
result = inputMin;
} else if (extrapolateLeft === 'extend') {
// noop
}
}
if (result > inputMax) {
if (extrapolateRight === 'identity') {
return result;
} else if (extrapolateRight === 'clamp') {
result = inputMax;
} else if (extrapolateRight === 'extend') {
// noop
}
}
if (outputMin === outputMax) {
return outputMin;
}
if (inputMin === inputMax) {
if (input <= inputMin) {
return outputMin;
}
return outputMax;
}
// Input Range
if (inputMin === -Infinity) {
result = -result;
} else if (inputMax === Infinity) {
result = result - inputMin;
} else {
result = (result - inputMin) / (inputMax - inputMin);
}
// Easing
result = easing(result);
// Output Range
if (outputMin === -Infinity) {
result = -result;
} else if (outputMax === Infinity) {
result = result + outputMin;
} else {
result = result * (outputMax - outputMin) + outputMin;
}
return result;
}
function colorToRgba(input) {
var normalizedColor = (0, _normalizeColors.default)(input);
if (normalizedColor === null || typeof normalizedColor !== 'number') {
return input;
}
normalizedColor = normalizedColor || 0;
var r = (normalizedColor & 0xff000000) >>> 24;
var g = (normalizedColor & 0x00ff0000) >>> 16;
var b = (normalizedColor & 0x0000ff00) >>> 8;
var a = (normalizedColor & 0x000000ff) / 255;
return "rgba(" + r + ", " + g + ", " + b + ", " + a + ")";
}
var stringShapeRegex = /[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/g;
/**
* Supports string shapes by extracting numbers so new values can be computed,
* and recombines those values into new strings of the same shape. Supports
* things like:
*
* rgba(123, 42, 99, 0.36) // colors
* -45deg // values with units
*/
function createInterpolationFromStringOutputRange(config) {
var outputRange = config.outputRange;
(0, _invariant.default)(outputRange.length >= 2, 'Bad output range');
outputRange = outputRange.map(colorToRgba);
checkPattern(outputRange);
// ['rgba(0, 100, 200, 0)', 'rgba(50, 150, 250, 0.5)']
// ->
// [
// [0, 50],
// [100, 150],
// [200, 250],
// [0, 0.5],
// ]
/* $FlowFixMe[incompatible-use] (>=0.18.0): `outputRange[0].match()` can
* return `null`. Need to guard against this possibility. */
var outputRanges = outputRange[0].match(stringShapeRegex).map(() => []);
outputRange.forEach(value => {
/* $FlowFixMe[incompatible-use] (>=0.18.0): `value.match()` can return
* `null`. Need to guard against this possibility. */
value.match(stringShapeRegex).forEach((number, i) => {
outputRanges[i].push(+number);
});
});
var interpolations = outputRange[0].match(stringShapeRegex)
/* $FlowFixMe[incompatible-use] (>=0.18.0): `outputRange[0].match()` can
* return `null`. Need to guard against this possibility. */
/* $FlowFixMe[incompatible-call] (>=0.18.0): `outputRange[0].match()` can
* return `null`. Need to guard against this possibility. */.map((value, i) => {
return createInterpolation((0, _objectSpread2.default)((0, _objectSpread2.default)({}, config), {}, {
outputRange: outputRanges[i]
}));
});
// rgba requires that the r,g,b are integers.... so we want to round them, but we *dont* want to
// round the opacity (4th column).
var shouldRound = isRgbOrRgba(outputRange[0]);
return input => {
var i = 0;
// 'rgba(0, 100, 200, 0)'
// ->
// 'rgba(${interpolations[0](input)}, ${interpolations[1](input)}, ...'
return outputRange[0].replace(stringShapeRegex, () => {
var val = +interpolations[i++](input);
if (shouldRound) {
val = i < 4 ? Math.round(val) : Math.round(val * 1000) / 1000;
}
return String(val);
});
};
}
function isRgbOrRgba(range) {
return typeof range === 'string' && range.startsWith('rgb');
}
function checkPattern(arr) {
var pattern = arr[0].replace(stringShapeRegex, '');
for (var i = 1; i < arr.length; ++i) {
(0, _invariant.default)(pattern === arr[i].replace(stringShapeRegex, ''), 'invalid pattern ' + arr[0] + ' and ' + arr[i]);
}
}
function findRange(input, inputRange) {
var i;
for (i = 1; i < inputRange.length - 1; ++i) {
if (inputRange[i] >= input) {
break;
}
}
return i - 1;
}
function checkValidInputRange(arr) {
(0, _invariant.default)(arr.length >= 2, 'inputRange must have at least 2 elements');
var message = 'inputRange must be monotonically non-decreasing ' + String(arr);
for (var i = 1; i < arr.length; ++i) {
(0, _invariant.default)(arr[i] >= arr[i - 1], message);
}
}
function checkInfiniteRange(name, arr) {
(0, _invariant.default)(arr.length >= 2, name + ' must have at least 2 elements');
(0, _invariant.default)(arr.length !== 2 || arr[0] !== -Infinity || arr[1] !== Infinity,
/* $FlowFixMe[incompatible-type] (>=0.13.0) - In the addition expression
* below this comment, one or both of the operands may be something that
* doesn't cleanly convert to a string, like undefined, null, and object,
* etc. If you really mean this implicit string conversion, you can do
* something like String(myThing) */
name + 'cannot be ]-infinity;+infinity[ ' + arr);
}
class AnimatedInterpolation extends _AnimatedWithChildren.default {
// Export for testing.
constructor(parent, config) {
super();
this._parent = parent;
this._config = config;
this._interpolation = createInterpolation(config);
}
__makeNative(platformConfig) {
this._parent.__makeNative(platformConfig);
super.__makeNative(platformConfig);
}
__getValue() {
var parentValue = this._parent.__getValue();
(0, _invariant.default)(typeof parentValue === 'number', 'Cannot interpolate an input which is not a number.');
return this._interpolation(parentValue);
}
interpolate(config) {
return new AnimatedInterpolation(this, config);
}
__attach() {
this._parent.__addChild(this);
}
__detach() {
this._parent.__removeChild(this);
super.__detach();
}
__transformDataType(range) {
return range.map(_NativeAnimatedHelper.default.transformDataType);
}
__getNativeConfig() {
if (__DEV__) {
_NativeAnimatedHelper.default.validateInterpolation(this._config);
}
return {
inputRange: this._config.inputRange,
// Only the `outputRange` can contain strings so we don't need to transform `inputRange` here
outputRange: this.__transformDataType(this._config.outputRange),
extrapolateLeft: this._config.extrapolateLeft || this._config.extrapolate || 'extend',
extrapolateRight: this._config.extrapolateRight || this._config.extrapolate || 'extend',
type: 'interpolation'
};
}
}
AnimatedInterpolation.__createInterpolation = createInterpolation;
var _default = AnimatedInterpolation;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/nodes/AnimatedModulo.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _AnimatedInterpolation = _interopRequireDefault(require("./AnimatedInterpolation"));
var _AnimatedWithChildren = _interopRequireDefault(require("./AnimatedWithChildren"));
class AnimatedModulo extends _AnimatedWithChildren.default {
constructor(a, modulus) {
super();
this._a = a;
this._modulus = modulus;
}
__makeNative(platformConfig) {
this._a.__makeNative(platformConfig);
super.__makeNative(platformConfig);
}
__getValue() {
return (this._a.__getValue() % this._modulus + this._modulus) % this._modulus;
}
interpolate(config) {
return new _AnimatedInterpolation.default(this, config);
}
__attach() {
this._a.__addChild(this);
}
__detach() {
this._a.__removeChild(this);
super.__detach();
}
__getNativeConfig() {
return {
type: 'modulus',
input: this._a.__getNativeTag(),
modulus: this._modulus
};
}
}
var _default = AnimatedModulo;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/nodes/AnimatedMultiplication.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _AnimatedInterpolation = _interopRequireDefault(require("./AnimatedInterpolation"));
var _AnimatedValue = _interopRequireDefault(require("./AnimatedValue"));
var _AnimatedWithChildren = _interopRequireDefault(require("./AnimatedWithChildren"));
class AnimatedMultiplication extends _AnimatedWithChildren.default {
constructor(a, b) {
super();
this._a = typeof a === 'number' ? new _AnimatedValue.default(a) : a;
this._b = typeof b === 'number' ? new _AnimatedValue.default(b) : b;
}
__makeNative(platformConfig) {
this._a.__makeNative(platformConfig);
this._b.__makeNative(platformConfig);
super.__makeNative(platformConfig);
}
__getValue() {
return this._a.__getValue() * this._b.__getValue();
}
interpolate(config) {
return new _AnimatedInterpolation.default(this, config);
}
__attach() {
this._a.__addChild(this);
this._b.__addChild(this);
}
__detach() {
this._a.__removeChild(this);
this._b.__removeChild(this);
super.__detach();
}
__getNativeConfig() {
return {
type: 'multiplication',
input: [this._a.__getNativeTag(), this._b.__getNativeTag()]
};
}
}
var _default = AnimatedMultiplication;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/nodes/AnimatedNode.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _NativeAnimatedHelper = _interopRequireDefault(require("../NativeAnimatedHelper"));
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
var NativeAnimatedAPI = _NativeAnimatedHelper.default.API;
var _uniqueId = 1;
// Note(vjeux): this would be better as an interface but flow doesn't
// support them yet
class AnimatedNode {
__attach() {}
__detach() {
if (this.__isNative && this.__nativeTag != null) {
_NativeAnimatedHelper.default.API.dropAnimatedNode(this.__nativeTag);
this.__nativeTag = undefined;
}
}
__getValue() {}
__getAnimatedValue() {
return this.__getValue();
}
__addChild(child) {}
__removeChild(child) {}
__getChildren() {
return [];
}
/* Methods and props used by native Animated impl */
constructor() {
this._listeners = {};
}
__makeNative(platformConfig) {
if (!this.__isNative) {
throw new Error('This node cannot be made a "native" animated node');
}
this._platformConfig = platformConfig;
if (this.hasListeners()) {
this._startListeningToNativeValueUpdates();
}
}
/**
* Adds an asynchronous listener to the value so you can observe updates from
* animations. This is useful because there is no way to
* synchronously read the value because it might be driven natively.
*
* See https://reactnative.dev/docs/animatedvalue#addlistener
*/
addListener(callback) {
var id = String(_uniqueId++);
this._listeners[id] = callback;
if (this.__isNative) {
this._startListeningToNativeValueUpdates();
}
return id;
}
/**
* Unregister a listener. The `id` param shall match the identifier
* previously returned by `addListener()`.
*
* See https://reactnative.dev/docs/animatedvalue#removelistener
*/
removeListener(id) {
delete this._listeners[id];
if (this.__isNative && !this.hasListeners()) {
this._stopListeningForNativeValueUpdates();
}
}
/**
* Remove all registered listeners.
*
* See https://reactnative.dev/docs/animatedvalue#removealllisteners
*/
removeAllListeners() {
this._listeners = {};
if (this.__isNative) {
this._stopListeningForNativeValueUpdates();
}
}
hasListeners() {
return !!Object.keys(this._listeners).length;
}
_startListeningToNativeValueUpdates() {
if (this.__nativeAnimatedValueListener && !this.__shouldUpdateListenersForNewNativeTag) {
return;
}
if (this.__shouldUpdateListenersForNewNativeTag) {
this.__shouldUpdateListenersForNewNativeTag = false;
this._stopListeningForNativeValueUpdates();
}
NativeAnimatedAPI.startListeningToAnimatedNodeValue(this.__getNativeTag());
this.__nativeAnimatedValueListener = _NativeAnimatedHelper.default.nativeEventEmitter.addListener('onAnimatedValueUpdate', data => {
if (data.tag !== this.__getNativeTag()) {
return;
}
this.__onAnimatedValueUpdateReceived(data.value);
});
}
__onAnimatedValueUpdateReceived(value) {
this.__callListeners(value);
}
__callListeners(value) {
for (var _key in this._listeners) {
this._listeners[_key]({
value
});
}
}
_stopListeningForNativeValueUpdates() {
if (!this.__nativeAnimatedValueListener) {
return;
}
this.__nativeAnimatedValueListener.remove();
this.__nativeAnimatedValueListener = null;
NativeAnimatedAPI.stopListeningToAnimatedNodeValue(this.__getNativeTag());
}
__getNativeTag() {
var _this$__nativeTag;
_NativeAnimatedHelper.default.assertNativeAnimatedModule();
(0, _invariant.default)(this.__isNative, 'Attempt to get native tag from node not marked as "native"');
var nativeTag = (_this$__nativeTag = this.__nativeTag) !== null && _this$__nativeTag !== void 0 ? _this$__nativeTag : _NativeAnimatedHelper.default.generateNewNodeTag();
if (this.__nativeTag == null) {
this.__nativeTag = nativeTag;
var config = this.__getNativeConfig();
if (this._platformConfig) {
config.platformConfig = this._platformConfig;
}
_NativeAnimatedHelper.default.API.createAnimatedNode(nativeTag, config);
this.__shouldUpdateListenersForNewNativeTag = true;
}
return nativeTag;
}
__getNativeConfig() {
throw new Error('This JS animated node type cannot be used as native animated node');
}
toJSON() {
return this.__getValue();
}
__getPlatformConfig() {
return this._platformConfig;
}
__setPlatformConfig(platformConfig) {
this._platformConfig = platformConfig;
}
}
var _default = AnimatedNode;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/nodes/AnimatedProps.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _AnimatedEvent = require("../AnimatedEvent");
var _AnimatedNode = _interopRequireDefault(require("./AnimatedNode"));
var _AnimatedStyle = _interopRequireDefault(require("./AnimatedStyle"));
var _NativeAnimatedHelper = _interopRequireDefault(require("../NativeAnimatedHelper"));
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
class AnimatedProps extends _AnimatedNode.default {
constructor(props, callback) {
super();
if (props.style) {
props = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, props), {}, {
style: new _AnimatedStyle.default(props.style)
});
}
this._props = props;
this._callback = callback;
this.__attach();
}
__getValue() {
var props = {};
for (var key in this._props) {
var value = this._props[key];
if (value instanceof _AnimatedNode.default) {
if (!value.__isNative || value instanceof _AnimatedStyle.default) {
// We cannot use value of natively driven nodes this way as the value we have access from
// JS may not be up to date.
props[key] = value.__getValue();
}
} else if (value instanceof _AnimatedEvent.AnimatedEvent) {
props[key] = value.__getHandler();
} else {
props[key] = value;
}
}
return props;
}
__getAnimatedValue() {
var props = {};
for (var key in this._props) {
var value = this._props[key];
if (value instanceof _AnimatedNode.default) {
props[key] = value.__getAnimatedValue();
}
}
return props;
}
__attach() {
for (var key in this._props) {
var value = this._props[key];
if (value instanceof _AnimatedNode.default) {
value.__addChild(this);
}
}
}
__detach() {
if (this.__isNative && this._animatedView) {
this.__disconnectAnimatedView();
}
for (var key in this._props) {
var value = this._props[key];
if (value instanceof _AnimatedNode.default) {
value.__removeChild(this);
}
}
super.__detach();
}
update() {
this._callback();
}
__makeNative() {
if (!this.__isNative) {
this.__isNative = true;
for (var key in this._props) {
var value = this._props[key];
if (value instanceof _AnimatedNode.default) {
value.__makeNative();
}
}
if (this._animatedView) {
this.__connectAnimatedView();
}
}
}
setNativeView(animatedView) {
if (this._animatedView === animatedView) {
return;
}
this._animatedView = animatedView;
if (this.__isNative) {
this.__connectAnimatedView();
}
}
__connectAnimatedView() {
(0, _invariant.default)(this.__isNative, 'Expected node to be marked as "native"');
var nativeViewTag = this._animatedView;
(0, _invariant.default)(nativeViewTag != null, 'Unable to locate attached view in the native tree');
_NativeAnimatedHelper.default.API.connectAnimatedNodeToView(this.__getNativeTag(), nativeViewTag);
}
__disconnectAnimatedView() {
(0, _invariant.default)(this.__isNative, 'Expected node to be marked as "native"');
var nativeViewTag = this._animatedView;
(0, _invariant.default)(nativeViewTag != null, 'Unable to locate attached view in the native tree');
_NativeAnimatedHelper.default.API.disconnectAnimatedNodeFromView(this.__getNativeTag(), nativeViewTag);
}
__restoreDefaultValues() {
// When using the native driver, view properties need to be restored to
// their default values manually since react no longer tracks them. This
// is needed to handle cases where a prop driven by native animated is removed
// after having been changed natively by an animation.
if (this.__isNative) {
_NativeAnimatedHelper.default.API.restoreDefaultValues(this.__getNativeTag());
}
}
__getNativeConfig() {
var propsConfig = {};
for (var propKey in this._props) {
var value = this._props[propKey];
if (value instanceof _AnimatedNode.default) {
value.__makeNative();
propsConfig[propKey] = value.__getNativeTag();
}
}
return {
type: 'props',
props: propsConfig
};
}
}
var _default = AnimatedProps;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/nodes/AnimatedStyle.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _AnimatedNode = _interopRequireDefault(require("./AnimatedNode"));
var _AnimatedTransform = _interopRequireDefault(require("./AnimatedTransform"));
var _AnimatedWithChildren = _interopRequireDefault(require("./AnimatedWithChildren"));
var _NativeAnimatedHelper = _interopRequireDefault(require("../NativeAnimatedHelper"));
var _StyleSheet = _interopRequireDefault(require("../../../../exports/StyleSheet"));
var flattenStyle = _StyleSheet.default.flatten;
function createAnimatedStyle(inputStyle) {
var style = flattenStyle(inputStyle);
var animatedStyles = {};
for (var key in style) {
var value = style[key];
if (key === 'transform' && Array.isArray(value)) {
animatedStyles[key] = new _AnimatedTransform.default(value);
} else if (value instanceof _AnimatedNode.default) {
animatedStyles[key] = value;
} else if (value && !Array.isArray(value) && typeof value === 'object') {
animatedStyles[key] = createAnimatedStyle(value);
}
}
return animatedStyles;
}
class AnimatedStyle extends _AnimatedWithChildren.default {
constructor(style) {
super();
this._inputStyle = style;
this._style = createAnimatedStyle(style);
}
// Recursively get values for nested styles (like iOS's shadowOffset)
_walkStyleAndGetValues(style) {
var updatedStyle = {};
for (var key in style) {
var value = style[key];
if (value instanceof _AnimatedNode.default) {
if (!value.__isNative) {
// We cannot use value of natively driven nodes this way as the value we have access from
// JS may not be up to date.
updatedStyle[key] = value.__getValue();
}
} else if (value && !Array.isArray(value) && typeof value === 'object') {
// Support animating nested values (for example: shadowOffset.height)
updatedStyle[key] = this._walkStyleAndGetValues(value);
} else {
updatedStyle[key] = value;
}
}
return updatedStyle;
}
__getValue() {
return [this._inputStyle, this._walkStyleAndGetValues(this._style)];
}
// Recursively get animated values for nested styles (like iOS's shadowOffset)
_walkStyleAndGetAnimatedValues(style) {
var updatedStyle = {};
for (var key in style) {
var value = style[key];
if (value instanceof _AnimatedNode.default) {
updatedStyle[key] = value.__getAnimatedValue();
} else if (value && !Array.isArray(value) && typeof value === 'object') {
// Support animating nested values (for example: shadowOffset.height)
updatedStyle[key] = this._walkStyleAndGetAnimatedValues(value);
}
}
return updatedStyle;
}
__getAnimatedValue() {
return this._walkStyleAndGetAnimatedValues(this._style);
}
__attach() {
for (var key in this._style) {
var value = this._style[key];
if (value instanceof _AnimatedNode.default) {
value.__addChild(this);
}
}
}
__detach() {
for (var key in this._style) {
var value = this._style[key];
if (value instanceof _AnimatedNode.default) {
value.__removeChild(this);
}
}
super.__detach();
}
__makeNative() {
for (var key in this._style) {
var value = this._style[key];
if (value instanceof _AnimatedNode.default) {
value.__makeNative();
}
}
super.__makeNative();
}
__getNativeConfig() {
var styleConfig = {};
for (var styleKey in this._style) {
if (this._style[styleKey] instanceof _AnimatedNode.default) {
var style = this._style[styleKey];
style.__makeNative();
styleConfig[styleKey] = style.__getNativeTag();
}
}
_NativeAnimatedHelper.default.validateStyles(styleConfig);
return {
type: 'style',
style: styleConfig
};
}
}
var _default = AnimatedStyle;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/nodes/AnimatedSubtraction.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _AnimatedInterpolation = _interopRequireDefault(require("./AnimatedInterpolation"));
var _AnimatedValue = _interopRequireDefault(require("./AnimatedValue"));
var _AnimatedWithChildren = _interopRequireDefault(require("./AnimatedWithChildren"));
class AnimatedSubtraction extends _AnimatedWithChildren.default {
constructor(a, b) {
super();
this._a = typeof a === 'number' ? new _AnimatedValue.default(a) : a;
this._b = typeof b === 'number' ? new _AnimatedValue.default(b) : b;
}
__makeNative(platformConfig) {
this._a.__makeNative(platformConfig);
this._b.__makeNative(platformConfig);
super.__makeNative(platformConfig);
}
__getValue() {
return this._a.__getValue() - this._b.__getValue();
}
interpolate(config) {
return new _AnimatedInterpolation.default(this, config);
}
__attach() {
this._a.__addChild(this);
this._b.__addChild(this);
}
__detach() {
this._a.__removeChild(this);
this._b.__removeChild(this);
super.__detach();
}
__getNativeConfig() {
return {
type: 'subtraction',
input: [this._a.__getNativeTag(), this._b.__getNativeTag()]
};
}
}
var _default = AnimatedSubtraction;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/nodes/AnimatedTracking.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _AnimatedValue = _interopRequireDefault(require("./AnimatedValue"));
var _AnimatedNode = _interopRequireDefault(require("./AnimatedNode"));
var _NativeAnimatedHelper = require("../NativeAnimatedHelper");
class AnimatedTracking extends _AnimatedNode.default {
constructor(value, parent, animationClass, animationConfig, callback) {
super();
this._value = value;
this._parent = parent;
this._animationClass = animationClass;
this._animationConfig = animationConfig;
this._useNativeDriver = (0, _NativeAnimatedHelper.shouldUseNativeDriver)(animationConfig);
this._callback = callback;
this.__attach();
}
__makeNative() {
this.__isNative = true;
this._parent.__makeNative();
super.__makeNative();
this._value.__makeNative();
}
__getValue() {
return this._parent.__getValue();
}
__attach() {
this._parent.__addChild(this);
if (this._useNativeDriver) {
// when the tracking starts we need to convert this node to a "native node"
// so that the parent node will be made "native" too. This is necessary as
// if we don't do this `update` method will get called. At that point it
// may be too late as it would mean the JS driver has already started
// updating node values
this.__makeNative();
}
}
__detach() {
this._parent.__removeChild(this);
super.__detach();
}
update() {
this._value.animate(new this._animationClass((0, _objectSpread2.default)((0, _objectSpread2.default)({}, this._animationConfig), {}, {
toValue: this._animationConfig.toValue.__getValue()
})), this._callback);
}
__getNativeConfig() {
var animation = new this._animationClass((0, _objectSpread2.default)((0, _objectSpread2.default)({}, this._animationConfig), {}, {
// remove toValue from the config as it's a ref to Animated.Value
toValue: undefined
}));
var animationConfig = animation.__getNativeAnimationConfig();
return {
type: 'tracking',
animationId: (0, _NativeAnimatedHelper.generateNewAnimationId)(),
animationConfig,
toValue: this._parent.__getNativeTag(),
value: this._value.__getNativeTag()
};
}
}
var _default = AnimatedTracking;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/nodes/AnimatedTransform.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _AnimatedNode = _interopRequireDefault(require("./AnimatedNode"));
var _AnimatedWithChildren = _interopRequireDefault(require("./AnimatedWithChildren"));
var _NativeAnimatedHelper = _interopRequireDefault(require("../NativeAnimatedHelper"));
class AnimatedTransform extends _AnimatedWithChildren.default {
constructor(transforms) {
super();
this._transforms = transforms;
}
__makeNative() {
this._transforms.forEach(transform => {
for (var key in transform) {
var value = transform[key];
if (value instanceof _AnimatedNode.default) {
value.__makeNative();
}
}
});
super.__makeNative();
}
__getValue() {
return this._transforms.map(transform => {
var result = {};
for (var key in transform) {
var value = transform[key];
if (value instanceof _AnimatedNode.default) {
result[key] = value.__getValue();
} else {
result[key] = value;
}
}
return result;
});
}
__getAnimatedValue() {
return this._transforms.map(transform => {
var result = {};
for (var key in transform) {
var value = transform[key];
if (value instanceof _AnimatedNode.default) {
result[key] = value.__getAnimatedValue();
} else {
// All transform components needed to recompose matrix
result[key] = value;
}
}
return result;
});
}
__attach() {
this._transforms.forEach(transform => {
for (var key in transform) {
var value = transform[key];
if (value instanceof _AnimatedNode.default) {
value.__addChild(this);
}
}
});
}
__detach() {
this._transforms.forEach(transform => {
for (var key in transform) {
var value = transform[key];
if (value instanceof _AnimatedNode.default) {
value.__removeChild(this);
}
}
});
super.__detach();
}
__getNativeConfig() {
var transConfigs = [];
this._transforms.forEach(transform => {
for (var key in transform) {
var value = transform[key];
if (value instanceof _AnimatedNode.default) {
transConfigs.push({
type: 'animated',
property: key,
nodeTag: value.__getNativeTag()
});
} else {
transConfigs.push({
type: 'static',
property: key,
value: _NativeAnimatedHelper.default.transformDataType(value)
});
}
}
});
_NativeAnimatedHelper.default.validateTransform(transConfigs);
return {
type: 'transform',
transforms: transConfigs
};
}
}
var _default = AnimatedTransform;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/nodes/AnimatedValue.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _AnimatedInterpolation = _interopRequireDefault(require("./AnimatedInterpolation"));
var _AnimatedWithChildren = _interopRequireDefault(require("./AnimatedWithChildren"));
var _InteractionManager = _interopRequireDefault(require("../../../../exports/InteractionManager"));
var _NativeAnimatedHelper = _interopRequireDefault(require("../NativeAnimatedHelper"));
var NativeAnimatedAPI = _NativeAnimatedHelper.default.API;
/**
* Animated works by building a directed acyclic graph of dependencies
* transparently when you render your Animated components.
*
* new Animated.Value(0)
* .interpolate() .interpolate() new Animated.Value(1)
* opacity translateY scale
* style transform
* View#234 style
* View#123
*
* A) Top Down phase
* When an Animated.Value is updated, we recursively go down through this
* graph in order to find leaf nodes: the views that we flag as needing
* an update.
*
* B) Bottom Up phase
* When a view is flagged as needing an update, we recursively go back up
* in order to build the new value that it needs. The reason why we need
* this two-phases process is to deal with composite props such as
* transform which can receive values from multiple parents.
*/
function _flush(rootNode) {
var animatedStyles = new Set();
function findAnimatedStyles(node) {
/* $FlowFixMe[prop-missing] (>=0.68.0 site=react_native_fb) This comment
* suppresses an error found when Flow v0.68 was deployed. To see the error
* delete this comment and run Flow. */
if (typeof node.update === 'function') {
animatedStyles.add(node);
} else {
node.__getChildren().forEach(findAnimatedStyles);
}
}
findAnimatedStyles(rootNode);
// $FlowFixMe[prop-missing]
animatedStyles.forEach(animatedStyle => animatedStyle.update());
}
/**
* Some operations are executed only on batch end, which is _mostly_ scheduled when
* Animated component props change. For some of the changes which require immediate execution
* (e.g. setValue), we create a separate batch in case none is scheduled.
*/
function _executeAsAnimatedBatch(id, operation) {
NativeAnimatedAPI.setWaitingForIdentifier(id);
operation();
NativeAnimatedAPI.unsetWaitingForIdentifier(id);
}
/**
* Standard value for driving animations. One `Animated.Value` can drive
* multiple properties in a synchronized fashion, but can only be driven by one
* mechanism at a time. Using a new mechanism (e.g. starting a new animation,
* or calling `setValue`) will stop any previous ones.
*
* See https://reactnative.dev/docs/animatedvalue
*/
class AnimatedValue extends _AnimatedWithChildren.default {
constructor(value, config) {
super();
if (typeof value !== 'number') {
throw new Error('AnimatedValue: Attempting to set value to undefined');
}
this._startingValue = this._value = value;
this._offset = 0;
this._animation = null;
if (config && config.useNativeDriver) {
this.__makeNative();
}
}
__detach() {
if (this.__isNative) {
NativeAnimatedAPI.getValue(this.__getNativeTag(), value => {
this._value = value - this._offset;
});
}
this.stopAnimation();
super.__detach();
}
__getValue() {
return this._value + this._offset;
}
/**
* Directly set the value. This will stop any animations running on the value
* and update all the bound properties.
*
* See https://reactnative.dev/docs/animatedvalue#setvalue
*/
setValue(value) {
if (this._animation) {
this._animation.stop();
this._animation = null;
}
this._updateValue(value, !this.__isNative /* don't perform a flush for natively driven values */);
if (this.__isNative) {
_executeAsAnimatedBatch(this.__getNativeTag().toString(), () => NativeAnimatedAPI.setAnimatedNodeValue(this.__getNativeTag(), value));
}
}
/**
* Sets an offset that is applied on top of whatever value is set, whether via
* `setValue`, an animation, or `Animated.event`. Useful for compensating
* things like the start of a pan gesture.
*
* See https://reactnative.dev/docs/animatedvalue#setoffset
*/
setOffset(offset) {
this._offset = offset;
if (this.__isNative) {
NativeAnimatedAPI.setAnimatedNodeOffset(this.__getNativeTag(), offset);
}
}
/**
* Merges the offset value into the base value and resets the offset to zero.
* The final output of the value is unchanged.
*
* See https://reactnative.dev/docs/animatedvalue#flattenoffset
*/
flattenOffset() {
this._value += this._offset;
this._offset = 0;
if (this.__isNative) {
NativeAnimatedAPI.flattenAnimatedNodeOffset(this.__getNativeTag());
}
}
/**
* Sets the offset value to the base value, and resets the base value to zero.
* The final output of the value is unchanged.
*
* See https://reactnative.dev/docs/animatedvalue#extractoffset
*/
extractOffset() {
this._offset += this._value;
this._value = 0;
if (this.__isNative) {
NativeAnimatedAPI.extractAnimatedNodeOffset(this.__getNativeTag());
}
}
/**
* Stops any running animation or tracking. `callback` is invoked with the
* final value after stopping the animation, which is useful for updating
* state to match the animation position with layout.
*
* See https://reactnative.dev/docs/animatedvalue#stopanimation
*/
stopAnimation(callback) {
this.stopTracking();
this._animation && this._animation.stop();
this._animation = null;
if (callback) {
if (this.__isNative) {
NativeAnimatedAPI.getValue(this.__getNativeTag(), callback);
} else {
callback(this.__getValue());
}
}
}
/**
* Stops any animation and resets the value to its original.
*
* See https://reactnative.dev/docs/animatedvalue#resetanimation
*/
resetAnimation(callback) {
this.stopAnimation(callback);
this._value = this._startingValue;
if (this.__isNative) {
NativeAnimatedAPI.setAnimatedNodeValue(this.__getNativeTag(), this._startingValue);
}
}
__onAnimatedValueUpdateReceived(value) {
this._updateValue(value, false /*flush*/);
}
/**
* Interpolates the value before updating the property, e.g. mapping 0-1 to
* 0-10.
*/
interpolate(config) {
return new _AnimatedInterpolation.default(this, config);
}
/**
* Typically only used internally, but could be used by a custom Animation
* class.
*
* See https://reactnative.dev/docs/animatedvalue#animate
*/
animate(animation, callback) {
var handle = null;
if (animation.__isInteraction) {
handle = _InteractionManager.default.createInteractionHandle();
}
var previousAnimation = this._animation;
this._animation && this._animation.stop();
this._animation = animation;
animation.start(this._value, value => {
// Natively driven animations will never call into that callback
this._updateValue(value, true /* flush */);
}, result => {
this._animation = null;
if (handle !== null) {
_InteractionManager.default.clearInteractionHandle(handle);
}
callback && callback(result);
}, previousAnimation, this);
}
/**
* Typically only used internally.
*/
stopTracking() {
this._tracking && this._tracking.__detach();
this._tracking = null;
}
/**
* Typically only used internally.
*/
track(tracking) {
this.stopTracking();
this._tracking = tracking;
// Make sure that the tracking animation starts executing
this._tracking && this._tracking.update();
}
_updateValue(value, flush) {
if (value === undefined) {
throw new Error('AnimatedValue: Attempting to set value to undefined');
}
this._value = value;
if (flush) {
_flush(this);
}
super.__callListeners(this.__getValue());
}
__getNativeConfig() {
return {
type: 'value',
value: this._value,
offset: this._offset
};
}
}
var _default = AnimatedValue;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/nodes/AnimatedValueXY.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _AnimatedValue = _interopRequireDefault(require("./AnimatedValue"));
var _AnimatedWithChildren = _interopRequireDefault(require("./AnimatedWithChildren"));
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
var _uniqueId = 1;
/**
* 2D Value for driving 2D animations, such as pan gestures. Almost identical
* API to normal `Animated.Value`, but multiplexed.
*
* See https://reactnative.dev/docs/animatedvaluexy.html
*/
class AnimatedValueXY extends _AnimatedWithChildren.default {
constructor(valueIn) {
super();
var value = valueIn || {
x: 0,
y: 0
}; // fixme: shouldn't need `: any`
if (typeof value.x === 'number' && typeof value.y === 'number') {
this.x = new _AnimatedValue.default(value.x);
this.y = new _AnimatedValue.default(value.y);
} else {
(0, _invariant.default)(value.x instanceof _AnimatedValue.default && value.y instanceof _AnimatedValue.default, 'AnimatedValueXY must be initialized with an object of numbers or ' + 'AnimatedValues.');
this.x = value.x;
this.y = value.y;
}
this._listeners = {};
}
/**
* Directly set the value. This will stop any animations running on the value
* and update all the bound properties.
*
* See https://reactnative.dev/docs/animatedvaluexy.html#setvalue
*/
setValue(value) {
this.x.setValue(value.x);
this.y.setValue(value.y);
}
/**
* Sets an offset that is applied on top of whatever value is set, whether
* via `setValue`, an animation, or `Animated.event`. Useful for compensating
* things like the start of a pan gesture.
*
* See https://reactnative.dev/docs/animatedvaluexy.html#setoffset
*/
setOffset(offset) {
this.x.setOffset(offset.x);
this.y.setOffset(offset.y);
}
/**
* Merges the offset value into the base value and resets the offset to zero.
* The final output of the value is unchanged.
*
* See https://reactnative.dev/docs/animatedvaluexy.html#flattenoffset
*/
flattenOffset() {
this.x.flattenOffset();
this.y.flattenOffset();
}
/**
* Sets the offset value to the base value, and resets the base value to
* zero. The final output of the value is unchanged.
*
* See https://reactnative.dev/docs/animatedvaluexy.html#extractoffset
*/
extractOffset() {
this.x.extractOffset();
this.y.extractOffset();
}
__getValue() {
return {
x: this.x.__getValue(),
y: this.y.__getValue()
};
}
/**
* Stops any animation and resets the value to its original.
*
* See https://reactnative.dev/docs/animatedvaluexy.html#resetanimation
*/
resetAnimation(callback) {
this.x.resetAnimation();
this.y.resetAnimation();
callback && callback(this.__getValue());
}
/**
* Stops any running animation or tracking. `callback` is invoked with the
* final value after stopping the animation, which is useful for updating
* state to match the animation position with layout.
*
* See https://reactnative.dev/docs/animatedvaluexy.html#stopanimation
*/
stopAnimation(callback) {
this.x.stopAnimation();
this.y.stopAnimation();
callback && callback(this.__getValue());
}
/**
* Adds an asynchronous listener to the value so you can observe updates from
* animations. This is useful because there is no way to synchronously read
* the value because it might be driven natively.
*
* Returns a string that serves as an identifier for the listener.
*
* See https://reactnative.dev/docs/animatedvaluexy.html#addlistener
*/
addListener(callback) {
var id = String(_uniqueId++);
var jointCallback = _ref => {
var number = _ref.value;
callback(this.__getValue());
};
this._listeners[id] = {
x: this.x.addListener(jointCallback),
y: this.y.addListener(jointCallback)
};
return id;
}
/**
* Unregister a listener. The `id` param shall match the identifier
* previously returned by `addListener()`.
*
* See https://reactnative.dev/docs/animatedvaluexy.html#removelistener
*/
removeListener(id) {
this.x.removeListener(this._listeners[id].x);
this.y.removeListener(this._listeners[id].y);
delete this._listeners[id];
}
/**
* Remove all registered listeners.
*
* See https://reactnative.dev/docs/animatedvaluexy.html#removealllisteners
*/
removeAllListeners() {
this.x.removeAllListeners();
this.y.removeAllListeners();
this._listeners = {};
}
/**
* Converts `{x, y}` into `{left, top}` for use in style.
*
* See https://reactnative.dev/docs/animatedvaluexy.html#getlayout
*/
getLayout() {
return {
left: this.x,
top: this.y
};
}
/**
* Converts `{x, y}` into a useable translation transform.
*
* See https://reactnative.dev/docs/animatedvaluexy.html#gettranslatetransform
*/
getTranslateTransform() {
return [{
translateX: this.x
}, {
translateY: this.y
}];
}
}
var _default = AnimatedValueXY;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/nodes/AnimatedWithChildren.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _createForOfIteratorHelperLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/createForOfIteratorHelperLoose"));
var _AnimatedNode = _interopRequireDefault(require("./AnimatedNode"));
var _NativeAnimatedHelper = _interopRequireDefault(require("../NativeAnimatedHelper"));
class AnimatedWithChildren extends _AnimatedNode.default {
constructor() {
super();
this._children = [];
}
__makeNative(platformConfig) {
if (!this.__isNative) {
this.__isNative = true;
for (var _iterator = (0, _createForOfIteratorHelperLoose2.default)(this._children), _step; !(_step = _iterator()).done;) {
var child = _step.value;
child.__makeNative(platformConfig);
_NativeAnimatedHelper.default.API.connectAnimatedNodes(this.__getNativeTag(), child.__getNativeTag());
}
}
super.__makeNative(platformConfig);
}
__addChild(child) {
if (this._children.length === 0) {
this.__attach();
}
this._children.push(child);
if (this.__isNative) {
// Only accept "native" animated nodes as children
child.__makeNative(this.__getPlatformConfig());
_NativeAnimatedHelper.default.API.connectAnimatedNodes(this.__getNativeTag(), child.__getNativeTag());
}
}
__removeChild(child) {
var index = this._children.indexOf(child);
if (index === -1) {
console.warn("Trying to remove a child that doesn't exist");
return;
}
if (this.__isNative && child.__isNative) {
_NativeAnimatedHelper.default.API.disconnectAnimatedNodes(this.__getNativeTag(), child.__getNativeTag());
}
this._children.splice(index, 1);
if (this._children.length === 0) {
this.__detach();
}
}
__getChildren() {
return this._children;
}
__callListeners(value) {
super.__callListeners(value);
if (!this.__isNative) {
for (var _iterator2 = (0, _createForOfIteratorHelperLoose2.default)(this._children), _step2; !(_step2 = _iterator2()).done;) {
var child = _step2.value;
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
if (child.__getValue) {
child.__callListeners(child.__getValue());
}
}
}
}
}
var _default = AnimatedWithChildren;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Animated/useAnimatedProps.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = useAnimatedProps;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _AnimatedProps = _interopRequireDefault(require("./nodes/AnimatedProps"));
var _AnimatedEvent = require("./AnimatedEvent");
var _useRefEffect = _interopRequireDefault(require("../Utilities/useRefEffect"));
var _NativeAnimatedHelper = _interopRequireDefault(require("./NativeAnimatedHelper"));
var _react = require("react");
var _useLayoutEffect = _interopRequireDefault(require("../../../modules/useLayoutEffect"));
function useAnimatedProps(props) {
var _useReducer = (0, _react.useReducer)(count => count + 1, 0),
scheduleUpdate = _useReducer[1];
var onUpdateRef = (0, _react.useRef)(null);
// TODO: Only invalidate `node` if animated props or `style` change. In the
// previous implementation, we permitted `style` to override props with the
// same name property name as styles, so we can probably continue doing that.
// The ordering of other props *should* not matter.
var node = (0, _react.useMemo)(() => new _AnimatedProps.default(props, () => onUpdateRef.current == null ? void 0 : onUpdateRef.current()), [props]);
useAnimatedPropsLifecycle(node);
// TODO: This "effect" does three things:
//
// 1) Call `setNativeView`.
// 2) Update `onUpdateRef`.
// 3) Update listeners for `AnimatedEvent` props.
//
// Ideally, each of these would be separat "effects" so that they are not
// unnecessarily re-run when irrelevant dependencies change. For example, we
// should be able to hoist all `AnimatedEvent` props and only do #3 if either
// the `AnimatedEvent` props change or `instance` changes.
//
// But there is no way to transparently compose three separate callback refs,
// so we just combine them all into one for now.
var refEffect = (0, _react.useCallback)(instance => {
// NOTE: This may be called more often than necessary (e.g. when `props`
// changes), but `setNativeView` already optimizes for that.
node.setNativeView(instance);
// NOTE: This callback is only used by the JavaScript animation driver.
onUpdateRef.current = () => {
// Schedule an update for this component to update `reducedProps`,
// but do not compute it immediately. If a parent also updated, we
// need to merge those new props in before updating.
scheduleUpdate();
};
var target = getEventTarget(instance);
var events = [];
for (var propName in props) {
var propValue = props[propName];
if (propValue instanceof _AnimatedEvent.AnimatedEvent && propValue.__isNative) {
propValue.__attach(target, propName);
events.push([propName, propValue]);
}
}
return () => {
onUpdateRef.current = null;
for (var _i = 0, _events = events; _i < _events.length; _i++) {
var _events$_i = _events[_i],
_propName = _events$_i[0],
_propValue = _events$_i[1];
_propValue.__detach(target, _propName);
}
};
}, [props, node]);
var callbackRef = (0, _useRefEffect.default)(refEffect);
return [reduceAnimatedProps(node), callbackRef];
}
function reduceAnimatedProps(node) {
// Force `collapsable` to be false so that the native view is not flattened.
// Flattened views cannot be accurately referenced by the native driver.
return (0, _objectSpread2.default)((0, _objectSpread2.default)({}, node.__getValue()), {}, {
collapsable: false
});
}
/**
* Manages the lifecycle of the supplied `AnimatedProps` by invoking `__attach`
* and `__detach`. However, this is more complicated because `AnimatedProps`
* uses reference counting to determine when to recursively detach its children
* nodes. So in order to optimize this, we avoid detaching until the next attach
* unless we are unmounting.
*/
function useAnimatedPropsLifecycle(node) {
var prevNodeRef = (0, _react.useRef)(null);
var isUnmountingRef = (0, _react.useRef)(false);
(0, _react.useEffect)(() => {
// It is ok for multiple components to call `flushQueue` because it noops
// if the queue is empty. When multiple animated components are mounted at
// the same time. Only first component flushes the queue and the others will noop.
_NativeAnimatedHelper.default.API.flushQueue();
});
(0, _useLayoutEffect.default)(() => {
isUnmountingRef.current = false;
return () => {
isUnmountingRef.current = true;
};
}, []);
(0, _useLayoutEffect.default)(() => {
node.__attach();
if (prevNodeRef.current != null) {
var prevNode = prevNodeRef.current;
// TODO: Stop restoring default values (unless `reset` is called).
prevNode.__restoreDefaultValues();
prevNode.__detach();
prevNodeRef.current = null;
}
return () => {
if (isUnmountingRef.current) {
// NOTE: Do not restore default values on unmount, see D18197735.
node.__detach();
} else {
prevNodeRef.current = node;
}
};
}, [node]);
}
function getEventTarget(instance) {
return typeof instance === 'object' && typeof (instance == null ? void 0 : instance.getScrollableNode) === 'function' ?
// $FlowFixMe[incompatible-use] - Legacy instance assumptions.
instance.getScrollableNode() : instance;
}
// $FlowFixMe[unclear-type] - Legacy instance assumptions.
function isFabricInstance(instance) {
var _instance$getScrollRe;
return hasFabricHandle(instance) ||
// Some components have a setNativeProps function but aren't a host component
// such as lists like FlatList and SectionList. These should also use
// forceUpdate in Fabric since setNativeProps doesn't exist on the underlying
// host component. This crazy hack is essentially special casing those lists and
// ScrollView itself to use forceUpdate in Fabric.
// If these components end up using forwardRef then these hacks can go away
// as instance would actually be the underlying host component and the above check
// would be sufficient.
hasFabricHandle(instance == null ? void 0 : instance.getNativeScrollRef == null ? void 0 : instance.getNativeScrollRef()) || hasFabricHandle(instance == null ? void 0 : instance.getScrollResponder == null ? void 0 : (_instance$getScrollRe = instance.getScrollResponder()) == null ? void 0 : _instance$getScrollRe.getNativeScrollRef == null ? void 0 : _instance$getScrollRe.getNativeScrollRef());
}
// $FlowFixMe[unclear-type] - Legacy instance assumptions.
function hasFabricHandle(instance) {
var _instance$_internalIn, _instance$_internalIn2;
// eslint-disable-next-line dot-notation
return (instance == null ? void 0 : (_instance$_internalIn = instance['_internalInstanceHandle']) == null ? void 0 : (_instance$_internalIn2 = _instance$_internalIn.stateNode) == null ? void 0 : _instance$_internalIn2.canonical) != null;
}
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Batchinator/index.js
/**
* 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.
*
* @format
*
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _InteractionManager = _interopRequireDefault(require("../../../exports/InteractionManager"));
/**
* A simple class for batching up invocations of a low-pri callback. A timeout is set to run the
* callback once after a delay, no matter how many times it's scheduled. Once the delay is reached,
* InteractionManager.runAfterInteractions is used to invoke the callback after any hi-pri
* interactions are done running.
*
* Make sure to cleanup with dispose(). Example:
*
* class Widget extends React.Component {
* _batchedSave: new Batchinator(() => this._saveState, 1000);
* _saveSate() {
* // save this.state to disk
* }
* componentDidUpdate() {
* this._batchedSave.schedule();
* }
* componentWillUnmount() {
* this._batchedSave.dispose();
* }
* ...
* }
*/
class Batchinator {
constructor(callback, delayMS) {
this._delay = delayMS;
this._callback = callback;
}
/*
* Cleanup any pending tasks.
*
* By default, if there is a pending task the callback is run immediately. Set the option abort to
* true to not call the callback if it was pending.
*/
dispose(options) {
if (options === void 0) {
options = {
abort: false
};
}
if (this._taskHandle) {
this._taskHandle.cancel();
if (!options.abort) {
this._callback();
}
this._taskHandle = null;
}
}
schedule() {
if (this._taskHandle) {
return;
}
var timeoutHandle = setTimeout(() => {
this._taskHandle = _InteractionManager.default.runAfterInteractions(() => {
// Note that we clear the handle before invoking the callback so that if the callback calls
// schedule again, it will actually schedule another task.
this._taskHandle = null;
this._callback();
});
}, this._delay);
this._taskHandle = {
cancel: () => clearTimeout(timeoutHandle)
};
}
}
var _default = Batchinator;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/EventEmitter/NativeEventEmitter.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _Platform = _interopRequireDefault(require("../../../exports/Platform"));
var _RCTDeviceEventEmitter = _interopRequireDefault(require("./RCTDeviceEventEmitter"));
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
/**
* `NativeEventEmitter` is intended for use by Native Modules to emit events to
* JavaScript listeners. If a `NativeModule` is supplied to the constructor, it
* will be notified (via `addListener` and `removeListeners`) when the listener
* count changes to manage "native memory".
*
* Currently, all native events are fired via a global `RCTDeviceEventEmitter`.
* This means event names must be globally unique, and it means that call sites
* can theoretically listen to `RCTDeviceEventEmitter` (although discouraged).
*/
class NativeEventEmitter {
constructor(nativeModule) {
if (_Platform.default.OS === 'ios') {
(0, _invariant.default)(nativeModule != null, '`new NativeEventEmitter()` requires a non-null argument.');
this._nativeModule = nativeModule;
}
}
addListener(eventType, listener, context) {
var _this$_nativeModule;
(_this$_nativeModule = this._nativeModule) == null ? void 0 : _this$_nativeModule.addListener(eventType);
var subscription = _RCTDeviceEventEmitter.default.addListener(eventType, listener, context);
return {
remove: () => {
if (subscription != null) {
var _this$_nativeModule2;
(_this$_nativeModule2 = this._nativeModule) == null ? void 0 : _this$_nativeModule2.removeListeners(1);
// $FlowFixMe[incompatible-use]
subscription.remove();
subscription = null;
}
}
};
}
/**
* @deprecated Use `remove` on the EventSubscription from `addListener`.
*/
removeListener(eventType, listener) {
var _this$_nativeModule3;
(_this$_nativeModule3 = this._nativeModule) == null ? void 0 : _this$_nativeModule3.removeListeners(1);
// NOTE: This will report a deprecation notice via `console.error`.
// $FlowFixMe[prop-missing] - `removeListener` exists but is deprecated.
_RCTDeviceEventEmitter.default.removeListener(eventType, listener);
}
emit(eventType) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
// Generally, `RCTDeviceEventEmitter` is directly invoked. But this is
// included for completeness.
_RCTDeviceEventEmitter.default.emit(eventType, ...args);
}
removeAllListeners(eventType) {
var _this$_nativeModule4;
(0, _invariant.default)(eventType != null, '`NativeEventEmitter.removeAllListener()` requires a non-null argument.');
(_this$_nativeModule4 = this._nativeModule) == null ? void 0 : _this$_nativeModule4.removeListeners(this.listenerCount(eventType));
_RCTDeviceEventEmitter.default.removeAllListeners(eventType);
}
listenerCount(eventType) {
return _RCTDeviceEventEmitter.default.listenerCount(eventType);
}
}
exports.default = NativeEventEmitter;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/EventEmitter/RCTDeviceEventEmitter.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _EventEmitter = _interopRequireDefault(require("../vendor/emitter/EventEmitter"));
/**
* 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.
*
*
* @format
*/
/**
* Global EventEmitter used by the native platform to emit events to JavaScript.
* Events are identified by globally unique event names.
*
* NativeModules that emit events should instead subclass `NativeEventEmitter`.
*/
var _default = new _EventEmitter.default();
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/FillRateHelper/index.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
class Info {
constructor() {
this.any_blank_count = 0;
this.any_blank_ms = 0;
this.any_blank_speed_sum = 0;
this.mostly_blank_count = 0;
this.mostly_blank_ms = 0;
this.pixels_blank = 0;
this.pixels_sampled = 0;
this.pixels_scrolled = 0;
this.total_time_spent = 0;
this.sample_count = 0;
}
}
var DEBUG = false;
var _listeners = [];
var _minSampleCount = 10;
var _sampleRate = DEBUG ? 1 : null;
/**
* A helper class for detecting when the maximem fill rate of `VirtualizedList` is exceeded.
* By default the sampling rate is set to zero and this will do nothing. If you want to collect
* samples (e.g. to log them), make sure to call `FillRateHelper.setSampleRate(0.0-1.0)`.
*
* Listeners and sample rate are global for all `VirtualizedList`s - typical usage will combine with
* `SceneTracker.getActiveScene` to determine the context of the events.
*/
class FillRateHelper {
static addListener(callback) {
if (_sampleRate === null) {
console.warn('Call `FillRateHelper.setSampleRate` before `addListener`.');
}
_listeners.push(callback);
return {
remove: () => {
_listeners = _listeners.filter(listener => callback !== listener);
}
};
}
static setSampleRate(sampleRate) {
_sampleRate = sampleRate;
}
static setMinSampleCount(minSampleCount) {
_minSampleCount = minSampleCount;
}
constructor(getFrameMetrics) {
this._anyBlankStartTime = null;
this._enabled = false;
this._info = new Info();
this._mostlyBlankStartTime = null;
this._samplesStartTime = null;
this._getFrameMetrics = getFrameMetrics;
this._enabled = (_sampleRate || 0) > Math.random();
this._resetData();
}
activate() {
if (this._enabled && this._samplesStartTime == null) {
DEBUG && console.debug('FillRateHelper: activate');
this._samplesStartTime = global.performance.now();
}
}
deactivateAndFlush() {
if (!this._enabled) {
return;
}
var start = this._samplesStartTime; // const for flow
if (start == null) {
DEBUG && console.debug('FillRateHelper: bail on deactivate with no start time');
return;
}
if (this._info.sample_count < _minSampleCount) {
// Don't bother with under-sampled events.
this._resetData();
return;
}
var total_time_spent = global.performance.now() - start;
var info = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, this._info), {}, {
total_time_spent
});
if (DEBUG) {
var derived = {
avg_blankness: this._info.pixels_blank / this._info.pixels_sampled,
avg_speed: this._info.pixels_scrolled / (total_time_spent / 1000),
avg_speed_when_any_blank: this._info.any_blank_speed_sum / this._info.any_blank_count,
any_blank_per_min: this._info.any_blank_count / (total_time_spent / 1000 / 60),
any_blank_time_frac: this._info.any_blank_ms / total_time_spent,
mostly_blank_per_min: this._info.mostly_blank_count / (total_time_spent / 1000 / 60),
mostly_blank_time_frac: this._info.mostly_blank_ms / total_time_spent
};
for (var key in derived) {
// $FlowFixMe[prop-missing]
derived[key] = Math.round(1000 * derived[key]) / 1000;
}
console.debug('FillRateHelper deactivateAndFlush: ', {
derived,
info
});
}
_listeners.forEach(listener => listener(info));
this._resetData();
}
computeBlankness(props, cellsAroundViewport, scrollMetrics) {
if (!this._enabled || props.getItemCount(props.data) === 0 || cellsAroundViewport.last < cellsAroundViewport.first || this._samplesStartTime == null) {
return 0;
}
var dOffset = scrollMetrics.dOffset,
offset = scrollMetrics.offset,
velocity = scrollMetrics.velocity,
visibleLength = scrollMetrics.visibleLength;
// Denominator metrics that we track for all events - most of the time there is no blankness and
// we want to capture that.
this._info.sample_count++;
this._info.pixels_sampled += Math.round(visibleLength);
this._info.pixels_scrolled += Math.round(Math.abs(dOffset));
var scrollSpeed = Math.round(Math.abs(velocity) * 1000); // px / sec
// Whether blank now or not, record the elapsed time blank if we were blank last time.
var now = global.performance.now();
if (this._anyBlankStartTime != null) {
this._info.any_blank_ms += now - this._anyBlankStartTime;
}
this._anyBlankStartTime = null;
if (this._mostlyBlankStartTime != null) {
this._info.mostly_blank_ms += now - this._mostlyBlankStartTime;
}
this._mostlyBlankStartTime = null;
var blankTop = 0;
var first = cellsAroundViewport.first;
var firstFrame = this._getFrameMetrics(first, props);
while (first <= cellsAroundViewport.last && (!firstFrame || !firstFrame.inLayout)) {
firstFrame = this._getFrameMetrics(first, props);
first++;
}
// Only count blankTop if we aren't rendering the first item, otherwise we will count the header
// as blank.
if (firstFrame && first > 0) {
blankTop = Math.min(visibleLength, Math.max(0, firstFrame.offset - offset));
}
var blankBottom = 0;
var last = cellsAroundViewport.last;
var lastFrame = this._getFrameMetrics(last, props);
while (last >= cellsAroundViewport.first && (!lastFrame || !lastFrame.inLayout)) {
lastFrame = this._getFrameMetrics(last, props);
last--;
}
// Only count blankBottom if we aren't rendering the last item, otherwise we will count the
// footer as blank.
if (lastFrame && last < props.getItemCount(props.data) - 1) {
var bottomEdge = lastFrame.offset + lastFrame.length;
blankBottom = Math.min(visibleLength, Math.max(0, offset + visibleLength - bottomEdge));
}
var pixels_blank = Math.round(blankTop + blankBottom);
var blankness = pixels_blank / visibleLength;
if (blankness > 0) {
this._anyBlankStartTime = now;
this._info.any_blank_speed_sum += scrollSpeed;
this._info.any_blank_count++;
this._info.pixels_blank += pixels_blank;
if (blankness > 0.5) {
this._mostlyBlankStartTime = now;
this._info.mostly_blank_count++;
}
} else if (scrollSpeed < 0.01 || Math.abs(dOffset) < 1) {
this.deactivateAndFlush();
}
return blankness;
}
enabled() {
return this._enabled;
}
_resetData() {
this._anyBlankStartTime = null;
this._info = new Info();
this._mostlyBlankStartTime = null;
this._samplesStartTime = null;
}
}
var _default = FillRateHelper;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/FlatList/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _View = _interopRequireDefault(require("../../../exports/View"));
var _StyleSheet = _interopRequireDefault(require("../../../exports/StyleSheet"));
var _deepDiffer = _interopRequireDefault(require("../deepDiffer"));
var _Platform = _interopRequireDefault(require("../../../exports/Platform"));
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
var React = _interopRequireWildcard(require("react"));
var _VirtualizedList = _interopRequireDefault(require("../VirtualizedList"));
var _VirtualizeUtils = require("../VirtualizeUtils");
var _memoizeOne = _interopRequireDefault(require("memoize-one"));
var _excluded = ["numColumns", "columnWrapperStyle", "removeClippedSubviews", "strictMode"];
/**
* Default Props Helper Functions
* Use the following helper functions for default values
*/
// removeClippedSubviewsOrDefault(this.props.removeClippedSubviews)
function removeClippedSubviewsOrDefault(removeClippedSubviews) {
return removeClippedSubviews !== null && removeClippedSubviews !== void 0 ? removeClippedSubviews : _Platform.default.OS === 'android';
}
// numColumnsOrDefault(this.props.numColumns)
function numColumnsOrDefault(numColumns) {
return numColumns !== null && numColumns !== void 0 ? numColumns : 1;
}
function isArrayLike(data) {
// $FlowExpectedError[incompatible-use]
return typeof Object(data).length === 'number';
}
/**
* A performant interface for rendering simple, flat lists, supporting the most handy features:
*
* - Fully cross-platform.
* - Optional horizontal mode.
* - Configurable viewability callbacks.
* - Header support.
* - Footer support.
* - Separator support.
* - Pull to Refresh.
* - Scroll loading.
* - ScrollToIndex support.
*
* If you need section support, use [`<SectionList>`](docs/sectionlist.html).
*
* Minimal Example:
*
* <FlatList
* data={[{key: 'a'}, {key: 'b'}]}
* renderItem={({item}) => <Text>{item.key}</Text>}
* />
*
* More complex, multi-select example demonstrating `PureComponent` usage for perf optimization and avoiding bugs.
*
* - By binding the `onPressItem` handler, the props will remain `===` and `PureComponent` will
* prevent wasteful re-renders unless the actual `id`, `selected`, or `title` props change, even
* if the components rendered in `MyListItem` did not have such optimizations.
* - By passing `extraData={this.state}` to `FlatList` we make sure `FlatList` itself will re-render
* when the `state.selected` changes. Without setting this prop, `FlatList` would not know it
* needs to re-render any items because it is also a `PureComponent` and the prop comparison will
* not show any changes.
* - `keyExtractor` tells the list to use the `id`s for the react keys instead of the default `key` property.
*
*
* class MyListItem extends React.PureComponent {
* _onPress = () => {
* this.props.onPressItem(this.props.id);
* };
*
* render() {
* const textColor = this.props.selected ? "red" : "black";
* return (
* <TouchableOpacity onPress={this._onPress}>
* <View>
* <Text style={{ color: textColor }}>
* {this.props.title}
* </Text>
* </View>
* </TouchableOpacity>
* );
* }
* }
*
* class MultiSelectList extends React.PureComponent {
* state = {selected: (new Map(): Map<string, boolean>)};
*
* _keyExtractor = (item, index) => item.id;
*
* _onPressItem = (id: string) => {
* // updater functions are preferred for transactional updates
* this.setState((state) => {
* // copy the map rather than modifying state.
* const selected = new Map(state.selected);
* selected.set(id, !selected.get(id)); // toggle
* return {selected};
* });
* };
*
* _renderItem = ({item}) => (
* <MyListItem
* id={item.id}
* onPressItem={this._onPressItem}
* selected={!!this.state.selected.get(item.id)}
* title={item.title}
* />
* );
*
* render() {
* return (
* <FlatList
* data={this.props.data}
* extraData={this.state}
* keyExtractor={this._keyExtractor}
* renderItem={this._renderItem}
* />
* );
* }
* }
*
* This is a convenience wrapper around [`<VirtualizedList>`](docs/virtualizedlist.html),
* and thus inherits its props (as well as those of `ScrollView`) that aren't explicitly listed
* here, along with the following caveats:
*
* - Internal state is not preserved when content scrolls out of the render window. Make sure all
* your data is captured in the item data or external stores like Flux, Redux, or Relay.
* - This is a `PureComponent` which means that it will not re-render if `props` remain shallow-
* equal. Make sure that everything your `renderItem` function depends on is passed as a prop
* (e.g. `extraData`) that is not `===` after updates, otherwise your UI may not update on
* changes. This includes the `data` prop and parent component state.
* - In order to constrain memory and enable smooth scrolling, content is rendered asynchronously
* offscreen. This means it's possible to scroll faster than the fill rate ands momentarily see
* blank content. This is a tradeoff that can be adjusted to suit the needs of each application,
* and we are working on improving it behind the scenes.
* - By default, the list looks for a `key` prop on each item and uses that for the React key.
* Alternatively, you can provide a custom `keyExtractor` prop.
*
* Also inherits [ScrollView Props](docs/scrollview.html#props), unless it is nested in another FlatList of same orientation.
*/
class FlatList extends React.PureComponent {
/**
* Scrolls to the end of the content. May be janky without `getItemLayout` prop.
*/
scrollToEnd(params) {
if (this._listRef) {
this._listRef.scrollToEnd(params);
}
}
/**
* Scrolls to the item at the specified index such that it is positioned in the viewable area
* such that `viewPosition` 0 places it at the top, 1 at the bottom, and 0.5 centered in the
* middle. `viewOffset` is a fixed number of pixels to offset the final target position.
*
* Note: cannot scroll to locations outside the render window without specifying the
* `getItemLayout` prop.
*/
scrollToIndex(params) {
if (this._listRef) {
this._listRef.scrollToIndex(params);
}
}
/**
* Requires linear scan through data - use `scrollToIndex` instead if possible.
*
* Note: cannot scroll to locations outside the render window without specifying the
* `getItemLayout` prop.
*/
scrollToItem(params) {
if (this._listRef) {
this._listRef.scrollToItem(params);
}
}
/**
* Scroll to a specific content pixel offset in the list.
*
* Check out [scrollToOffset](docs/virtualizedlist.html#scrolltooffset) of VirtualizedList
*/
scrollToOffset(params) {
if (this._listRef) {
this._listRef.scrollToOffset(params);
}
}
/**
* Tells the list an interaction has occurred, which should trigger viewability calculations, e.g.
* if `waitForInteractions` is true and the user has not scrolled. This is typically called by
* taps on items or by navigation actions.
*/
recordInteraction() {
if (this._listRef) {
this._listRef.recordInteraction();
}
}
/**
* Displays the scroll indicators momentarily.
*
* @platform ios
*/
flashScrollIndicators() {
if (this._listRef) {
this._listRef.flashScrollIndicators();
}
}
/**
* Provides a handle to the underlying scroll responder.
*/
getScrollResponder() {
if (this._listRef) {
return this._listRef.getScrollResponder();
}
}
/**
* Provides a reference to the underlying host component
*/
getNativeScrollRef() {
if (this._listRef) {
/* $FlowFixMe[incompatible-return] Suppresses errors found when fixing
* TextInput typing */
return this._listRef.getScrollRef();
}
}
getScrollableNode() {
if (this._listRef) {
return this._listRef.getScrollableNode();
}
}
constructor(_props) {
super(_props);
this._virtualizedListPairs = [];
this._captureRef = ref => {
this._listRef = ref;
};
this._getItem = (data, index) => {
var numColumns = numColumnsOrDefault(this.props.numColumns);
if (numColumns > 1) {
var ret = [];
for (var kk = 0; kk < numColumns; kk++) {
var itemIndex = index * numColumns + kk;
if (itemIndex < data.length) {
var _item = data[itemIndex];
ret.push(_item);
}
}
return ret;
} else {
return data[index];
}
};
this._getItemCount = data => {
// Legacy behavior of FlatList was to forward "undefined" length if invalid
// data like a non-arraylike object is passed. VirtualizedList would then
// coerce this, and the math would work out to no-op. For compatibility, if
// invalid data is passed, we tell VirtualizedList there are zero items
// available to prevent it from trying to read from the invalid data
// (without propagating invalidly typed data).
if (data != null && isArrayLike(data)) {
var numColumns = numColumnsOrDefault(this.props.numColumns);
return numColumns > 1 ? Math.ceil(data.length / numColumns) : data.length;
} else {
return 0;
}
};
this._keyExtractor = (items, index) => {
var _this$props$keyExtrac;
var numColumns = numColumnsOrDefault(this.props.numColumns);
var keyExtractor = (_this$props$keyExtrac = this.props.keyExtractor) !== null && _this$props$keyExtrac !== void 0 ? _this$props$keyExtrac : _VirtualizeUtils.keyExtractor;
if (numColumns > 1) {
(0, _invariant.default)(Array.isArray(items), 'FlatList: Encountered internal consistency error, expected each item to consist of an ' + 'array with 1-%s columns; instead, received a single item.', numColumns);
return items.map((item, kk) => keyExtractor(item, index * numColumns + kk)).join(':');
}
// $FlowFixMe[incompatible-call] Can't call keyExtractor with an array
return keyExtractor(items, index);
};
this._renderer = (ListItemComponent, renderItem, columnWrapperStyle, numColumns, extraData
// $FlowFixMe[missing-local-annot]
) => {
var cols = numColumnsOrDefault(numColumns);
var render = props => {
if (ListItemComponent) {
// $FlowFixMe[not-a-component] Component isn't valid
// $FlowFixMe[incompatible-type-arg] Component isn't valid
// $FlowFixMe[incompatible-return] Component isn't valid
return /*#__PURE__*/React.createElement(ListItemComponent, props);
} else if (renderItem) {
// $FlowFixMe[incompatible-call]
return renderItem(props);
} else {
return null;
}
};
var renderProp = info => {
if (cols > 1) {
var _item2 = info.item,
_index = info.index;
(0, _invariant.default)(Array.isArray(_item2), 'Expected array of items with numColumns > 1');
return /*#__PURE__*/React.createElement(_View.default, {
style: [styles.row, columnWrapperStyle]
}, _item2.map((it, kk) => {
var element = render({
// $FlowFixMe[incompatible-call]
item: it,
index: _index * cols + kk,
separators: info.separators
});
return element != null ? /*#__PURE__*/React.createElement(React.Fragment, {
key: kk
}, element) : null;
}));
} else {
return render(info);
}
};
return ListItemComponent ? {
ListItemComponent: renderProp
} : {
renderItem: renderProp
};
};
this._memoizedRenderer = (0, _memoizeOne.default)(this._renderer);
this._checkProps(this.props);
if (this.props.viewabilityConfigCallbackPairs) {
this._virtualizedListPairs = this.props.viewabilityConfigCallbackPairs.map(pair => ({
viewabilityConfig: pair.viewabilityConfig,
onViewableItemsChanged: this._createOnViewableItemsChanged(pair.onViewableItemsChanged)
}));
} else if (this.props.onViewableItemsChanged) {
this._virtualizedListPairs.push({
/* $FlowFixMe[incompatible-call] (>=0.63.0 site=react_native_fb) This
* comment suppresses an error found when Flow v0.63 was deployed. To
* see the error delete this comment and run Flow. */
viewabilityConfig: this.props.viewabilityConfig,
onViewableItemsChanged: this._createOnViewableItemsChanged(this.props.onViewableItemsChanged)
});
}
}
// $FlowFixMe[missing-local-annot]
componentDidUpdate(prevProps) {
(0, _invariant.default)(prevProps.numColumns === this.props.numColumns, 'Changing numColumns on the fly is not supported. Change the key prop on FlatList when ' + 'changing the number of columns to force a fresh render of the component.');
(0, _invariant.default)(prevProps.onViewableItemsChanged === this.props.onViewableItemsChanged, 'Changing onViewableItemsChanged on the fly is not supported');
(0, _invariant.default)(!(0, _deepDiffer.default)(prevProps.viewabilityConfig, this.props.viewabilityConfig), 'Changing viewabilityConfig on the fly is not supported');
(0, _invariant.default)(prevProps.viewabilityConfigCallbackPairs === this.props.viewabilityConfigCallbackPairs, 'Changing viewabilityConfigCallbackPairs on the fly is not supported');
this._checkProps(this.props);
}
// $FlowFixMe[missing-local-annot]
_checkProps(props) {
var getItem = props.getItem,
getItemCount = props.getItemCount,
horizontal = props.horizontal,
columnWrapperStyle = props.columnWrapperStyle,
onViewableItemsChanged = props.onViewableItemsChanged,
viewabilityConfigCallbackPairs = props.viewabilityConfigCallbackPairs;
var numColumns = numColumnsOrDefault(this.props.numColumns);
(0, _invariant.default)(!getItem && !getItemCount, 'FlatList does not support custom data formats.');
if (numColumns > 1) {
(0, _invariant.default)(!horizontal, 'numColumns does not support horizontal.');
} else {
(0, _invariant.default)(!columnWrapperStyle, 'columnWrapperStyle not supported for single column lists');
}
(0, _invariant.default)(!(onViewableItemsChanged && viewabilityConfigCallbackPairs), 'FlatList does not support setting both onViewableItemsChanged and ' + 'viewabilityConfigCallbackPairs.');
}
_pushMultiColumnViewable(arr, v) {
var _this$props$keyExtrac2;
var numColumns = numColumnsOrDefault(this.props.numColumns);
var keyExtractor = (_this$props$keyExtrac2 = this.props.keyExtractor) !== null && _this$props$keyExtrac2 !== void 0 ? _this$props$keyExtrac2 : _VirtualizeUtils.keyExtractor;
v.item.forEach((item, ii) => {
(0, _invariant.default)(v.index != null, 'Missing index!');
var index = v.index * numColumns + ii;
arr.push((0, _objectSpread2.default)((0, _objectSpread2.default)({}, v), {}, {
item,
key: keyExtractor(item, index),
index
}));
});
}
_createOnViewableItemsChanged(onViewableItemsChanged
// $FlowFixMe[missing-local-annot]
) {
return info => {
var numColumns = numColumnsOrDefault(this.props.numColumns);
if (onViewableItemsChanged) {
if (numColumns > 1) {
var changed = [];
var viewableItems = [];
info.viewableItems.forEach(v => this._pushMultiColumnViewable(viewableItems, v));
info.changed.forEach(v => this._pushMultiColumnViewable(changed, v));
onViewableItemsChanged({
viewableItems,
changed
});
} else {
onViewableItemsChanged(info);
}
}
};
}
render() {
var _this$props = this.props,
numColumns = _this$props.numColumns,
columnWrapperStyle = _this$props.columnWrapperStyle,
_removeClippedSubviews = _this$props.removeClippedSubviews,
_this$props$strictMod = _this$props.strictMode,
strictMode = _this$props$strictMod === void 0 ? false : _this$props$strictMod,
restProps = (0, _objectWithoutPropertiesLoose2.default)(_this$props, _excluded);
var renderer = strictMode ? this._memoizedRenderer : this._renderer;
return (
/*#__PURE__*/
// $FlowFixMe[incompatible-exact] - `restProps` (`Props`) is inexact.
React.createElement(_VirtualizedList.default, (0, _extends2.default)({}, restProps, {
getItem: this._getItem,
getItemCount: this._getItemCount,
keyExtractor: this._keyExtractor,
ref: this._captureRef,
viewabilityConfigCallbackPairs: this._virtualizedListPairs,
removeClippedSubviews: removeClippedSubviewsOrDefault(_removeClippedSubviews)
}, renderer(this.props.ListItemComponent, this.props.renderItem, columnWrapperStyle, numColumns, this.props.extraData)))
);
}
}
var styles = _StyleSheet.default.create({
row: {
flexDirection: 'row'
}
});
var _default = FlatList;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/LayoutAnimation/index.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _Platform = _interopRequireDefault(require("../../../exports/Platform"));
var _UIManager = _interopRequireDefault(require("../../../exports/UIManager"));
var __DEV__ = process.env.NODE_ENV !== 'production';
function configureNext(config, onAnimationDidEnd) {
if (!_Platform.default.isTesting) {
_UIManager.default.configureNextLayoutAnimation(config, onAnimationDidEnd !== null && onAnimationDidEnd !== void 0 ? onAnimationDidEnd : function () {}, function () {} /* unused onError */);
}
}
function create(duration, type, property) {
return {
duration,
create: {
type,
property
},
update: {
type
},
delete: {
type,
property
}
};
}
var Presets = {
easeInEaseOut: create(300, 'easeInEaseOut', 'opacity'),
linear: create(500, 'linear', 'opacity'),
spring: {
duration: 700,
create: {
type: 'linear',
property: 'opacity'
},
update: {
type: 'spring',
springDamping: 0.4
},
delete: {
type: 'linear',
property: 'opacity'
}
}
};
/**
* Automatically animates views to their new positions when the
* next layout happens.
*
* A common way to use this API is to call it before calling `setState`.
*
* Note that in order to get this to work on **Android** you need to set the following flags via `UIManager`:
*
* UIManager.setLayoutAnimationEnabledExperimental && UIManager.setLayoutAnimationEnabledExperimental(true);
*/
var LayoutAnimation = {
/**
* Schedules an animation to happen on the next layout.
*
* @param config Specifies animation properties:
*
* - `duration` in milliseconds
* - `create`, `AnimationConfig` for animating in new views
* - `update`, `AnimationConfig` for animating views that have been updated
*
* @param onAnimationDidEnd Called when the animation finished.
* Only supported on iOS.
* @param onError Called on error. Only supported on iOS.
*/
configureNext,
/**
* Helper for creating a config for `configureNext`.
*/
create,
Types: Object.freeze({
spring: 'spring',
linear: 'linear',
easeInEaseOut: 'easeInEaseOut',
easeIn: 'easeIn',
easeOut: 'easeOut',
keyboard: 'keyboard'
}),
Properties: Object.freeze({
opacity: 'opacity',
scaleX: 'scaleX',
scaleY: 'scaleY',
scaleXY: 'scaleXY'
}),
checkConfig() {
console.error('LayoutAnimation.checkConfig(...) has been disabled.');
},
Presets,
easeInEaseOut: configureNext.bind(null, Presets.easeInEaseOut),
linear: configureNext.bind(null, Presets.linear),
spring: configureNext.bind(null, Presets.spring)
};
var _default = LayoutAnimation;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/PanResponder/index.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _InteractionManager = _interopRequireDefault(require("../../../exports/InteractionManager"));
var _TouchHistoryMath = _interopRequireDefault(require("../TouchHistoryMath"));
var currentCentroidXOfTouchesChangedAfter = _TouchHistoryMath.default.currentCentroidXOfTouchesChangedAfter;
var currentCentroidYOfTouchesChangedAfter = _TouchHistoryMath.default.currentCentroidYOfTouchesChangedAfter;
var previousCentroidXOfTouchesChangedAfter = _TouchHistoryMath.default.previousCentroidXOfTouchesChangedAfter;
var previousCentroidYOfTouchesChangedAfter = _TouchHistoryMath.default.previousCentroidYOfTouchesChangedAfter;
var currentCentroidX = _TouchHistoryMath.default.currentCentroidX;
var currentCentroidY = _TouchHistoryMath.default.currentCentroidY;
/**
* `PanResponder` reconciles several touches into a single gesture. It makes
* single-touch gestures resilient to extra touches, and can be used to
* recognize simple multi-touch gestures.
*
* By default, `PanResponder` holds an `InteractionManager` handle to block
* long-running JS events from interrupting active gestures.
*
* It provides a predictable wrapper of the responder handlers provided by the
* [gesture responder system](docs/gesture-responder-system.html).
* For each handler, it provides a new `gestureState` object alongside the
* native event object:
*
* ```
* onPanResponderMove: (event, gestureState) => {}
* ```
*
* A native event is a synthetic touch event with the following form:
*
* - `nativeEvent`
* + `changedTouches` - Array of all touch events that have changed since the last event
* + `identifier` - The ID of the touch
* + `locationX` - The X position of the touch, relative to the element
* + `locationY` - The Y position of the touch, relative to the element
* + `pageX` - The X position of the touch, relative to the root element
* + `pageY` - The Y position of the touch, relative to the root element
* + `target` - The node id of the element receiving the touch event
* + `timestamp` - A time identifier for the touch, useful for velocity calculation
* + `touches` - Array of all current touches on the screen
*
* A `gestureState` object has the following:
*
* - `stateID` - ID of the gestureState- persisted as long as there at least
* one touch on screen
* - `moveX` - the latest screen coordinates of the recently-moved touch
* - `moveY` - the latest screen coordinates of the recently-moved touch
* - `x0` - the screen coordinates of the responder grant
* - `y0` - the screen coordinates of the responder grant
* - `dx` - accumulated distance of the gesture since the touch started
* - `dy` - accumulated distance of the gesture since the touch started
* - `vx` - current velocity of the gesture
* - `vy` - current velocity of the gesture
* - `numberActiveTouches` - Number of touches currently on screen
*
* ### Basic Usage
*
* ```
* componentWillMount: function() {
* this._panResponder = PanResponder.create({
* // Ask to be the responder:
* onStartShouldSetPanResponder: (evt, gestureState) => true,
* onStartShouldSetPanResponderCapture: (evt, gestureState) => true,
* onMoveShouldSetPanResponder: (evt, gestureState) => true,
* onMoveShouldSetPanResponderCapture: (evt, gestureState) => true,
*
* onPanResponderGrant: (evt, gestureState) => {
* // The gesture has started. Show visual feedback so the user knows
* // what is happening!
*
* // gestureState.d{x,y} will be set to zero now
* },
* onPanResponderMove: (evt, gestureState) => {
* // The most recent move distance is gestureState.move{X,Y}
*
* // The accumulated gesture distance since becoming responder is
* // gestureState.d{x,y}
* },
* onPanResponderTerminationRequest: (evt, gestureState) => true,
* onPanResponderRelease: (evt, gestureState) => {
* // The user has released all touches while this view is the
* // responder. This typically means a gesture has succeeded
* },
* onPanResponderTerminate: (evt, gestureState) => {
* // Another component has become the responder, so this gesture
* // should be cancelled
* },
* onShouldBlockNativeResponder: (evt, gestureState) => {
* // Returns whether this component should block native components from becoming the JS
* // responder. Returns true by default. Is currently only supported on android.
* return true;
* },
* });
* },
*
* render: function() {
* return (
* <View {...this._panResponder.panHandlers} />
* );
* },
*
* ```
*
* ### Working Example
*
* To see it in action, try the
* [PanResponder example in RNTester](https://github.com/facebook/react-native/blob/master/RNTester/js/PanResponderExample.js)
*/
var PanResponder = {
/**
*
* A graphical explanation of the touch data flow:
*
* +----------------------------+ +--------------------------------+
* | ResponderTouchHistoryStore | |TouchHistoryMath |
* +----------------------------+ +----------+---------------------+
* |Global store of touchHistory| |Allocation-less math util |
* |including activeness, start | |on touch history (centroids |
* |position, prev/cur position.| |and multitouch movement etc) |
* | | | |
* +----^-----------------------+ +----^---------------------------+
* | |
* | (records relevant history |
* | of touches relevant for |
* | implementing higher level |
* | gestures) |
* | |
* +----+-----------------------+ +----|---------------------------+
* | ResponderEventPlugin | | | Your App/Component |
* +----------------------------+ +----|---------------------------+
* |Negotiates which view gets | Low level | | High level |
* |onResponderMove events. | events w/ | +-+-------+ events w/ |
* |Also records history into | touchHistory| | Pan | multitouch + |
* |ResponderTouchHistoryStore. +---------------->Responder+-----> accumulative|
* +----------------------------+ attached to | | | distance and |
* each event | +---------+ velocity. |
* | |
* | |
* +--------------------------------+
*
*
*
* Gesture that calculates cumulative movement over time in a way that just
* "does the right thing" for multiple touches. The "right thing" is very
* nuanced. When moving two touches in opposite directions, the cumulative
* distance is zero in each dimension. When two touches move in parallel five
* pixels in the same direction, the cumulative distance is five, not ten. If
* two touches start, one moves five in a direction, then stops and the other
* touch moves fives in the same direction, the cumulative distance is ten.
*
* This logic requires a kind of processing of time "clusters" of touch events
* so that two touch moves that essentially occur in parallel but move every
* other frame respectively, are considered part of the same movement.
*
* Explanation of some of the non-obvious fields:
*
* - moveX/moveY: If no move event has been observed, then `(moveX, moveY)` is
* invalid. If a move event has been observed, `(moveX, moveY)` is the
* centroid of the most recently moved "cluster" of active touches.
* (Currently all move have the same timeStamp, but later we should add some
* threshold for what is considered to be "moving"). If a palm is
* accidentally counted as a touch, but a finger is moving greatly, the palm
* will move slightly, but we only want to count the single moving touch.
* - x0/y0: Centroid location (non-cumulative) at the time of becoming
* responder.
* - dx/dy: Cumulative touch distance - not the same thing as sum of each touch
* distance. Accounts for touch moves that are clustered together in time,
* moving the same direction. Only valid when currently responder (otherwise,
* it only represents the drag distance below the threshold).
* - vx/vy: Velocity.
*/
_initializeGestureState(gestureState) {
gestureState.moveX = 0;
gestureState.moveY = 0;
gestureState.x0 = 0;
gestureState.y0 = 0;
gestureState.dx = 0;
gestureState.dy = 0;
gestureState.vx = 0;
gestureState.vy = 0;
gestureState.numberActiveTouches = 0;
// All `gestureState` accounts for timeStamps up until:
gestureState._accountsForMovesUpTo = 0;
},
/**
* This is nuanced and is necessary. It is incorrect to continuously take all
* active *and* recently moved touches, find the centroid, and track how that
* result changes over time. Instead, we must take all recently moved
* touches, and calculate how the centroid has changed just for those
* recently moved touches, and append that change to an accumulator. This is
* to (at least) handle the case where the user is moving three fingers, and
* then one of the fingers stops but the other two continue.
*
* This is very different than taking all of the recently moved touches and
* storing their centroid as `dx/dy`. For correctness, we must *accumulate
* changes* in the centroid of recently moved touches.
*
* There is also some nuance with how we handle multiple moved touches in a
* single event. With the way `ReactNativeEventEmitter` dispatches touches as
* individual events, multiple touches generate two 'move' events, each of
* them triggering `onResponderMove`. But with the way `PanResponder` works,
* all of the gesture inference is performed on the first dispatch, since it
* looks at all of the touches (even the ones for which there hasn't been a
* native dispatch yet). Therefore, `PanResponder` does not call
* `onResponderMove` passed the first dispatch. This diverges from the
* typical responder callback pattern (without using `PanResponder`), but
* avoids more dispatches than necessary.
*/
_updateGestureStateOnMove(gestureState, touchHistory) {
gestureState.numberActiveTouches = touchHistory.numberActiveTouches;
gestureState.moveX = currentCentroidXOfTouchesChangedAfter(touchHistory, gestureState._accountsForMovesUpTo);
gestureState.moveY = currentCentroidYOfTouchesChangedAfter(touchHistory, gestureState._accountsForMovesUpTo);
var movedAfter = gestureState._accountsForMovesUpTo;
var prevX = previousCentroidXOfTouchesChangedAfter(touchHistory, movedAfter);
var x = currentCentroidXOfTouchesChangedAfter(touchHistory, movedAfter);
var prevY = previousCentroidYOfTouchesChangedAfter(touchHistory, movedAfter);
var y = currentCentroidYOfTouchesChangedAfter(touchHistory, movedAfter);
var nextDX = gestureState.dx + (x - prevX);
var nextDY = gestureState.dy + (y - prevY);
// TODO: This must be filtered intelligently.
var dt = touchHistory.mostRecentTimeStamp - gestureState._accountsForMovesUpTo;
gestureState.vx = (nextDX - gestureState.dx) / dt;
gestureState.vy = (nextDY - gestureState.dy) / dt;
gestureState.dx = nextDX;
gestureState.dy = nextDY;
gestureState._accountsForMovesUpTo = touchHistory.mostRecentTimeStamp;
},
/**
* @param {object} config Enhanced versions of all of the responder callbacks
* that provide not only the typical `ResponderSyntheticEvent`, but also the
* `PanResponder` gesture state. Simply replace the word `Responder` with
* `PanResponder` in each of the typical `onResponder*` callbacks. For
* example, the `config` object would look like:
*
* - `onMoveShouldSetPanResponder: (e, gestureState) => {...}`
* - `onMoveShouldSetPanResponderCapture: (e, gestureState) => {...}`
* - `onStartShouldSetPanResponder: (e, gestureState) => {...}`
* - `onStartShouldSetPanResponderCapture: (e, gestureState) => {...}`
* - `onPanResponderReject: (e, gestureState) => {...}`
* - `onPanResponderGrant: (e, gestureState) => {...}`
* - `onPanResponderStart: (e, gestureState) => {...}`
* - `onPanResponderEnd: (e, gestureState) => {...}`
* - `onPanResponderRelease: (e, gestureState) => {...}`
* - `onPanResponderMove: (e, gestureState) => {...}`
* - `onPanResponderTerminate: (e, gestureState) => {...}`
* - `onPanResponderTerminationRequest: (e, gestureState) => {...}`
* - `onShouldBlockNativeResponder: (e, gestureState) => {...}`
*
* In general, for events that have capture equivalents, we update the
* gestureState once in the capture phase and can use it in the bubble phase
* as well.
*
* Be careful with onStartShould* callbacks. They only reflect updated
* `gestureState` for start/end events that bubble/capture to the Node.
* Once the node is the responder, you can rely on every start/end event
* being processed by the gesture and `gestureState` being updated
* accordingly. (numberActiveTouches) may not be totally accurate unless you
* are the responder.
*/
create(config) {
var interactionState = {
handle: null,
shouldCancelClick: false,
timeout: null
};
var gestureState = {
// Useful for debugging
stateID: Math.random(),
moveX: 0,
moveY: 0,
x0: 0,
y0: 0,
dx: 0,
dy: 0,
vx: 0,
vy: 0,
numberActiveTouches: 0,
_accountsForMovesUpTo: 0
};
var panHandlers = {
onStartShouldSetResponder(event) {
return config.onStartShouldSetPanResponder == null ? false : config.onStartShouldSetPanResponder(event, gestureState);
},
onMoveShouldSetResponder(event) {
return config.onMoveShouldSetPanResponder == null ? false : config.onMoveShouldSetPanResponder(event, gestureState);
},
onStartShouldSetResponderCapture(event) {
// TODO: Actually, we should reinitialize the state any time
// touches.length increases from 0 active to > 0 active.
if (event.nativeEvent.touches.length === 1) {
PanResponder._initializeGestureState(gestureState);
}
gestureState.numberActiveTouches = event.touchHistory.numberActiveTouches;
return config.onStartShouldSetPanResponderCapture != null ? config.onStartShouldSetPanResponderCapture(event, gestureState) : false;
},
onMoveShouldSetResponderCapture(event) {
var touchHistory = event.touchHistory;
// Responder system incorrectly dispatches should* to current responder
// Filter out any touch moves past the first one - we would have
// already processed multi-touch geometry during the first event.
if (gestureState._accountsForMovesUpTo === touchHistory.mostRecentTimeStamp) {
return false;
}
PanResponder._updateGestureStateOnMove(gestureState, touchHistory);
return config.onMoveShouldSetPanResponderCapture ? config.onMoveShouldSetPanResponderCapture(event, gestureState) : false;
},
onResponderGrant(event) {
if (!interactionState.handle) {
interactionState.handle = _InteractionManager.default.createInteractionHandle();
}
if (interactionState.timeout) {
clearInteractionTimeout(interactionState);
}
interactionState.shouldCancelClick = true;
gestureState.x0 = currentCentroidX(event.touchHistory);
gestureState.y0 = currentCentroidY(event.touchHistory);
gestureState.dx = 0;
gestureState.dy = 0;
if (config.onPanResponderGrant) {
config.onPanResponderGrant(event, gestureState);
}
// TODO: t7467124 investigate if this can be removed
return config.onShouldBlockNativeResponder == null ? true : config.onShouldBlockNativeResponder(event, gestureState);
},
onResponderReject(event) {
clearInteractionHandle(interactionState, config.onPanResponderReject, event, gestureState);
},
onResponderRelease(event) {
clearInteractionHandle(interactionState, config.onPanResponderRelease, event, gestureState);
setInteractionTimeout(interactionState);
PanResponder._initializeGestureState(gestureState);
},
onResponderStart(event) {
var touchHistory = event.touchHistory;
gestureState.numberActiveTouches = touchHistory.numberActiveTouches;
if (config.onPanResponderStart) {
config.onPanResponderStart(event, gestureState);
}
},
onResponderMove(event) {
var touchHistory = event.touchHistory;
// Guard against the dispatch of two touch moves when there are two
// simultaneously changed touches.
if (gestureState._accountsForMovesUpTo === touchHistory.mostRecentTimeStamp) {
return;
}
// Filter out any touch moves past the first one - we would have
// already processed multi-touch geometry during the first event.
PanResponder._updateGestureStateOnMove(gestureState, touchHistory);
if (config.onPanResponderMove) {
config.onPanResponderMove(event, gestureState);
}
},
onResponderEnd(event) {
var touchHistory = event.touchHistory;
gestureState.numberActiveTouches = touchHistory.numberActiveTouches;
clearInteractionHandle(interactionState, config.onPanResponderEnd, event, gestureState);
},
onResponderTerminate(event) {
clearInteractionHandle(interactionState, config.onPanResponderTerminate, event, gestureState);
setInteractionTimeout(interactionState);
PanResponder._initializeGestureState(gestureState);
},
onResponderTerminationRequest(event) {
return config.onPanResponderTerminationRequest == null ? true : config.onPanResponderTerminationRequest(event, gestureState);
},
// We do not want to trigger 'click' activated gestures or native behaviors
// on any pan target that is under a mouse cursor when it is released.
// Browsers will natively cancel 'click' events on a target if a non-mouse
// active pointer moves.
onClickCapture: event => {
if (interactionState.shouldCancelClick === true) {
event.stopPropagation();
event.preventDefault();
}
}
};
return {
panHandlers,
getInteractionHandle() {
return interactionState.handle;
}
};
}
};
function clearInteractionHandle(interactionState, callback, event, gestureState) {
if (interactionState.handle) {
_InteractionManager.default.clearInteractionHandle(interactionState.handle);
interactionState.handle = null;
}
if (callback) {
callback(event, gestureState);
}
}
function clearInteractionTimeout(interactionState) {
clearTimeout(interactionState.timeout);
}
function setInteractionTimeout(interactionState) {
interactionState.timeout = setTimeout(() => {
interactionState.shouldCancelClick = false;
}, 250);
}
var _default = PanResponder;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/PooledClass/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
/* eslint-disable */
/**
* 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.
*
* From React 16.0.0
*/
var twoArgumentPooler = function twoArgumentPooler(a1, a2) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2);
return instance;
} else {
return new Klass(a1, a2);
}
};
var standardReleaser = function standardReleaser(instance) {
var Klass = this;
instance.destructor();
if (Klass.instancePool.length < Klass.poolSize) {
Klass.instancePool.push(instance);
}
};
var DEFAULT_POOL_SIZE = 10;
var DEFAULT_POOLER = twoArgumentPooler;
/**
* Augments `CopyConstructor` to be a poolable class, augmenting only the class
* itself (statically) not adding any prototypical fields. Any CopyConstructor
* you give this may have a `poolSize` property, and will look for a
* prototypical `destructor` on instances.
*
* @param {Function} CopyConstructor Constructor that can be used to reset.
* @param {Function} pooler Customizable pooler.
*/
var addPoolingTo = function addPoolingTo(CopyConstructor, pooler) {
// Casting as any so that flow ignores the actual implementation and trusts
// it to match the type we declared
var NewKlass = CopyConstructor;
NewKlass.instancePool = [];
NewKlass.getPooled = pooler || DEFAULT_POOLER;
if (!NewKlass.poolSize) {
NewKlass.poolSize = DEFAULT_POOL_SIZE;
}
NewKlass.release = standardReleaser;
return NewKlass;
};
var PooledClass = {
addPoolingTo: addPoolingTo,
twoArgumentPooler: twoArgumentPooler
};
var _default = PooledClass;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/ReactNative/ReactNativeFeatureFlags.js
/**
* 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.
*
*
* @format
*/
'use strict';
exports.__esModule = true;
exports.default = void 0;
var ReactNativeFeatureFlags = {
isLayoutAnimationEnabled: () => true,
shouldEmitW3CPointerEvents: () => false,
shouldPressibilityUseW3CPointerEventsForHover: () => false,
animatedShouldDebounceQueueFlush: () => false,
animatedShouldUseSingleOp: () => false
};
var _default = ReactNativeFeatureFlags;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/SectionList/index.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var _Platform = _interopRequireDefault(require("../../../exports/Platform"));
var React = _interopRequireWildcard(require("react"));
var _VirtualizedSectionList = _interopRequireDefault(require("../VirtualizedSectionList"));
var _excluded = ["stickySectionHeadersEnabled"];
/**
* A performant interface for rendering sectioned lists, supporting the most handy features:
*
* - Fully cross-platform.
* - Configurable viewability callbacks.
* - List header support.
* - List footer support.
* - Item separator support.
* - Section header support.
* - Section separator support.
* - Heterogeneous data and item rendering support.
* - Pull to Refresh.
* - Scroll loading.
*
* If you don't need section support and want a simpler interface, use
* [`<FlatList>`](https://reactnative.dev/docs/flatlist).
*
* Simple Examples:
*
* <SectionList
* renderItem={({item}) => <ListItem title={item} />}
* renderSectionHeader={({section}) => <Header title={section.title} />}
* sections={[ // homogeneous rendering between sections
* {data: [...], title: ...},
* {data: [...], title: ...},
* {data: [...], title: ...},
* ]}
* />
*
* <SectionList
* sections={[ // heterogeneous rendering between sections
* {data: [...], renderItem: ...},
* {data: [...], renderItem: ...},
* {data: [...], renderItem: ...},
* ]}
* />
*
* This is a convenience wrapper around [`<VirtualizedList>`](docs/virtualizedlist),
* and thus inherits its props (as well as those of `ScrollView`) that aren't explicitly listed
* here, along with the following caveats:
*
* - Internal state is not preserved when content scrolls out of the render window. Make sure all
* your data is captured in the item data or external stores like Flux, Redux, or Relay.
* - This is a `PureComponent` which means that it will not re-render if `props` remain shallow-
* equal. Make sure that everything your `renderItem` function depends on is passed as a prop
* (e.g. `extraData`) that is not `===` after updates, otherwise your UI may not update on
* changes. This includes the `data` prop and parent component state.
* - In order to constrain memory and enable smooth scrolling, content is rendered asynchronously
* offscreen. This means it's possible to scroll faster than the fill rate and momentarily see
* blank content. This is a tradeoff that can be adjusted to suit the needs of each application,
* and we are working on improving it behind the scenes.
* - By default, the list looks for a `key` prop on each item and uses that for the React key.
* Alternatively, you can provide a custom `keyExtractor` prop.
*
*/
class SectionList extends React.PureComponent {
constructor() {
super(...arguments);
this._captureRef = ref => {
this._wrapperListRef = ref;
};
}
/**
* Scrolls to the item at the specified `sectionIndex` and `itemIndex` (within the section)
* positioned in the viewable area such that `viewPosition` 0 places it at the top (and may be
* covered by a sticky header), 1 at the bottom, and 0.5 centered in the middle. `viewOffset` is a
* fixed number of pixels to offset the final target position, e.g. to compensate for sticky
* headers.
*
* Note: cannot scroll to locations outside the render window without specifying the
* `getItemLayout` prop.
*/
scrollToLocation(params) {
if (this._wrapperListRef != null) {
this._wrapperListRef.scrollToLocation(params);
}
}
/**
* Tells the list an interaction has occurred, which should trigger viewability calculations, e.g.
* if `waitForInteractions` is true and the user has not scrolled. This is typically called by
* taps on items or by navigation actions.
*/
recordInteraction() {
var listRef = this._wrapperListRef && this._wrapperListRef.getListRef();
listRef && listRef.recordInteraction();
}
/**
* Displays the scroll indicators momentarily.
*
* @platform ios
*/
flashScrollIndicators() {
var listRef = this._wrapperListRef && this._wrapperListRef.getListRef();
listRef && listRef.flashScrollIndicators();
}
/**
* Provides a handle to the underlying scroll responder.
*/
getScrollResponder() {
var listRef = this._wrapperListRef && this._wrapperListRef.getListRef();
if (listRef) {
return listRef.getScrollResponder();
}
}
getScrollableNode() {
var listRef = this._wrapperListRef && this._wrapperListRef.getListRef();
if (listRef) {
return listRef.getScrollableNode();
}
}
render() {
var _this$props = this.props,
_stickySectionHeadersEnabled = _this$props.stickySectionHeadersEnabled,
restProps = (0, _objectWithoutPropertiesLoose2.default)(_this$props, _excluded);
var stickySectionHeadersEnabled = _stickySectionHeadersEnabled !== null && _stickySectionHeadersEnabled !== void 0 ? _stickySectionHeadersEnabled : _Platform.default.OS === 'ios';
return /*#__PURE__*/React.createElement(_VirtualizedSectionList.default, (0, _extends2.default)({}, restProps, {
stickySectionHeadersEnabled: stickySectionHeadersEnabled,
ref: this._captureRef,
getItemCount: items => items.length,
getItem: (items, index) => items[index]
}));
}
}
exports.default = SectionList;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/TouchHistoryMath/index.js
"use strict";
exports.__esModule = true;
exports.default = void 0;
/**
* 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.
*
* @format
*/
var TouchHistoryMath = {
/**
* This code is optimized and not intended to look beautiful. This allows
* computing of touch centroids that have moved after `touchesChangedAfter`
* timeStamp. You can compute the current centroid involving all touches
* moves after `touchesChangedAfter`, or you can compute the previous
* centroid of all touches that were moved after `touchesChangedAfter`.
*
* @param {TouchHistoryMath} touchHistory Standard Responder touch track
* data.
* @param {number} touchesChangedAfter timeStamp after which moved touches
* are considered "actively moving" - not just "active".
* @param {boolean} isXAxis Consider `x` dimension vs. `y` dimension.
* @param {boolean} ofCurrent Compute current centroid for actively moving
* touches vs. previous centroid of now actively moving touches.
* @return {number} value of centroid in specified dimension.
*/
centroidDimension: function centroidDimension(touchHistory, touchesChangedAfter, isXAxis, ofCurrent) {
var touchBank = touchHistory.touchBank;
var total = 0;
var count = 0;
var oneTouchData = touchHistory.numberActiveTouches === 1 ? touchHistory.touchBank[touchHistory.indexOfSingleActiveTouch] : null;
if (oneTouchData !== null) {
if (oneTouchData.touchActive && oneTouchData.currentTimeStamp > touchesChangedAfter) {
total += ofCurrent && isXAxis ? oneTouchData.currentPageX : ofCurrent && !isXAxis ? oneTouchData.currentPageY : !ofCurrent && isXAxis ? oneTouchData.previousPageX : oneTouchData.previousPageY;
count = 1;
}
} else {
for (var i = 0; i < touchBank.length; i++) {
var touchTrack = touchBank[i];
if (touchTrack !== null && touchTrack !== undefined && touchTrack.touchActive && touchTrack.currentTimeStamp >= touchesChangedAfter) {
var toAdd = void 0; // Yuck, program temporarily in invalid state.
if (ofCurrent && isXAxis) {
toAdd = touchTrack.currentPageX;
} else if (ofCurrent && !isXAxis) {
toAdd = touchTrack.currentPageY;
} else if (!ofCurrent && isXAxis) {
toAdd = touchTrack.previousPageX;
} else {
toAdd = touchTrack.previousPageY;
}
total += toAdd;
count++;
}
}
}
return count > 0 ? total / count : TouchHistoryMath.noCentroid;
},
currentCentroidXOfTouchesChangedAfter: function currentCentroidXOfTouchesChangedAfter(touchHistory, touchesChangedAfter) {
return TouchHistoryMath.centroidDimension(touchHistory, touchesChangedAfter, true,
// isXAxis
true // ofCurrent
);
},
currentCentroidYOfTouchesChangedAfter: function currentCentroidYOfTouchesChangedAfter(touchHistory, touchesChangedAfter) {
return TouchHistoryMath.centroidDimension(touchHistory, touchesChangedAfter, false,
// isXAxis
true // ofCurrent
);
},
previousCentroidXOfTouchesChangedAfter: function previousCentroidXOfTouchesChangedAfter(touchHistory, touchesChangedAfter) {
return TouchHistoryMath.centroidDimension(touchHistory, touchesChangedAfter, true,
// isXAxis
false // ofCurrent
);
},
previousCentroidYOfTouchesChangedAfter: function previousCentroidYOfTouchesChangedAfter(touchHistory, touchesChangedAfter) {
return TouchHistoryMath.centroidDimension(touchHistory, touchesChangedAfter, false,
// isXAxis
false // ofCurrent
);
},
currentCentroidX: function currentCentroidX(touchHistory) {
return TouchHistoryMath.centroidDimension(touchHistory, 0,
// touchesChangedAfter
true,
// isXAxis
true // ofCurrent
);
},
currentCentroidY: function currentCentroidY(touchHistory) {
return TouchHistoryMath.centroidDimension(touchHistory, 0,
// touchesChangedAfter
false,
// isXAxis
true // ofCurrent
);
},
noCentroid: -1
};
var _default = TouchHistoryMath;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/TurboModule/TurboModuleRegistry.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.get = get;
exports.getEnforcing = getEnforcing;
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
function get(name) {
return null;
}
function getEnforcing(name) {
var module = get(name);
(0, _invariant.default)(module != null, "TurboModuleRegistry.getEnforcing(...): '" + name + "' could not be found. " + 'Verify that a module by this name is registered in the native binary.');
return module;
}
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Utilities/Platform.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _Platform = _interopRequireDefault(require("../../../exports/Platform"));
var _default = _Platform.default;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Utilities/clamp.js
/**
* 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.
*
* @format
*
*/
'use strict';
function clamp(min, value, max) {
if (value < min) {
return min;
}
if (value > max) {
return max;
}
return value;
}
module.exports = clamp;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Utilities/useMergeRefs.js
"use strict";
exports.__esModule = true;
exports.default = useMergeRefs;
var _react = require("react");
/**
* 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.
*
*
* @format
*/
/**
* Constructs a new ref that forwards new values to each of the given refs. The
* given refs will always be invoked in the order that they are supplied.
*
* WARNING: A known problem of merging refs using this approach is that if any
* of the given refs change, the returned callback ref will also be changed. If
* the returned callback ref is supplied as a `ref` to a React element, this may
* lead to problems with the given refs being invoked more times than desired.
*/
function useMergeRefs() {
for (var _len = arguments.length, refs = new Array(_len), _key = 0; _key < _len; _key++) {
refs[_key] = arguments[_key];
}
return (0, _react.useCallback)(current => {
for (var _i = 0, _refs = refs; _i < _refs.length; _i++) {
var ref = _refs[_i];
if (ref != null) {
if (typeof ref === 'function') {
ref(current);
} else {
ref.current = current;
}
}
}
}, [...refs] // eslint-disable-line react-hooks/exhaustive-deps
);
}
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/Utilities/useRefEffect.js
"use strict";
exports.__esModule = true;
exports.default = useRefEffect;
var _react = require("react");
/**
* 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.
*
*
* @format
*/
/**
* Constructs a callback ref that provides similar semantics as `useEffect`. The
* supplied `effect` callback will be called with non-null component instances.
* The `effect` callback can also optionally return a cleanup function.
*
* When a component is updated or unmounted, the cleanup function is called. The
* `effect` callback will then be called again, if applicable.
*
* When a new `effect` callback is supplied, the previously returned cleanup
* function will be called before the new `effect` callback is called with the
* same instance.
*
* WARNING: The `effect` callback should be stable (e.g. using `useCallback`).
*/
function useRefEffect(effect) {
var cleanupRef = (0, _react.useRef)(undefined);
return (0, _react.useCallback)(instance => {
if (cleanupRef.current) {
cleanupRef.current();
cleanupRef.current = undefined;
}
if (instance != null) {
cleanupRef.current = effect(instance);
}
}, [effect]);
}
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/ViewabilityHelper/index.js
/**
* 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.
*
*
* @format
*/
'use strict';
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _createForOfIteratorHelperLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/createForOfIteratorHelperLoose"));
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
/**
* A Utility class for calculating viewable items based on current metrics like scroll position and
* layout.
*
* An item is said to be in a "viewable" state when any of the following
* is true for longer than `minimumViewTime` milliseconds (after an interaction if `waitForInteraction`
* is true):
*
* - Occupying >= `viewAreaCoveragePercentThreshold` of the view area XOR fraction of the item
* visible in the view area >= `itemVisiblePercentThreshold`.
* - Entirely visible on screen
*/
class ViewabilityHelper {
constructor(config) {
if (config === void 0) {
config = {
viewAreaCoveragePercentThreshold: 0
};
}
this._hasInteracted = false;
this._timers = new Set();
this._viewableIndices = [];
this._viewableItems = new Map();
this._config = config;
}
/**
* Cleanup, e.g. on unmount. Clears any pending timers.
*/
dispose() {
/* $FlowFixMe[incompatible-call] (>=0.63.0 site=react_native_fb) This
* comment suppresses an error found when Flow v0.63 was deployed. To see
* the error delete this comment and run Flow. */
this._timers.forEach(clearTimeout);
}
/**
* Determines which items are viewable based on the current metrics and config.
*/
computeViewableItems(props, scrollOffset, viewportHeight, getFrameMetrics,
// Optional optimization to reduce the scan size
renderRange) {
var itemCount = props.getItemCount(props.data);
var _this$_config = this._config,
itemVisiblePercentThreshold = _this$_config.itemVisiblePercentThreshold,
viewAreaCoveragePercentThreshold = _this$_config.viewAreaCoveragePercentThreshold;
var viewAreaMode = viewAreaCoveragePercentThreshold != null;
var viewablePercentThreshold = viewAreaMode ? viewAreaCoveragePercentThreshold : itemVisiblePercentThreshold;
(0, _invariant.default)(viewablePercentThreshold != null && itemVisiblePercentThreshold != null !== (viewAreaCoveragePercentThreshold != null), 'Must set exactly one of itemVisiblePercentThreshold or viewAreaCoveragePercentThreshold');
var viewableIndices = [];
if (itemCount === 0) {
return viewableIndices;
}
var firstVisible = -1;
var _ref = renderRange || {
first: 0,
last: itemCount - 1
},
first = _ref.first,
last = _ref.last;
if (last >= itemCount) {
console.warn('Invalid render range computing viewability ' + JSON.stringify({
renderRange,
itemCount
}));
return [];
}
for (var idx = first; idx <= last; idx++) {
var metrics = getFrameMetrics(idx, props);
if (!metrics) {
continue;
}
var top = metrics.offset - scrollOffset;
var bottom = top + metrics.length;
if (top < viewportHeight && bottom > 0) {
firstVisible = idx;
if (_isViewable(viewAreaMode, viewablePercentThreshold, top, bottom, viewportHeight, metrics.length)) {
viewableIndices.push(idx);
}
} else if (firstVisible >= 0) {
break;
}
}
return viewableIndices;
}
/**
* Figures out which items are viewable and how that has changed from before and calls
* `onViewableItemsChanged` as appropriate.
*/
onUpdate(props, scrollOffset, viewportHeight, getFrameMetrics, createViewToken, onViewableItemsChanged,
// Optional optimization to reduce the scan size
renderRange) {
var itemCount = props.getItemCount(props.data);
if (this._config.waitForInteraction && !this._hasInteracted || itemCount === 0 || !getFrameMetrics(0, props)) {
return;
}
var viewableIndices = [];
if (itemCount) {
viewableIndices = this.computeViewableItems(props, scrollOffset, viewportHeight, getFrameMetrics, renderRange);
}
if (this._viewableIndices.length === viewableIndices.length && this._viewableIndices.every((v, ii) => v === viewableIndices[ii])) {
// We might get a lot of scroll events where visibility doesn't change and we don't want to do
// extra work in those cases.
return;
}
this._viewableIndices = viewableIndices;
if (this._config.minimumViewTime) {
var handle = setTimeout(() => {
/* $FlowFixMe[incompatible-call] (>=0.63.0 site=react_native_fb) This
* comment suppresses an error found when Flow v0.63 was deployed. To
* see the error delete this comment and run Flow. */
this._timers.delete(handle);
this._onUpdateSync(props, viewableIndices, onViewableItemsChanged, createViewToken);
}, this._config.minimumViewTime);
/* $FlowFixMe[incompatible-call] (>=0.63.0 site=react_native_fb) This
* comment suppresses an error found when Flow v0.63 was deployed. To see
* the error delete this comment and run Flow. */
this._timers.add(handle);
} else {
this._onUpdateSync(props, viewableIndices, onViewableItemsChanged, createViewToken);
}
}
/**
* clean-up cached _viewableIndices to evaluate changed items on next update
*/
resetViewableIndices() {
this._viewableIndices = [];
}
/**
* Records that an interaction has happened even if there has been no scroll.
*/
recordInteraction() {
this._hasInteracted = true;
}
_onUpdateSync(props, viewableIndicesToCheck, onViewableItemsChanged, createViewToken) {
// Filter out indices that have gone out of view since this call was scheduled.
viewableIndicesToCheck = viewableIndicesToCheck.filter(ii => this._viewableIndices.includes(ii));
var prevItems = this._viewableItems;
var nextItems = new Map(viewableIndicesToCheck.map(ii => {
var viewable = createViewToken(ii, true, props);
return [viewable.key, viewable];
}));
var changed = [];
for (var _iterator = (0, _createForOfIteratorHelperLoose2.default)(nextItems), _step; !(_step = _iterator()).done;) {
var _step$value = _step.value,
key = _step$value[0],
viewable = _step$value[1];
if (!prevItems.has(key)) {
changed.push(viewable);
}
}
for (var _iterator2 = (0, _createForOfIteratorHelperLoose2.default)(prevItems), _step2; !(_step2 = _iterator2()).done;) {
var _step2$value = _step2.value,
_key = _step2$value[0],
_viewable = _step2$value[1];
if (!nextItems.has(_key)) {
changed.push((0, _objectSpread2.default)((0, _objectSpread2.default)({}, _viewable), {}, {
isViewable: false
}));
}
}
if (changed.length > 0) {
this._viewableItems = nextItems;
onViewableItemsChanged({
viewableItems: Array.from(nextItems.values()),
changed,
viewabilityConfig: this._config
});
}
}
}
function _isViewable(viewAreaMode, viewablePercentThreshold, top, bottom, viewportHeight, itemLength) {
if (_isEntirelyVisible(top, bottom, viewportHeight)) {
return true;
} else {
var pixels = _getPixelsVisible(top, bottom, viewportHeight);
var percent = 100 * (viewAreaMode ? pixels / viewportHeight : pixels / itemLength);
return percent >= viewablePercentThreshold;
}
}
function _getPixelsVisible(top, bottom, viewportHeight) {
var visibleHeight = Math.min(bottom, viewportHeight) - Math.max(top, 0);
return Math.max(0, visibleHeight);
}
function _isEntirelyVisible(top, bottom, viewportHeight) {
return top >= 0 && bottom <= viewportHeight && bottom > top;
}
var _default = ViewabilityHelper;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/VirtualizeUtils/index.js
/**
* 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.
*
*
* @format
*/
'use strict';
exports.__esModule = true;
exports.computeWindowedRenderLimits = computeWindowedRenderLimits;
exports.elementsThatOverlapOffsets = elementsThatOverlapOffsets;
exports.keyExtractor = keyExtractor;
exports.newRangeCount = newRangeCount;
/**
* Used to find the indices of the frames that overlap the given offsets. Useful for finding the
* items that bound different windows of content, such as the visible area or the buffered overscan
* area.
*/
function elementsThatOverlapOffsets(offsets, props, getFrameMetrics, zoomScale) {
if (zoomScale === void 0) {
zoomScale = 1;
}
var itemCount = props.getItemCount(props.data);
var result = [];
for (var offsetIndex = 0; offsetIndex < offsets.length; offsetIndex++) {
var currentOffset = offsets[offsetIndex];
var left = 0;
var right = itemCount - 1;
while (left <= right) {
// eslint-disable-next-line no-bitwise
var mid = left + (right - left >>> 1);
var frame = getFrameMetrics(mid, props);
var scaledOffsetStart = frame.offset * zoomScale;
var scaledOffsetEnd = (frame.offset + frame.length) * zoomScale;
// We want the first frame that contains the offset, with inclusive bounds. Thus, for the
// first frame the scaledOffsetStart is inclusive, while for other frames it is exclusive.
if (mid === 0 && currentOffset < scaledOffsetStart || mid !== 0 && currentOffset <= scaledOffsetStart) {
right = mid - 1;
} else if (currentOffset > scaledOffsetEnd) {
left = mid + 1;
} else {
result[offsetIndex] = mid;
break;
}
}
}
return result;
}
/**
* Computes the number of elements in the `next` range that are new compared to the `prev` range.
* Handy for calculating how many new items will be rendered when the render window changes so we
* can restrict the number of new items render at once so that content can appear on the screen
* faster.
*/
function newRangeCount(prev, next) {
return next.last - next.first + 1 - Math.max(0, 1 + Math.min(next.last, prev.last) - Math.max(next.first, prev.first));
}
/**
* Custom logic for determining which items should be rendered given the current frame and scroll
* metrics, as well as the previous render state. The algorithm may evolve over time, but generally
* prioritizes the visible area first, then expands that with overscan regions ahead and behind,
* biased in the direction of scroll.
*/
function computeWindowedRenderLimits(props, maxToRenderPerBatch, windowSize, prev, getFrameMetricsApprox, scrollMetrics) {
var itemCount = props.getItemCount(props.data);
if (itemCount === 0) {
return {
first: 0,
last: -1
};
}
var offset = scrollMetrics.offset,
velocity = scrollMetrics.velocity,
visibleLength = scrollMetrics.visibleLength,
_scrollMetrics$zoomSc = scrollMetrics.zoomScale,
zoomScale = _scrollMetrics$zoomSc === void 0 ? 1 : _scrollMetrics$zoomSc;
// Start with visible area, then compute maximum overscan region by expanding from there, biased
// in the direction of scroll. Total overscan area is capped, which should cap memory consumption
// too.
var visibleBegin = Math.max(0, offset);
var visibleEnd = visibleBegin + visibleLength;
var overscanLength = (windowSize - 1) * visibleLength;
// Considering velocity seems to introduce more churn than it's worth.
var leadFactor = 0.5; // Math.max(0, Math.min(1, velocity / 25 + 0.5));
var fillPreference = velocity > 1 ? 'after' : velocity < -1 ? 'before' : 'none';
var overscanBegin = Math.max(0, visibleBegin - (1 - leadFactor) * overscanLength);
var overscanEnd = Math.max(0, visibleEnd + leadFactor * overscanLength);
var lastItemOffset = getFrameMetricsApprox(itemCount - 1, props).offset * zoomScale;
if (lastItemOffset < overscanBegin) {
// Entire list is before our overscan window
return {
first: Math.max(0, itemCount - 1 - maxToRenderPerBatch),
last: itemCount - 1
};
}
// Find the indices that correspond to the items at the render boundaries we're targeting.
var _elementsThatOverlapO = elementsThatOverlapOffsets([overscanBegin, visibleBegin, visibleEnd, overscanEnd], props, getFrameMetricsApprox, zoomScale),
overscanFirst = _elementsThatOverlapO[0],
first = _elementsThatOverlapO[1],
last = _elementsThatOverlapO[2],
overscanLast = _elementsThatOverlapO[3];
overscanFirst = overscanFirst == null ? 0 : overscanFirst;
first = first == null ? Math.max(0, overscanFirst) : first;
overscanLast = overscanLast == null ? itemCount - 1 : overscanLast;
last = last == null ? Math.min(overscanLast, first + maxToRenderPerBatch - 1) : last;
var visible = {
first,
last
};
// We want to limit the number of new cells we're rendering per batch so that we can fill the
// content on the screen quickly. If we rendered the entire overscan window at once, the user
// could be staring at white space for a long time waiting for a bunch of offscreen content to
// render.
var newCellCount = newRangeCount(prev, visible);
while (true) {
if (first <= overscanFirst && last >= overscanLast) {
// If we fill the entire overscan range, we're done.
break;
}
var maxNewCells = newCellCount >= maxToRenderPerBatch;
var firstWillAddMore = first <= prev.first || first > prev.last;
var firstShouldIncrement = first > overscanFirst && (!maxNewCells || !firstWillAddMore);
var lastWillAddMore = last >= prev.last || last < prev.first;
var lastShouldIncrement = last < overscanLast && (!maxNewCells || !lastWillAddMore);
if (maxNewCells && !firstShouldIncrement && !lastShouldIncrement) {
// We only want to stop if we've hit maxNewCells AND we cannot increment first or last
// without rendering new items. This let's us preserve as many already rendered items as
// possible, reducing render churn and keeping the rendered overscan range as large as
// possible.
break;
}
if (firstShouldIncrement && !(fillPreference === 'after' && lastShouldIncrement && lastWillAddMore)) {
if (firstWillAddMore) {
newCellCount++;
}
first--;
}
if (lastShouldIncrement && !(fillPreference === 'before' && firstShouldIncrement && firstWillAddMore)) {
if (lastWillAddMore) {
newCellCount++;
}
last++;
}
}
if (!(last >= first && first >= 0 && last < itemCount && first >= overscanFirst && last <= overscanLast && first <= visible.first && last >= visible.last)) {
throw new Error('Bad window calculation ' + JSON.stringify({
first,
last,
itemCount,
overscanFirst,
overscanLast,
visible
}));
}
return {
first,
last
};
}
function keyExtractor(item, index) {
if (typeof item === 'object' && (item == null ? void 0 : item.key) != null) {
return item.key;
}
if (typeof item === 'object' && (item == null ? void 0 : item.id) != null) {
return item.id;
}
return String(index);
}
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/VirtualizedList/CellRenderMask.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.CellRenderMask = void 0;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
/**
* 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.
*
*
* @format
*/
class CellRenderMask {
constructor(numCells) {
(0, _invariant.default)(numCells >= 0, 'CellRenderMask must contain a non-negative number os cells');
this._numCells = numCells;
if (numCells === 0) {
this._regions = [];
} else {
this._regions = [{
first: 0,
last: numCells - 1,
isSpacer: true
}];
}
}
enumerateRegions() {
return this._regions;
}
addCells(cells) {
(0, _invariant.default)(cells.first >= 0 && cells.first < this._numCells && cells.last >= -1 && cells.last < this._numCells && cells.last >= cells.first - 1, 'CellRenderMask.addCells called with invalid cell range');
// VirtualizedList uses inclusive ranges, where zero-count states are
// possible. E.g. [0, -1] for no cells, starting at 0.
if (cells.last < cells.first) {
return;
}
var _this$_findRegion = this._findRegion(cells.first),
firstIntersect = _this$_findRegion[0],
firstIntersectIdx = _this$_findRegion[1];
var _this$_findRegion2 = this._findRegion(cells.last),
lastIntersect = _this$_findRegion2[0],
lastIntersectIdx = _this$_findRegion2[1];
// Fast-path if the cells to add are already all present in the mask. We
// will otherwise need to do some mutation.
if (firstIntersectIdx === lastIntersectIdx && !firstIntersect.isSpacer) {
return;
}
// We need to replace the existing covered regions with 1-3 new regions
// depending whether we need to split spacers out of overlapping regions.
var newLeadRegion = [];
var newTailRegion = [];
var newMainRegion = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, cells), {}, {
isSpacer: false
});
if (firstIntersect.first < newMainRegion.first) {
if (firstIntersect.isSpacer) {
newLeadRegion.push({
first: firstIntersect.first,
last: newMainRegion.first - 1,
isSpacer: true
});
} else {
newMainRegion.first = firstIntersect.first;
}
}
if (lastIntersect.last > newMainRegion.last) {
if (lastIntersect.isSpacer) {
newTailRegion.push({
first: newMainRegion.last + 1,
last: lastIntersect.last,
isSpacer: true
});
} else {
newMainRegion.last = lastIntersect.last;
}
}
var replacementRegions = [...newLeadRegion, newMainRegion, ...newTailRegion];
var numRegionsToDelete = lastIntersectIdx - firstIntersectIdx + 1;
this._regions.splice(firstIntersectIdx, numRegionsToDelete, ...replacementRegions);
}
numCells() {
return this._numCells;
}
equals(other) {
return this._numCells === other._numCells && this._regions.length === other._regions.length && this._regions.every((region, i) => region.first === other._regions[i].first && region.last === other._regions[i].last && region.isSpacer === other._regions[i].isSpacer);
}
_findRegion(cellIdx) {
var firstIdx = 0;
var lastIdx = this._regions.length - 1;
while (firstIdx <= lastIdx) {
var middleIdx = Math.floor((firstIdx + lastIdx) / 2);
var middleRegion = this._regions[middleIdx];
if (cellIdx >= middleRegion.first && cellIdx <= middleRegion.last) {
return [middleRegion, middleIdx];
} else if (cellIdx < middleRegion.first) {
lastIdx = middleIdx - 1;
} else if (cellIdx > middleRegion.last) {
firstIdx = middleIdx + 1;
}
}
(0, _invariant.default)(false, "A region was not found containing cellIdx " + cellIdx);
}
}
exports.CellRenderMask = CellRenderMask;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/VirtualizedList/ChildListCollection.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _createForOfIteratorHelperLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/createForOfIteratorHelperLoose"));
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
/**
* 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.
*
*
* @format
*/
class ChildListCollection {
constructor() {
this._cellKeyToChildren = new Map();
this._childrenToCellKey = new Map();
}
add(list, cellKey) {
var _this$_cellKeyToChild;
(0, _invariant.default)(!this._childrenToCellKey.has(list), 'Trying to add already present child list');
var cellLists = (_this$_cellKeyToChild = this._cellKeyToChildren.get(cellKey)) !== null && _this$_cellKeyToChild !== void 0 ? _this$_cellKeyToChild : new Set();
cellLists.add(list);
this._cellKeyToChildren.set(cellKey, cellLists);
this._childrenToCellKey.set(list, cellKey);
}
remove(list) {
var cellKey = this._childrenToCellKey.get(list);
(0, _invariant.default)(cellKey != null, 'Trying to remove non-present child list');
this._childrenToCellKey.delete(list);
var cellLists = this._cellKeyToChildren.get(cellKey);
(0, _invariant.default)(cellLists, '_cellKeyToChildren should contain cellKey');
cellLists.delete(list);
if (cellLists.size === 0) {
this._cellKeyToChildren.delete(cellKey);
}
}
forEach(fn) {
for (var _iterator = (0, _createForOfIteratorHelperLoose2.default)(this._cellKeyToChildren.values()), _step; !(_step = _iterator()).done;) {
var listSet = _step.value;
for (var _iterator2 = (0, _createForOfIteratorHelperLoose2.default)(listSet), _step2; !(_step2 = _iterator2()).done;) {
var list = _step2.value;
fn(list);
}
}
}
forEachInCell(cellKey, fn) {
var _this$_cellKeyToChild2;
var listSet = (_this$_cellKeyToChild2 = this._cellKeyToChildren.get(cellKey)) !== null && _this$_cellKeyToChild2 !== void 0 ? _this$_cellKeyToChild2 : [];
for (var _iterator3 = (0, _createForOfIteratorHelperLoose2.default)(listSet), _step3; !(_step3 = _iterator3()).done;) {
var list = _step3.value;
fn(list);
}
}
anyInCell(cellKey, fn) {
var _this$_cellKeyToChild3;
var listSet = (_this$_cellKeyToChild3 = this._cellKeyToChildren.get(cellKey)) !== null && _this$_cellKeyToChild3 !== void 0 ? _this$_cellKeyToChild3 : [];
for (var _iterator4 = (0, _createForOfIteratorHelperLoose2.default)(listSet), _step4; !(_step4 = _iterator4()).done;) {
var list = _step4.value;
if (fn(list)) {
return true;
}
}
return false;
}
size() {
return this._childrenToCellKey.size;
}
}
exports.default = ChildListCollection;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/VirtualizedList/StateSafePureComponent.js
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
var React = _interopRequireWildcard(require("react"));
/**
* 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.
*
*
* @format
*/
/**
* `setState` is called asynchronously, and should not rely on the value of
* `this.props` or `this.state`:
* https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous
*
* SafePureComponent adds runtime enforcement, to catch cases where these
* variables are read in a state updater function, instead of the ones passed
* in.
*/
class StateSafePureComponent extends React.PureComponent {
constructor(props) {
super(props);
this._inAsyncStateUpdate = false;
this._installSetStateHooks();
}
setState(partialState, callback) {
if (typeof partialState === 'function') {
super.setState((state, props) => {
this._inAsyncStateUpdate = true;
var ret;
try {
ret = partialState(state, props);
} catch (err) {
throw err;
} finally {
this._inAsyncStateUpdate = false;
}
return ret;
}, callback);
} else {
super.setState(partialState, callback);
}
}
_installSetStateHooks() {
var that = this;
var props = this.props,
state = this.state;
Object.defineProperty(this, 'props', {
get() {
(0, _invariant.default)(!that._inAsyncStateUpdate, '"this.props" should not be accessed during state updates');
return props;
},
set(newProps) {
props = newProps;
}
});
Object.defineProperty(this, 'state', {
get() {
(0, _invariant.default)(!that._inAsyncStateUpdate, '"this.state" should not be acceessed during state updates');
return state;
},
set(newState) {
state = newState;
}
});
}
}
exports.default = StateSafePureComponent;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/VirtualizedList/VirtualizedListCellRenderer.js
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _View = _interopRequireDefault(require("../../../exports/View"));
var _StyleSheet = _interopRequireDefault(require("../../../exports/StyleSheet"));
var _VirtualizedListContext = require("./VirtualizedListContext.js");
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
var React = _interopRequireWildcard(require("react"));
/**
* 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.
*
*
* @format
*/
class CellRenderer extends React.Component {
constructor() {
super(...arguments);
this.state = {
separatorProps: {
highlighted: false,
leadingItem: this.props.item
}
};
this._separators = {
highlight: () => {
var _this$props = this.props,
cellKey = _this$props.cellKey,
prevCellKey = _this$props.prevCellKey;
this.props.onUpdateSeparators([cellKey, prevCellKey], {
highlighted: true
});
},
unhighlight: () => {
var _this$props2 = this.props,
cellKey = _this$props2.cellKey,
prevCellKey = _this$props2.prevCellKey;
this.props.onUpdateSeparators([cellKey, prevCellKey], {
highlighted: false
});
},
updateProps: (select, newProps) => {
var _this$props3 = this.props,
cellKey = _this$props3.cellKey,
prevCellKey = _this$props3.prevCellKey;
this.props.onUpdateSeparators([select === 'leading' ? prevCellKey : cellKey], newProps);
}
};
this._onLayout = nativeEvent => {
this.props.onCellLayout && this.props.onCellLayout(nativeEvent, this.props.cellKey, this.props.index);
};
}
static getDerivedStateFromProps(props, prevState) {
return {
separatorProps: (0, _objectSpread2.default)((0, _objectSpread2.default)({}, prevState.separatorProps), {}, {
leadingItem: props.item
})
};
}
// TODO: consider factoring separator stuff out of VirtualizedList into FlatList since it's not
// reused by SectionList and we can keep VirtualizedList simpler.
// $FlowFixMe[missing-local-annot]
updateSeparatorProps(newProps) {
this.setState(state => ({
separatorProps: (0, _objectSpread2.default)((0, _objectSpread2.default)({}, state.separatorProps), newProps)
}));
}
componentWillUnmount() {
this.props.onUnmount(this.props.cellKey);
}
_renderElement(renderItem, ListItemComponent, item, index) {
if (renderItem && ListItemComponent) {
console.warn('VirtualizedList: Both ListItemComponent and renderItem props are present. ListItemComponent will take' + ' precedence over renderItem.');
}
if (ListItemComponent) {
/* $FlowFixMe[not-a-component] (>=0.108.0 site=react_native_fb) This
* comment suppresses an error found when Flow v0.108 was deployed. To
* see the error, delete this comment and run Flow. */
/* $FlowFixMe[incompatible-type-arg] (>=0.108.0 site=react_native_fb)
* This comment suppresses an error found when Flow v0.108 was deployed.
* To see the error, delete this comment and run Flow. */
return /*#__PURE__*/React.createElement(ListItemComponent, {
item,
index,
separators: this._separators
});
}
if (renderItem) {
return renderItem({
item,
index,
separators: this._separators
});
}
(0, _invariant.default)(false, 'VirtualizedList: Either ListItemComponent or renderItem props are required but none were found.');
}
render() {
var _this$props4 = this.props,
CellRendererComponent = _this$props4.CellRendererComponent,
ItemSeparatorComponent = _this$props4.ItemSeparatorComponent,
ListItemComponent = _this$props4.ListItemComponent,
cellKey = _this$props4.cellKey,
horizontal = _this$props4.horizontal,
item = _this$props4.item,
index = _this$props4.index,
inversionStyle = _this$props4.inversionStyle,
onCellFocusCapture = _this$props4.onCellFocusCapture,
onCellLayout = _this$props4.onCellLayout,
renderItem = _this$props4.renderItem;
var element = this._renderElement(renderItem, ListItemComponent, item, index);
// NOTE: that when this is a sticky header, `onLayout` will get automatically extracted and
// called explicitly by `ScrollViewStickyHeader`.
var itemSeparator = /*#__PURE__*/React.isValidElement(ItemSeparatorComponent) ?
// $FlowFixMe[incompatible-type]
ItemSeparatorComponent :
// $FlowFixMe[incompatible-type]
ItemSeparatorComponent && /*#__PURE__*/React.createElement(ItemSeparatorComponent, this.state.separatorProps);
var cellStyle = inversionStyle ? horizontal ? [styles.rowReverse, inversionStyle] : [styles.columnReverse, inversionStyle] : horizontal ? [styles.row, inversionStyle] : inversionStyle;
var result = !CellRendererComponent ? /*#__PURE__*/React.createElement(_View.default, (0, _extends2.default)({
style: cellStyle,
onFocusCapture: onCellFocusCapture
}, onCellLayout && {
onLayout: this._onLayout
}), element, itemSeparator) : /*#__PURE__*/React.createElement(CellRendererComponent, (0, _extends2.default)({
cellKey: cellKey,
index: index,
item: item,
style: cellStyle,
onFocusCapture: onCellFocusCapture
}, onCellLayout && {
onLayout: this._onLayout
}), element, itemSeparator);
return /*#__PURE__*/React.createElement(_VirtualizedListContext.VirtualizedListCellContextProvider, {
cellKey: this.props.cellKey
}, result);
}
}
exports.default = CellRenderer;
var styles = _StyleSheet.default.create({
row: {
flexDirection: 'row'
},
rowReverse: {
flexDirection: 'row-reverse'
},
columnReverse: {
flexDirection: 'column-reverse'
}
});
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/VirtualizedList/VirtualizedListContext.js
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.VirtualizedListCellContextProvider = VirtualizedListCellContextProvider;
exports.VirtualizedListContext = void 0;
exports.VirtualizedListContextProvider = VirtualizedListContextProvider;
exports.VirtualizedListContextResetter = VirtualizedListContextResetter;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var React = _interopRequireWildcard(require("react"));
/**
* 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.
*
*
* @format
*/
var __DEV__ = process.env.NODE_ENV !== 'production';
var VirtualizedListContext = /*#__PURE__*/React.createContext(null);
exports.VirtualizedListContext = VirtualizedListContext;
if (__DEV__) {
VirtualizedListContext.displayName = 'VirtualizedListContext';
}
/**
* Resets the context. Intended for use by portal-like components (e.g. Modal).
*/
function VirtualizedListContextResetter(_ref) {
var children = _ref.children;
return /*#__PURE__*/React.createElement(VirtualizedListContext.Provider, {
value: null
}, children);
}
/**
* Sets the context with memoization. Intended to be used by `VirtualizedList`.
*/
function VirtualizedListContextProvider(_ref2) {
var children = _ref2.children,
value = _ref2.value;
// Avoid setting a newly created context object if the values are identical.
var context = (0, React.useMemo)(() => ({
cellKey: null,
getScrollMetrics: value.getScrollMetrics,
horizontal: value.horizontal,
getOutermostParentListRef: value.getOutermostParentListRef,
registerAsNestedChild: value.registerAsNestedChild,
unregisterAsNestedChild: value.unregisterAsNestedChild
}), [value.getScrollMetrics, value.horizontal, value.getOutermostParentListRef, value.registerAsNestedChild, value.unregisterAsNestedChild]);
return /*#__PURE__*/React.createElement(VirtualizedListContext.Provider, {
value: context
}, children);
}
/**
* Sets the `cellKey`. Intended to be used by `VirtualizedList` for each cell.
*/
function VirtualizedListCellContextProvider(_ref3) {
var cellKey = _ref3.cellKey,
children = _ref3.children;
// Avoid setting a newly created context object if the values are identical.
var currContext = (0, React.useContext)(VirtualizedListContext);
var context = (0, React.useMemo)(() => currContext == null ? null : (0, _objectSpread2.default)((0, _objectSpread2.default)({}, currContext), {}, {
cellKey
}), [currContext, cellKey]);
return /*#__PURE__*/React.createElement(VirtualizedListContext.Provider, {
value: context
}, children);
}
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/VirtualizedList/index.js
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = void 0;
var _createForOfIteratorHelperLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/createForOfIteratorHelperLoose"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _RefreshControl = _interopRequireDefault(require("../../../exports/RefreshControl"));
var _ScrollView = _interopRequireDefault(require("../../../exports/ScrollView"));
var _View = _interopRequireDefault(require("../../../exports/View"));
var _StyleSheet = _interopRequireDefault(require("../../../exports/StyleSheet"));
var _findNodeHandle = _interopRequireDefault(require("../../../exports/findNodeHandle"));
var _Batchinator = _interopRequireDefault(require("../Batchinator"));
var _clamp = _interopRequireDefault(require("../Utilities/clamp"));
var _infoLog = _interopRequireDefault(require("../infoLog"));
var _CellRenderMask = require("./CellRenderMask");
var _ChildListCollection = _interopRequireDefault(require("./ChildListCollection"));
var _FillRateHelper = _interopRequireDefault(require("../FillRateHelper"));
var _StateSafePureComponent = _interopRequireDefault(require("./StateSafePureComponent"));
var _ViewabilityHelper = _interopRequireDefault(require("../ViewabilityHelper"));
var _VirtualizedListCellRenderer = _interopRequireDefault(require("./VirtualizedListCellRenderer"));
var _VirtualizedListContext = require("./VirtualizedListContext.js");
var _VirtualizeUtils = require("../VirtualizeUtils");
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
var _nullthrows = _interopRequireDefault(require("nullthrows"));
var React = _interopRequireWildcard(require("react"));
/**
* 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.
*
*
* @format
*/
var __DEV__ = process.env.NODE_ENV !== 'production';
var ON_EDGE_REACHED_EPSILON = 0.001;
var _usedIndexForKey = false;
var _keylessItemComponentName = '';
/**
* Default Props Helper Functions
* Use the following helper functions for default values
*/
// horizontalOrDefault(this.props.horizontal)
function horizontalOrDefault(horizontal) {
return horizontal !== null && horizontal !== void 0 ? horizontal : false;
}
// initialNumToRenderOrDefault(this.props.initialNumToRender)
function initialNumToRenderOrDefault(initialNumToRender) {
return initialNumToRender !== null && initialNumToRender !== void 0 ? initialNumToRender : 10;
}
// maxToRenderPerBatchOrDefault(this.props.maxToRenderPerBatch)
function maxToRenderPerBatchOrDefault(maxToRenderPerBatch) {
return maxToRenderPerBatch !== null && maxToRenderPerBatch !== void 0 ? maxToRenderPerBatch : 10;
}
// onStartReachedThresholdOrDefault(this.props.onStartReachedThreshold)
function onStartReachedThresholdOrDefault(onStartReachedThreshold) {
return onStartReachedThreshold !== null && onStartReachedThreshold !== void 0 ? onStartReachedThreshold : 2;
}
// onEndReachedThresholdOrDefault(this.props.onEndReachedThreshold)
function onEndReachedThresholdOrDefault(onEndReachedThreshold) {
return onEndReachedThreshold !== null && onEndReachedThreshold !== void 0 ? onEndReachedThreshold : 2;
}
// getScrollingThreshold(visibleLength, onEndReachedThreshold)
function getScrollingThreshold(threshold, visibleLength) {
return threshold * visibleLength / 2;
}
// scrollEventThrottleOrDefault(this.props.scrollEventThrottle)
function scrollEventThrottleOrDefault(scrollEventThrottle) {
return scrollEventThrottle !== null && scrollEventThrottle !== void 0 ? scrollEventThrottle : 50;
}
// windowSizeOrDefault(this.props.windowSize)
function windowSizeOrDefault(windowSize) {
return windowSize !== null && windowSize !== void 0 ? windowSize : 21;
}
function findLastWhere(arr, predicate) {
for (var i = arr.length - 1; i >= 0; i--) {
if (predicate(arr[i])) {
return arr[i];
}
}
return null;
}
/**
* Base implementation for the more convenient [`<FlatList>`](https://reactnative.dev/docs/flatlist)
* and [`<SectionList>`](https://reactnative.dev/docs/sectionlist) components, which are also better
* documented. In general, this should only really be used if you need more flexibility than
* `FlatList` provides, e.g. for use with immutable data instead of plain arrays.
*
* Virtualization massively improves memory consumption and performance of large lists by
* maintaining a finite render window of active items and replacing all items outside of the render
* window with appropriately sized blank space. The window adapts to scrolling behavior, and items
* are rendered incrementally with low-pri (after any running interactions) if they are far from the
* visible area, or with hi-pri otherwise to minimize the potential of seeing blank space.
*
* Some caveats:
*
* - Internal state is not preserved when content scrolls out of the render window. Make sure all
* your data is captured in the item data or external stores like Flux, Redux, or Relay.
* - This is a `PureComponent` which means that it will not re-render if `props` remain shallow-
* equal. Make sure that everything your `renderItem` function depends on is passed as a prop
* (e.g. `extraData`) that is not `===` after updates, otherwise your UI may not update on
* changes. This includes the `data` prop and parent component state.
* - In order to constrain memory and enable smooth scrolling, content is rendered asynchronously
* offscreen. This means it's possible to scroll faster than the fill rate ands momentarily see
* blank content. This is a tradeoff that can be adjusted to suit the needs of each application,
* and we are working on improving it behind the scenes.
* - By default, the list looks for a `key` or `id` prop on each item and uses that for the React key.
* Alternatively, you can provide a custom `keyExtractor` prop.
* - As an effort to remove defaultProps, use helper functions when referencing certain props
*
*/
class VirtualizedList extends _StateSafePureComponent.default {
// scrollToEnd may be janky without getItemLayout prop
scrollToEnd(params) {
var animated = params ? params.animated : true;
var veryLast = this.props.getItemCount(this.props.data) - 1;
if (veryLast < 0) {
return;
}
var frame = this.__getFrameMetricsApprox(veryLast, this.props);
var offset = Math.max(0, frame.offset + frame.length + this._footerLength - this._scrollMetrics.visibleLength);
if (this._scrollRef == null) {
return;
}
if (this._scrollRef.scrollTo == null) {
console.warn('No scrollTo method provided. This may be because you have two nested ' + 'VirtualizedLists with the same orientation, or because you are ' + 'using a custom component that does not implement scrollTo.');
return;
}
this._scrollRef.scrollTo(horizontalOrDefault(this.props.horizontal) ? {
x: offset,
animated
} : {
y: offset,
animated
});
}
// scrollToIndex may be janky without getItemLayout prop
scrollToIndex(params) {
var _this$props = this.props,
data = _this$props.data,
horizontal = _this$props.horizontal,
getItemCount = _this$props.getItemCount,
getItemLayout = _this$props.getItemLayout,
onScrollToIndexFailed = _this$props.onScrollToIndexFailed;
var animated = params.animated,
index = params.index,
viewOffset = params.viewOffset,
viewPosition = params.viewPosition;
(0, _invariant.default)(index >= 0, "scrollToIndex out of range: requested index " + index + " but minimum is 0");
(0, _invariant.default)(getItemCount(data) >= 1, "scrollToIndex out of range: item length " + getItemCount(data) + " but minimum is 1");
(0, _invariant.default)(index < getItemCount(data), "scrollToIndex out of range: requested index " + index + " is out of 0 to " + (getItemCount(data) - 1));
if (!getItemLayout && index > this._highestMeasuredFrameIndex) {
(0, _invariant.default)(!!onScrollToIndexFailed, 'scrollToIndex should be used in conjunction with getItemLayout or onScrollToIndexFailed, ' + 'otherwise there is no way to know the location of offscreen indices or handle failures.');
onScrollToIndexFailed({
averageItemLength: this._averageCellLength,
highestMeasuredFrameIndex: this._highestMeasuredFrameIndex,
index
});
return;
}
var frame = this.__getFrameMetricsApprox(Math.floor(index), this.props);
var offset = Math.max(0, this._getOffsetApprox(index, this.props) - (viewPosition || 0) * (this._scrollMetrics.visibleLength - frame.length)) - (viewOffset || 0);
if (this._scrollRef == null) {
return;
}
if (this._scrollRef.scrollTo == null) {
console.warn('No scrollTo method provided. This may be because you have two nested ' + 'VirtualizedLists with the same orientation, or because you are ' + 'using a custom component that does not implement scrollTo.');
return;
}
this._scrollRef.scrollTo(horizontal ? {
x: offset,
animated
} : {
y: offset,
animated
});
}
// scrollToItem may be janky without getItemLayout prop. Required linear scan through items -
// use scrollToIndex instead if possible.
scrollToItem(params) {
var item = params.item;
var _this$props2 = this.props,
data = _this$props2.data,
getItem = _this$props2.getItem,
getItemCount = _this$props2.getItemCount;
var itemCount = getItemCount(data);
for (var _index = 0; _index < itemCount; _index++) {
if (getItem(data, _index) === item) {
this.scrollToIndex((0, _objectSpread2.default)((0, _objectSpread2.default)({}, params), {}, {
index: _index
}));
break;
}
}
}
/**
* Scroll to a specific content pixel offset in the list.
*
* Param `offset` expects the offset to scroll to.
* In case of `horizontal` is true, the offset is the x-value,
* in any other case the offset is the y-value.
*
* Param `animated` (`true` by default) defines whether the list
* should do an animation while scrolling.
*/
scrollToOffset(params) {
var animated = params.animated,
offset = params.offset;
if (this._scrollRef == null) {
return;
}
if (this._scrollRef.scrollTo == null) {
console.warn('No scrollTo method provided. This may be because you have two nested ' + 'VirtualizedLists with the same orientation, or because you are ' + 'using a custom component that does not implement scrollTo.');
return;
}
this._scrollRef.scrollTo(horizontalOrDefault(this.props.horizontal) ? {
x: offset,
animated
} : {
y: offset,
animated
});
}
recordInteraction() {
this._nestedChildLists.forEach(childList => {
childList.recordInteraction();
});
this._viewabilityTuples.forEach(t => {
t.viewabilityHelper.recordInteraction();
});
this._updateViewableItems(this.props, this.state.cellsAroundViewport);
}
flashScrollIndicators() {
if (this._scrollRef == null) {
return;
}
this._scrollRef.flashScrollIndicators();
}
/**
* Provides a handle to the underlying scroll responder.
* Note that `this._scrollRef` might not be a `ScrollView`, so we
* need to check that it responds to `getScrollResponder` before calling it.
*/
getScrollResponder() {
if (this._scrollRef && this._scrollRef.getScrollResponder) {
return this._scrollRef.getScrollResponder();
}
}
getScrollableNode() {
if (this._scrollRef && this._scrollRef.getScrollableNode) {
return this._scrollRef.getScrollableNode();
} else {
return this._scrollRef;
}
}
getScrollRef() {
if (this._scrollRef && this._scrollRef.getScrollRef) {
return this._scrollRef.getScrollRef();
} else {
return this._scrollRef;
}
}
_getCellKey() {
var _this$context;
return ((_this$context = this.context) == null ? void 0 : _this$context.cellKey) || 'rootList';
}
// $FlowFixMe[missing-local-annot]
hasMore() {
return this._hasMore;
}
// $FlowFixMe[missing-local-annot]
constructor(_props) {
var _this$props$updateCel;
super(_props);
this._getScrollMetrics = () => {
return this._scrollMetrics;
};
this._getOutermostParentListRef = () => {
if (this._isNestedWithSameOrientation()) {
return this.context.getOutermostParentListRef();
} else {
return this;
}
};
this._registerAsNestedChild = childList => {
this._nestedChildLists.add(childList.ref, childList.cellKey);
if (this._hasInteracted) {
childList.ref.recordInteraction();
}
};
this._unregisterAsNestedChild = childList => {
this._nestedChildLists.remove(childList.ref);
};
this._onUpdateSeparators = (keys, newProps) => {
keys.forEach(key => {
var ref = key != null && this._cellRefs[key];
ref && ref.updateSeparatorProps(newProps);
});
};
this._getSpacerKey = isVertical => isVertical ? 'height' : 'width';
this._averageCellLength = 0;
this._cellRefs = {};
this._frames = {};
this._footerLength = 0;
this._hasTriggeredInitialScrollToIndex = false;
this._hasInteracted = false;
this._hasMore = false;
this._hasWarned = {};
this._headerLength = 0;
this._hiPriInProgress = false;
this._highestMeasuredFrameIndex = 0;
this._indicesToKeys = new Map();
this._lastFocusedCellKey = null;
this._nestedChildLists = new _ChildListCollection.default();
this._offsetFromParentVirtualizedList = 0;
this._prevParentOffset = 0;
this._scrollMetrics = {
contentLength: 0,
dOffset: 0,
dt: 10,
offset: 0,
timestamp: 0,
velocity: 0,
visibleLength: 0,
zoomScale: 1
};
this._scrollRef = null;
this._sentStartForContentLength = 0;
this._sentEndForContentLength = 0;
this._totalCellLength = 0;
this._totalCellsMeasured = 0;
this._viewabilityTuples = [];
this._captureScrollRef = ref => {
this._scrollRef = ref;
};
this._defaultRenderScrollComponent = props => {
var onRefresh = props.onRefresh;
if (this._isNestedWithSameOrientation()) {
// $FlowFixMe[prop-missing] - Typing ReactNativeComponent revealed errors
return /*#__PURE__*/React.createElement(_View.default, props);
} else if (onRefresh) {
var _props$refreshing;
(0, _invariant.default)(typeof props.refreshing === 'boolean', '`refreshing` prop must be set as a boolean in order to use `onRefresh`, but got `' + JSON.stringify((_props$refreshing = props.refreshing) !== null && _props$refreshing !== void 0 ? _props$refreshing : 'undefined') + '`');
return (
/*#__PURE__*/
// $FlowFixMe[prop-missing] Invalid prop usage
// $FlowFixMe[incompatible-use]
React.createElement(_ScrollView.default, (0, _extends2.default)({}, props, {
refreshControl: props.refreshControl == null ? /*#__PURE__*/React.createElement(_RefreshControl.default
// $FlowFixMe[incompatible-type]
, {
refreshing: props.refreshing,
onRefresh: onRefresh,
progressViewOffset: props.progressViewOffset
}) : props.refreshControl
}))
);
} else {
// $FlowFixMe[prop-missing] Invalid prop usage
// $FlowFixMe[incompatible-use]
return /*#__PURE__*/React.createElement(_ScrollView.default, props);
}
};
this._onCellLayout = (e, cellKey, index) => {
var layout = e.nativeEvent.layout;
var next = {
offset: this._selectOffset(layout),
length: this._selectLength(layout),
index,
inLayout: true
};
var curr = this._frames[cellKey];
if (!curr || next.offset !== curr.offset || next.length !== curr.length || index !== curr.index) {
this._totalCellLength += next.length - (curr ? curr.length : 0);
this._totalCellsMeasured += curr ? 0 : 1;
this._averageCellLength = this._totalCellLength / this._totalCellsMeasured;
this._frames[cellKey] = next;
this._highestMeasuredFrameIndex = Math.max(this._highestMeasuredFrameIndex, index);
this._scheduleCellsToRenderUpdate();
} else {
this._frames[cellKey].inLayout = true;
}
this._triggerRemeasureForChildListsInCell(cellKey);
this._computeBlankness();
this._updateViewableItems(this.props, this.state.cellsAroundViewport);
};
this._onCellUnmount = cellKey => {
delete this._cellRefs[cellKey];
var curr = this._frames[cellKey];
if (curr) {
this._frames[cellKey] = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, curr), {}, {
inLayout: false
});
}
};
this._onLayout = e => {
if (this._isNestedWithSameOrientation()) {
// Need to adjust our scroll metrics to be relative to our containing
// VirtualizedList before we can make claims about list item viewability
this.measureLayoutRelativeToContainingList();
} else {
this._scrollMetrics.visibleLength = this._selectLength(e.nativeEvent.layout);
}
this.props.onLayout && this.props.onLayout(e);
this._scheduleCellsToRenderUpdate();
this._maybeCallOnEdgeReached();
};
this._onLayoutEmpty = e => {
this.props.onLayout && this.props.onLayout(e);
};
this._onLayoutFooter = e => {
this._triggerRemeasureForChildListsInCell(this._getFooterCellKey());
this._footerLength = this._selectLength(e.nativeEvent.layout);
};
this._onLayoutHeader = e => {
this._headerLength = this._selectLength(e.nativeEvent.layout);
};
this._onContentSizeChange = (width, height) => {
if (width > 0 && height > 0 && this.props.initialScrollIndex != null && this.props.initialScrollIndex > 0 && !this._hasTriggeredInitialScrollToIndex) {
if (this.props.contentOffset == null) {
if (this.props.initialScrollIndex < this.props.getItemCount(this.props.data)) {
this.scrollToIndex({
animated: false,
index: (0, _nullthrows.default)(this.props.initialScrollIndex)
});
} else {
this.scrollToEnd({
animated: false
});
}
}
this._hasTriggeredInitialScrollToIndex = true;
}
if (this.props.onContentSizeChange) {
this.props.onContentSizeChange(width, height);
}
this._scrollMetrics.contentLength = this._selectLength({
height,
width
});
this._scheduleCellsToRenderUpdate();
this._maybeCallOnEdgeReached();
};
this._convertParentScrollMetrics = metrics => {
// Offset of the top of the nested list relative to the top of its parent's viewport
var offset = metrics.offset - this._offsetFromParentVirtualizedList;
// Child's visible length is the same as its parent's
var visibleLength = metrics.visibleLength;
var dOffset = offset - this._scrollMetrics.offset;
var contentLength = this._scrollMetrics.contentLength;
return {
visibleLength,
contentLength,
offset,
dOffset
};
};
this._onScroll = e => {
this._nestedChildLists.forEach(childList => {
childList._onScroll(e);
});
if (this.props.onScroll) {
this.props.onScroll(e);
}
var timestamp = e.timeStamp;
var visibleLength = this._selectLength(e.nativeEvent.layoutMeasurement);
var contentLength = this._selectLength(e.nativeEvent.contentSize);
var offset = this._selectOffset(e.nativeEvent.contentOffset);
var dOffset = offset - this._scrollMetrics.offset;
if (this._isNestedWithSameOrientation()) {
if (this._scrollMetrics.contentLength === 0) {
// Ignore scroll events until onLayout has been called and we
// know our offset from our offset from our parent
return;
}
var _this$_convertParentS = this._convertParentScrollMetrics({
visibleLength,
offset
});
visibleLength = _this$_convertParentS.visibleLength;
contentLength = _this$_convertParentS.contentLength;
offset = _this$_convertParentS.offset;
dOffset = _this$_convertParentS.dOffset;
}
var dt = this._scrollMetrics.timestamp ? Math.max(1, timestamp - this._scrollMetrics.timestamp) : 1;
var velocity = dOffset / dt;
if (dt > 500 && this._scrollMetrics.dt > 500 && contentLength > 5 * visibleLength && !this._hasWarned.perf) {
(0, _infoLog.default)('VirtualizedList: You have a large list that is slow to update - make sure your ' + 'renderItem function renders components that follow React performance best practices ' + 'like PureComponent, shouldComponentUpdate, etc.', {
dt,
prevDt: this._scrollMetrics.dt,
contentLength
});
this._hasWarned.perf = true;
}
// For invalid negative values (w/ RTL), set this to 1.
var zoomScale = e.nativeEvent.zoomScale < 0 ? 1 : e.nativeEvent.zoomScale;
this._scrollMetrics = {
contentLength,
dt,
dOffset,
offset,
timestamp,
velocity,
visibleLength,
zoomScale
};
this._updateViewableItems(this.props, this.state.cellsAroundViewport);
if (!this.props) {
return;
}
this._maybeCallOnEdgeReached();
if (velocity !== 0) {
this._fillRateHelper.activate();
}
this._computeBlankness();
this._scheduleCellsToRenderUpdate();
};
this._onScrollBeginDrag = e => {
this._nestedChildLists.forEach(childList => {
childList._onScrollBeginDrag(e);
});
this._viewabilityTuples.forEach(tuple => {
tuple.viewabilityHelper.recordInteraction();
});
this._hasInteracted = true;
this.props.onScrollBeginDrag && this.props.onScrollBeginDrag(e);
};
this._onScrollEndDrag = e => {
this._nestedChildLists.forEach(childList => {
childList._onScrollEndDrag(e);
});
var velocity = e.nativeEvent.velocity;
if (velocity) {
this._scrollMetrics.velocity = this._selectOffset(velocity);
}
this._computeBlankness();
this.props.onScrollEndDrag && this.props.onScrollEndDrag(e);
};
this._onMomentumScrollBegin = e => {
this._nestedChildLists.forEach(childList => {
childList._onMomentumScrollBegin(e);
});
this.props.onMomentumScrollBegin && this.props.onMomentumScrollBegin(e);
};
this._onMomentumScrollEnd = e => {
this._nestedChildLists.forEach(childList => {
childList._onMomentumScrollEnd(e);
});
this._scrollMetrics.velocity = 0;
this._computeBlankness();
this.props.onMomentumScrollEnd && this.props.onMomentumScrollEnd(e);
};
this._updateCellsToRender = () => {
this._updateViewableItems(this.props, this.state.cellsAroundViewport);
this.setState((state, props) => {
var cellsAroundViewport = this._adjustCellsAroundViewport(props, state.cellsAroundViewport);
var renderMask = VirtualizedList._createRenderMask(props, cellsAroundViewport, this._getNonViewportRenderRegions(props));
if (cellsAroundViewport.first === state.cellsAroundViewport.first && cellsAroundViewport.last === state.cellsAroundViewport.last && renderMask.equals(state.renderMask)) {
return null;
}
return {
cellsAroundViewport,
renderMask
};
});
};
this._createViewToken = (index, isViewable, props
// $FlowFixMe[missing-local-annot]
) => {
var data = props.data,
getItem = props.getItem;
var item = getItem(data, index);
return {
index,
item,
key: this._keyExtractor(item, index, props),
isViewable
};
};
this._getOffsetApprox = (index, props) => {
if (Number.isInteger(index)) {
return this.__getFrameMetricsApprox(index, props).offset;
} else {
var frameMetrics = this.__getFrameMetricsApprox(Math.floor(index), props);
var remainder = index - Math.floor(index);
return frameMetrics.offset + remainder * frameMetrics.length;
}
};
this.__getFrameMetricsApprox = (index, props) => {
var frame = this._getFrameMetrics(index, props);
if (frame && frame.index === index) {
// check for invalid frames due to row re-ordering
return frame;
} else {
var data = props.data,
getItemCount = props.getItemCount,
getItemLayout = props.getItemLayout;
(0, _invariant.default)(index >= 0 && index < getItemCount(data), 'Tried to get frame for out of range index ' + index);
(0, _invariant.default)(!getItemLayout, 'Should not have to estimate frames when a measurement metrics function is provided');
return {
length: this._averageCellLength,
offset: this._averageCellLength * index
};
}
};
this._getFrameMetrics = (index, props) => {
var data = props.data,
getItem = props.getItem,
getItemCount = props.getItemCount,
getItemLayout = props.getItemLayout;
(0, _invariant.default)(index >= 0 && index < getItemCount(data), 'Tried to get frame for out of range index ' + index);
var item = getItem(data, index);
var frame = this._frames[this._keyExtractor(item, index, props)];
if (!frame || frame.index !== index) {
if (getItemLayout) {
/* $FlowFixMe[prop-missing] (>=0.63.0 site=react_native_fb) This comment
* suppresses an error found when Flow v0.63 was deployed. To see the error
* delete this comment and run Flow. */
return getItemLayout(data, index);
}
}
return frame;
};
this._getNonViewportRenderRegions = props => {
// Keep a viewport's worth of content around the last focused cell to allow
// random navigation around it without any blanking. E.g. tabbing from one
// focused item out of viewport to another.
if (!(this._lastFocusedCellKey && this._cellRefs[this._lastFocusedCellKey])) {
return [];
}
var lastFocusedCellRenderer = this._cellRefs[this._lastFocusedCellKey];
var focusedCellIndex = lastFocusedCellRenderer.props.index;
var itemCount = props.getItemCount(props.data);
// The last cell we rendered may be at a new index. Bail if we don't know
// where it is.
if (focusedCellIndex >= itemCount || this._keyExtractor(props.getItem(props.data, focusedCellIndex), focusedCellIndex, props) !== this._lastFocusedCellKey) {
return [];
}
var first = focusedCellIndex;
var heightOfCellsBeforeFocused = 0;
for (var i = first - 1; i >= 0 && heightOfCellsBeforeFocused < this._scrollMetrics.visibleLength; i--) {
first--;
heightOfCellsBeforeFocused += this.__getFrameMetricsApprox(i, props).length;
}
var last = focusedCellIndex;
var heightOfCellsAfterFocused = 0;
for (var _i = last + 1; _i < itemCount && heightOfCellsAfterFocused < this._scrollMetrics.visibleLength; _i++) {
last++;
heightOfCellsAfterFocused += this.__getFrameMetricsApprox(_i, props).length;
}
return [{
first,
last
}];
};
this._checkProps(_props);
this._fillRateHelper = new _FillRateHelper.default(this._getFrameMetrics);
this._updateCellsToRenderBatcher = new _Batchinator.default(this._updateCellsToRender, (_this$props$updateCel = this.props.updateCellsBatchingPeriod) !== null && _this$props$updateCel !== void 0 ? _this$props$updateCel : 50);
if (this.props.viewabilityConfigCallbackPairs) {
this._viewabilityTuples = this.props.viewabilityConfigCallbackPairs.map(pair => ({
viewabilityHelper: new _ViewabilityHelper.default(pair.viewabilityConfig),
onViewableItemsChanged: pair.onViewableItemsChanged
}));
} else {
var _this$props3 = this.props,
onViewableItemsChanged = _this$props3.onViewableItemsChanged,
viewabilityConfig = _this$props3.viewabilityConfig;
if (onViewableItemsChanged) {
this._viewabilityTuples.push({
viewabilityHelper: new _ViewabilityHelper.default(viewabilityConfig),
onViewableItemsChanged: onViewableItemsChanged
});
}
}
var initialRenderRegion = VirtualizedList._initialRenderRegion(_props);
this.state = {
cellsAroundViewport: initialRenderRegion,
renderMask: VirtualizedList._createRenderMask(_props, initialRenderRegion)
};
// REACT-NATIVE-WEB patch to preserve during future RN merges: Support inverted wheel scroller.
// For issue https://github.com/necolas/react-native-web/issues/995
this.invertedWheelEventHandler = ev => {
var scrollOffset = this.props.horizontal ? ev.target.scrollLeft : ev.target.scrollTop;
var scrollLength = this.props.horizontal ? ev.target.scrollWidth : ev.target.scrollHeight;
var clientLength = this.props.horizontal ? ev.target.clientWidth : ev.target.clientHeight;
var isEventTargetScrollable = scrollLength > clientLength;
var delta = this.props.horizontal ? ev.deltaX || ev.wheelDeltaX : ev.deltaY || ev.wheelDeltaY;
var leftoverDelta = delta;
if (isEventTargetScrollable) {
leftoverDelta = delta < 0 ? Math.min(delta + scrollOffset, 0) : Math.max(delta - (scrollLength - clientLength - scrollOffset), 0);
}
var targetDelta = delta - leftoverDelta;
if (this.props.inverted && this._scrollRef && this._scrollRef.getScrollableNode) {
var node = this._scrollRef.getScrollableNode();
if (this.props.horizontal) {
ev.target.scrollLeft += targetDelta;
var nextScrollLeft = node.scrollLeft - leftoverDelta;
node.scrollLeft = !this.props.getItemLayout ? Math.min(nextScrollLeft, this._totalCellLength) : nextScrollLeft;
} else {
ev.target.scrollTop += targetDelta;
var nextScrollTop = node.scrollTop - leftoverDelta;
node.scrollTop = !this.props.getItemLayout ? Math.min(nextScrollTop, this._totalCellLength) : nextScrollTop;
}
ev.preventDefault();
}
};
}
_checkProps(props) {
var onScroll = props.onScroll,
windowSize = props.windowSize,
getItemCount = props.getItemCount,
data = props.data,
initialScrollIndex = props.initialScrollIndex;
(0, _invariant.default)(
// $FlowFixMe[prop-missing]
!onScroll || !onScroll.__isNative, 'Components based on VirtualizedList must be wrapped with Animated.createAnimatedComponent ' + 'to support native onScroll events with useNativeDriver');
(0, _invariant.default)(windowSizeOrDefault(windowSize) > 0, 'VirtualizedList: The windowSize prop must be present and set to a value greater than 0.');
(0, _invariant.default)(getItemCount, 'VirtualizedList: The "getItemCount" prop must be provided');
var itemCount = getItemCount(data);
if (initialScrollIndex != null && !this._hasTriggeredInitialScrollToIndex && (initialScrollIndex < 0 || itemCount > 0 && initialScrollIndex >= itemCount) && !this._hasWarned.initialScrollIndex) {
console.warn("initialScrollIndex \"" + initialScrollIndex + "\" is not valid (list has " + itemCount + " items)");
this._hasWarned.initialScrollIndex = true;
}
if (__DEV__ && !this._hasWarned.flexWrap) {
// $FlowFixMe[underconstrained-implicit-instantiation]
var flatStyles = _StyleSheet.default.flatten(this.props.contentContainerStyle);
if (flatStyles != null && flatStyles.flexWrap === 'wrap') {
console.warn('`flexWrap: `wrap`` is not supported with the `VirtualizedList` components.' + 'Consider using `numColumns` with `FlatList` instead.');
this._hasWarned.flexWrap = true;
}
}
}
static _createRenderMask(props, cellsAroundViewport, additionalRegions) {
var itemCount = props.getItemCount(props.data);
(0, _invariant.default)(cellsAroundViewport.first >= 0 && cellsAroundViewport.last >= cellsAroundViewport.first - 1 && cellsAroundViewport.last < itemCount, "Invalid cells around viewport \"[" + cellsAroundViewport.first + ", " + cellsAroundViewport.last + "]\" was passed to VirtualizedList._createRenderMask");
var renderMask = new _CellRenderMask.CellRenderMask(itemCount);
if (itemCount > 0) {
var allRegions = [cellsAroundViewport, ...(additionalRegions !== null && additionalRegions !== void 0 ? additionalRegions : [])];
for (var _i2 = 0, _allRegions = allRegions; _i2 < _allRegions.length; _i2++) {
var region = _allRegions[_i2];
renderMask.addCells(region);
}
// The initially rendered cells are retained as part of the
// "scroll-to-top" optimization
if (props.initialScrollIndex == null || props.initialScrollIndex <= 0) {
var initialRegion = VirtualizedList._initialRenderRegion(props);
renderMask.addCells(initialRegion);
}
// The layout coordinates of sticker headers may be off-screen while the
// actual header is on-screen. Keep the most recent before the viewport
// rendered, even if its layout coordinates are not in viewport.
var stickyIndicesSet = new Set(props.stickyHeaderIndices);
VirtualizedList._ensureClosestStickyHeader(props, stickyIndicesSet, renderMask, cellsAroundViewport.first);
}
return renderMask;
}
static _initialRenderRegion(props) {
var _props$initialScrollI;
var itemCount = props.getItemCount(props.data);
var firstCellIndex = Math.max(0, Math.min(itemCount - 1, Math.floor((_props$initialScrollI = props.initialScrollIndex) !== null && _props$initialScrollI !== void 0 ? _props$initialScrollI : 0)));
var lastCellIndex = Math.min(itemCount, firstCellIndex + initialNumToRenderOrDefault(props.initialNumToRender)) - 1;
return {
first: firstCellIndex,
last: lastCellIndex
};
}
static _ensureClosestStickyHeader(props, stickyIndicesSet, renderMask, cellIdx) {
var stickyOffset = props.ListHeaderComponent ? 1 : 0;
for (var itemIdx = cellIdx - 1; itemIdx >= 0; itemIdx--) {
if (stickyIndicesSet.has(itemIdx + stickyOffset)) {
renderMask.addCells({
first: itemIdx,
last: itemIdx
});
break;
}
}
}
_adjustCellsAroundViewport(props, cellsAroundViewport) {
var data = props.data,
getItemCount = props.getItemCount;
var onEndReachedThreshold = onEndReachedThresholdOrDefault(props.onEndReachedThreshold);
var _this$_scrollMetrics = this._scrollMetrics,
contentLength = _this$_scrollMetrics.contentLength,
offset = _this$_scrollMetrics.offset,
visibleLength = _this$_scrollMetrics.visibleLength;
var distanceFromEnd = contentLength - visibleLength - offset;
// Wait until the scroll view metrics have been set up. And until then,
// we will trust the initialNumToRender suggestion
if (visibleLength <= 0 || contentLength <= 0) {
return cellsAroundViewport.last >= getItemCount(data) ? VirtualizedList._constrainToItemCount(cellsAroundViewport, props) : cellsAroundViewport;
}
var newCellsAroundViewport;
if (props.disableVirtualization) {
var renderAhead = distanceFromEnd < onEndReachedThreshold * visibleLength ? maxToRenderPerBatchOrDefault(props.maxToRenderPerBatch) : 0;
newCellsAroundViewport = {
first: 0,
last: Math.min(cellsAroundViewport.last + renderAhead, getItemCount(data) - 1)
};
} else {
// If we have a non-zero initialScrollIndex and run this before we've scrolled,
// we'll wipe out the initialNumToRender rendered elements starting at initialScrollIndex.
// So let's wait until we've scrolled the view to the right place. And until then,
// we will trust the initialScrollIndex suggestion.
// Thus, we want to recalculate the windowed render limits if any of the following hold:
// - initialScrollIndex is undefined or is 0
// - initialScrollIndex > 0 AND scrolling is complete
// - initialScrollIndex > 0 AND the end of the list is visible (this handles the case
// where the list is shorter than the visible area)
if (props.initialScrollIndex && !this._scrollMetrics.offset && Math.abs(distanceFromEnd) >= Number.EPSILON) {
return cellsAroundViewport.last >= getItemCount(data) ? VirtualizedList._constrainToItemCount(cellsAroundViewport, props) : cellsAroundViewport;
}
newCellsAroundViewport = (0, _VirtualizeUtils.computeWindowedRenderLimits)(props, maxToRenderPerBatchOrDefault(props.maxToRenderPerBatch), windowSizeOrDefault(props.windowSize), cellsAroundViewport, this.__getFrameMetricsApprox, this._scrollMetrics);
(0, _invariant.default)(newCellsAroundViewport.last < getItemCount(data), 'computeWindowedRenderLimits() should return range in-bounds');
}
if (this._nestedChildLists.size() > 0) {
// If some cell in the new state has a child list in it, we should only render
// up through that item, so that we give that list a chance to render.
// Otherwise there's churn from multiple child lists mounting and un-mounting
// their items.
// Will this prevent rendering if the nested list doesn't realize the end?
var childIdx = this._findFirstChildWithMore(newCellsAroundViewport.first, newCellsAroundViewport.last);
newCellsAroundViewport.last = childIdx !== null && childIdx !== void 0 ? childIdx : newCellsAroundViewport.last;
}
return newCellsAroundViewport;
}
_findFirstChildWithMore(first, last) {
for (var ii = first; ii <= last; ii++) {
var cellKeyForIndex = this._indicesToKeys.get(ii);
if (cellKeyForIndex != null && this._nestedChildLists.anyInCell(cellKeyForIndex, childList => childList.hasMore())) {
return ii;
}
}
return null;
}
componentDidMount() {
if (this._isNestedWithSameOrientation()) {
this.context.registerAsNestedChild({
ref: this,
cellKey: this.context.cellKey
});
}
// REACT-NATIVE-WEB patch to preserve during future RN merges: Support inverted wheel scroller.
this.setupWebWheelHandler();
}
componentWillUnmount() {
if (this._isNestedWithSameOrientation()) {
this.context.unregisterAsNestedChild({
ref: this
});
}
this._updateCellsToRenderBatcher.dispose({
abort: true
});
this._viewabilityTuples.forEach(tuple => {
tuple.viewabilityHelper.dispose();
});
this._fillRateHelper.deactivateAndFlush();
// REACT-NATIVE-WEB patch to preserve during future RN merges: Support inverted wheel scroller.
this.teardownWebWheelHandler();
}
// REACT-NATIVE-WEB patch to preserve during future RN merges: Support inverted wheel scroller.
setupWebWheelHandler() {
if (this._scrollRef && this._scrollRef.getScrollableNode) {
this._scrollRef.getScrollableNode().addEventListener('wheel', this.invertedWheelEventHandler, {
passive: true
});
} else {
setTimeout(() => this.setupWebWheelHandler(), 50);
return;
}
}
// REACT-NATIVE-WEB patch to preserve during future RN merges: Support inverted wheel scroller.
teardownWebWheelHandler() {
if (this._scrollRef && this._scrollRef.getScrollableNode) {
this._scrollRef.getScrollableNode().removeEventListener('wheel', this.invertedWheelEventHandler);
}
}
static getDerivedStateFromProps(newProps, prevState) {
// first and last could be stale (e.g. if a new, shorter items props is passed in), so we make
// sure we're rendering a reasonable range here.
var itemCount = newProps.getItemCount(newProps.data);
if (itemCount === prevState.renderMask.numCells()) {
return prevState;
}
var constrainedCells = VirtualizedList._constrainToItemCount(prevState.cellsAroundViewport, newProps);
return {
cellsAroundViewport: constrainedCells,
renderMask: VirtualizedList._createRenderMask(newProps, constrainedCells)
};
}
_pushCells(cells, stickyHeaderIndices, stickyIndicesFromProps, first, last, inversionStyle) {
var _this = this;
var _this$props4 = this.props,
CellRendererComponent = _this$props4.CellRendererComponent,
ItemSeparatorComponent = _this$props4.ItemSeparatorComponent,
ListHeaderComponent = _this$props4.ListHeaderComponent,
ListItemComponent = _this$props4.ListItemComponent,
data = _this$props4.data,
debug = _this$props4.debug,
getItem = _this$props4.getItem,
getItemCount = _this$props4.getItemCount,
getItemLayout = _this$props4.getItemLayout,
horizontal = _this$props4.horizontal,
renderItem = _this$props4.renderItem;
var stickyOffset = ListHeaderComponent ? 1 : 0;
var end = getItemCount(data) - 1;
var prevCellKey;
last = Math.min(end, last);
var _loop = function _loop() {
var item = getItem(data, ii);
var key = _this._keyExtractor(item, ii, _this.props);
_this._indicesToKeys.set(ii, key);
if (stickyIndicesFromProps.has(ii + stickyOffset)) {
stickyHeaderIndices.push(cells.length);
}
var shouldListenForLayout = getItemLayout == null || debug || _this._fillRateHelper.enabled();
cells.push( /*#__PURE__*/React.createElement(_VirtualizedListCellRenderer.default, (0, _extends2.default)({
CellRendererComponent: CellRendererComponent,
ItemSeparatorComponent: ii < end ? ItemSeparatorComponent : undefined,
ListItemComponent: ListItemComponent,
cellKey: key,
horizontal: horizontal,
index: ii,
inversionStyle: inversionStyle,
item: item,
key: key,
prevCellKey: prevCellKey,
onUpdateSeparators: _this._onUpdateSeparators,
onCellFocusCapture: e => _this._onCellFocusCapture(key),
onUnmount: _this._onCellUnmount,
ref: _ref => {
_this._cellRefs[key] = _ref;
},
renderItem: renderItem
}, shouldListenForLayout && {
onCellLayout: _this._onCellLayout
})));
prevCellKey = key;
};
for (var ii = first; ii <= last; ii++) {
_loop();
}
}
static _constrainToItemCount(cells, props) {
var itemCount = props.getItemCount(props.data);
var last = Math.min(itemCount - 1, cells.last);
var maxToRenderPerBatch = maxToRenderPerBatchOrDefault(props.maxToRenderPerBatch);
return {
first: (0, _clamp.default)(0, itemCount - 1 - maxToRenderPerBatch, cells.first),
last
};
}
_isNestedWithSameOrientation() {
var nestedContext = this.context;
return !!(nestedContext && !!nestedContext.horizontal === horizontalOrDefault(this.props.horizontal));
}
_keyExtractor(item, index, props
// $FlowFixMe[missing-local-annot]
) {
if (props.keyExtractor != null) {
return props.keyExtractor(item, index);
}
var key = (0, _VirtualizeUtils.keyExtractor)(item, index);
if (key === String(index)) {
_usedIndexForKey = true;
if (item.type && item.type.displayName) {
_keylessItemComponentName = item.type.displayName;
}
}
return key;
}
render() {
this._checkProps(this.props);
var _this$props5 = this.props,
ListEmptyComponent = _this$props5.ListEmptyComponent,
ListFooterComponent = _this$props5.ListFooterComponent,
ListHeaderComponent = _this$props5.ListHeaderComponent;
var _this$props6 = this.props,
data = _this$props6.data,
horizontal = _this$props6.horizontal;
var inversionStyle = this.props.inverted ? horizontalOrDefault(this.props.horizontal) ? styles.horizontallyInverted : styles.verticallyInverted : null;
var cells = [];
var stickyIndicesFromProps = new Set(this.props.stickyHeaderIndices);
var stickyHeaderIndices = [];
// 1. Add cell for ListHeaderComponent
if (ListHeaderComponent) {
if (stickyIndicesFromProps.has(0)) {
stickyHeaderIndices.push(0);
}
var _element = /*#__PURE__*/React.isValidElement(ListHeaderComponent) ? ListHeaderComponent :
/*#__PURE__*/
// $FlowFixMe[not-a-component]
// $FlowFixMe[incompatible-type-arg]
React.createElement(ListHeaderComponent, null);
cells.push( /*#__PURE__*/React.createElement(_VirtualizedListContext.VirtualizedListCellContextProvider, {
cellKey: this._getCellKey() + '-header',
key: "$header"
}, /*#__PURE__*/React.createElement(_View.default, {
onLayout: this._onLayoutHeader,
style: [inversionStyle, this.props.ListHeaderComponentStyle]
},
// $FlowFixMe[incompatible-type] - Typing ReactNativeComponent revealed errors
_element)));
}
// 2a. Add a cell for ListEmptyComponent if applicable
var itemCount = this.props.getItemCount(data);
if (itemCount === 0 && ListEmptyComponent) {
var _element2 = /*#__PURE__*/React.isValidElement(ListEmptyComponent) ? ListEmptyComponent :
/*#__PURE__*/
// $FlowFixMe[not-a-component]
// $FlowFixMe[incompatible-type-arg]
React.createElement(ListEmptyComponent, null);
cells.push( /*#__PURE__*/React.createElement(_VirtualizedListContext.VirtualizedListCellContextProvider, {
cellKey: this._getCellKey() + '-empty',
key: "$empty"
}, /*#__PURE__*/React.cloneElement(_element2, {
onLayout: event => {
this._onLayoutEmpty(event);
if (_element2.props.onLayout) {
_element2.props.onLayout(event);
}
},
style: [inversionStyle, _element2.props.style]
})));
}
// 2b. Add cells and spacers for each item
if (itemCount > 0) {
_usedIndexForKey = false;
_keylessItemComponentName = '';
var spacerKey = this._getSpacerKey(!horizontal);
var renderRegions = this.state.renderMask.enumerateRegions();
var lastSpacer = findLastWhere(renderRegions, r => r.isSpacer);
for (var _iterator = (0, _createForOfIteratorHelperLoose2.default)(renderRegions), _step; !(_step = _iterator()).done;) {
var section = _step.value;
if (section.isSpacer) {
// Legacy behavior is to avoid spacers when virtualization is
// disabled (including head spacers on initial render).
if (this.props.disableVirtualization) {
continue;
}
// Without getItemLayout, we limit our tail spacer to the _highestMeasuredFrameIndex to
// prevent the user for hyperscrolling into un-measured area because otherwise content will
// likely jump around as it renders in above the viewport.
var isLastSpacer = section === lastSpacer;
var constrainToMeasured = isLastSpacer && !this.props.getItemLayout;
var last = constrainToMeasured ? (0, _clamp.default)(section.first - 1, section.last, this._highestMeasuredFrameIndex) : section.last;
var firstMetrics = this.__getFrameMetricsApprox(section.first, this.props);
var lastMetrics = this.__getFrameMetricsApprox(last, this.props);
var spacerSize = lastMetrics.offset + lastMetrics.length - firstMetrics.offset;
cells.push( /*#__PURE__*/React.createElement(_View.default, {
key: "$spacer-" + section.first,
style: {
[spacerKey]: spacerSize
}
}));
} else {
this._pushCells(cells, stickyHeaderIndices, stickyIndicesFromProps, section.first, section.last, inversionStyle);
}
}
if (!this._hasWarned.keys && _usedIndexForKey) {
console.warn('VirtualizedList: missing keys for items, make sure to specify a key or id property on each ' + 'item or provide a custom keyExtractor.', _keylessItemComponentName);
this._hasWarned.keys = true;
}
}
// 3. Add cell for ListFooterComponent
if (ListFooterComponent) {
var _element3 = /*#__PURE__*/React.isValidElement(ListFooterComponent) ? ListFooterComponent :
/*#__PURE__*/
// $FlowFixMe[not-a-component]
// $FlowFixMe[incompatible-type-arg]
React.createElement(ListFooterComponent, null);
cells.push( /*#__PURE__*/React.createElement(_VirtualizedListContext.VirtualizedListCellContextProvider, {
cellKey: this._getFooterCellKey(),
key: "$footer"
}, /*#__PURE__*/React.createElement(_View.default, {
onLayout: this._onLayoutFooter,
style: [inversionStyle, this.props.ListFooterComponentStyle]
},
// $FlowFixMe[incompatible-type] - Typing ReactNativeComponent revealed errors
_element3)));
}
// 4. Render the ScrollView
var scrollProps = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, this.props), {}, {
onContentSizeChange: this._onContentSizeChange,
onLayout: this._onLayout,
onScroll: this._onScroll,
onScrollBeginDrag: this._onScrollBeginDrag,
onScrollEndDrag: this._onScrollEndDrag,
onMomentumScrollBegin: this._onMomentumScrollBegin,
onMomentumScrollEnd: this._onMomentumScrollEnd,
scrollEventThrottle: scrollEventThrottleOrDefault(this.props.scrollEventThrottle),
// TODO: Android support
invertStickyHeaders: this.props.invertStickyHeaders !== undefined ? this.props.invertStickyHeaders : this.props.inverted,
stickyHeaderIndices,
style: inversionStyle ? [inversionStyle, this.props.style] : this.props.style
});
this._hasMore = this.state.cellsAroundViewport.last < itemCount - 1;
var innerRet = /*#__PURE__*/React.createElement(_VirtualizedListContext.VirtualizedListContextProvider, {
value: {
cellKey: null,
getScrollMetrics: this._getScrollMetrics,
horizontal: horizontalOrDefault(this.props.horizontal),
getOutermostParentListRef: this._getOutermostParentListRef,
registerAsNestedChild: this._registerAsNestedChild,
unregisterAsNestedChild: this._unregisterAsNestedChild
}
}, /*#__PURE__*/React.cloneElement((this.props.renderScrollComponent || this._defaultRenderScrollComponent)(scrollProps), {
ref: this._captureScrollRef
}, cells));
var ret = innerRet;
/* https://github.com/necolas/react-native-web/issues/2239: Re-enable when ScrollView.Context.Consumer is available.
if (__DEV__) {
ret = (
<ScrollView.Context.Consumer>
{scrollContext => {
if (
scrollContext != null &&
!scrollContext.horizontal ===
!horizontalOrDefault(this.props.horizontal) &&
!this._hasWarned.nesting &&
this.context == null &&
this.props.scrollEnabled !== false
) {
// TODO (T46547044): use React.warn once 16.9 is sync'd: https://github.com/facebook/react/pull/15170
console.error(
'VirtualizedLists should never be nested inside plain ScrollViews with the same ' +
'orientation because it can break windowing and other functionality - use another ' +
'VirtualizedList-backed container instead.',
);
this._hasWarned.nesting = true;
}
return innerRet;
}}
</ScrollView.Context.Consumer>
);
}*/
if (this.props.debug) {
return /*#__PURE__*/React.createElement(_View.default, {
style: styles.debug
}, ret, this._renderDebugOverlay());
} else {
return ret;
}
}
componentDidUpdate(prevProps) {
var _this$props7 = this.props,
data = _this$props7.data,
extraData = _this$props7.extraData;
if (data !== prevProps.data || extraData !== prevProps.extraData) {
// clear the viewableIndices cache to also trigger
// the onViewableItemsChanged callback with the new data
this._viewabilityTuples.forEach(tuple => {
tuple.viewabilityHelper.resetViewableIndices();
});
}
// The `this._hiPriInProgress` is guaranteeing a hiPri cell update will only happen
// once per fiber update. The `_scheduleCellsToRenderUpdate` will set it to true
// if a hiPri update needs to perform. If `componentDidUpdate` is triggered with
// `this._hiPriInProgress=true`, means it's triggered by the hiPri update. The
// `_scheduleCellsToRenderUpdate` will check this condition and not perform
// another hiPri update.
var hiPriInProgress = this._hiPriInProgress;
this._scheduleCellsToRenderUpdate();
// Make sure setting `this._hiPriInProgress` back to false after `componentDidUpdate`
// is triggered with `this._hiPriInProgress = true`
if (hiPriInProgress) {
this._hiPriInProgress = false;
}
}
_computeBlankness() {
this._fillRateHelper.computeBlankness(this.props, this.state.cellsAroundViewport, this._scrollMetrics);
}
/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's
* LTI update could not be added via codemod */
_onCellFocusCapture(cellKey) {
this._lastFocusedCellKey = cellKey;
this._updateCellsToRender();
}
_triggerRemeasureForChildListsInCell(cellKey) {
this._nestedChildLists.forEachInCell(cellKey, childList => {
childList.measureLayoutRelativeToContainingList();
});
}
measureLayoutRelativeToContainingList() {
// TODO (T35574538): findNodeHandle sometimes crashes with "Unable to find
// node on an unmounted component" during scrolling
try {
if (!this._scrollRef) {
return;
}
// We are assuming that getOutermostParentListRef().getScrollRef()
// is a non-null reference to a ScrollView
this._scrollRef.measureLayout(this.context.getOutermostParentListRef().getScrollRef(), (x, y, width, height) => {
this._offsetFromParentVirtualizedList = this._selectOffset({
x,
y
});
this._scrollMetrics.contentLength = this._selectLength({
width,
height
});
var scrollMetrics = this._convertParentScrollMetrics(this.context.getScrollMetrics());
var metricsChanged = this._scrollMetrics.visibleLength !== scrollMetrics.visibleLength || this._scrollMetrics.offset !== scrollMetrics.offset;
if (metricsChanged) {
this._scrollMetrics.visibleLength = scrollMetrics.visibleLength;
this._scrollMetrics.offset = scrollMetrics.offset;
// If metrics of the scrollView changed, then we triggered remeasure for child list
// to ensure VirtualizedList has the right information.
this._nestedChildLists.forEach(childList => {
childList.measureLayoutRelativeToContainingList();
});
}
}, error => {
console.warn("VirtualizedList: Encountered an error while measuring a list's" + ' offset from its containing VirtualizedList.');
});
} catch (error) {
console.warn('measureLayoutRelativeToContainingList threw an error', error.stack);
}
}
_getFooterCellKey() {
return this._getCellKey() + '-footer';
}
// $FlowFixMe[missing-local-annot]
_renderDebugOverlay() {
var normalize = this._scrollMetrics.visibleLength / (this._scrollMetrics.contentLength || 1);
var framesInLayout = [];
var itemCount = this.props.getItemCount(this.props.data);
for (var ii = 0; ii < itemCount; ii++) {
var frame = this.__getFrameMetricsApprox(ii, this.props);
/* $FlowFixMe[prop-missing] (>=0.68.0 site=react_native_fb) This comment
* suppresses an error found when Flow v0.68 was deployed. To see the
* error delete this comment and run Flow. */
if (frame.inLayout) {
framesInLayout.push(frame);
}
}
var windowTop = this.__getFrameMetricsApprox(this.state.cellsAroundViewport.first, this.props).offset;
var frameLast = this.__getFrameMetricsApprox(this.state.cellsAroundViewport.last, this.props);
var windowLen = frameLast.offset + frameLast.length - windowTop;
var visTop = this._scrollMetrics.offset;
var visLen = this._scrollMetrics.visibleLength;
return /*#__PURE__*/React.createElement(_View.default, {
style: [styles.debugOverlayBase, styles.debugOverlay]
}, framesInLayout.map((f, ii) => /*#__PURE__*/React.createElement(_View.default, {
key: 'f' + ii,
style: [styles.debugOverlayBase, styles.debugOverlayFrame, {
top: f.offset * normalize,
height: f.length * normalize
}]
})), /*#__PURE__*/React.createElement(_View.default, {
style: [styles.debugOverlayBase, styles.debugOverlayFrameLast, {
top: windowTop * normalize,
height: windowLen * normalize
}]
}), /*#__PURE__*/React.createElement(_View.default, {
style: [styles.debugOverlayBase, styles.debugOverlayFrameVis, {
top: visTop * normalize,
height: visLen * normalize
}]
}));
}
_selectLength(metrics) {
return !horizontalOrDefault(this.props.horizontal) ? metrics.height : metrics.width;
}
_selectOffset(metrics) {
return !horizontalOrDefault(this.props.horizontal) ? metrics.y : metrics.x;
}
_maybeCallOnEdgeReached() {
var _this$props8 = this.props,
data = _this$props8.data,
getItemCount = _this$props8.getItemCount,
onStartReached = _this$props8.onStartReached,
onStartReachedThreshold = _this$props8.onStartReachedThreshold,
onEndReached = _this$props8.onEndReached,
onEndReachedThreshold = _this$props8.onEndReachedThreshold,
initialScrollIndex = _this$props8.initialScrollIndex;
var _this$_scrollMetrics2 = this._scrollMetrics,
contentLength = _this$_scrollMetrics2.contentLength,
visibleLength = _this$_scrollMetrics2.visibleLength,
offset = _this$_scrollMetrics2.offset;
var distanceFromStart = offset;
var distanceFromEnd = contentLength - visibleLength - offset;
// Especially when oERT is zero it's necessary to 'floor' very small distance values to be 0
// since debouncing causes us to not fire this event for every single "pixel" we scroll and can thus
// be at the edge of the list with a distance approximating 0 but not quite there.
if (distanceFromStart < ON_EDGE_REACHED_EPSILON) {
distanceFromStart = 0;
}
if (distanceFromEnd < ON_EDGE_REACHED_EPSILON) {
distanceFromEnd = 0;
}
// TODO: T121172172 Look into why we're "defaulting" to a threshold of 2px
// when oERT is not present (different from 2 viewports used elsewhere)
var DEFAULT_THRESHOLD_PX = 2;
var startThreshold = onStartReachedThreshold != null ? onStartReachedThreshold * visibleLength : DEFAULT_THRESHOLD_PX;
var endThreshold = onEndReachedThreshold != null ? onEndReachedThreshold * visibleLength : DEFAULT_THRESHOLD_PX;
var isWithinStartThreshold = distanceFromStart <= startThreshold;
var isWithinEndThreshold = distanceFromEnd <= endThreshold;
// First check if the user just scrolled within the end threshold
// and call onEndReached only once for a given content length,
// and only if onStartReached is not being executed
if (onEndReached && this.state.cellsAroundViewport.last === getItemCount(data) - 1 && isWithinEndThreshold && this._scrollMetrics.contentLength !== this._sentEndForContentLength) {
this._sentEndForContentLength = this._scrollMetrics.contentLength;
onEndReached({
distanceFromEnd
});
}
// Next check if the user just scrolled within the start threshold
// and call onStartReached only once for a given content length,
// and only if onEndReached is not being executed
else if (onStartReached != null && this.state.cellsAroundViewport.first === 0 && isWithinStartThreshold && this._scrollMetrics.contentLength !== this._sentStartForContentLength) {
// On initial mount when using initialScrollIndex the offset will be 0 initially
// and will trigger an unexpected onStartReached. To avoid this we can use
// timestamp to differentiate between the initial scroll metrics and when we actually
// received the first scroll event.
if (!initialScrollIndex || this._scrollMetrics.timestamp !== 0) {
this._sentStartForContentLength = this._scrollMetrics.contentLength;
onStartReached({
distanceFromStart
});
}
}
// If the user scrolls away from the start or end and back again,
// cause onStartReached or onEndReached to be triggered again
else {
this._sentStartForContentLength = isWithinStartThreshold ? this._sentStartForContentLength : 0;
this._sentEndForContentLength = isWithinEndThreshold ? this._sentEndForContentLength : 0;
}
}
_scheduleCellsToRenderUpdate() {
var _this$state$cellsArou = this.state.cellsAroundViewport,
first = _this$state$cellsArou.first,
last = _this$state$cellsArou.last;
var _this$_scrollMetrics3 = this._scrollMetrics,
offset = _this$_scrollMetrics3.offset,
visibleLength = _this$_scrollMetrics3.visibleLength,
velocity = _this$_scrollMetrics3.velocity;
var itemCount = this.props.getItemCount(this.props.data);
var hiPri = false;
var onStartReachedThreshold = onStartReachedThresholdOrDefault(this.props.onStartReachedThreshold);
var onEndReachedThreshold = onEndReachedThresholdOrDefault(this.props.onEndReachedThreshold);
// Mark as high priority if we're close to the start of the first item
// But only if there are items before the first rendered item
if (first > 0) {
var distTop = offset - this.__getFrameMetricsApprox(first, this.props).offset;
hiPri = distTop < 0 || velocity < -2 && distTop < getScrollingThreshold(onStartReachedThreshold, visibleLength);
}
// Mark as high priority if we're close to the end of the last item
// But only if there are items after the last rendered item
if (!hiPri && last >= 0 && last < itemCount - 1) {
var distBottom = this.__getFrameMetricsApprox(last, this.props).offset - (offset + visibleLength);
hiPri = distBottom < 0 || velocity > 2 && distBottom < getScrollingThreshold(onEndReachedThreshold, visibleLength);
}
// Only trigger high-priority updates if we've actually rendered cells,
// and with that size estimate, accurately compute how many cells we should render.
// Otherwise, it would just render as many cells as it can (of zero dimension),
// each time through attempting to render more (limited by maxToRenderPerBatch),
// starving the renderer from actually laying out the objects and computing _averageCellLength.
// If this is triggered in an `componentDidUpdate` followed by a hiPri cellToRenderUpdate
// We shouldn't do another hipri cellToRenderUpdate
if (hiPri && (this._averageCellLength || this.props.getItemLayout) && !this._hiPriInProgress) {
this._hiPriInProgress = true;
// Don't worry about interactions when scrolling quickly; focus on filling content as fast
// as possible.
this._updateCellsToRenderBatcher.dispose({
abort: true
});
this._updateCellsToRender();
return;
} else {
this._updateCellsToRenderBatcher.schedule();
}
}
_updateViewableItems(props, cellsAroundViewport) {
this._viewabilityTuples.forEach(tuple => {
tuple.viewabilityHelper.onUpdate(props, this._scrollMetrics.offset, this._scrollMetrics.visibleLength, this._getFrameMetrics, this._createViewToken, tuple.onViewableItemsChanged, cellsAroundViewport);
});
}
}
VirtualizedList.contextType = _VirtualizedListContext.VirtualizedListContext;
var styles = _StyleSheet.default.create({
verticallyInverted: {
transform: 'scaleY(-1)'
},
horizontallyInverted: {
transform: 'scaleX(-1)'
},
debug: {
flex: 1
},
debugOverlayBase: {
position: 'absolute',
top: 0,
right: 0
},
debugOverlay: {
bottom: 0,
width: 20,
borderColor: 'blue',
borderWidth: 1
},
debugOverlayFrame: {
left: 0,
backgroundColor: 'orange'
},
debugOverlayFrameLast: {
left: 0,
borderColor: 'green',
borderWidth: 2
},
debugOverlayFrameVis: {
left: 0,
borderColor: 'red',
borderWidth: 2
}
});
var _default = VirtualizedList;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/VirtualizedSectionList/index.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _createForOfIteratorHelperLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/createForOfIteratorHelperLoose"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _View = _interopRequireDefault(require("../../../exports/View"));
var _VirtualizedList = _interopRequireDefault(require("../VirtualizedList"));
var _VirtualizeUtils = require("../VirtualizeUtils");
var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));
var React = _interopRequireWildcard(require("react"));
var _excluded = ["ItemSeparatorComponent", "SectionSeparatorComponent", "renderItem", "renderSectionFooter", "renderSectionHeader", "sections", "stickySectionHeadersEnabled"];
/**
* Right now this just flattens everything into one list and uses VirtualizedList under the
* hood. The only operation that might not scale well is concatting the data arrays of all the
* sections when new props are received, which should be plenty fast for up to ~10,000 items.
*/
class VirtualizedSectionList extends React.PureComponent {
constructor() {
super(...arguments);
this._keyExtractor = (item, index) => {
var info = this._subExtractor(index);
return info && info.key || String(index);
};
this._convertViewable = viewable => {
var _info$index;
(0, _invariant.default)(viewable.index != null, 'Received a broken ViewToken');
var info = this._subExtractor(viewable.index);
if (!info) {
return null;
}
var keyExtractorWithNullableIndex = info.section.keyExtractor;
var keyExtractorWithNonNullableIndex = this.props.keyExtractor || _VirtualizeUtils.keyExtractor;
var key = keyExtractorWithNullableIndex != null ? keyExtractorWithNullableIndex(viewable.item, info.index) : keyExtractorWithNonNullableIndex(viewable.item, (_info$index = info.index) !== null && _info$index !== void 0 ? _info$index : 0);
return (0, _objectSpread2.default)((0, _objectSpread2.default)({}, viewable), {}, {
index: info.index,
key,
section: info.section
});
};
this._onViewableItemsChanged = _ref => {
var viewableItems = _ref.viewableItems,
changed = _ref.changed;
var onViewableItemsChanged = this.props.onViewableItemsChanged;
if (onViewableItemsChanged != null) {
onViewableItemsChanged({
viewableItems: viewableItems.map(this._convertViewable, this).filter(Boolean),
changed: changed.map(this._convertViewable, this).filter(Boolean)
});
}
};
this._renderItem = listItemCount =>
// eslint-disable-next-line react/no-unstable-nested-components
_ref2 => {
var item = _ref2.item,
index = _ref2.index;
var info = this._subExtractor(index);
if (!info) {
return null;
}
var infoIndex = info.index;
if (infoIndex == null) {
var section = info.section;
if (info.header === true) {
var renderSectionHeader = this.props.renderSectionHeader;
return renderSectionHeader ? renderSectionHeader({
section
}) : null;
} else {
var renderSectionFooter = this.props.renderSectionFooter;
return renderSectionFooter ? renderSectionFooter({
section
}) : null;
}
} else {
var renderItem = info.section.renderItem || this.props.renderItem;
var SeparatorComponent = this._getSeparatorComponent(index, info, listItemCount);
(0, _invariant.default)(renderItem, 'no renderItem!');
return /*#__PURE__*/React.createElement(ItemWithSeparator, {
SeparatorComponent: SeparatorComponent,
LeadingSeparatorComponent: infoIndex === 0 ? this.props.SectionSeparatorComponent : undefined,
cellKey: info.key,
index: infoIndex,
item: item,
leadingItem: info.leadingItem,
leadingSection: info.leadingSection,
prevCellKey: (this._subExtractor(index - 1) || {}).key
// Callback to provide updateHighlight for this item
,
setSelfHighlightCallback: this._setUpdateHighlightFor,
setSelfUpdatePropsCallback: this._setUpdatePropsFor
// Provide child ability to set highlight/updateProps for previous item using prevCellKey
,
updateHighlightFor: this._updateHighlightFor,
updatePropsFor: this._updatePropsFor,
renderItem: renderItem,
section: info.section,
trailingItem: info.trailingItem,
trailingSection: info.trailingSection,
inverted: !!this.props.inverted
});
}
};
this._updatePropsFor = (cellKey, value) => {
var updateProps = this._updatePropsMap[cellKey];
if (updateProps != null) {
updateProps(value);
}
};
this._updateHighlightFor = (cellKey, value) => {
var updateHighlight = this._updateHighlightMap[cellKey];
if (updateHighlight != null) {
updateHighlight(value);
}
};
this._setUpdateHighlightFor = (cellKey, updateHighlightFn) => {
if (updateHighlightFn != null) {
this._updateHighlightMap[cellKey] = updateHighlightFn;
} else {
// $FlowFixMe[prop-missing]
delete this._updateHighlightFor[cellKey];
}
};
this._setUpdatePropsFor = (cellKey, updatePropsFn) => {
if (updatePropsFn != null) {
this._updatePropsMap[cellKey] = updatePropsFn;
} else {
delete this._updatePropsMap[cellKey];
}
};
this._updateHighlightMap = {};
this._updatePropsMap = {};
this._captureRef = ref => {
this._listRef = ref;
};
}
scrollToLocation(params) {
var index = params.itemIndex;
for (var i = 0; i < params.sectionIndex; i++) {
index += this.props.getItemCount(this.props.sections[i].data) + 2;
}
var viewOffset = params.viewOffset || 0;
if (this._listRef == null) {
return;
}
if (params.itemIndex > 0 && this.props.stickySectionHeadersEnabled) {
var frame = this._listRef.__getFrameMetricsApprox(index - params.itemIndex, this._listRef.props);
viewOffset += frame.length;
}
var toIndexParams = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, params), {}, {
viewOffset,
index
});
// $FlowFixMe[incompatible-use]
this._listRef.scrollToIndex(toIndexParams);
}
getListRef() {
return this._listRef;
}
render() {
var _this$props = this.props,
ItemSeparatorComponent = _this$props.ItemSeparatorComponent,
SectionSeparatorComponent = _this$props.SectionSeparatorComponent,
_renderItem = _this$props.renderItem,
renderSectionFooter = _this$props.renderSectionFooter,
renderSectionHeader = _this$props.renderSectionHeader,
_sections = _this$props.sections,
stickySectionHeadersEnabled = _this$props.stickySectionHeadersEnabled,
passThroughProps = (0, _objectWithoutPropertiesLoose2.default)(_this$props, _excluded);
var listHeaderOffset = this.props.ListHeaderComponent ? 1 : 0;
var stickyHeaderIndices = this.props.stickySectionHeadersEnabled ? [] : undefined;
var itemCount = 0;
for (var _iterator = (0, _createForOfIteratorHelperLoose2.default)(this.props.sections), _step; !(_step = _iterator()).done;) {
var section = _step.value;
// Track the section header indices
if (stickyHeaderIndices != null) {
stickyHeaderIndices.push(itemCount + listHeaderOffset);
}
// Add two for the section header and footer.
itemCount += 2;
itemCount += this.props.getItemCount(section.data);
}
var renderItem = this._renderItem(itemCount);
return /*#__PURE__*/React.createElement(_VirtualizedList.default, (0, _extends2.default)({}, passThroughProps, {
keyExtractor: this._keyExtractor,
stickyHeaderIndices: stickyHeaderIndices,
renderItem: renderItem,
data: this.props.sections,
getItem: (sections, index) => this._getItem(this.props, sections, index),
getItemCount: () => itemCount,
onViewableItemsChanged: this.props.onViewableItemsChanged ? this._onViewableItemsChanged : undefined,
ref: this._captureRef
}));
}
_getItem(props, sections, index) {
if (!sections) {
return null;
}
var itemIdx = index - 1;
for (var i = 0; i < sections.length; i++) {
var section = sections[i];
var sectionData = section.data;
var itemCount = props.getItemCount(sectionData);
if (itemIdx === -1 || itemIdx === itemCount) {
// We intend for there to be overflow by one on both ends of the list.
// This will be for headers and footers. When returning a header or footer
// item the section itself is the item.
return section;
} else if (itemIdx < itemCount) {
// If we are in the bounds of the list's data then return the item.
return props.getItem(sectionData, itemIdx);
} else {
itemIdx -= itemCount + 2; // Add two for the header and footer
}
}
return null;
}
// $FlowFixMe[missing-local-annot]
_subExtractor(index) {
var itemIndex = index;
var _this$props2 = this.props,
getItem = _this$props2.getItem,
getItemCount = _this$props2.getItemCount,
keyExtractor = _this$props2.keyExtractor,
sections = _this$props2.sections;
for (var i = 0; i < sections.length; i++) {
var section = sections[i];
var sectionData = section.data;
var key = section.key || String(i);
itemIndex -= 1; // The section adds an item for the header
if (itemIndex >= getItemCount(sectionData) + 1) {
itemIndex -= getItemCount(sectionData) + 1; // The section adds an item for the footer.
} else if (itemIndex === -1) {
return {
section,
key: key + ':header',
index: null,
header: true,
trailingSection: sections[i + 1]
};
} else if (itemIndex === getItemCount(sectionData)) {
return {
section,
key: key + ':footer',
index: null,
header: false,
trailingSection: sections[i + 1]
};
} else {
var extractor = section.keyExtractor || keyExtractor || _VirtualizeUtils.keyExtractor;
return {
section,
key: key + ':' + extractor(getItem(sectionData, itemIndex), itemIndex),
index: itemIndex,
leadingItem: getItem(sectionData, itemIndex - 1),
leadingSection: sections[i - 1],
trailingItem: getItem(sectionData, itemIndex + 1),
trailingSection: sections[i + 1]
};
}
}
}
_getSeparatorComponent(index, info, listItemCount) {
info = info || this._subExtractor(index);
if (!info) {
return null;
}
var ItemSeparatorComponent = info.section.ItemSeparatorComponent || this.props.ItemSeparatorComponent;
var SectionSeparatorComponent = this.props.SectionSeparatorComponent;
var isLastItemInList = index === listItemCount - 1;
var isLastItemInSection = info.index === this.props.getItemCount(info.section.data) - 1;
if (SectionSeparatorComponent && isLastItemInSection) {
return SectionSeparatorComponent;
}
if (ItemSeparatorComponent && !isLastItemInSection && !isLastItemInList) {
return ItemSeparatorComponent;
}
return null;
}
}
function ItemWithSeparator(props) {
var LeadingSeparatorComponent = props.LeadingSeparatorComponent,
SeparatorComponent = props.SeparatorComponent,
cellKey = props.cellKey,
prevCellKey = props.prevCellKey,
setSelfHighlightCallback = props.setSelfHighlightCallback,
updateHighlightFor = props.updateHighlightFor,
setSelfUpdatePropsCallback = props.setSelfUpdatePropsCallback,
updatePropsFor = props.updatePropsFor,
item = props.item,
index = props.index,
section = props.section,
inverted = props.inverted;
var _React$useState = React.useState(false),
leadingSeparatorHiglighted = _React$useState[0],
setLeadingSeparatorHighlighted = _React$useState[1];
var _React$useState2 = React.useState(false),
separatorHighlighted = _React$useState2[0],
setSeparatorHighlighted = _React$useState2[1];
var _React$useState3 = React.useState({
leadingItem: props.leadingItem,
leadingSection: props.leadingSection,
section: props.section,
trailingItem: props.item,
trailingSection: props.trailingSection
}),
leadingSeparatorProps = _React$useState3[0],
setLeadingSeparatorProps = _React$useState3[1];
var _React$useState4 = React.useState({
leadingItem: props.item,
leadingSection: props.leadingSection,
section: props.section,
trailingItem: props.trailingItem,
trailingSection: props.trailingSection
}),
separatorProps = _React$useState4[0],
setSeparatorProps = _React$useState4[1];
React.useEffect(() => {
setSelfHighlightCallback(cellKey, setSeparatorHighlighted);
// $FlowFixMe[incompatible-call]
setSelfUpdatePropsCallback(cellKey, setSeparatorProps);
return () => {
setSelfUpdatePropsCallback(cellKey, null);
setSelfHighlightCallback(cellKey, null);
};
}, [cellKey, setSelfHighlightCallback, setSeparatorProps, setSelfUpdatePropsCallback]);
var separators = {
highlight: () => {
setLeadingSeparatorHighlighted(true);
setSeparatorHighlighted(true);
if (prevCellKey != null) {
updateHighlightFor(prevCellKey, true);
}
},
unhighlight: () => {
setLeadingSeparatorHighlighted(false);
setSeparatorHighlighted(false);
if (prevCellKey != null) {
updateHighlightFor(prevCellKey, false);
}
},
updateProps: (select, newProps) => {
if (select === 'leading') {
if (LeadingSeparatorComponent != null) {
setLeadingSeparatorProps((0, _objectSpread2.default)((0, _objectSpread2.default)({}, leadingSeparatorProps), newProps));
} else if (prevCellKey != null) {
// update the previous item's separator
updatePropsFor(prevCellKey, (0, _objectSpread2.default)((0, _objectSpread2.default)({}, leadingSeparatorProps), newProps));
}
} else if (select === 'trailing' && SeparatorComponent != null) {
setSeparatorProps((0, _objectSpread2.default)((0, _objectSpread2.default)({}, separatorProps), newProps));
}
}
};
var element = props.renderItem({
item,
index,
section,
separators
});
var leadingSeparator = LeadingSeparatorComponent != null && /*#__PURE__*/React.createElement(LeadingSeparatorComponent, (0, _extends2.default)({
highlighted: leadingSeparatorHiglighted
}, leadingSeparatorProps));
var separator = SeparatorComponent != null && /*#__PURE__*/React.createElement(SeparatorComponent, (0, _extends2.default)({
highlighted: separatorHighlighted
}, separatorProps));
return leadingSeparator || separator ? /*#__PURE__*/React.createElement(_View.default, null, inverted === false ? leadingSeparator : separator, element, inverted === false ? separator : leadingSeparator) : element;
}
/* $FlowFixMe[class-object-subtyping] added when improving typing for this
* parameters */
// $FlowFixMe[method-unbinding]
var _default = VirtualizedSectionList;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/deepDiffer/index.js
/**
* 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.
*
* @format
*
*/
'use strict';
/*
* @returns {bool} true if different, false if equal
*/
exports.__esModule = true;
exports.default = void 0;
var deepDiffer = function deepDiffer(one, two, maxDepth) {
if (maxDepth === void 0) {
maxDepth = -1;
}
if (maxDepth === 0) {
return true;
}
if (one === two) {
// Short circuit on identical object references instead of traversing them.
return false;
}
if (typeof one === 'function' && typeof two === 'function') {
// We consider all functions equal
return false;
}
if (typeof one !== 'object' || one === null) {
// Primitives can be directly compared
return one !== two;
}
if (typeof two !== 'object' || two === null) {
// We know they are different because the previous case would have triggered
// otherwise.
return true;
}
if (one.constructor !== two.constructor) {
return true;
}
if (Array.isArray(one)) {
// We know two is also an array because the constructors are equal
var len = one.length;
if (two.length !== len) {
return true;
}
for (var ii = 0; ii < len; ii++) {
if (deepDiffer(one[ii], two[ii], maxDepth - 1)) {
return true;
}
}
} else {
for (var key in one) {
if (deepDiffer(one[key], two[key], maxDepth - 1)) {
return true;
}
}
for (var twoKey in two) {
// The only case we haven't checked yet is keys that are in two but aren't
// in one, which means they are different.
if (one[twoKey] === undefined && two[twoKey] !== undefined) {
return true;
}
}
}
return false;
};
var _default = deepDiffer;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/infoLog/index.js
/**
* 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.
*
* @format
*
*/
'use strict';
/**
* Intentional info-level logging for clear separation from ad-hoc console debug logging.
*/
exports.__esModule = true;
exports.default = void 0;
function infoLog() {
return console.log(...arguments);
}
var _default = infoLog;
exports.default = _default;
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/dist/cjs/vendor/react-native/vendor/emitter/EventEmitter.js
"use strict";
exports.__esModule = true;
exports.default = void 0;
/**
* 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.
*
*
* @format
*/
/**
* EventEmitter manages listeners and publishes events to them.
*
* EventEmitter accepts a single type parameter that defines the valid events
* and associated listener argument(s).
*
* @example
*
* const emitter = new EventEmitter<{
* success: [number, string],
* error: [Error],
* }>();
*
* emitter.on('success', (statusCode, responseText) => {...});
* emitter.emit('success', 200, '...');
*
* emitter.on('error', error => {...});
* emitter.emit('error', new Error('Resource not found'));
*
*/
class EventEmitter {
constructor() {
this._registry = {};
}
/**
* Registers a listener that is called when the supplied event is emitted.
* Returns a subscription that has a `remove` method to undo registration.
*/
addListener(eventType, listener, context) {
var registrations = allocate(this._registry, eventType);
var registration = {
context,
listener,
remove() {
registrations.delete(registration);
}
};
registrations.add(registration);
return registration;
}
/**
* Emits the supplied event. Additional arguments supplied to `emit` will be
* passed through to each of the registered listeners.
*
* If a listener modifies the listeners registered for the same event, those
* changes will not be reflected in the current invocation of `emit`.
*/
emit(eventType) {
var registrations = this._registry[eventType];
if (registrations != null) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
for (var _i = 0, _arr = [...registrations]; _i < _arr.length; _i++) {
var registration = _arr[_i];
registration.listener.apply(registration.context, args);
}
}
}
/**
* Removes all registered listeners.
*/
removeAllListeners(eventType) {
if (eventType == null) {
this._registry = {};
} else {
delete this._registry[eventType];
}
}
/**
* Returns the number of registered listeners for the supplied event.
*/
listenerCount(eventType) {
var registrations = this._registry[eventType];
return registrations == null ? 0 : registrations.size;
}
}
exports.default = EventEmitter;
function allocate(registry, eventType) {
var registrations = registry[eventType];
if (registrations == null) {
registrations = new Set();
registry[eventType] = registrations;
}
return registrations;
}
module.exports = exports.default;
webpack://frontend-mybets/../../node_modules/react-native-web/node_modules/@react-native/normalize-colors/index.js
/**
* 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.
*
* @format
* @noflow
*/
/* eslint no-bitwise: 0 */
'use strict';
function normalizeColor(color) {
if (typeof color === 'number') {
if (color >>> 0 === color && color >= 0 && color <= 0xffffffff) {
return color;
}
return null;
}
if (typeof color !== 'string') {
return null;
}
const matchers = getMatchers();
let match;
// Ordered based on occurrences on Facebook codebase
if ((match = matchers.hex6.exec(color))) {
return parseInt(match[1] + 'ff', 16) >>> 0;
}
const colorFromKeyword = normalizeKeyword(color);
if (colorFromKeyword != null) {
return colorFromKeyword;
}
if ((match = matchers.rgb.exec(color))) {
return (
((parse255(match[1]) << 24) | // r
(parse255(match[2]) << 16) | // g
(parse255(match[3]) << 8) | // b
0x000000ff) >>> // a
0
);
}
if ((match = matchers.rgba.exec(color))) {
// rgba(R G B / A) notation
if (match[6] !== undefined) {
return (
((parse255(match[6]) << 24) | // r
(parse255(match[7]) << 16) | // g
(parse255(match[8]) << 8) | // b
parse1(match[9])) >>> // a
0
);
}
// rgba(R, G, B, A) notation
return (
((parse255(match[2]) << 24) | // r
(parse255(match[3]) << 16) | // g
(parse255(match[4]) << 8) | // b
parse1(match[5])) >>> // a
0
);
}
if ((match = matchers.hex3.exec(color))) {
return (
parseInt(
match[1] +
match[1] + // r
match[2] +
match[2] + // g
match[3] +
match[3] + // b
'ff', // a
16,
) >>> 0
);
}
// https://drafts.csswg.org/css-color-4/#hex-notation
if ((match = matchers.hex8.exec(color))) {
return parseInt(match[1], 16) >>> 0;
}
if ((match = matchers.hex4.exec(color))) {
return (
parseInt(
match[1] +
match[1] + // r
match[2] +
match[2] + // g
match[3] +
match[3] + // b
match[4] +
match[4], // a
16,
) >>> 0
);
}
if ((match = matchers.hsl.exec(color))) {
return (
(hslToRgb(
parse360(match[1]), // h
parsePercentage(match[2]), // s
parsePercentage(match[3]), // l
) |
0x000000ff) >>> // a
0
);
}
if ((match = matchers.hsla.exec(color))) {
// hsla(H S L / A) notation
if (match[6] !== undefined) {
return (
(hslToRgb(
parse360(match[6]), // h
parsePercentage(match[7]), // s
parsePercentage(match[8]), // l
) |
parse1(match[9])) >>> // a
0
);
}
// hsla(H, S, L, A) notation
return (
(hslToRgb(
parse360(match[2]), // h
parsePercentage(match[3]), // s
parsePercentage(match[4]), // l
) |
parse1(match[5])) >>> // a
0
);
}
if ((match = matchers.hwb.exec(color))) {
return (
(hwbToRgb(
parse360(match[1]), // h
parsePercentage(match[2]), // w
parsePercentage(match[3]), // b
) |
0x000000ff) >>> // a
0
);
}
return null;
}
function hue2rgb(p, q, t) {
if (t < 0) {
t += 1;
}
if (t > 1) {
t -= 1;
}
if (t < 1 / 6) {
return p + (q - p) * 6 * t;
}
if (t < 1 / 2) {
return q;
}
if (t < 2 / 3) {
return p + (q - p) * (2 / 3 - t) * 6;
}
return p;
}
function hslToRgb(h, s, l) {
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
const r = hue2rgb(p, q, h + 1 / 3);
const g = hue2rgb(p, q, h);
const b = hue2rgb(p, q, h - 1 / 3);
return (
(Math.round(r * 255) << 24) |
(Math.round(g * 255) << 16) |
(Math.round(b * 255) << 8)
);
}
function hwbToRgb(h, w, b) {
if (w + b >= 1) {
const gray = Math.round((w * 255) / (w + b));
return (gray << 24) | (gray << 16) | (gray << 8);
}
const red = hue2rgb(0, 1, h + 1 / 3) * (1 - w - b) + w;
const green = hue2rgb(0, 1, h) * (1 - w - b) + w;
const blue = hue2rgb(0, 1, h - 1 / 3) * (1 - w - b) + w;
return (
(Math.round(red * 255) << 24) |
(Math.round(green * 255) << 16) |
(Math.round(blue * 255) << 8)
);
}
const NUMBER = '[-+]?\\d*\\.?\\d+';
const PERCENTAGE = NUMBER + '%';
function call(...args) {
return '\\(\\s*(' + args.join(')\\s*,?\\s*(') + ')\\s*\\)';
}
function callWithSlashSeparator(...args) {
return (
'\\(\\s*(' +
args.slice(0, args.length - 1).join(')\\s*,?\\s*(') +
')\\s*/\\s*(' +
args[args.length - 1] +
')\\s*\\)'
);
}
function commaSeparatedCall(...args) {
return '\\(\\s*(' + args.join(')\\s*,\\s*(') + ')\\s*\\)';
}
let cachedMatchers;
function getMatchers() {
if (cachedMatchers === undefined) {
cachedMatchers = {
rgb: new RegExp('rgb' + call(NUMBER, NUMBER, NUMBER)),
rgba: new RegExp(
'rgba(' +
commaSeparatedCall(NUMBER, NUMBER, NUMBER, NUMBER) +
'|' +
callWithSlashSeparator(NUMBER, NUMBER, NUMBER, NUMBER) +
')',
),
hsl: new RegExp('hsl' + call(NUMBER, PERCENTAGE, PERCENTAGE)),
hsla: new RegExp(
'hsla(' +
commaSeparatedCall(NUMBER, PERCENTAGE, PERCENTAGE, NUMBER) +
'|' +
callWithSlashSeparator(NUMBER, PERCENTAGE, PERCENTAGE, NUMBER) +
')',
),
hwb: new RegExp('hwb' + call(NUMBER, PERCENTAGE, PERCENTAGE)),
hex3: /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
hex4: /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
hex6: /^#([0-9a-fA-F]{6})$/,
hex8: /^#([0-9a-fA-F]{8})$/,
};
}
return cachedMatchers;
}
function parse255(str) {
const int = parseInt(str, 10);
if (int < 0) {
return 0;
}
if (int > 255) {
return 255;
}
return int;
}
function parse360(str) {
const int = parseFloat(str);
return (((int % 360) + 360) % 360) / 360;
}
function parse1(str) {
const num = parseFloat(str);
if (num < 0) {
return 0;
}
if (num > 1) {
return 255;
}
return Math.round(num * 255);
}
function parsePercentage(str) {
// parseFloat conveniently ignores the final %
const int = parseFloat(str);
if (int < 0) {
return 0;
}
if (int > 100) {
return 1;
}
return int / 100;
}
function normalizeKeyword(name) {
// prettier-ignore
switch (name) {
case 'transparent': return 0x00000000;
// http://www.w3.org/TR/css3-color/#svg-color
case 'aliceblue': return 0xf0f8ffff;
case 'antiquewhite': return 0xfaebd7ff;
case 'aqua': return 0x00ffffff;
case 'aquamarine': return 0x7fffd4ff;
case 'azure': return 0xf0ffffff;
case 'beige': return 0xf5f5dcff;
case 'bisque': return 0xffe4c4ff;
case 'black': return 0x000000ff;
case 'blanchedalmond': return 0xffebcdff;
case 'blue': return 0x0000ffff;
case 'blueviolet': return 0x8a2be2ff;
case 'brown': return 0xa52a2aff;
case 'burlywood': return 0xdeb887ff;
case 'burntsienna': return 0xea7e5dff;
case 'cadetblue': return 0x5f9ea0ff;
case 'chartreuse': return 0x7fff00ff;
case 'chocolate': return 0xd2691eff;
case 'coral': return 0xff7f50ff;
case 'cornflowerblue': return 0x6495edff;
case 'cornsilk': return 0xfff8dcff;
case 'crimson': return 0xdc143cff;
case 'cyan': return 0x00ffffff;
case 'darkblue': return 0x00008bff;
case 'darkcyan': return 0x008b8bff;
case 'darkgoldenrod': return 0xb8860bff;
case 'darkgray': return 0xa9a9a9ff;
case 'darkgreen': return 0x006400ff;
case 'darkgrey': return 0xa9a9a9ff;
case 'darkkhaki': return 0xbdb76bff;
case 'darkmagenta': return 0x8b008bff;
case 'darkolivegreen': return 0x556b2fff;
case 'darkorange': return 0xff8c00ff;
case 'darkorchid': return 0x9932ccff;
case 'darkred': return 0x8b0000ff;
case 'darksalmon': return 0xe9967aff;
case 'darkseagreen': return 0x8fbc8fff;
case 'darkslateblue': return 0x483d8bff;
case 'darkslategray': return 0x2f4f4fff;
case 'darkslategrey': return 0x2f4f4fff;
case 'darkturquoise': return 0x00ced1ff;
case 'darkviolet': return 0x9400d3ff;
case 'deeppink': return 0xff1493ff;
case 'deepskyblue': return 0x00bfffff;
case 'dimgray': return 0x696969ff;
case 'dimgrey': return 0x696969ff;
case 'dodgerblue': return 0x1e90ffff;
case 'firebrick': return 0xb22222ff;
case 'floralwhite': return 0xfffaf0ff;
case 'forestgreen': return 0x228b22ff;
case 'fuchsia': return 0xff00ffff;
case 'gainsboro': return 0xdcdcdcff;
case 'ghostwhite': return 0xf8f8ffff;
case 'gold': return 0xffd700ff;
case 'goldenrod': return 0xdaa520ff;
case 'gray': return 0x808080ff;
case 'green': return 0x008000ff;
case 'greenyellow': return 0xadff2fff;
case 'grey': return 0x808080ff;
case 'honeydew': return 0xf0fff0ff;
case 'hotpink': return 0xff69b4ff;
case 'indianred': return 0xcd5c5cff;
case 'indigo': return 0x4b0082ff;
case 'ivory': return 0xfffff0ff;
case 'khaki': return 0xf0e68cff;
case 'lavender': return 0xe6e6faff;
case 'lavenderblush': return 0xfff0f5ff;
case 'lawngreen': return 0x7cfc00ff;
case 'lemonchiffon': return 0xfffacdff;
case 'lightblue': return 0xadd8e6ff;
case 'lightcoral': return 0xf08080ff;
case 'lightcyan': return 0xe0ffffff;
case 'lightgoldenrodyellow': return 0xfafad2ff;
case 'lightgray': return 0xd3d3d3ff;
case 'lightgreen': return 0x90ee90ff;
case 'lightgrey': return 0xd3d3d3ff;
case 'lightpink': return 0xffb6c1ff;
case 'lightsalmon': return 0xffa07aff;
case 'lightseagreen': return 0x20b2aaff;
case 'lightskyblue': return 0x87cefaff;
case 'lightslategray': return 0x778899ff;
case 'lightslategrey': return 0x778899ff;
case 'lightsteelblue': return 0xb0c4deff;
case 'lightyellow': return 0xffffe0ff;
case 'lime': return 0x00ff00ff;
case 'limegreen': return 0x32cd32ff;
case 'linen': return 0xfaf0e6ff;
case 'magenta': return 0xff00ffff;
case 'maroon': return 0x800000ff;
case 'mediumaquamarine': return 0x66cdaaff;
case 'mediumblue': return 0x0000cdff;
case 'mediumorchid': return 0xba55d3ff;
case 'mediumpurple': return 0x9370dbff;
case 'mediumseagreen': return 0x3cb371ff;
case 'mediumslateblue': return 0x7b68eeff;
case 'mediumspringgreen': return 0x00fa9aff;
case 'mediumturquoise': return 0x48d1ccff;
case 'mediumvioletred': return 0xc71585ff;
case 'midnightblue': return 0x191970ff;
case 'mintcream': return 0xf5fffaff;
case 'mistyrose': return 0xffe4e1ff;
case 'moccasin': return 0xffe4b5ff;
case 'navajowhite': return 0xffdeadff;
case 'navy': return 0x000080ff;
case 'oldlace': return 0xfdf5e6ff;
case 'olive': return 0x808000ff;
case 'olivedrab': return 0x6b8e23ff;
case 'orange': return 0xffa500ff;
case 'orangered': return 0xff4500ff;
case 'orchid': return 0xda70d6ff;
case 'palegoldenrod': return 0xeee8aaff;
case 'palegreen': return 0x98fb98ff;
case 'paleturquoise': return 0xafeeeeff;
case 'palevioletred': return 0xdb7093ff;
case 'papayawhip': return 0xffefd5ff;
case 'peachpuff': return 0xffdab9ff;
case 'peru': return 0xcd853fff;
case 'pink': return 0xffc0cbff;
case 'plum': return 0xdda0ddff;
case 'powderblue': return 0xb0e0e6ff;
case 'purple': return 0x800080ff;
case 'rebeccapurple': return 0x663399ff;
case 'red': return 0xff0000ff;
case 'rosybrown': return 0xbc8f8fff;
case 'royalblue': return 0x4169e1ff;
case 'saddlebrown': return 0x8b4513ff;
case 'salmon': return 0xfa8072ff;
case 'sandybrown': return 0xf4a460ff;
case 'seagreen': return 0x2e8b57ff;
case 'seashell': return 0xfff5eeff;
case 'sienna': return 0xa0522dff;
case 'silver': return 0xc0c0c0ff;
case 'skyblue': return 0x87ceebff;
case 'slateblue': return 0x6a5acdff;
case 'slategray': return 0x708090ff;
case 'slategrey': return 0x708090ff;
case 'snow': return 0xfffafaff;
case 'springgreen': return 0x00ff7fff;
case 'steelblue': return 0x4682b4ff;
case 'tan': return 0xd2b48cff;
case 'teal': return 0x008080ff;
case 'thistle': return 0xd8bfd8ff;
case 'tomato': return 0xff6347ff;
case 'turquoise': return 0x40e0d0ff;
case 'violet': return 0xee82eeff;
case 'wheat': return 0xf5deb3ff;
case 'white': return 0xffffffff;
case 'whitesmoke': return 0xf5f5f5ff;
case 'yellow': return 0xffff00ff;
case 'yellowgreen': return 0x9acd32ff;
}
return null;
}
module.exports = normalizeColor;
webpack://frontend-mybets/../../node_modules/react-redux/es/components/Context.js
import React from 'react';
export var ReactReduxContext = /*#__PURE__*/React.createContext(null);
if (process.env.NODE_ENV !== 'production') {
ReactReduxContext.displayName = 'ReactRedux';
}
export default ReactReduxContext;
webpack://frontend-mybets/../../node_modules/react-redux/es/utils/batch.js
// Default to a dummy "batch" implementation that just runs the callback
function defaultNoopBatch(callback) {
callback();
}
var batch = defaultNoopBatch; // Allow injecting another batching function later
export var setBatch = function setBatch(newBatch) {
return batch = newBatch;
}; // Supply a getter just to skip dealing with ESM bindings
export var getBatch = function getBatch() {
return batch;
};
webpack://frontend-mybets/../../node_modules/react-redux/es/utils/Subscription.js
import { getBatch } from './batch'; // encapsulates the subscription logic for connecting a component to the redux store, as
// well as nesting subscriptions of descendant components, so that we can ensure the
// ancestor components re-render before descendants
var nullListeners = {
notify: function notify() {}
};
function createListenerCollection() {
var batch = getBatch();
var first = null;
var last = null;
return {
clear: function clear() {
first = null;
last = null;
},
notify: function notify() {
batch(function () {
var listener = first;
while (listener) {
listener.callback();
listener = listener.next;
}
});
},
get: function get() {
var listeners = [];
var listener = first;
while (listener) {
listeners.push(listener);
listener = listener.next;
}
return listeners;
},
subscribe: function subscribe(callback) {
var isSubscribed = true;
var listener = last = {
callback: callback,
next: null,
prev: last
};
if (listener.prev) {
listener.prev.next = listener;
} else {
first = listener;
}
return function unsubscribe() {
if (!isSubscribed || first === null) return;
isSubscribed = false;
if (listener.next) {
listener.next.prev = listener.prev;
} else {
last = listener.prev;
}
if (listener.prev) {
listener.prev.next = listener.next;
} else {
first = listener.next;
}
};
}
};
}
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;
}();
export { Subscription as default };
webpack://frontend-mybets/../../node_modules/react-redux/es/utils/useIsomorphicLayoutEffect.js
import { useEffect, useLayoutEffect } from 'react'; // 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 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
export var useIsomorphicLayoutEffect = typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined' ? useLayoutEffect : useEffect;
webpack://frontend-mybets/../../node_modules/react-redux/es/components/Provider.js
import React, { useMemo } from 'react';
import PropTypes from 'prop-types';
import { ReactReduxContext } from './Context';
import Subscription from '../utils/Subscription';
import { useIsomorphicLayoutEffect } from '../utils/useIsomorphicLayoutEffect';
function Provider(_ref) {
var store = _ref.store,
context = _ref.context,
children = _ref.children;
var contextValue = useMemo(function () {
var subscription = new Subscription(store);
subscription.onStateChange = subscription.notifyNestedSubs;
return {
store: store,
subscription: subscription
};
}, [store]);
var previousState = useMemo(function () {
return store.getState();
}, [store]);
useIsomorphicLayoutEffect(function () {
var subscription = contextValue.subscription;
subscription.trySubscribe();
if (previousState !== store.getState()) {
subscription.notifyNestedSubs();
}
return function () {
subscription.tryUnsubscribe();
subscription.onStateChange = null;
};
}, [contextValue, previousState]);
var Context = context || ReactReduxContext;
return /*#__PURE__*/React.createElement(Context.Provider, {
value: contextValue
}, children);
}
if (process.env.NODE_ENV !== 'production') {
Provider.propTypes = {
store: PropTypes.shape({
subscribe: PropTypes.func.isRequired,
dispatch: PropTypes.func.isRequired,
getState: PropTypes.func.isRequired
}),
context: PropTypes.object,
children: PropTypes.any
};
}
export default Provider;
webpack://frontend-mybets/../../node_modules/react-redux/node_modules/@babel/runtime/helpers/esm/extends.js
export default function _extends() {
_extends = Object.assign ? Object.assign.bind() : 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);
}
webpack://frontend-mybets/../../node_modules/react-redux/node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js
export default 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;
}
webpack://frontend-mybets/../../node_modules/react-redux/es/components/connectAdvanced.js
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import hoistStatics from 'hoist-non-react-statics';
import React, { useContext, useMemo, useRef, useReducer } from 'react';
import { isValidElementType, isContextConsumer } from 'react-is';
import Subscription from '../utils/Subscription';
import { useIsomorphicLayoutEffect } from '../utils/useIsomorphicLayoutEffect';
import { ReactReduxContext } from './Context'; // Define some constant arrays just to avoid re-creating these
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];
}
function useIsomorphicLayoutEffectWithArgs(effectFunc, effectArgs, dependencies) {
useIsomorphicLayoutEffect(function () {
return effectFunc.apply(void 0, effectArgs);
}, dependencies);
}
function captureWrapperProps(lastWrapperProps, lastChildProps, renderIsScheduled, wrapperProps, actualChildProps, childPropsFromStoreUpdate, notifyNestedSubs) {
// 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();
}
}
function subscribeUpdates(shouldHandleStateChanges, store, subscription, childPropsSelector, lastWrapperProps, lastChildProps, renderIsScheduled, childPropsFromStoreUpdate, notifyNestedSubs, forceComponentUpdateDispatch) {
// 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: {
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();
subscription.onStateChange = null;
if (lastThrownError) {
// It's possible that we caught an error due to a bad mapState function, but the
// parent re-rendered without this component and we're about to unmount.
// This shouldn't happen as long as we do top-down subscriptions correctly, but
// if we ever do those wrong, this throw will surface the error in our tests.
// In that case, throw the error from here so it doesn't get lost.
throw lastThrownError;
}
};
return unsubscribeWrapper;
}
var initStateUpdates = function initStateUpdates() {
return [null, 0];
};
export default 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"]);
if (process.env.NODE_ENV !== 'production') {
if (renderCountProp !== undefined) {
throw new Error("renderCountProp is removed. render counting is built into the latest React Dev Tools profiling extension");
}
if (withRef) {
throw new Error('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';
if (storeKey !== 'store') {
throw new Error('storeKey has been removed and does not do anything. ' + customStoreWarningMessage);
}
}
var Context = context;
return function wrapWithConnect(WrappedComponent) {
if (process.env.NODE_ENV !== 'production' && !isValidElementType(WrappedComponent)) {
throw new Error("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 ? useMemo : function (callback) {
return callback();
};
function ConnectFunction(props) {
var _useMemo = 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 reactReduxForwardedRef = props.reactReduxForwardedRef,
wrapperProps = _objectWithoutPropertiesLoose(props, ["reactReduxForwardedRef"]);
return [props.context, reactReduxForwardedRef, wrapperProps];
}, [props]),
propsContext = _useMemo[0],
reactReduxForwardedRef = _useMemo[1],
wrapperProps = _useMemo[2];
var ContextToUse = 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 && isContextConsumer( /*#__PURE__*/React.createElement(propsContext.Consumer, null)) ? propsContext : Context;
}, [propsContext, Context]); // Retrieve the store and ancestor subscription via context, if available
var contextValue = useContext(ContextToUse); // The store _must_ exist as either a prop or in context.
// We'll check to see if it _looks_ like a Redux store first.
// This allows us to pass through a `store` prop that is just a plain value.
var didStoreComeFromProps = Boolean(props.store) && Boolean(props.store.getState) && Boolean(props.store.dispatch);
var didStoreComeFromContext = Boolean(contextValue) && Boolean(contextValue.store);
if (process.env.NODE_ENV !== 'production' && !didStoreComeFromProps && !didStoreComeFromContext) {
throw new Error("Could not find \"store\" in the context of " + ("\"" + displayName + "\". Either wrap the root component in a <Provider>, ") + "or pass a custom React context provider to <Provider> and the corresponding " + ("React context consumer to " + displayName + " in connect options."));
} // Based on the previous check, one of these must be true
var store = didStoreComeFromProps ? props.store : contextValue.store;
var childPropsSelector = 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 = 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 = 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 = 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 = useRef();
var lastWrapperProps = useRef(wrapperProps);
var childPropsFromStoreUpdate = useRef();
var renderIsScheduled = 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.
useIsomorphicLayoutEffectWithArgs(captureWrapperProps, [lastWrapperProps, lastChildProps, renderIsScheduled, wrapperProps, actualChildProps, childPropsFromStoreUpdate, notifyNestedSubs]); // Our re-subscribe logic only runs when the store/subscription setup changes
useIsomorphicLayoutEffectWithArgs(subscribeUpdates, [shouldHandleStateChanges, store, subscription, childPropsSelector, lastWrapperProps, lastChildProps, renderIsScheduled, childPropsFromStoreUpdate, notifyNestedSubs, forceComponentUpdateDispatch], [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 = useMemo(function () {
return /*#__PURE__*/React.createElement(WrappedComponent, _extends({}, actualChildProps, {
ref: reactReduxForwardedRef
}));
}, [reactReduxForwardedRef, WrappedComponent, actualChildProps]); // If React sees the exact same element reference as last time, it bails out of re-rendering
// that child, same as if it was wrapped in React.memo() or returned false from shouldComponentUpdate.
var renderedChild = 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 /*#__PURE__*/React.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.memo(ConnectFunction) : ConnectFunction;
Connect.WrappedComponent = WrappedComponent;
Connect.displayName = ConnectFunction.displayName = displayName;
if (forwardRef) {
var forwarded = React.forwardRef(function forwardConnectRef(props, ref) {
return /*#__PURE__*/React.createElement(Connect, _extends({}, props, {
reactReduxForwardedRef: ref
}));
});
forwarded.displayName = displayName;
forwarded.WrappedComponent = WrappedComponent;
return hoistStatics(forwarded, WrappedComponent);
}
return hoistStatics(Connect, WrappedComponent);
};
}
webpack://frontend-mybets/../../node_modules/react-redux/es/utils/shallowEqual.js
function is(x, y) {
if (x === y) {
return x !== 0 || y !== 0 || 1 / x === 1 / y;
} else {
return x !== x && y !== y;
}
}
export default 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 (!Object.prototype.hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
return false;
}
}
return true;
}
webpack://frontend-mybets/../../node_modules/react-redux/es/connect/wrapMapToProps.js
import verifyPlainObject from '../utils/verifyPlainObject';
export 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..
export 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.
//
export 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);
}
if (process.env.NODE_ENV !== 'production') verifyPlainObject(props, displayName, methodName);
return props;
};
return proxy;
};
}
webpack://frontend-mybets/../../node_modules/react-redux/es/connect/mapDispatchToProps.js
import bindActionCreators from '../utils/bindActionCreators';
import { wrapMapToPropsConstant, wrapMapToPropsFunc } from './wrapMapToProps';
export function whenMapDispatchToPropsIsFunction(mapDispatchToProps) {
return typeof mapDispatchToProps === 'function' ? wrapMapToPropsFunc(mapDispatchToProps, 'mapDispatchToProps') : undefined;
}
export function whenMapDispatchToPropsIsMissing(mapDispatchToProps) {
return !mapDispatchToProps ? wrapMapToPropsConstant(function (dispatch) {
return {
dispatch: dispatch
};
}) : undefined;
}
export function whenMapDispatchToPropsIsObject(mapDispatchToProps) {
return mapDispatchToProps && typeof mapDispatchToProps === 'object' ? wrapMapToPropsConstant(function (dispatch) {
return bindActionCreators(mapDispatchToProps, dispatch);
}) : undefined;
}
export default [whenMapDispatchToPropsIsFunction, whenMapDispatchToPropsIsMissing, whenMapDispatchToPropsIsObject];
webpack://frontend-mybets/../../node_modules/react-redux/es/utils/bindActionCreators.js
export default function bindActionCreators(actionCreators, dispatch) {
var boundActionCreators = {};
var _loop = function _loop(key) {
var actionCreator = actionCreators[key];
if (typeof actionCreator === 'function') {
boundActionCreators[key] = function () {
return dispatch(actionCreator.apply(void 0, arguments));
};
}
};
for (var key in actionCreators) {
_loop(key);
}
return boundActionCreators;
}
webpack://frontend-mybets/../../node_modules/react-redux/es/connect/mapStateToProps.js
import { wrapMapToPropsConstant, wrapMapToPropsFunc } from './wrapMapToProps';
export function whenMapStateToPropsIsFunction(mapStateToProps) {
return typeof mapStateToProps === 'function' ? wrapMapToPropsFunc(mapStateToProps, 'mapStateToProps') : undefined;
}
export function whenMapStateToPropsIsMissing(mapStateToProps) {
return !mapStateToProps ? wrapMapToPropsConstant(function () {
return {};
}) : undefined;
}
export default [whenMapStateToPropsIsFunction, whenMapStateToPropsIsMissing];
webpack://frontend-mybets/../../node_modules/react-redux/es/connect/mergeProps.js
import _extends from "@babel/runtime/helpers/esm/extends";
import verifyPlainObject from '../utils/verifyPlainObject';
export function defaultMergeProps(stateProps, dispatchProps, ownProps) {
return _extends({}, ownProps, stateProps, dispatchProps);
}
export 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;
if (process.env.NODE_ENV !== 'production') verifyPlainObject(mergedProps, displayName, 'mergeProps');
}
return mergedProps;
};
};
}
export function whenMergePropsIsFunction(mergeProps) {
return typeof mergeProps === 'function' ? wrapMergePropsFunc(mergeProps) : undefined;
}
export function whenMergePropsIsOmitted(mergeProps) {
return !mergeProps ? function () {
return defaultMergeProps;
} : undefined;
}
export default [whenMergePropsIsFunction, whenMergePropsIsOmitted];
webpack://frontend-mybets/../../node_modules/react-redux/es/connect/selectorFactory.js
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import verifySubselectors from './verifySubselectors';
export function impureFinalPropsSelectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch) {
return function impureFinalPropsSelector(state, ownProps) {
return mergeProps(mapStateToProps(state, ownProps), mapDispatchToProps(dispatch, ownProps), ownProps);
};
}
export 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.
export default 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);
if (process.env.NODE_ENV !== 'production') {
verifySubselectors(mapStateToProps, mapDispatchToProps, mergeProps, options.displayName);
}
var selectorFactory = options.pure ? pureFinalPropsSelectorFactory : impureFinalPropsSelectorFactory;
return selectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch, options);
}
webpack://frontend-mybets/../../node_modules/react-redux/es/connect/connect.js
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import connectAdvanced from '../components/connectAdvanced';
import shallowEqual from '../utils/shallowEqual';
import defaultMapDispatchToPropsFactories from './mapDispatchToProps';
import defaultMapStateToPropsFactories from './mapStateToProps';
import defaultMergePropsFactories from './mergeProps';
import defaultSelectorFactory from './selectorFactory';
/*
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
export 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 ? defaultSelectorFactory : _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));
};
}
export default /*#__PURE__*/createConnect();
webpack://frontend-mybets/../../node_modules/react-redux/es/hooks/useReduxContext.js
import { useContext } from 'react';
import { ReactReduxContext } from '../components/Context';
/**
* 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>
* }
*/
export function useReduxContext() {
var contextValue = useContext(ReactReduxContext);
if (process.env.NODE_ENV !== 'production' && !contextValue) {
throw new Error('could not find react-redux context value; please ensure the component is wrapped in a <Provider>');
}
return contextValue;
}
webpack://frontend-mybets/../../node_modules/react-redux/es/hooks/useStore.js
import { useContext } from 'react';
import { ReactReduxContext } from '../components/Context';
import { useReduxContext as useDefaultReduxContext } from './useReduxContext';
/**
* Hook factory, which creates a `useStore` hook bound to a given context.
*
* @param {React.Context} [context=ReactReduxContext] Context passed to your `<Provider>`.
* @returns {Function} A `useStore` hook bound to the specified context.
*/
export function createStoreHook(context) {
if (context === void 0) {
context = ReactReduxContext;
}
var useReduxContext = context === ReactReduxContext ? useDefaultReduxContext : function () {
return useContext(context);
};
return function useStore() {
var _useReduxContext = useReduxContext(),
store = _useReduxContext.store;
return store;
};
}
/**
* A hook to access the redux store.
*
* @returns {any} the redux store
*
* @example
*
* import React from 'react'
* import { useStore } from 'react-redux'
*
* export const ExampleComponent = () => {
* const store = useStore()
* return <div>{store.getState()}</div>
* }
*/
export var useStore = /*#__PURE__*/createStoreHook();
webpack://frontend-mybets/../../node_modules/react-redux/es/hooks/useDispatch.js
import { ReactReduxContext } from '../components/Context';
import { useStore as useDefaultStore, createStoreHook } from './useStore';
/**
* Hook factory, which creates a `useDispatch` hook bound to a given context.
*
* @param {React.Context} [context=ReactReduxContext] Context passed to your `<Provider>`.
* @returns {Function} A `useDispatch` hook bound to the specified context.
*/
export function createDispatchHook(context) {
if (context === void 0) {
context = ReactReduxContext;
}
var useStore = context === ReactReduxContext ? useDefaultStore : createStoreHook(context);
return function useDispatch() {
var store = useStore();
return store.dispatch;
};
}
/**
* A hook to access the redux `dispatch` function.
*
* @returns {any|function} redux store's `dispatch` function
*
* @example
*
* import React, { useCallback } from 'react'
* import { useDispatch } from 'react-redux'
*
* export const CounterComponent = ({ value }) => {
* const dispatch = useDispatch()
* const increaseCounter = useCallback(() => dispatch({ type: 'increase-counter' }), [])
* return (
* <div>
* <span>{value}</span>
* <button onClick={increaseCounter}>Increase counter</button>
* </div>
* )
* }
*/
export var useDispatch = /*#__PURE__*/createDispatchHook();
webpack://frontend-mybets/../../node_modules/react-redux/es/hooks/useSelector.js
import { useReducer, useRef, useMemo, useContext, useDebugValue } from 'react';
import { useReduxContext as useDefaultReduxContext } from './useReduxContext';
import Subscription from '../utils/Subscription';
import { useIsomorphicLayoutEffect } from '../utils/useIsomorphicLayoutEffect';
import { ReactReduxContext } from '../components/Context';
var refEquality = function refEquality(a, b) {
return a === b;
};
function useSelectorWithStoreAndSubscription(selector, equalityFn, store, contextSub) {
var _useReducer = useReducer(function (s) {
return s + 1;
}, 0),
forceRender = _useReducer[1];
var subscription = useMemo(function () {
return new Subscription(store, contextSub);
}, [store, contextSub]);
var latestSubscriptionCallbackError = useRef();
var latestSelector = useRef();
var latestStoreState = useRef();
var latestSelectedState = useRef();
var storeState = store.getState();
var selectedState;
try {
if (selector !== latestSelector.current || storeState !== latestStoreState.current || latestSubscriptionCallbackError.current) {
var newSelectedState = selector(storeState); // ensure latest selected state is reused so that a custom equality function can result in identical references
if (latestSelectedState.current === undefined || !equalityFn(newSelectedState, latestSelectedState.current)) {
selectedState = newSelectedState;
} else {
selectedState = latestSelectedState.current;
}
} else {
selectedState = latestSelectedState.current;
}
} catch (err) {
if (latestSubscriptionCallbackError.current) {
err.message += "\nThe error may be correlated with this previous error:\n" + latestSubscriptionCallbackError.current.stack + "\n\n";
}
throw err;
}
useIsomorphicLayoutEffect(function () {
latestSelector.current = selector;
latestStoreState.current = storeState;
latestSelectedState.current = selectedState;
latestSubscriptionCallbackError.current = undefined;
});
useIsomorphicLayoutEffect(function () {
function checkForUpdates() {
try {
var newStoreState = store.getState();
var _newSelectedState = latestSelector.current(newStoreState);
if (equalityFn(_newSelectedState, latestSelectedState.current)) {
return;
}
latestSelectedState.current = _newSelectedState;
latestStoreState.current = newStoreState;
} 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;
}
/**
* Hook factory, which creates a `useSelector` hook bound to a given context.
*
* @param {React.Context} [context=ReactReduxContext] Context passed to your `<Provider>`.
* @returns {Function} A `useSelector` hook bound to the specified context.
*/
export function createSelectorHook(context) {
if (context === void 0) {
context = ReactReduxContext;
}
var useReduxContext = context === ReactReduxContext ? useDefaultReduxContext : function () {
return useContext(context);
};
return function useSelector(selector, equalityFn) {
if (equalityFn === void 0) {
equalityFn = refEquality;
}
if (process.env.NODE_ENV !== 'production') {
if (!selector) {
throw new Error("You must pass a selector to useSelector");
}
if (typeof selector !== 'function') {
throw new Error("You must pass a function as a selector to useSelector");
}
if (typeof equalityFn !== 'function') {
throw new Error("You must pass a function as an equality function to useSelector");
}
}
var _useReduxContext = useReduxContext(),
store = _useReduxContext.store,
contextSub = _useReduxContext.subscription;
var selectedState = useSelectorWithStoreAndSubscription(selector, equalityFn, store, contextSub);
useDebugValue(selectedState);
return selectedState;
};
}
/**
* A hook to access the redux store's state. This hook takes a selector function
* as an argument. The selector is called with the store state.
*
* This hook takes an optional equality comparison function as the second parameter
* that allows you to customize the way the selected state is compared to determine
* whether the component needs to be re-rendered.
*
* @param {Function} selector the selector function
* @param {Function=} equalityFn the function that will be used to determine equality
*
* @returns {any} the selected state
*
* @example
*
* import React from 'react'
* import { useSelector } from 'react-redux'
*
* export const CounterComponent = () => {
* const counter = useSelector(state => state.counter)
* return <div>{counter}</div>
* }
*/
export var useSelector = /*#__PURE__*/createSelectorHook();
webpack://frontend-mybets/../../node_modules/react-redux/es/index.js
import Provider from './components/Provider';
import connectAdvanced from './components/connectAdvanced';
import { ReactReduxContext } from './components/Context';
import connect from './connect/connect';
import { useDispatch, createDispatchHook } from './hooks/useDispatch';
import { useSelector, createSelectorHook } from './hooks/useSelector';
import { useStore, createStoreHook } from './hooks/useStore';
import { setBatch } from './utils/batch';
import { unstable_batchedUpdates as batch } from './utils/reactBatchedUpdates';
import shallowEqual from './utils/shallowEqual';
setBatch(batch);
export { Provider, connectAdvanced, ReactReduxContext, connect, batch, useDispatch, createDispatchHook, useSelector, createSelectorHook, useStore, createStoreHook, shallowEqual };
webpack://frontend-mybets/../../node_modules/react-redux/node_modules/react-is/cjs/react-is.production.min.js
/** @license React v16.13.1
* react-is.production.min.js
*
* 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.
*/
'use strict';var b="function"===typeof Symbol&&Symbol.for,c=b?Symbol.for("react.element"):60103,d=b?Symbol.for("react.portal"):60106,e=b?Symbol.for("react.fragment"):60107,f=b?Symbol.for("react.strict_mode"):60108,g=b?Symbol.for("react.profiler"):60114,h=b?Symbol.for("react.provider"):60109,k=b?Symbol.for("react.context"):60110,l=b?Symbol.for("react.async_mode"):60111,m=b?Symbol.for("react.concurrent_mode"):60111,n=b?Symbol.for("react.forward_ref"):60112,p=b?Symbol.for("react.suspense"):60113,q=b?
Symbol.for("react.suspense_list"):60120,r=b?Symbol.for("react.memo"):60115,t=b?Symbol.for("react.lazy"):60116,v=b?Symbol.for("react.block"):60121,w=b?Symbol.for("react.fundamental"):60117,x=b?Symbol.for("react.responder"):60118,y=b?Symbol.for("react.scope"):60119;
function z(a){if("object"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case t:case r:case h:return a;default:return u}}case d:return u}}}function A(a){return z(a)===m}exports.AsyncMode=l;exports.ConcurrentMode=m;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=n;exports.Fragment=e;exports.Lazy=t;exports.Memo=r;exports.Portal=d;
exports.Profiler=g;exports.StrictMode=f;exports.Suspense=p;exports.isAsyncMode=function(a){return A(a)||z(a)===l};exports.isConcurrentMode=A;exports.isContextConsumer=function(a){return z(a)===k};exports.isContextProvider=function(a){return z(a)===h};exports.isElement=function(a){return"object"===typeof a&&null!==a&&a.$$typeof===c};exports.isForwardRef=function(a){return z(a)===n};exports.isFragment=function(a){return z(a)===e};exports.isLazy=function(a){return z(a)===t};
exports.isMemo=function(a){return z(a)===r};exports.isPortal=function(a){return z(a)===d};exports.isProfiler=function(a){return z(a)===g};exports.isStrictMode=function(a){return z(a)===f};exports.isSuspense=function(a){return z(a)===p};
exports.isValidElementType=function(a){return"string"===typeof a||"function"===typeof a||a===e||a===m||a===g||a===f||a===p||a===q||"object"===typeof a&&null!==a&&(a.$$typeof===t||a.$$typeof===r||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n||a.$$typeof===w||a.$$typeof===x||a.$$typeof===y||a.$$typeof===v)};exports.typeOf=z;
webpack://frontend-mybets/../../node_modules/react-redux/node_modules/react-is/index.js
'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/react-is.production.min.js');
} else {
module.exports = require('./cjs/react-is.development.js');
}
webpack://frontend-mybets/../../node_modules/react-side-effect/lib/index.js
'use strict';
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var React = require('react');
var React__default = _interopDefault(React);
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
function withSideEffect(reducePropsToState, handleStateChangeOnClient, mapStateOnServer) {
if (typeof reducePropsToState !== 'function') {
throw new Error('Expected reducePropsToState to be a function.');
}
if (typeof handleStateChangeOnClient !== 'function') {
throw new Error('Expected handleStateChangeOnClient to be a function.');
}
if (typeof mapStateOnServer !== 'undefined' && typeof mapStateOnServer !== 'function') {
throw new Error('Expected mapStateOnServer to either be undefined or a function.');
}
function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}
return function wrap(WrappedComponent) {
if (typeof WrappedComponent !== 'function') {
throw new Error('Expected WrappedComponent to be a React component.');
}
var mountedInstances = [];
var state;
function emitChange() {
state = reducePropsToState(mountedInstances.map(function (instance) {
return instance.props;
}));
if (SideEffect.canUseDOM) {
handleStateChangeOnClient(state);
} else if (mapStateOnServer) {
state = mapStateOnServer(state);
}
}
var SideEffect =
/*#__PURE__*/
function (_PureComponent) {
_inheritsLoose(SideEffect, _PureComponent);
function SideEffect() {
return _PureComponent.apply(this, arguments) || this;
}
// Try to use displayName of wrapped component
// Expose canUseDOM so tests can monkeypatch it
SideEffect.peek = function peek() {
return state;
};
SideEffect.rewind = function rewind() {
if (SideEffect.canUseDOM) {
throw new Error('You may only call rewind() on the server. Call peek() to read the current state.');
}
var recordedState = state;
state = undefined;
mountedInstances = [];
return recordedState;
};
var _proto = SideEffect.prototype;
_proto.UNSAFE_componentWillMount = function UNSAFE_componentWillMount() {
mountedInstances.push(this);
emitChange();
};
_proto.componentDidUpdate = function componentDidUpdate() {
emitChange();
};
_proto.componentWillUnmount = function componentWillUnmount() {
var index = mountedInstances.indexOf(this);
mountedInstances.splice(index, 1);
emitChange();
};
_proto.render = function render() {
return React__default.createElement(WrappedComponent, this.props);
};
return SideEffect;
}(React.PureComponent);
_defineProperty(SideEffect, "displayName", "SideEffect(" + getDisplayName(WrappedComponent) + ")");
_defineProperty(SideEffect, "canUseDOM", canUseDOM);
return SideEffect;
};
}
module.exports = withSideEffect;
webpack://frontend-mybets/../../node_modules/react/cjs/react.production.min.js
/**
* @license React
* react.production.min.js
*
* 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.
*/
'use strict';var l=Symbol.for("react.element"),n=Symbol.for("react.portal"),p=Symbol.for("react.fragment"),q=Symbol.for("react.strict_mode"),r=Symbol.for("react.profiler"),t=Symbol.for("react.provider"),u=Symbol.for("react.context"),v=Symbol.for("react.forward_ref"),w=Symbol.for("react.suspense"),x=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),z=Symbol.iterator;function A(a){if(null===a||"object"!==typeof a)return null;a=z&&a[z]||a["@@iterator"];return"function"===typeof a?a:null}
var B={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C=Object.assign,D={};function E(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}E.prototype.isReactComponent={};
E.prototype.setState=function(a,b){if("object"!==typeof a&&"function"!==typeof a&&null!=a)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,a,b,"setState")};E.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,"forceUpdate")};function F(){}F.prototype=E.prototype;function G(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}var H=G.prototype=new F;
H.constructor=G;C(H,E.prototype);H.isPureReactComponent=!0;var I=Array.isArray,J=Object.prototype.hasOwnProperty,K={current:null},L={key:!0,ref:!0,__self:!0,__source:!0};
function M(a,b,e){var d,c={},k=null,h=null;if(null!=b)for(d in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(k=""+b.key),b)J.call(b,d)&&!L.hasOwnProperty(d)&&(c[d]=b[d]);var g=arguments.length-2;if(1===g)c.children=e;else if(1<g){for(var f=Array(g),m=0;m<g;m++)f[m]=arguments[m+2];c.children=f}if(a&&a.defaultProps)for(d in g=a.defaultProps,g)void 0===c[d]&&(c[d]=g[d]);return{$$typeof:l,type:a,key:k,ref:h,props:c,_owner:K.current}}
function N(a,b){return{$$typeof:l,type:a.type,key:b,ref:a.ref,props:a.props,_owner:a._owner}}function O(a){return"object"===typeof a&&null!==a&&a.$$typeof===l}function escape(a){var b={"=":"=0",":":"=2"};return"$"+a.replace(/[=:]/g,function(a){return b[a]})}var P=/\/+/g;function Q(a,b){return"object"===typeof a&&null!==a&&null!=a.key?escape(""+a.key):b.toString(36)}
function R(a,b,e,d,c){var k=typeof a;if("undefined"===k||"boolean"===k)a=null;var h=!1;if(null===a)h=!0;else switch(k){case "string":case "number":h=!0;break;case "object":switch(a.$$typeof){case l:case n:h=!0}}if(h)return h=a,c=c(h),a=""===d?"."+Q(h,0):d,I(c)?(e="",null!=a&&(e=a.replace(P,"$&/")+"/"),R(c,b,e,"",function(a){return a})):null!=c&&(O(c)&&(c=N(c,e+(!c.key||h&&h.key===c.key?"":(""+c.key).replace(P,"$&/")+"/")+a)),b.push(c)),1;h=0;d=""===d?".":d+":";if(I(a))for(var g=0;g<a.length;g++){k=
a[g];var f=d+Q(k,g);h+=R(k,b,e,f,c)}else if(f=A(a),"function"===typeof f)for(a=f.call(a),g=0;!(k=a.next()).done;)k=k.value,f=d+Q(k,g++),h+=R(k,b,e,f,c);else if("object"===k)throw b=String(a),Error("Objects are not valid as a React child (found: "+("[object Object]"===b?"object with keys {"+Object.keys(a).join(", ")+"}":b)+"). If you meant to render a collection of children, use an array instead.");return h}
function S(a,b,e){if(null==a)return a;var d=[],c=0;R(a,d,"","",function(a){return b.call(e,a,c++)});return d}function T(a){if(-1===a._status){var b=a._result;b=b();b.then(function(b){if(0===a._status||-1===a._status)a._status=1,a._result=b},function(b){if(0===a._status||-1===a._status)a._status=2,a._result=b});-1===a._status&&(a._status=0,a._result=b)}if(1===a._status)return a._result.default;throw a._result;}
var U={current:null},V={transition:null},W={ReactCurrentDispatcher:U,ReactCurrentBatchConfig:V,ReactCurrentOwner:K};function X(){throw Error("act(...) is not supported in production builds of React.");}
exports.Children={map:S,forEach:function(a,b,e){S(a,function(){b.apply(this,arguments)},e)},count:function(a){var b=0;S(a,function(){b++});return b},toArray:function(a){return S(a,function(a){return a})||[]},only:function(a){if(!O(a))throw Error("React.Children.only expected to receive a single React element child.");return a}};exports.Component=E;exports.Fragment=p;exports.Profiler=r;exports.PureComponent=G;exports.StrictMode=q;exports.Suspense=w;
exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=W;exports.act=X;
exports.cloneElement=function(a,b,e){if(null===a||void 0===a)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+a+".");var d=C({},a.props),c=a.key,k=a.ref,h=a._owner;if(null!=b){void 0!==b.ref&&(k=b.ref,h=K.current);void 0!==b.key&&(c=""+b.key);if(a.type&&a.type.defaultProps)var g=a.type.defaultProps;for(f in b)J.call(b,f)&&!L.hasOwnProperty(f)&&(d[f]=void 0===b[f]&&void 0!==g?g[f]:b[f])}var f=arguments.length-2;if(1===f)d.children=e;else if(1<f){g=Array(f);
for(var m=0;m<f;m++)g[m]=arguments[m+2];d.children=g}return{$$typeof:l,type:a.type,key:c,ref:k,props:d,_owner:h}};exports.createContext=function(a){a={$$typeof:u,_currentValue:a,_currentValue2:a,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null};a.Provider={$$typeof:t,_context:a};return a.Consumer=a};exports.createElement=M;exports.createFactory=function(a){var b=M.bind(null,a);b.type=a;return b};exports.createRef=function(){return{current:null}};
exports.forwardRef=function(a){return{$$typeof:v,render:a}};exports.isValidElement=O;exports.lazy=function(a){return{$$typeof:y,_payload:{_status:-1,_result:a},_init:T}};exports.memo=function(a,b){return{$$typeof:x,type:a,compare:void 0===b?null:b}};exports.startTransition=function(a){var b=V.transition;V.transition={};try{a()}finally{V.transition=b}};exports.unstable_act=X;exports.useCallback=function(a,b){return U.current.useCallback(a,b)};exports.useContext=function(a){return U.current.useContext(a)};
exports.useDebugValue=function(){};exports.useDeferredValue=function(a){return U.current.useDeferredValue(a)};exports.useEffect=function(a,b){return U.current.useEffect(a,b)};exports.useId=function(){return U.current.useId()};exports.useImperativeHandle=function(a,b,e){return U.current.useImperativeHandle(a,b,e)};exports.useInsertionEffect=function(a,b){return U.current.useInsertionEffect(a,b)};exports.useLayoutEffect=function(a,b){return U.current.useLayoutEffect(a,b)};
exports.useMemo=function(a,b){return U.current.useMemo(a,b)};exports.useReducer=function(a,b,e){return U.current.useReducer(a,b,e)};exports.useRef=function(a){return U.current.useRef(a)};exports.useState=function(a){return U.current.useState(a)};exports.useSyncExternalStore=function(a,b,e){return U.current.useSyncExternalStore(a,b,e)};exports.useTransition=function(){return U.current.useTransition()};exports.version="18.3.1";
webpack://frontend-mybets/../../node_modules/react/index.js
'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/react.production.min.js');
} else {
module.exports = require('./cjs/react.development.js');
}
webpack://frontend-mybets/../../node_modules/redux-devtools-extension/index.js
'use strict';
var compose = require('redux').compose;
exports.__esModule = true;
exports.composeWithDevTools =
typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
: function () {
if (arguments.length === 0) return undefined;
if (typeof arguments[0] === 'object') return compose;
return compose.apply(null, arguments);
};
exports.devToolsEnhancer =
typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION__
? window.__REDUX_DEVTOOLS_EXTENSION__
: function () {
return function (noop) {
return noop;
};
};
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/objectSpread2.js
import defineProperty from "./defineProperty.js";
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;
}
export default 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;
}
webpack://frontend-mybets/../../node_modules/redux/es/redux.js
import _objectSpread from '@babel/runtime/helpers/esm/objectSpread2';
/**
* Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js
*
* Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes
* during build.
* @param {number} code
*/
function formatProdErrorMessage(code) {
return "Minified Redux error #" + code + "; visit https://redux.js.org/Errors?code=" + code + " for the full message or " + 'use the non-minified dev environment for full errors. ';
}
// Inlined version of the `symbol-observable` polyfill
var $$observable = (function () {
return typeof Symbol === 'function' && Symbol.observable || '@@observable';
})();
/**
* These are private action types reserved by Redux.
* For any unknown actions, you must return the current state.
* If the current state is undefined, you must return the initial state.
* Do not reference these action types directly in your code.
*/
var randomString = function randomString() {
return Math.random().toString(36).substring(7).split('').join('.');
};
var ActionTypes = {
INIT: "@@redux/INIT" + randomString(),
REPLACE: "@@redux/REPLACE" + randomString(),
PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() {
return "@@redux/PROBE_UNKNOWN_ACTION" + randomString();
}
};
/**
* @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 = obj;
while (Object.getPrototypeOf(proto) !== null) {
proto = Object.getPrototypeOf(proto);
}
return Object.getPrototypeOf(obj) === proto;
}
function kindOf(val) {
var typeOfVal = typeof val;
if (process.env.NODE_ENV !== 'production') {
// Inlined / shortened version of `kindOf` from https://github.com/jonschlinkert/kind-of
function miniKindOf(val) {
if (val === void 0) return 'undefined';
if (val === null) return 'null';
var type = typeof val;
switch (type) {
case 'boolean':
case 'string':
case 'number':
case 'symbol':
case 'function':
{
return type;
}
}
if (Array.isArray(val)) return 'array';
if (isDate(val)) return 'date';
if (isError(val)) return 'error';
var constructorName = ctorName(val);
switch (constructorName) {
case 'Symbol':
case 'Promise':
case 'WeakMap':
case 'WeakSet':
case 'Map':
case 'Set':
return constructorName;
} // other
return type.slice(8, -1).toLowerCase().replace(/\s/g, '');
}
function ctorName(val) {
return typeof val.constructor === 'function' ? val.constructor.name : null;
}
function isError(val) {
return val instanceof Error || typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number';
}
function isDate(val) {
if (val instanceof Date) return true;
return typeof val.toDateString === 'function' && typeof val.getDate === 'function' && typeof val.setDate === 'function';
}
typeOfVal = miniKindOf(val);
}
return typeOfVal;
}
/**
* Creates a Redux store that holds the state tree.
* The only way to change the data in the store is to call `dispatch()` on it.
*
* There should only be a single store in your app. To specify how different
* parts of the state tree respond to actions, you may combine several reducers
* into a single reducer function by using `combineReducers`.
*
* @param {Function} reducer A function that returns the next state tree, given
* the current state tree and the action to handle.
*
* @param {any} [preloadedState] The initial state. You may optionally specify it
* to hydrate the state from the server in universal apps, or to restore a
* previously serialized user session.
* If you use `combineReducers` to produce the root reducer function, this must be
* an object with the same shape as `combineReducers` keys.
*
* @param {Function} [enhancer] The store enhancer. You may optionally specify it
* to enhance the store with third-party capabilities such as middleware,
* time travel, persistence, etc. The only store enhancer that ships with Redux
* is `applyMiddleware()`.
*
* @returns {Store} A Redux store that lets you read the state, dispatch actions
* and subscribe to changes.
*/
function createStore(reducer, preloadedState, enhancer) {
var _ref2;
if (typeof preloadedState === 'function' && typeof enhancer === 'function' || typeof enhancer === 'function' && typeof arguments[3] === 'function') {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(0) : 'It looks like you are passing several store enhancers to ' + 'createStore(). This is not supported. Instead, compose them ' + 'together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.');
}
if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
enhancer = preloadedState;
preloadedState = undefined;
}
if (typeof enhancer !== 'undefined') {
if (typeof enhancer !== 'function') {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(1) : "Expected the enhancer to be a function. Instead, received: '" + kindOf(enhancer) + "'");
}
return enhancer(createStore)(reducer, preloadedState);
}
if (typeof reducer !== 'function') {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(2) : "Expected the root reducer to be a function. Instead, received: '" + kindOf(reducer) + "'");
}
var currentReducer = reducer;
var currentState = preloadedState;
var currentListeners = [];
var nextListeners = currentListeners;
var isDispatching = false;
/**
* This makes a shallow copy of currentListeners so we can use
* nextListeners as a temporary list while dispatching.
*
* This prevents any bugs around consumers calling
* subscribe/unsubscribe in the middle of a dispatch.
*/
function ensureCanMutateNextListeners() {
if (nextListeners === currentListeners) {
nextListeners = currentListeners.slice();
}
}
/**
* Reads the state tree managed by the store.
*
* @returns {any} The current state tree of your application.
*/
function getState() {
if (isDispatching) {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(3) : 'You may not call store.getState() while the reducer is executing. ' + 'The reducer has already received the state as an argument. ' + 'Pass it down from the top reducer instead of reading it from the store.');
}
return currentState;
}
/**
* Adds a change listener. It will be called any time an action is dispatched,
* and some part of the state tree may potentially have changed. You may then
* call `getState()` to read the current state tree inside the callback.
*
* You may call `dispatch()` from a change listener, with the following
* caveats:
*
* 1. The subscriptions are snapshotted just before every `dispatch()` call.
* If you subscribe or unsubscribe while the listeners are being invoked, this
* will not have any effect on the `dispatch()` that is currently in progress.
* However, the next `dispatch()` call, whether nested or not, will use a more
* recent snapshot of the subscription list.
*
* 2. The listener should not expect to see all state changes, as the state
* might have been updated multiple times during a nested `dispatch()` before
* the listener is called. It is, however, guaranteed that all subscribers
* registered before the `dispatch()` started will be called with the latest
* state by the time it exits.
*
* @param {Function} listener A callback to be invoked on every dispatch.
* @returns {Function} A function to remove this change listener.
*/
function subscribe(listener) {
if (typeof listener !== 'function') {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(4) : "Expected the listener to be a function. Instead, received: '" + kindOf(listener) + "'");
}
if (isDispatching) {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(5) : 'You may not call store.subscribe() while the reducer is executing. ' + 'If you would like to be notified after the store has been updated, subscribe from a ' + 'component and invoke store.getState() in the callback to access the latest state. ' + 'See https://redux.js.org/api/store#subscribelistener for more details.');
}
var isSubscribed = true;
ensureCanMutateNextListeners();
nextListeners.push(listener);
return function unsubscribe() {
if (!isSubscribed) {
return;
}
if (isDispatching) {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(6) : 'You may not unsubscribe from a store listener while the reducer is executing. ' + 'See https://redux.js.org/api/store#subscribelistener for more details.');
}
isSubscribed = false;
ensureCanMutateNextListeners();
var index = nextListeners.indexOf(listener);
nextListeners.splice(index, 1);
currentListeners = null;
};
}
/**
* Dispatches an action. It is the only way to trigger a state change.
*
* The `reducer` function, used to create the store, will be called with the
* current state tree and the given `action`. Its return value will
* be considered the **next** state of the tree, and the change listeners
* will be notified.
*
* The base implementation only supports plain object actions. If you want to
* dispatch a Promise, an Observable, a thunk, or something else, you need to
* wrap your store creating function into the corresponding middleware. For
* example, see the documentation for the `redux-thunk` package. Even the
* middleware will eventually dispatch plain object actions using this method.
*
* @param {Object} action A plain object representing “what changed”. It is
* a good idea to keep actions serializable so you can record and replay user
* sessions, or use the time travelling `redux-devtools`. An action must have
* a `type` property which may not be `undefined`. It is a good idea to use
* string constants for action types.
*
* @returns {Object} For convenience, the same action object you dispatched.
*
* Note that, if you use a custom middleware, it may wrap `dispatch()` to
* return something else (for example, a Promise you can await).
*/
function dispatch(action) {
if (!isPlainObject(action)) {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(7) : "Actions must be plain objects. Instead, the actual type was: '" + kindOf(action) + "'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.");
}
if (typeof action.type === 'undefined') {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(8) : 'Actions may not have an undefined "type" property. You may have misspelled an action type string constant.');
}
if (isDispatching) {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(9) : 'Reducers may not dispatch actions.');
}
try {
isDispatching = true;
currentState = currentReducer(currentState, action);
} finally {
isDispatching = false;
}
var listeners = currentListeners = nextListeners;
for (var i = 0; i < listeners.length; i++) {
var listener = listeners[i];
listener();
}
return action;
}
/**
* Replaces the reducer currently used by the store to calculate the state.
*
* You might need this if your app implements code splitting and you want to
* load some of the reducers dynamically. You might also need this if you
* implement a hot reloading mechanism for Redux.
*
* @param {Function} nextReducer The reducer for the store to use instead.
* @returns {void}
*/
function replaceReducer(nextReducer) {
if (typeof nextReducer !== 'function') {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(10) : "Expected the nextReducer to be a function. Instead, received: '" + kindOf(nextReducer));
}
currentReducer = nextReducer; // This action has a similiar effect to ActionTypes.INIT.
// Any reducers that existed in both the new and old rootReducer
// will receive the previous state. This effectively populates
// the new state tree with any relevant data from the old one.
dispatch({
type: ActionTypes.REPLACE
});
}
/**
* Interoperability point for observable/reactive libraries.
* @returns {observable} A minimal observable of state changes.
* For more information, see the observable proposal:
* https://github.com/tc39/proposal-observable
*/
function observable() {
var _ref;
var outerSubscribe = subscribe;
return _ref = {
/**
* The minimal observable subscription method.
* @param {Object} observer Any object that can be used as an observer.
* The observer object should have a `next` method.
* @returns {subscription} An object with an `unsubscribe` method that can
* be used to unsubscribe the observable from the store, and prevent further
* emission of values from the observable.
*/
subscribe: function subscribe(observer) {
if (typeof observer !== 'object' || observer === null) {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(11) : "Expected the observer to be an object. Instead, received: '" + kindOf(observer) + "'");
}
function observeState() {
if (observer.next) {
observer.next(getState());
}
}
observeState();
var unsubscribe = outerSubscribe(observeState);
return {
unsubscribe: unsubscribe
};
}
}, _ref[$$observable] = function () {
return this;
}, _ref;
} // When a store is created, an "INIT" action is dispatched so that every
// reducer returns their initial state. This effectively populates
// the initial state tree.
dispatch({
type: ActionTypes.INIT
});
return _ref2 = {
dispatch: dispatch,
subscribe: subscribe,
getState: getState,
replaceReducer: replaceReducer
}, _ref2[$$observable] = observable, _ref2;
}
/**
* 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);
} catch (e) {} // eslint-disable-line no-empty
}
function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {
var reducerKeys = Object.keys(reducers);
var argumentName = action && action.type === ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer';
if (reducerKeys.length === 0) {
return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.';
}
if (!isPlainObject(inputState)) {
return "The " + argumentName + " has unexpected type of \"" + kindOf(inputState) + "\". Expected argument to be an object with the following " + ("keys: \"" + reducerKeys.join('", "') + "\"");
}
var unexpectedKeys = Object.keys(inputState).filter(function (key) {
return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key];
});
unexpectedKeys.forEach(function (key) {
unexpectedKeyCache[key] = true;
});
if (action && action.type === ActionTypes.REPLACE) return;
if (unexpectedKeys.length > 0) {
return "Unexpected " + (unexpectedKeys.length > 1 ? 'keys' : 'key') + " " + ("\"" + unexpectedKeys.join('", "') + "\" found in " + argumentName + ". ") + "Expected to find one of the known reducer keys instead: " + ("\"" + reducerKeys.join('", "') + "\". Unexpected keys will be ignored.");
}
}
function assertReducerShape(reducers) {
Object.keys(reducers).forEach(function (key) {
var reducer = reducers[key];
var initialState = reducer(undefined, {
type: ActionTypes.INIT
});
if (typeof initialState === 'undefined') {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(12) : "The slice reducer for key \"" + key + "\" returned undefined during initialization. " + "If the state passed to the reducer is undefined, you must " + "explicitly return the initial state. The initial state may " + "not be undefined. If you don't want to set a value for this reducer, " + "you can use null instead of undefined.");
}
if (typeof reducer(undefined, {
type: ActionTypes.PROBE_UNKNOWN_ACTION()
}) === 'undefined') {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(13) : "The slice reducer for key \"" + key + "\" returned undefined when probed with a random type. " + ("Don't try to handle '" + ActionTypes.INIT + "' or other actions in \"redux/*\" ") + "namespace. They are considered private. Instead, you must return the " + "current state for any unknown actions, unless it is undefined, " + "in which case you must return the initial state, regardless of the " + "action type. The initial state may not be undefined, but can be null.");
}
});
}
/**
* Turns an object whose values are different reducer functions, into a single
* reducer function. It will call every child reducer, and gather their results
* into a single state object, whose keys correspond to the keys of the passed
* reducer functions.
*
* @param {Object} reducers An object whose values correspond to different
* reducer functions that need to be combined into one. One handy way to obtain
* it is to use ES6 `import * as reducers` syntax. The reducers may never return
* undefined for any action. Instead, they should return their initial state
* if the state passed to them was undefined, and the current state for any
* unrecognized action.
*
* @returns {Function} A reducer function that invokes every reducer inside the
* passed object, and builds a state object with the same shape.
*/
function combineReducers(reducers) {
var reducerKeys = Object.keys(reducers);
var finalReducers = {};
for (var i = 0; i < reducerKeys.length; i++) {
var key = reducerKeys[i];
if (process.env.NODE_ENV !== 'production') {
if (typeof reducers[key] === 'undefined') {
warning("No reducer provided for key \"" + key + "\"");
}
}
if (typeof reducers[key] === 'function') {
finalReducers[key] = reducers[key];
}
}
var finalReducerKeys = Object.keys(finalReducers); // This is used to make sure we don't warn about the same
// keys multiple times.
var unexpectedKeyCache;
if (process.env.NODE_ENV !== 'production') {
unexpectedKeyCache = {};
}
var shapeAssertionError;
try {
assertReducerShape(finalReducers);
} catch (e) {
shapeAssertionError = e;
}
return function combination(state, action) {
if (state === void 0) {
state = {};
}
if (shapeAssertionError) {
throw shapeAssertionError;
}
if (process.env.NODE_ENV !== 'production') {
var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache);
if (warningMessage) {
warning(warningMessage);
}
}
var hasChanged = false;
var nextState = {};
for (var _i = 0; _i < finalReducerKeys.length; _i++) {
var _key = finalReducerKeys[_i];
var reducer = finalReducers[_key];
var previousStateForKey = state[_key];
var nextStateForKey = reducer(previousStateForKey, action);
if (typeof nextStateForKey === 'undefined') {
var actionType = action && action.type;
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(14) : "When called with an action of type " + (actionType ? "\"" + String(actionType) + "\"" : '(unknown type)') + ", the slice reducer for key \"" + _key + "\" returned undefined. " + "To ignore an action, you must explicitly return the previous state. " + "If you want this reducer to hold no value, you can return null instead of undefined.");
}
nextState[_key] = nextStateForKey;
hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
}
hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length;
return hasChanged ? nextState : state;
};
}
function bindActionCreator(actionCreator, dispatch) {
return function () {
return dispatch(actionCreator.apply(this, arguments));
};
}
/**
* Turns an object whose values are action creators, into an object with the
* same keys, but with every function wrapped into a `dispatch` call so they
* may be invoked directly. This is just a convenience method, as you can call
* `store.dispatch(MyActionCreators.doSomething())` yourself just fine.
*
* For convenience, you can also pass an action creator as the first argument,
* and get a dispatch wrapped function in return.
*
* @param {Function|Object} actionCreators An object whose values are action
* creator functions. One handy way to obtain it is to use ES6 `import * as`
* syntax. You may also pass a single function.
*
* @param {Function} dispatch The `dispatch` function available on your Redux
* store.
*
* @returns {Function|Object} The object mimicking the original object, but with
* every action creator wrapped into the `dispatch` call. If you passed a
* function as `actionCreators`, the return value will also be a single
* function.
*/
function bindActionCreators(actionCreators, dispatch) {
if (typeof actionCreators === 'function') {
return bindActionCreator(actionCreators, dispatch);
}
if (typeof actionCreators !== 'object' || actionCreators === null) {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(16) : "bindActionCreators expected an object or a function, but instead received: '" + kindOf(actionCreators) + "'. " + "Did you write \"import ActionCreators from\" instead of \"import * as ActionCreators from\"?");
}
var boundActionCreators = {};
for (var key in actionCreators) {
var actionCreator = actionCreators[key];
if (typeof actionCreator === 'function') {
boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);
}
}
return boundActionCreators;
}
/**
* Composes single-argument functions from right to left. The rightmost
* function can take multiple arguments as it provides the signature for
* the resulting composite function.
*
* @param {...Function} funcs The functions to compose.
* @returns {Function} A function obtained by composing the argument functions
* from right to left. For example, compose(f, g, h) is identical to doing
* (...args) => f(g(h(...args))).
*/
function compose() {
for (var _len = arguments.length, funcs = new 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];
}
return funcs.reduce(function (a, b) {
return function () {
return a(b.apply(void 0, arguments));
};
});
}
/**
* Creates a store enhancer that applies middleware to the dispatch method
* of the Redux store. This is handy for a variety of tasks, such as expressing
* asynchronous actions in a concise manner, or logging every action payload.
*
* See `redux-thunk` package as an example of the Redux middleware.
*
* Because middleware is potentially asynchronous, this should be the first
* store enhancer in the composition chain.
*
* Note that each middleware will be given the `dispatch` and `getState` functions
* as named arguments.
*
* @param {...Function} middlewares The middleware chain to be applied.
* @returns {Function} A store enhancer applying the middleware.
*/
function applyMiddleware() {
for (var _len = arguments.length, middlewares = new Array(_len), _key = 0; _key < _len; _key++) {
middlewares[_key] = arguments[_key];
}
return function (createStore) {
return function () {
var store = createStore.apply(void 0, arguments);
var _dispatch = function dispatch() {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(15) : 'Dispatching while constructing your middleware is not allowed. ' + 'Other middleware would not be applied to this dispatch.');
};
var middlewareAPI = {
getState: store.getState,
dispatch: function dispatch() {
return _dispatch.apply(void 0, arguments);
}
};
var chain = middlewares.map(function (middleware) {
return middleware(middlewareAPI);
});
_dispatch = compose.apply(void 0, chain)(store.dispatch);
return _objectSpread(_objectSpread({}, store), {}, {
dispatch: _dispatch
});
};
};
}
/*
* This is a dummy function to check if the function name has been altered by minification.
* If the function has been minified and NODE_ENV !== 'production', warn the user.
*/
function isCrushed() {}
if (process.env.NODE_ENV !== 'production' && typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed') {
warning('You are currently using minified code outside of NODE_ENV === "production". ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or setting mode to production in webpack (https://webpack.js.org/concepts/mode/) ' + 'to ensure you have the correct code for your production build.');
}
export { ActionTypes as __DO_NOT_USE__ActionTypes, applyMiddleware, bindActionCreators, combineReducers, compose, createStore };
webpack://frontend-mybets/../../node_modules/rehackt/index.js
"use strict";
module.exports = require("react");
webpack://frontend-mybets/../../node_modules/scheduler/cjs/scheduler.production.min.js
/**
* @license React
* scheduler.production.min.js
*
* 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.
*/
'use strict';function f(a,b){var c=a.length;a.push(b);a:for(;0<c;){var d=c-1>>>1,e=a[d];if(0<g(e,b))a[d]=b,a[c]=e,c=d;else break a}}function h(a){return 0===a.length?null:a[0]}function k(a){if(0===a.length)return null;var b=a[0],c=a.pop();if(c!==b){a[0]=c;a:for(var d=0,e=a.length,w=e>>>1;d<w;){var m=2*(d+1)-1,C=a[m],n=m+1,x=a[n];if(0>g(C,c))n<e&&0>g(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(n<e&&0>g(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b}
function g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if("object"===typeof performance&&"function"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()}}else{var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q}}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D="function"===typeof setTimeout?setTimeout:null,E="function"===typeof clearTimeout?clearTimeout:null,F="undefined"!==typeof setImmediate?setImmediate:null;
"undefined"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t)}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else{var b=h(t);null!==b&&K(H,b.startTime-a)}}
function J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if("function"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();"function"===typeof e?v.callback=e:v===h(r)&&k(r);G(b)}else k(r);v=h(r)}if(null!==v)var w=!0;else{var m=h(t);null!==m&&K(H,m.startTime-b);w=!1}return w}finally{v=null,y=c,z=!1}}var N=!1,O=null,L=-1,P=5,Q=-1;
function M(){return exports.unstable_now()-Q<P?!1:!0}function R(){if(null!==O){var a=exports.unstable_now();Q=a;var b=!0;try{b=O(!0,a)}finally{b?S():(N=!1,O=null)}}else N=!1}var S;if("function"===typeof F)S=function(){F(R)};else if("undefined"!==typeof MessageChannel){var T=new MessageChannel,U=T.port2;T.port1.onmessage=R;S=function(){U.postMessage(null)}}else S=function(){D(R,0)};function I(a){O=a;N||(N=!0,S())}function K(a,b){L=D(function(){a(exports.unstable_now())},b)}
exports.unstable_IdlePriority=5;exports.unstable_ImmediatePriority=1;exports.unstable_LowPriority=4;exports.unstable_NormalPriority=3;exports.unstable_Profiling=null;exports.unstable_UserBlockingPriority=2;exports.unstable_cancelCallback=function(a){a.callback=null};exports.unstable_continueExecution=function(){A||z||(A=!0,I(J))};
exports.unstable_forceFrameRate=function(a){0>a||125<a?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):P=0<a?Math.floor(1E3/a):5};exports.unstable_getCurrentPriorityLevel=function(){return y};exports.unstable_getFirstCallbackNode=function(){return h(r)};exports.unstable_next=function(a){switch(y){case 1:case 2:case 3:var b=3;break;default:b=y}var c=y;y=b;try{return a()}finally{y=c}};exports.unstable_pauseExecution=function(){};
exports.unstable_requestPaint=function(){};exports.unstable_runWithPriority=function(a,b){switch(a){case 1:case 2:case 3:case 4:case 5:break;default:a=3}var c=y;y=a;try{return b()}finally{y=c}};
exports.unstable_scheduleCallback=function(a,b,c){var d=exports.unstable_now();"object"===typeof c&&null!==c?(c=c.delay,c="number"===typeof c&&0<c?d+c:d):c=d;switch(a){case 1:var e=-1;break;case 2:e=250;break;case 5:e=1073741823;break;case 4:e=1E4;break;default:e=5E3}e=c+e;a={id:u++,callback:b,priorityLevel:a,startTime:c,expirationTime:e,sortIndex:-1};c>d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a};
exports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c}}};
webpack://frontend-mybets/../../node_modules/scheduler/index.js
'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/scheduler.production.min.js');
} else {
module.exports = require('./cjs/scheduler.development.js');
}
webpack://frontend-mybets/../../node_modules/shallowequal/index.js
//
module.exports = function shallowEqual(objA, objB, compare, compareContext) {
var ret = compare ? compare.call(compareContext, objA, objB) : void 0;
if (ret !== void 0) {
return !!ret;
}
if (objA === objB) {
return true;
}
if (typeof objA !== "object" || !objA || typeof objB !== "object" || !objB) {
return false;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
var bHasOwnProperty = Object.prototype.hasOwnProperty.bind(objB);
// Test for A's keys different from B.
for (var idx = 0; idx < keysA.length; idx++) {
var key = keysA[idx];
if (!bHasOwnProperty(key)) {
return false;
}
var valueA = objA[key];
var valueB = objB[key];
ret = compare ? compare.call(compareContext, valueA, valueB, key) : void 0;
if (ret === false || (ret === void 0 && valueA !== valueB)) {
return false;
}
}
return true;
};
webpack://frontend-mybets/../../node_modules/split-on-first/index.js
'use strict';
module.exports = (string, separator) => {
if (!(typeof string === 'string' && typeof separator === 'string')) {
throw new TypeError('Expected the arguments to be of type `string`');
}
if (separator === '') {
return [string];
}
const separatorIndex = string.indexOf(separator);
if (separatorIndex === -1) {
return [string];
}
return [
string.slice(0, separatorIndex),
string.slice(separatorIndex + separator.length)
];
};
webpack://frontend-mybets/../../node_modules/strict-uri-encode/index.js
'use strict';
module.exports = str => encodeURIComponent(str).replace(/[!'()*]/g, x => `%${x.charCodeAt(0).toString(16).toUpperCase()}`);
webpack://frontend-mybets/../../node_modules/@emotion/memoize/dist/emotion-memoize.esm.js
function memoize(fn) {
var cache = Object.create(null);
return function (arg) {
if (cache[arg] === undefined) cache[arg] = fn(arg);
return cache[arg];
};
}
export { memoize as default };
webpack://frontend-mybets/../../node_modules/@emotion/is-prop-valid/dist/emotion-is-prop-valid.esm.js
import memoize from '@emotion/memoize';
// eslint-disable-next-line no-undef
var reactPropsRegex = /^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|abbr|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|disableRemotePlayback|download|draggable|encType|enterKeyHint|fetchpriority|fetchPriority|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|translate|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|incremental|fallback|inert|itemProp|itemScope|itemType|itemID|itemRef|on|option|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/; // https://esbench.com/bench/5bfee68a4cd7e6009ef61d23
var isPropValid = /* #__PURE__ */memoize(function (prop) {
return reactPropsRegex.test(prop) || prop.charCodeAt(0) === 111
/* o */
&& prop.charCodeAt(1) === 110
/* n */
&& prop.charCodeAt(2) < 91;
}
/* Z+1 */
);
export { isPropValid as default };
webpack://frontend-mybets/../../node_modules/styled-components/dist/styled-components.browser.esm.js
import{typeOf as e,isElement as t,isValidElementType as n}from"react-is";import r,{useState as o,useContext as s,useMemo as i,useEffect as a,useRef as c,createElement as u,useDebugValue as l,useLayoutEffect as d}from"react";import h from"shallowequal";import p from"@emotion/stylis";import f from"@emotion/unitless";import m from"@emotion/is-prop-valid";import y from"hoist-non-react-statics";function v(){return(v=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}var g=function(e,t){for(var n=[e[0]],r=0,o=t.length;r<o;r+=1)n.push(t[r],e[r+1]);return n},S=function(t){return null!==t&&"object"==typeof t&&"[object Object]"===(t.toString?t.toString():Object.prototype.toString.call(t))&&!e(t)},w=Object.freeze([]),E=Object.freeze({});function b(e){return"function"==typeof e}function _(e){return"production"!==process.env.NODE_ENV&&"string"==typeof e&&e||e.displayName||e.name||"Component"}function N(e){return e&&"string"==typeof e.styledComponentId}var A="undefined"!=typeof process&&(process.env.REACT_APP_SC_ATTR||process.env.SC_ATTR)||"data-styled",C="5.3.1",I="undefined"!=typeof window&&"HTMLElement"in window,P=Boolean("boolean"==typeof SC_DISABLE_SPEEDY?SC_DISABLE_SPEEDY:"undefined"!=typeof process&&void 0!==process.env.REACT_APP_SC_DISABLE_SPEEDY&&""!==process.env.REACT_APP_SC_DISABLE_SPEEDY?"false"!==process.env.REACT_APP_SC_DISABLE_SPEEDY&&process.env.REACT_APP_SC_DISABLE_SPEEDY:"undefined"!=typeof process&&void 0!==process.env.SC_DISABLE_SPEEDY&&""!==process.env.SC_DISABLE_SPEEDY?"false"!==process.env.SC_DISABLE_SPEEDY&&process.env.SC_DISABLE_SPEEDY:"production"!==process.env.NODE_ENV),O={},R="production"!==process.env.NODE_ENV?{1:"Cannot create styled-component for component: %s.\n\n",2:"Can't collect styles once you've consumed a `ServerStyleSheet`'s styles! `ServerStyleSheet` is a one off instance for each server-side render cycle.\n\n- Are you trying to reuse it across renders?\n- Are you accidentally calling collectStyles twice?\n\n",3:"Streaming SSR is only supported in a Node.js environment; Please do not try to call this method in the browser.\n\n",4:"The `StyleSheetManager` expects a valid target or sheet prop!\n\n- Does this error occur on the client and is your target falsy?\n- Does this error occur on the server and is the sheet falsy?\n\n",5:"The clone method cannot be used on the client!\n\n- Are you running in a client-like environment on the server?\n- Are you trying to run SSR on the client?\n\n",6:"Trying to insert a new style tag, but the given Node is unmounted!\n\n- Are you using a custom target that isn't mounted?\n- Does your document not have a valid head element?\n- Have you accidentally removed a style tag manually?\n\n",7:'ThemeProvider: Please return an object from your "theme" prop function, e.g.\n\n```js\ntheme={() => ({})}\n```\n\n',8:'ThemeProvider: Please make your "theme" prop an object.\n\n',9:"Missing document `<head>`\n\n",10:"Cannot find a StyleSheet instance. Usually this happens if there are multiple copies of styled-components loaded at once. Check out this issue for how to troubleshoot and fix the common cases where this situation can happen: https://github.com/styled-components/styled-components/issues/1941#issuecomment-417862021\n\n",11:"_This error was replaced with a dev-time warning, it will be deleted for v4 final._ [createGlobalStyle] received children which will not be rendered. Please use the component without passing children elements.\n\n",12:"It seems you are interpolating a keyframe declaration (%s) into an untagged string. This was supported in styled-components v3, but is not longer supported in v4 as keyframes are now injected on-demand. Please wrap your string in the css\\`\\` helper which ensures the styles are injected correctly. See https://www.styled-components.com/docs/api#css\n\n",13:"%s is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details.\n\n",14:'ThemeProvider: "theme" prop is required.\n\n',15:"A stylis plugin has been supplied that is not named. We need a name for each plugin to be able to prevent styling collisions between different stylis configurations within the same app. Before you pass your plugin to `<StyleSheetManager stylisPlugins={[]}>`, please make sure each plugin is uniquely-named, e.g.\n\n```js\nObject.defineProperty(importedPlugin, 'name', { value: 'some-unique-name' });\n```\n\n",16:"Reached the limit of how many styled components may be created at group %s.\nYou may only create up to 1,073,741,824 components. If you're creating components dynamically,\nas for instance in your render method then you may be running into this limitation.\n\n",17:"CSSStyleSheet could not be found on HTMLStyleElement.\nHas styled-components' style tag been unmounted or altered by another script?\n"}:{};function D(){for(var e=arguments.length<=0?void 0:arguments[0],t=[],n=1,r=arguments.length;n<r;n+=1)t.push(n<0||arguments.length<=n?void 0:arguments[n]);return t.forEach((function(t){e=e.replace(/%[a-z]/,t)})),e}function j(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];throw"production"===process.env.NODE_ENV?new Error("An error occurred. See https://git.io/JUIaE#"+e+" for more information."+(n.length>0?" Args: "+n.join(", "):"")):new Error(D.apply(void 0,[R[e]].concat(n)).trim())}var T=function(){function e(e){this.groupSizes=new Uint32Array(512),this.length=512,this.tag=e}var t=e.prototype;return t.indexOfGroup=function(e){for(var t=0,n=0;n<e;n++)t+=this.groupSizes[n];return t},t.insertRules=function(e,t){if(e>=this.groupSizes.length){for(var n=this.groupSizes,r=n.length,o=r;e>=o;)(o<<=1)<0&&j(16,""+e);this.groupSizes=new Uint32Array(o),this.groupSizes.set(n),this.length=o;for(var s=r;s<o;s++)this.groupSizes[s]=0}for(var i=this.indexOfGroup(e+1),a=0,c=t.length;a<c;a++)this.tag.insertRule(i,t[a])&&(this.groupSizes[e]++,i++)},t.clearGroup=function(e){if(e<this.length){var t=this.groupSizes[e],n=this.indexOfGroup(e),r=n+t;this.groupSizes[e]=0;for(var o=n;o<r;o++)this.tag.deleteRule(n)}},t.getGroup=function(e){var t="";if(e>=this.length||0===this.groupSizes[e])return t;for(var n=this.groupSizes[e],r=this.indexOfGroup(e),o=r+n,s=r;s<o;s++)t+=this.tag.getRule(s)+"/*!sc*/\n";return t},e}(),k=new Map,x=new Map,V=1,B=function(e){if(k.has(e))return k.get(e);for(;x.has(V);)V++;var t=V++;return"production"!==process.env.NODE_ENV&&((0|t)<0||t>1<<30)&&j(16,""+t),k.set(e,t),x.set(t,e),t},M=function(e){return x.get(e)},z=function(e,t){t>=V&&(V=t+1),k.set(e,t),x.set(t,e)},L="style["+A+'][data-styled-version="5.3.1"]',G=new RegExp("^"+A+'\\.g(\\d+)\\[id="([\\w\\d-]+)"\\].*?"([^"]*)'),F=function(e,t,n){for(var r,o=n.split(","),s=0,i=o.length;s<i;s++)(r=o[s])&&e.registerName(t,r)},Y=function(e,t){for(var n=(t.innerHTML||"").split("/*!sc*/\n"),r=[],o=0,s=n.length;o<s;o++){var i=n[o].trim();if(i){var a=i.match(G);if(a){var c=0|parseInt(a[1],10),u=a[2];0!==c&&(z(u,c),F(e,u,a[3]),e.getTag().insertRules(c,r)),r.length=0}else r.push(i)}}},q=function(){return"undefined"!=typeof window&&void 0!==window.__webpack_nonce__?window.__webpack_nonce__:null},H=function(e){var t=document.head,n=e||t,r=document.createElement("style"),o=function(e){for(var t=e.childNodes,n=t.length;n>=0;n--){var r=t[n];if(r&&1===r.nodeType&&r.hasAttribute(A))return r}}(n),s=void 0!==o?o.nextSibling:null;r.setAttribute(A,"active"),r.setAttribute("data-styled-version","5.3.1");var i=q();return i&&r.setAttribute("nonce",i),n.insertBefore(r,s),r},$=function(){function e(e){var t=this.element=H(e);t.appendChild(document.createTextNode("")),this.sheet=function(e){if(e.sheet)return e.sheet;for(var t=document.styleSheets,n=0,r=t.length;n<r;n++){var o=t[n];if(o.ownerNode===e)return o}j(17)}(t),this.length=0}var t=e.prototype;return t.insertRule=function(e,t){try{return this.sheet.insertRule(t,e),this.length++,!0}catch(e){return!1}},t.deleteRule=function(e){this.sheet.deleteRule(e),this.length--},t.getRule=function(e){var t=this.sheet.cssRules[e];return void 0!==t&&"string"==typeof t.cssText?t.cssText:""},e}(),W=function(){function e(e){var t=this.element=H(e);this.nodes=t.childNodes,this.length=0}var t=e.prototype;return t.insertRule=function(e,t){if(e<=this.length&&e>=0){var n=document.createTextNode(t),r=this.nodes[e];return this.element.insertBefore(n,r||null),this.length++,!0}return!1},t.deleteRule=function(e){this.element.removeChild(this.nodes[e]),this.length--},t.getRule=function(e){return e<this.length?this.nodes[e].textContent:""},e}(),U=function(){function e(e){this.rules=[],this.length=0}var t=e.prototype;return t.insertRule=function(e,t){return e<=this.length&&(this.rules.splice(e,0,t),this.length++,!0)},t.deleteRule=function(e){this.rules.splice(e,1),this.length--},t.getRule=function(e){return e<this.length?this.rules[e]:""},e}(),J=I,X={isServer:!I,useCSSOMInjection:!P},Z=function(){function e(e,t,n){void 0===e&&(e=E),void 0===t&&(t={}),this.options=v({},X,{},e),this.gs=t,this.names=new Map(n),this.server=!!e.isServer,!this.server&&I&&J&&(J=!1,function(e){for(var t=document.querySelectorAll(L),n=0,r=t.length;n<r;n++){var o=t[n];o&&"active"!==o.getAttribute(A)&&(Y(e,o),o.parentNode&&o.parentNode.removeChild(o))}}(this))}e.registerId=function(e){return B(e)};var t=e.prototype;return t.reconstructWithOptions=function(t,n){return void 0===n&&(n=!0),new e(v({},this.options,{},t),this.gs,n&&this.names||void 0)},t.allocateGSInstance=function(e){return this.gs[e]=(this.gs[e]||0)+1},t.getTag=function(){return this.tag||(this.tag=(n=(t=this.options).isServer,r=t.useCSSOMInjection,o=t.target,e=n?new U(o):r?new $(o):new W(o),new T(e)));var e,t,n,r,o},t.hasNameForId=function(e,t){return this.names.has(e)&&this.names.get(e).has(t)},t.registerName=function(e,t){if(B(e),this.names.has(e))this.names.get(e).add(t);else{var n=new Set;n.add(t),this.names.set(e,n)}},t.insertRules=function(e,t,n){this.registerName(e,t),this.getTag().insertRules(B(e),n)},t.clearNames=function(e){this.names.has(e)&&this.names.get(e).clear()},t.clearRules=function(e){this.getTag().clearGroup(B(e)),this.clearNames(e)},t.clearTag=function(){this.tag=void 0},t.toString=function(){return function(e){for(var t=e.getTag(),n=t.length,r="",o=0;o<n;o++){var s=M(o);if(void 0!==s){var i=e.names.get(s),a=t.getGroup(o);if(i&&a&&i.size){var c=A+".g"+o+'[id="'+s+'"]',u="";void 0!==i&&i.forEach((function(e){e.length>0&&(u+=e+",")})),r+=""+a+c+'{content:"'+u+'"}/*!sc*/\n'}}}return r}(this)},e}(),K=/(a)(d)/gi,Q=function(e){return String.fromCharCode(e+(e>25?39:97))};function ee(e){var t,n="";for(t=Math.abs(e);t>52;t=t/52|0)n=Q(t%52)+n;return(Q(t%52)+n).replace(K,"$1-$2")}var te=function(e,t){for(var n=t.length;n;)e=33*e^t.charCodeAt(--n);return e},ne=function(e){return te(5381,e)};function re(e){for(var t=0;t<e.length;t+=1){var n=e[t];if(b(n)&&!N(n))return!1}return!0}var oe=ne("5.3.1"),se=function(){function e(e,t,n){this.rules=e,this.staticRulesId="",this.isStatic="production"===process.env.NODE_ENV&&(void 0===n||n.isStatic)&&re(e),this.componentId=t,this.baseHash=te(oe,t),this.baseStyle=n,Z.registerId(t)}return e.prototype.generateAndInjectStyles=function(e,t,n){var r=this.componentId,o=[];if(this.baseStyle&&o.push(this.baseStyle.generateAndInjectStyles(e,t,n)),this.isStatic&&!n.hash)if(this.staticRulesId&&t.hasNameForId(r,this.staticRulesId))o.push(this.staticRulesId);else{var s=Ne(this.rules,e,t,n).join(""),i=ee(te(this.baseHash,s)>>>0);if(!t.hasNameForId(r,i)){var a=n(s,"."+i,void 0,r);t.insertRules(r,i,a)}o.push(i),this.staticRulesId=i}else{for(var c=this.rules.length,u=te(this.baseHash,n.hash),l="",d=0;d<c;d++){var h=this.rules[d];if("string"==typeof h)l+=h,"production"!==process.env.NODE_ENV&&(u=te(u,h+d));else if(h){var p=Ne(h,e,t,n),f=Array.isArray(p)?p.join(""):p;u=te(u,f+d),l+=f}}if(l){var m=ee(u>>>0);if(!t.hasNameForId(r,m)){var y=n(l,"."+m,void 0,r);t.insertRules(r,m,y)}o.push(m)}}return o.join(" ")},e}(),ie=/^\s*\/\/.*$/gm,ae=[":","[",".","#"];function ce(e){var t,n,r,o,s=void 0===e?E:e,i=s.options,a=void 0===i?E:i,c=s.plugins,u=void 0===c?w:c,l=new p(a),d=[],h=function(e){function t(t){if(t)try{e(t+"}")}catch(e){}}return function(n,r,o,s,i,a,c,u,l,d){switch(n){case 1:if(0===l&&64===r.charCodeAt(0))return e(r+";"),"";break;case 2:if(0===u)return r+"/*|*/";break;case 3:switch(u){case 102:case 112:return e(o[0]+r),"";default:return r+(0===d?"/*|*/":"")}case-2:r.split("/*|*/}").forEach(t)}}}((function(e){d.push(e)})),f=function(e,r,s){return 0===r&&-1!==ae.indexOf(s[n.length])||s.match(o)?e:"."+t};function m(e,s,i,a){void 0===a&&(a="&");var c=e.replace(ie,""),u=s&&i?i+" "+s+" { "+c+" }":c;return t=a,n=s,r=new RegExp("\\"+n+"\\b","g"),o=new RegExp("(\\"+n+"\\b){2,}"),l(i||!s?"":s,u)}return l.use([].concat(u,[function(e,t,o){2===e&&o.length&&o[0].lastIndexOf(n)>0&&(o[0]=o[0].replace(r,f))},h,function(e){if(-2===e){var t=d;return d=[],t}}])),m.hash=u.length?u.reduce((function(e,t){return t.name||j(15),te(e,t.name)}),5381).toString():"",m}var ue=r.createContext(),le=ue.Consumer,de=r.createContext(),he=(de.Consumer,new Z),pe=ce();function fe(){return s(ue)||he}function me(){return s(de)||pe}function ye(e){var t=o(e.stylisPlugins),n=t[0],s=t[1],c=fe(),u=i((function(){var t=c;return e.sheet?t=e.sheet:e.target&&(t=t.reconstructWithOptions({target:e.target},!1)),e.disableCSSOMInjection&&(t=t.reconstructWithOptions({useCSSOMInjection:!1})),t}),[e.disableCSSOMInjection,e.sheet,e.target]),l=i((function(){return ce({options:{prefix:!e.disableVendorPrefixes},plugins:n})}),[e.disableVendorPrefixes,n]);return a((function(){h(n,e.stylisPlugins)||s(e.stylisPlugins)}),[e.stylisPlugins]),r.createElement(ue.Provider,{value:u},r.createElement(de.Provider,{value:l},"production"!==process.env.NODE_ENV?r.Children.only(e.children):e.children))}var ve=function(){function e(e,t){var n=this;this.inject=function(e,t){void 0===t&&(t=pe);var r=n.name+t.hash;e.hasNameForId(n.id,r)||e.insertRules(n.id,r,t(n.rules,r,"@keyframes"))},this.toString=function(){return j(12,String(n.name))},this.name=e,this.id="sc-keyframes-"+e,this.rules=t}return e.prototype.getName=function(e){return void 0===e&&(e=pe),this.name+e.hash},e}(),ge=/([A-Z])/,Se=/([A-Z])/g,we=/^ms-/,Ee=function(e){return"-"+e.toLowerCase()};function be(e){return ge.test(e)?e.replace(Se,Ee).replace(we,"-ms-"):e}var _e=function(e){return null==e||!1===e||""===e};function Ne(e,n,r,o){if(Array.isArray(e)){for(var s,i=[],a=0,c=e.length;a<c;a+=1)""!==(s=Ne(e[a],n,r,o))&&(Array.isArray(s)?i.push.apply(i,s):i.push(s));return i}if(_e(e))return"";if(N(e))return"."+e.styledComponentId;if(b(e)){if("function"!=typeof(l=e)||l.prototype&&l.prototype.isReactComponent||!n)return e;var u=e(n);return"production"!==process.env.NODE_ENV&&t(u)&&console.warn(_(e)+" is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details."),Ne(u,n,r,o)}var l;return e instanceof ve?r?(e.inject(r,o),e.getName(o)):e:S(e)?function e(t,n){var r,o,s=[];for(var i in t)t.hasOwnProperty(i)&&!_e(t[i])&&(Array.isArray(t[i])&&t[i].isCss||b(t[i])?s.push(be(i)+":",t[i],";"):S(t[i])?s.push.apply(s,e(t[i],i)):s.push(be(i)+": "+(r=i,null==(o=t[i])||"boolean"==typeof o||""===o?"":"number"!=typeof o||0===o||r in f?String(o).trim():o+"px")+";"));return n?[n+" {"].concat(s,["}"]):s}(e):e.toString()}var Ae=function(e){return Array.isArray(e)&&(e.isCss=!0),e};function Ce(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return b(e)||S(e)?Ae(Ne(g(w,[e].concat(n)))):0===n.length&&1===e.length&&"string"==typeof e[0]?e:Ae(Ne(g(e,n)))}var Ie=/invalid hook call/i,Pe=new Set,Oe=function(e,t){if("production"!==process.env.NODE_ENV){var n="The component "+e+(t?' with the id of "'+t+'"':"")+" has been created dynamically.\nYou may see this warning because you've called styled inside another component.\nTo resolve this only create new StyledComponents outside of any render method and function component.",r=console.error;try{var o=!0;console.error=function(e){if(Ie.test(e))o=!1,Pe.delete(n);else{for(var t=arguments.length,s=new Array(t>1?t-1:0),i=1;i<t;i++)s[i-1]=arguments[i];r.apply(void 0,[e].concat(s))}},c(),o&&!Pe.has(n)&&(console.warn(n),Pe.add(n))}catch(e){Ie.test(e.message)&&Pe.delete(n)}finally{console.error=r}}},Re=function(e,t,n){return void 0===n&&(n=E),e.theme!==n.theme&&e.theme||t||n.theme},De=/[!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~-]+/g,je=/(^-|-$)/g;function Te(e){return e.replace(De,"-").replace(je,"")}var ke=function(e){return ee(ne(e)>>>0)};function xe(e){return"string"==typeof e&&("production"===process.env.NODE_ENV||e.charAt(0)===e.charAt(0).toLowerCase())}var Ve=function(e){return"function"==typeof e||"object"==typeof e&&null!==e&&!Array.isArray(e)},Be=function(e){return"__proto__"!==e&&"constructor"!==e&&"prototype"!==e};function Me(e,t,n){var r=e[n];Ve(t)&&Ve(r)?ze(r,t):e[n]=t}function ze(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];for(var o=0,s=n;o<s.length;o++){var i=s[o];if(Ve(i))for(var a in i)Be(a)&&Me(e,i[a],a)}return e}var Le=r.createContext(),Ge=Le.Consumer;function Fe(e){var t=s(Le),n=i((function(){return function(e,t){if(!e)return j(14);if(b(e)){var n=e(t);return"production"===process.env.NODE_ENV||null!==n&&!Array.isArray(n)&&"object"==typeof n?n:j(7)}return Array.isArray(e)||"object"!=typeof e?j(8):t?v({},t,{},e):e}(e.theme,t)}),[e.theme,t]);return e.children?r.createElement(Le.Provider,{value:n},e.children):null}var Ye={};function qe(e,t,n){var o=N(e),i=!xe(e),a=t.attrs,c=void 0===a?w:a,d=t.componentId,h=void 0===d?function(e,t){var n="string"!=typeof e?"sc":Te(e);Ye[n]=(Ye[n]||0)+1;var r=n+"-"+ke("5.3.1"+n+Ye[n]);return t?t+"-"+r:r}(t.displayName,t.parentComponentId):d,p=t.displayName,f=void 0===p?function(e){return xe(e)?"styled."+e:"Styled("+_(e)+")"}(e):p,g=t.displayName&&t.componentId?Te(t.displayName)+"-"+t.componentId:t.componentId||h,S=o&&e.attrs?Array.prototype.concat(e.attrs,c).filter(Boolean):c,A=t.shouldForwardProp;o&&e.shouldForwardProp&&(A=t.shouldForwardProp?function(n,r,o){return e.shouldForwardProp(n,r,o)&&t.shouldForwardProp(n,r,o)}:e.shouldForwardProp);var C,I=new se(n,g,o?e.componentStyle:void 0),P=I.isStatic&&0===c.length,O=function(e,t){return function(e,t,n,r){var o=e.attrs,i=e.componentStyle,a=e.defaultProps,c=e.foldedComponentIds,d=e.shouldForwardProp,h=e.styledComponentId,p=e.target;"production"!==process.env.NODE_ENV&&l(h);var f=function(e,t,n){void 0===e&&(e=E);var r=v({},t,{theme:e}),o={};return n.forEach((function(e){var t,n,s,i=e;for(t in b(i)&&(i=i(r)),i)r[t]=o[t]="className"===t?(n=o[t],s=i[t],n&&s?n+" "+s:n||s):i[t]})),[r,o]}(Re(t,s(Le),a)||E,t,o),y=f[0],g=f[1],S=function(e,t,n,r){var o=fe(),s=me(),i=t?e.generateAndInjectStyles(E,o,s):e.generateAndInjectStyles(n,o,s);return"production"!==process.env.NODE_ENV&&l(i),"production"!==process.env.NODE_ENV&&!t&&r&&r(i),i}(i,r,y,"production"!==process.env.NODE_ENV?e.warnTooManyClasses:void 0),w=n,_=g.$as||t.$as||g.as||t.as||p,N=xe(_),A=g!==t?v({},t,{},g):t,C={};for(var I in A)"$"!==I[0]&&"as"!==I&&("forwardedAs"===I?C.as=A[I]:(d?d(I,m,_):!N||m(I))&&(C[I]=A[I]));return t.style&&g.style!==t.style&&(C.style=v({},t.style,{},g.style)),C.className=Array.prototype.concat(c,h,S!==h?S:null,t.className,g.className).filter(Boolean).join(" "),C.ref=w,u(_,C)}(C,e,t,P)};return O.displayName=f,(C=r.forwardRef(O)).attrs=S,C.componentStyle=I,C.displayName=f,C.shouldForwardProp=A,C.foldedComponentIds=o?Array.prototype.concat(e.foldedComponentIds,e.styledComponentId):w,C.styledComponentId=g,C.target=o?e.target:e,C.withComponent=function(e){var r=t.componentId,o=function(e,t){if(null==e)return{};var n,r,o={},s=Object.keys(e);for(r=0;r<s.length;r++)n=s[r],t.indexOf(n)>=0||(o[n]=e[n]);return o}(t,["componentId"]),s=r&&r+"-"+(xe(e)?e:Te(_(e)));return qe(e,v({},o,{attrs:S,componentId:s}),n)},Object.defineProperty(C,"defaultProps",{get:function(){return this._foldedDefaultProps},set:function(t){this._foldedDefaultProps=o?ze({},e.defaultProps,t):t}}),"production"!==process.env.NODE_ENV&&(Oe(f,g),C.warnTooManyClasses=function(e,t){var n={},r=!1;return function(o){if(!r&&(n[o]=!0,Object.keys(n).length>=200)){var s=t?' with the id of "'+t+'"':"";console.warn("Over 200 classes were generated for component "+e+s+".\nConsider using the attrs method, together with a style object for frequently changed styles.\nExample:\n const Component = styled.div.attrs(props => ({\n style: {\n background: props.background,\n },\n }))`width: 100%;`\n\n <Component />"),r=!0,n={}}}}(f,g)),C.toString=function(){return"."+C.styledComponentId},i&&y(C,e,{attrs:!0,componentStyle:!0,displayName:!0,foldedComponentIds:!0,shouldForwardProp:!0,styledComponentId:!0,target:!0,withComponent:!0}),C}var He=function(e){return function e(t,r,o){if(void 0===o&&(o=E),!n(r))return j(1,String(r));var s=function(){return t(r,o,Ce.apply(void 0,arguments))};return s.withConfig=function(n){return e(t,r,v({},o,{},n))},s.attrs=function(n){return e(t,r,v({},o,{attrs:Array.prototype.concat(o.attrs,n).filter(Boolean)}))},s}(qe,e)};["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","big","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","keygen","label","legend","li","link","main","map","mark","marquee","menu","menuitem","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","small","source","span","strong","style","sub","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr","circle","clipPath","defs","ellipse","foreignObject","g","image","line","linearGradient","marker","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","svg","text","textPath","tspan"].forEach((function(e){He[e]=He(e)}));var $e=function(){function e(e,t){this.rules=e,this.componentId=t,this.isStatic=re(e),Z.registerId(this.componentId+1)}var t=e.prototype;return t.createStyles=function(e,t,n,r){var o=r(Ne(this.rules,t,n,r).join(""),""),s=this.componentId+e;n.insertRules(s,s,o)},t.removeStyles=function(e,t){t.clearRules(this.componentId+e)},t.renderStyles=function(e,t,n,r){e>2&&Z.registerId(this.componentId+e),this.removeStyles(e,n),this.createStyles(e,t,n,r)},e}();function We(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];var i=Ce.apply(void 0,[e].concat(n)),a="sc-global-"+ke(JSON.stringify(i)),u=new $e(i,a);function l(e){var t=fe(),n=me(),o=s(Le),l=c(t.allocateGSInstance(a)).current;return"production"!==process.env.NODE_ENV&&r.Children.count(e.children)&&console.warn("The global style component "+a+" was given child JSX. createGlobalStyle does not render children."),"production"!==process.env.NODE_ENV&&i.some((function(e){return"string"==typeof e&&-1!==e.indexOf("@import")}))&&console.warn("Please do not use @import CSS syntax in createGlobalStyle at this time, as the CSSOM APIs we use in production do not handle it well. Instead, we recommend using a library such as react-helmet to inject a typical <link> meta tag to the stylesheet, or simply embedding it manually in your index.html <head> section for a simpler app."),t.server&&h(l,e,t,o,n),d((function(){if(!t.server)return h(l,e,t,o,n),function(){return u.removeStyles(l,t)}}),[l,e,t,o,n]),null}function h(e,t,n,r,o){if(u.isStatic)u.renderStyles(e,O,n,o);else{var s=v({},t,{theme:Re(t,r,l.defaultProps)});u.renderStyles(e,s,n,o)}}return"production"!==process.env.NODE_ENV&&Oe(a),r.memo(l)}function Ue(e){"production"!==process.env.NODE_ENV&&"undefined"!=typeof navigator&&"ReactNative"===navigator.product&&console.warn("`keyframes` cannot be used on ReactNative, only on the web. To do animation in ReactNative please use Animated.");for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];var o=Ce.apply(void 0,[e].concat(n)).join(""),s=ke(o);return new ve(s,o)}var Je=function(){function e(){var e=this;this._emitSheetCSS=function(){var t=e.instance.toString();if(!t)return"";var n=q();return"<style "+[n&&'nonce="'+n+'"',A+'="true"','data-styled-version="5.3.1"'].filter(Boolean).join(" ")+">"+t+"</style>"},this.getStyleTags=function(){return e.sealed?j(2):e._emitSheetCSS()},this.getStyleElement=function(){var t;if(e.sealed)return j(2);var n=((t={})[A]="",t["data-styled-version"]="5.3.1",t.dangerouslySetInnerHTML={__html:e.instance.toString()},t),o=q();return o&&(n.nonce=o),[r.createElement("style",v({},n,{key:"sc-0-0"}))]},this.seal=function(){e.sealed=!0},this.instance=new Z({isServer:!0}),this.sealed=!1}var t=e.prototype;return t.collectStyles=function(e){return this.sealed?j(2):r.createElement(ye,{sheet:this.instance},e)},t.interleaveWithNodeStream=function(e){return j(3)},e}(),Xe=function(e){var t=r.forwardRef((function(t,n){var o=s(Le),i=e.defaultProps,a=Re(t,o,i);return"production"!==process.env.NODE_ENV&&void 0===a&&console.warn('[withTheme] You are not using a ThemeProvider nor passing a theme prop or a theme in defaultProps in component class "'+_(e)+'"'),r.createElement(e,v({},t,{theme:a,ref:n}))}));return y(t,e),t.displayName="WithTheme("+_(e)+")",t},Ze=function(){return s(Le)},Ke={StyleSheet:Z,masterSheet:he};"production"!==process.env.NODE_ENV&&"undefined"!=typeof navigator&&"ReactNative"===navigator.product&&console.warn("It looks like you've imported 'styled-components' on React Native.\nPerhaps you're looking to import 'styled-components/native'?\nRead more about this at https://www.styled-components.com/docs/basics#react-native"),"production"!==process.env.NODE_ENV&&"test"!==process.env.NODE_ENV&&"undefined"!=typeof window&&(window["__styled-components-init__"]=window["__styled-components-init__"]||0,1===window["__styled-components-init__"]&&console.warn("It looks like there are several instances of 'styled-components' initialized in this application. This may cause dynamic styles to not render properly, errors during the rehydration process, a missing theme prop, and makes your application bigger without good reason.\n\nSee https://s-c.sh/2BAXzed for more info."),window["__styled-components-init__"]+=1);export default He;export{Je as ServerStyleSheet,le as StyleSheetConsumer,ue as StyleSheetContext,ye as StyleSheetManager,Ge as ThemeConsumer,Le as ThemeContext,Fe as ThemeProvider,Ke as __PRIVATE__,We as createGlobalStyle,Ce as css,N as isStyledComponent,Ue as keyframes,Ze as useTheme,C as version,Xe as withTheme};
//# sourceMappingURL=styled-components.browser.esm.js.map
webpack://frontend-mybets/../../node_modules/styled-components/native/dist/styled-components.native.esm.js
import transformDeclPairs from 'css-to-react-native';
import { typeOf, isElement, isValidElementType } from 'react-is';
import React, { useContext, useMemo, createElement, Component } from 'react';
import 'shallowequal';
import Stylis from '@emotion/stylis';
import unitless from '@emotion/unitless';
import supportsColor from 'supports-color';
import hoist from 'hoist-non-react-statics';
//
/* eslint-disable no-bitwise */
var AD_REPLACER_R = /(a)(d)/gi;
/* This is the "capacity" of our alphabet i.e. 2x26 for all letters plus their capitalised
* counterparts */
var charsLength = 52;
/* start at 75 for 'a' until 'z' (25) and then start at 65 for capitalised letters */
var getAlphabeticChar = function getAlphabeticChar(code) {
return String.fromCharCode(code + (code > 25 ? 39 : 97));
};
/* input a number, usually a hash and convert it to base-52 */
function generateAlphabeticName(code) {
var name = '';
var x;
/* get a char and divide by alphabet-length */
for (x = Math.abs(code); x > charsLength; x = x / charsLength | 0) {
name = getAlphabeticChar(x % charsLength) + name;
}
return (getAlphabeticChar(x % charsLength) + name).replace(AD_REPLACER_R, '$1-$2');
}
//
/* eslint-disable */
var SEED = 5381; // When we have separate strings it's useful to run a progressive
// version of djb2 where we pretend that we're still looping over
// the same string
var phash = function phash(h, x) {
var i = x.length;
while (i) {
h = h * 33 ^ x.charCodeAt(--i);
}
return h;
}; // This is a djb2 hashing function
var hash = function hash(x) {
return phash(SEED, x);
};
//
var generateComponentId = (function (str) {
return generateAlphabeticName(hash(str) >>> 0);
});
//
function getComponentName(target) {
return (process.env.NODE_ENV !== 'production' ? typeof target === 'string' && target : false) || // $FlowFixMe
target.displayName || // $FlowFixMe
target.name || 'Component';
}
//
function isFunction(test) {
return typeof test === 'function';
}
//
function isStatelessFunction(test) {
return typeof test === 'function' && !(test.prototype && test.prototype.isReactComponent);
}
//
var isPlainObject = (function (x) {
return x !== null && typeof x === 'object' && (x.toString ? x.toString() : Object.prototype.toString.call(x)) === '[object Object]' && !typeOf(x);
});
//
function isStyledComponent(target) {
return target && typeof target.styledComponentId === 'string';
}
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 _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
function _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;
}
//
var SC_ATTR = typeof process !== 'undefined' && (process.env.REACT_APP_SC_ATTR || process.env.SC_ATTR) || 'data-styled';
var SC_ATTR_ACTIVE = 'active';
var SC_ATTR_VERSION = 'data-styled-version';
var SC_VERSION = "5.3.1";
var SPLITTER = '/*!sc*/\n';
var IS_BROWSER = typeof window !== 'undefined' && 'HTMLElement' in window;
var DISABLE_SPEEDY = Boolean(typeof SC_DISABLE_SPEEDY === 'boolean' ? SC_DISABLE_SPEEDY : typeof process !== 'undefined' && typeof process.env.REACT_APP_SC_DISABLE_SPEEDY !== 'undefined' && process.env.REACT_APP_SC_DISABLE_SPEEDY !== '' ? process.env.REACT_APP_SC_DISABLE_SPEEDY === 'false' ? false : process.env.REACT_APP_SC_DISABLE_SPEEDY : typeof process !== 'undefined' && typeof process.env.SC_DISABLE_SPEEDY !== 'undefined' && process.env.SC_DISABLE_SPEEDY !== '' ? process.env.SC_DISABLE_SPEEDY === 'false' ? false : process.env.SC_DISABLE_SPEEDY : process.env.NODE_ENV !== 'production'); // Shared empty execution context when generating static styles
//
var EMPTY_ARRAY = Object.freeze([]);
var EMPTY_OBJECT = Object.freeze({});
var errorMap = {
"1": "Cannot create styled-component for component: %s.\n\n",
"2": "Can't collect styles once you've consumed a `ServerStyleSheet`'s styles! `ServerStyleSheet` is a one off instance for each server-side render cycle.\n\n- Are you trying to reuse it across renders?\n- Are you accidentally calling collectStyles twice?\n\n",
"3": "Streaming SSR is only supported in a Node.js environment; Please do not try to call this method in the browser.\n\n",
"4": "The `StyleSheetManager` expects a valid target or sheet prop!\n\n- Does this error occur on the client and is your target falsy?\n- Does this error occur on the server and is the sheet falsy?\n\n",
"5": "The clone method cannot be used on the client!\n\n- Are you running in a client-like environment on the server?\n- Are you trying to run SSR on the client?\n\n",
"6": "Trying to insert a new style tag, but the given Node is unmounted!\n\n- Are you using a custom target that isn't mounted?\n- Does your document not have a valid head element?\n- Have you accidentally removed a style tag manually?\n\n",
"7": "ThemeProvider: Please return an object from your \"theme\" prop function, e.g.\n\n```js\ntheme={() => ({})}\n```\n\n",
"8": "ThemeProvider: Please make your \"theme\" prop an object.\n\n",
"9": "Missing document `<head>`\n\n",
"10": "Cannot find a StyleSheet instance. Usually this happens if there are multiple copies of styled-components loaded at once. Check out this issue for how to troubleshoot and fix the common cases where this situation can happen: https://github.com/styled-components/styled-components/issues/1941#issuecomment-417862021\n\n",
"11": "_This error was replaced with a dev-time warning, it will be deleted for v4 final._ [createGlobalStyle] received children which will not be rendered. Please use the component without passing children elements.\n\n",
"12": "It seems you are interpolating a keyframe declaration (%s) into an untagged string. This was supported in styled-components v3, but is not longer supported in v4 as keyframes are now injected on-demand. Please wrap your string in the css\\`\\` helper which ensures the styles are injected correctly. See https://www.styled-components.com/docs/api#css\n\n",
"13": "%s is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details.\n\n",
"14": "ThemeProvider: \"theme\" prop is required.\n\n",
"15": "A stylis plugin has been supplied that is not named. We need a name for each plugin to be able to prevent styling collisions between different stylis configurations within the same app. Before you pass your plugin to `<StyleSheetManager stylisPlugins={[]}>`, please make sure each plugin is uniquely-named, e.g.\n\n```js\nObject.defineProperty(importedPlugin, 'name', { value: 'some-unique-name' });\n```\n\n",
"16": "Reached the limit of how many styled components may be created at group %s.\nYou may only create up to 1,073,741,824 components. If you're creating components dynamically,\nas for instance in your render method then you may be running into this limitation.\n\n",
"17": "CSSStyleSheet could not be found on HTMLStyleElement.\nHas styled-components' style tag been unmounted or altered by another script?\n"
};
//
var ERRORS = process.env.NODE_ENV !== 'production' ? errorMap : {};
/**
* super basic version of sprintf
*/
function format() {
var a = arguments.length <= 0 ? undefined : arguments[0];
var b = [];
for (var c = 1, len = arguments.length; c < len; c += 1) {
b.push(c < 0 || arguments.length <= c ? undefined : arguments[c]);
}
b.forEach(function (d) {
a = a.replace(/%[a-z]/, d);
});
return a;
}
/**
* Create an error file out of errors.md for development and a simple web link to the full errors
* in production mode.
*/
function throwStyledComponentsError(code) {
for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
interpolations[_key - 1] = arguments[_key];
}
if (process.env.NODE_ENV === 'production') {
throw new Error("An error occurred. See https://git.io/JUIaE#" + code + " for more information." + (interpolations.length > 0 ? " Args: " + interpolations.join(', ') : ''));
} else {
throw new Error(format.apply(void 0, [ERRORS[code]].concat(interpolations)).trim());
}
}
//
/** Create a GroupedTag with an underlying Tag implementation */
var makeGroupedTag = function makeGroupedTag(tag) {
return new DefaultGroupedTag(tag);
};
var BASE_SIZE = 1 << 9;
var DefaultGroupedTag = /*#__PURE__*/function () {
function DefaultGroupedTag(tag) {
this.groupSizes = new Uint32Array(BASE_SIZE);
this.length = BASE_SIZE;
this.tag = tag;
}
var _proto = DefaultGroupedTag.prototype;
_proto.indexOfGroup = function indexOfGroup(group) {
var index = 0;
for (var i = 0; i < group; i++) {
index += this.groupSizes[i];
}
return index;
};
_proto.insertRules = function insertRules(group, rules) {
if (group >= this.groupSizes.length) {
var oldBuffer = this.groupSizes;
var oldSize = oldBuffer.length;
var newSize = oldSize;
while (group >= newSize) {
newSize <<= 1;
if (newSize < 0) {
throwStyledComponentsError(16, "" + group);
}
}
this.groupSizes = new Uint32Array(newSize);
this.groupSizes.set(oldBuffer);
this.length = newSize;
for (var i = oldSize; i < newSize; i++) {
this.groupSizes[i] = 0;
}
}
var ruleIndex = this.indexOfGroup(group + 1);
for (var _i = 0, l = rules.length; _i < l; _i++) {
if (this.tag.insertRule(ruleIndex, rules[_i])) {
this.groupSizes[group]++;
ruleIndex++;
}
}
};
_proto.clearGroup = function clearGroup(group) {
if (group < this.length) {
var length = this.groupSizes[group];
var startIndex = this.indexOfGroup(group);
var endIndex = startIndex + length;
this.groupSizes[group] = 0;
for (var i = startIndex; i < endIndex; i++) {
this.tag.deleteRule(startIndex);
}
}
};
_proto.getGroup = function getGroup(group) {
var css = '';
if (group >= this.length || this.groupSizes[group] === 0) {
return css;
}
var length = this.groupSizes[group];
var startIndex = this.indexOfGroup(group);
var endIndex = startIndex + length;
for (var i = startIndex; i < endIndex; i++) {
css += "" + this.tag.getRule(i) + SPLITTER;
}
return css;
};
return DefaultGroupedTag;
}();
//
var MAX_SMI = 1 << 31 - 1;
var groupIDRegister = new Map();
var reverseRegister = new Map();
var nextFreeGroup = 1;
var getGroupForId = function getGroupForId(id) {
if (groupIDRegister.has(id)) {
return groupIDRegister.get(id);
}
while (reverseRegister.has(nextFreeGroup)) {
nextFreeGroup++;
}
var group = nextFreeGroup++;
if (process.env.NODE_ENV !== 'production' && ((group | 0) < 0 || group > MAX_SMI)) {
throwStyledComponentsError(16, "" + group);
}
groupIDRegister.set(id, group);
reverseRegister.set(group, id);
return group;
};
var getIdForGroup = function getIdForGroup(group) {
return reverseRegister.get(group);
};
var setGroupForId = function setGroupForId(id, group) {
if (group >= nextFreeGroup) {
nextFreeGroup = group + 1;
}
groupIDRegister.set(id, group);
reverseRegister.set(group, id);
};
//
var SELECTOR = "style[" + SC_ATTR + "][" + SC_ATTR_VERSION + "=\"" + SC_VERSION + "\"]";
var MARKER_RE = new RegExp("^" + SC_ATTR + "\\.g(\\d+)\\[id=\"([\\w\\d-]+)\"\\].*?\"([^\"]*)");
var outputSheet = function outputSheet(sheet) {
var tag = sheet.getTag();
var length = tag.length;
var css = '';
for (var group = 0; group < length; group++) {
var id = getIdForGroup(group);
if (id === undefined) continue;
var names = sheet.names.get(id);
var rules = tag.getGroup(group);
if (!names || !rules || !names.size) continue;
var selector = SC_ATTR + ".g" + group + "[id=\"" + id + "\"]";
var content = '';
if (names !== undefined) {
names.forEach(function (name) {
if (name.length > 0) {
content += name + ",";
}
});
} // NOTE: It's easier to collect rules and have the marker
// after the actual rules to simplify the rehydration
css += "" + rules + selector + "{content:\"" + content + "\"}" + SPLITTER;
}
return css;
};
var rehydrateNamesFromContent = function rehydrateNamesFromContent(sheet, id, content) {
var names = content.split(',');
var name;
for (var i = 0, l = names.length; i < l; i++) {
// eslint-disable-next-line
if (name = names[i]) {
sheet.registerName(id, name);
}
}
};
var rehydrateSheetFromTag = function rehydrateSheetFromTag(sheet, style) {
var parts = (style.innerHTML || '').split(SPLITTER);
var rules = [];
for (var i = 0, l = parts.length; i < l; i++) {
var part = parts[i].trim();
if (!part) continue;
var marker = part.match(MARKER_RE);
if (marker) {
var group = parseInt(marker[1], 10) | 0;
var id = marker[2];
if (group !== 0) {
// Rehydrate componentId to group index mapping
setGroupForId(id, group); // Rehydrate names and rules
// looks like: data-styled.g11[id="idA"]{content:"nameA,"}
rehydrateNamesFromContent(sheet, id, marker[3]);
sheet.getTag().insertRules(group, rules);
}
rules.length = 0;
} else {
rules.push(part);
}
}
};
var rehydrateSheet = function rehydrateSheet(sheet) {
var nodes = document.querySelectorAll(SELECTOR);
for (var i = 0, l = nodes.length; i < l; i++) {
var node = nodes[i];
if (node && node.getAttribute(SC_ATTR) !== SC_ATTR_ACTIVE) {
rehydrateSheetFromTag(sheet, node);
if (node.parentNode) {
node.parentNode.removeChild(node);
}
}
}
};
//
/* eslint-disable camelcase, no-undef */
var getNonce = function getNonce() {
return typeof window !== 'undefined' ? typeof window.__webpack_nonce__ !== 'undefined' ? window.__webpack_nonce__ : null : null;
};
//
var ELEMENT_TYPE = 1;
/* Node.ELEMENT_TYPE */
/** Find last style element if any inside target */
var findLastStyleTag = function findLastStyleTag(target) {
var childNodes = target.childNodes;
for (var i = childNodes.length; i >= 0; i--) {
var child = childNodes[i];
if (child && child.nodeType === ELEMENT_TYPE && child.hasAttribute(SC_ATTR)) {
return child;
}
}
return undefined;
};
/** Create a style element inside `target` or <head> after the last */
var makeStyleTag = function makeStyleTag(target) {
var head = document.head;
var parent = target || head;
var style = document.createElement('style');
var prevStyle = findLastStyleTag(parent);
var nextSibling = prevStyle !== undefined ? prevStyle.nextSibling : null;
style.setAttribute(SC_ATTR, SC_ATTR_ACTIVE);
style.setAttribute(SC_ATTR_VERSION, SC_VERSION);
var nonce = getNonce();
if (nonce) style.setAttribute('nonce', nonce);
parent.insertBefore(style, nextSibling);
return style;
};
/** Get the CSSStyleSheet instance for a given style element */
var getSheet = function getSheet(tag) {
if (tag.sheet) {
return tag.sheet;
} // Avoid Firefox quirk where the style element might not have a sheet property
var _document = document,
styleSheets = _document.styleSheets;
for (var i = 0, l = styleSheets.length; i < l; i++) {
var sheet = styleSheets[i];
if (sheet.ownerNode === tag) {
return sheet;
}
}
throwStyledComponentsError(17);
return undefined;
};
//
/** Create a CSSStyleSheet-like tag depending on the environment */
var makeTag = function makeTag(_ref) {
var isServer = _ref.isServer,
useCSSOMInjection = _ref.useCSSOMInjection,
target = _ref.target;
if (isServer) {
return new VirtualTag(target);
} else if (useCSSOMInjection) {
return new CSSOMTag(target);
} else {
return new TextTag(target);
}
};
var CSSOMTag = /*#__PURE__*/function () {
function CSSOMTag(target) {
var element = this.element = makeStyleTag(target); // Avoid Edge bug where empty style elements don't create sheets
element.appendChild(document.createTextNode(''));
this.sheet = getSheet(element);
this.length = 0;
}
var _proto = CSSOMTag.prototype;
_proto.insertRule = function insertRule(index, rule) {
try {
this.sheet.insertRule(rule, index);
this.length++;
return true;
} catch (_error) {
return false;
}
};
_proto.deleteRule = function deleteRule(index) {
this.sheet.deleteRule(index);
this.length--;
};
_proto.getRule = function getRule(index) {
var rule = this.sheet.cssRules[index]; // Avoid IE11 quirk where cssText is inaccessible on some invalid rules
if (rule !== undefined && typeof rule.cssText === 'string') {
return rule.cssText;
} else {
return '';
}
};
return CSSOMTag;
}();
/** A Tag that emulates the CSSStyleSheet API but uses text nodes */
var TextTag = /*#__PURE__*/function () {
function TextTag(target) {
var element = this.element = makeStyleTag(target);
this.nodes = element.childNodes;
this.length = 0;
}
var _proto2 = TextTag.prototype;
_proto2.insertRule = function insertRule(index, rule) {
if (index <= this.length && index >= 0) {
var node = document.createTextNode(rule);
var refNode = this.nodes[index];
this.element.insertBefore(node, refNode || null);
this.length++;
return true;
} else {
return false;
}
};
_proto2.deleteRule = function deleteRule(index) {
this.element.removeChild(this.nodes[index]);
this.length--;
};
_proto2.getRule = function getRule(index) {
if (index < this.length) {
return this.nodes[index].textContent;
} else {
return '';
}
};
return TextTag;
}();
/** A completely virtual (server-side) Tag that doesn't manipulate the DOM */
var VirtualTag = /*#__PURE__*/function () {
function VirtualTag(_target) {
this.rules = [];
this.length = 0;
}
var _proto3 = VirtualTag.prototype;
_proto3.insertRule = function insertRule(index, rule) {
if (index <= this.length) {
this.rules.splice(index, 0, rule);
this.length++;
return true;
} else {
return false;
}
};
_proto3.deleteRule = function deleteRule(index) {
this.rules.splice(index, 1);
this.length--;
};
_proto3.getRule = function getRule(index) {
if (index < this.length) {
return this.rules[index];
} else {
return '';
}
};
return VirtualTag;
}();
var SHOULD_REHYDRATE = IS_BROWSER;
var defaultOptions = {
isServer: !IS_BROWSER,
useCSSOMInjection: !DISABLE_SPEEDY
};
/** Contains the main stylesheet logic for stringification and caching */
var StyleSheet = /*#__PURE__*/function () {
/** Register a group ID to give it an index */
StyleSheet.registerId = function registerId(id) {
return getGroupForId(id);
};
function StyleSheet(options, globalStyles, names) {
if (options === void 0) {
options = EMPTY_OBJECT;
}
if (globalStyles === void 0) {
globalStyles = {};
}
this.options = _extends({}, defaultOptions, {}, options);
this.gs = globalStyles;
this.names = new Map(names);
this.server = !!options.isServer; // We rehydrate only once and use the sheet that is created first
if (!this.server && IS_BROWSER && SHOULD_REHYDRATE) {
SHOULD_REHYDRATE = false;
rehydrateSheet(this);
}
}
var _proto = StyleSheet.prototype;
_proto.reconstructWithOptions = function reconstructWithOptions(options, withNames) {
if (withNames === void 0) {
withNames = true;
}
return new StyleSheet(_extends({}, this.options, {}, options), this.gs, withNames && this.names || undefined);
};
_proto.allocateGSInstance = function allocateGSInstance(id) {
return this.gs[id] = (this.gs[id] || 0) + 1;
}
/** Lazily initialises a GroupedTag for when it's actually needed */
;
_proto.getTag = function getTag() {
return this.tag || (this.tag = makeGroupedTag(makeTag(this.options)));
}
/** Check whether a name is known for caching */
;
_proto.hasNameForId = function hasNameForId(id, name) {
return this.names.has(id) && this.names.get(id).has(name);
}
/** Mark a group's name as known for caching */
;
_proto.registerName = function registerName(id, name) {
getGroupForId(id);
if (!this.names.has(id)) {
var groupNames = new Set();
groupNames.add(name);
this.names.set(id, groupNames);
} else {
this.names.get(id).add(name);
}
}
/** Insert new rules which also marks the name as known */
;
_proto.insertRules = function insertRules(id, name, rules) {
this.registerName(id, name);
this.getTag().insertRules(getGroupForId(id), rules);
}
/** Clears all cached names for a given group ID */
;
_proto.clearNames = function clearNames(id) {
if (this.names.has(id)) {
this.names.get(id).clear();
}
}
/** Clears all rules for a given group ID */
;
_proto.clearRules = function clearRules(id) {
this.getTag().clearGroup(getGroupForId(id));
this.clearNames(id);
}
/** Clears the entire tag which deletes all rules but not its names */
;
_proto.clearTag = function clearTag() {
// NOTE: This does not clear the names, since it's only used during SSR
// so that we can continuously output only new rules
this.tag = undefined;
}
/** Outputs the current sheet as a CSS string with markers for SSR */
;
_proto.toString = function toString() {
return outputSheet(this);
};
return StyleSheet;
}();
/**
* MIT License
*
* Copyright (c) 2016 Sultan Tarimo
*
* 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.
*/
/* eslint-disable */
function insertRulePlugin (insertRule) {
var delimiter = '/*|*/';
var needle = delimiter + "}";
function toSheet(block) {
if (block) {
try {
insertRule(block + "}");
} catch (e) {}
}
}
return function ruleSheet(context, content, selectors, parents, line, column, length, ns, depth, at) {
switch (context) {
// property
case 1:
// @import
if (depth === 0 && content.charCodeAt(0) === 64) return insertRule(content + ";"), '';
break;
// selector
case 2:
if (ns === 0) return content + delimiter;
break;
// at-rule
case 3:
switch (ns) {
// @font-face, @page
case 102:
case 112:
return insertRule(selectors[0] + content), '';
default:
return content + (at === 0 ? delimiter : '');
}
case -2:
content.split(needle).forEach(toSheet);
}
};
}
var COMMENT_REGEX = /^\s*\/\/.*$/gm;
var COMPLEX_SELECTOR_PREFIX = [':', '[', '.', '#'];
function createStylisInstance(_temp) {
var _ref = _temp === void 0 ? EMPTY_OBJECT : _temp,
_ref$options = _ref.options,
options = _ref$options === void 0 ? EMPTY_OBJECT : _ref$options,
_ref$plugins = _ref.plugins,
plugins = _ref$plugins === void 0 ? EMPTY_ARRAY : _ref$plugins;
var stylis = new Stylis(options); // Wrap `insertRulePlugin to build a list of rules,
// and then make our own plugin to return the rules. This
// makes it easier to hook into the existing SSR architecture
var parsingRules = []; // eslint-disable-next-line consistent-return
var returnRulesPlugin = function returnRulesPlugin(context) {
if (context === -2) {
var parsedRules = parsingRules;
parsingRules = [];
return parsedRules;
}
};
var parseRulesPlugin = insertRulePlugin(function (rule) {
parsingRules.push(rule);
});
var _componentId;
var _selector;
var _selectorRegexp;
var _consecutiveSelfRefRegExp;
var selfReferenceReplacer = function selfReferenceReplacer(match, offset, string) {
if ( // do not replace the first occurrence if it is complex (has a modifier)
(offset === 0 ? COMPLEX_SELECTOR_PREFIX.indexOf(string[_selector.length]) === -1 : true) && // no consecutive self refs (.b.b); that is a precedence boost and treated differently
!string.match(_consecutiveSelfRefRegExp)) {
return "." + _componentId;
}
return match;
};
/**
* When writing a style like
*
* & + & {
* color: red;
* }
*
* The second ampersand should be a reference to the static component class. stylis
* has no knowledge of static class so we have to intelligently replace the base selector.
*
* https://github.com/thysultan/stylis.js/tree/v3.5.4#plugins <- more info about the context phase values
* "2" means this plugin is taking effect at the very end after all other processing is complete
*/
var selfReferenceReplacementPlugin = function selfReferenceReplacementPlugin(context, _, selectors) {
if (context === 2 && selectors.length && selectors[0].lastIndexOf(_selector) > 0) {
// eslint-disable-next-line no-param-reassign
selectors[0] = selectors[0].replace(_selectorRegexp, selfReferenceReplacer);
}
};
stylis.use([].concat(plugins, [selfReferenceReplacementPlugin, parseRulesPlugin, returnRulesPlugin]));
function stringifyRules(css, selector, prefix, componentId) {
if (componentId === void 0) {
componentId = '&';
}
var flatCSS = css.replace(COMMENT_REGEX, '');
var cssStr = selector && prefix ? prefix + " " + selector + " { " + flatCSS + " }" : flatCSS; // stylis has no concept of state to be passed to plugins
// but since JS is single-threaded, we can rely on that to ensure
// these properties stay in sync with the current stylis run
_componentId = componentId;
_selector = selector;
_selectorRegexp = new RegExp("\\" + _selector + "\\b", 'g');
_consecutiveSelfRefRegExp = new RegExp("(\\" + _selector + "\\b){2,}");
return stylis(prefix || !selector ? '' : selector, cssStr);
}
stringifyRules.hash = plugins.length ? plugins.reduce(function (acc, plugin) {
if (!plugin.name) {
throwStyledComponentsError(15);
}
return phash(acc, plugin.name);
}, SEED).toString() : '';
return stringifyRules;
}
//
var StyleSheetContext = React.createContext();
var StyleSheetConsumer = StyleSheetContext.Consumer;
var StylisContext = React.createContext();
var StylisConsumer = StylisContext.Consumer;
var masterSheet = new StyleSheet();
var masterStylis = createStylisInstance();
//
var Keyframes = /*#__PURE__*/function () {
function Keyframes(name, rules) {
var _this = this;
this.inject = function (styleSheet, stylisInstance) {
if (stylisInstance === void 0) {
stylisInstance = masterStylis;
}
var resolvedName = _this.name + stylisInstance.hash;
if (!styleSheet.hasNameForId(_this.id, resolvedName)) {
styleSheet.insertRules(_this.id, resolvedName, stylisInstance(_this.rules, resolvedName, '@keyframes'));
}
};
this.toString = function () {
return throwStyledComponentsError(12, String(_this.name));
};
this.name = name;
this.id = "sc-keyframes-" + name;
this.rules = rules;
}
var _proto = Keyframes.prototype;
_proto.getName = function getName(stylisInstance) {
if (stylisInstance === void 0) {
stylisInstance = masterStylis;
}
return this.name + stylisInstance.hash;
};
return Keyframes;
}();
//
/**
* inlined version of
* https://github.com/facebook/fbjs/blob/master/packages/fbjs/src/core/hyphenateStyleName.js
*/
var uppercaseCheck = /([A-Z])/;
var uppercasePattern = /([A-Z])/g;
var msPattern = /^ms-/;
var prefixAndLowerCase = function prefixAndLowerCase(_char) {
return "-" + _char.toLowerCase();
};
/**
* Hyphenates a camelcased CSS property name, for example:
*
* > hyphenateStyleName('backgroundColor')
* < "background-color"
* > hyphenateStyleName('MozTransition')
* < "-moz-transition"
* > hyphenateStyleName('msTransition')
* < "-ms-transition"
*
* As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
* is converted to `-ms-`.
*
* @param {string} string
* @return {string}
*/
function hyphenateStyleName(string) {
return uppercaseCheck.test(string) ? string.replace(uppercasePattern, prefixAndLowerCase).replace(msPattern, '-ms-') : string;
}
//
function addUnitIfNeeded(name, value) {
// https://github.com/amilajack/eslint-plugin-flowtype-errors/issues/133
// $FlowFixMe
if (value == null || typeof value === 'boolean' || value === '') {
return '';
}
if (typeof value === 'number' && value !== 0 && !(name in unitless)) {
return value + "px"; // Presumes implicit 'px' suffix for unitless numbers
}
return String(value).trim();
}
//
/**
* It's falsish not falsy because 0 is allowed.
*/
var isFalsish = function isFalsish(chunk) {
return chunk === undefined || chunk === null || chunk === false || chunk === '';
};
var objToCssArray = function objToCssArray(obj, prevKey) {
var rules = [];
for (var key in obj) {
if (!obj.hasOwnProperty(key) || isFalsish(obj[key])) continue;
if (Array.isArray(obj[key]) && obj[key].isCss || isFunction(obj[key])) {
rules.push(hyphenateStyleName(key) + ":", obj[key], ';');
} else if (isPlainObject(obj[key])) {
rules.push.apply(rules, objToCssArray(obj[key], key));
} else {
rules.push(hyphenateStyleName(key) + ": " + addUnitIfNeeded(key, obj[key]) + ";");
}
}
return prevKey ? [prevKey + " {"].concat(rules, ['}']) : rules;
};
function flatten(chunk, executionContext, styleSheet, stylisInstance) {
if (Array.isArray(chunk)) {
var ruleSet = [];
for (var i = 0, len = chunk.length, result; i < len; i += 1) {
result = flatten(chunk[i], executionContext, styleSheet, stylisInstance);
if (result === '') continue;else if (Array.isArray(result)) ruleSet.push.apply(ruleSet, result);else ruleSet.push(result);
}
return ruleSet;
}
if (isFalsish(chunk)) {
return '';
}
/* Handle other components */
if (isStyledComponent(chunk)) {
return "." + chunk.styledComponentId;
}
/* Either execute or defer the function */
if (isFunction(chunk)) {
if (isStatelessFunction(chunk) && executionContext) {
var _result = chunk(executionContext);
if (process.env.NODE_ENV !== 'production' && isElement(_result)) {
// eslint-disable-next-line no-console
console.warn(getComponentName(chunk) + " is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details.");
}
return flatten(_result, executionContext, styleSheet, stylisInstance);
} else return chunk;
}
if (chunk instanceof Keyframes) {
if (styleSheet) {
chunk.inject(styleSheet, stylisInstance);
return chunk.getName(stylisInstance);
} else return chunk;
}
/* Handle objects */
return isPlainObject(chunk) ? objToCssArray(chunk) : chunk.toString();
}
//
var printed = {};
function warnOnce(message) {
if (printed[message]) return;
printed[message] = true;
if (typeof console !== 'undefined' && console.warn) console.warn(message);
}
//
var SINGLE_QUOTE = "'".charCodeAt(0);
var DOUBLE_QUOTE = '"'.charCodeAt(0);
var BACKSLASH = '\\'.charCodeAt(0);
var SLASH = '/'.charCodeAt(0);
var NEWLINE = '\n'.charCodeAt(0);
var SPACE = ' '.charCodeAt(0);
var FEED = '\f'.charCodeAt(0);
var TAB = '\t'.charCodeAt(0);
var CR = '\r'.charCodeAt(0);
var OPEN_SQUARE = '['.charCodeAt(0);
var CLOSE_SQUARE = ']'.charCodeAt(0);
var OPEN_PARENTHESES = '('.charCodeAt(0);
var CLOSE_PARENTHESES = ')'.charCodeAt(0);
var OPEN_CURLY = '{'.charCodeAt(0);
var CLOSE_CURLY = '}'.charCodeAt(0);
var SEMICOLON = ';'.charCodeAt(0);
var ASTERISK = '*'.charCodeAt(0);
var COLON = ':'.charCodeAt(0);
var AT = '@'.charCodeAt(0);
var RE_AT_END = /[ \n\t\r\f\{\(\)'"\\;/\[\]#]/g;
var RE_WORD_END = /[ \n\t\r\f\(\)\{\}:;@!'"\\\]\[#]|\/(?=\*)/g;
var RE_BAD_BRACKET = /.[\\\/\("'\n]/;
function tokenize(input, options) {
if (options === void 0) {
options = {};
}
var tokens = [];
var css = input.css.valueOf();
var ignore = options.ignoreErrors;
var code, next, quote, lines, last, content, escape, nextLine, nextOffset, escaped, escapePos, prev, n;
var length = css.length;
var offset = -1;
var line = 1;
var pos = 0;
function unclosed(what) {
throw input.error("Unclosed " + what, line, pos - offset);
}
while (pos < length) {
code = css.charCodeAt(pos);
if (code === NEWLINE || code === FEED || code === CR && css.charCodeAt(pos + 1) !== NEWLINE) {
offset = pos;
line += 1;
}
switch (code) {
case NEWLINE:
case SPACE:
case TAB:
case CR:
case FEED:
next = pos;
do {
next += 1;
code = css.charCodeAt(next);
if (code === NEWLINE) {
offset = next;
line += 1;
}
} while (code === SPACE || code === NEWLINE || code === TAB || code === CR || code === FEED);
tokens.push(['space', css.slice(pos, next)]);
pos = next - 1;
break;
case OPEN_SQUARE:
tokens.push(['[', '[', line, pos - offset]);
break;
case CLOSE_SQUARE:
tokens.push([']', ']', line, pos - offset]);
break;
case OPEN_CURLY:
tokens.push(['{', '{', line, pos - offset]);
break;
case CLOSE_CURLY:
tokens.push(['}', '}', line, pos - offset]);
break;
case COLON:
tokens.push([':', ':', line, pos - offset]);
break;
case SEMICOLON:
tokens.push([';', ';', line, pos - offset]);
break;
case OPEN_PARENTHESES:
prev = tokens.length ? tokens[tokens.length - 1][1] : '';
n = css.charCodeAt(pos + 1);
if (prev === 'url' && n !== SINGLE_QUOTE && n !== DOUBLE_QUOTE && n !== SPACE && n !== NEWLINE && n !== TAB && n !== FEED && n !== CR) {
next = pos;
do {
escaped = false;
next = css.indexOf(')', next + 1);
if (next === -1) {
if (ignore) {
next = pos;
break;
} else {
unclosed('bracket');
}
}
escapePos = next;
while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
escapePos -= 1;
escaped = !escaped;
}
} while (escaped);
tokens.push(['brackets', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);
pos = next;
} else {
next = css.indexOf(')', pos + 1);
content = css.slice(pos, next + 1);
if (next === -1 || RE_BAD_BRACKET.test(content)) {
tokens.push(['(', '(', line, pos - offset]);
} else {
tokens.push(['brackets', content, line, pos - offset, line, next - offset]);
pos = next;
}
}
break;
case CLOSE_PARENTHESES:
tokens.push([')', ')', line, pos - offset]);
break;
case SINGLE_QUOTE:
case DOUBLE_QUOTE:
quote = code === SINGLE_QUOTE ? "'" : '"';
next = pos;
do {
escaped = false;
next = css.indexOf(quote, next + 1);
if (next === -1) {
if (ignore) {
next = pos + 1;
break;
} else {
unclosed('quote');
}
}
escapePos = next;
while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
escapePos -= 1;
escaped = !escaped;
}
} while (escaped);
content = css.slice(pos, next + 1);
lines = content.split('\n');
last = lines.length - 1;
if (last > 0) {
nextLine = line + last;
nextOffset = next - lines[last].length;
} else {
nextLine = line;
nextOffset = offset;
}
tokens.push(['string', css.slice(pos, next + 1), line, pos - offset, nextLine, next - nextOffset]);
offset = nextOffset;
line = nextLine;
pos = next;
break;
case AT:
RE_AT_END.lastIndex = pos + 1;
RE_AT_END.test(css);
if (RE_AT_END.lastIndex === 0) {
next = css.length - 1;
} else {
next = RE_AT_END.lastIndex - 2;
}
tokens.push(['at-word', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);
pos = next;
break;
case BACKSLASH:
next = pos;
escape = true;
while (css.charCodeAt(next + 1) === BACKSLASH) {
next += 1;
escape = !escape;
}
code = css.charCodeAt(next + 1);
if (escape && code !== SLASH && code !== SPACE && code !== NEWLINE && code !== TAB && code !== CR && code !== FEED) {
next += 1;
}
tokens.push(['word', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);
pos = next;
break;
default:
if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) {
next = css.indexOf('*/', pos + 2) + 1;
if (next === 0) {
if (ignore) {
next = css.length;
} else {
unclosed('comment');
}
}
content = css.slice(pos, next + 1);
lines = content.split('\n');
last = lines.length - 1;
if (last > 0) {
nextLine = line + last;
nextOffset = next - lines[last].length;
} else {
nextLine = line;
nextOffset = offset;
}
tokens.push(['comment', content, line, pos - offset, nextLine, next - nextOffset]);
offset = nextOffset;
line = nextLine;
pos = next;
} else {
RE_WORD_END.lastIndex = pos + 1;
RE_WORD_END.test(css);
if (RE_WORD_END.lastIndex === 0) {
next = css.length - 1;
} else {
next = RE_WORD_END.lastIndex - 2;
}
tokens.push(['word', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);
pos = next;
}
break;
}
pos++;
}
return tokens;
}
//
var HIGHLIGHT_THEME = {
brackets: [36, 39],
// cyan
string: [31, 39],
// red
'at-word': [31, 39],
// red
comment: [90, 39],
// gray
'{': [32, 39],
// green
'}': [32, 39],
// green
':': [1, 22],
// bold
';': [1, 22],
// bold
'(': [1, 22],
// bold
')': [1, 22] // bold
};
function code(color) {
return "\x1B[" + color + "m";
}
function terminalHighlight(css) {
var tokens = tokenize(new Input(css), {
ignoreErrors: true
});
var result = [];
tokens.forEach(function (token) {
var color = HIGHLIGHT_THEME[token[0]];
if (color) {
result.push(token[1].split(/\r?\n/).map(function (i) {
return code(color[0]) + i + code(color[1]);
}).join('\n'));
} else {
result.push(token[1]);
}
});
return result.join('');
}
/**
* The CSS parser throws this error for broken CSS.
*
* Custom parsers can throw this error for broken custom syntax using
* the {@link Node#error} method.
*
* PostCSS will use the input source map to detect the original error location.
* If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS,
* PostCSS will show the original position in the Sass file.
*
* If you need the position in the PostCSS input
* (e.g., to debug the previous compiler), use `error.input.file`.
*
* @example
* // Catching and checking syntax error
* try {
* postcss.parse('a{')
* } catch (error) {
* if ( error.name === 'CssSyntaxError' ) {
* error //=> CssSyntaxError
* }
* }
*
* @example
* // Raising error from plugin
* throw node.error('Unknown variable', { plugin: 'postcss-vars' });
*/
var CssSyntaxError = /*#__PURE__*/function () {
/**
* @param {string} message - error message
* @param {number} [line] - source line of the error
* @param {number} [column] - source column of the error
* @param {string} [source] - source code of the broken file
* @param {string} [file] - absolute path to the broken file
* @param {string} [plugin] - PostCSS plugin name, if error came from plugin
*/
function CssSyntaxError(message, line, column, source, file, plugin) {
/**
* @member {string} - Always equal to `'CssSyntaxError'`. You should
* always check error type
* by `error.name === 'CssSyntaxError'` instead of
* `error instanceof CssSyntaxError`, because
* npm could have several PostCSS versions.
*
* @example
* if ( error.name === 'CssSyntaxError' ) {
* error //=> CssSyntaxError
* }
*/
this.name = 'CssSyntaxError';
/**
* @member {string} - Error message.
*
* @example
* error.message //=> 'Unclosed block'
*/
this.reason = message;
if (file) {
/**
* @member {string} - Absolute path to the broken file.
*
* @example
* error.file //=> 'a.sass'
* error.input.file //=> 'a.css'
*/
this.file = file;
}
if (source) {
/**
* @member {string} - Source code of the broken file.
*
* @example
* error.source //=> 'a { b {} }'
* error.input.column //=> 'a b { }'
*/
this.source = source;
}
if (plugin) {
/**
* @member {string} - Plugin name, if error came from plugin.
*
* @example
* error.plugin //=> 'postcss-vars'
*/
this.plugin = plugin;
}
if (typeof line !== 'undefined' && typeof column !== 'undefined') {
/**
* @member {number} - Source line of the error.
*
* @example
* error.line //=> 2
* error.input.line //=> 4
*/
this.line = line;
/**
* @member {number} - Source column of the error.
*
* @example
* error.column //=> 1
* error.input.column //=> 4
*/
this.column = column;
}
this.setMessage();
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CssSyntaxError);
}
}
var _proto = CssSyntaxError.prototype;
_proto.setMessage = function setMessage() {
/**
* @member {string} - Full error text in the GNU error format
* with plugin, file, line and column.
*
* @example
* error.message //=> 'a.css:1:1: Unclosed block'
*/
this.message = this.plugin ? this.plugin + ": " : '';
this.message += this.file ? this.file : '<css input>';
if (typeof this.line !== 'undefined') {
this.message += ":" + this.line + ":" + this.column;
}
this.message += ": " + this.reason;
}
/**
* Returns a few lines of CSS source that caused the error.
*
* If the CSS has an input source map without `sourceContent`,
* this method will return an empty string.
*
* @param {boolean} [color] whether arrow will be colored red by terminal
* color codes. By default, PostCSS will detect
* color support by `process.stdout.isTTY`
* and `process.env.NODE_DISABLE_COLORS`.
*
* @example
* error.showSourceCode() //=> " 4 | }
* // 5 | a {
* // > 6 | bad
* // | ^
* // 7 | }
* // 8 | b {"
*
* @return {string} few lines of CSS source that caused the error
*/
;
_proto.showSourceCode = function showSourceCode(color) {
var _this = this;
if (!this.source) return '';
var css = this.source;
if (typeof color === 'undefined') color = supportsColor;
if (color) css = terminalHighlight(css);
var lines = css.split(/\r?\n/);
var start = Math.max(this.line - 3, 0);
var end = Math.min(this.line + 2, lines.length);
var maxWidth = String(end).length;
return lines.slice(start, end).map(function (line, index) {
var number = start + 1 + index;
var padded = (" " + number).slice(-maxWidth);
var gutter = " " + padded + " | ";
if (number === _this.line) {
var spacing = gutter.replace(/\d/g, ' ') + line.slice(0, _this.column - 1).replace(/[^\t]/g, ' ');
return ">" + gutter + line + "\n " + spacing + "^";
} else {
return " " + gutter + line;
}
}).join('\n');
}
/**
* Returns error position, message and source code of the broken part.
*
* @example
* error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block
* // > 1 | a {
* // | ^"
*
* @return {string} error position, message and source code
*/
;
_proto.toString = function toString() {
var code = this.showSourceCode();
if (code) {
code = "\n\n" + code + "\n";
}
return this.name + ": " + this.message + code;
};
_createClass(CssSyntaxError, [{
key: "generated",
get: function get() {
warnOnce('CssSyntaxError#generated is deprecated. Use input instead.');
return this.input;
}
/**
* @memberof CssSyntaxError#
* @member {Input} input - Input object with PostCSS internal information
* about input file. If input has source map
* from previous tool, PostCSS will use origin
* (for example, Sass) source. You can use this
* object to get PostCSS input source.
*
* @example
* error.input.file //=> 'a.css'
* error.file //=> 'a.sass'
*/
}]);
return CssSyntaxError;
}();
//
/* eslint-disable valid-jsdoc */
var defaultRaw = {
colon: ': ',
indent: ' ',
beforeDecl: '\n',
beforeRule: '\n',
beforeOpen: ' ',
beforeClose: '\n',
beforeComment: '\n',
after: '\n',
emptyBody: '',
commentLeft: ' ',
commentRight: ' '
};
function capitalize(str) {
return str[0].toUpperCase() + str.slice(1);
}
var Stringifier = /*#__PURE__*/function () {
function Stringifier(builder) {
this.builder = builder;
}
var _proto = Stringifier.prototype;
_proto.stringify = function stringify(node, semicolon) {
this[node.type](node, semicolon);
};
_proto.root = function root(node) {
this.body(node);
if (node.raws.after) this.builder(node.raws.after);
};
_proto.comment = function comment(node) {
var left = this.raw(node, 'left', 'commentLeft');
var right = this.raw(node, 'right', 'commentRight');
this.builder("/*" + left + node.text + right + "*/", node);
};
_proto.decl = function decl(node, semicolon) {
var between = this.raw(node, 'between', 'colon');
var string = node.prop + between + this.rawValue(node, 'value');
if (node.important) {
string += node.raws.important || ' !important';
}
if (semicolon) string += ';';
this.builder(string, node);
};
_proto.rule = function rule(node) {
this.block(node, this.rawValue(node, 'selector'));
};
_proto.atrule = function atrule(node, semicolon) {
var name = "@" + node.name;
var params = node.params ? this.rawValue(node, 'params') : '';
if (typeof node.raws.afterName !== 'undefined') {
name += node.raws.afterName;
} else if (params) {
name += ' ';
}
if (node.nodes) {
this.block(node, name + params);
} else {
var end = (node.raws.between || '') + (semicolon ? ';' : '');
this.builder(name + params + end, node);
}
};
_proto.body = function body(node) {
var last = node.nodes.length - 1;
while (last > 0) {
if (node.nodes[last].type !== 'comment') break;
last -= 1;
}
var semicolon = this.raw(node, 'semicolon');
for (var i = 0; i < node.nodes.length; i++) {
var child = node.nodes[i];
var before = this.raw(child, 'before');
if (before) this.builder(before);
this.stringify(child, last !== i || semicolon);
}
};
_proto.block = function block(node, start) {
var between = this.raw(node, 'between', 'beforeOpen');
this.builder(start + between + "{", node, 'start');
var after;
if (node.nodes && node.nodes.length) {
this.body(node);
after = this.raw(node, 'after');
} else {
after = this.raw(node, 'after', 'emptyBody');
}
if (after) this.builder(after);
this.builder('}', node, 'end');
};
_proto.raw = function raw(node, own, detect) {
var value;
if (!detect) detect = own; // Already had
if (own) {
value = node.raws[own];
if (typeof value !== 'undefined') return value;
}
var parent = node.parent; // Hack for first rule in CSS
if (detect === 'before') {
if (!parent || parent.type === 'root' && parent.first === node) {
return '';
}
} // Floating child without parent
if (!parent) return defaultRaw[detect]; // Detect style by other nodes
var root = node.root();
if (!root.rawCache) root.rawCache = {};
if (typeof root.rawCache[detect] !== 'undefined') {
return root.rawCache[detect];
}
if (detect === 'before' || detect === 'after') {
return this.beforeAfter(node, detect);
} else {
var method = "raw" + capitalize(detect);
if (this[method]) {
value = this[method](root, node);
} else {
root.walk(function (i) {
value = i.raws[own];
if (typeof value !== 'undefined') return false;
});
}
}
if (typeof value === 'undefined') value = defaultRaw[detect];
root.rawCache[detect] = value;
return value;
};
_proto.rawSemicolon = function rawSemicolon(root) {
var value;
root.walk(function (i) {
if (i.nodes && i.nodes.length && i.last.type === 'decl') {
value = i.raws.semicolon;
if (typeof value !== 'undefined') return false;
}
});
return value;
};
_proto.rawEmptyBody = function rawEmptyBody(root) {
var value;
root.walk(function (i) {
if (i.nodes && i.nodes.length === 0) {
value = i.raws.after;
if (typeof value !== 'undefined') return false;
}
});
return value;
};
_proto.rawIndent = function rawIndent(root) {
if (root.raws.indent) return root.raws.indent;
var value;
root.walk(function (i) {
var p = i.parent;
if (p && p !== root && p.parent && p.parent === root) {
if (typeof i.raws.before !== 'undefined') {
var parts = i.raws.before.split('\n');
value = parts[parts.length - 1];
value = value.replace(/[^\s]/g, '');
return false;
}
}
});
return value;
};
_proto.rawBeforeComment = function rawBeforeComment(root, node) {
var value;
root.walkComments(function (i) {
if (typeof i.raws.before !== 'undefined') {
value = i.raws.before;
if (value.indexOf('\n') !== -1) {
value = value.replace(/[^\n]+$/, '');
}
return false;
}
});
if (typeof value === 'undefined') {
value = this.raw(node, null, 'beforeDecl');
}
return value;
};
_proto.rawBeforeDecl = function rawBeforeDecl(root, node) {
var value;
root.walkDecls(function (i) {
if (typeof i.raws.before !== 'undefined') {
value = i.raws.before;
if (value.indexOf('\n') !== -1) {
value = value.replace(/[^\n]+$/, '');
}
return false;
}
});
if (typeof value === 'undefined') {
value = this.raw(node, null, 'beforeRule');
}
return value;
};
_proto.rawBeforeRule = function rawBeforeRule(root) {
var value;
root.walk(function (i) {
if (i.nodes && (i.parent !== root || root.first !== i)) {
if (typeof i.raws.before !== 'undefined') {
value = i.raws.before;
if (value.indexOf('\n') !== -1) {
value = value.replace(/[^\n]+$/, '');
}
return false;
}
}
});
return value;
};
_proto.rawBeforeClose = function rawBeforeClose(root) {
var value;
root.walk(function (i) {
if (i.nodes && i.nodes.length > 0) {
if (typeof i.raws.after !== 'undefined') {
value = i.raws.after;
if (value.indexOf('\n') !== -1) {
value = value.replace(/[^\n]+$/, '');
}
return false;
}
}
});
return value;
};
_proto.rawBeforeOpen = function rawBeforeOpen(root) {
var value;
root.walk(function (i) {
if (i.type !== 'decl') {
value = i.raws.between;
if (typeof value !== 'undefined') return false;
}
});
return value;
};
_proto.rawColon = function rawColon(root) {
var value;
root.walkDecls(function (i) {
if (typeof i.raws.between !== 'undefined') {
value = i.raws.between.replace(/[^\s:]/g, '');
return false;
}
});
return value;
};
_proto.beforeAfter = function beforeAfter(node, detect) {
var value;
if (node.type === 'decl') {
value = this.raw(node, null, 'beforeDecl');
} else if (node.type === 'comment') {
value = this.raw(node, null, 'beforeComment');
} else if (detect === 'before') {
value = this.raw(node, null, 'beforeRule');
} else {
value = this.raw(node, null, 'beforeClose');
}
var buf = node.parent;
var depth = 0;
while (buf && buf.type !== 'root') {
depth += 1;
buf = buf.parent;
}
if (value.indexOf('\n') !== -1) {
var indent = this.raw(node, null, 'indent');
if (indent.length) {
for (var step = 0; step < depth; step++) {
value += indent;
}
}
}
return value;
};
_proto.rawValue = function rawValue(node, prop) {
var value = node[prop];
var raw = node.raws[prop];
if (raw && raw.value === value) {
return raw.raw;
} else {
return value;
}
};
return Stringifier;
}();
//
function stringify(node, builder) {
var str = new Stringifier(builder);
str.stringify(node);
}
/**
* @typedef {object} position
* @property {number} line - source line in file
* @property {number} column - source column in file
*/
/**
* @typedef {object} source
* @property {Input} input - {@link Input} with input file
* @property {position} start - The starting position of the node’s source
* @property {position} end - The ending position of the node’s source
*/
var cloneNode = function cloneNode(obj, parent) {
var cloned = new obj.constructor();
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
var value = obj[i];
var type = typeof value;
if (i === 'parent' && type === 'object') {
if (parent) cloned[i] = parent;
} else if (i === 'source') {
cloned[i] = value;
} else if (value instanceof Array) {
cloned[i] = value.map(function (j) {
return cloneNode(j, cloned);
});
} else if (i !== 'before' && i !== 'after' && i !== 'between' && i !== 'semicolon') {
if (type === 'object' && value !== null) value = cloneNode(value);
cloned[i] = value;
}
}
return cloned;
};
/**
* All node classes inherit the following common methods.
*
* @abstract
*/
var Node = /*#__PURE__*/function () {
/**
* @param {object} [defaults] - value for node properties
*/
function Node(defaults) {
if (defaults === void 0) {
defaults = {};
}
this.raws = {};
for (var name in defaults) {
this[name] = defaults[name];
}
}
/**
* Returns a CssSyntaxError instance containing the original position
* of the node in the source, showing line and column numbers and also
* a small excerpt to facilitate debugging.
*
* If present, an input source map will be used to get the original position
* of the source, even from a previous compilation step
* (e.g., from Sass compilation).
*
* This method produces very useful error messages.
*
* @param {string} message - error description
* @param {object} [opts] - options
* @param {string} opts.plugin - plugin name that created this error.
* PostCSS will set it automatically.
* @param {string} opts.word - a word inside a node’s string that should
* be highlighted as the source of the error
* @param {number} opts.index - an index inside a node’s string that should
* be highlighted as the source of the error
*
* @return {CssSyntaxError} error object to throw it
*
* @example
* if ( !variables[name] ) {
* throw decl.error('Unknown variable ' + name, { word: name });
* // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
* // color: $black
* // a
* // ^
* // background: white
* }
*/
var _proto = Node.prototype;
_proto.error = function error(message, opts) {
if (opts === void 0) {
opts = {};
}
if (this.source) {
var pos = this.positionBy(opts);
return this.source.input.error(message, pos.line, pos.column, opts);
} else {
return new CssSyntaxError(message);
}
}
/**
* This method is provided as a convenience wrapper for {@link Result#warn}.
*
* @param {Result} result - the {@link Result} instance
* that will receive the warning
* @param {string} text - warning message
* @param {object} [opts] - options
* @param {string} opts.plugin - plugin name that created this warning.
* PostCSS will set it automatically.
* @param {string} opts.word - a word inside a node’s string that should
* be highlighted as the source of the warning
* @param {number} opts.index - an index inside a node’s string that should
* be highlighted as the source of the warning
*
* @return {Warning} created warning object
*
* @example
* const plugin = postcss.plugin('postcss-deprecated', () => {
* return (root, result) => {
* root.walkDecls('bad', decl => {
* decl.warn(result, 'Deprecated property bad');
* });
* };
* });
*/
;
_proto.warn = function warn(result, text, opts) {
var data = {
node: this
};
for (var i in opts) {
data[i] = opts[i];
}
return result.warn(text, data);
}
/**
* Removes the node from its parent and cleans the parent properties
* from the node and its children.
*
* @example
* if ( decl.prop.match(/^-webkit-/) ) {
* decl.remove();
* }
*
* @return {Node} node to make calls chain
*/
;
_proto.remove = function remove() {
if (this.parent) {
this.parent.removeChild(this);
}
this.parent = undefined;
return this;
}
/**
* Returns a CSS string representing the node.
*
* @param {stringifier|syntax} [stringifier] - a syntax to use
* in string generation
*
* @return {string} CSS string of this node
*
* @example
* postcss.rule({ selector: 'a' }).toString() //=> "a {}"
*/
;
_proto.toString = function toString(stringifier) {
if (stringifier === void 0) {
stringifier = stringify;
}
if (stringifier.stringify) stringifier = stringifier.stringify;
var result = '';
stringifier(this, function (i) {
result += i;
});
return result;
}
/**
* Returns a clone of the node.
*
* The resulting cloned node and its (cloned) children will have
* a clean parent and code style properties.
*
* @param {object} [overrides] - new properties to override in the clone.
*
* @example
* const cloned = decl.clone({ prop: '-moz-' + decl.prop });
* cloned.raws.before //=> undefined
* cloned.parent //=> undefined
* cloned.toString() //=> -moz-transform: scale(0)
*
* @return {Node} clone of the node
*/
;
_proto.clone = function clone(overrides) {
if (overrides === void 0) {
overrides = {};
}
var cloned = cloneNode(this);
for (var name in overrides) {
cloned[name] = overrides[name];
}
return cloned;
}
/**
* Shortcut to clone the node and insert the resulting cloned node
* before the current node.
*
* @param {object} [overrides] - new properties to override in the clone.
*
* @example
* decl.cloneBefore({ prop: '-moz-' + decl.prop });
*
* @return {Node} - new node
*/
;
_proto.cloneBefore = function cloneBefore(overrides) {
if (overrides === void 0) {
overrides = {};
}
var cloned = this.clone(overrides);
this.parent.insertBefore(this, cloned);
return cloned;
}
/**
* Shortcut to clone the node and insert the resulting cloned node
* after the current node.
*
* @param {object} [overrides] - new properties to override in the clone.
*
* @return {Node} - new node
*/
;
_proto.cloneAfter = function cloneAfter(overrides) {
if (overrides === void 0) {
overrides = {};
}
var cloned = this.clone(overrides);
this.parent.insertAfter(this, cloned);
return cloned;
}
/**
* Inserts node(s) before the current node and removes the current node.
*
* @param {...Node} nodes - node(s) to replace current one
*
* @example
* if ( atrule.name == 'mixin' ) {
* atrule.replaceWith(mixinRules[atrule.params]);
* }
*
* @return {Node} current node to methods chain
*/
;
_proto.replaceWith = function replaceWith() {
var _this = this;
if (this.parent) {
for (var _len = arguments.length, nodes = new Array(_len), _key = 0; _key < _len; _key++) {
nodes[_key] = arguments[_key];
}
nodes.forEach(function (node) {
_this.parent.insertBefore(_this, node);
});
this.remove();
}
return this;
}
/**
* Removes the node from its current parent and inserts it
* at the end of `newParent`.
*
* This will clean the `before` and `after` code {@link Node#raws} data
* from the node and replace them with the indentation style of `newParent`.
* It will also clean the `between` property
* if `newParent` is in another {@link Root}.
*
* @param {Container} newParent - container node where the current node
* will be moved
*
* @example
* atrule.moveTo(atrule.root());
*
* @return {Node} current node to methods chain
*/
;
_proto.moveTo = function moveTo(newParent) {
this.cleanRaws(this.root() === newParent.root());
this.remove();
newParent.append(this);
return this;
}
/**
* Removes the node from its current parent and inserts it into
* a new parent before `otherNode`.
*
* This will also clean the node’s code style properties just as it would
* in {@link Node#moveTo}.
*
* @param {Node} otherNode - node that will be before current node
*
* @return {Node} current node to methods chain
*/
;
_proto.moveBefore = function moveBefore(otherNode) {
this.cleanRaws(this.root() === otherNode.root());
this.remove();
otherNode.parent.insertBefore(otherNode, this);
return this;
}
/**
* Removes the node from its current parent and inserts it into
* a new parent after `otherNode`.
*
* This will also clean the node’s code style properties just as it would
* in {@link Node#moveTo}.
*
* @param {Node} otherNode - node that will be after current node
*
* @return {Node} current node to methods chain
*/
;
_proto.moveAfter = function moveAfter(otherNode) {
this.cleanRaws(this.root() === otherNode.root());
this.remove();
otherNode.parent.insertAfter(otherNode, this);
return this;
}
/**
* Returns the next child of the node’s parent.
* Returns `undefined` if the current node is the last child.
*
* @return {Node|undefined} next node
*
* @example
* if ( comment.text === 'delete next' ) {
* const next = comment.next();
* if ( next ) {
* next.remove();
* }
* }
*/
;
_proto.next = function next() {
var index = this.parent.index(this);
return this.parent.nodes[index + 1];
}
/**
* Returns the previous child of the node’s parent.
* Returns `undefined` if the current node is the first child.
*
* @return {Node|undefined} previous node
*
* @example
* const annotation = decl.prev();
* if ( annotation.type == 'comment' ) {
* readAnnotation(annotation.text);
* }
*/
;
_proto.prev = function prev() {
var index = this.parent.index(this);
return this.parent.nodes[index - 1];
};
_proto.toJSON = function toJSON() {
var fixed = {};
for (var name in this) {
if (!this.hasOwnProperty(name)) continue;
if (name === 'parent') continue;
var value = this[name];
if (value instanceof Array) {
fixed[name] = value.map(function (i) {
if (typeof i === 'object' && i.toJSON) {
return i.toJSON();
} else {
return i;
}
});
} else if (typeof value === 'object' && value.toJSON) {
fixed[name] = value.toJSON();
} else {
fixed[name] = value;
}
}
return fixed;
}
/**
* Returns a {@link Node#raws} value. If the node is missing
* the code style property (because the node was manually built or cloned),
* PostCSS will try to autodetect the code style property by looking
* at other nodes in the tree.
*
* @param {string} prop - name of code style property
* @param {string} [defaultType] - name of default value, it can be missed
* if the value is the same as prop
*
* @example
* const root = postcss.parse('a { background: white }');
* root.nodes[0].append({ prop: 'color', value: 'black' });
* root.nodes[0].nodes[1].raws.before //=> undefined
* root.nodes[0].nodes[1].raw('before') //=> ' '
*
* @return {string} code style value
*/
;
_proto.raw = function raw(prop, defaultType) {
var str = new Stringifier();
return str.raw(this, prop, defaultType);
}
/**
* Finds the Root instance of the node’s tree.
*
* @example
* root.nodes[0].nodes[0].root() === root
*
* @return {Root} root parent
*/
;
_proto.root = function root() {
var result = this;
while (result.parent) {
result = result.parent;
}
return result;
};
_proto.cleanRaws = function cleanRaws(keepBetween) {
delete this.raws.before;
delete this.raws.after;
if (!keepBetween) delete this.raws.between;
};
_proto.positionInside = function positionInside(index) {
var string = this.toString();
var column = this.source.start.column;
var line = this.source.start.line;
for (var i = 0; i < index; i++) {
if (string[i] === '\n') {
column = 1;
line += 1;
} else {
column += 1;
}
}
return {
line: line,
column: column
};
};
_proto.positionBy = function positionBy(opts) {
var pos = this.source.start;
if (opts.index) {
pos = this.positionInside(opts.index);
} else if (opts.word) {
var index = this.toString().indexOf(opts.word);
if (index !== -1) pos = this.positionInside(index);
}
return pos;
};
_proto.removeSelf = function removeSelf() {
warnOnce('Node#removeSelf is deprecated. Use Node#remove.');
return this.remove();
};
_proto.replace = function replace(nodes) {
warnOnce('Node#replace is deprecated. Use Node#replaceWith');
return this.replaceWith(nodes);
};
_proto.style = function style(own, detect) {
warnOnce('Node#style() is deprecated. Use Node#raw()');
return this.raw(own, detect);
};
_proto.cleanStyles = function cleanStyles(keepBetween) {
warnOnce('Node#cleanStyles() is deprecated. Use Node#cleanRaws()');
return this.cleanRaws(keepBetween);
};
_createClass(Node, [{
key: "before",
get: function get() {
warnOnce('Node#before is deprecated. Use Node#raws.before');
return this.raws.before;
},
set: function set(val) {
warnOnce('Node#before is deprecated. Use Node#raws.before');
this.raws.before = val;
}
}, {
key: "between",
get: function get() {
warnOnce('Node#between is deprecated. Use Node#raws.between');
return this.raws.between;
},
set: function set(val) {
warnOnce('Node#between is deprecated. Use Node#raws.between');
this.raws.between = val;
}
/**
* @memberof Node#
* @member {string} type - String representing the node’s type.
* Possible values are `root`, `atrule`, `rule`,
* `decl`, or `comment`.
*
* @example
* postcss.decl({ prop: 'color', value: 'black' }).type //=> 'decl'
*/
/**
* @memberof Node#
* @member {Container} parent - the node’s parent node.
*
* @example
* root.nodes[0].parent == root;
*/
/**
* @memberof Node#
* @member {source} source - the input source of the node
*
* The property is used in source map generation.
*
* If you create a node manually (e.g., with `postcss.decl()`),
* that node will not have a `source` property and will be absent
* from the source map. For this reason, the plugin developer should
* consider cloning nodes to create new ones (in which case the new node’s
* source will reference the original, cloned node) or setting
* the `source` property manually.
*
* ```js
* // Bad
* const prefixed = postcss.decl({
* prop: '-moz-' + decl.prop,
* value: decl.value
* });
*
* // Good
* const prefixed = decl.clone({ prop: '-moz-' + decl.prop });
* ```
*
* ```js
* if ( atrule.name == 'add-link' ) {
* const rule = postcss.rule({ selector: 'a', source: atrule.source });
* atrule.parent.insertBefore(atrule, rule);
* }
* ```
*
* @example
* decl.source.input.from //=> '/home/ai/a.sass'
* decl.source.start //=> { line: 10, column: 2 }
* decl.source.end //=> { line: 10, column: 12 }
*/
/**
* @memberof Node#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
* * `after`: the space symbols after the last child of the node
* to the end of the node.
* * `between`: the symbols between the property and value
* for declarations, selector and `{` for rules, or last parameter
* and `{` for at-rules.
* * `semicolon`: contains true if the last child has
* an (optional) semicolon.
* * `afterName`: the space between the at-rule name and its parameters.
* * `left`: the space symbols between `/*` and the comment’s text.
* * `right`: the space symbols between the comment’s text
* and <code>*/</code>.
* * `important`: the content of the important statement,
* if it is not just `!important`.
*
* PostCSS cleans selectors, declaration values and at-rule parameters
* from comments and extra spaces, but it stores origin content in raws
* properties. As such, if you don’t change a declaration’s value,
* PostCSS will use the raw value with comments.
*
* @example
* const root = postcss.parse('a {\n color:black\n}')
* root.first.first.raws //=> { before: '\n ', between: ':' }
*/
}]);
return Node;
}();
/**
* Represents a CSS declaration.
*
* @extends Node
*
* @example
* const root = postcss.parse('a { color: black }');
* const decl = root.first.first;
* decl.type //=> 'decl'
* decl.toString() //=> ' color: black'
*/
var Declaration = /*#__PURE__*/function (_Node) {
_inheritsLoose(Declaration, _Node);
function Declaration(defaults) {
var _this;
_this = _Node.call(this, defaults) || this;
_this.type = 'decl';
return _this;
}
_createClass(Declaration, [{
key: "_value",
get: function get() {
warnOnce('Node#_value was deprecated. Use Node#raws.value');
return this.raws.value;
},
set: function set(val) {
warnOnce('Node#_value was deprecated. Use Node#raws.value');
this.raws.value = val;
}
}, {
key: "_important",
get: function get() {
warnOnce('Node#_important was deprecated. Use Node#raws.important');
return this.raws.important;
},
set: function set(val) {
warnOnce('Node#_important was deprecated. Use Node#raws.important');
this.raws.important = val;
}
/**
* @memberof Declaration#
* @member {string} prop - the declaration’s property name
*
* @example
* const root = postcss.parse('a { color: black }');
* const decl = root.first.first;
* decl.prop //=> 'color'
*/
/**
* @memberof Declaration#
* @member {string} value - the declaration’s value
*
* @example
* const root = postcss.parse('a { color: black }');
* const decl = root.first.first;
* decl.value //=> 'black'
*/
/**
* @memberof Declaration#
* @member {boolean} important - `true` if the declaration
* has an !important annotation.
*
* @example
* const root = postcss.parse('a { color: black !important; color: red }');
* root.first.first.important //=> true
* root.first.last.important //=> undefined
*/
/**
* @memberof Declaration#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
* * `between`: the symbols between the property and value
* for declarations, selector and `{` for rules, or last parameter
* and `{` for at-rules.
* * `important`: the content of the important statement,
* if it is not just `!important`.
*
* PostCSS cleans declaration from comments and extra spaces,
* but it stores origin content in raws properties.
* As such, if you don’t change a declaration’s value,
* PostCSS will use the raw value with comments.
*
* @example
* const root = postcss.parse('a {\n color:black\n}')
* root.first.first.raws //=> { before: '\n ', between: ':' }
*/
}]);
return Declaration;
}(Node);
/**
* Represents a comment between declarations or statements (rule and at-rules).
*
* Comments inside selectors, at-rule parameters, or declaration values
* will be stored in the `raws` properties explained above.
*
* @extends Node
*/
var Comment = /*#__PURE__*/function (_Node) {
_inheritsLoose(Comment, _Node);
function Comment(defaults) {
var _this;
_this = _Node.call(this, defaults) || this;
_this.type = 'comment';
return _this;
}
_createClass(Comment, [{
key: "left",
get: function get() {
warnOnce('Comment#left was deprecated. Use Comment#raws.left');
return this.raws.left;
},
set: function set(val) {
warnOnce('Comment#left was deprecated. Use Comment#raws.left');
this.raws.left = val;
}
}, {
key: "right",
get: function get() {
warnOnce('Comment#right was deprecated. Use Comment#raws.right');
return this.raws.right;
},
set: function set(val) {
warnOnce('Comment#right was deprecated. Use Comment#raws.right');
this.raws.right = val;
}
/**
* @memberof Comment#
* @member {string} text - the comment’s text
*/
/**
* @memberof Comment#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node.
* * `left`: the space symbols between `/*` and the comment’s text.
* * `right`: the space symbols between the comment’s text.
*/
}]);
return Comment;
}(Node);
//
var Parser = /*#__PURE__*/function () {
function Parser(input) {
this.input = input;
this.pos = 0;
this.root = new Root();
this.current = this.root;
this.spaces = '';
this.semicolon = false;
this.root.source = {
input: input,
start: {
line: 1,
column: 1
}
};
}
var _proto = Parser.prototype;
_proto.tokenize = function tokenize$1() {
this.tokens = tokenize(this.input);
};
_proto.loop = function loop() {
var token;
while (this.pos < this.tokens.length) {
token = this.tokens[this.pos];
switch (token[0]) {
case 'space':
case ';':
this.spaces += token[1];
break;
case '}':
this.end(token);
break;
case 'comment':
this.comment(token);
break;
case 'at-word':
this.atrule(token);
break;
case '{':
this.emptyRule(token);
break;
default:
this.other();
break;
}
this.pos += 1;
}
this.endFile();
};
_proto.comment = function comment(token) {
var node = new Comment();
this.init(node, token[2], token[3]);
node.source.end = {
line: token[4],
column: token[5]
};
var text = token[1].slice(2, -2);
if (/^\s*$/.test(text)) {
node.text = '';
node.raws.left = text;
node.raws.right = '';
} else {
var match = text.match(/^(\s*)([^]*[^\s])(\s*)$/);
node.text = match[2];
node.raws.left = match[1];
node.raws.right = match[3];
}
};
_proto.emptyRule = function emptyRule(token) {
var node = new Rule();
this.init(node, token[2], token[3]);
node.selector = '';
node.raws.between = '';
this.current = node;
};
_proto.other = function other() {
var token;
var end = false;
var type = null;
var colon = false;
var bracket = null;
var brackets = [];
var start = this.pos;
while (this.pos < this.tokens.length) {
token = this.tokens[this.pos];
type = token[0];
if (type === '(' || type === '[') {
if (!bracket) bracket = token;
brackets.push(type === '(' ? ')' : ']');
} else if (brackets.length === 0) {
if (type === ';') {
if (colon) {
this.decl(this.tokens.slice(start, this.pos + 1));
return;
} else {
break;
}
} else if (type === '{') {
this.rule(this.tokens.slice(start, this.pos + 1));
return;
} else if (type === '}') {
this.pos -= 1;
end = true;
break;
} else if (type === ':') {
colon = true;
}
} else if (type === brackets[brackets.length - 1]) {
brackets.pop();
if (brackets.length === 0) bracket = null;
}
this.pos += 1;
}
if (this.pos === this.tokens.length) {
this.pos -= 1;
end = true;
}
if (brackets.length > 0) this.unclosedBracket(bracket);
if (end && colon) {
while (this.pos > start) {
token = this.tokens[this.pos][0];
if (token !== 'space' && token !== 'comment') break;
this.pos -= 1;
}
this.decl(this.tokens.slice(start, this.pos + 1));
return;
}
this.unknownWord(start);
};
_proto.rule = function rule(tokens) {
tokens.pop();
var node = new Rule();
this.init(node, tokens[0][2], tokens[0][3]);
node.raws.between = this.spacesFromEnd(tokens);
this.raw(node, 'selector', tokens);
this.current = node;
};
_proto.decl = function decl(tokens) {
var node = new Declaration();
this.init(node);
var last = tokens[tokens.length - 1];
if (last[0] === ';') {
this.semicolon = true;
tokens.pop();
}
if (last[4]) {
node.source.end = {
line: last[4],
column: last[5]
};
} else {
node.source.end = {
line: last[2],
column: last[3]
};
}
while (tokens[0][0] !== 'word') {
node.raws.before += tokens.shift()[1];
}
node.source.start = {
line: tokens[0][2],
column: tokens[0][3]
};
node.prop = '';
while (tokens.length) {
var type = tokens[0][0];
if (type === ':' || type === 'space' || type === 'comment') {
break;
}
node.prop += tokens.shift()[1];
}
node.raws.between = '';
var token;
while (tokens.length) {
token = tokens.shift();
if (token[0] === ':') {
node.raws.between += token[1];
break;
} else {
node.raws.between += token[1];
}
}
if (node.prop[0] === '_' || node.prop[0] === '*') {
node.raws.before += node.prop[0];
node.prop = node.prop.slice(1);
}
node.raws.between += this.spacesFromStart(tokens);
this.precheckMissedSemicolon(tokens);
for (var i = tokens.length - 1; i > 0; i--) {
token = tokens[i];
if (token[1] === '!important') {
node.important = true;
var string = this.stringFrom(tokens, i);
string = this.spacesFromEnd(tokens) + string;
if (string !== ' !important') node.raws.important = string;
break;
} else if (token[1] === 'important') {
var cache = tokens.slice(0);
var str = '';
for (var j = i; j > 0; j--) {
var _type = cache[j][0];
if (str.trim().indexOf('!') === 0 && _type !== 'space') {
break;
}
str = cache.pop()[1] + str;
}
if (str.trim().indexOf('!') === 0) {
node.important = true;
node.raws.important = str;
tokens = cache;
}
}
if (token[0] !== 'space' && token[0] !== 'comment') {
break;
}
}
this.raw(node, 'value', tokens);
if (node.value.indexOf(':') !== -1) this.checkMissedSemicolon(tokens);
};
_proto.atrule = function atrule(token) {
var node = new AtRule();
node.name = token[1].slice(1);
if (node.name === '') {
this.unnamedAtrule(node, token);
}
this.init(node, token[2], token[3]);
var last = false;
var open = false;
var params = [];
this.pos += 1;
while (this.pos < this.tokens.length) {
token = this.tokens[this.pos];
if (token[0] === ';') {
node.source.end = {
line: token[2],
column: token[3]
};
this.semicolon = true;
break;
} else if (token[0] === '{') {
open = true;
break;
} else if (token[0] === '}') {
this.end(token);
break;
} else {
params.push(token);
}
this.pos += 1;
}
if (this.pos === this.tokens.length) {
last = true;
}
node.raws.between = this.spacesFromEnd(params);
if (params.length) {
node.raws.afterName = this.spacesFromStart(params);
this.raw(node, 'params', params);
if (last) {
token = params[params.length - 1];
node.source.end = {
line: token[4],
column: token[5]
};
this.spaces = node.raws.between;
node.raws.between = '';
}
} else {
node.raws.afterName = '';
node.params = '';
}
if (open) {
node.nodes = [];
this.current = node;
}
};
_proto.end = function end(token) {
if (this.current.nodes && this.current.nodes.length) {
this.current.raws.semicolon = this.semicolon;
}
this.semicolon = false;
this.current.raws.after = (this.current.raws.after || '') + this.spaces;
this.spaces = '';
if (this.current.parent) {
this.current.source.end = {
line: token[2],
column: token[3]
};
this.current = this.current.parent;
} else {
this.unexpectedClose(token);
}
};
_proto.endFile = function endFile() {
if (this.current.parent) this.unclosedBlock();
if (this.current.nodes && this.current.nodes.length) {
this.current.raws.semicolon = this.semicolon;
}
this.current.raws.after = (this.current.raws.after || '') + this.spaces;
} // Helpers
;
_proto.init = function init(node, line, column) {
this.current.push(node);
node.source = {
start: {
line: line,
column: column
},
input: this.input
};
node.raws.before = this.spaces;
this.spaces = '';
if (node.type !== 'comment') this.semicolon = false;
};
_proto.raw = function raw(node, prop, tokens) {
var token, type;
var length = tokens.length;
var value = '';
var clean = true;
for (var i = 0; i < length; i += 1) {
token = tokens[i];
type = token[0];
if (type === 'comment' || type === 'space' && i === length - 1) {
clean = false;
} else {
value += token[1];
}
}
if (!clean) {
var raw = tokens.reduce(function (all, i) {
return all + i[1];
}, '');
node.raws[prop] = {
value: value,
raw: raw
};
}
node[prop] = value;
};
_proto.spacesFromEnd = function spacesFromEnd(tokens) {
var lastTokenType;
var spaces = '';
while (tokens.length) {
lastTokenType = tokens[tokens.length - 1][0];
if (lastTokenType !== 'space' && lastTokenType !== 'comment') break;
spaces = tokens.pop()[1] + spaces;
}
return spaces;
};
_proto.spacesFromStart = function spacesFromStart(tokens) {
var next;
var spaces = '';
while (tokens.length) {
next = tokens[0][0];
if (next !== 'space' && next !== 'comment') break;
spaces += tokens.shift()[1];
}
return spaces;
};
_proto.stringFrom = function stringFrom(tokens, from) {
var result = '';
for (var i = from; i < tokens.length; i++) {
result += tokens[i][1];
}
tokens.splice(from, tokens.length - from);
return result;
};
_proto.colon = function colon(tokens) {
var brackets = 0;
var token, type, prev;
for (var i = 0; i < tokens.length; i++) {
token = tokens[i];
type = token[0];
if (type === '(') {
brackets += 1;
} else if (type === ')') {
brackets -= 1;
} else if (brackets === 0 && type === ':') {
if (!prev) {
this.doubleColon(token);
} else if (prev[0] === 'word' && prev[1] === 'progid') {
continue;
} else {
return i;
}
}
prev = token;
}
return false;
} // Errors
;
_proto.unclosedBracket = function unclosedBracket(bracket) {
throw this.input.error('Unclosed bracket', bracket[2], bracket[3]);
};
_proto.unknownWord = function unknownWord(start) {
var token = this.tokens[start];
throw this.input.error('Unknown word', token[2], token[3]);
};
_proto.unexpectedClose = function unexpectedClose(token) {
throw this.input.error('Unexpected }', token[2], token[3]);
};
_proto.unclosedBlock = function unclosedBlock() {
var pos = this.current.source.start;
throw this.input.error('Unclosed block', pos.line, pos.column);
};
_proto.doubleColon = function doubleColon(token) {
throw this.input.error('Double colon', token[2], token[3]);
};
_proto.unnamedAtrule = function unnamedAtrule(node, token) {
throw this.input.error('At-rule without name', token[2], token[3]);
};
_proto.precheckMissedSemicolon = function precheckMissedSemicolon(tokens) {
};
_proto.checkMissedSemicolon = function checkMissedSemicolon(tokens) {
var colon = this.colon(tokens);
if (colon === false) return;
var founded = 0;
var token;
for (var j = colon - 1; j >= 0; j--) {
token = tokens[j];
if (token[0] !== 'space') {
founded += 1;
if (founded === 2) break;
}
}
throw this.input.error('Missed semicolon', token[2], token[3]);
};
return Parser;
}();
//
function parse(css, opts) {
if (opts && opts.safe) {
throw new Error('Option safe was removed. ' + 'Use parser: require("postcss-safe-parser")');
}
var input = new Input(css, opts);
var parser = new Parser(input);
try {
parser.tokenize();
parser.loop();
} catch (e) {
if (e.name === 'CssSyntaxError' && opts && opts.from) {
if (/\.scss$/i.test(opts.from)) {
e.message += '\nYou tried to parse SCSS with ' + 'the standard CSS parser; ' + 'try again with the postcss-scss parser';
} else if (/\.less$/i.test(opts.from)) {
e.message += '\nYou tried to parse Less with ' + 'the standard CSS parser; ' + 'try again with the postcss-less parser';
}
}
throw e;
}
return parser.root;
}
function cleanSource(nodes) {
return nodes.map(function (i) {
if (i.nodes) i.nodes = cleanSource(i.nodes);
delete i.source;
return i;
});
}
/**
* @callback childCondition
* @param {Node} node - container child
* @param {number} index - child index
* @param {Node[]} nodes - all container children
* @return {boolean}
*/
/**
* @callback childIterator
* @param {Node} node - container child
* @param {number} index - child index
* @return {false|undefined} returning `false` will break iteration
*/
/**
* The {@link Root}, {@link AtRule}, and {@link Rule} container nodes
* inherit some common methods to help work with their children.
*
* Note that all containers can store any content. If you write a rule inside
* a rule, PostCSS will parse it.
*
* @extends Node
* @abstract
*/
var Container = /*#__PURE__*/function (_Node) {
_inheritsLoose(Container, _Node);
function Container() {
return _Node.apply(this, arguments) || this;
}
var _proto = Container.prototype;
_proto.push = function push(child) {
child.parent = this;
this.nodes.push(child);
return this;
}
/**
* Iterates through the container’s immediate children,
* calling `callback` for each child.
*
* Returning `false` in the callback will break iteration.
*
* This method only iterates through the container’s immediate children.
* If you need to recursively iterate through all the container’s descendant
* nodes, use {@link Container#walk}.
*
* Unlike the for `{}`-cycle or `Array#forEach` this iterator is safe
* if you are mutating the array of child nodes during iteration.
* PostCSS will adjust the current index to match the mutations.
*
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* const root = postcss.parse('a { color: black; z-index: 1 }');
* const rule = root.first;
*
* for ( let decl of rule.nodes ) {
* decl.cloneBefore({ prop: '-webkit-' + decl.prop });
* // Cycle will be infinite, because cloneBefore moves the current node
* // to the next index
* }
*
* rule.each(decl => {
* decl.cloneBefore({ prop: '-webkit-' + decl.prop });
* // Will be executed only for color and z-index
* });
*/
;
_proto.each = function each(callback) {
if (!this.lastEach) this.lastEach = 0;
if (!this.indexes) this.indexes = {};
this.lastEach += 1;
var id = this.lastEach;
this.indexes[id] = 0;
if (!this.nodes) return undefined;
var index, result;
while (this.indexes[id] < this.nodes.length) {
index = this.indexes[id];
result = callback(this.nodes[index], index);
if (result === false) break;
this.indexes[id] += 1;
}
delete this.indexes[id];
return result;
}
/**
* Traverses the container’s descendant nodes, calling callback
* for each node.
*
* Like container.each(), this method is safe to use
* if you are mutating arrays during iteration.
*
* If you only need to iterate through the container’s immediate children,
* use {@link Container#each}.
*
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* root.walk(node => {
* // Traverses all descendant nodes.
* });
*/
;
_proto.walk = function walk(callback) {
return this.each(function (child, i) {
var result = callback(child, i);
if (result !== false && child.walk) {
result = child.walk(callback);
}
return result;
});
}
/**
* Traverses the container’s descendant nodes, calling callback
* for each declaration node.
*
* If you pass a filter, iteration will only happen over declarations
* with matching properties.
*
* Like {@link Container#each}, this method is safe
* to use if you are mutating arrays during iteration.
*
* @param {string|RegExp} [prop] - string or regular expression
* to filter declarations by property name
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* root.walkDecls(decl => {
* checkPropertySupport(decl.prop);
* });
*
* root.walkDecls('border-radius', decl => {
* decl.remove();
* });
*
* root.walkDecls(/^background/, decl => {
* decl.value = takeFirstColorFromGradient(decl.value);
* });
*/
;
_proto.walkDecls = function walkDecls(prop, callback) {
if (!callback) {
callback = prop;
return this.walk(function (child, i) {
if (child.type === 'decl') {
return callback(child, i);
}
});
} else if (prop instanceof RegExp) {
return this.walk(function (child, i) {
if (child.type === 'decl' && prop.test(child.prop)) {
return callback(child, i);
}
});
} else {
return this.walk(function (child, i) {
if (child.type === 'decl' && child.prop === prop) {
return callback(child, i);
}
});
}
}
/**
* Traverses the container’s descendant nodes, calling callback
* for each rule node.
*
* If you pass a filter, iteration will only happen over rules
* with matching selectors.
*
* Like {@link Container#each}, this method is safe
* to use if you are mutating arrays during iteration.
*
* @param {string|RegExp} [selector] - string or regular expression
* to filter rules by selector
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* const selectors = [];
* root.walkRules(rule => {
* selectors.push(rule.selector);
* });
* console.log(`Your CSS uses ${selectors.length} selectors`);
*/
;
_proto.walkRules = function walkRules(selector, callback) {
if (!callback) {
callback = selector;
return this.walk(function (child, i) {
if (child.type === 'rule') {
return callback(child, i);
}
});
} else if (selector instanceof RegExp) {
return this.walk(function (child, i) {
if (child.type === 'rule' && selector.test(child.selector)) {
return callback(child, i);
}
});
} else {
return this.walk(function (child, i) {
if (child.type === 'rule' && child.selector === selector) {
return callback(child, i);
}
});
}
}
/**
* Traverses the container’s descendant nodes, calling callback
* for each at-rule node.
*
* If you pass a filter, iteration will only happen over at-rules
* that have matching names.
*
* Like {@link Container#each}, this method is safe
* to use if you are mutating arrays during iteration.
*
* @param {string|RegExp} [name] - string or regular expression
* to filter at-rules by name
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* root.walkAtRules(rule => {
* if ( isOld(rule.name) ) rule.remove();
* });
*
* let first = false;
* root.walkAtRules('charset', rule => {
* if ( !first ) {
* first = true;
* } else {
* rule.remove();
* }
* });
*/
;
_proto.walkAtRules = function walkAtRules(name, callback) {
if (!callback) {
callback = name;
return this.walk(function (child, i) {
if (child.type === 'atrule') {
return callback(child, i);
}
});
} else if (name instanceof RegExp) {
return this.walk(function (child, i) {
if (child.type === 'atrule' && name.test(child.name)) {
return callback(child, i);
}
});
} else {
return this.walk(function (child, i) {
if (child.type === 'atrule' && child.name === name) {
return callback(child, i);
}
});
}
}
/**
* Traverses the container’s descendant nodes, calling callback
* for each comment node.
*
* Like {@link Container#each}, this method is safe
* to use if you are mutating arrays during iteration.
*
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* root.walkComments(comment => {
* comment.remove();
* });
*/
;
_proto.walkComments = function walkComments(callback) {
return this.walk(function (child, i) {
if (child.type === 'comment') {
return callback(child, i);
}
});
}
/**
* Inserts new nodes to the start of the container.
*
* @param {...(Node|object|string|Node[])} children - new nodes
*
* @return {Node} this node for methods chain
*
* @example
* const decl1 = postcss.decl({ prop: 'color', value: 'black' });
* const decl2 = postcss.decl({ prop: 'background-color', value: 'white' });
* rule.append(decl1, decl2);
*
* root.append({ name: 'charset', params: '"UTF-8"' }); // at-rule
* root.append({ selector: 'a' }); // rule
* rule.append({ prop: 'color', value: 'black' }); // declaration
* rule.append({ text: 'Comment' }) // comment
*
* root.append('a {}');
* root.first.append('color: black; z-index: 1');
*/
;
_proto.append = function append() {
var _this = this;
for (var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++) {
children[_key] = arguments[_key];
}
children.forEach(function (child) {
var nodes = _this.normalize(child, _this.last);
nodes.forEach(function (node) {
return _this.nodes.push(node);
});
});
return this;
}
/**
* Inserts new nodes to the end of the container.
*
* @param {...(Node|object|string|Node[])} children - new nodes
*
* @return {Node} this node for methods chain
*
* @example
* const decl1 = postcss.decl({ prop: 'color', value: 'black' });
* const decl2 = postcss.decl({ prop: 'background-color', value: 'white' });
* rule.prepend(decl1, decl2);
*
* root.append({ name: 'charset', params: '"UTF-8"' }); // at-rule
* root.append({ selector: 'a' }); // rule
* rule.append({ prop: 'color', value: 'black' }); // declaration
* rule.append({ text: 'Comment' }) // comment
*
* root.append('a {}');
* root.first.append('color: black; z-index: 1');
*/
;
_proto.prepend = function prepend() {
var _this2 = this;
for (var _len2 = arguments.length, children = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
children[_key2] = arguments[_key2];
}
children = children.reverse();
children.forEach(function (child) {
var nodes = _this2.normalize(child, _this2.first, 'prepend').reverse();
nodes.forEach(function (node) {
return _this2.nodes.unshift(node);
});
for (var id in _this2.indexes) {
_this2.indexes[id] = _this2.indexes[id] + nodes.length;
}
});
return this;
};
_proto.cleanRaws = function cleanRaws(keepBetween) {
_Node.prototype.cleanRaws.call(this, keepBetween);
if (this.nodes) {
this.nodes.forEach(function (node) {
return node.cleanRaws(keepBetween);
});
}
}
/**
* Insert new node before old node within the container.
*
* @param {Node|number} exist - child or child’s index.
* @param {Node|object|string|Node[]} add - new node
*
* @return {Node} this node for methods chain
*
* @example
* rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }));
*/
;
_proto.insertBefore = function insertBefore(exist, add) {
var _this3 = this;
exist = this.index(exist);
var type = exist === 0 ? 'prepend' : false;
var nodes = this.normalize(add, this.nodes[exist], type).reverse();
nodes.forEach(function (node) {
return _this3.nodes.splice(exist, 0, node);
});
var index;
for (var id in this.indexes) {
index = this.indexes[id];
if (exist <= index) {
this.indexes[id] = index + nodes.length;
}
}
return this;
}
/**
* Insert new node after old node within the container.
*
* @param {Node|number} exist - child or child’s index
* @param {Node|object|string|Node[]} add - new node
*
* @return {Node} this node for methods chain
*/
;
_proto.insertAfter = function insertAfter(exist, add) {
var _this4 = this;
exist = this.index(exist);
var nodes = this.normalize(add, this.nodes[exist]).reverse();
nodes.forEach(function (node) {
return _this4.nodes.splice(exist + 1, 0, node);
});
var index;
for (var id in this.indexes) {
index = this.indexes[id];
if (exist < index) {
this.indexes[id] = index + nodes.length;
}
}
return this;
};
_proto.remove = function remove(child) {
if (typeof child !== 'undefined') {
warnOnce('Container#remove is deprecated. ' + 'Use Container#removeChild');
this.removeChild(child);
} else {
_Node.prototype.remove.call(this);
}
return this;
}
/**
* Removes node from the container and cleans the parent properties
* from the node and its children.
*
* @param {Node|number} child - child or child’s index
*
* @return {Node} this node for methods chain
*
* @example
* rule.nodes.length //=> 5
* rule.removeChild(decl);
* rule.nodes.length //=> 4
* decl.parent //=> undefined
*/
;
_proto.removeChild = function removeChild(child) {
child = this.index(child);
this.nodes[child].parent = undefined;
this.nodes.splice(child, 1);
var index;
for (var id in this.indexes) {
index = this.indexes[id];
if (index >= child) {
this.indexes[id] = index - 1;
}
}
return this;
}
/**
* Removes all children from the container
* and cleans their parent properties.
*
* @return {Node} this node for methods chain
*
* @example
* rule.removeAll();
* rule.nodes.length //=> 0
*/
;
_proto.removeAll = function removeAll() {
this.nodes.forEach(function (node) {
return node.parent = undefined;
});
this.nodes = [];
return this;
}
/**
* Passes all declaration values within the container that match pattern
* through callback, replacing those values with the returned result
* of callback.
*
* This method is useful if you are using a custom unit or function
* and need to iterate through all values.
*
* @param {string|RegExp} pattern - replace pattern
* @param {object} opts - options to speed up the search
* @param {string|string[]} opts.props - an array of property names
* @param {string} opts.fast - string that’s used
* to narrow down values and speed up
the regexp search
* @param {function|string} callback - string to replace pattern
* or callback that returns a new
* value.
* The callback will receive
* the same arguments as those
* passed to a function parameter
* of `String#replace`.
*
* @return {Node} this node for methods chain
*
* @example
* root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {
* return 15 * parseInt(string) + 'px';
* });
*/
;
_proto.replaceValues = function replaceValues(pattern, opts, callback) {
if (!callback) {
callback = opts;
opts = {};
}
this.walkDecls(function (decl) {
if (opts.props && opts.props.indexOf(decl.prop) === -1) return;
if (opts.fast && decl.value.indexOf(opts.fast) === -1) return;
decl.value = decl.value.replace(pattern, callback);
});
return this;
}
/**
* Returns `true` if callback returns `true`
* for all of the container’s children.
*
* @param {childCondition} condition - iterator returns true or false.
*
* @return {boolean} is every child pass condition
*
* @example
* const noPrefixes = rule.every(i => i.prop[0] !== '-');
*/
;
_proto.every = function every(condition) {
return this.nodes.every(condition);
}
/**
* Returns `true` if callback returns `true` for (at least) one
* of the container’s children.
*
* @param {childCondition} condition - iterator returns true or false.
*
* @return {boolean} is some child pass condition
*
* @example
* const hasPrefix = rule.some(i => i.prop[0] === '-');
*/
;
_proto.some = function some(condition) {
return this.nodes.some(condition);
}
/**
* Returns a `child`’s index within the {@link Container#nodes} array.
*
* @param {Node} child - child of the current container.
*
* @return {number} child index
*
* @example
* rule.index( rule.nodes[2] ) //=> 2
*/
;
_proto.index = function index(child) {
if (typeof child === 'number') {
return child;
} else {
return this.nodes.indexOf(child);
}
}
/**
* The container’s first child.
*
* @type {Node}
*
* @example
* rule.first == rules.nodes[0];
*/
;
_proto.normalize = function normalize(nodes, sample) {
var _this5 = this;
if (typeof nodes === 'string') {
nodes = cleanSource(parse(nodes).nodes);
} else if (!Array.isArray(nodes)) {
if (nodes.type === 'root') {
nodes = nodes.nodes;
} else if (nodes.type) {
nodes = [nodes];
} else if (nodes.prop) {
if (typeof nodes.value === 'undefined') {
throw new Error('Value field is missed in node creation');
} else if (typeof nodes.value !== 'string') {
nodes.value = String(nodes.value);
}
nodes = [new Declaration(nodes)];
} else if (nodes.selector) {
nodes = [new Rule(nodes)];
} else if (nodes.name) {
nodes = [new AtRule(nodes)];
} else if (nodes.text) {
nodes = [new Comment(nodes)];
} else {
throw new Error('Unknown node type in node creation');
}
}
var processed = nodes.map(function (i) {
if (typeof i.raws === 'undefined') i = _this5.rebuild(i);
if (i.parent) i = i.clone();
if (typeof i.raws.before === 'undefined') {
if (sample && typeof sample.raws.before !== 'undefined') {
i.raws.before = sample.raws.before.replace(/[^\s]/g, '');
}
}
i.parent = _this5;
return i;
});
return processed;
};
_proto.rebuild = function rebuild(node, parent) {
var _this6 = this;
var fix;
if (node.type === 'root') {
fix = new Root();
} else if (node.type === 'atrule') {
fix = new AtRule();
} else if (node.type === 'rule') {
fix = new Rule();
} else if (node.type === 'decl') {
fix = new Declaration();
} else if (node.type === 'comment') {
fix = new Comment();
}
for (var i in node) {
if (i === 'nodes') {
fix.nodes = node.nodes.map(function (j) {
return _this6.rebuild(j, fix);
});
} else if (i === 'parent' && parent) {
fix.parent = parent;
} else if (node.hasOwnProperty(i)) {
fix[i] = node[i];
}
}
return fix;
};
_proto.eachInside = function eachInside(callback) {
warnOnce('Container#eachInside is deprecated. ' + 'Use Container#walk instead.');
return this.walk(callback);
};
_proto.eachDecl = function eachDecl(prop, callback) {
warnOnce('Container#eachDecl is deprecated. ' + 'Use Container#walkDecls instead.');
return this.walkDecls(prop, callback);
};
_proto.eachRule = function eachRule(selector, callback) {
warnOnce('Container#eachRule is deprecated. ' + 'Use Container#walkRules instead.');
return this.walkRules(selector, callback);
};
_proto.eachAtRule = function eachAtRule(name, callback) {
warnOnce('Container#eachAtRule is deprecated. ' + 'Use Container#walkAtRules instead.');
return this.walkAtRules(name, callback);
};
_proto.eachComment = function eachComment(callback) {
warnOnce('Container#eachComment is deprecated. ' + 'Use Container#walkComments instead.');
return this.walkComments(callback);
};
_createClass(Container, [{
key: "first",
get: function get() {
if (!this.nodes) return undefined;
return this.nodes[0];
}
/**
* The container’s last child.
*
* @type {Node}
*
* @example
* rule.last == rule.nodes[rule.nodes.length - 1];
*/
}, {
key: "last",
get: function get() {
if (!this.nodes) return undefined;
return this.nodes[this.nodes.length - 1];
}
}, {
key: "semicolon",
get: function get() {
warnOnce('Node#semicolon is deprecated. Use Node#raws.semicolon');
return this.raws.semicolon;
},
set: function set(val) {
warnOnce('Node#semicolon is deprecated. Use Node#raws.semicolon');
this.raws.semicolon = val;
}
}, {
key: "after",
get: function get() {
warnOnce('Node#after is deprecated. Use Node#raws.after');
return this.raws.after;
},
set: function set(val) {
warnOnce('Node#after is deprecated. Use Node#raws.after');
this.raws.after = val;
}
/**
* @memberof Container#
* @member {Node[]} nodes - an array containing the container’s children
*
* @example
* const root = postcss.parse('a { color: black }');
* root.nodes.length //=> 1
* root.nodes[0].selector //=> 'a'
* root.nodes[0].nodes[0].prop //=> 'color'
*/
}]);
return Container;
}(Node);
/**
* Represents an at-rule.
*
* If it’s followed in the CSS by a {} block, this node will have
* a nodes property representing its children.
*
* @extends Container
*
* @example
* const root = postcss.parse('@charset "UTF-8"; @media print {}');
*
* const charset = root.first;
* charset.type //=> 'atrule'
* charset.nodes //=> undefined
*
* const media = root.last;
* media.nodes //=> []
*/
var AtRule = /*#__PURE__*/function (_Container) {
_inheritsLoose(AtRule, _Container);
function AtRule(defaults) {
var _this;
_this = _Container.call(this, defaults) || this;
_this.type = 'atrule';
return _this;
}
var _proto = AtRule.prototype;
_proto.append = function append() {
var _Container$prototype$;
if (!this.nodes) this.nodes = [];
for (var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++) {
children[_key] = arguments[_key];
}
return (_Container$prototype$ = _Container.prototype.append).call.apply(_Container$prototype$, [this].concat(children));
};
_proto.prepend = function prepend() {
var _Container$prototype$2;
if (!this.nodes) this.nodes = [];
for (var _len2 = arguments.length, children = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
children[_key2] = arguments[_key2];
}
return (_Container$prototype$2 = _Container.prototype.prepend).call.apply(_Container$prototype$2, [this].concat(children));
};
_createClass(AtRule, [{
key: "afterName",
get: function get() {
warnOnce('AtRule#afterName was deprecated. Use AtRule#raws.afterName');
return this.raws.afterName;
},
set: function set(val) {
warnOnce('AtRule#afterName was deprecated. Use AtRule#raws.afterName');
this.raws.afterName = val;
}
}, {
key: "_params",
get: function get() {
warnOnce('AtRule#_params was deprecated. Use AtRule#raws.params');
return this.raws.params;
},
set: function set(val) {
warnOnce('AtRule#_params was deprecated. Use AtRule#raws.params');
this.raws.params = val;
}
/**
* @memberof AtRule#
* @member {string} name - the at-rule’s name immediately follows the `@`
*
* @example
* const root = postcss.parse('@media print {}');
* media.name //=> 'media'
* const media = root.first;
*/
/**
* @memberof AtRule#
* @member {string} params - the at-rule’s parameters, the values
* that follow the at-rule’s name but precede
* any {} block
*
* @example
* const root = postcss.parse('@media print, screen {}');
* const media = root.first;
* media.params //=> 'print, screen'
*/
/**
* @memberof AtRule#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
* * `after`: the space symbols after the last child of the node
* to the end of the node.
* * `between`: the symbols between the property and value
* for declarations, selector and `{` for rules, or last parameter
* and `{` for at-rules.
* * `semicolon`: contains true if the last child has
* an (optional) semicolon.
* * `afterName`: the space between the at-rule name and its parameters.
*
* PostCSS cleans at-rule parameters from comments and extra spaces,
* but it stores origin content in raws properties.
* As such, if you don’t change a declaration’s value,
* PostCSS will use the raw value with comments.
*
* @example
* const root = postcss.parse(' @media\nprint {\n}')
* root.first.first.raws //=> { before: ' ',
* // between: ' ',
* // afterName: '\n',
* // after: '\n' }
*/
}]);
return AtRule;
}(Container);
//
/**
* Contains helpers for safely splitting lists of CSS values,
* preserving parentheses and quotes.
*
* @example
* const list = postcss.list;
*
* @namespace list
*/
var list = {
split: function split(string, separators, last) {
var array = [];
var current = '';
var split = false;
var func = 0;
var quote = false;
var escape = false;
for (var i = 0; i < string.length; i++) {
var letter = string[i];
if (quote) {
if (escape) {
escape = false;
} else if (letter === '\\') {
escape = true;
} else if (letter === quote) {
quote = false;
}
} else if (letter === '"' || letter === "'") {
quote = letter;
} else if (letter === '(') {
func += 1;
} else if (letter === ')') {
if (func > 0) func -= 1;
} else if (func === 0) {
if (separators.indexOf(letter) !== -1) split = true;
}
if (split) {
if (current !== '') array.push(current.trim());
current = '';
split = false;
} else {
current += letter;
}
}
if (last || current !== '') array.push(current.trim());
return array;
},
/**
* Safely splits space-separated values (such as those for `background`,
* `border-radius`, and other shorthand properties).
*
* @param {string} string - space-separated values
*
* @return {string[]} splitted values
*
* @example
* postcss.list.space('1px calc(10% + 1px)') //=> ['1px', 'calc(10% + 1px)']
*/
space: function space(string) {
var spaces = [' ', '\n', '\t'];
return list.split(string, spaces);
},
/**
* Safely splits comma-separated values (such as those for `transition-*`
* and `background` properties).
*
* @param {string} string - comma-separated values
*
* @return {string[]} splitted values
*
* @example
* postcss.list.comma('black, linear-gradient(white, black)')
* //=> ['black', 'linear-gradient(white, black)']
*/
comma: function comma(string) {
var comma = ',';
return list.split(string, [comma], true);
}
};
/**
* Represents a CSS rule: a selector followed by a declaration block.
*
* @extends Container
*
* @example
* const root = postcss.parse('a{}');
* const rule = root.first;
* rule.type //=> 'rule'
* rule.toString() //=> 'a{}'
*/
var Rule = /*#__PURE__*/function (_Container) {
_inheritsLoose(Rule, _Container);
function Rule(defaults) {
var _this;
_this = _Container.call(this, defaults) || this;
_this.type = 'rule';
if (!_this.nodes) _this.nodes = [];
return _this;
}
/**
* An array containing the rule’s individual selectors.
* Groups of selectors are split at commas.
*
* @type {string[]}
*
* @example
* const root = postcss.parse('a, b { }');
* const rule = root.first;
*
* rule.selector //=> 'a, b'
* rule.selectors //=> ['a', 'b']
*
* rule.selectors = ['a', 'strong'];
* rule.selector //=> 'a, strong'
*/
_createClass(Rule, [{
key: "selectors",
get: function get() {
return list.comma(this.selector);
},
set: function set(values) {
var match = this.selector ? this.selector.match(/,\s*/) : null;
var sep = match ? match[0] : "," + this.raw('between', 'beforeOpen');
this.selector = values.join(sep);
}
}, {
key: "_selector",
get: function get() {
warnOnce('Rule#_selector is deprecated. Use Rule#raws.selector');
return this.raws.selector;
},
set: function set(val) {
warnOnce('Rule#_selector is deprecated. Use Rule#raws.selector');
this.raws.selector = val;
}
/**
* @memberof Rule#
* @member {string} selector - the rule’s full selector represented
* as a string
*
* @example
* const root = postcss.parse('a, b { }');
* const rule = root.first;
* rule.selector //=> 'a, b'
*/
/**
* @memberof Rule#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
* * `after`: the space symbols after the last child of the node
* to the end of the node.
* * `between`: the symbols between the property and value
* for declarations, selector and `{` for rules, or last parameter
* and `{` for at-rules.
* * `semicolon`: contains true if the last child has
* an (optional) semicolon.
*
* PostCSS cleans selectors from comments and extra spaces,
* but it stores origin content in raws properties.
* As such, if you don’t change a declaration’s value,
* PostCSS will use the raw value with comments.
*
* @example
* const root = postcss.parse('a {\n color:black\n}')
* root.first.first.raws //=> { before: '', between: ' ', after: '\n' }
*/
}]);
return Rule;
}(Container);
//
/**
* Represents a plugin’s warning. It can be created using {@link Node#warn}.
*
* @example
* if ( decl.important ) {
* decl.warn(result, 'Avoid !important', { word: '!important' });
* }
*/
var Warning = /*#__PURE__*/function () {
/**
* @param {string} text - warning message
* @param {Object} [opts] - warning options
* @param {Node} opts.node - CSS node that caused the warning
* @param {string} opts.word - word in CSS source that caused the warning
* @param {number} opts.index - index in CSS node string that caused
* the warning
* @param {string} opts.plugin - name of the plugin that created
* this warning. {@link Result#warn} fills
* this property automatically.
*/
function Warning(text, opts) {
if (opts === void 0) {
opts = {};
}
/**
* @member {string} - Type to filter warnings from
* {@link Result#messages}. Always equal
* to `"warning"`.
*
* @example
* const nonWarning = result.messages.filter(i => i.type !== 'warning')
*/
this.type = 'warning';
/**
* @member {string} - The warning message.
*
* @example
* warning.text //=> 'Try to avoid !important'
*/
this.text = text;
if (opts.node && opts.node.source) {
var pos = opts.node.positionBy(opts);
/**
* @member {number} - Line in the input file
* with this warning’s source
*
* @example
* warning.line //=> 5
*/
this.line = pos.line;
/**
* @member {number} - Column in the input file
* with this warning’s source.
*
* @example
* warning.column //=> 6
*/
this.column = pos.column;
}
for (var opt in opts) {
this[opt] = opts[opt];
}
}
/**
* Returns a warning position and message.
*
* @example
* warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important'
*
* @return {string} warning position and message
*/
var _proto = Warning.prototype;
_proto.toString = function toString() {
if (this.node) {
return this.node.error(this.text, {
plugin: this.plugin,
index: this.index,
word: this.word
}).message;
} else if (this.plugin) {
return this.plugin + ": " + this.text;
} else {
return this.text;
}
}
/**
* @memberof Warning#
* @member {string} plugin - The name of the plugin that created
* it will fill this property automatically.
* this warning. When you call {@link Node#warn}
*
* @example
* warning.plugin //=> 'postcss-important'
*/
/**
* @memberof Warning#
* @member {Node} node - Contains the CSS node that caused the warning.
*
* @example
* warning.node.toString() //=> 'color: white !important'
*/
;
return Warning;
}();
/**
* @typedef {object} Message
* @property {string} type - message type
* @property {string} plugin - source PostCSS plugin name
*/
/**
* Provides the result of the PostCSS transformations.
*
* A Result instance is returned by {@link LazyResult#then}
* or {@link Root#toResult} methods.
*
* @example
* postcss([cssnext]).process(css).then(function (result) {
* console.log(result.css);
* });
*
* @example
* var result2 = postcss.parse(css).toResult();
*/
var Result = /*#__PURE__*/function () {
/**
* @param {Processor} processor - processor used for this transformation.
* @param {Root} root - Root node after all transformations.
* @param {processOptions} opts - options from the {@link Processor#process}
* or {@link Root#toResult}
*/
function Result(processor, root, opts) {
/**
* @member {Processor} - The Processor instance used
* for this transformation.
*
* @example
* for ( let plugin of result.processor.plugins) {
* if ( plugin.postcssPlugin === 'postcss-bad' ) {
* throw 'postcss-good is incompatible with postcss-bad';
* }
* });
*/
this.processor = processor;
/**
* @member {Message[]} - Contains messages from plugins
* (e.g., warnings or custom messages).
* Each message should have type
* and plugin properties.
*
* @example
* postcss.plugin('postcss-min-browser', () => {
* return (root, result) => {
* var browsers = detectMinBrowsersByCanIUse(root);
* result.messages.push({
* type: 'min-browser',
* plugin: 'postcss-min-browser',
* browsers: browsers
* });
* };
* });
*/
this.messages = [];
/**
* @member {Root} - Root node after all transformations.
*
* @example
* root.toResult().root == root;
*/
this.root = root;
/**
* @member {processOptions} - Options from the {@link Processor#process}
* or {@link Root#toResult} call
* that produced this Result instance.
*
* @example
* root.toResult(opts).opts == opts;
*/
this.opts = opts;
/**
* @member {string} - A CSS string representing of {@link Result#root}.
*
* @example
* postcss.parse('a{}').toResult().css //=> "a{}"
*/
this.css = undefined;
/**
* @member {SourceMapGenerator} - An instance of `SourceMapGenerator`
* class from the `source-map` library,
* representing changes
* to the {@link Result#root} instance.
*
* @example
* result.map.toJSON() //=> { version: 3, file: 'a.css', … }
*
* @example
* if ( result.map ) {
* fs.writeFileSync(result.opts.to + '.map', result.map.toString());
* }
*/
this.map = undefined;
}
/**
* Returns for @{link Result#css} content.
*
* @example
* result + '' === result.css
*
* @return {string} string representing of {@link Result#root}
*/
var _proto = Result.prototype;
_proto.toString = function toString() {
return this.css;
}
/**
* Creates an instance of {@link Warning} and adds it
* to {@link Result#messages}.
*
* @param {string} text - warning message
* @param {Object} [opts] - warning options
* @param {Node} opts.node - CSS node that caused the warning
* @param {string} opts.word - word in CSS source that caused the warning
* @param {number} opts.index - index in CSS node string that caused
* the warning
* @param {string} opts.plugin - name of the plugin that created
* this warning. {@link Result#warn} fills
* this property automatically.
*
* @return {Warning} created warning
*/
;
_proto.warn = function warn(text, opts) {
if (opts === void 0) {
opts = {};
}
if (!opts.plugin) {
if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
opts.plugin = this.lastPlugin.postcssPlugin;
}
}
var warning = new Warning(text, opts);
this.messages.push(warning);
return warning;
}
/**
* Returns warnings from plugins. Filters {@link Warning} instances
* from {@link Result#messages}.
*
* @example
* result.warnings().forEach(warn => {
* console.warn(warn.toString());
* });
*
* @return {Warning[]} warnings from plugins
*/
;
_proto.warnings = function warnings() {
return this.messages.filter(function (i) {
return i.type === 'warning';
});
}
/**
* An alias for the {@link Result#css} property.
* Use it with syntaxes that generate non-CSS output.
* @type {string}
*
* @example
* result.css === result.content;
*/
;
_createClass(Result, [{
key: "content",
get: function get() {
return this.css;
}
}]);
return Result;
}();
function isPromise(obj) {
return typeof obj === 'object' && typeof obj.then === 'function';
}
/**
* @callback onFulfilled
* @param {Result} result
*/
/**
* @callback onRejected
* @param {Error} error
*/
/**
* A Promise proxy for the result of PostCSS transformations.
*
* A `LazyResult` instance is returned by {@link Processor#process}.
*
* @example
* const lazy = postcss([cssnext]).process(css);
*/
var LazyResult = /*#__PURE__*/function () {
function LazyResult(processor, css, opts) {
this.stringified = false;
this.processed = false;
var root;
if (typeof css === 'object' && css.type === 'root') {
root = css;
} else if (css instanceof LazyResult || css instanceof Result) {
root = css.root;
if (css.map) {
if (typeof opts.map === 'undefined') opts.map = {};
if (!opts.map.inline) opts.map.inline = false;
opts.map.prev = css.map;
}
} else {
var parser = parse;
if (opts.syntax) parser = opts.syntax.parse;
if (opts.parser) parser = opts.parser;
if (parser.parse) parser = parser.parse;
try {
root = parser(css, opts);
} catch (error) {
this.error = error;
}
}
this.result = new Result(processor, root, opts);
}
/**
* Returns a {@link Processor} instance, which will be used
* for CSS transformations.
* @type {Processor}
*/
var _proto = LazyResult.prototype;
/**
* Processes input CSS through synchronous plugins
* and calls {@link Result#warnings()}.
*
* @return {Warning[]} warnings from plugins
*/
_proto.warnings = function warnings() {
return this.sync().warnings();
}
/**
* Alias for the {@link LazyResult#css} property.
*
* @example
* lazy + '' === lazy.css;
*
* @return {string} output CSS
*/
;
_proto.toString = function toString() {
return this.css;
}
/**
* Processes input CSS through synchronous and asynchronous plugins
* and calls `onFulfilled` with a Result instance. If a plugin throws
* an error, the `onRejected` callback will be executed.
*
* It implements standard Promise API.
*
* @param {onFulfilled} onFulfilled - callback will be executed
* when all plugins will finish work
* @param {onRejected} onRejected - callback will be execited on any error
*
* @return {Promise} Promise API to make queue
*
* @example
* postcss([cssnext]).process(css).then(result => {
* console.log(result.css);
* });
*/
;
_proto.then = function then(onFulfilled, onRejected) {
return this.async().then(onFulfilled, onRejected);
}
/**
* Processes input CSS through synchronous and asynchronous plugins
* and calls onRejected for each error thrown in any plugin.
*
* It implements standard Promise API.
*
* @param {onRejected} onRejected - callback will be execited on any error
*
* @return {Promise} Promise API to make queue
*
* @example
* postcss([cssnext]).process(css).then(result => {
* console.log(result.css);
* }).catch(error => {
* console.error(error);
* });
*/
;
_proto["catch"] = function _catch(onRejected) {
return this.async()["catch"](onRejected);
};
_proto.handleError = function handleError(error, plugin) {
try {
this.error = error;
if (error.name === 'CssSyntaxError' && !error.plugin) {
error.plugin = plugin.postcssPlugin;
error.setMessage();
} else if (plugin.postcssVersion) {
var pluginName = plugin.postcssPlugin;
var pluginVer = plugin.postcssVersion;
var runtimeVer = this.result.processor.version;
var a = pluginVer.split('.');
var b = runtimeVer.split('.');
if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) {
warnOnce("" + ('Your current PostCSS version ' + 'is ') + runtimeVer + ", but " + pluginName + " " + ("uses " + pluginVer + ". Perhaps this is ") + "the source of the error below.");
}
}
} catch (err) {
if (console && console.error) console.error(err);
}
};
_proto.asyncTick = function asyncTick(resolve, reject) {
var _this = this;
if (this.plugin >= this.processor.plugins.length) {
this.processed = true;
return resolve();
}
try {
var plugin = this.processor.plugins[this.plugin];
var promise = this.run(plugin);
this.plugin += 1;
if (isPromise(promise)) {
promise.then(function () {
_this.asyncTick(resolve, reject);
})["catch"](function (error) {
_this.handleError(error, plugin);
_this.processed = true;
reject(error);
});
} else {
this.asyncTick(resolve, reject);
}
} catch (error) {
this.processed = true;
reject(error);
}
};
_proto.async = function async() {
var _this2 = this;
if (this.processed) {
return new Promise(function (resolve, reject) {
if (_this2.error) {
reject(_this2.error);
} else {
resolve(_this2.stringify());
}
});
}
if (this.processing) {
return this.processing;
}
this.processing = new Promise(function (resolve, reject) {
if (_this2.error) return reject(_this2.error);
_this2.plugin = 0;
_this2.asyncTick(resolve, reject);
}).then(function () {
_this2.processed = true;
return _this2.stringify();
});
return this.processing;
};
_proto.sync = function sync() {
var _this3 = this;
if (this.processed) return this.result;
this.processed = true;
if (this.processing) {
throw new Error('Use process(css).then(cb) to work with async plugins');
}
if (this.error) throw this.error;
this.result.processor.plugins.forEach(function (plugin) {
var promise = _this3.run(plugin);
if (isPromise(promise)) {
throw new Error('Use process(css).then(cb) to work with async plugins');
}
});
return this.result;
};
_proto.run = function run(plugin) {
this.result.lastPlugin = plugin;
try {
return plugin(this.result.root, this.result);
} catch (error) {
this.handleError(error, plugin);
throw error;
}
};
_proto.stringify = function stringify$1() {
if (this.stringified) return this.result;
this.stringified = true;
this.sync();
var opts = this.result.opts;
var str = stringify;
if (opts.syntax) str = opts.syntax.stringify;
if (opts.stringifier) str = opts.stringifier;
if (str.stringify) str = str.stringify;
var result = '';
str(this.root, function (i) {
result += i;
});
this.result.css = result;
return this.result;
};
_createClass(LazyResult, [{
key: "processor",
get: function get() {
return this.result.processor;
}
/**
* Options from the {@link Processor#process} call.
* @type {processOptions}
*/
}, {
key: "opts",
get: function get() {
return this.result.opts;
}
/**
* Processes input CSS through synchronous plugins, converts `Root`
* to a CSS string and returns {@link Result#css}.
*
* This property will only work with synchronous plugins.
* If the processor contains any asynchronous plugins
* it will throw an error. This is why this method is only
* for debug purpose, you should always use {@link LazyResult#then}.
*
* @type {string}
* @see Result#css
*/
}, {
key: "css",
get: function get() {
return this.stringify().css;
}
/**
* An alias for the `css` property. Use it with syntaxes
* that generate non-CSS output.
*
* This property will only work with synchronous plugins.
* If the processor contains any asynchronous plugins
* it will throw an error. This is why this method is only
* for debug purpose, you should always use {@link LazyResult#then}.
*
* @type {string}
* @see Result#content
*/
}, {
key: "content",
get: function get() {
return this.stringify().content;
}
/**
* Processes input CSS through synchronous plugins
* and returns {@link Result#map}.
*
* This property will only work with synchronous plugins.
* If the processor contains any asynchronous plugins
* it will throw an error. This is why this method is only
* for debug purpose, you should always use {@link LazyResult#then}.
*
* @type {SourceMapGenerator}
* @see Result#map
*/
}, {
key: "map",
get: function get() {
return this.stringify().map;
}
/**
* Processes input CSS through synchronous plugins
* and returns {@link Result#root}.
*
* This property will only work with synchronous plugins. If the processor
* contains any asynchronous plugins it will throw an error.
*
* This is why this method is only for debug purpose,
* you should always use {@link LazyResult#then}.
*
* @type {Root}
* @see Result#root
*/
}, {
key: "root",
get: function get() {
return this.sync().root;
}
/**
* Processes input CSS through synchronous plugins
* and returns {@link Result#messages}.
*
* This property will only work with synchronous plugins. If the processor
* contains any asynchronous plugins it will throw an error.
*
* This is why this method is only for debug purpose,
* you should always use {@link LazyResult#then}.
*
* @type {Message[]}
* @see Result#messages
*/
}, {
key: "messages",
get: function get() {
return this.sync().messages;
}
}]);
return LazyResult;
}();
//
/**
* @callback builder
* @param {string} part - part of generated CSS connected to this node
* @param {Node} node - AST node
* @param {"start"|"end"} [type] - node’s part type
*/
/**
* @callback parser
*
* @param {string|toString} css - string with input CSS or any object
* with toString() method, like a Buffer
* @param {processOptions} [opts] - options with only `from` and `map` keys
*
* @return {Root} PostCSS AST
*/
/**
* @callback stringifier
*
* @param {Node} node - start node for stringifing. Usually {@link Root}.
* @param {builder} builder - function to concatenate CSS from node’s parts
* or generate string and source map
*
* @return {void}
*/
/**
* @typedef {object} syntax
* @property {parser} parse - function to generate AST by string
* @property {stringifier} stringify - function to generate string by AST
*/
/**
* @typedef {object} toString
* @property {function} toString
*/
/**
* @callback pluginFunction
* @param {Root} root - parsed input CSS
* @param {Result} result - result to set warnings or check other plugins
*/
/**
* @typedef {object} Plugin
* @property {function} postcss - PostCSS plugin function
*/
/**
* @typedef {object} processOptions
* @property {string} from - the path of the CSS source file.
* You should always set `from`,
* because it is used in source map
* generation and syntax error messages.
* @property {string} to - the path where you’ll put the output
* CSS file. You should always set `to`
* to generate correct source maps.
* @property {parser} parser - function to generate AST by string
* @property {stringifier} stringifier - class to generate string by AST
* @property {syntax} syntax - object with `parse` and `stringify`
* @property {object} map - source map options
* @property {boolean} map.inline - does source map should
* be embedded in the output
* CSS as a base64-encoded
* comment
* @property {string|object|false|function} map.prev - source map content
* from a previous
* processing step
* (for example, Sass).
* PostCSS will try to find
* previous map
* automatically, so you
* could disable it by
* `false` value.
* @property {boolean} map.sourcesContent - does PostCSS should set
* the origin content to map
* @property {string|false} map.annotation - does PostCSS should set
* annotation comment to map
* @property {string} map.from - override `from` in map’s
* `sources`
*/
/**
* Contains plugins to process CSS. Create one `Processor` instance,
* initialize its plugins, and then use that instance on numerous CSS files.
*
* @example
* const processor = postcss([autoprefixer, precss]);
* processor.process(css1).then(result => console.log(result.css));
* processor.process(css2).then(result => console.log(result.css));
*/
var Processor = /*#__PURE__*/function () {
/**
* @param {Array.<Plugin|pluginFunction>|Processor} plugins - PostCSS
* plugins. See {@link Processor#use} for plugin format.
*/
function Processor(plugins) {
if (plugins === void 0) {
plugins = [];
}
/**
* @member {string} - Current PostCSS version.
*
* @example
* if ( result.processor.version.split('.')[0] !== '5' ) {
* throw new Error('This plugin works only with PostCSS 5');
* }
*/
this.version = '5.2.0';
/**
* @member {pluginFunction[]} - Plugins added to this processor.
*
* @example
* const processor = postcss([autoprefixer, precss]);
* processor.plugins.length //=> 2
*/
this.plugins = this.normalize(plugins);
}
/**
* Adds a plugin to be used as a CSS processor.
*
* PostCSS plugin can be in 4 formats:
* * A plugin created by {@link postcss.plugin} method.
* * A function. PostCSS will pass the function a @{link Root}
* as the first argument and current {@link Result} instance
* as the second.
* * An object with a `postcss` method. PostCSS will use that method
* as described in #2.
* * Another {@link Processor} instance. PostCSS will copy plugins
* from that instance into this one.
*
* Plugins can also be added by passing them as arguments when creating
* a `postcss` instance (see [`postcss(plugins)`]).
*
* Asynchronous plugins should return a `Promise` instance.
*
* @param {Plugin|pluginFunction|Processor} plugin - PostCSS plugin
* or {@link Processor}
* with plugins
*
* @example
* const processor = postcss()
* .use(autoprefixer)
* .use(precss);
*
* @return {Processes} current processor to make methods chain
*/
var _proto = Processor.prototype;
_proto.use = function use(plugin) {
this.plugins = this.plugins.concat(this.normalize([plugin]));
return this;
}
/**
* Parses source CSS and returns a {@link LazyResult} Promise proxy.
* Because some plugins can be asynchronous it doesn’t make
* any transformations. Transformations will be applied
* in the {@link LazyResult} methods.
*
* @param {string|toString|Result} css - String with input CSS or
* any object with a `toString()`
* method, like a Buffer.
* Optionally, send a {@link Result}
* instance and the processor will
* take the {@link Root} from it.
* @param {processOptions} [opts] - options
*
* @return {LazyResult} Promise proxy
*
* @example
* processor.process(css, { from: 'a.css', to: 'a.out.css' })
* .then(result => {
* console.log(result.css);
* });
*/
;
_proto.process = function process(css, opts) {
if (opts === void 0) {
opts = {};
}
return new LazyResult(this, css, opts);
};
_proto.normalize = function normalize(plugins) {
var normalized = [];
plugins.forEach(function (i) {
if (i.postcss) i = i.postcss;
if (typeof i === 'object' && Array.isArray(i.plugins)) {
normalized = normalized.concat(i.plugins);
} else if (typeof i === 'function') {
normalized.push(i);
} else {
throw new Error(i + " is not a PostCSS plugin");
}
});
return normalized;
};
return Processor;
}();
/**
* Represents a CSS file and contains all its parsed nodes.
*
* @extends Container
*
* @example
* const root = postcss.parse('a{color:black} b{z-index:2}');
* root.type //=> 'root'
* root.nodes.length //=> 2
*/
var Root = /*#__PURE__*/function (_Container) {
_inheritsLoose(Root, _Container);
function Root(defaults) {
var _this;
_this = _Container.call(this, defaults) || this;
_this.type = 'root';
if (!_this.nodes) _this.nodes = [];
return _this;
}
var _proto = Root.prototype;
_proto.removeChild = function removeChild(child) {
child = this.index(child);
if (child === 0 && this.nodes.length > 1) {
this.nodes[1].raws.before = this.nodes[child].raws.before;
}
return _Container.prototype.removeChild.call(this, child);
};
_proto.normalize = function normalize(child, sample, type) {
var nodes = _Container.prototype.normalize.call(this, child);
if (sample) {
if (type === 'prepend') {
if (this.nodes.length > 1) {
sample.raws.before = this.nodes[1].raws.before;
} else {
delete sample.raws.before;
}
} else if (this.first !== sample) {
nodes.forEach(function (node) {
node.raws.before = sample.raws.before;
});
}
}
return nodes;
}
/**
* Returns a {@link Result} instance representing the root’s CSS.
*
* @param {processOptions} [opts] - options with only `to` and `map` keys
*
* @return {Result} result with current root’s CSS
*
* @example
* const root1 = postcss.parse(css1, { from: 'a.css' });
* const root2 = postcss.parse(css2, { from: 'b.css' });
* root1.append(root2);
* const result = root1.toResult({ to: 'all.css', map: true });
*/
;
_proto.toResult = function toResult(opts) {
if (opts === void 0) {
opts = {};
}
var lazy = new LazyResult(new Processor(), this, opts);
return lazy.stringify();
};
_proto.remove = function remove(child) {
warnOnce('Root#remove is deprecated. Use Root#removeChild');
this.removeChild(child);
};
_proto.prevMap = function prevMap() {
warnOnce('Root#prevMap is deprecated. Use Root#source.input.map');
return this.source.input.map;
}
/**
* @memberof Root#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `after`: the space symbols after the last child to the end of file.
* * `semicolon`: is the last child has an (optional) semicolon.
*
* @example
* postcss.parse('a {}\n').raws //=> { after: '\n' }
* postcss.parse('a {}').raws //=> { after: '' }
*/
;
return Root;
}(Container);
var sequence = 0;
/**
* @typedef {object} filePosition
* @property {string} file - path to file
* @property {number} line - source line in file
* @property {number} column - source column in file
*/
/**
* Represents the source CSS.
*
* @example
* const root = postcss.parse(css, { from: file });
* const input = root.source.input;
*/
var Input = /*#__PURE__*/function () {
/**
* @param {string} css - input CSS source
* @param {object} [opts] - {@link Processor#process} options
*/
function Input(css, opts) {
if (opts === void 0) {
opts = {};
}
/**
* @member {string} - input CSS source
*
* @example
* const input = postcss.parse('a{}', { from: file }).input;
* input.css //=> "a{}";
*/
this.css = css.toString();
if (this.css[0] === "\uFEFF" || this.css[0] === "\uFFFE") {
this.css = this.css.slice(1);
}
if (opts.from) {
if (/^\w+:\/\//.test(opts.from)) {
/**
* @member {string} - The absolute path to the CSS source file
* defined with the `from` option.
*
* @example
* const root = postcss.parse(css, { from: 'a.css' });
* root.source.input.file //=> '/home/ai/a.css'
*/
this.file = opts.from;
} else {
this.file = path.resolve(opts.from);
}
}
/*
let map = new PreviousMap(this.css, opts);
if ( map.text ) {
/!**
* @member {PreviousMap} - The input source map passed from
* a compilation step before PostCSS
* (for example, from Sass compiler).
*
* @example
* root.source.input.map.consumer().sources //=> ['a.sass']
*!/
this.map = map;
let file = map.consumer().file;
if ( !this.file && file ) this.file = this.mapResolve(file);
}
*/
if (!this.file) {
sequence += 1;
/**
* @member {string} - The unique ID of the CSS source. It will be
* created if `from` option is not provided
* (because PostCSS does not know the file path).
*
* @example
* const root = postcss.parse(css);
* root.source.input.file //=> undefined
* root.source.input.id //=> "<input css 1>"
*/
this.id = "<input css " + sequence + ">";
}
if (this.map) this.map.file = this.from;
}
var _proto = Input.prototype;
_proto.error = function error(message, line, column, opts) {
if (opts === void 0) {
opts = {};
}
var result;
var origin = this.origin(line, column);
if (origin) {
result = new CssSyntaxError(message, origin.line, origin.column, origin.source, origin.file, opts.plugin);
} else {
result = new CssSyntaxError(message, line, column, this.css, this.file, opts.plugin);
}
result.input = {
line: line,
column: column,
source: this.css
};
if (this.file) result.input.file = this.file;
return result;
}
/**
* Reads the input source map and returns a symbol position
* in the input source (e.g., in a Sass file that was compiled
* to CSS before being passed to PostCSS).
*
* @param {number} line - line in input CSS
* @param {number} column - column in input CSS
*
* @return {filePosition} position in input source
*
* @example
* root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 }
*/
;
_proto.origin = function origin(line, column) {
if (!this.map) return false;
var consumer = this.map.consumer();
var from = consumer.originalPositionFor({
line: line,
column: column
});
if (!from.source) return false;
var result = {
file: this.mapResolve(from.source),
line: from.line,
column: from.column
};
var source = consumer.sourceContentFor(from.source);
if (source) result.source = source;
return result;
};
_proto.mapResolve = function mapResolve(file) {
if (/^\w+:\/\//.test(file)) {
return file;
} else {
return path.resolve(this.map.consumer().sourceRoot || '.', file);
}
}
/**
* The CSS source identifier. Contains {@link Input#file} if the user
* set the `from` option, or {@link Input#id} if they did not.
* @type {string}
*
* @example
* const root = postcss.parse(css, { from: 'a.css' });
* root.source.input.from //=> "/home/ai/a.css"
*
* const root = postcss.parse(css);
* root.source.input.from //=> "<input css 1>"
*/
;
_createClass(Input, [{
key: "from",
get: function get() {
return this.file || this.id;
}
}]);
return Input;
}();
var SafeParser = /*#__PURE__*/function (_Parser) {
_inheritsLoose(SafeParser, _Parser);
function SafeParser() {
return _Parser.apply(this, arguments) || this;
}
var _proto = SafeParser.prototype;
_proto.tokenize = function tokenize$1() {
this.tokens = tokenize(this.input, {
ignoreErrors: true
});
};
_proto.comment = function comment(token) {
var node = new Comment();
this.init(node, token[2], token[3]);
node.source.end = {
line: token[4],
column: token[5]
};
var text = token[1].slice(2);
if (text.slice(-2) === '*/') text = text.slice(0, -2);
if (/^\s*$/.test(text)) {
node.text = '';
node.raws.left = text;
node.raws.right = '';
} else {
var match = text.match(/^(\s*)([^]*[^\s])(\s*)$/);
node.text = match[2];
node.raws.left = match[1];
node.raws.right = match[3];
}
};
_proto.unclosedBracket = function unclosedBracket() {};
_proto.unknownWord = function unknownWord(start) {
var buffer = this.tokens.slice(start, this.pos + 1);
this.spaces += buffer.map(function (i) {
return i[1];
}).join('');
};
_proto.unexpectedClose = function unexpectedClose() {
this.current.raws.after += '}';
};
_proto.doubleColon = function doubleColon() {};
_proto.unnamedAtrule = function unnamedAtrule(node) {
node.name = '';
};
_proto.precheckMissedSemicolon = function precheckMissedSemicolon(tokens) {
var colon = this.colon(tokens);
if (colon === false) return;
var split;
for (split = colon - 1; split >= 0; split--) {
if (tokens[split][0] === 'word') break;
}
for (split -= 1; split >= 0; split--) {
if (tokens[split][0] !== 'space') {
split += 1;
break;
}
}
var other = tokens.splice(split, tokens.length - split);
this.decl(other);
};
_proto.checkMissedSemicolon = function checkMissedSemicolon() {};
_proto.endFile = function endFile() {
if (this.current.nodes && this.current.nodes.length) {
this.current.raws.semicolon = this.semicolon;
}
this.current.raws.after = (this.current.raws.after || '') + this.spaces;
while (this.current.parent) {
this.current = this.current.parent;
this.current.raws.after = '';
}
};
return SafeParser;
}(Parser);
//
function safeParse(css, opts) {
var input = new Input(css, opts);
var parser = new SafeParser(input);
parser.tokenize();
parser.loop();
return parser.root;
}
//
var generated = {};
/*
InlineStyle takes arbitrary CSS and generates a flat object
*/
var _InlineStyle = (function (styleSheet) {
var InlineStyle = /*#__PURE__*/function () {
function InlineStyle(rules) {
this.rules = rules;
}
var _proto = InlineStyle.prototype;
_proto.generateStyleObject = function generateStyleObject(executionContext) {
var flatCSS = flatten(this.rules, executionContext).join('');
var hash = generateComponentId(flatCSS);
if (!generated[hash]) {
var root = safeParse(flatCSS);
var declPairs = [];
root.each(function (node) {
if (node.type === 'decl') {
declPairs.push([node.prop, node.value]);
} else if (process.env.NODE_ENV !== 'production' && node.type !== 'comment') {
/* eslint-disable no-console */
console.warn("Node of type " + node.type + " not supported as an inline style");
}
}); // RN currently does not support differing values for the corner radii of Image
// components (but does for View). It is almost impossible to tell whether we'll have
// support, so we'll just disable multiple values here.
// https://github.com/styled-components/css-to-react-native/issues/11
var styleObject = transformDeclPairs(declPairs, ['borderRadius', 'borderWidth', 'borderColor', 'borderStyle']);
var styles = styleSheet.create({
generated: styleObject
});
generated[hash] = styles.generated;
}
return generated[hash];
};
return InlineStyle;
}();
return InlineStyle;
});
/* eslint-disable */
/**
mixin-deep; https://github.com/jonschlinkert/mixin-deep
Inlined such that it will be consistently transpiled to an IE-compatible syntax.
The MIT License (MIT)
Copyright (c) 2014-present, Jon Schlinkert.
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 isObject = function isObject(val) {
return typeof val === 'function' || typeof val === 'object' && val !== null && !Array.isArray(val);
};
var isValidKey = function isValidKey(key) {
return key !== '__proto__' && key !== 'constructor' && key !== 'prototype';
};
function mixin(target, val, key) {
var obj = target[key];
if (isObject(val) && isObject(obj)) {
mixinDeep(obj, val);
} else {
target[key] = val;
}
}
function mixinDeep(target) {
for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
rest[_key - 1] = arguments[_key];
}
for (var _i = 0, _rest = rest; _i < _rest.length; _i++) {
var obj = _rest[_i];
if (isObject(obj)) {
for (var key in obj) {
if (isValidKey(key)) {
mixin(target, obj[key], key);
}
}
}
}
return target;
}
//
var determineTheme = (function (props, providedTheme, defaultProps) {
if (defaultProps === void 0) {
defaultProps = EMPTY_OBJECT;
}
return props.theme !== defaultProps.theme && props.theme || providedTheme || defaultProps.theme;
});
//
function isTag(target) {
return typeof target === 'string' && (process.env.NODE_ENV !== 'production' ? target.charAt(0) === target.charAt(0).toLowerCase() : true);
}
//
function generateDisplayName(target) {
return isTag(target) ? "styled." + target : "Styled(" + getComponentName(target) + ")";
}
var ThemeContext = React.createContext();
var ThemeConsumer = ThemeContext.Consumer;
function mergeTheme(theme, outerTheme) {
if (!theme) {
return throwStyledComponentsError(14);
}
if (isFunction(theme)) {
var mergedTheme = theme(outerTheme);
if (process.env.NODE_ENV !== 'production' && (mergedTheme === null || Array.isArray(mergedTheme) || typeof mergedTheme !== 'object')) {
return throwStyledComponentsError(7);
}
return mergedTheme;
}
if (Array.isArray(theme) || typeof theme !== 'object') {
return throwStyledComponentsError(8);
}
return outerTheme ? _extends({}, outerTheme, {}, theme) : theme;
}
/**
* Provide a theme to an entire react component tree via context
*/
function ThemeProvider(props) {
var outerTheme = useContext(ThemeContext);
var themeContext = useMemo(function () {
return mergeTheme(props.theme, outerTheme);
}, [props.theme, outerTheme]);
if (!props.children) {
return null;
}
return /*#__PURE__*/React.createElement(ThemeContext.Provider, {
value: themeContext
}, props.children);
}
// if the user makes use of ThemeProvider or StyleSheetManager things will break.
// Validator defaults to true if not in HTML/DOM env
var validAttr = function validAttr() {
return true;
};
var StyledNativeComponent = /*#__PURE__*/function (_Component) {
_inheritsLoose(StyledNativeComponent, _Component);
function StyledNativeComponent() {
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.attrs = {};
return _this;
}
var _proto = StyledNativeComponent.prototype;
_proto.render = function render() {
var _this2 = this;
return /*#__PURE__*/React.createElement(ThemeConsumer, null, function (theme) {
var _this2$props = _this2.props,
transientAsProp = _this2$props.$as,
renderAs = _this2$props.as,
forwardedComponent = _this2$props.forwardedComponent,
forwardedAs = _this2$props.forwardedAs,
forwardedRef = _this2$props.forwardedRef,
testID = _this2$props.testID,
_this2$props$style = _this2$props.style,
style = _this2$props$style === void 0 ? [] : _this2$props$style,
props = _objectWithoutPropertiesLoose(_this2$props, ["$as", "as", "forwardedComponent", "forwardedAs", "forwardedRef", "testID", "style"]);
var defaultProps = forwardedComponent.defaultProps,
target = forwardedComponent.target,
shouldForwardProp = forwardedComponent.shouldForwardProp;
var elementToBeRendered = _this2.attrs.$as || _this2.attrs.as || transientAsProp || renderAs || target;
var generatedStyles = _this2.generateAndInjectStyles(determineTheme(_this2.props, theme, defaultProps) || EMPTY_OBJECT, _this2.props);
var isTargetTag = isTag(elementToBeRendered);
var computedProps = _this2.attrs !== props ? _extends({}, props, {}, _this2.attrs) : props;
var propFilterFn = shouldForwardProp || isTargetTag && validAttr;
var propsForElement = {};
var key;
for (key in computedProps) {
if (key[0] === '$' || key === 'as') continue;else if (key === 'forwardedAs') {
propsForElement.as = props[key];
} else if (!propFilterFn || propFilterFn(key, validAttr)) {
// Don't pass through filtered tags through to native elements
propsForElement[key] = computedProps[key];
}
}
propsForElement.style = typeof style === 'function' ? function (state) {
return [generatedStyles].concat(style(state));
} : [generatedStyles].concat(style);
propsForElement.testID = testID;
if (forwardedRef) propsForElement.ref = forwardedRef;
if (forwardedAs) propsForElement.as = forwardedAs;
return createElement(elementToBeRendered, propsForElement);
});
};
_proto.buildExecutionContext = function buildExecutionContext(theme, props, attrs) {
var _this3 = this;
var context = _extends({}, props, {
theme: theme
});
if (!attrs.length) return context;
this.attrs = {};
attrs.forEach(function (attrDef) {
var resolvedAttrDef = attrDef;
var attr;
var key;
if (isFunction(resolvedAttrDef)) {
resolvedAttrDef = resolvedAttrDef(context);
}
/* eslint-disable guard-for-in */
for (key in resolvedAttrDef) {
attr = resolvedAttrDef[key];
_this3.attrs[key] = attr;
context[key] = attr;
}
/* eslint-enable */
});
return context;
};
_proto.generateAndInjectStyles = function generateAndInjectStyles(theme, props) {
var inlineStyle = props.forwardedComponent.inlineStyle;
var executionContext = this.buildExecutionContext(theme, props, props.forwardedComponent.attrs);
return inlineStyle.generateStyleObject(executionContext);
};
_proto.setNativeProps = function setNativeProps(nativeProps) {
if (this.root !== undefined) {
// $FlowFixMe
this.root.setNativeProps(nativeProps);
} else if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line no-console
console.warn('setNativeProps was called on a Styled Component wrapping a stateless functional component.');
}
};
return StyledNativeComponent;
}(Component);
var _StyledNativeComponent = (function (InlineStyle) {
var createStyledNativeComponent = function createStyledNativeComponent(target, options, rules) {
var _options$attrs = options.attrs,
attrs = _options$attrs === void 0 ? EMPTY_ARRAY : _options$attrs,
_options$displayName = options.displayName,
displayName = _options$displayName === void 0 ? generateDisplayName(target) : _options$displayName,
_options$ParentCompon = options.ParentComponent,
ParentComponent = _options$ParentCompon === void 0 ? StyledNativeComponent : _options$ParentCompon;
var isClass = !isTag(target);
var isTargetStyledComp = isStyledComponent(target); // $FlowFixMe
var WrappedStyledNativeComponent = React.forwardRef(function (props, ref) {
return /*#__PURE__*/React.createElement(ParentComponent, _extends({}, props, {
forwardedComponent: WrappedStyledNativeComponent,
forwardedRef: ref
}));
});
var finalAttrs = // $FlowFixMe
isTargetStyledComp && target.attrs ? Array.prototype.concat(target.attrs, attrs).filter(Boolean) : attrs; // eslint-disable-next-line prefer-destructuring
var shouldForwardProp = options.shouldForwardProp; // $FlowFixMe
if (isTargetStyledComp && target.shouldForwardProp) {
if (shouldForwardProp) {
// compose nested shouldForwardProp calls
shouldForwardProp = function shouldForwardProp(prop, filterFn, elementToBeCreated) {
return (// $FlowFixMe
target.shouldForwardProp(prop, filterFn, elementToBeCreated) && options.shouldForwardProp(prop, filterFn, elementToBeCreated)
);
};
} else {
// eslint-disable-next-line prefer-destructuring
shouldForwardProp = target.shouldForwardProp;
}
}
/**
* forwardRef creates a new interim component, which we'll take advantage of
* instead of extending ParentComponent to create _another_ interim class
*/
// $FlowFixMe
WrappedStyledNativeComponent.attrs = finalAttrs;
WrappedStyledNativeComponent.displayName = displayName; // $FlowFixMe
WrappedStyledNativeComponent.shouldForwardProp = shouldForwardProp; // $FlowFixMe
WrappedStyledNativeComponent.inlineStyle = new InlineStyle( // $FlowFixMe
isTargetStyledComp ? target.inlineStyle.rules.concat(rules) : rules); // $FlowFixMe
WrappedStyledNativeComponent.styledComponentId = 'StyledNativeComponent'; // $FlowFixMe
WrappedStyledNativeComponent.target = isTargetStyledComp ? // $FlowFixMe
target.target : target; // $FlowFixMe
WrappedStyledNativeComponent.withComponent = function withComponent(tag) {
var _ = options.displayName,
__ = options.componentId,
optionsToCopy = _objectWithoutPropertiesLoose(options, ["displayName", "componentId"]);
var newOptions = _extends({}, optionsToCopy, {
attrs: finalAttrs,
ParentComponent: ParentComponent
});
return createStyledNativeComponent(tag, newOptions, rules);
}; // $FlowFixMe
Object.defineProperty(WrappedStyledNativeComponent, 'defaultProps', {
get: function get() {
return this._foldedDefaultProps;
},
set: function set(obj) {
// $FlowFixMe
this._foldedDefaultProps = isTargetStyledComp ? mixinDeep({}, target.defaultProps, obj) : obj;
}
});
if (isClass) {
hoist(WrappedStyledNativeComponent, target, {
// all SC-specific things should not be hoisted
attrs: true,
displayName: true,
shouldForwardProp: true,
inlineStyle: true,
styledComponentId: true,
target: true,
withComponent: true
});
}
return WrappedStyledNativeComponent;
};
return createStyledNativeComponent;
});
//
var interleave = (function (strings, interpolations) {
var result = [strings[0]];
for (var i = 0, len = interpolations.length; i < len; i += 1) {
result.push(interpolations[i], strings[i + 1]);
}
return result;
});
//
/**
* Used when flattening object styles to determine if we should
* expand an array of styles.
*/
var addTag = function addTag(arg) {
if (Array.isArray(arg)) {
// eslint-disable-next-line no-param-reassign
arg.isCss = true;
}
return arg;
};
function css(styles) {
for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
interpolations[_key - 1] = arguments[_key];
}
if (isFunction(styles) || isPlainObject(styles)) {
// $FlowFixMe
return addTag(flatten(interleave(EMPTY_ARRAY, [styles].concat(interpolations))));
}
if (interpolations.length === 0 && styles.length === 1 && typeof styles[0] === 'string') {
// $FlowFixMe
return styles;
} // $FlowFixMe
return addTag(flatten(interleave(styles, interpolations)));
}
function constructWithOptions(componentConstructor, tag, options) {
if (options === void 0) {
options = EMPTY_OBJECT;
}
if (!isValidElementType(tag)) {
return throwStyledComponentsError(1, String(tag));
}
/* This is callable directly as a template function */
// $FlowFixMe: Not typed to avoid destructuring arguments
var templateFunction = function templateFunction() {
return componentConstructor(tag, options, css.apply(void 0, arguments));
};
/* If config methods are called, wrap up a new template function and merge options */
templateFunction.withConfig = function (config) {
return constructWithOptions(componentConstructor, tag, _extends({}, options, {}, config));
};
/* Modify/inject new props at runtime */
templateFunction.attrs = function (attrs) {
return constructWithOptions(componentConstructor, tag, _extends({}, options, {
attrs: Array.prototype.concat(options.attrs, attrs).filter(Boolean)
}));
};
return templateFunction;
}
// export default <Config: { theme?: any }, Instance>(
// Component: AbstractComponent<Config, Instance>
// ): AbstractComponent<$Diff<Config, { theme?: any }> & { theme?: any }, Instance>
//
// but the old build system tooling doesn't support the syntax
var withTheme = (function (Component) {
// $FlowFixMe This should be React.forwardRef<Config, Instance>
var WithTheme = React.forwardRef(function (props, ref) {
var theme = useContext(ThemeContext); // $FlowFixMe defaultProps isn't declared so it can be inferrable
var defaultProps = Component.defaultProps;
var themeProp = determineTheme(props, theme, defaultProps);
if (process.env.NODE_ENV !== 'production' && themeProp === undefined) {
// eslint-disable-next-line no-console
console.warn("[withTheme] You are not using a ThemeProvider nor passing a theme prop or a theme in defaultProps in component class \"" + getComponentName(Component) + "\"");
}
return /*#__PURE__*/React.createElement(Component, _extends({}, props, {
theme: themeProp,
ref: ref
}));
});
hoist(WithTheme, Component);
WithTheme.displayName = "WithTheme(" + getComponentName(Component) + ")";
return WithTheme;
});
//
var useTheme = function useTheme() {
return useContext(ThemeContext);
};
//
var reactNative = require('react-native');
var InlineStyle = _InlineStyle(reactNative.StyleSheet);
var StyledNativeComponent$1 = _StyledNativeComponent(InlineStyle);
var styled = function styled(tag) {
return constructWithOptions(StyledNativeComponent$1, tag);
};
/* React native lazy-requires each of these modules for some reason, so let's
* assume it's for a good reason and not eagerly load them all */
var aliases = "ActivityIndicator ActivityIndicatorIOS ART Button DatePickerIOS DrawerLayoutAndroid\n Image ImageBackground ImageEditor ImageStore KeyboardAvoidingView ListView MapView Modal NavigatorIOS\n Picker PickerIOS ProgressBarAndroid ProgressViewIOS ScrollView SegmentedControlIOS Slider\n SliderIOS SnapshotViewIOS Switch RecyclerViewBackedScrollView RefreshControl SafeAreaView StatusBar\n SwipeableListView SwitchAndroid SwitchIOS TabBarIOS Text TextInput ToastAndroid ToolbarAndroid\n Touchable TouchableHighlight TouchableNativeFeedback TouchableOpacity TouchableWithoutFeedback\n View ViewPagerAndroid WebView FlatList SectionList VirtualizedList Pressable";
/* Define a getter for each alias which simply gets the reactNative component
* and passes it to styled */
aliases.split(/\s+/m).forEach(function (alias) {
return Object.defineProperty(styled, alias, {
enumerable: true,
configurable: false,
get: function get() {
return styled(reactNative[alias]);
}
});
});
export default styled;
export { ThemeConsumer, ThemeContext, ThemeProvider, css, isStyledComponent, useTheme, withTheme };
//# sourceMappingURL=styled-components.native.esm.js.map
webpack://frontend-mybets/../../node_modules/@styled-system/core/dist/index.esm.js
import assign from 'object-assign';
export var merge = function merge(a, b) {
var result = assign({}, a, b);
for (var key in a) {
var _assign;
if (!a[key] || typeof b[key] !== 'object') continue;
assign(result, (_assign = {}, _assign[key] = assign(a[key], b[key]), _assign));
}
return result;
}; // sort object-value responsive styles
var sort = function sort(obj) {
var next = {};
Object.keys(obj).sort(function (a, b) {
return a.localeCompare(b, undefined, {
numeric: true,
sensitivity: 'base'
});
}).forEach(function (key) {
next[key] = obj[key];
});
return next;
};
var defaults = {
breakpoints: [40, 52, 64].map(function (n) {
return n + 'em';
})
};
var createMediaQuery = function createMediaQuery(n) {
return "@media screen and (min-width: " + n + ")";
};
var getValue = function getValue(n, scale) {
return get(scale, n, n);
};
export var get = function get(obj, key, def, p, undef) {
key = key && key.split ? key.split('.') : [key];
for (p = 0; p < key.length; p++) {
obj = obj ? obj[key[p]] : undef;
}
return obj === undef ? def : obj;
};
export var createParser = function createParser(config) {
var cache = {};
var parse = function parse(props) {
var styles = {};
var shouldSort = false;
var isCacheDisabled = props.theme && props.theme.disableStyledSystemCache;
for (var key in props) {
if (!config[key]) continue;
var sx = config[key];
var raw = props[key];
var scale = get(props.theme, sx.scale, sx.defaults);
if (typeof raw === 'object') {
cache.breakpoints = !isCacheDisabled && cache.breakpoints || get(props.theme, 'breakpoints', defaults.breakpoints);
if (Array.isArray(raw)) {
cache.media = !isCacheDisabled && cache.media || [null].concat(cache.breakpoints.map(createMediaQuery));
styles = merge(styles, parseResponsiveStyle(cache.media, sx, scale, raw, props));
continue;
}
if (raw !== null) {
styles = merge(styles, parseResponsiveObject(cache.breakpoints, sx, scale, raw, props));
shouldSort = true;
}
continue;
}
assign(styles, sx(raw, scale, props));
} // sort object-based responsive styles
if (shouldSort) {
styles = sort(styles);
}
return styles;
};
parse.config = config;
parse.propNames = Object.keys(config);
parse.cache = cache;
var keys = Object.keys(config).filter(function (k) {
return k !== 'config';
});
if (keys.length > 1) {
keys.forEach(function (key) {
var _createParser;
parse[key] = createParser((_createParser = {}, _createParser[key] = config[key], _createParser));
});
}
return parse;
};
var parseResponsiveStyle = function parseResponsiveStyle(mediaQueries, sx, scale, raw, _props) {
var styles = {};
raw.slice(0, mediaQueries.length).forEach(function (value, i) {
var media = mediaQueries[i];
var style = sx(value, scale, _props);
if (!media) {
assign(styles, style);
} else {
var _assign2;
assign(styles, (_assign2 = {}, _assign2[media] = assign({}, styles[media], style), _assign2));
}
});
return styles;
};
var parseResponsiveObject = function parseResponsiveObject(breakpoints, sx, scale, raw, _props) {
var styles = {};
for (var key in raw) {
var breakpoint = breakpoints[key];
var value = raw[key];
var style = sx(value, scale, _props);
if (!breakpoint) {
assign(styles, style);
} else {
var _assign3;
var media = createMediaQuery(breakpoint);
assign(styles, (_assign3 = {}, _assign3[media] = assign({}, styles[media], style), _assign3));
}
}
return styles;
};
export var createStyleFunction = function createStyleFunction(_ref) {
var properties = _ref.properties,
property = _ref.property,
scale = _ref.scale,
_ref$transform = _ref.transform,
transform = _ref$transform === void 0 ? getValue : _ref$transform,
defaultScale = _ref.defaultScale;
properties = properties || [property];
var sx = function sx(value, scale, _props) {
var result = {};
var n = transform(value, scale, _props);
if (n === null) return;
properties.forEach(function (prop) {
result[prop] = n;
});
return result;
};
sx.scale = scale;
sx.defaults = defaultScale;
return sx;
}; // new v5 API
export var system = function system(args) {
if (args === void 0) {
args = {};
}
var config = {};
Object.keys(args).forEach(function (key) {
var conf = args[key];
if (conf === true) {
// shortcut definition
config[key] = createStyleFunction({
property: key,
scale: key
});
return;
}
if (typeof conf === 'function') {
config[key] = conf;
return;
}
config[key] = createStyleFunction(conf);
});
var parser = createParser(config);
return parser;
};
export var compose = function compose() {
var config = {};
for (var _len = arguments.length, parsers = new Array(_len), _key = 0; _key < _len; _key++) {
parsers[_key] = arguments[_key];
}
parsers.forEach(function (parser) {
if (!parser || !parser.config) return;
assign(config, parser.config);
});
var parser = createParser(config);
return parser;
};
webpack://frontend-mybets/../../node_modules/@styled-system/layout/dist/index.esm.js
import { system, get } from '@styled-system/core';
var isNumber = function isNumber(n) {
return typeof n === 'number' && !isNaN(n);
};
var getWidth = function getWidth(n, scale) {
return get(scale, n, !isNumber(n) || n > 1 ? n : n * 100 + '%');
};
var config = {
width: {
property: 'width',
scale: 'sizes',
transform: getWidth
},
height: {
property: 'height',
scale: 'sizes'
},
minWidth: {
property: 'minWidth',
scale: 'sizes'
},
minHeight: {
property: 'minHeight',
scale: 'sizes'
},
maxWidth: {
property: 'maxWidth',
scale: 'sizes'
},
maxHeight: {
property: 'maxHeight',
scale: 'sizes'
},
size: {
properties: ['width', 'height'],
scale: 'sizes'
},
overflow: true,
overflowX: true,
overflowY: true,
display: true,
verticalAlign: true
};
export var layout = system(config);
export default layout;
webpack://frontend-mybets/../../node_modules/@styled-system/color/dist/index.esm.js
import { system } from '@styled-system/core';
var config = {
color: {
property: 'color',
scale: 'colors'
},
backgroundColor: {
property: 'backgroundColor',
scale: 'colors'
},
opacity: true
};
config.bg = config.backgroundColor;
export var color = system(config);
export default color;
webpack://frontend-mybets/../../node_modules/@styled-system/typography/dist/index.esm.js
import { system } from '@styled-system/core';
var defaults = {
fontSizes: [12, 14, 16, 20, 24, 32, 48, 64, 72]
};
var config = {
fontFamily: {
property: 'fontFamily',
scale: 'fonts'
},
fontSize: {
property: 'fontSize',
scale: 'fontSizes',
defaultScale: defaults.fontSizes
},
fontWeight: {
property: 'fontWeight',
scale: 'fontWeights'
},
lineHeight: {
property: 'lineHeight',
scale: 'lineHeights'
},
letterSpacing: {
property: 'letterSpacing',
scale: 'letterSpacings'
},
textAlign: true,
fontStyle: true
};
export var typography = system(config);
export default typography;
webpack://frontend-mybets/../../node_modules/@styled-system/flexbox/dist/index.esm.js
import { system } from '@styled-system/core';
var config = {
alignItems: true,
alignContent: true,
justifyItems: true,
justifyContent: true,
flexWrap: true,
flexDirection: true,
// item
flex: true,
flexGrow: true,
flexShrink: true,
flexBasis: true,
justifySelf: true,
alignSelf: true,
order: true
};
export var flexbox = system(config);
export default flexbox;
webpack://frontend-mybets/../../node_modules/@styled-system/grid/dist/index.esm.js
import { system } from '@styled-system/core';
var defaults = {
space: [0, 4, 8, 16, 32, 64, 128, 256, 512]
};
var config = {
gridGap: {
property: 'gridGap',
scale: 'space',
defaultScale: defaults.space
},
gridColumnGap: {
property: 'gridColumnGap',
scale: 'space',
defaultScale: defaults.space
},
gridRowGap: {
property: 'gridRowGap',
scale: 'space',
defaultScale: defaults.space
},
gridColumn: true,
gridRow: true,
gridAutoFlow: true,
gridAutoColumns: true,
gridAutoRows: true,
gridTemplateColumns: true,
gridTemplateRows: true,
gridTemplateAreas: true,
gridArea: true
};
export var grid = system(config);
export default grid;
webpack://frontend-mybets/../../node_modules/@styled-system/border/dist/index.esm.js
import { system } from '@styled-system/core';
var config = {
border: {
property: 'border',
scale: 'borders'
},
borderWidth: {
property: 'borderWidth',
scale: 'borderWidths'
},
borderStyle: {
property: 'borderStyle',
scale: 'borderStyles'
},
borderColor: {
property: 'borderColor',
scale: 'colors'
},
borderRadius: {
property: 'borderRadius',
scale: 'radii'
},
borderTop: {
property: 'borderTop',
scale: 'borders'
},
borderTopLeftRadius: {
property: 'borderTopLeftRadius',
scale: 'radii'
},
borderTopRightRadius: {
property: 'borderTopRightRadius',
scale: 'radii'
},
borderRight: {
property: 'borderRight',
scale: 'borders'
},
borderBottom: {
property: 'borderBottom',
scale: 'borders'
},
borderBottomLeftRadius: {
property: 'borderBottomLeftRadius',
scale: 'radii'
},
borderBottomRightRadius: {
property: 'borderBottomRightRadius',
scale: 'radii'
},
borderLeft: {
property: 'borderLeft',
scale: 'borders'
},
borderX: {
properties: ['borderLeft', 'borderRight'],
scale: 'borders'
},
borderY: {
properties: ['borderTop', 'borderBottom'],
scale: 'borders'
}
};
config.borderTopWidth = {
property: 'borderTopWidth',
scale: 'borderWidths'
};
config.borderTopColor = {
property: 'borderTopColor',
scale: 'colors'
};
config.borderTopStyle = {
property: 'borderTopStyle',
scale: 'borderStyles'
};
config.borderTopLeftRadius = {
property: 'borderTopLeftRadius',
scale: 'radii'
};
config.borderTopRightRadius = {
property: 'borderTopRightRadius',
scale: 'radii'
};
config.borderBottomWidth = {
property: 'borderBottomWidth',
scale: 'borderWidths'
};
config.borderBottomColor = {
property: 'borderBottomColor',
scale: 'colors'
};
config.borderBottomStyle = {
property: 'borderBottomStyle',
scale: 'borderStyles'
};
config.borderBottomLeftRadius = {
property: 'borderBottomLeftRadius',
scale: 'radii'
};
config.borderBottomRightRadius = {
property: 'borderBottomRightRadius',
scale: 'radii'
};
config.borderLeftWidth = {
property: 'borderLeftWidth',
scale: 'borderWidths'
};
config.borderLeftColor = {
property: 'borderLeftColor',
scale: 'colors'
};
config.borderLeftStyle = {
property: 'borderLeftStyle',
scale: 'borderStyles'
};
config.borderRightWidth = {
property: 'borderRightWidth',
scale: 'borderWidths'
};
config.borderRightColor = {
property: 'borderRightColor',
scale: 'colors'
};
config.borderRightStyle = {
property: 'borderRightStyle',
scale: 'borderStyles'
};
export var border = system(config);
export default border;
webpack://frontend-mybets/../../node_modules/@styled-system/background/dist/index.esm.js
import { system } from '@styled-system/core';
var config = {
background: true,
backgroundImage: true,
backgroundSize: true,
backgroundPosition: true,
backgroundRepeat: true
};
config.bgImage = config.backgroundImage;
config.bgSize = config.backgroundSize;
config.bgPosition = config.backgroundPosition;
config.bgRepeat = config.backgroundRepeat;
export var background = system(config);
export default background;
webpack://frontend-mybets/../../node_modules/@styled-system/position/dist/index.esm.js
import { system } from '@styled-system/core';
var defaults = {
space: [0, 4, 8, 16, 32, 64, 128, 256, 512]
};
var config = {
position: true,
zIndex: {
property: 'zIndex',
scale: 'zIndices'
},
top: {
property: 'top',
scale: 'space',
defaultScale: defaults.space
},
right: {
property: 'right',
scale: 'space',
defaultScale: defaults.space
},
bottom: {
property: 'bottom',
scale: 'space',
defaultScale: defaults.space
},
left: {
property: 'left',
scale: 'space',
defaultScale: defaults.space
}
};
export var position = system(config);
export default position;
webpack://frontend-mybets/../../node_modules/@styled-system/space/dist/index.esm.js
import { get, system, compose } from '@styled-system/core';
var defaults = {
space: [0, 4, 8, 16, 32, 64, 128, 256, 512]
};
var isNumber = function isNumber(n) {
return typeof n === 'number' && !isNaN(n);
};
var getMargin = function getMargin(n, scale) {
if (!isNumber(n)) {
return get(scale, n, n);
}
var isNegative = n < 0;
var absolute = Math.abs(n);
var value = get(scale, absolute, absolute);
if (!isNumber(value)) {
return isNegative ? '-' + value : value;
}
return value * (isNegative ? -1 : 1);
};
var configs = {};
configs.margin = {
margin: {
property: 'margin',
scale: 'space',
transform: getMargin,
defaultScale: defaults.space
},
marginTop: {
property: 'marginTop',
scale: 'space',
transform: getMargin,
defaultScale: defaults.space
},
marginRight: {
property: 'marginRight',
scale: 'space',
transform: getMargin,
defaultScale: defaults.space
},
marginBottom: {
property: 'marginBottom',
scale: 'space',
transform: getMargin,
defaultScale: defaults.space
},
marginLeft: {
property: 'marginLeft',
scale: 'space',
transform: getMargin,
defaultScale: defaults.space
},
marginX: {
properties: ['marginLeft', 'marginRight'],
scale: 'space',
transform: getMargin,
defaultScale: defaults.space
},
marginY: {
properties: ['marginTop', 'marginBottom'],
scale: 'space',
transform: getMargin,
defaultScale: defaults.space
}
};
configs.margin.m = configs.margin.margin;
configs.margin.mt = configs.margin.marginTop;
configs.margin.mr = configs.margin.marginRight;
configs.margin.mb = configs.margin.marginBottom;
configs.margin.ml = configs.margin.marginLeft;
configs.margin.mx = configs.margin.marginX;
configs.margin.my = configs.margin.marginY;
configs.padding = {
padding: {
property: 'padding',
scale: 'space',
defaultScale: defaults.space
},
paddingTop: {
property: 'paddingTop',
scale: 'space',
defaultScale: defaults.space
},
paddingRight: {
property: 'paddingRight',
scale: 'space',
defaultScale: defaults.space
},
paddingBottom: {
property: 'paddingBottom',
scale: 'space',
defaultScale: defaults.space
},
paddingLeft: {
property: 'paddingLeft',
scale: 'space',
defaultScale: defaults.space
},
paddingX: {
properties: ['paddingLeft', 'paddingRight'],
scale: 'space',
defaultScale: defaults.space
},
paddingY: {
properties: ['paddingTop', 'paddingBottom'],
scale: 'space',
defaultScale: defaults.space
}
};
configs.padding.p = configs.padding.padding;
configs.padding.pt = configs.padding.paddingTop;
configs.padding.pr = configs.padding.paddingRight;
configs.padding.pb = configs.padding.paddingBottom;
configs.padding.pl = configs.padding.paddingLeft;
configs.padding.px = configs.padding.paddingX;
configs.padding.py = configs.padding.paddingY;
export var margin = system(configs.margin);
export var padding = system(configs.padding);
export var space = compose(margin, padding);
export default space;
webpack://frontend-mybets/../../node_modules/@styled-system/shadow/dist/index.esm.js
import { system } from '@styled-system/core';
export var shadow = system({
boxShadow: {
property: 'boxShadow',
scale: 'shadows'
},
textShadow: {
property: 'textShadow',
scale: 'shadows'
}
});
export default shadow;
webpack://frontend-mybets/../../node_modules/@styled-system/css/dist/index.esm.js
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); }
// based on https://github.com/developit/dlv
export var get = function get(obj, key, def, p, undef) {
key = key && key.split ? key.split('.') : [key];
for (p = 0; p < key.length; p++) {
obj = obj ? obj[key[p]] : undef;
}
return obj === undef ? def : obj;
};
var defaultBreakpoints = [40, 52, 64].map(function (n) {
return n + 'em';
});
var defaultTheme = {
space: [0, 4, 8, 16, 32, 64, 128, 256, 512],
fontSizes: [12, 14, 16, 20, 24, 32, 48, 64, 72]
};
var aliases = {
bg: 'backgroundColor',
m: 'margin',
mt: 'marginTop',
mr: 'marginRight',
mb: 'marginBottom',
ml: 'marginLeft',
mx: 'marginX',
my: 'marginY',
p: 'padding',
pt: 'paddingTop',
pr: 'paddingRight',
pb: 'paddingBottom',
pl: 'paddingLeft',
px: 'paddingX',
py: 'paddingY'
};
var multiples = {
marginX: ['marginLeft', 'marginRight'],
marginY: ['marginTop', 'marginBottom'],
paddingX: ['paddingLeft', 'paddingRight'],
paddingY: ['paddingTop', 'paddingBottom'],
size: ['width', 'height']
};
var scales = {
color: 'colors',
backgroundColor: 'colors',
borderColor: 'colors',
margin: 'space',
marginTop: 'space',
marginRight: 'space',
marginBottom: 'space',
marginLeft: 'space',
marginX: 'space',
marginY: 'space',
padding: 'space',
paddingTop: 'space',
paddingRight: 'space',
paddingBottom: 'space',
paddingLeft: 'space',
paddingX: 'space',
paddingY: 'space',
top: 'space',
right: 'space',
bottom: 'space',
left: 'space',
gridGap: 'space',
gridColumnGap: 'space',
gridRowGap: 'space',
gap: 'space',
columnGap: 'space',
rowGap: 'space',
fontFamily: 'fonts',
fontSize: 'fontSizes',
fontWeight: 'fontWeights',
lineHeight: 'lineHeights',
letterSpacing: 'letterSpacings',
border: 'borders',
borderTop: 'borders',
borderRight: 'borders',
borderBottom: 'borders',
borderLeft: 'borders',
borderWidth: 'borderWidths',
borderStyle: 'borderStyles',
borderRadius: 'radii',
borderTopRightRadius: 'radii',
borderTopLeftRadius: 'radii',
borderBottomRightRadius: 'radii',
borderBottomLeftRadius: 'radii',
borderTopWidth: 'borderWidths',
borderTopColor: 'colors',
borderTopStyle: 'borderStyles',
borderBottomWidth: 'borderWidths',
borderBottomColor: 'colors',
borderBottomStyle: 'borderStyles',
borderLeftWidth: 'borderWidths',
borderLeftColor: 'colors',
borderLeftStyle: 'borderStyles',
borderRightWidth: 'borderWidths',
borderRightColor: 'colors',
borderRightStyle: 'borderStyles',
outlineColor: 'colors',
boxShadow: 'shadows',
textShadow: 'shadows',
zIndex: 'zIndices',
width: 'sizes',
minWidth: 'sizes',
maxWidth: 'sizes',
height: 'sizes',
minHeight: 'sizes',
maxHeight: 'sizes',
flexBasis: 'sizes',
size: 'sizes',
// svg
fill: 'colors',
stroke: 'colors'
};
var positiveOrNegative = function positiveOrNegative(scale, value) {
if (typeof value !== 'number' || value >= 0) {
return get(scale, value, value);
}
var absolute = Math.abs(value);
var n = get(scale, absolute, absolute);
if (typeof n === 'string') return '-' + n;
return n * -1;
};
var transforms = ['margin', 'marginTop', 'marginRight', 'marginBottom', 'marginLeft', 'marginX', 'marginY', 'top', 'bottom', 'left', 'right'].reduce(function (acc, curr) {
var _extends2;
return _extends({}, acc, (_extends2 = {}, _extends2[curr] = positiveOrNegative, _extends2));
}, {});
export var responsive = function responsive(styles) {
return function (theme) {
var next = {};
var breakpoints = get(theme, 'breakpoints', defaultBreakpoints);
var mediaQueries = [null].concat(breakpoints.map(function (n) {
return "@media screen and (min-width: " + n + ")";
}));
for (var key in styles) {
var value = typeof styles[key] === 'function' ? styles[key](theme) : styles[key];
if (value == null) continue;
if (!Array.isArray(value)) {
next[key] = value;
continue;
}
for (var i = 0; i < value.slice(0, mediaQueries.length).length; i++) {
var media = mediaQueries[i];
if (!media) {
next[key] = value[i];
continue;
}
next[media] = next[media] || {};
if (value[i] == null) continue;
next[media][key] = value[i];
}
}
return next;
};
};
export var css = function css(args) {
return function (props) {
if (props === void 0) {
props = {};
}
var theme = _extends({}, defaultTheme, {}, props.theme || props);
var result = {};
var obj = typeof args === 'function' ? args(theme) : args;
var styles = responsive(obj)(theme);
for (var key in styles) {
var x = styles[key];
var val = typeof x === 'function' ? x(theme) : x;
if (key === 'variant') {
var variant = css(get(theme, val))(theme);
result = _extends({}, result, {}, variant);
continue;
}
if (val && typeof val === 'object') {
result[key] = css(val)(theme);
continue;
}
var prop = get(aliases, key, key);
var scaleName = get(scales, prop);
var scale = get(theme, scaleName, get(theme, prop, {}));
var transform = get(transforms, prop, get);
var value = transform(scale, val, val);
if (multiples[prop]) {
var dirs = multiples[prop];
for (var i = 0; i < dirs.length; i++) {
result[dirs[i]] = value;
}
} else {
result[prop] = value;
}
}
return result;
};
};
export default css;
webpack://frontend-mybets/../../node_modules/@styled-system/variant/dist/index.esm.js
import { get, createParser } from '@styled-system/core';
import css from '@styled-system/css';
export var variant = function variant(_ref) {
var _config;
var scale = _ref.scale,
_ref$prop = _ref.prop,
prop = _ref$prop === void 0 ? 'variant' : _ref$prop,
_ref$variants = _ref.variants,
variants = _ref$variants === void 0 ? {} : _ref$variants,
key = _ref.key;
var sx;
if (Object.keys(variants).length) {
sx = function sx(value, scale, props) {
return css(get(scale, value, null))(props.theme);
};
} else {
sx = function sx(value, scale) {
return get(scale, value, null);
};
}
sx.scale = scale || key;
sx.defaults = variants;
var config = (_config = {}, _config[prop] = sx, _config);
var parser = createParser(config);
return parser;
};
export default variant;
export var buttonStyle = variant({
key: 'buttons'
});
export var textStyle = variant({
key: 'textStyles',
prop: 'textStyle'
});
export var colorStyle = variant({
key: 'colorStyles',
prop: 'colors'
});
webpack://frontend-mybets/../../node_modules/styled-system/dist/index.esm.js
import { createStyleFunction, createParser } from '@styled-system/core'; // v4 api shims
import layout from '@styled-system/layout';
import color from '@styled-system/color';
import typography from '@styled-system/typography';
import flexbox from '@styled-system/flexbox';
import grid from '@styled-system/grid';
import border from '@styled-system/border';
import background from '@styled-system/background';
import position from '@styled-system/position';
export { get, createParser, createStyleFunction, compose, system } from '@styled-system/core';
export { margin, padding, space } from '@styled-system/space';
export { color } from '@styled-system/color';
export { layout } from '@styled-system/layout';
export { typography } from '@styled-system/typography';
export { flexbox } from '@styled-system/flexbox';
export { border } from '@styled-system/border';
export { background } from '@styled-system/background';
export { position } from '@styled-system/position';
export { grid } from '@styled-system/grid';
export { shadow } from '@styled-system/shadow';
export { default as boxShadow, default as textShadow } from '@styled-system/shadow';
export { variant, buttonStyle, textStyle, colorStyle } from '@styled-system/variant';
var width = layout.width,
height = layout.height,
minWidth = layout.minWidth,
minHeight = layout.minHeight,
maxWidth = layout.maxWidth,
maxHeight = layout.maxHeight,
size = layout.size,
verticalAlign = layout.verticalAlign,
display = layout.display,
overflow = layout.overflow,
overflowX = layout.overflowX,
overflowY = layout.overflowY;
var opacity = color.opacity;
var fontSize = typography.fontSize,
fontFamily = typography.fontFamily,
fontWeight = typography.fontWeight,
lineHeight = typography.lineHeight,
textAlign = typography.textAlign,
fontStyle = typography.fontStyle,
letterSpacing = typography.letterSpacing;
var alignItems = flexbox.alignItems,
alignContent = flexbox.alignContent,
justifyItems = flexbox.justifyItems,
justifyContent = flexbox.justifyContent,
flexWrap = flexbox.flexWrap,
flexDirection = flexbox.flexDirection,
flex = flexbox.flex,
flexGrow = flexbox.flexGrow,
flexShrink = flexbox.flexShrink,
flexBasis = flexbox.flexBasis,
justifySelf = flexbox.justifySelf,
alignSelf = flexbox.alignSelf,
order = flexbox.order;
var gridGap = grid.gridGap,
gridColumnGap = grid.gridColumnGap,
gridRowGap = grid.gridRowGap,
gridColumn = grid.gridColumn,
gridRow = grid.gridRow,
gridAutoFlow = grid.gridAutoFlow,
gridAutoColumns = grid.gridAutoColumns,
gridAutoRows = grid.gridAutoRows,
gridTemplateColumns = grid.gridTemplateColumns,
gridTemplateRows = grid.gridTemplateRows,
gridTemplateAreas = grid.gridTemplateAreas,
gridArea = grid.gridArea;
var borderWidth = border.borderWidth,
borderStyle = border.borderStyle,
borderColor = border.borderColor,
borderTop = border.borderTop,
borderRight = border.borderRight,
borderBottom = border.borderBottom,
borderLeft = border.borderLeft,
borderRadius = border.borderRadius;
var backgroundImage = background.backgroundImage,
backgroundSize = background.backgroundSize,
backgroundPosition = background.backgroundPosition,
backgroundRepeat = background.backgroundRepeat;
var zIndex = position.zIndex,
top = position.top,
right = position.right,
bottom = position.bottom,
left = position.left;
export { default as borders } from '@styled-system/border';
export { width, height, minWidth, minHeight, maxWidth, maxHeight, size, verticalAlign, display, overflow, overflowX, overflowY // color
, opacity // typography
, fontSize, fontFamily, fontWeight, lineHeight, textAlign, fontStyle, letterSpacing // flexbox
, alignItems, alignContent, justifyItems, justifyContent, flexWrap, flexDirection, flex, flexGrow, flexShrink, flexBasis, justifySelf, alignSelf, order // grid
, gridGap, gridColumnGap, gridRowGap, gridColumn, gridRow, gridAutoFlow, gridAutoColumns, gridAutoRows, gridTemplateColumns, gridTemplateRows, gridTemplateAreas, gridArea // border
, borderWidth, borderStyle, borderColor, borderTop, borderRight, borderBottom, borderLeft, borderRadius // background
, backgroundImage, backgroundSize, backgroundPosition, backgroundRepeat // position
, zIndex, top, right, bottom, left }; // v4 style API shim
export var style = function style(_ref) {
var prop = _ref.prop,
cssProperty = _ref.cssProperty,
alias = _ref.alias,
key = _ref.key,
transformValue = _ref.transformValue,
scale = _ref.scale,
properties = _ref.properties;
var config = {};
config[prop] = createStyleFunction({
properties: properties,
property: cssProperty || prop,
scale: key,
defaultScale: scale,
transform: transformValue
});
if (alias) config[alias] = config[prop];
var parse = createParser(config);
return parse;
};
webpack://frontend-mybets/../../node_modules/styleq/dist/styleq.js
/**
* 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.
*
*
*/
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.styleq = void 0;
var cache = new WeakMap();
var compiledKey = '$$css';
function createStyleq(options) {
var disableCache;
var disableMix;
var transform;
if (options != null) {
disableCache = options.disableCache === true;
disableMix = options.disableMix === true;
transform = options.transform;
}
return function styleq() {
// Keep track of property commits to the className
var definedProperties = []; // The className and inline style to build up
var className = '';
var inlineStyle = null; // The current position in the cache graph
var nextCache = disableCache ? null : cache; // This way of creating an array from arguments is fastest
var styles = new Array(arguments.length);
for (var i = 0; i < arguments.length; i++) {
styles[i] = arguments[i];
} // Iterate over styles from last to first
while (styles.length > 0) {
var possibleStyle = styles.pop(); // Skip empty items
if (possibleStyle == null || possibleStyle === false) {
continue;
} // Push nested styles back onto the stack to be processed
if (Array.isArray(possibleStyle)) {
for (var _i = 0; _i < possibleStyle.length; _i++) {
styles.push(possibleStyle[_i]);
}
continue;
} // Process an individual style object
var style = transform != null ? transform(possibleStyle) : possibleStyle;
if (style.$$css) {
// Build up the class names defined by this object
var classNameChunk = ''; // Check the cache to see if we've already done this work
if (nextCache != null && nextCache.has(style)) {
// Cache: read
var cacheEntry = nextCache.get(style);
if (cacheEntry != null) {
classNameChunk = cacheEntry[0]; // $FlowIgnore
definedProperties.push.apply(definedProperties, cacheEntry[1]);
nextCache = cacheEntry[2];
}
} // Update the chunks with data from this object
else {
// The properties defined by this object
var definedPropertiesChunk = [];
for (var prop in style) {
var value = style[prop];
if (prop === compiledKey) continue; // Each property value is used as an HTML class name
// { 'debug.string': 'debug.string', opacity: 's-jskmnoqp' }
if (typeof value === 'string' || value === null) {
// Only add to chunks if this property hasn't already been seen
if (!definedProperties.includes(prop)) {
definedProperties.push(prop);
if (nextCache != null) {
definedPropertiesChunk.push(prop);
}
if (typeof value === 'string') {
classNameChunk += classNameChunk ? ' ' + value : value;
}
}
} // If we encounter a value that isn't a string or `null`
else {
console.error("styleq: ".concat(prop, " typeof ").concat(String(value), " is not \"string\" or \"null\"."));
}
} // Cache: write
if (nextCache != null) {
// Create the next WeakMap for this sequence of styles
var weakMap = new WeakMap();
nextCache.set(style, [classNameChunk, definedPropertiesChunk, weakMap]);
nextCache = weakMap;
}
} // Order of classes in chunks matches property-iteration order of style
// object. Order of chunks matches passed order of styles from first to
// last (which we iterate over in reverse).
if (classNameChunk) {
className = className ? classNameChunk + ' ' + className : classNameChunk;
}
} // ----- DYNAMIC: Process inline style object -----
else {
if (disableMix) {
if (inlineStyle == null) {
inlineStyle = {};
}
inlineStyle = Object.assign({}, style, inlineStyle);
} else {
var subStyle = null;
for (var _prop in style) {
var _value = style[_prop];
if (_value !== undefined) {
if (!definedProperties.includes(_prop)) {
if (_value != null) {
if (inlineStyle == null) {
inlineStyle = {};
}
if (subStyle == null) {
subStyle = {};
}
subStyle[_prop] = _value;
}
definedProperties.push(_prop); // Cache is unnecessary overhead if results can't be reused.
nextCache = null;
}
}
}
if (subStyle != null) {
inlineStyle = Object.assign(subStyle, inlineStyle);
}
}
}
}
var styleProps = [className, inlineStyle];
return styleProps;
};
}
var styleq = createStyleq();
exports.styleq = styleq;
styleq.factory = createStyleq;
webpack://frontend-mybets/../../node_modules/styleq/dist/transform-localize-style.js
/**
* 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.
*/
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.localizeStyle = localizeStyle;
var cache = new WeakMap();
var markerProp = '$$css$localize';
/**
* The compiler polyfills logical properties and values, generating a class
* name for both writing directions. The style objects are annotated by
* the compiler as needing this runtime transform. The results are memoized.
*
* { '$$css$localize': true, float: [ 'float-left', 'float-right' ] }
* => { float: 'float-left' }
*/
function compileStyle(style, isRTL) {
// Create a new compiled style for styleq
var compiledStyle = {};
for (var prop in style) {
if (prop !== markerProp) {
var value = style[prop];
if (Array.isArray(value)) {
compiledStyle[prop] = isRTL ? value[1] : value[0];
} else {
compiledStyle[prop] = value;
}
}
}
return compiledStyle;
}
function localizeStyle(style, isRTL) {
if (style[markerProp] != null) {
var compiledStyleIndex = isRTL ? 1 : 0; // Check the cache in case we've already seen this object
if (cache.has(style)) {
var _cachedStyles = cache.get(style);
var _compiledStyle = _cachedStyles[compiledStyleIndex];
if (_compiledStyle == null) {
// Update the missing cache entry
_compiledStyle = compileStyle(style, isRTL);
_cachedStyles[compiledStyleIndex] = _compiledStyle;
cache.set(style, _cachedStyles);
}
return _compiledStyle;
} // Create a new compiled style for styleq
var compiledStyle = compileStyle(style, isRTL);
var cachedStyles = new Array(2);
cachedStyles[compiledStyleIndex] = compiledStyle;
cache.set(style, cachedStyles);
return compiledStyle;
}
return style;
}
webpack://frontend-mybets/../../node_modules/styleq/transform-localize-style.js
/**
* 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.
*/
module.exports = require('./dist/transform-localize-style');
webpack://frontend-mybets/../../node_modules/supports-color/browser.js
'use strict';
module.exports = {
stdout: false,
stderr: false
};
webpack://frontend-mybets/../../node_modules/uuid/dist/esm-browser/rng.js
// Unique ID creation requires a high quality random # generator. In the browser we therefore
// require the crypto API and do not support built-in fallback to lower quality random number
// generators (like Math.random()).
let getRandomValues;
const rnds8 = new Uint8Array(16);
export default function rng() {
// lazy load so that environments that need to polyfill have a chance to do so
if (!getRandomValues) {
// getRandomValues needs to be invoked in a context where "this" is a Crypto implementation.
getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
if (!getRandomValues) {
throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
}
}
return getRandomValues(rnds8);
}
webpack://frontend-mybets/../../node_modules/uuid/dist/esm-browser/stringify.js
import validate from './validate.js';
/**
* Convert array of 16 byte values to UUID string format of the form:
* XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
*/
const byteToHex = [];
for (let i = 0; i < 256; ++i) {
byteToHex.push((i + 0x100).toString(16).slice(1));
}
export function unsafeStringify(arr, offset = 0) {
// Note: Be careful editing this code! It's been tuned for performance
// and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
}
function stringify(arr, offset = 0) {
const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one
// of the following:
// - One or more input array values don't map to a hex octet (leading to
// "undefined" in the uuid)
// - Invalid input values for the RFC `version` or `variant` fields
if (!validate(uuid)) {
throw TypeError('Stringified UUID is invalid');
}
return uuid;
}
export default stringify;
webpack://frontend-mybets/../../node_modules/uuid/dist/esm-browser/native.js
const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);
export default {
randomUUID
};
webpack://frontend-mybets/../../node_modules/uuid/dist/esm-browser/v4.js
import native from './native.js';
import rng from './rng.js';
import { unsafeStringify } from './stringify.js';
function v4(options, buf, offset) {
if (native.randomUUID && !buf && !options) {
return native.randomUUID();
}
options = options || {};
const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
rnds[6] = rnds[6] & 0x0f | 0x40;
rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
if (buf) {
offset = offset || 0;
for (let i = 0; i < 16; ++i) {
buf[offset + i] = rnds[i];
}
return buf;
}
return unsafeStringify(rnds);
}
export default v4;
webpack://frontend-mybets/../../node_modules/react-native-web/node_modules/@babel/runtime/helpers/arrayLikeToArray.js
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;
}
module.exports = _arrayLikeToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
webpack://frontend-mybets/../../node_modules/react-native-web/node_modules/@babel/runtime/helpers/createForOfIteratorHelperLoose.js
var unsupportedIterableToArray = require("./unsupportedIterableToArray.js");
function _createForOfIteratorHelperLoose(o, allowArrayLike) {
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
if (it) return (it = it.call(o)).next.bind(it);
if (Array.isArray(o) || (it = unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
return function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
module.exports = _createForOfIteratorHelperLoose, module.exports.__esModule = true, module.exports["default"] = module.exports;
webpack://frontend-mybets/../../node_modules/react-native-web/node_modules/@babel/runtime/helpers/defineProperty.js
var toPropertyKey = require("./toPropertyKey.js");
function _defineProperty(obj, key, value) {
key = toPropertyKey(key);
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports;
webpack://frontend-mybets/../../node_modules/react-native-web/node_modules/@babel/runtime/helpers/extends.js
function _extends() {
module.exports = _extends = Object.assign ? Object.assign.bind() : 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;
}, module.exports.__esModule = true, module.exports["default"] = module.exports;
return _extends.apply(this, arguments);
}
module.exports = _extends, module.exports.__esModule = true, module.exports["default"] = module.exports;
webpack://frontend-mybets/../../node_modules/react-native-web/node_modules/@babel/runtime/helpers/interopRequireDefault.js
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
module.exports = _interopRequireDefault, module.exports.__esModule = true, module.exports["default"] = module.exports;
webpack://frontend-mybets/../../node_modules/react-native-web/node_modules/@babel/runtime/helpers/interopRequireWildcard.js
var _typeof = require("./typeof.js")["default"];
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") {
return {
"default": obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj["default"] = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
module.exports = _interopRequireWildcard, module.exports.__esModule = true, module.exports["default"] = module.exports;
webpack://frontend-mybets/../../node_modules/react-native-web/node_modules/@babel/runtime/helpers/objectSpread2.js
var defineProperty = require("./defineProperty.js");
function ownKeys(e, r) {
var t = Object.keys(e);
if (Object.getOwnPropertySymbols) {
var o = Object.getOwnPropertySymbols(e);
r && (o = o.filter(function (r) {
return Object.getOwnPropertyDescriptor(e, r).enumerable;
})), t.push.apply(t, o);
}
return t;
}
function _objectSpread2(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
defineProperty(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
module.exports = _objectSpread2, module.exports.__esModule = true, module.exports["default"] = module.exports;
webpack://frontend-mybets/../../node_modules/react-native-web/node_modules/@babel/runtime/helpers/objectWithoutPropertiesLoose.js
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;
}
module.exports = _objectWithoutPropertiesLoose, module.exports.__esModule = true, module.exports["default"] = module.exports;
webpack://frontend-mybets/../../node_modules/react-native-web/node_modules/@babel/runtime/helpers/toPrimitive.js
var _typeof = require("./typeof.js")["default"];
function _toPrimitive(input, hint) {
if (_typeof(input) !== "object" || input === null) return input;
var prim = input[Symbol.toPrimitive];
if (prim !== undefined) {
var res = prim.call(input, hint || "default");
if (_typeof(res) !== "object") return res;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return (hint === "string" ? String : Number)(input);
}
module.exports = _toPrimitive, module.exports.__esModule = true, module.exports["default"] = module.exports;
webpack://frontend-mybets/../../node_modules/react-native-web/node_modules/@babel/runtime/helpers/toPropertyKey.js
var _typeof = require("./typeof.js")["default"];
var toPrimitive = require("./toPrimitive.js");
function _toPropertyKey(arg) {
var key = toPrimitive(arg, "string");
return _typeof(key) === "symbol" ? key : String(key);
}
module.exports = _toPropertyKey, module.exports.__esModule = true, module.exports["default"] = module.exports;
webpack://frontend-mybets/../../node_modules/react-native-web/node_modules/@babel/runtime/helpers/typeof.js
function _typeof(o) {
"@babel/helpers - typeof";
return (module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
return typeof o;
} : function (o) {
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
}, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(o);
}
module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports;
webpack://frontend-mybets/../../node_modules/react-native-web/node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js
var arrayLikeToArray = require("./arrayLikeToArray.js");
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);
}
module.exports = _unsupportedIterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js
export default 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;
}
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js
export default function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
export default function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/classCallCheck.js
export default function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/createClass.js
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);
}
}
export default function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/defineProperty.js
export default 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;
}
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/extends.js
export default 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);
}
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js
export default function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/inherits.js
import setPrototypeOf from "./setPrototypeOf.js";
export default 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);
}
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/jsx.js
var REACT_ELEMENT_TYPE;
export default function _createRawReactElement(type, props, key, children) {
if (!REACT_ELEMENT_TYPE) {
REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol["for"] && Symbol["for"]("react.element") || 0xeac7;
}
var defaultProps = type && type.defaultProps;
var childrenLength = arguments.length - 3;
if (!props && childrenLength !== 0) {
props = {
children: void 0
};
}
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = new Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 3];
}
props.children = childArray;
}
if (props && defaultProps) {
for (var propName in defaultProps) {
if (props[propName] === void 0) {
props[propName] = defaultProps[propName];
}
}
} else if (!props) {
props = defaultProps || {};
}
return {
$$typeof: REACT_ELEMENT_TYPE,
type: type,
key: key === undefined ? null : "" + key,
ref: null,
props: props,
_owner: null
};
}
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js
import objectWithoutPropertiesLoose from "./objectWithoutPropertiesLoose.js";
export default 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;
}
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js
export default 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;
}
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js
import _typeof from "@babel/runtime/helpers/typeof";
import assertThisInitialized from "./assertThisInitialized.js";
export default function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return assertThisInitialized(self);
}
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js
export default function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/slicedToArray.js
import arrayWithHoles from "./arrayWithHoles.js";
import iterableToArrayLimit from "./iterableToArrayLimit.js";
import unsupportedIterableToArray from "./unsupportedIterableToArray.js";
import nonIterableRest from "./nonIterableRest.js";
export default function _slicedToArray(arr, i) {
return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();
}
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js
export default function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js
export default function _iterableToArrayLimit(arr, i) {
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
if (_i == null) return;
var _arr = [];
var _n = true;
var _d = false;
var _s, _e;
try {
for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/nonIterableRest.js
export default function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/toConsumableArray.js
import arrayWithoutHoles from "./arrayWithoutHoles.js";
import iterableToArray from "./iterableToArray.js";
import unsupportedIterableToArray from "./unsupportedIterableToArray.js";
import nonIterableSpread from "./nonIterableSpread.js";
export default function _toConsumableArray(arr) {
return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();
}
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js
import arrayLikeToArray from "./arrayLikeToArray.js";
export default function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return arrayLikeToArray(arr);
}
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/iterableToArray.js
export default function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js
export default 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.");
}
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/typeof.js
export default 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);
}
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js
import arrayLikeToArray from "./arrayLikeToArray.js";
export default 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);
}
webpack://frontend-mybets/../../node_modules/@react-spring/core/node_modules/@react-spring/rafz/dist/react-spring_rafz.modern.mjs
// src/index.ts
var updateQueue = makeQueue();
var raf = (fn) => schedule(fn, updateQueue);
var writeQueue = makeQueue();
raf.write = (fn) => schedule(fn, writeQueue);
var onStartQueue = makeQueue();
raf.onStart = (fn) => schedule(fn, onStartQueue);
var onFrameQueue = makeQueue();
raf.onFrame = (fn) => schedule(fn, onFrameQueue);
var onFinishQueue = makeQueue();
raf.onFinish = (fn) => schedule(fn, onFinishQueue);
var timeouts = [];
raf.setTimeout = (handler, ms) => {
const time = raf.now() + ms;
const cancel = () => {
const i = timeouts.findIndex((t) => t.cancel == cancel);
if (~i)
timeouts.splice(i, 1);
pendingCount -= ~i ? 1 : 0;
};
const timeout = { time, handler, cancel };
timeouts.splice(findTimeout(time), 0, timeout);
pendingCount += 1;
start();
return timeout;
};
var findTimeout = (time) => ~(~timeouts.findIndex((t) => t.time > time) || ~timeouts.length);
raf.cancel = (fn) => {
onStartQueue.delete(fn);
onFrameQueue.delete(fn);
onFinishQueue.delete(fn);
updateQueue.delete(fn);
writeQueue.delete(fn);
};
raf.sync = (fn) => {
sync = true;
raf.batchedUpdates(fn);
sync = false;
};
raf.throttle = (fn) => {
let lastArgs;
function queuedFn() {
try {
fn(...lastArgs);
} finally {
lastArgs = null;
}
}
function throttled(...args) {
lastArgs = args;
raf.onStart(queuedFn);
}
throttled.handler = fn;
throttled.cancel = () => {
onStartQueue.delete(queuedFn);
lastArgs = null;
};
return throttled;
};
var nativeRaf = typeof window != "undefined" ? window.requestAnimationFrame : (
// eslint-disable-next-line @typescript-eslint/no-empty-function
() => {
}
);
raf.use = (impl) => nativeRaf = impl;
raf.now = typeof performance != "undefined" ? () => performance.now() : Date.now;
raf.batchedUpdates = (fn) => fn();
raf.catch = console.error;
raf.frameLoop = "always";
raf.advance = () => {
if (raf.frameLoop !== "demand") {
console.warn(
"Cannot call the manual advancement of rafz whilst frameLoop is not set as demand"
);
} else {
update();
}
};
var ts = -1;
var pendingCount = 0;
var sync = false;
function schedule(fn, queue) {
if (sync) {
queue.delete(fn);
fn(0);
} else {
queue.add(fn);
start();
}
}
function start() {
if (ts < 0) {
ts = 0;
if (raf.frameLoop !== "demand") {
nativeRaf(loop);
}
}
}
function stop() {
ts = -1;
}
function loop() {
if (~ts) {
nativeRaf(loop);
raf.batchedUpdates(update);
}
}
function update() {
const prevTs = ts;
ts = raf.now();
const count = findTimeout(ts);
if (count) {
eachSafely(timeouts.splice(0, count), (t) => t.handler());
pendingCount -= count;
}
if (!pendingCount) {
stop();
return;
}
onStartQueue.flush();
updateQueue.flush(prevTs ? Math.min(64, ts - prevTs) : 16.667);
onFrameQueue.flush();
writeQueue.flush();
onFinishQueue.flush();
}
function makeQueue() {
let next = /* @__PURE__ */ new Set();
let current = next;
return {
add(fn) {
pendingCount += current == next && !next.has(fn) ? 1 : 0;
next.add(fn);
},
delete(fn) {
pendingCount -= current == next && next.has(fn) ? 1 : 0;
return next.delete(fn);
},
flush(arg) {
if (current.size) {
next = /* @__PURE__ */ new Set();
pendingCount -= current.size;
eachSafely(current, (fn) => fn(arg) && next.add(fn));
pendingCount += next.size;
current = next;
}
}
};
}
function eachSafely(values, each) {
values.forEach((value) => {
try {
each(value);
} catch (e) {
raf.catch(e);
}
});
}
var __raf = {
/** The number of pending tasks */
count() {
return pendingCount;
},
/** Whether there's a raf update loop running */
isRunning() {
return ts >= 0;
},
/** Clear internal state. Never call from update loop! */
clear() {
ts = -1;
timeouts = [];
onStartQueue = makeQueue();
updateQueue = makeQueue();
onFrameQueue = makeQueue();
writeQueue = makeQueue();
onFinishQueue = makeQueue();
pendingCount = 0;
}
};
export {
__raf,
raf
};
//# sourceMappingURL=react-spring_rafz.modern.mjs.map
webpack://frontend-mybets/../../node_modules/@react-spring/core/node_modules/@react-spring/shared/dist/react-spring_shared.modern.mjs
var __defProp = Object.defineProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
// src/globals.ts
var globals_exports = {};
__export(globals_exports, {
assign: () => assign,
colors: () => colors,
createStringInterpolator: () => createStringInterpolator,
skipAnimation: () => skipAnimation,
to: () => to,
willAdvance: () => willAdvance
});
import { raf } from "@react-spring/rafz";
// src/helpers.ts
function noop() {
}
var defineHidden = (obj, key, value) => Object.defineProperty(obj, key, { value, writable: true, configurable: true });
var is = {
arr: Array.isArray,
obj: (a) => !!a && a.constructor.name === "Object",
fun: (a) => typeof a === "function",
str: (a) => typeof a === "string",
num: (a) => typeof a === "number",
und: (a) => a === void 0
};
function isEqual(a, b) {
if (is.arr(a)) {
if (!is.arr(b) || a.length !== b.length)
return false;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i])
return false;
}
return true;
}
return a === b;
}
var each = (obj, fn) => obj.forEach(fn);
function eachProp(obj, fn, ctx) {
if (is.arr(obj)) {
for (let i = 0; i < obj.length; i++) {
fn.call(ctx, obj[i], `${i}`);
}
return;
}
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
fn.call(ctx, obj[key], key);
}
}
}
var toArray = (a) => is.und(a) ? [] : is.arr(a) ? a : [a];
function flush(queue, iterator) {
if (queue.size) {
const items = Array.from(queue);
queue.clear();
each(items, iterator);
}
}
var flushCalls = (queue, ...args) => flush(queue, (fn) => fn(...args));
var isSSR = () => typeof window === "undefined" || !window.navigator || /ServerSideRendering|^Deno\//.test(window.navigator.userAgent);
// src/globals.ts
var createStringInterpolator;
var to;
var colors = null;
var skipAnimation = false;
var willAdvance = noop;
var assign = (globals) => {
if (globals.to)
to = globals.to;
if (globals.now)
raf.now = globals.now;
if (globals.colors !== void 0)
colors = globals.colors;
if (globals.skipAnimation != null)
skipAnimation = globals.skipAnimation;
if (globals.createStringInterpolator)
createStringInterpolator = globals.createStringInterpolator;
if (globals.requestAnimationFrame)
raf.use(globals.requestAnimationFrame);
if (globals.batchedUpdates)
raf.batchedUpdates = globals.batchedUpdates;
if (globals.willAdvance)
willAdvance = globals.willAdvance;
if (globals.frameLoop)
raf.frameLoop = globals.frameLoop;
};
// src/FrameLoop.ts
import { raf as raf2 } from "@react-spring/rafz";
var startQueue = /* @__PURE__ */ new Set();
var currentFrame = [];
var prevFrame = [];
var priority = 0;
var frameLoop = {
get idle() {
return !startQueue.size && !currentFrame.length;
},
/** Advance the given animation on every frame until idle. */
start(animation) {
if (priority > animation.priority) {
startQueue.add(animation);
raf2.onStart(flushStartQueue);
} else {
startSafely(animation);
raf2(advance);
}
},
/** Advance all animations by the given time. */
advance,
/** Call this when an animation's priority changes. */
sort(animation) {
if (priority) {
raf2.onFrame(() => frameLoop.sort(animation));
} else {
const prevIndex = currentFrame.indexOf(animation);
if (~prevIndex) {
currentFrame.splice(prevIndex, 1);
startUnsafely(animation);
}
}
},
/**
* Clear all animations. For testing purposes.
*
* ☠️ Never call this from within the frameloop.
*/
clear() {
currentFrame = [];
startQueue.clear();
}
};
function flushStartQueue() {
startQueue.forEach(startSafely);
startQueue.clear();
raf2(advance);
}
function startSafely(animation) {
if (!currentFrame.includes(animation))
startUnsafely(animation);
}
function startUnsafely(animation) {
currentFrame.splice(
findIndex(currentFrame, (other) => other.priority > animation.priority),
0,
animation
);
}
function advance(dt) {
const nextFrame = prevFrame;
for (let i = 0; i < currentFrame.length; i++) {
const animation = currentFrame[i];
priority = animation.priority;
if (!animation.idle) {
willAdvance(animation);
animation.advance(dt);
if (!animation.idle) {
nextFrame.push(animation);
}
}
}
priority = 0;
prevFrame = currentFrame;
prevFrame.length = 0;
currentFrame = nextFrame;
return currentFrame.length > 0;
}
function findIndex(arr, test) {
const index = arr.findIndex(test);
return index < 0 ? arr.length : index;
}
// src/clamp.ts
var clamp = (min, max, v) => Math.min(Math.max(v, min), max);
// src/colors.ts
var colors2 = {
transparent: 0,
aliceblue: 4042850303,
antiquewhite: 4209760255,
aqua: 16777215,
aquamarine: 2147472639,
azure: 4043309055,
beige: 4126530815,
bisque: 4293182719,
black: 255,
blanchedalmond: 4293643775,
blue: 65535,
blueviolet: 2318131967,
brown: 2771004159,
burlywood: 3736635391,
burntsienna: 3934150143,
cadetblue: 1604231423,
chartreuse: 2147418367,
chocolate: 3530104575,
coral: 4286533887,
cornflowerblue: 1687547391,
cornsilk: 4294499583,
crimson: 3692313855,
cyan: 16777215,
darkblue: 35839,
darkcyan: 9145343,
darkgoldenrod: 3095792639,
darkgray: 2846468607,
darkgreen: 6553855,
darkgrey: 2846468607,
darkkhaki: 3182914559,
darkmagenta: 2332068863,
darkolivegreen: 1433087999,
darkorange: 4287365375,
darkorchid: 2570243327,
darkred: 2332033279,
darksalmon: 3918953215,
darkseagreen: 2411499519,
darkslateblue: 1211993087,
darkslategray: 793726975,
darkslategrey: 793726975,
darkturquoise: 13554175,
darkviolet: 2483082239,
deeppink: 4279538687,
deepskyblue: 12582911,
dimgray: 1768516095,
dimgrey: 1768516095,
dodgerblue: 512819199,
firebrick: 2988581631,
floralwhite: 4294635775,
forestgreen: 579543807,
fuchsia: 4278255615,
gainsboro: 3705462015,
ghostwhite: 4177068031,
gold: 4292280575,
goldenrod: 3668254975,
gray: 2155905279,
green: 8388863,
greenyellow: 2919182335,
grey: 2155905279,
honeydew: 4043305215,
hotpink: 4285117695,
indianred: 3445382399,
indigo: 1258324735,
ivory: 4294963455,
khaki: 4041641215,
lavender: 3873897215,
lavenderblush: 4293981695,
lawngreen: 2096890111,
lemonchiffon: 4294626815,
lightblue: 2916673279,
lightcoral: 4034953471,
lightcyan: 3774873599,
lightgoldenrodyellow: 4210742015,
lightgray: 3553874943,
lightgreen: 2431553791,
lightgrey: 3553874943,
lightpink: 4290167295,
lightsalmon: 4288707327,
lightseagreen: 548580095,
lightskyblue: 2278488831,
lightslategray: 2005441023,
lightslategrey: 2005441023,
lightsteelblue: 2965692159,
lightyellow: 4294959359,
lime: 16711935,
limegreen: 852308735,
linen: 4210091775,
magenta: 4278255615,
maroon: 2147483903,
mediumaquamarine: 1724754687,
mediumblue: 52735,
mediumorchid: 3126187007,
mediumpurple: 2473647103,
mediumseagreen: 1018393087,
mediumslateblue: 2070474495,
mediumspringgreen: 16423679,
mediumturquoise: 1221709055,
mediumvioletred: 3340076543,
midnightblue: 421097727,
mintcream: 4127193855,
mistyrose: 4293190143,
moccasin: 4293178879,
navajowhite: 4292783615,
navy: 33023,
oldlace: 4260751103,
olive: 2155872511,
olivedrab: 1804477439,
orange: 4289003775,
orangered: 4282712319,
orchid: 3664828159,
palegoldenrod: 4008225535,
palegreen: 2566625535,
paleturquoise: 2951671551,
palevioletred: 3681588223,
papayawhip: 4293907967,
peachpuff: 4292524543,
peru: 3448061951,
pink: 4290825215,
plum: 3718307327,
powderblue: 2967529215,
purple: 2147516671,
rebeccapurple: 1714657791,
red: 4278190335,
rosybrown: 3163525119,
royalblue: 1097458175,
saddlebrown: 2336560127,
salmon: 4202722047,
sandybrown: 4104413439,
seagreen: 780883967,
seashell: 4294307583,
sienna: 2689740287,
silver: 3233857791,
skyblue: 2278484991,
slateblue: 1784335871,
slategray: 1887473919,
slategrey: 1887473919,
snow: 4294638335,
springgreen: 16744447,
steelblue: 1182971135,
tan: 3535047935,
teal: 8421631,
thistle: 3636451583,
tomato: 4284696575,
turquoise: 1088475391,
violet: 4001558271,
wheat: 4125012991,
white: 4294967295,
whitesmoke: 4126537215,
yellow: 4294902015,
yellowgreen: 2597139199
};
// src/colorMatchers.ts
var NUMBER = "[-+]?\\d*\\.?\\d+";
var PERCENTAGE = NUMBER + "%";
function call(...parts) {
return "\\(\\s*(" + parts.join(")\\s*,\\s*(") + ")\\s*\\)";
}
var rgb = new RegExp("rgb" + call(NUMBER, NUMBER, NUMBER));
var rgba = new RegExp("rgba" + call(NUMBER, NUMBER, NUMBER, NUMBER));
var hsl = new RegExp("hsl" + call(NUMBER, PERCENTAGE, PERCENTAGE));
var hsla = new RegExp(
"hsla" + call(NUMBER, PERCENTAGE, PERCENTAGE, NUMBER)
);
var hex3 = /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/;
var hex4 = /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/;
var hex6 = /^#([0-9a-fA-F]{6})$/;
var hex8 = /^#([0-9a-fA-F]{8})$/;
// src/normalizeColor.ts
function normalizeColor(color) {
let match;
if (typeof color === "number") {
return color >>> 0 === color && color >= 0 && color <= 4294967295 ? color : null;
}
if (match = hex6.exec(color))
return parseInt(match[1] + "ff", 16) >>> 0;
if (colors && colors[color] !== void 0) {
return colors[color];
}
if (match = rgb.exec(color)) {
return (parse255(match[1]) << 24 | // r
parse255(match[2]) << 16 | // g
parse255(match[3]) << 8 | // b
255) >>> // a
0;
}
if (match = rgba.exec(color)) {
return (parse255(match[1]) << 24 | // r
parse255(match[2]) << 16 | // g
parse255(match[3]) << 8 | // b
parse1(match[4])) >>> // a
0;
}
if (match = hex3.exec(color)) {
return parseInt(
match[1] + match[1] + // r
match[2] + match[2] + // g
match[3] + match[3] + // b
"ff",
// a
16
) >>> 0;
}
if (match = hex8.exec(color))
return parseInt(match[1], 16) >>> 0;
if (match = hex4.exec(color)) {
return parseInt(
match[1] + match[1] + // r
match[2] + match[2] + // g
match[3] + match[3] + // b
match[4] + match[4],
// a
16
) >>> 0;
}
if (match = hsl.exec(color)) {
return (hslToRgb(
parse360(match[1]),
// h
parsePercentage(match[2]),
// s
parsePercentage(match[3])
// l
) | 255) >>> // a
0;
}
if (match = hsla.exec(color)) {
return (hslToRgb(
parse360(match[1]),
// h
parsePercentage(match[2]),
// s
parsePercentage(match[3])
// l
) | parse1(match[4])) >>> // a
0;
}
return null;
}
function hue2rgb(p, q, t) {
if (t < 0)
t += 1;
if (t > 1)
t -= 1;
if (t < 1 / 6)
return p + (q - p) * 6 * t;
if (t < 1 / 2)
return q;
if (t < 2 / 3)
return p + (q - p) * (2 / 3 - t) * 6;
return p;
}
function hslToRgb(h, s, l) {
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
const r = hue2rgb(p, q, h + 1 / 3);
const g = hue2rgb(p, q, h);
const b = hue2rgb(p, q, h - 1 / 3);
return Math.round(r * 255) << 24 | Math.round(g * 255) << 16 | Math.round(b * 255) << 8;
}
function parse255(str) {
const int = parseInt(str, 10);
if (int < 0)
return 0;
if (int > 255)
return 255;
return int;
}
function parse360(str) {
const int = parseFloat(str);
return (int % 360 + 360) % 360 / 360;
}
function parse1(str) {
const num = parseFloat(str);
if (num < 0)
return 0;
if (num > 1)
return 255;
return Math.round(num * 255);
}
function parsePercentage(str) {
const int = parseFloat(str);
if (int < 0)
return 0;
if (int > 100)
return 1;
return int / 100;
}
// src/colorToRgba.ts
function colorToRgba(input) {
let int32Color = normalizeColor(input);
if (int32Color === null)
return input;
int32Color = int32Color || 0;
const r = (int32Color & 4278190080) >>> 24;
const g = (int32Color & 16711680) >>> 16;
const b = (int32Color & 65280) >>> 8;
const a = (int32Color & 255) / 255;
return `rgba(${r}, ${g}, ${b}, ${a})`;
}
// src/createInterpolator.ts
var createInterpolator = (range, output, extrapolate) => {
if (is.fun(range)) {
return range;
}
if (is.arr(range)) {
return createInterpolator({
range,
output,
extrapolate
});
}
if (is.str(range.output[0])) {
return createStringInterpolator(range);
}
const config = range;
const outputRange = config.output;
const inputRange = config.range || [0, 1];
const extrapolateLeft = config.extrapolateLeft || config.extrapolate || "extend";
const extrapolateRight = config.extrapolateRight || config.extrapolate || "extend";
const easing = config.easing || ((t) => t);
return (input) => {
const range2 = findRange(input, inputRange);
return interpolate(
input,
inputRange[range2],
inputRange[range2 + 1],
outputRange[range2],
outputRange[range2 + 1],
easing,
extrapolateLeft,
extrapolateRight,
config.map
);
};
};
function interpolate(input, inputMin, inputMax, outputMin, outputMax, easing, extrapolateLeft, extrapolateRight, map) {
let result = map ? map(input) : input;
if (result < inputMin) {
if (extrapolateLeft === "identity")
return result;
else if (extrapolateLeft === "clamp")
result = inputMin;
}
if (result > inputMax) {
if (extrapolateRight === "identity")
return result;
else if (extrapolateRight === "clamp")
result = inputMax;
}
if (outputMin === outputMax)
return outputMin;
if (inputMin === inputMax)
return input <= inputMin ? outputMin : outputMax;
if (inputMin === -Infinity)
result = -result;
else if (inputMax === Infinity)
result = result - inputMin;
else
result = (result - inputMin) / (inputMax - inputMin);
result = easing(result);
if (outputMin === -Infinity)
result = -result;
else if (outputMax === Infinity)
result = result + outputMin;
else
result = result * (outputMax - outputMin) + outputMin;
return result;
}
function findRange(input, inputRange) {
for (var i = 1; i < inputRange.length - 1; ++i)
if (inputRange[i] >= input)
break;
return i - 1;
}
// src/easings.ts
var steps = (steps2, direction = "end") => (progress2) => {
progress2 = direction === "end" ? Math.min(progress2, 0.999) : Math.max(progress2, 1e-3);
const expanded = progress2 * steps2;
const rounded = direction === "end" ? Math.floor(expanded) : Math.ceil(expanded);
return clamp(0, 1, rounded / steps2);
};
var c1 = 1.70158;
var c2 = c1 * 1.525;
var c3 = c1 + 1;
var c4 = 2 * Math.PI / 3;
var c5 = 2 * Math.PI / 4.5;
var bounceOut = (x) => {
const n1 = 7.5625;
const d1 = 2.75;
if (x < 1 / d1) {
return n1 * x * x;
} else if (x < 2 / d1) {
return n1 * (x -= 1.5 / d1) * x + 0.75;
} else if (x < 2.5 / d1) {
return n1 * (x -= 2.25 / d1) * x + 0.9375;
} else {
return n1 * (x -= 2.625 / d1) * x + 0.984375;
}
};
var easings = {
linear: (x) => x,
easeInQuad: (x) => x * x,
easeOutQuad: (x) => 1 - (1 - x) * (1 - x),
easeInOutQuad: (x) => x < 0.5 ? 2 * x * x : 1 - Math.pow(-2 * x + 2, 2) / 2,
easeInCubic: (x) => x * x * x,
easeOutCubic: (x) => 1 - Math.pow(1 - x, 3),
easeInOutCubic: (x) => x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2,
easeInQuart: (x) => x * x * x * x,
easeOutQuart: (x) => 1 - Math.pow(1 - x, 4),
easeInOutQuart: (x) => x < 0.5 ? 8 * x * x * x * x : 1 - Math.pow(-2 * x + 2, 4) / 2,
easeInQuint: (x) => x * x * x * x * x,
easeOutQuint: (x) => 1 - Math.pow(1 - x, 5),
easeInOutQuint: (x) => x < 0.5 ? 16 * x * x * x * x * x : 1 - Math.pow(-2 * x + 2, 5) / 2,
easeInSine: (x) => 1 - Math.cos(x * Math.PI / 2),
easeOutSine: (x) => Math.sin(x * Math.PI / 2),
easeInOutSine: (x) => -(Math.cos(Math.PI * x) - 1) / 2,
easeInExpo: (x) => x === 0 ? 0 : Math.pow(2, 10 * x - 10),
easeOutExpo: (x) => x === 1 ? 1 : 1 - Math.pow(2, -10 * x),
easeInOutExpo: (x) => x === 0 ? 0 : x === 1 ? 1 : x < 0.5 ? Math.pow(2, 20 * x - 10) / 2 : (2 - Math.pow(2, -20 * x + 10)) / 2,
easeInCirc: (x) => 1 - Math.sqrt(1 - Math.pow(x, 2)),
easeOutCirc: (x) => Math.sqrt(1 - Math.pow(x - 1, 2)),
easeInOutCirc: (x) => x < 0.5 ? (1 - Math.sqrt(1 - Math.pow(2 * x, 2))) / 2 : (Math.sqrt(1 - Math.pow(-2 * x + 2, 2)) + 1) / 2,
easeInBack: (x) => c3 * x * x * x - c1 * x * x,
easeOutBack: (x) => 1 + c3 * Math.pow(x - 1, 3) + c1 * Math.pow(x - 1, 2),
easeInOutBack: (x) => x < 0.5 ? Math.pow(2 * x, 2) * ((c2 + 1) * 2 * x - c2) / 2 : (Math.pow(2 * x - 2, 2) * ((c2 + 1) * (x * 2 - 2) + c2) + 2) / 2,
easeInElastic: (x) => x === 0 ? 0 : x === 1 ? 1 : -Math.pow(2, 10 * x - 10) * Math.sin((x * 10 - 10.75) * c4),
easeOutElastic: (x) => x === 0 ? 0 : x === 1 ? 1 : Math.pow(2, -10 * x) * Math.sin((x * 10 - 0.75) * c4) + 1,
easeInOutElastic: (x) => x === 0 ? 0 : x === 1 ? 1 : x < 0.5 ? -(Math.pow(2, 20 * x - 10) * Math.sin((20 * x - 11.125) * c5)) / 2 : Math.pow(2, -20 * x + 10) * Math.sin((20 * x - 11.125) * c5) / 2 + 1,
easeInBounce: (x) => 1 - bounceOut(1 - x),
easeOutBounce: bounceOut,
easeInOutBounce: (x) => x < 0.5 ? (1 - bounceOut(1 - 2 * x)) / 2 : (1 + bounceOut(2 * x - 1)) / 2,
steps
};
// src/fluids.ts
var $get = Symbol.for("FluidValue.get");
var $observers = Symbol.for("FluidValue.observers");
var hasFluidValue = (arg) => Boolean(arg && arg[$get]);
var getFluidValue = (arg) => arg && arg[$get] ? arg[$get]() : arg;
var getFluidObservers = (target) => target[$observers] || null;
function callFluidObserver(observer2, event) {
if (observer2.eventObserved) {
observer2.eventObserved(event);
} else {
observer2(event);
}
}
function callFluidObservers(target, event) {
const observers = target[$observers];
if (observers) {
observers.forEach((observer2) => {
callFluidObserver(observer2, event);
});
}
}
var FluidValue = class {
constructor(get) {
if (!get && !(get = this.get)) {
throw Error("Unknown getter");
}
setFluidGetter(this, get);
}
};
$get, $observers;
var setFluidGetter = (target, get) => setHidden(target, $get, get);
function addFluidObserver(target, observer2) {
if (target[$get]) {
let observers = target[$observers];
if (!observers) {
setHidden(target, $observers, observers = /* @__PURE__ */ new Set());
}
if (!observers.has(observer2)) {
observers.add(observer2);
if (target.observerAdded) {
target.observerAdded(observers.size, observer2);
}
}
}
return observer2;
}
function removeFluidObserver(target, observer2) {
const observers = target[$observers];
if (observers && observers.has(observer2)) {
const count = observers.size - 1;
if (count) {
observers.delete(observer2);
} else {
target[$observers] = null;
}
if (target.observerRemoved) {
target.observerRemoved(count, observer2);
}
}
}
var setHidden = (target, key, value) => Object.defineProperty(target, key, {
value,
writable: true,
configurable: true
});
// src/regexs.ts
var numberRegex = /[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
var colorRegex = /(#(?:[0-9a-f]{2}){2,4}|(#[0-9a-f]{3})|(rgb|hsl)a?\((-?\d+%?[,\s]+){2,3}\s*[\d\.]+%?\))/gi;
var unitRegex = new RegExp(`(${numberRegex.source})(%|[a-z]+)`, "i");
var rgbaRegex = /rgba\(([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+)\)/gi;
var cssVariableRegex = /var\((--[a-zA-Z0-9-_]+),? ?([a-zA-Z0-9 ()%#.,-]+)?\)/;
// src/variableToRgba.ts
var variableToRgba = (input) => {
const [token, fallback] = parseCSSVariable(input);
if (!token || isSSR()) {
return input;
}
const value = window.getComputedStyle(document.documentElement).getPropertyValue(token);
if (value) {
return value.trim();
} else if (fallback && fallback.startsWith("--")) {
const value2 = window.getComputedStyle(document.documentElement).getPropertyValue(fallback);
if (value2) {
return value2;
} else {
return input;
}
} else if (fallback && cssVariableRegex.test(fallback)) {
return variableToRgba(fallback);
} else if (fallback) {
return fallback;
}
return input;
};
var parseCSSVariable = (current) => {
const match = cssVariableRegex.exec(current);
if (!match)
return [,];
const [, token, fallback] = match;
return [token, fallback];
};
// src/stringInterpolation.ts
var namedColorRegex;
var rgbaRound = (_, p1, p2, p3, p4) => `rgba(${Math.round(p1)}, ${Math.round(p2)}, ${Math.round(p3)}, ${p4})`;
var createStringInterpolator2 = (config) => {
if (!namedColorRegex)
namedColorRegex = colors ? (
// match color names, ignore partial matches
new RegExp(`(${Object.keys(colors).join("|")})(?!\\w)`, "g")
) : (
// never match
/^\b$/
);
const output = config.output.map((value) => {
return getFluidValue(value).replace(cssVariableRegex, variableToRgba).replace(colorRegex, colorToRgba).replace(namedColorRegex, colorToRgba);
});
const keyframes = output.map((value) => value.match(numberRegex).map(Number));
const outputRanges = keyframes[0].map(
(_, i) => keyframes.map((values) => {
if (!(i in values)) {
throw Error('The arity of each "output" value must be equal');
}
return values[i];
})
);
const interpolators = outputRanges.map(
(output2) => createInterpolator({ ...config, output: output2 })
);
return (input) => {
const missingUnit = !unitRegex.test(output[0]) && output.find((value) => unitRegex.test(value))?.replace(numberRegex, "");
let i = 0;
return output[0].replace(
numberRegex,
() => `${interpolators[i++](input)}${missingUnit || ""}`
).replace(rgbaRegex, rgbaRound);
};
};
// src/deprecations.ts
var prefix = "react-spring: ";
var once = (fn) => {
const func = fn;
let called = false;
if (typeof func != "function") {
throw new TypeError(`${prefix}once requires a function parameter`);
}
return (...args) => {
if (!called) {
func(...args);
called = true;
}
};
};
var warnInterpolate = once(console.warn);
function deprecateInterpolate() {
warnInterpolate(
`${prefix}The "interpolate" function is deprecated in v9 (use "to" instead)`
);
}
var warnDirectCall = once(console.warn);
function deprecateDirectCall() {
warnDirectCall(
`${prefix}Directly calling start instead of using the api object is deprecated in v9 (use ".start" instead), this will be removed in later 0.X.0 versions`
);
}
// src/isAnimatedString.ts
function isAnimatedString(value) {
return is.str(value) && (value[0] == "#" || /\d/.test(value) || // Do not identify a CSS variable as an AnimatedString if its SSR
!isSSR() && cssVariableRegex.test(value) || value in (colors || {}));
}
// src/dom-events/scroll/index.ts
import { raf as raf3 } from "@react-spring/rafz";
// src/dom-events/resize/resizeElement.ts
var observer;
var resizeHandlers = /* @__PURE__ */ new WeakMap();
var handleObservation = (entries) => entries.forEach(({ target, contentRect }) => {
return resizeHandlers.get(target)?.forEach((handler) => handler(contentRect));
});
function resizeElement(handler, target) {
if (!observer) {
if (typeof ResizeObserver !== "undefined") {
observer = new ResizeObserver(handleObservation);
}
}
let elementHandlers = resizeHandlers.get(target);
if (!elementHandlers) {
elementHandlers = /* @__PURE__ */ new Set();
resizeHandlers.set(target, elementHandlers);
}
elementHandlers.add(handler);
if (observer) {
observer.observe(target);
}
return () => {
const elementHandlers2 = resizeHandlers.get(target);
if (!elementHandlers2)
return;
elementHandlers2.delete(handler);
if (!elementHandlers2.size && observer) {
observer.unobserve(target);
}
};
}
// src/dom-events/resize/resizeWindow.ts
var listeners = /* @__PURE__ */ new Set();
var cleanupWindowResizeHandler;
var createResizeHandler = () => {
const handleResize = () => {
listeners.forEach(
(callback) => callback({
width: window.innerWidth,
height: window.innerHeight
})
);
};
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
};
};
var resizeWindow = (callback) => {
listeners.add(callback);
if (!cleanupWindowResizeHandler) {
cleanupWindowResizeHandler = createResizeHandler();
}
return () => {
listeners.delete(callback);
if (!listeners.size && cleanupWindowResizeHandler) {
cleanupWindowResizeHandler();
cleanupWindowResizeHandler = void 0;
}
};
};
// src/dom-events/resize/index.ts
var onResize = (callback, { container = document.documentElement } = {}) => {
if (container === document.documentElement) {
return resizeWindow(callback);
} else {
return resizeElement(callback, container);
}
};
// src/progress.ts
var progress = (min, max, value) => max - min === 0 ? 1 : (value - min) / (max - min);
// src/dom-events/scroll/ScrollHandler.ts
var SCROLL_KEYS = {
x: {
length: "Width",
position: "Left"
},
y: {
length: "Height",
position: "Top"
}
};
var ScrollHandler = class {
constructor(callback, container) {
this.createAxis = () => ({
current: 0,
progress: 0,
scrollLength: 0
});
this.updateAxis = (axisName) => {
const axis = this.info[axisName];
const { length, position } = SCROLL_KEYS[axisName];
axis.current = this.container[`scroll${position}`];
axis.scrollLength = this.container[`scroll${length}`] - this.container[`client${length}`];
axis.progress = progress(0, axis.scrollLength, axis.current);
};
this.update = () => {
this.updateAxis("x");
this.updateAxis("y");
};
this.sendEvent = () => {
this.callback(this.info);
};
this.advance = () => {
this.update();
this.sendEvent();
};
this.callback = callback;
this.container = container;
this.info = {
time: 0,
x: this.createAxis(),
y: this.createAxis()
};
}
};
// src/dom-events/scroll/index.ts
var scrollListeners = /* @__PURE__ */ new WeakMap();
var resizeListeners = /* @__PURE__ */ new WeakMap();
var onScrollHandlers = /* @__PURE__ */ new WeakMap();
var getTarget = (container) => container === document.documentElement ? window : container;
var onScroll = (callback, { container = document.documentElement } = {}) => {
let containerHandlers = onScrollHandlers.get(container);
if (!containerHandlers) {
containerHandlers = /* @__PURE__ */ new Set();
onScrollHandlers.set(container, containerHandlers);
}
const containerHandler = new ScrollHandler(callback, container);
containerHandlers.add(containerHandler);
if (!scrollListeners.has(container)) {
const listener = () => {
containerHandlers?.forEach((handler) => handler.advance());
return true;
};
scrollListeners.set(container, listener);
const target = getTarget(container);
window.addEventListener("resize", listener, { passive: true });
if (container !== document.documentElement) {
resizeListeners.set(container, onResize(listener, { container }));
}
target.addEventListener("scroll", listener, { passive: true });
}
const animateScroll = scrollListeners.get(container);
raf3(animateScroll);
return () => {
raf3.cancel(animateScroll);
const containerHandlers2 = onScrollHandlers.get(container);
if (!containerHandlers2)
return;
containerHandlers2.delete(containerHandler);
if (containerHandlers2.size)
return;
const listener = scrollListeners.get(container);
scrollListeners.delete(container);
if (listener) {
getTarget(container).removeEventListener("scroll", listener);
window.removeEventListener("resize", listener);
resizeListeners.get(container)?.();
}
};
};
// src/hooks/useConstant.ts
import { useRef } from "react";
function useConstant(init) {
const ref = useRef(null);
if (ref.current === null) {
ref.current = init();
}
return ref.current;
}
// src/hooks/useForceUpdate.ts
import { useState } from "react";
// src/hooks/useIsMounted.ts
import { useRef as useRef2 } from "react";
// src/hooks/useIsomorphicLayoutEffect.ts
import { useEffect, useLayoutEffect } from "react";
var useIsomorphicLayoutEffect = isSSR() ? useEffect : useLayoutEffect;
// src/hooks/useIsMounted.ts
var useIsMounted = () => {
const isMounted = useRef2(false);
useIsomorphicLayoutEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
};
}, []);
return isMounted;
};
// src/hooks/useForceUpdate.ts
function useForceUpdate() {
const update = useState()[1];
const isMounted = useIsMounted();
return () => {
if (isMounted.current) {
update(Math.random());
}
};
}
// src/hooks/useMemoOne.ts
import { useEffect as useEffect2, useRef as useRef3, useState as useState2 } from "react";
function useMemoOne(getResult, inputs) {
const [initial] = useState2(
() => ({
inputs,
result: getResult()
})
);
const committed = useRef3();
const prevCache = committed.current;
let cache = prevCache;
if (cache) {
const useCache = Boolean(
inputs && cache.inputs && areInputsEqual(inputs, cache.inputs)
);
if (!useCache) {
cache = {
inputs,
result: getResult()
};
}
} else {
cache = initial;
}
useEffect2(() => {
committed.current = cache;
if (prevCache == initial) {
initial.inputs = initial.result = void 0;
}
}, [cache]);
return cache.result;
}
function areInputsEqual(next, prev) {
if (next.length !== prev.length) {
return false;
}
for (let i = 0; i < next.length; i++) {
if (next[i] !== prev[i]) {
return false;
}
}
return true;
}
// src/hooks/useOnce.ts
import { useEffect as useEffect3 } from "react";
var useOnce = (effect) => useEffect3(effect, emptyDeps);
var emptyDeps = [];
// src/hooks/usePrev.ts
import { useEffect as useEffect4, useRef as useRef4 } from "react";
function usePrev(value) {
const prevRef = useRef4();
useEffect4(() => {
prevRef.current = value;
});
return prevRef.current;
}
// src/hooks/useReducedMotion.ts
import { useState as useState3 } from "react";
var useReducedMotion = () => {
const [reducedMotion, setReducedMotion] = useState3(null);
useIsomorphicLayoutEffect(() => {
const mql = window.matchMedia("(prefers-reduced-motion)");
const handleMediaChange = (e) => {
setReducedMotion(e.matches);
assign({
skipAnimation: e.matches
});
};
handleMediaChange(mql);
if (mql.addEventListener) {
mql.addEventListener("change", handleMediaChange);
} else {
mql.addListener(handleMediaChange);
}
return () => {
if (mql.removeEventListener) {
mql.removeEventListener("change", handleMediaChange);
} else {
mql.removeListener(handleMediaChange);
}
};
}, []);
return reducedMotion;
};
// src/index.ts
import { raf as raf4 } from "@react-spring/rafz";
export {
FluidValue,
globals_exports as Globals,
addFluidObserver,
callFluidObserver,
callFluidObservers,
clamp,
colorToRgba,
colors2 as colors,
createInterpolator,
createStringInterpolator2 as createStringInterpolator,
defineHidden,
deprecateDirectCall,
deprecateInterpolate,
each,
eachProp,
easings,
flush,
flushCalls,
frameLoop,
getFluidObservers,
getFluidValue,
hasFluidValue,
hex3,
hex4,
hex6,
hex8,
hsl,
hsla,
is,
isAnimatedString,
isEqual,
isSSR,
noop,
onResize,
onScroll,
once,
prefix,
raf4 as raf,
removeFluidObserver,
rgb,
rgba,
setFluidGetter,
toArray,
useConstant,
useForceUpdate,
useIsomorphicLayoutEffect,
useMemoOne,
useOnce,
usePrev,
useReducedMotion
};
//# sourceMappingURL=react-spring_shared.modern.mjs.map
webpack://frontend-mybets/../../node_modules/@react-spring/core/node_modules/@react-spring/animated/dist/react-spring_animated.modern.mjs
// src/Animated.ts
import { defineHidden } from "@react-spring/shared";
var $node = Symbol.for("Animated:node");
var isAnimated = (value) => !!value && value[$node] === value;
var getAnimated = (owner) => owner && owner[$node];
var setAnimated = (owner, node) => defineHidden(owner, $node, node);
var getPayload = (owner) => owner && owner[$node] && owner[$node].getPayload();
var Animated = class {
constructor() {
setAnimated(this, this);
}
/** Get every `AnimatedValue` used by this node. */
getPayload() {
return this.payload || [];
}
};
// src/AnimatedValue.ts
import { is } from "@react-spring/shared";
var AnimatedValue = class extends Animated {
constructor(_value) {
super();
this._value = _value;
this.done = true;
this.durationProgress = 0;
if (is.num(this._value)) {
this.lastPosition = this._value;
}
}
/** @internal */
static create(value) {
return new AnimatedValue(value);
}
getPayload() {
return [this];
}
getValue() {
return this._value;
}
setValue(value, step) {
if (is.num(value)) {
this.lastPosition = value;
if (step) {
value = Math.round(value / step) * step;
if (this.done) {
this.lastPosition = value;
}
}
}
if (this._value === value) {
return false;
}
this._value = value;
return true;
}
reset() {
const { done } = this;
this.done = false;
if (is.num(this._value)) {
this.elapsedTime = 0;
this.durationProgress = 0;
this.lastPosition = this._value;
if (done)
this.lastVelocity = null;
this.v0 = null;
}
}
};
// src/AnimatedString.ts
import { is as is2, createInterpolator } from "@react-spring/shared";
var AnimatedString = class extends AnimatedValue {
constructor(value) {
super(0);
this._string = null;
this._toString = createInterpolator({
output: [value, value]
});
}
/** @internal */
static create(value) {
return new AnimatedString(value);
}
getValue() {
const value = this._string;
return value == null ? this._string = this._toString(this._value) : value;
}
setValue(value) {
if (is2.str(value)) {
if (value == this._string) {
return false;
}
this._string = value;
this._value = 1;
} else if (super.setValue(value)) {
this._string = null;
} else {
return false;
}
return true;
}
reset(goal) {
if (goal) {
this._toString = createInterpolator({
output: [this.getValue(), goal]
});
}
this._value = 0;
super.reset();
}
};
// src/AnimatedArray.ts
import { isAnimatedString } from "@react-spring/shared";
// src/AnimatedObject.ts
import {
each,
eachProp,
getFluidValue,
hasFluidValue
} from "@react-spring/shared";
// src/context.ts
var TreeContext = { dependencies: null };
// src/AnimatedObject.ts
var AnimatedObject = class extends Animated {
constructor(source) {
super();
this.source = source;
this.setValue(source);
}
getValue(animated) {
const values = {};
eachProp(this.source, (source, key) => {
if (isAnimated(source)) {
values[key] = source.getValue(animated);
} else if (hasFluidValue(source)) {
values[key] = getFluidValue(source);
} else if (!animated) {
values[key] = source;
}
});
return values;
}
/** Replace the raw object data */
setValue(source) {
this.source = source;
this.payload = this._makePayload(source);
}
reset() {
if (this.payload) {
each(this.payload, (node) => node.reset());
}
}
/** Create a payload set. */
_makePayload(source) {
if (source) {
const payload = /* @__PURE__ */ new Set();
eachProp(source, this._addToPayload, payload);
return Array.from(payload);
}
}
/** Add to a payload set. */
_addToPayload(source) {
if (TreeContext.dependencies && hasFluidValue(source)) {
TreeContext.dependencies.add(source);
}
const payload = getPayload(source);
if (payload) {
each(payload, (node) => this.add(node));
}
}
};
// src/AnimatedArray.ts
var AnimatedArray = class extends AnimatedObject {
constructor(source) {
super(source);
}
/** @internal */
static create(source) {
return new AnimatedArray(source);
}
getValue() {
return this.source.map((node) => node.getValue());
}
setValue(source) {
const payload = this.getPayload();
if (source.length == payload.length) {
return payload.map((node, i) => node.setValue(source[i])).some(Boolean);
}
super.setValue(source.map(makeAnimated));
return true;
}
};
function makeAnimated(value) {
const nodeType = isAnimatedString(value) ? AnimatedString : AnimatedValue;
return nodeType.create(value);
}
// src/getAnimatedType.ts
import { is as is3, isAnimatedString as isAnimatedString2 } from "@react-spring/shared";
function getAnimatedType(value) {
const parentNode = getAnimated(value);
return parentNode ? parentNode.constructor : is3.arr(value) ? AnimatedArray : isAnimatedString2(value) ? AnimatedString : AnimatedValue;
}
// src/createHost.ts
import { is as is5, eachProp as eachProp2 } from "@react-spring/shared";
// src/withAnimated.tsx
import * as React from "react";
import { forwardRef, useRef, useCallback, useEffect } from "react";
import {
is as is4,
each as each2,
raf,
useForceUpdate,
useOnce,
addFluidObserver,
removeFluidObserver,
useIsomorphicLayoutEffect
} from "@react-spring/shared";
var withAnimated = (Component, host) => {
const hasInstance = (
// Function components must use "forwardRef" to avoid being
// re-rendered on every animation frame.
!is4.fun(Component) || Component.prototype && Component.prototype.isReactComponent
);
return forwardRef((givenProps, givenRef) => {
const instanceRef = useRef(null);
const ref = hasInstance && // eslint-disable-next-line react-hooks/rules-of-hooks
useCallback(
(value) => {
instanceRef.current = updateRef(givenRef, value);
},
[givenRef]
);
const [props, deps] = getAnimatedState(givenProps, host);
const forceUpdate = useForceUpdate();
const callback = () => {
const instance = instanceRef.current;
if (hasInstance && !instance) {
return;
}
const didUpdate = instance ? host.applyAnimatedValues(instance, props.getValue(true)) : false;
if (didUpdate === false) {
forceUpdate();
}
};
const observer = new PropsObserver(callback, deps);
const observerRef = useRef();
useIsomorphicLayoutEffect(() => {
observerRef.current = observer;
each2(deps, (dep) => addFluidObserver(dep, observer));
return () => {
if (observerRef.current) {
each2(
observerRef.current.deps,
(dep) => removeFluidObserver(dep, observerRef.current)
);
raf.cancel(observerRef.current.update);
}
};
});
useEffect(callback, []);
useOnce(() => () => {
const observer2 = observerRef.current;
each2(observer2.deps, (dep) => removeFluidObserver(dep, observer2));
});
const usedProps = host.getComponentProps(props.getValue());
return /* @__PURE__ */ React.createElement(Component, { ...usedProps, ref });
});
};
var PropsObserver = class {
constructor(update, deps) {
this.update = update;
this.deps = deps;
}
eventObserved(event) {
if (event.type == "change") {
raf.write(this.update);
}
}
};
function getAnimatedState(props, host) {
const dependencies = /* @__PURE__ */ new Set();
TreeContext.dependencies = dependencies;
if (props.style)
props = {
...props,
style: host.createAnimatedStyle(props.style)
};
props = new AnimatedObject(props);
TreeContext.dependencies = null;
return [props, dependencies];
}
function updateRef(ref, value) {
if (ref) {
if (is4.fun(ref))
ref(value);
else
ref.current = value;
}
return value;
}
// src/createHost.ts
var cacheKey = Symbol.for("AnimatedComponent");
var createHost = (components, {
applyAnimatedValues = () => false,
createAnimatedStyle = (style) => new AnimatedObject(style),
getComponentProps = (props) => props
} = {}) => {
const hostConfig = {
applyAnimatedValues,
createAnimatedStyle,
getComponentProps
};
const animated = (Component) => {
const displayName = getDisplayName(Component) || "Anonymous";
if (is5.str(Component)) {
Component = animated[Component] || (animated[Component] = withAnimated(Component, hostConfig));
} else {
Component = Component[cacheKey] || (Component[cacheKey] = withAnimated(Component, hostConfig));
}
Component.displayName = `Animated(${displayName})`;
return Component;
};
eachProp2(components, (Component, key) => {
if (is5.arr(components)) {
key = getDisplayName(Component);
}
animated[key] = animated(Component);
});
return {
animated
};
};
var getDisplayName = (arg) => is5.str(arg) ? arg : arg && is5.str(arg.displayName) ? arg.displayName : is5.fun(arg) && arg.name || null;
export {
Animated,
AnimatedArray,
AnimatedObject,
AnimatedString,
AnimatedValue,
createHost,
getAnimated,
getAnimatedType,
getPayload,
isAnimated,
setAnimated
};
//# sourceMappingURL=react-spring_animated.modern.mjs.map
webpack://frontend-mybets/../../node_modules/@react-spring/core/dist/react-spring_core.modern.mjs
// src/hooks/useChain.ts
import { each, useIsomorphicLayoutEffect } from "@react-spring/shared";
// src/helpers.ts
import {
is,
toArray,
eachProp,
getFluidValue,
isAnimatedString,
Globals as G
} from "@react-spring/shared";
function callProp(value, ...args) {
return is.fun(value) ? value(...args) : value;
}
var matchProp = (value, key) => value === true || !!(key && value && (is.fun(value) ? value(key) : toArray(value).includes(key)));
var resolveProp = (prop, key) => is.obj(prop) ? key && prop[key] : prop;
var getDefaultProp = (props, key) => props.default === true ? props[key] : props.default ? props.default[key] : void 0;
var noopTransform = (value) => value;
var getDefaultProps = (props, transform = noopTransform) => {
let keys = DEFAULT_PROPS;
if (props.default && props.default !== true) {
props = props.default;
keys = Object.keys(props);
}
const defaults2 = {};
for (const key of keys) {
const value = transform(props[key], key);
if (!is.und(value)) {
defaults2[key] = value;
}
}
return defaults2;
};
var DEFAULT_PROPS = [
"config",
"onProps",
"onStart",
"onChange",
"onPause",
"onResume",
"onRest"
];
var RESERVED_PROPS = {
config: 1,
from: 1,
to: 1,
ref: 1,
loop: 1,
reset: 1,
pause: 1,
cancel: 1,
reverse: 1,
immediate: 1,
default: 1,
delay: 1,
onProps: 1,
onStart: 1,
onChange: 1,
onPause: 1,
onResume: 1,
onRest: 1,
onResolve: 1,
// Transition props
items: 1,
trail: 1,
sort: 1,
expires: 1,
initial: 1,
enter: 1,
update: 1,
leave: 1,
children: 1,
onDestroyed: 1,
// Internal props
keys: 1,
callId: 1,
parentId: 1
};
function getForwardProps(props) {
const forward = {};
let count = 0;
eachProp(props, (value, prop) => {
if (!RESERVED_PROPS[prop]) {
forward[prop] = value;
count++;
}
});
if (count) {
return forward;
}
}
function inferTo(props) {
const to2 = getForwardProps(props);
if (to2) {
const out = { to: to2 };
eachProp(props, (val, key) => key in to2 || (out[key] = val));
return out;
}
return { ...props };
}
function computeGoal(value) {
value = getFluidValue(value);
return is.arr(value) ? value.map(computeGoal) : isAnimatedString(value) ? G.createStringInterpolator({
range: [0, 1],
output: [value, value]
})(1) : value;
}
function hasProps(props) {
for (const _ in props)
return true;
return false;
}
function isAsyncTo(to2) {
return is.fun(to2) || is.arr(to2) && is.obj(to2[0]);
}
function detachRefs(ctrl, ref) {
ctrl.ref?.delete(ctrl);
ref?.delete(ctrl);
}
function replaceRef(ctrl, ref) {
if (ref && ctrl.ref !== ref) {
ctrl.ref?.delete(ctrl);
ref.add(ctrl);
ctrl.ref = ref;
}
}
// src/hooks/useChain.ts
function useChain(refs, timeSteps, timeFrame = 1e3) {
useIsomorphicLayoutEffect(() => {
if (timeSteps) {
let prevDelay = 0;
each(refs, (ref, i) => {
const controllers = ref.current;
if (controllers.length) {
let delay = timeFrame * timeSteps[i];
if (isNaN(delay))
delay = prevDelay;
else
prevDelay = delay;
each(controllers, (ctrl) => {
each(ctrl.queue, (props) => {
const memoizedDelayProp = props.delay;
props.delay = (key) => delay + callProp(memoizedDelayProp || 0, key);
});
});
ref.start();
}
});
} else {
let p = Promise.resolve();
each(refs, (ref) => {
const controllers = ref.current;
if (controllers.length) {
const queues = controllers.map((ctrl) => {
const q = ctrl.queue;
ctrl.queue = [];
return q;
});
p = p.then(() => {
each(
controllers,
(ctrl, i) => each(queues[i] || [], (update2) => ctrl.queue.push(update2))
);
return Promise.all(ref.start());
});
}
});
}
});
}
// src/hooks/useSpring.ts
import { is as is9 } from "@react-spring/shared";
// src/hooks/useSprings.ts
import { useContext as useContext2, useMemo, useRef } from "react";
import {
is as is8,
each as each5,
usePrev,
useOnce,
useForceUpdate,
useIsomorphicLayoutEffect as useIsomorphicLayoutEffect2
} from "@react-spring/shared";
// src/SpringValue.ts
import {
is as is5,
raf as raf3,
each as each2,
isEqual,
toArray as toArray2,
eachProp as eachProp3,
frameLoop as frameLoop2,
flushCalls,
getFluidValue as getFluidValue2,
isAnimatedString as isAnimatedString2,
Globals as G5,
callFluidObservers as callFluidObservers2,
hasFluidValue,
addFluidObserver,
removeFluidObserver,
getFluidObservers
} from "@react-spring/shared";
import {
AnimatedValue,
AnimatedString,
getPayload,
getAnimated as getAnimated2,
setAnimated,
getAnimatedType
} from "@react-spring/animated";
// src/AnimationConfig.ts
import { is as is2, easings } from "@react-spring/shared";
// src/constants.ts
var config = {
default: { tension: 170, friction: 26 },
gentle: { tension: 120, friction: 14 },
wobbly: { tension: 180, friction: 12 },
stiff: { tension: 210, friction: 20 },
slow: { tension: 280, friction: 60 },
molasses: { tension: 280, friction: 120 }
};
// src/AnimationConfig.ts
var defaults = {
...config.default,
mass: 1,
damping: 1,
easing: easings.linear,
clamp: false
};
var AnimationConfig = class {
constructor() {
/**
* The initial velocity of one or more values.
*
* @default 0
*/
this.velocity = 0;
Object.assign(this, defaults);
}
};
function mergeConfig(config2, newConfig, defaultConfig) {
if (defaultConfig) {
defaultConfig = { ...defaultConfig };
sanitizeConfig(defaultConfig, newConfig);
newConfig = { ...defaultConfig, ...newConfig };
}
sanitizeConfig(config2, newConfig);
Object.assign(config2, newConfig);
for (const key in defaults) {
if (config2[key] == null) {
config2[key] = defaults[key];
}
}
let { frequency, damping } = config2;
const { mass } = config2;
if (!is2.und(frequency)) {
if (frequency < 0.01)
frequency = 0.01;
if (damping < 0)
damping = 0;
config2.tension = Math.pow(2 * Math.PI / frequency, 2) * mass;
config2.friction = 4 * Math.PI * damping * mass / frequency;
}
return config2;
}
function sanitizeConfig(config2, props) {
if (!is2.und(props.decay)) {
config2.duration = void 0;
} else {
const isTensionConfig = !is2.und(props.tension) || !is2.und(props.friction);
if (isTensionConfig || !is2.und(props.frequency) || !is2.und(props.damping) || !is2.und(props.mass)) {
config2.duration = void 0;
config2.decay = void 0;
}
if (isTensionConfig) {
config2.frequency = void 0;
}
}
}
// src/Animation.ts
var emptyArray = [];
var Animation = class {
constructor() {
this.changed = false;
this.values = emptyArray;
this.toValues = null;
this.fromValues = emptyArray;
this.config = new AnimationConfig();
this.immediate = false;
}
};
// src/scheduleProps.ts
import { is as is3, raf, Globals as G2 } from "@react-spring/shared";
function scheduleProps(callId, { key, props, defaultProps, state, actions }) {
return new Promise((resolve, reject) => {
let delay;
let timeout;
let cancel = matchProp(props.cancel ?? defaultProps?.cancel, key);
if (cancel) {
onStart();
} else {
if (!is3.und(props.pause)) {
state.paused = matchProp(props.pause, key);
}
let pause = defaultProps?.pause;
if (pause !== true) {
pause = state.paused || matchProp(pause, key);
}
delay = callProp(props.delay || 0, key);
if (pause) {
state.resumeQueue.add(onResume);
actions.pause();
} else {
actions.resume();
onResume();
}
}
function onPause() {
state.resumeQueue.add(onResume);
state.timeouts.delete(timeout);
timeout.cancel();
delay = timeout.time - raf.now();
}
function onResume() {
if (delay > 0 && !G2.skipAnimation) {
state.delayed = true;
timeout = raf.setTimeout(onStart, delay);
state.pauseQueue.add(onPause);
state.timeouts.add(timeout);
} else {
onStart();
}
}
function onStart() {
if (state.delayed) {
state.delayed = false;
}
state.pauseQueue.delete(onPause);
state.timeouts.delete(timeout);
if (callId <= (state.cancelId || 0)) {
cancel = true;
}
try {
actions.start({ ...props, callId, cancel }, resolve);
} catch (err) {
reject(err);
}
}
});
}
// src/runAsync.ts
import {
is as is4,
raf as raf2,
flush,
eachProp as eachProp2,
Globals as G3
} from "@react-spring/shared";
// src/AnimationResult.ts
var getCombinedResult = (target, results) => results.length == 1 ? results[0] : results.some((result) => result.cancelled) ? getCancelledResult(target.get()) : results.every((result) => result.noop) ? getNoopResult(target.get()) : getFinishedResult(
target.get(),
results.every((result) => result.finished)
);
var getNoopResult = (value) => ({
value,
noop: true,
finished: true,
cancelled: false
});
var getFinishedResult = (value, finished, cancelled = false) => ({
value,
finished,
cancelled
});
var getCancelledResult = (value) => ({
value,
cancelled: true,
finished: false
});
// src/runAsync.ts
function runAsync(to2, props, state, target) {
const { callId, parentId, onRest } = props;
const { asyncTo: prevTo, promise: prevPromise } = state;
if (!parentId && to2 === prevTo && !props.reset) {
return prevPromise;
}
return state.promise = (async () => {
state.asyncId = callId;
state.asyncTo = to2;
const defaultProps = getDefaultProps(
props,
(value, key) => (
// The `onRest` prop is only called when the `runAsync` promise is resolved.
key === "onRest" ? void 0 : value
)
);
let preventBail;
let bail;
const bailPromise = new Promise(
(resolve, reject) => (preventBail = resolve, bail = reject)
);
const bailIfEnded = (bailSignal) => {
const bailResult = (
// The `cancel` prop or `stop` method was used.
callId <= (state.cancelId || 0) && getCancelledResult(target) || // The async `to` prop was replaced.
callId !== state.asyncId && getFinishedResult(target, false)
);
if (bailResult) {
bailSignal.result = bailResult;
bail(bailSignal);
throw bailSignal;
}
};
const animate = (arg1, arg2) => {
const bailSignal = new BailSignal();
const skipAnimationSignal = new SkipAnimationSignal();
return (async () => {
if (G3.skipAnimation) {
stopAsync(state);
skipAnimationSignal.result = getFinishedResult(target, false);
bail(skipAnimationSignal);
throw skipAnimationSignal;
}
bailIfEnded(bailSignal);
const props2 = is4.obj(arg1) ? { ...arg1 } : { ...arg2, to: arg1 };
props2.parentId = callId;
eachProp2(defaultProps, (value, key) => {
if (is4.und(props2[key])) {
props2[key] = value;
}
});
const result2 = await target.start(props2);
bailIfEnded(bailSignal);
if (state.paused) {
await new Promise((resume) => {
state.resumeQueue.add(resume);
});
}
return result2;
})();
};
let result;
if (G3.skipAnimation) {
stopAsync(state);
return getFinishedResult(target, false);
}
try {
let animating;
if (is4.arr(to2)) {
animating = (async (queue) => {
for (const props2 of queue) {
await animate(props2);
}
})(to2);
} else {
animating = Promise.resolve(to2(animate, target.stop.bind(target)));
}
await Promise.all([animating.then(preventBail), bailPromise]);
result = getFinishedResult(target.get(), true, false);
} catch (err) {
if (err instanceof BailSignal) {
result = err.result;
} else if (err instanceof SkipAnimationSignal) {
result = err.result;
} else {
throw err;
}
} finally {
if (callId == state.asyncId) {
state.asyncId = parentId;
state.asyncTo = parentId ? prevTo : void 0;
state.promise = parentId ? prevPromise : void 0;
}
}
if (is4.fun(onRest)) {
raf2.batchedUpdates(() => {
onRest(result, target, target.item);
});
}
return result;
})();
}
function stopAsync(state, cancelId) {
flush(state.timeouts, (t) => t.cancel());
state.pauseQueue.clear();
state.resumeQueue.clear();
state.asyncId = state.asyncTo = state.promise = void 0;
if (cancelId)
state.cancelId = cancelId;
}
var BailSignal = class extends Error {
constructor() {
super(
"An async animation has been interrupted. You see this error because you forgot to use `await` or `.catch(...)` on its returned promise."
);
}
};
var SkipAnimationSignal = class extends Error {
constructor() {
super("SkipAnimationSignal");
}
};
// src/FrameValue.ts
import {
deprecateInterpolate,
frameLoop,
FluidValue as FluidValue2,
Globals as G4,
callFluidObservers
} from "@react-spring/shared";
import { getAnimated } from "@react-spring/animated";
var isFrameValue = (value) => value instanceof FrameValue;
var nextId = 1;
var FrameValue = class extends FluidValue2 {
constructor() {
super(...arguments);
this.id = nextId++;
this._priority = 0;
}
get priority() {
return this._priority;
}
set priority(priority) {
if (this._priority != priority) {
this._priority = priority;
this._onPriorityChange(priority);
}
}
/** Get the current value */
get() {
const node = getAnimated(this);
return node && node.getValue();
}
/** Create a spring that maps our value to another value */
to(...args) {
return G4.to(this, args);
}
/** @deprecated Use the `to` method instead. */
interpolate(...args) {
deprecateInterpolate();
return G4.to(this, args);
}
toJSON() {
return this.get();
}
observerAdded(count) {
if (count == 1)
this._attach();
}
observerRemoved(count) {
if (count == 0)
this._detach();
}
/** Called when the first child is added. */
_attach() {
}
/** Called when the last child is removed. */
_detach() {
}
/** Tell our children about our new value */
_onChange(value, idle = false) {
callFluidObservers(this, {
type: "change",
parent: this,
value,
idle
});
}
/** Tell our children about our new priority */
_onPriorityChange(priority) {
if (!this.idle) {
frameLoop.sort(this);
}
callFluidObservers(this, {
type: "priority",
parent: this,
priority
});
}
};
// src/SpringPhase.ts
var $P = Symbol.for("SpringPhase");
var HAS_ANIMATED = 1;
var IS_ANIMATING = 2;
var IS_PAUSED = 4;
var hasAnimated = (target) => (target[$P] & HAS_ANIMATED) > 0;
var isAnimating = (target) => (target[$P] & IS_ANIMATING) > 0;
var isPaused = (target) => (target[$P] & IS_PAUSED) > 0;
var setActiveBit = (target, active) => active ? target[$P] |= IS_ANIMATING | HAS_ANIMATED : target[$P] &= ~IS_ANIMATING;
var setPausedBit = (target, paused) => paused ? target[$P] |= IS_PAUSED : target[$P] &= ~IS_PAUSED;
// src/SpringValue.ts
var SpringValue = class extends FrameValue {
constructor(arg1, arg2) {
super();
/** The animation state */
this.animation = new Animation();
/** Some props have customizable default values */
this.defaultProps = {};
/** The state for `runAsync` calls */
this._state = {
paused: false,
delayed: false,
pauseQueue: /* @__PURE__ */ new Set(),
resumeQueue: /* @__PURE__ */ new Set(),
timeouts: /* @__PURE__ */ new Set()
};
/** The promise resolvers of pending `start` calls */
this._pendingCalls = /* @__PURE__ */ new Set();
/** The counter for tracking `scheduleProps` calls */
this._lastCallId = 0;
/** The last `scheduleProps` call that changed the `to` prop */
this._lastToId = 0;
this._memoizedDuration = 0;
if (!is5.und(arg1) || !is5.und(arg2)) {
const props = is5.obj(arg1) ? { ...arg1 } : { ...arg2, from: arg1 };
if (is5.und(props.default)) {
props.default = true;
}
this.start(props);
}
}
/** Equals true when not advancing on each frame. */
get idle() {
return !(isAnimating(this) || this._state.asyncTo) || isPaused(this);
}
get goal() {
return getFluidValue2(this.animation.to);
}
get velocity() {
const node = getAnimated2(this);
return node instanceof AnimatedValue ? node.lastVelocity || 0 : node.getPayload().map((node2) => node2.lastVelocity || 0);
}
/**
* When true, this value has been animated at least once.
*/
get hasAnimated() {
return hasAnimated(this);
}
/**
* When true, this value has an unfinished animation,
* which is either active or paused.
*/
get isAnimating() {
return isAnimating(this);
}
/**
* When true, all current and future animations are paused.
*/
get isPaused() {
return isPaused(this);
}
/**
*
*
*/
get isDelayed() {
return this._state.delayed;
}
/** Advance the current animation by a number of milliseconds */
advance(dt) {
let idle = true;
let changed = false;
const anim = this.animation;
let { toValues } = anim;
const { config: config2 } = anim;
const payload = getPayload(anim.to);
if (!payload && hasFluidValue(anim.to)) {
toValues = toArray2(getFluidValue2(anim.to));
}
anim.values.forEach((node2, i) => {
if (node2.done)
return;
const to2 = (
// Animated strings always go from 0 to 1.
node2.constructor == AnimatedString ? 1 : payload ? payload[i].lastPosition : toValues[i]
);
let finished = anim.immediate;
let position = to2;
if (!finished) {
position = node2.lastPosition;
if (config2.tension <= 0) {
node2.done = true;
return;
}
let elapsed = node2.elapsedTime += dt;
const from = anim.fromValues[i];
const v0 = node2.v0 != null ? node2.v0 : node2.v0 = is5.arr(config2.velocity) ? config2.velocity[i] : config2.velocity;
let velocity;
const precision = config2.precision || (from == to2 ? 5e-3 : Math.min(1, Math.abs(to2 - from) * 1e-3));
if (!is5.und(config2.duration)) {
let p = 1;
if (config2.duration > 0) {
if (this._memoizedDuration !== config2.duration) {
this._memoizedDuration = config2.duration;
if (node2.durationProgress > 0) {
node2.elapsedTime = config2.duration * node2.durationProgress;
elapsed = node2.elapsedTime += dt;
}
}
p = (config2.progress || 0) + elapsed / this._memoizedDuration;
p = p > 1 ? 1 : p < 0 ? 0 : p;
node2.durationProgress = p;
}
position = from + config2.easing(p) * (to2 - from);
velocity = (position - node2.lastPosition) / dt;
finished = p == 1;
} else if (config2.decay) {
const decay = config2.decay === true ? 0.998 : config2.decay;
const e = Math.exp(-(1 - decay) * elapsed);
position = from + v0 / (1 - decay) * (1 - e);
finished = Math.abs(node2.lastPosition - position) <= precision;
velocity = v0 * e;
} else {
velocity = node2.lastVelocity == null ? v0 : node2.lastVelocity;
const restVelocity = config2.restVelocity || precision / 10;
const bounceFactor = config2.clamp ? 0 : config2.bounce;
const canBounce = !is5.und(bounceFactor);
const isGrowing = from == to2 ? node2.v0 > 0 : from < to2;
let isMoving;
let isBouncing = false;
const step = 1;
const numSteps = Math.ceil(dt / step);
for (let n = 0; n < numSteps; ++n) {
isMoving = Math.abs(velocity) > restVelocity;
if (!isMoving) {
finished = Math.abs(to2 - position) <= precision;
if (finished) {
break;
}
}
if (canBounce) {
isBouncing = position == to2 || position > to2 == isGrowing;
if (isBouncing) {
velocity = -velocity * bounceFactor;
position = to2;
}
}
const springForce = -config2.tension * 1e-6 * (position - to2);
const dampingForce = -config2.friction * 1e-3 * velocity;
const acceleration = (springForce + dampingForce) / config2.mass;
velocity = velocity + acceleration * step;
position = position + velocity * step;
}
}
node2.lastVelocity = velocity;
if (Number.isNaN(position)) {
console.warn(`Got NaN while animating:`, this);
finished = true;
}
}
if (payload && !payload[i].done) {
finished = false;
}
if (finished) {
node2.done = true;
} else {
idle = false;
}
if (node2.setValue(position, config2.round)) {
changed = true;
}
});
const node = getAnimated2(this);
const currVal = node.getValue();
if (idle) {
const finalVal = getFluidValue2(anim.to);
if ((currVal !== finalVal || changed) && !config2.decay) {
node.setValue(finalVal);
this._onChange(finalVal);
} else if (changed && config2.decay) {
this._onChange(currVal);
}
this._stop();
} else if (changed) {
this._onChange(currVal);
}
}
/** Set the current value, while stopping the current animation */
set(value) {
raf3.batchedUpdates(() => {
this._stop();
this._focus(value);
this._set(value);
});
return this;
}
/**
* Freeze the active animation in time, as well as any updates merged
* before `resume` is called.
*/
pause() {
this._update({ pause: true });
}
/** Resume the animation if paused. */
resume() {
this._update({ pause: false });
}
/** Skip to the end of the current animation. */
finish() {
if (isAnimating(this)) {
const { to: to2, config: config2 } = this.animation;
raf3.batchedUpdates(() => {
this._onStart();
if (!config2.decay) {
this._set(to2, false);
}
this._stop();
});
}
return this;
}
/** Push props into the pending queue. */
update(props) {
const queue = this.queue || (this.queue = []);
queue.push(props);
return this;
}
start(to2, arg2) {
let queue;
if (!is5.und(to2)) {
queue = [is5.obj(to2) ? to2 : { ...arg2, to: to2 }];
} else {
queue = this.queue || [];
this.queue = [];
}
return Promise.all(
queue.map((props) => {
const up = this._update(props);
return up;
})
).then((results) => getCombinedResult(this, results));
}
/**
* Stop the current animation, and cancel any delayed updates.
*
* Pass `true` to call `onRest` with `cancelled: true`.
*/
stop(cancel) {
const { to: to2 } = this.animation;
this._focus(this.get());
stopAsync(this._state, cancel && this._lastCallId);
raf3.batchedUpdates(() => this._stop(to2, cancel));
return this;
}
/** Restart the animation. */
reset() {
this._update({ reset: true });
}
/** @internal */
eventObserved(event) {
if (event.type == "change") {
this._start();
} else if (event.type == "priority") {
this.priority = event.priority + 1;
}
}
/**
* Parse the `to` and `from` range from the given `props` object.
*
* This also ensures the initial value is available to animated components
* during the render phase.
*/
_prepareNode(props) {
const key = this.key || "";
let { to: to2, from } = props;
to2 = is5.obj(to2) ? to2[key] : to2;
if (to2 == null || isAsyncTo(to2)) {
to2 = void 0;
}
from = is5.obj(from) ? from[key] : from;
if (from == null) {
from = void 0;
}
const range = { to: to2, from };
if (!hasAnimated(this)) {
if (props.reverse)
[to2, from] = [from, to2];
from = getFluidValue2(from);
if (!is5.und(from)) {
this._set(from);
} else if (!getAnimated2(this)) {
this._set(to2);
}
}
return range;
}
/** Every update is processed by this method before merging. */
_update({ ...props }, isLoop) {
const { key, defaultProps } = this;
if (props.default)
Object.assign(
defaultProps,
getDefaultProps(
props,
(value, prop) => /^on/.test(prop) ? resolveProp(value, key) : value
)
);
mergeActiveFn(this, props, "onProps");
sendEvent(this, "onProps", props, this);
const range = this._prepareNode(props);
if (Object.isFrozen(this)) {
throw Error(
"Cannot animate a `SpringValue` object that is frozen. Did you forget to pass your component to `animated(...)` before animating its props?"
);
}
const state = this._state;
return scheduleProps(++this._lastCallId, {
key,
props,
defaultProps,
state,
actions: {
pause: () => {
if (!isPaused(this)) {
setPausedBit(this, true);
flushCalls(state.pauseQueue);
sendEvent(
this,
"onPause",
getFinishedResult(this, checkFinished(this, this.animation.to)),
this
);
}
},
resume: () => {
if (isPaused(this)) {
setPausedBit(this, false);
if (isAnimating(this)) {
this._resume();
}
flushCalls(state.resumeQueue);
sendEvent(
this,
"onResume",
getFinishedResult(this, checkFinished(this, this.animation.to)),
this
);
}
},
start: this._merge.bind(this, range)
}
}).then((result) => {
if (props.loop && result.finished && !(isLoop && result.noop)) {
const nextProps = createLoopUpdate(props);
if (nextProps) {
return this._update(nextProps, true);
}
}
return result;
});
}
/** Merge props into the current animation */
_merge(range, props, resolve) {
if (props.cancel) {
this.stop(true);
return resolve(getCancelledResult(this));
}
const hasToProp = !is5.und(range.to);
const hasFromProp = !is5.und(range.from);
if (hasToProp || hasFromProp) {
if (props.callId > this._lastToId) {
this._lastToId = props.callId;
} else {
return resolve(getCancelledResult(this));
}
}
const { key, defaultProps, animation: anim } = this;
const { to: prevTo, from: prevFrom } = anim;
let { to: to2 = prevTo, from = prevFrom } = range;
if (hasFromProp && !hasToProp && (!props.default || is5.und(to2))) {
to2 = from;
}
if (props.reverse)
[to2, from] = [from, to2];
const hasFromChanged = !isEqual(from, prevFrom);
if (hasFromChanged) {
anim.from = from;
}
from = getFluidValue2(from);
const hasToChanged = !isEqual(to2, prevTo);
if (hasToChanged) {
this._focus(to2);
}
const hasAsyncTo = isAsyncTo(props.to);
const { config: config2 } = anim;
const { decay, velocity } = config2;
if (hasToProp || hasFromProp) {
config2.velocity = 0;
}
if (props.config && !hasAsyncTo) {
mergeConfig(
config2,
callProp(props.config, key),
// Avoid calling the same "config" prop twice.
props.config !== defaultProps.config ? callProp(defaultProps.config, key) : void 0
);
}
let node = getAnimated2(this);
if (!node || is5.und(to2)) {
return resolve(getFinishedResult(this, true));
}
const reset = (
// When `reset` is undefined, the `from` prop implies `reset: true`,
// except for declarative updates. When `reset` is defined, there
// must exist a value to animate from.
is5.und(props.reset) ? hasFromProp && !props.default : !is5.und(from) && matchProp(props.reset, key)
);
const value = reset ? from : this.get();
const goal = computeGoal(to2);
const isAnimatable = is5.num(goal) || is5.arr(goal) || isAnimatedString2(goal);
const immediate = !hasAsyncTo && (!isAnimatable || matchProp(defaultProps.immediate || props.immediate, key));
if (hasToChanged) {
const nodeType = getAnimatedType(to2);
if (nodeType !== node.constructor) {
if (immediate) {
node = this._set(goal);
} else
throw Error(
`Cannot animate between ${node.constructor.name} and ${nodeType.name}, as the "to" prop suggests`
);
}
}
const goalType = node.constructor;
let started = hasFluidValue(to2);
let finished = false;
if (!started) {
const hasValueChanged = reset || !hasAnimated(this) && hasFromChanged;
if (hasToChanged || hasValueChanged) {
finished = isEqual(computeGoal(value), goal);
started = !finished;
}
if (!isEqual(anim.immediate, immediate) && !immediate || !isEqual(config2.decay, decay) || !isEqual(config2.velocity, velocity)) {
started = true;
}
}
if (finished && isAnimating(this)) {
if (anim.changed && !reset) {
started = true;
} else if (!started) {
this._stop(prevTo);
}
}
if (!hasAsyncTo) {
if (started || hasFluidValue(prevTo)) {
anim.values = node.getPayload();
anim.toValues = hasFluidValue(to2) ? null : goalType == AnimatedString ? [1] : toArray2(goal);
}
if (anim.immediate != immediate) {
anim.immediate = immediate;
if (!immediate && !reset) {
this._set(prevTo);
}
}
if (started) {
const { onRest } = anim;
each2(ACTIVE_EVENTS, (type) => mergeActiveFn(this, props, type));
const result = getFinishedResult(this, checkFinished(this, prevTo));
flushCalls(this._pendingCalls, result);
this._pendingCalls.add(resolve);
if (anim.changed)
raf3.batchedUpdates(() => {
anim.changed = !reset;
onRest?.(result, this);
if (reset) {
callProp(defaultProps.onRest, result);
} else {
anim.onStart?.(result, this);
}
});
}
}
if (reset) {
this._set(value);
}
if (hasAsyncTo) {
resolve(runAsync(props.to, props, this._state, this));
} else if (started) {
this._start();
} else if (isAnimating(this) && !hasToChanged) {
this._pendingCalls.add(resolve);
} else {
resolve(getNoopResult(value));
}
}
/** Update the `animation.to` value, which might be a `FluidValue` */
_focus(value) {
const anim = this.animation;
if (value !== anim.to) {
if (getFluidObservers(this)) {
this._detach();
}
anim.to = value;
if (getFluidObservers(this)) {
this._attach();
}
}
}
_attach() {
let priority = 0;
const { to: to2 } = this.animation;
if (hasFluidValue(to2)) {
addFluidObserver(to2, this);
if (isFrameValue(to2)) {
priority = to2.priority + 1;
}
}
this.priority = priority;
}
_detach() {
const { to: to2 } = this.animation;
if (hasFluidValue(to2)) {
removeFluidObserver(to2, this);
}
}
/**
* Update the current value from outside the frameloop,
* and return the `Animated` node.
*/
_set(arg, idle = true) {
const value = getFluidValue2(arg);
if (!is5.und(value)) {
const oldNode = getAnimated2(this);
if (!oldNode || !isEqual(value, oldNode.getValue())) {
const nodeType = getAnimatedType(value);
if (!oldNode || oldNode.constructor != nodeType) {
setAnimated(this, nodeType.create(value));
} else {
oldNode.setValue(value);
}
if (oldNode) {
raf3.batchedUpdates(() => {
this._onChange(value, idle);
});
}
}
}
return getAnimated2(this);
}
_onStart() {
const anim = this.animation;
if (!anim.changed) {
anim.changed = true;
sendEvent(
this,
"onStart",
getFinishedResult(this, checkFinished(this, anim.to)),
this
);
}
}
_onChange(value, idle) {
if (!idle) {
this._onStart();
callProp(this.animation.onChange, value, this);
}
callProp(this.defaultProps.onChange, value, this);
super._onChange(value, idle);
}
// This method resets the animation state (even if already animating) to
// ensure the latest from/to range is used, and it also ensures this spring
// is added to the frameloop.
_start() {
const anim = this.animation;
getAnimated2(this).reset(getFluidValue2(anim.to));
if (!anim.immediate) {
anim.fromValues = anim.values.map((node) => node.lastPosition);
}
if (!isAnimating(this)) {
setActiveBit(this, true);
if (!isPaused(this)) {
this._resume();
}
}
}
_resume() {
if (G5.skipAnimation) {
this.finish();
} else {
frameLoop2.start(this);
}
}
/**
* Exit the frameloop and notify `onRest` listeners.
*
* Always wrap `_stop` calls with `batchedUpdates`.
*/
_stop(goal, cancel) {
if (isAnimating(this)) {
setActiveBit(this, false);
const anim = this.animation;
each2(anim.values, (node) => {
node.done = true;
});
if (anim.toValues) {
anim.onChange = anim.onPause = anim.onResume = void 0;
}
callFluidObservers2(this, {
type: "idle",
parent: this
});
const result = cancel ? getCancelledResult(this.get()) : getFinishedResult(this.get(), checkFinished(this, goal ?? anim.to));
flushCalls(this._pendingCalls, result);
if (anim.changed) {
anim.changed = false;
sendEvent(this, "onRest", result, this);
}
}
}
};
function checkFinished(target, to2) {
const goal = computeGoal(to2);
const value = computeGoal(target.get());
return isEqual(value, goal);
}
function createLoopUpdate(props, loop = props.loop, to2 = props.to) {
const loopRet = callProp(loop);
if (loopRet) {
const overrides = loopRet !== true && inferTo(loopRet);
const reverse = (overrides || props).reverse;
const reset = !overrides || overrides.reset;
return createUpdate({
...props,
loop,
// Avoid updating default props when looping.
default: false,
// Never loop the `pause` prop.
pause: void 0,
// For the "reverse" prop to loop as expected, the "to" prop
// must be undefined. The "reverse" prop is ignored when the
// "to" prop is an array or function.
to: !reverse || isAsyncTo(to2) ? to2 : void 0,
// Ignore the "from" prop except on reset.
from: reset ? props.from : void 0,
reset,
// The "loop" prop can return a "useSpring" props object to
// override any of the original props.
...overrides
});
}
}
function createUpdate(props) {
const { to: to2, from } = props = inferTo(props);
const keys = /* @__PURE__ */ new Set();
if (is5.obj(to2))
findDefined(to2, keys);
if (is5.obj(from))
findDefined(from, keys);
props.keys = keys.size ? Array.from(keys) : null;
return props;
}
function declareUpdate(props) {
const update2 = createUpdate(props);
if (is5.und(update2.default)) {
update2.default = getDefaultProps(update2);
}
return update2;
}
function findDefined(values, keys) {
eachProp3(values, (value, key) => value != null && keys.add(key));
}
var ACTIVE_EVENTS = [
"onStart",
"onRest",
"onChange",
"onPause",
"onResume"
];
function mergeActiveFn(target, props, type) {
target.animation[type] = props[type] !== getDefaultProp(props, type) ? resolveProp(props[type], target.key) : void 0;
}
function sendEvent(target, type, ...args) {
target.animation[type]?.(...args);
target.defaultProps[type]?.(...args);
}
// src/Controller.ts
import {
is as is6,
raf as raf4,
each as each3,
noop,
flush as flush2,
toArray as toArray3,
eachProp as eachProp4,
flushCalls as flushCalls2,
addFluidObserver as addFluidObserver2
} from "@react-spring/shared";
var BATCHED_EVENTS = ["onStart", "onChange", "onRest"];
var nextId2 = 1;
var Controller = class {
constructor(props, flush3) {
this.id = nextId2++;
/** The animated values */
this.springs = {};
/** The queue of props passed to the `update` method. */
this.queue = [];
/** The counter for tracking `scheduleProps` calls */
this._lastAsyncId = 0;
/** The values currently being animated */
this._active = /* @__PURE__ */ new Set();
/** The values that changed recently */
this._changed = /* @__PURE__ */ new Set();
/** Equals false when `onStart` listeners can be called */
this._started = false;
/** State used by the `runAsync` function */
this._state = {
paused: false,
pauseQueue: /* @__PURE__ */ new Set(),
resumeQueue: /* @__PURE__ */ new Set(),
timeouts: /* @__PURE__ */ new Set()
};
/** The event queues that are flushed once per frame maximum */
this._events = {
onStart: /* @__PURE__ */ new Map(),
onChange: /* @__PURE__ */ new Map(),
onRest: /* @__PURE__ */ new Map()
};
this._onFrame = this._onFrame.bind(this);
if (flush3) {
this._flush = flush3;
}
if (props) {
this.start({ default: true, ...props });
}
}
/**
* Equals `true` when no spring values are in the frameloop, and
* no async animation is currently active.
*/
get idle() {
return !this._state.asyncTo && Object.values(this.springs).every((spring) => {
return spring.idle && !spring.isDelayed && !spring.isPaused;
});
}
get item() {
return this._item;
}
set item(item) {
this._item = item;
}
/** Get the current values of our springs */
get() {
const values = {};
this.each((spring, key) => values[key] = spring.get());
return values;
}
/** Set the current values without animating. */
set(values) {
for (const key in values) {
const value = values[key];
if (!is6.und(value)) {
this.springs[key].set(value);
}
}
}
/** Push an update onto the queue of each value. */
update(props) {
if (props) {
this.queue.push(createUpdate(props));
}
return this;
}
/**
* Start the queued animations for every spring, and resolve the returned
* promise once all queued animations have finished or been cancelled.
*
* When you pass a queue (instead of nothing), that queue is used instead of
* the queued animations added with the `update` method, which are left alone.
*/
start(props) {
let { queue } = this;
if (props) {
queue = toArray3(props).map(createUpdate);
} else {
this.queue = [];
}
if (this._flush) {
return this._flush(this, queue);
}
prepareKeys(this, queue);
return flushUpdateQueue(this, queue);
}
/** @internal */
stop(arg, keys) {
if (arg !== !!arg) {
keys = arg;
}
if (keys) {
const springs = this.springs;
each3(toArray3(keys), (key) => springs[key].stop(!!arg));
} else {
stopAsync(this._state, this._lastAsyncId);
this.each((spring) => spring.stop(!!arg));
}
return this;
}
/** Freeze the active animation in time */
pause(keys) {
if (is6.und(keys)) {
this.start({ pause: true });
} else {
const springs = this.springs;
each3(toArray3(keys), (key) => springs[key].pause());
}
return this;
}
/** Resume the animation if paused. */
resume(keys) {
if (is6.und(keys)) {
this.start({ pause: false });
} else {
const springs = this.springs;
each3(toArray3(keys), (key) => springs[key].resume());
}
return this;
}
/** Call a function once per spring value */
each(iterator) {
eachProp4(this.springs, iterator);
}
/** @internal Called at the end of every animation frame */
_onFrame() {
const { onStart, onChange, onRest } = this._events;
const active = this._active.size > 0;
const changed = this._changed.size > 0;
if (active && !this._started || changed && !this._started) {
this._started = true;
flush2(onStart, ([onStart2, result]) => {
result.value = this.get();
onStart2(result, this, this._item);
});
}
const idle = !active && this._started;
const values = changed || idle && onRest.size ? this.get() : null;
if (changed && onChange.size) {
flush2(onChange, ([onChange2, result]) => {
result.value = values;
onChange2(result, this, this._item);
});
}
if (idle) {
this._started = false;
flush2(onRest, ([onRest2, result]) => {
result.value = values;
onRest2(result, this, this._item);
});
}
}
/** @internal */
eventObserved(event) {
if (event.type == "change") {
this._changed.add(event.parent);
if (!event.idle) {
this._active.add(event.parent);
}
} else if (event.type == "idle") {
this._active.delete(event.parent);
} else
return;
raf4.onFrame(this._onFrame);
}
};
function flushUpdateQueue(ctrl, queue) {
return Promise.all(queue.map((props) => flushUpdate(ctrl, props))).then(
(results) => getCombinedResult(ctrl, results)
);
}
async function flushUpdate(ctrl, props, isLoop) {
const { keys, to: to2, from, loop, onRest, onResolve } = props;
const defaults2 = is6.obj(props.default) && props.default;
if (loop) {
props.loop = false;
}
if (to2 === false)
props.to = null;
if (from === false)
props.from = null;
const asyncTo = is6.arr(to2) || is6.fun(to2) ? to2 : void 0;
if (asyncTo) {
props.to = void 0;
props.onRest = void 0;
if (defaults2) {
defaults2.onRest = void 0;
}
} else {
each3(BATCHED_EVENTS, (key) => {
const handler = props[key];
if (is6.fun(handler)) {
const queue = ctrl["_events"][key];
props[key] = ({ finished, cancelled }) => {
const result2 = queue.get(handler);
if (result2) {
if (!finished)
result2.finished = false;
if (cancelled)
result2.cancelled = true;
} else {
queue.set(handler, {
value: null,
finished: finished || false,
cancelled: cancelled || false
});
}
};
if (defaults2) {
defaults2[key] = props[key];
}
}
});
}
const state = ctrl["_state"];
if (props.pause === !state.paused) {
state.paused = props.pause;
flushCalls2(props.pause ? state.pauseQueue : state.resumeQueue);
} else if (state.paused) {
props.pause = true;
}
const promises = (keys || Object.keys(ctrl.springs)).map(
(key) => ctrl.springs[key].start(props)
);
const cancel = props.cancel === true || getDefaultProp(props, "cancel") === true;
if (asyncTo || cancel && state.asyncId) {
promises.push(
scheduleProps(++ctrl["_lastAsyncId"], {
props,
state,
actions: {
pause: noop,
resume: noop,
start(props2, resolve) {
if (cancel) {
stopAsync(state, ctrl["_lastAsyncId"]);
resolve(getCancelledResult(ctrl));
} else {
props2.onRest = onRest;
resolve(
runAsync(
asyncTo,
props2,
state,
ctrl
)
);
}
}
}
})
);
}
if (state.paused) {
await new Promise((resume) => {
state.resumeQueue.add(resume);
});
}
const result = getCombinedResult(ctrl, await Promise.all(promises));
if (loop && result.finished && !(isLoop && result.noop)) {
const nextProps = createLoopUpdate(props, loop, to2);
if (nextProps) {
prepareKeys(ctrl, [nextProps]);
return flushUpdate(ctrl, nextProps, true);
}
}
if (onResolve) {
raf4.batchedUpdates(() => onResolve(result, ctrl, ctrl.item));
}
return result;
}
function getSprings(ctrl, props) {
const springs = { ...ctrl.springs };
if (props) {
each3(toArray3(props), (props2) => {
if (is6.und(props2.keys)) {
props2 = createUpdate(props2);
}
if (!is6.obj(props2.to)) {
props2 = { ...props2, to: void 0 };
}
prepareSprings(springs, props2, (key) => {
return createSpring(key);
});
});
}
setSprings(ctrl, springs);
return springs;
}
function setSprings(ctrl, springs) {
eachProp4(springs, (spring, key) => {
if (!ctrl.springs[key]) {
ctrl.springs[key] = spring;
addFluidObserver2(spring, ctrl);
}
});
}
function createSpring(key, observer) {
const spring = new SpringValue();
spring.key = key;
if (observer) {
addFluidObserver2(spring, observer);
}
return spring;
}
function prepareSprings(springs, props, create) {
if (props.keys) {
each3(props.keys, (key) => {
const spring = springs[key] || (springs[key] = create(key));
spring["_prepareNode"](props);
});
}
}
function prepareKeys(ctrl, queue) {
each3(queue, (props) => {
prepareSprings(ctrl.springs, props, (key) => {
return createSpring(key, ctrl);
});
});
}
// src/SpringContext.tsx
import * as React from "react";
import { useContext } from "react";
import { useMemoOne } from "@react-spring/shared";
var SpringContext = ({
children,
...props
}) => {
const inherited = useContext(ctx);
const pause = props.pause || !!inherited.pause, immediate = props.immediate || !!inherited.immediate;
props = useMemoOne(() => ({ pause, immediate }), [pause, immediate]);
const { Provider } = ctx;
return /* @__PURE__ */ React.createElement(Provider, { value: props }, children);
};
var ctx = makeContext(SpringContext, {});
SpringContext.Provider = ctx.Provider;
SpringContext.Consumer = ctx.Consumer;
function makeContext(target, init) {
Object.assign(target, React.createContext(init));
target.Provider._context = target;
target.Consumer._context = target;
return target;
}
// src/SpringRef.ts
import { each as each4, is as is7, deprecateDirectCall } from "@react-spring/shared";
var SpringRef = () => {
const current = [];
const SpringRef2 = function(props) {
deprecateDirectCall();
const results = [];
each4(current, (ctrl, i) => {
if (is7.und(props)) {
results.push(ctrl.start());
} else {
const update2 = _getProps(props, ctrl, i);
if (update2) {
results.push(ctrl.start(update2));
}
}
});
return results;
};
SpringRef2.current = current;
SpringRef2.add = function(ctrl) {
if (!current.includes(ctrl)) {
current.push(ctrl);
}
};
SpringRef2.delete = function(ctrl) {
const i = current.indexOf(ctrl);
if (~i)
current.splice(i, 1);
};
SpringRef2.pause = function() {
each4(current, (ctrl) => ctrl.pause(...arguments));
return this;
};
SpringRef2.resume = function() {
each4(current, (ctrl) => ctrl.resume(...arguments));
return this;
};
SpringRef2.set = function(values) {
each4(current, (ctrl, i) => {
const update2 = is7.fun(values) ? values(i, ctrl) : values;
if (update2) {
ctrl.set(update2);
}
});
};
SpringRef2.start = function(props) {
const results = [];
each4(current, (ctrl, i) => {
if (is7.und(props)) {
results.push(ctrl.start());
} else {
const update2 = this._getProps(props, ctrl, i);
if (update2) {
results.push(ctrl.start(update2));
}
}
});
return results;
};
SpringRef2.stop = function() {
each4(current, (ctrl) => ctrl.stop(...arguments));
return this;
};
SpringRef2.update = function(props) {
each4(current, (ctrl, i) => ctrl.update(this._getProps(props, ctrl, i)));
return this;
};
const _getProps = function(arg, ctrl, index) {
return is7.fun(arg) ? arg(index, ctrl) : arg;
};
SpringRef2._getProps = _getProps;
return SpringRef2;
};
// src/hooks/useSprings.ts
function useSprings(length, props, deps) {
const propsFn = is8.fun(props) && props;
if (propsFn && !deps)
deps = [];
const ref = useMemo(
() => propsFn || arguments.length == 3 ? SpringRef() : void 0,
[]
);
const layoutId = useRef(0);
const forceUpdate = useForceUpdate();
const state = useMemo(
() => ({
ctrls: [],
queue: [],
flush(ctrl, updates2) {
const springs2 = getSprings(ctrl, updates2);
const canFlushSync = layoutId.current > 0 && !state.queue.length && !Object.keys(springs2).some((key) => !ctrl.springs[key]);
return canFlushSync ? flushUpdateQueue(ctrl, updates2) : new Promise((resolve) => {
setSprings(ctrl, springs2);
state.queue.push(() => {
resolve(flushUpdateQueue(ctrl, updates2));
});
forceUpdate();
});
}
}),
[]
);
const ctrls = useRef([...state.ctrls]);
const updates = [];
const prevLength = usePrev(length) || 0;
useMemo(() => {
each5(ctrls.current.slice(length, prevLength), (ctrl) => {
detachRefs(ctrl, ref);
ctrl.stop(true);
});
ctrls.current.length = length;
declareUpdates(prevLength, length);
}, [length]);
useMemo(() => {
declareUpdates(0, Math.min(prevLength, length));
}, deps);
function declareUpdates(startIndex, endIndex) {
for (let i = startIndex; i < endIndex; i++) {
const ctrl = ctrls.current[i] || (ctrls.current[i] = new Controller(null, state.flush));
const update2 = propsFn ? propsFn(i, ctrl) : props[i];
if (update2) {
updates[i] = declareUpdate(update2);
}
}
}
const springs = ctrls.current.map((ctrl, i) => getSprings(ctrl, updates[i]));
const context = useContext2(SpringContext);
const prevContext = usePrev(context);
const hasContext = context !== prevContext && hasProps(context);
useIsomorphicLayoutEffect2(() => {
layoutId.current++;
state.ctrls = ctrls.current;
const { queue } = state;
if (queue.length) {
state.queue = [];
each5(queue, (cb) => cb());
}
each5(ctrls.current, (ctrl, i) => {
ref?.add(ctrl);
if (hasContext) {
ctrl.start({ default: context });
}
const update2 = updates[i];
if (update2) {
replaceRef(ctrl, update2.ref);
if (ctrl.ref) {
ctrl.queue.push(update2);
} else {
ctrl.start(update2);
}
}
});
});
useOnce(() => () => {
each5(state.ctrls, (ctrl) => ctrl.stop(true));
});
const values = springs.map((x) => ({ ...x }));
return ref ? [values, ref] : values;
}
// src/hooks/useSpring.ts
function useSpring(props, deps) {
const isFn = is9.fun(props);
const [[values], ref] = useSprings(
1,
isFn ? props : [props],
isFn ? deps || [] : deps
);
return isFn || arguments.length == 2 ? [values, ref] : values;
}
// src/hooks/useSpringRef.ts
import { useState } from "react";
var initSpringRef = () => SpringRef();
var useSpringRef = () => useState(initSpringRef)[0];
// src/hooks/useSpringValue.ts
import { useConstant, useOnce as useOnce2 } from "@react-spring/shared";
var useSpringValue = (initial, props) => {
const springValue = useConstant(() => new SpringValue(initial, props));
useOnce2(() => () => {
springValue.stop();
});
return springValue;
};
// src/hooks/useTrail.ts
import { each as each6, is as is10, useIsomorphicLayoutEffect as useIsomorphicLayoutEffect3 } from "@react-spring/shared";
function useTrail(length, propsArg, deps) {
const propsFn = is10.fun(propsArg) && propsArg;
if (propsFn && !deps)
deps = [];
let reverse = true;
let passedRef = void 0;
const result = useSprings(
length,
(i, ctrl) => {
const props = propsFn ? propsFn(i, ctrl) : propsArg;
passedRef = props.ref;
reverse = reverse && props.reverse;
return props;
},
// Ensure the props function is called when no deps exist.
// This works around the 3 argument rule.
deps || [{}]
);
useIsomorphicLayoutEffect3(() => {
each6(result[1].current, (ctrl, i) => {
const parent = result[1].current[i + (reverse ? 1 : -1)];
replaceRef(ctrl, passedRef);
if (ctrl.ref) {
if (parent) {
ctrl.update({ to: parent.springs });
}
return;
}
if (parent) {
ctrl.start({ to: parent.springs });
} else {
ctrl.start();
}
});
}, deps);
if (propsFn || arguments.length == 3) {
const ref = passedRef ?? result[1];
ref["_getProps"] = (propsArg2, ctrl, i) => {
const props = is10.fun(propsArg2) ? propsArg2(i, ctrl) : propsArg2;
if (props) {
const parent = ref.current[i + (props.reverse ? 1 : -1)];
if (parent)
props.to = parent.springs;
return props;
}
};
return result;
}
return result[0];
}
// src/hooks/useTransition.tsx
import * as React2 from "react";
import { useContext as useContext3, useRef as useRef2, useMemo as useMemo2 } from "react";
import {
is as is11,
toArray as toArray4,
useForceUpdate as useForceUpdate2,
useOnce as useOnce3,
usePrev as usePrev2,
each as each7,
useIsomorphicLayoutEffect as useIsomorphicLayoutEffect4
} from "@react-spring/shared";
function useTransition(data, props, deps) {
const propsFn = is11.fun(props) && props;
const {
reset,
sort,
trail = 0,
expires = true,
exitBeforeEnter = false,
onDestroyed,
ref: propsRef,
config: propsConfig
} = propsFn ? propsFn() : props;
const ref = useMemo2(
() => propsFn || arguments.length == 3 ? SpringRef() : void 0,
[]
);
const items = toArray4(data);
const transitions = [];
const usedTransitions = useRef2(null);
const prevTransitions = reset ? null : usedTransitions.current;
useIsomorphicLayoutEffect4(() => {
usedTransitions.current = transitions;
});
useOnce3(() => {
each7(transitions, (t) => {
ref?.add(t.ctrl);
t.ctrl.ref = ref;
});
return () => {
each7(usedTransitions.current, (t) => {
if (t.expired) {
clearTimeout(t.expirationId);
}
detachRefs(t.ctrl, ref);
t.ctrl.stop(true);
});
};
});
const keys = getKeys(items, propsFn ? propsFn() : props, prevTransitions);
const expired = reset && usedTransitions.current || [];
useIsomorphicLayoutEffect4(
() => each7(expired, ({ ctrl, item, key }) => {
detachRefs(ctrl, ref);
callProp(onDestroyed, item, key);
})
);
const reused = [];
if (prevTransitions)
each7(prevTransitions, (t, i) => {
if (t.expired) {
clearTimeout(t.expirationId);
expired.push(t);
} else {
i = reused[i] = keys.indexOf(t.key);
if (~i)
transitions[i] = t;
}
});
each7(items, (item, i) => {
if (!transitions[i]) {
transitions[i] = {
key: keys[i],
item,
phase: "mount" /* MOUNT */,
ctrl: new Controller()
};
transitions[i].ctrl.item = item;
}
});
if (reused.length) {
let i = -1;
const { leave } = propsFn ? propsFn() : props;
each7(reused, (keyIndex, prevIndex) => {
const t = prevTransitions[prevIndex];
if (~keyIndex) {
i = transitions.indexOf(t);
transitions[i] = { ...t, item: items[keyIndex] };
} else if (leave) {
transitions.splice(++i, 0, t);
}
});
}
if (is11.fun(sort)) {
transitions.sort((a, b) => sort(a.item, b.item));
}
let delay = -trail;
const forceUpdate = useForceUpdate2();
const defaultProps = getDefaultProps(props);
const changes = /* @__PURE__ */ new Map();
const exitingTransitions = useRef2(/* @__PURE__ */ new Map());
const forceChange = useRef2(false);
each7(transitions, (t, i) => {
const key = t.key;
const prevPhase = t.phase;
const p = propsFn ? propsFn() : props;
let to2;
let phase;
const propsDelay = callProp(p.delay || 0, key);
if (prevPhase == "mount" /* MOUNT */) {
to2 = p.enter;
phase = "enter" /* ENTER */;
} else {
const isLeave = keys.indexOf(key) < 0;
if (prevPhase != "leave" /* LEAVE */) {
if (isLeave) {
to2 = p.leave;
phase = "leave" /* LEAVE */;
} else if (to2 = p.update) {
phase = "update" /* UPDATE */;
} else
return;
} else if (!isLeave) {
to2 = p.enter;
phase = "enter" /* ENTER */;
} else
return;
}
to2 = callProp(to2, t.item, i);
to2 = is11.obj(to2) ? inferTo(to2) : { to: to2 };
if (!to2.config) {
const config2 = propsConfig || defaultProps.config;
to2.config = callProp(config2, t.item, i, phase);
}
delay += trail;
const payload = {
...defaultProps,
// we need to add our props.delay value you here.
delay: propsDelay + delay,
ref: propsRef,
immediate: p.immediate,
// This prevents implied resets.
reset: false,
// Merge any phase-specific props.
...to2
};
if (phase == "enter" /* ENTER */ && is11.und(payload.from)) {
const p2 = propsFn ? propsFn() : props;
const from = is11.und(p2.initial) || prevTransitions ? p2.from : p2.initial;
payload.from = callProp(from, t.item, i);
}
const { onResolve } = payload;
payload.onResolve = (result) => {
callProp(onResolve, result);
const transitions2 = usedTransitions.current;
const t2 = transitions2.find((t3) => t3.key === key);
if (!t2)
return;
if (result.cancelled && t2.phase != "update" /* UPDATE */) {
return;
}
if (t2.ctrl.idle) {
const idle = transitions2.every((t3) => t3.ctrl.idle);
if (t2.phase == "leave" /* LEAVE */) {
const expiry = callProp(expires, t2.item);
if (expiry !== false) {
const expiryMs = expiry === true ? 0 : expiry;
t2.expired = true;
if (!idle && expiryMs > 0) {
if (expiryMs <= 2147483647)
t2.expirationId = setTimeout(forceUpdate, expiryMs);
return;
}
}
}
if (idle && transitions2.some((t3) => t3.expired)) {
exitingTransitions.current.delete(t2);
if (exitBeforeEnter) {
forceChange.current = true;
}
forceUpdate();
}
}
};
const springs = getSprings(t.ctrl, payload);
if (phase === "leave" /* LEAVE */ && exitBeforeEnter) {
exitingTransitions.current.set(t, { phase, springs, payload });
} else {
changes.set(t, { phase, springs, payload });
}
});
const context = useContext3(SpringContext);
const prevContext = usePrev2(context);
const hasContext = context !== prevContext && hasProps(context);
useIsomorphicLayoutEffect4(() => {
if (hasContext) {
each7(transitions, (t) => {
t.ctrl.start({ default: context });
});
}
}, [context]);
each7(changes, (_, t) => {
if (exitingTransitions.current.size) {
const ind = transitions.findIndex((state) => state.key === t.key);
transitions.splice(ind, 1);
}
});
useIsomorphicLayoutEffect4(
() => {
each7(
exitingTransitions.current.size ? exitingTransitions.current : changes,
({ phase, payload }, t) => {
const { ctrl } = t;
t.phase = phase;
ref?.add(ctrl);
if (hasContext && phase == "enter" /* ENTER */) {
ctrl.start({ default: context });
}
if (payload) {
replaceRef(ctrl, payload.ref);
if ((ctrl.ref || ref) && !forceChange.current) {
ctrl.update(payload);
} else {
ctrl.start(payload);
if (forceChange.current) {
forceChange.current = false;
}
}
}
}
);
},
reset ? void 0 : deps
);
const renderTransitions = (render) => /* @__PURE__ */ React2.createElement(React2.Fragment, null, transitions.map((t, i) => {
const { springs } = changes.get(t) || t.ctrl;
const elem = render({ ...springs }, t.item, t, i);
return elem && elem.type ? /* @__PURE__ */ React2.createElement(
elem.type,
{
...elem.props,
key: is11.str(t.key) || is11.num(t.key) ? t.key : t.ctrl.id,
ref: elem.ref
}
) : elem;
}));
return ref ? [renderTransitions, ref] : renderTransitions;
}
var nextKey = 1;
function getKeys(items, { key, keys = key }, prevTransitions) {
if (keys === null) {
const reused = /* @__PURE__ */ new Set();
return items.map((item) => {
const t = prevTransitions && prevTransitions.find(
(t2) => t2.item === item && t2.phase !== "leave" /* LEAVE */ && !reused.has(t2)
);
if (t) {
reused.add(t);
return t.key;
}
return nextKey++;
});
}
return is11.und(keys) ? items : is11.fun(keys) ? items.map(keys) : toArray4(keys);
}
// src/hooks/useScroll.ts
import { each as each8, onScroll, useIsomorphicLayoutEffect as useIsomorphicLayoutEffect5 } from "@react-spring/shared";
var useScroll = ({
container,
...springOptions
} = {}) => {
const [scrollValues, api] = useSpring(
() => ({
scrollX: 0,
scrollY: 0,
scrollXProgress: 0,
scrollYProgress: 0,
...springOptions
}),
[]
);
useIsomorphicLayoutEffect5(() => {
const cleanupScroll = onScroll(
({ x, y }) => {
api.start({
scrollX: x.current,
scrollXProgress: x.progress,
scrollY: y.current,
scrollYProgress: y.progress
});
},
{ container: container?.current || void 0 }
);
return () => {
each8(Object.values(scrollValues), (value) => value.stop());
cleanupScroll();
};
}, []);
return scrollValues;
};
// src/hooks/useResize.ts
import { onResize, each as each9, useIsomorphicLayoutEffect as useIsomorphicLayoutEffect6 } from "@react-spring/shared";
var useResize = ({
container,
...springOptions
}) => {
const [sizeValues, api] = useSpring(
() => ({
width: 0,
height: 0,
...springOptions
}),
[]
);
useIsomorphicLayoutEffect6(() => {
const cleanupScroll = onResize(
({ width, height }) => {
api.start({
width,
height,
immediate: sizeValues.width.get() === 0 || sizeValues.height.get() === 0
});
},
{ container: container?.current || void 0 }
);
return () => {
each9(Object.values(sizeValues), (value) => value.stop());
cleanupScroll();
};
}, []);
return sizeValues;
};
// src/hooks/useInView.ts
import { useRef as useRef3, useState as useState2 } from "react";
import { is as is12, useIsomorphicLayoutEffect as useIsomorphicLayoutEffect7 } from "@react-spring/shared";
var defaultThresholdOptions = {
any: 0,
all: 1
};
function useInView(props, args) {
const [isInView, setIsInView] = useState2(false);
const ref = useRef3();
const propsFn = is12.fun(props) && props;
const springsProps = propsFn ? propsFn() : {};
const { to: to2 = {}, from = {}, ...restSpringProps } = springsProps;
const intersectionArguments = propsFn ? args : props;
const [springs, api] = useSpring(() => ({ from, ...restSpringProps }), []);
useIsomorphicLayoutEffect7(() => {
const element = ref.current;
const {
root,
once,
amount = "any",
...restArgs
} = intersectionArguments ?? {};
if (!element || once && isInView || typeof IntersectionObserver === "undefined")
return;
const activeIntersections = /* @__PURE__ */ new WeakMap();
const onEnter = () => {
if (to2) {
api.start(to2);
}
setIsInView(true);
const cleanup = () => {
if (from) {
api.start(from);
}
setIsInView(false);
};
return once ? void 0 : cleanup;
};
const handleIntersection = (entries) => {
entries.forEach((entry) => {
const onLeave = activeIntersections.get(entry.target);
if (entry.isIntersecting === Boolean(onLeave)) {
return;
}
if (entry.isIntersecting) {
const newOnLeave = onEnter();
if (is12.fun(newOnLeave)) {
activeIntersections.set(entry.target, newOnLeave);
} else {
observer.unobserve(entry.target);
}
} else if (onLeave) {
onLeave();
activeIntersections.delete(entry.target);
}
});
};
const observer = new IntersectionObserver(handleIntersection, {
root: root && root.current || void 0,
threshold: typeof amount === "number" || Array.isArray(amount) ? amount : defaultThresholdOptions[amount],
...restArgs
});
observer.observe(element);
return () => observer.unobserve(element);
}, [intersectionArguments]);
if (propsFn) {
return [ref, springs];
}
return [ref, isInView];
}
// src/components/Spring.tsx
function Spring({ children, ...props }) {
return children(useSpring(props));
}
// src/components/Trail.tsx
import { is as is13 } from "@react-spring/shared";
function Trail({
items,
children,
...props
}) {
const trails = useTrail(items.length, props);
return items.map((item, index) => {
const result = children(item, index);
return is13.fun(result) ? result(trails[index]) : result;
});
}
// src/components/Transition.tsx
function Transition({
items,
children,
...props
}) {
return useTransition(items, props)(children);
}
// src/interpolate.ts
import { deprecateInterpolate as deprecateInterpolate2 } from "@react-spring/shared";
// src/Interpolation.ts
import {
is as is14,
raf as raf5,
each as each10,
isEqual as isEqual2,
toArray as toArray5,
frameLoop as frameLoop3,
getFluidValue as getFluidValue3,
createInterpolator,
Globals as G6,
callFluidObservers as callFluidObservers3,
addFluidObserver as addFluidObserver3,
removeFluidObserver as removeFluidObserver2,
hasFluidValue as hasFluidValue2
} from "@react-spring/shared";
import {
getAnimated as getAnimated3,
setAnimated as setAnimated2,
getAnimatedType as getAnimatedType2,
getPayload as getPayload2
} from "@react-spring/animated";
var Interpolation = class extends FrameValue {
constructor(source, args) {
super();
this.source = source;
/** Equals false when in the frameloop */
this.idle = true;
/** The inputs which are currently animating */
this._active = /* @__PURE__ */ new Set();
this.calc = createInterpolator(...args);
const value = this._get();
const nodeType = getAnimatedType2(value);
setAnimated2(this, nodeType.create(value));
}
advance(_dt) {
const value = this._get();
const oldValue = this.get();
if (!isEqual2(value, oldValue)) {
getAnimated3(this).setValue(value);
this._onChange(value, this.idle);
}
if (!this.idle && checkIdle(this._active)) {
becomeIdle(this);
}
}
_get() {
const inputs = is14.arr(this.source) ? this.source.map(getFluidValue3) : toArray5(getFluidValue3(this.source));
return this.calc(...inputs);
}
_start() {
if (this.idle && !checkIdle(this._active)) {
this.idle = false;
each10(getPayload2(this), (node) => {
node.done = false;
});
if (G6.skipAnimation) {
raf5.batchedUpdates(() => this.advance());
becomeIdle(this);
} else {
frameLoop3.start(this);
}
}
}
// Observe our sources only when we're observed.
_attach() {
let priority = 1;
each10(toArray5(this.source), (source) => {
if (hasFluidValue2(source)) {
addFluidObserver3(source, this);
}
if (isFrameValue(source)) {
if (!source.idle) {
this._active.add(source);
}
priority = Math.max(priority, source.priority + 1);
}
});
this.priority = priority;
this._start();
}
// Stop observing our sources once we have no observers.
_detach() {
each10(toArray5(this.source), (source) => {
if (hasFluidValue2(source)) {
removeFluidObserver2(source, this);
}
});
this._active.clear();
becomeIdle(this);
}
/** @internal */
eventObserved(event) {
if (event.type == "change") {
if (event.idle) {
this.advance();
} else {
this._active.add(event.parent);
this._start();
}
} else if (event.type == "idle") {
this._active.delete(event.parent);
} else if (event.type == "priority") {
this.priority = toArray5(this.source).reduce(
(highest, parent) => Math.max(highest, (isFrameValue(parent) ? parent.priority : 0) + 1),
0
);
}
}
};
function isIdle(source) {
return source.idle !== false;
}
function checkIdle(active) {
return !active.size || Array.from(active).every(isIdle);
}
function becomeIdle(self) {
if (!self.idle) {
self.idle = true;
each10(getPayload2(self), (node) => {
node.done = true;
});
callFluidObservers3(self, {
type: "idle",
parent: self
});
}
}
// src/interpolate.ts
var to = (source, ...args) => new Interpolation(source, args);
var interpolate = (source, ...args) => (deprecateInterpolate2(), new Interpolation(source, args));
// src/globals.ts
import {
Globals,
frameLoop as frameLoop4,
createStringInterpolator
} from "@react-spring/shared";
Globals.assign({
createStringInterpolator,
to: (source, args) => new Interpolation(source, args)
});
var update = frameLoop4.advance;
// src/index.ts
import {
createInterpolator as createInterpolator2,
useIsomorphicLayoutEffect as useIsomorphicLayoutEffect8,
useReducedMotion,
easings as easings2
} from "@react-spring/shared";
export * from "@react-spring/types";
export {
BailSignal,
Controller,
FrameValue,
Globals,
Interpolation,
Spring,
SpringContext,
SpringRef,
SpringValue,
Trail,
Transition,
config,
createInterpolator2 as createInterpolator,
easings2 as easings,
inferTo,
interpolate,
to,
update,
useChain,
useInView,
useIsomorphicLayoutEffect8 as useIsomorphicLayoutEffect,
useReducedMotion,
useResize,
useScroll,
useSpring,
useSpringRef,
useSpringValue,
useSprings,
useTrail,
useTransition
};
//# sourceMappingURL=react-spring_core.modern.mjs.map
webpack://frontend-mybets/../../node_modules/@react-spring/web/node_modules/@react-spring/rafz/dist/react-spring_rafz.modern.mjs
// src/index.ts
var updateQueue = makeQueue();
var raf = (fn) => schedule(fn, updateQueue);
var writeQueue = makeQueue();
raf.write = (fn) => schedule(fn, writeQueue);
var onStartQueue = makeQueue();
raf.onStart = (fn) => schedule(fn, onStartQueue);
var onFrameQueue = makeQueue();
raf.onFrame = (fn) => schedule(fn, onFrameQueue);
var onFinishQueue = makeQueue();
raf.onFinish = (fn) => schedule(fn, onFinishQueue);
var timeouts = [];
raf.setTimeout = (handler, ms) => {
const time = raf.now() + ms;
const cancel = () => {
const i = timeouts.findIndex((t) => t.cancel == cancel);
if (~i)
timeouts.splice(i, 1);
pendingCount -= ~i ? 1 : 0;
};
const timeout = { time, handler, cancel };
timeouts.splice(findTimeout(time), 0, timeout);
pendingCount += 1;
start();
return timeout;
};
var findTimeout = (time) => ~(~timeouts.findIndex((t) => t.time > time) || ~timeouts.length);
raf.cancel = (fn) => {
onStartQueue.delete(fn);
onFrameQueue.delete(fn);
onFinishQueue.delete(fn);
updateQueue.delete(fn);
writeQueue.delete(fn);
};
raf.sync = (fn) => {
sync = true;
raf.batchedUpdates(fn);
sync = false;
};
raf.throttle = (fn) => {
let lastArgs;
function queuedFn() {
try {
fn(...lastArgs);
} finally {
lastArgs = null;
}
}
function throttled(...args) {
lastArgs = args;
raf.onStart(queuedFn);
}
throttled.handler = fn;
throttled.cancel = () => {
onStartQueue.delete(queuedFn);
lastArgs = null;
};
return throttled;
};
var nativeRaf = typeof window != "undefined" ? window.requestAnimationFrame : (
// eslint-disable-next-line @typescript-eslint/no-empty-function
() => {
}
);
raf.use = (impl) => nativeRaf = impl;
raf.now = typeof performance != "undefined" ? () => performance.now() : Date.now;
raf.batchedUpdates = (fn) => fn();
raf.catch = console.error;
raf.frameLoop = "always";
raf.advance = () => {
if (raf.frameLoop !== "demand") {
console.warn(
"Cannot call the manual advancement of rafz whilst frameLoop is not set as demand"
);
} else {
update();
}
};
var ts = -1;
var pendingCount = 0;
var sync = false;
function schedule(fn, queue) {
if (sync) {
queue.delete(fn);
fn(0);
} else {
queue.add(fn);
start();
}
}
function start() {
if (ts < 0) {
ts = 0;
if (raf.frameLoop !== "demand") {
nativeRaf(loop);
}
}
}
function stop() {
ts = -1;
}
function loop() {
if (~ts) {
nativeRaf(loop);
raf.batchedUpdates(update);
}
}
function update() {
const prevTs = ts;
ts = raf.now();
const count = findTimeout(ts);
if (count) {
eachSafely(timeouts.splice(0, count), (t) => t.handler());
pendingCount -= count;
}
if (!pendingCount) {
stop();
return;
}
onStartQueue.flush();
updateQueue.flush(prevTs ? Math.min(64, ts - prevTs) : 16.667);
onFrameQueue.flush();
writeQueue.flush();
onFinishQueue.flush();
}
function makeQueue() {
let next = /* @__PURE__ */ new Set();
let current = next;
return {
add(fn) {
pendingCount += current == next && !next.has(fn) ? 1 : 0;
next.add(fn);
},
delete(fn) {
pendingCount -= current == next && next.has(fn) ? 1 : 0;
return next.delete(fn);
},
flush(arg) {
if (current.size) {
next = /* @__PURE__ */ new Set();
pendingCount -= current.size;
eachSafely(current, (fn) => fn(arg) && next.add(fn));
pendingCount += next.size;
current = next;
}
}
};
}
function eachSafely(values, each) {
values.forEach((value) => {
try {
each(value);
} catch (e) {
raf.catch(e);
}
});
}
var __raf = {
/** The number of pending tasks */
count() {
return pendingCount;
},
/** Whether there's a raf update loop running */
isRunning() {
return ts >= 0;
},
/** Clear internal state. Never call from update loop! */
clear() {
ts = -1;
timeouts = [];
onStartQueue = makeQueue();
updateQueue = makeQueue();
onFrameQueue = makeQueue();
writeQueue = makeQueue();
onFinishQueue = makeQueue();
pendingCount = 0;
}
};
export {
__raf,
raf
};
//# sourceMappingURL=react-spring_rafz.modern.mjs.map
webpack://frontend-mybets/../../node_modules/@react-spring/web/node_modules/@react-spring/shared/dist/react-spring_shared.modern.mjs
var __defProp = Object.defineProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
// src/globals.ts
var globals_exports = {};
__export(globals_exports, {
assign: () => assign,
colors: () => colors,
createStringInterpolator: () => createStringInterpolator,
skipAnimation: () => skipAnimation,
to: () => to,
willAdvance: () => willAdvance
});
import { raf } from "@react-spring/rafz";
// src/helpers.ts
function noop() {
}
var defineHidden = (obj, key, value) => Object.defineProperty(obj, key, { value, writable: true, configurable: true });
var is = {
arr: Array.isArray,
obj: (a) => !!a && a.constructor.name === "Object",
fun: (a) => typeof a === "function",
str: (a) => typeof a === "string",
num: (a) => typeof a === "number",
und: (a) => a === void 0
};
function isEqual(a, b) {
if (is.arr(a)) {
if (!is.arr(b) || a.length !== b.length)
return false;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i])
return false;
}
return true;
}
return a === b;
}
var each = (obj, fn) => obj.forEach(fn);
function eachProp(obj, fn, ctx) {
if (is.arr(obj)) {
for (let i = 0; i < obj.length; i++) {
fn.call(ctx, obj[i], `${i}`);
}
return;
}
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
fn.call(ctx, obj[key], key);
}
}
}
var toArray = (a) => is.und(a) ? [] : is.arr(a) ? a : [a];
function flush(queue, iterator) {
if (queue.size) {
const items = Array.from(queue);
queue.clear();
each(items, iterator);
}
}
var flushCalls = (queue, ...args) => flush(queue, (fn) => fn(...args));
var isSSR = () => typeof window === "undefined" || !window.navigator || /ServerSideRendering|^Deno\//.test(window.navigator.userAgent);
// src/globals.ts
var createStringInterpolator;
var to;
var colors = null;
var skipAnimation = false;
var willAdvance = noop;
var assign = (globals) => {
if (globals.to)
to = globals.to;
if (globals.now)
raf.now = globals.now;
if (globals.colors !== void 0)
colors = globals.colors;
if (globals.skipAnimation != null)
skipAnimation = globals.skipAnimation;
if (globals.createStringInterpolator)
createStringInterpolator = globals.createStringInterpolator;
if (globals.requestAnimationFrame)
raf.use(globals.requestAnimationFrame);
if (globals.batchedUpdates)
raf.batchedUpdates = globals.batchedUpdates;
if (globals.willAdvance)
willAdvance = globals.willAdvance;
if (globals.frameLoop)
raf.frameLoop = globals.frameLoop;
};
// src/FrameLoop.ts
import { raf as raf2 } from "@react-spring/rafz";
var startQueue = /* @__PURE__ */ new Set();
var currentFrame = [];
var prevFrame = [];
var priority = 0;
var frameLoop = {
get idle() {
return !startQueue.size && !currentFrame.length;
},
/** Advance the given animation on every frame until idle. */
start(animation) {
if (priority > animation.priority) {
startQueue.add(animation);
raf2.onStart(flushStartQueue);
} else {
startSafely(animation);
raf2(advance);
}
},
/** Advance all animations by the given time. */
advance,
/** Call this when an animation's priority changes. */
sort(animation) {
if (priority) {
raf2.onFrame(() => frameLoop.sort(animation));
} else {
const prevIndex = currentFrame.indexOf(animation);
if (~prevIndex) {
currentFrame.splice(prevIndex, 1);
startUnsafely(animation);
}
}
},
/**
* Clear all animations. For testing purposes.
*
* ☠️ Never call this from within the frameloop.
*/
clear() {
currentFrame = [];
startQueue.clear();
}
};
function flushStartQueue() {
startQueue.forEach(startSafely);
startQueue.clear();
raf2(advance);
}
function startSafely(animation) {
if (!currentFrame.includes(animation))
startUnsafely(animation);
}
function startUnsafely(animation) {
currentFrame.splice(
findIndex(currentFrame, (other) => other.priority > animation.priority),
0,
animation
);
}
function advance(dt) {
const nextFrame = prevFrame;
for (let i = 0; i < currentFrame.length; i++) {
const animation = currentFrame[i];
priority = animation.priority;
if (!animation.idle) {
willAdvance(animation);
animation.advance(dt);
if (!animation.idle) {
nextFrame.push(animation);
}
}
}
priority = 0;
prevFrame = currentFrame;
prevFrame.length = 0;
currentFrame = nextFrame;
return currentFrame.length > 0;
}
function findIndex(arr, test) {
const index = arr.findIndex(test);
return index < 0 ? arr.length : index;
}
// src/clamp.ts
var clamp = (min, max, v) => Math.min(Math.max(v, min), max);
// src/colors.ts
var colors2 = {
transparent: 0,
aliceblue: 4042850303,
antiquewhite: 4209760255,
aqua: 16777215,
aquamarine: 2147472639,
azure: 4043309055,
beige: 4126530815,
bisque: 4293182719,
black: 255,
blanchedalmond: 4293643775,
blue: 65535,
blueviolet: 2318131967,
brown: 2771004159,
burlywood: 3736635391,
burntsienna: 3934150143,
cadetblue: 1604231423,
chartreuse: 2147418367,
chocolate: 3530104575,
coral: 4286533887,
cornflowerblue: 1687547391,
cornsilk: 4294499583,
crimson: 3692313855,
cyan: 16777215,
darkblue: 35839,
darkcyan: 9145343,
darkgoldenrod: 3095792639,
darkgray: 2846468607,
darkgreen: 6553855,
darkgrey: 2846468607,
darkkhaki: 3182914559,
darkmagenta: 2332068863,
darkolivegreen: 1433087999,
darkorange: 4287365375,
darkorchid: 2570243327,
darkred: 2332033279,
darksalmon: 3918953215,
darkseagreen: 2411499519,
darkslateblue: 1211993087,
darkslategray: 793726975,
darkslategrey: 793726975,
darkturquoise: 13554175,
darkviolet: 2483082239,
deeppink: 4279538687,
deepskyblue: 12582911,
dimgray: 1768516095,
dimgrey: 1768516095,
dodgerblue: 512819199,
firebrick: 2988581631,
floralwhite: 4294635775,
forestgreen: 579543807,
fuchsia: 4278255615,
gainsboro: 3705462015,
ghostwhite: 4177068031,
gold: 4292280575,
goldenrod: 3668254975,
gray: 2155905279,
green: 8388863,
greenyellow: 2919182335,
grey: 2155905279,
honeydew: 4043305215,
hotpink: 4285117695,
indianred: 3445382399,
indigo: 1258324735,
ivory: 4294963455,
khaki: 4041641215,
lavender: 3873897215,
lavenderblush: 4293981695,
lawngreen: 2096890111,
lemonchiffon: 4294626815,
lightblue: 2916673279,
lightcoral: 4034953471,
lightcyan: 3774873599,
lightgoldenrodyellow: 4210742015,
lightgray: 3553874943,
lightgreen: 2431553791,
lightgrey: 3553874943,
lightpink: 4290167295,
lightsalmon: 4288707327,
lightseagreen: 548580095,
lightskyblue: 2278488831,
lightslategray: 2005441023,
lightslategrey: 2005441023,
lightsteelblue: 2965692159,
lightyellow: 4294959359,
lime: 16711935,
limegreen: 852308735,
linen: 4210091775,
magenta: 4278255615,
maroon: 2147483903,
mediumaquamarine: 1724754687,
mediumblue: 52735,
mediumorchid: 3126187007,
mediumpurple: 2473647103,
mediumseagreen: 1018393087,
mediumslateblue: 2070474495,
mediumspringgreen: 16423679,
mediumturquoise: 1221709055,
mediumvioletred: 3340076543,
midnightblue: 421097727,
mintcream: 4127193855,
mistyrose: 4293190143,
moccasin: 4293178879,
navajowhite: 4292783615,
navy: 33023,
oldlace: 4260751103,
olive: 2155872511,
olivedrab: 1804477439,
orange: 4289003775,
orangered: 4282712319,
orchid: 3664828159,
palegoldenrod: 4008225535,
palegreen: 2566625535,
paleturquoise: 2951671551,
palevioletred: 3681588223,
papayawhip: 4293907967,
peachpuff: 4292524543,
peru: 3448061951,
pink: 4290825215,
plum: 3718307327,
powderblue: 2967529215,
purple: 2147516671,
rebeccapurple: 1714657791,
red: 4278190335,
rosybrown: 3163525119,
royalblue: 1097458175,
saddlebrown: 2336560127,
salmon: 4202722047,
sandybrown: 4104413439,
seagreen: 780883967,
seashell: 4294307583,
sienna: 2689740287,
silver: 3233857791,
skyblue: 2278484991,
slateblue: 1784335871,
slategray: 1887473919,
slategrey: 1887473919,
snow: 4294638335,
springgreen: 16744447,
steelblue: 1182971135,
tan: 3535047935,
teal: 8421631,
thistle: 3636451583,
tomato: 4284696575,
turquoise: 1088475391,
violet: 4001558271,
wheat: 4125012991,
white: 4294967295,
whitesmoke: 4126537215,
yellow: 4294902015,
yellowgreen: 2597139199
};
// src/colorMatchers.ts
var NUMBER = "[-+]?\\d*\\.?\\d+";
var PERCENTAGE = NUMBER + "%";
function call(...parts) {
return "\\(\\s*(" + parts.join(")\\s*,\\s*(") + ")\\s*\\)";
}
var rgb = new RegExp("rgb" + call(NUMBER, NUMBER, NUMBER));
var rgba = new RegExp("rgba" + call(NUMBER, NUMBER, NUMBER, NUMBER));
var hsl = new RegExp("hsl" + call(NUMBER, PERCENTAGE, PERCENTAGE));
var hsla = new RegExp(
"hsla" + call(NUMBER, PERCENTAGE, PERCENTAGE, NUMBER)
);
var hex3 = /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/;
var hex4 = /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/;
var hex6 = /^#([0-9a-fA-F]{6})$/;
var hex8 = /^#([0-9a-fA-F]{8})$/;
// src/normalizeColor.ts
function normalizeColor(color) {
let match;
if (typeof color === "number") {
return color >>> 0 === color && color >= 0 && color <= 4294967295 ? color : null;
}
if (match = hex6.exec(color))
return parseInt(match[1] + "ff", 16) >>> 0;
if (colors && colors[color] !== void 0) {
return colors[color];
}
if (match = rgb.exec(color)) {
return (parse255(match[1]) << 24 | // r
parse255(match[2]) << 16 | // g
parse255(match[3]) << 8 | // b
255) >>> // a
0;
}
if (match = rgba.exec(color)) {
return (parse255(match[1]) << 24 | // r
parse255(match[2]) << 16 | // g
parse255(match[3]) << 8 | // b
parse1(match[4])) >>> // a
0;
}
if (match = hex3.exec(color)) {
return parseInt(
match[1] + match[1] + // r
match[2] + match[2] + // g
match[3] + match[3] + // b
"ff",
// a
16
) >>> 0;
}
if (match = hex8.exec(color))
return parseInt(match[1], 16) >>> 0;
if (match = hex4.exec(color)) {
return parseInt(
match[1] + match[1] + // r
match[2] + match[2] + // g
match[3] + match[3] + // b
match[4] + match[4],
// a
16
) >>> 0;
}
if (match = hsl.exec(color)) {
return (hslToRgb(
parse360(match[1]),
// h
parsePercentage(match[2]),
// s
parsePercentage(match[3])
// l
) | 255) >>> // a
0;
}
if (match = hsla.exec(color)) {
return (hslToRgb(
parse360(match[1]),
// h
parsePercentage(match[2]),
// s
parsePercentage(match[3])
// l
) | parse1(match[4])) >>> // a
0;
}
return null;
}
function hue2rgb(p, q, t) {
if (t < 0)
t += 1;
if (t > 1)
t -= 1;
if (t < 1 / 6)
return p + (q - p) * 6 * t;
if (t < 1 / 2)
return q;
if (t < 2 / 3)
return p + (q - p) * (2 / 3 - t) * 6;
return p;
}
function hslToRgb(h, s, l) {
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
const r = hue2rgb(p, q, h + 1 / 3);
const g = hue2rgb(p, q, h);
const b = hue2rgb(p, q, h - 1 / 3);
return Math.round(r * 255) << 24 | Math.round(g * 255) << 16 | Math.round(b * 255) << 8;
}
function parse255(str) {
const int = parseInt(str, 10);
if (int < 0)
return 0;
if (int > 255)
return 255;
return int;
}
function parse360(str) {
const int = parseFloat(str);
return (int % 360 + 360) % 360 / 360;
}
function parse1(str) {
const num = parseFloat(str);
if (num < 0)
return 0;
if (num > 1)
return 255;
return Math.round(num * 255);
}
function parsePercentage(str) {
const int = parseFloat(str);
if (int < 0)
return 0;
if (int > 100)
return 1;
return int / 100;
}
// src/colorToRgba.ts
function colorToRgba(input) {
let int32Color = normalizeColor(input);
if (int32Color === null)
return input;
int32Color = int32Color || 0;
const r = (int32Color & 4278190080) >>> 24;
const g = (int32Color & 16711680) >>> 16;
const b = (int32Color & 65280) >>> 8;
const a = (int32Color & 255) / 255;
return `rgba(${r}, ${g}, ${b}, ${a})`;
}
// src/createInterpolator.ts
var createInterpolator = (range, output, extrapolate) => {
if (is.fun(range)) {
return range;
}
if (is.arr(range)) {
return createInterpolator({
range,
output,
extrapolate
});
}
if (is.str(range.output[0])) {
return createStringInterpolator(range);
}
const config = range;
const outputRange = config.output;
const inputRange = config.range || [0, 1];
const extrapolateLeft = config.extrapolateLeft || config.extrapolate || "extend";
const extrapolateRight = config.extrapolateRight || config.extrapolate || "extend";
const easing = config.easing || ((t) => t);
return (input) => {
const range2 = findRange(input, inputRange);
return interpolate(
input,
inputRange[range2],
inputRange[range2 + 1],
outputRange[range2],
outputRange[range2 + 1],
easing,
extrapolateLeft,
extrapolateRight,
config.map
);
};
};
function interpolate(input, inputMin, inputMax, outputMin, outputMax, easing, extrapolateLeft, extrapolateRight, map) {
let result = map ? map(input) : input;
if (result < inputMin) {
if (extrapolateLeft === "identity")
return result;
else if (extrapolateLeft === "clamp")
result = inputMin;
}
if (result > inputMax) {
if (extrapolateRight === "identity")
return result;
else if (extrapolateRight === "clamp")
result = inputMax;
}
if (outputMin === outputMax)
return outputMin;
if (inputMin === inputMax)
return input <= inputMin ? outputMin : outputMax;
if (inputMin === -Infinity)
result = -result;
else if (inputMax === Infinity)
result = result - inputMin;
else
result = (result - inputMin) / (inputMax - inputMin);
result = easing(result);
if (outputMin === -Infinity)
result = -result;
else if (outputMax === Infinity)
result = result + outputMin;
else
result = result * (outputMax - outputMin) + outputMin;
return result;
}
function findRange(input, inputRange) {
for (var i = 1; i < inputRange.length - 1; ++i)
if (inputRange[i] >= input)
break;
return i - 1;
}
// src/easings.ts
var steps = (steps2, direction = "end") => (progress2) => {
progress2 = direction === "end" ? Math.min(progress2, 0.999) : Math.max(progress2, 1e-3);
const expanded = progress2 * steps2;
const rounded = direction === "end" ? Math.floor(expanded) : Math.ceil(expanded);
return clamp(0, 1, rounded / steps2);
};
var c1 = 1.70158;
var c2 = c1 * 1.525;
var c3 = c1 + 1;
var c4 = 2 * Math.PI / 3;
var c5 = 2 * Math.PI / 4.5;
var bounceOut = (x) => {
const n1 = 7.5625;
const d1 = 2.75;
if (x < 1 / d1) {
return n1 * x * x;
} else if (x < 2 / d1) {
return n1 * (x -= 1.5 / d1) * x + 0.75;
} else if (x < 2.5 / d1) {
return n1 * (x -= 2.25 / d1) * x + 0.9375;
} else {
return n1 * (x -= 2.625 / d1) * x + 0.984375;
}
};
var easings = {
linear: (x) => x,
easeInQuad: (x) => x * x,
easeOutQuad: (x) => 1 - (1 - x) * (1 - x),
easeInOutQuad: (x) => x < 0.5 ? 2 * x * x : 1 - Math.pow(-2 * x + 2, 2) / 2,
easeInCubic: (x) => x * x * x,
easeOutCubic: (x) => 1 - Math.pow(1 - x, 3),
easeInOutCubic: (x) => x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2,
easeInQuart: (x) => x * x * x * x,
easeOutQuart: (x) => 1 - Math.pow(1 - x, 4),
easeInOutQuart: (x) => x < 0.5 ? 8 * x * x * x * x : 1 - Math.pow(-2 * x + 2, 4) / 2,
easeInQuint: (x) => x * x * x * x * x,
easeOutQuint: (x) => 1 - Math.pow(1 - x, 5),
easeInOutQuint: (x) => x < 0.5 ? 16 * x * x * x * x * x : 1 - Math.pow(-2 * x + 2, 5) / 2,
easeInSine: (x) => 1 - Math.cos(x * Math.PI / 2),
easeOutSine: (x) => Math.sin(x * Math.PI / 2),
easeInOutSine: (x) => -(Math.cos(Math.PI * x) - 1) / 2,
easeInExpo: (x) => x === 0 ? 0 : Math.pow(2, 10 * x - 10),
easeOutExpo: (x) => x === 1 ? 1 : 1 - Math.pow(2, -10 * x),
easeInOutExpo: (x) => x === 0 ? 0 : x === 1 ? 1 : x < 0.5 ? Math.pow(2, 20 * x - 10) / 2 : (2 - Math.pow(2, -20 * x + 10)) / 2,
easeInCirc: (x) => 1 - Math.sqrt(1 - Math.pow(x, 2)),
easeOutCirc: (x) => Math.sqrt(1 - Math.pow(x - 1, 2)),
easeInOutCirc: (x) => x < 0.5 ? (1 - Math.sqrt(1 - Math.pow(2 * x, 2))) / 2 : (Math.sqrt(1 - Math.pow(-2 * x + 2, 2)) + 1) / 2,
easeInBack: (x) => c3 * x * x * x - c1 * x * x,
easeOutBack: (x) => 1 + c3 * Math.pow(x - 1, 3) + c1 * Math.pow(x - 1, 2),
easeInOutBack: (x) => x < 0.5 ? Math.pow(2 * x, 2) * ((c2 + 1) * 2 * x - c2) / 2 : (Math.pow(2 * x - 2, 2) * ((c2 + 1) * (x * 2 - 2) + c2) + 2) / 2,
easeInElastic: (x) => x === 0 ? 0 : x === 1 ? 1 : -Math.pow(2, 10 * x - 10) * Math.sin((x * 10 - 10.75) * c4),
easeOutElastic: (x) => x === 0 ? 0 : x === 1 ? 1 : Math.pow(2, -10 * x) * Math.sin((x * 10 - 0.75) * c4) + 1,
easeInOutElastic: (x) => x === 0 ? 0 : x === 1 ? 1 : x < 0.5 ? -(Math.pow(2, 20 * x - 10) * Math.sin((20 * x - 11.125) * c5)) / 2 : Math.pow(2, -20 * x + 10) * Math.sin((20 * x - 11.125) * c5) / 2 + 1,
easeInBounce: (x) => 1 - bounceOut(1 - x),
easeOutBounce: bounceOut,
easeInOutBounce: (x) => x < 0.5 ? (1 - bounceOut(1 - 2 * x)) / 2 : (1 + bounceOut(2 * x - 1)) / 2,
steps
};
// src/fluids.ts
var $get = Symbol.for("FluidValue.get");
var $observers = Symbol.for("FluidValue.observers");
var hasFluidValue = (arg) => Boolean(arg && arg[$get]);
var getFluidValue = (arg) => arg && arg[$get] ? arg[$get]() : arg;
var getFluidObservers = (target) => target[$observers] || null;
function callFluidObserver(observer2, event) {
if (observer2.eventObserved) {
observer2.eventObserved(event);
} else {
observer2(event);
}
}
function callFluidObservers(target, event) {
const observers = target[$observers];
if (observers) {
observers.forEach((observer2) => {
callFluidObserver(observer2, event);
});
}
}
var FluidValue = class {
constructor(get) {
if (!get && !(get = this.get)) {
throw Error("Unknown getter");
}
setFluidGetter(this, get);
}
};
$get, $observers;
var setFluidGetter = (target, get) => setHidden(target, $get, get);
function addFluidObserver(target, observer2) {
if (target[$get]) {
let observers = target[$observers];
if (!observers) {
setHidden(target, $observers, observers = /* @__PURE__ */ new Set());
}
if (!observers.has(observer2)) {
observers.add(observer2);
if (target.observerAdded) {
target.observerAdded(observers.size, observer2);
}
}
}
return observer2;
}
function removeFluidObserver(target, observer2) {
const observers = target[$observers];
if (observers && observers.has(observer2)) {
const count = observers.size - 1;
if (count) {
observers.delete(observer2);
} else {
target[$observers] = null;
}
if (target.observerRemoved) {
target.observerRemoved(count, observer2);
}
}
}
var setHidden = (target, key, value) => Object.defineProperty(target, key, {
value,
writable: true,
configurable: true
});
// src/regexs.ts
var numberRegex = /[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
var colorRegex = /(#(?:[0-9a-f]{2}){2,4}|(#[0-9a-f]{3})|(rgb|hsl)a?\((-?\d+%?[,\s]+){2,3}\s*[\d\.]+%?\))/gi;
var unitRegex = new RegExp(`(${numberRegex.source})(%|[a-z]+)`, "i");
var rgbaRegex = /rgba\(([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+)\)/gi;
var cssVariableRegex = /var\((--[a-zA-Z0-9-_]+),? ?([a-zA-Z0-9 ()%#.,-]+)?\)/;
// src/variableToRgba.ts
var variableToRgba = (input) => {
const [token, fallback] = parseCSSVariable(input);
if (!token || isSSR()) {
return input;
}
const value = window.getComputedStyle(document.documentElement).getPropertyValue(token);
if (value) {
return value.trim();
} else if (fallback && fallback.startsWith("--")) {
const value2 = window.getComputedStyle(document.documentElement).getPropertyValue(fallback);
if (value2) {
return value2;
} else {
return input;
}
} else if (fallback && cssVariableRegex.test(fallback)) {
return variableToRgba(fallback);
} else if (fallback) {
return fallback;
}
return input;
};
var parseCSSVariable = (current) => {
const match = cssVariableRegex.exec(current);
if (!match)
return [,];
const [, token, fallback] = match;
return [token, fallback];
};
// src/stringInterpolation.ts
var namedColorRegex;
var rgbaRound = (_, p1, p2, p3, p4) => `rgba(${Math.round(p1)}, ${Math.round(p2)}, ${Math.round(p3)}, ${p4})`;
var createStringInterpolator2 = (config) => {
if (!namedColorRegex)
namedColorRegex = colors ? (
// match color names, ignore partial matches
new RegExp(`(${Object.keys(colors).join("|")})(?!\\w)`, "g")
) : (
// never match
/^\b$/
);
const output = config.output.map((value) => {
return getFluidValue(value).replace(cssVariableRegex, variableToRgba).replace(colorRegex, colorToRgba).replace(namedColorRegex, colorToRgba);
});
const keyframes = output.map((value) => value.match(numberRegex).map(Number));
const outputRanges = keyframes[0].map(
(_, i) => keyframes.map((values) => {
if (!(i in values)) {
throw Error('The arity of each "output" value must be equal');
}
return values[i];
})
);
const interpolators = outputRanges.map(
(output2) => createInterpolator({ ...config, output: output2 })
);
return (input) => {
const missingUnit = !unitRegex.test(output[0]) && output.find((value) => unitRegex.test(value))?.replace(numberRegex, "");
let i = 0;
return output[0].replace(
numberRegex,
() => `${interpolators[i++](input)}${missingUnit || ""}`
).replace(rgbaRegex, rgbaRound);
};
};
// src/deprecations.ts
var prefix = "react-spring: ";
var once = (fn) => {
const func = fn;
let called = false;
if (typeof func != "function") {
throw new TypeError(`${prefix}once requires a function parameter`);
}
return (...args) => {
if (!called) {
func(...args);
called = true;
}
};
};
var warnInterpolate = once(console.warn);
function deprecateInterpolate() {
warnInterpolate(
`${prefix}The "interpolate" function is deprecated in v9 (use "to" instead)`
);
}
var warnDirectCall = once(console.warn);
function deprecateDirectCall() {
warnDirectCall(
`${prefix}Directly calling start instead of using the api object is deprecated in v9 (use ".start" instead), this will be removed in later 0.X.0 versions`
);
}
// src/isAnimatedString.ts
function isAnimatedString(value) {
return is.str(value) && (value[0] == "#" || /\d/.test(value) || // Do not identify a CSS variable as an AnimatedString if its SSR
!isSSR() && cssVariableRegex.test(value) || value in (colors || {}));
}
// src/dom-events/scroll/index.ts
import { raf as raf3 } from "@react-spring/rafz";
// src/dom-events/resize/resizeElement.ts
var observer;
var resizeHandlers = /* @__PURE__ */ new WeakMap();
var handleObservation = (entries) => entries.forEach(({ target, contentRect }) => {
return resizeHandlers.get(target)?.forEach((handler) => handler(contentRect));
});
function resizeElement(handler, target) {
if (!observer) {
if (typeof ResizeObserver !== "undefined") {
observer = new ResizeObserver(handleObservation);
}
}
let elementHandlers = resizeHandlers.get(target);
if (!elementHandlers) {
elementHandlers = /* @__PURE__ */ new Set();
resizeHandlers.set(target, elementHandlers);
}
elementHandlers.add(handler);
if (observer) {
observer.observe(target);
}
return () => {
const elementHandlers2 = resizeHandlers.get(target);
if (!elementHandlers2)
return;
elementHandlers2.delete(handler);
if (!elementHandlers2.size && observer) {
observer.unobserve(target);
}
};
}
// src/dom-events/resize/resizeWindow.ts
var listeners = /* @__PURE__ */ new Set();
var cleanupWindowResizeHandler;
var createResizeHandler = () => {
const handleResize = () => {
listeners.forEach(
(callback) => callback({
width: window.innerWidth,
height: window.innerHeight
})
);
};
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
};
};
var resizeWindow = (callback) => {
listeners.add(callback);
if (!cleanupWindowResizeHandler) {
cleanupWindowResizeHandler = createResizeHandler();
}
return () => {
listeners.delete(callback);
if (!listeners.size && cleanupWindowResizeHandler) {
cleanupWindowResizeHandler();
cleanupWindowResizeHandler = void 0;
}
};
};
// src/dom-events/resize/index.ts
var onResize = (callback, { container = document.documentElement } = {}) => {
if (container === document.documentElement) {
return resizeWindow(callback);
} else {
return resizeElement(callback, container);
}
};
// src/progress.ts
var progress = (min, max, value) => max - min === 0 ? 1 : (value - min) / (max - min);
// src/dom-events/scroll/ScrollHandler.ts
var SCROLL_KEYS = {
x: {
length: "Width",
position: "Left"
},
y: {
length: "Height",
position: "Top"
}
};
var ScrollHandler = class {
constructor(callback, container) {
this.createAxis = () => ({
current: 0,
progress: 0,
scrollLength: 0
});
this.updateAxis = (axisName) => {
const axis = this.info[axisName];
const { length, position } = SCROLL_KEYS[axisName];
axis.current = this.container[`scroll${position}`];
axis.scrollLength = this.container[`scroll${length}`] - this.container[`client${length}`];
axis.progress = progress(0, axis.scrollLength, axis.current);
};
this.update = () => {
this.updateAxis("x");
this.updateAxis("y");
};
this.sendEvent = () => {
this.callback(this.info);
};
this.advance = () => {
this.update();
this.sendEvent();
};
this.callback = callback;
this.container = container;
this.info = {
time: 0,
x: this.createAxis(),
y: this.createAxis()
};
}
};
// src/dom-events/scroll/index.ts
var scrollListeners = /* @__PURE__ */ new WeakMap();
var resizeListeners = /* @__PURE__ */ new WeakMap();
var onScrollHandlers = /* @__PURE__ */ new WeakMap();
var getTarget = (container) => container === document.documentElement ? window : container;
var onScroll = (callback, { container = document.documentElement } = {}) => {
let containerHandlers = onScrollHandlers.get(container);
if (!containerHandlers) {
containerHandlers = /* @__PURE__ */ new Set();
onScrollHandlers.set(container, containerHandlers);
}
const containerHandler = new ScrollHandler(callback, container);
containerHandlers.add(containerHandler);
if (!scrollListeners.has(container)) {
const listener = () => {
containerHandlers?.forEach((handler) => handler.advance());
return true;
};
scrollListeners.set(container, listener);
const target = getTarget(container);
window.addEventListener("resize", listener, { passive: true });
if (container !== document.documentElement) {
resizeListeners.set(container, onResize(listener, { container }));
}
target.addEventListener("scroll", listener, { passive: true });
}
const animateScroll = scrollListeners.get(container);
raf3(animateScroll);
return () => {
raf3.cancel(animateScroll);
const containerHandlers2 = onScrollHandlers.get(container);
if (!containerHandlers2)
return;
containerHandlers2.delete(containerHandler);
if (containerHandlers2.size)
return;
const listener = scrollListeners.get(container);
scrollListeners.delete(container);
if (listener) {
getTarget(container).removeEventListener("scroll", listener);
window.removeEventListener("resize", listener);
resizeListeners.get(container)?.();
}
};
};
// src/hooks/useConstant.ts
import { useRef } from "react";
function useConstant(init) {
const ref = useRef(null);
if (ref.current === null) {
ref.current = init();
}
return ref.current;
}
// src/hooks/useForceUpdate.ts
import { useState } from "react";
// src/hooks/useIsMounted.ts
import { useRef as useRef2 } from "react";
// src/hooks/useIsomorphicLayoutEffect.ts
import { useEffect, useLayoutEffect } from "react";
var useIsomorphicLayoutEffect = isSSR() ? useEffect : useLayoutEffect;
// src/hooks/useIsMounted.ts
var useIsMounted = () => {
const isMounted = useRef2(false);
useIsomorphicLayoutEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
};
}, []);
return isMounted;
};
// src/hooks/useForceUpdate.ts
function useForceUpdate() {
const update = useState()[1];
const isMounted = useIsMounted();
return () => {
if (isMounted.current) {
update(Math.random());
}
};
}
// src/hooks/useMemoOne.ts
import { useEffect as useEffect2, useRef as useRef3, useState as useState2 } from "react";
function useMemoOne(getResult, inputs) {
const [initial] = useState2(
() => ({
inputs,
result: getResult()
})
);
const committed = useRef3();
const prevCache = committed.current;
let cache = prevCache;
if (cache) {
const useCache = Boolean(
inputs && cache.inputs && areInputsEqual(inputs, cache.inputs)
);
if (!useCache) {
cache = {
inputs,
result: getResult()
};
}
} else {
cache = initial;
}
useEffect2(() => {
committed.current = cache;
if (prevCache == initial) {
initial.inputs = initial.result = void 0;
}
}, [cache]);
return cache.result;
}
function areInputsEqual(next, prev) {
if (next.length !== prev.length) {
return false;
}
for (let i = 0; i < next.length; i++) {
if (next[i] !== prev[i]) {
return false;
}
}
return true;
}
// src/hooks/useOnce.ts
import { useEffect as useEffect3 } from "react";
var useOnce = (effect) => useEffect3(effect, emptyDeps);
var emptyDeps = [];
// src/hooks/usePrev.ts
import { useEffect as useEffect4, useRef as useRef4 } from "react";
function usePrev(value) {
const prevRef = useRef4();
useEffect4(() => {
prevRef.current = value;
});
return prevRef.current;
}
// src/hooks/useReducedMotion.ts
import { useState as useState3 } from "react";
var useReducedMotion = () => {
const [reducedMotion, setReducedMotion] = useState3(null);
useIsomorphicLayoutEffect(() => {
const mql = window.matchMedia("(prefers-reduced-motion)");
const handleMediaChange = (e) => {
setReducedMotion(e.matches);
assign({
skipAnimation: e.matches
});
};
handleMediaChange(mql);
if (mql.addEventListener) {
mql.addEventListener("change", handleMediaChange);
} else {
mql.addListener(handleMediaChange);
}
return () => {
if (mql.removeEventListener) {
mql.removeEventListener("change", handleMediaChange);
} else {
mql.removeListener(handleMediaChange);
}
};
}, []);
return reducedMotion;
};
// src/index.ts
import { raf as raf4 } from "@react-spring/rafz";
export {
FluidValue,
globals_exports as Globals,
addFluidObserver,
callFluidObserver,
callFluidObservers,
clamp,
colorToRgba,
colors2 as colors,
createInterpolator,
createStringInterpolator2 as createStringInterpolator,
defineHidden,
deprecateDirectCall,
deprecateInterpolate,
each,
eachProp,
easings,
flush,
flushCalls,
frameLoop,
getFluidObservers,
getFluidValue,
hasFluidValue,
hex3,
hex4,
hex6,
hex8,
hsl,
hsla,
is,
isAnimatedString,
isEqual,
isSSR,
noop,
onResize,
onScroll,
once,
prefix,
raf4 as raf,
removeFluidObserver,
rgb,
rgba,
setFluidGetter,
toArray,
useConstant,
useForceUpdate,
useIsomorphicLayoutEffect,
useMemoOne,
useOnce,
usePrev,
useReducedMotion
};
//# sourceMappingURL=react-spring_shared.modern.mjs.map
webpack://frontend-mybets/../../node_modules/@react-spring/web/node_modules/@react-spring/animated/dist/react-spring_animated.modern.mjs
// src/Animated.ts
import { defineHidden } from "@react-spring/shared";
var $node = Symbol.for("Animated:node");
var isAnimated = (value) => !!value && value[$node] === value;
var getAnimated = (owner) => owner && owner[$node];
var setAnimated = (owner, node) => defineHidden(owner, $node, node);
var getPayload = (owner) => owner && owner[$node] && owner[$node].getPayload();
var Animated = class {
constructor() {
setAnimated(this, this);
}
/** Get every `AnimatedValue` used by this node. */
getPayload() {
return this.payload || [];
}
};
// src/AnimatedValue.ts
import { is } from "@react-spring/shared";
var AnimatedValue = class extends Animated {
constructor(_value) {
super();
this._value = _value;
this.done = true;
this.durationProgress = 0;
if (is.num(this._value)) {
this.lastPosition = this._value;
}
}
/** @internal */
static create(value) {
return new AnimatedValue(value);
}
getPayload() {
return [this];
}
getValue() {
return this._value;
}
setValue(value, step) {
if (is.num(value)) {
this.lastPosition = value;
if (step) {
value = Math.round(value / step) * step;
if (this.done) {
this.lastPosition = value;
}
}
}
if (this._value === value) {
return false;
}
this._value = value;
return true;
}
reset() {
const { done } = this;
this.done = false;
if (is.num(this._value)) {
this.elapsedTime = 0;
this.durationProgress = 0;
this.lastPosition = this._value;
if (done)
this.lastVelocity = null;
this.v0 = null;
}
}
};
// src/AnimatedString.ts
import { is as is2, createInterpolator } from "@react-spring/shared";
var AnimatedString = class extends AnimatedValue {
constructor(value) {
super(0);
this._string = null;
this._toString = createInterpolator({
output: [value, value]
});
}
/** @internal */
static create(value) {
return new AnimatedString(value);
}
getValue() {
const value = this._string;
return value == null ? this._string = this._toString(this._value) : value;
}
setValue(value) {
if (is2.str(value)) {
if (value == this._string) {
return false;
}
this._string = value;
this._value = 1;
} else if (super.setValue(value)) {
this._string = null;
} else {
return false;
}
return true;
}
reset(goal) {
if (goal) {
this._toString = createInterpolator({
output: [this.getValue(), goal]
});
}
this._value = 0;
super.reset();
}
};
// src/AnimatedArray.ts
import { isAnimatedString } from "@react-spring/shared";
// src/AnimatedObject.ts
import {
each,
eachProp,
getFluidValue,
hasFluidValue
} from "@react-spring/shared";
// src/context.ts
var TreeContext = { dependencies: null };
// src/AnimatedObject.ts
var AnimatedObject = class extends Animated {
constructor(source) {
super();
this.source = source;
this.setValue(source);
}
getValue(animated) {
const values = {};
eachProp(this.source, (source, key) => {
if (isAnimated(source)) {
values[key] = source.getValue(animated);
} else if (hasFluidValue(source)) {
values[key] = getFluidValue(source);
} else if (!animated) {
values[key] = source;
}
});
return values;
}
/** Replace the raw object data */
setValue(source) {
this.source = source;
this.payload = this._makePayload(source);
}
reset() {
if (this.payload) {
each(this.payload, (node) => node.reset());
}
}
/** Create a payload set. */
_makePayload(source) {
if (source) {
const payload = /* @__PURE__ */ new Set();
eachProp(source, this._addToPayload, payload);
return Array.from(payload);
}
}
/** Add to a payload set. */
_addToPayload(source) {
if (TreeContext.dependencies && hasFluidValue(source)) {
TreeContext.dependencies.add(source);
}
const payload = getPayload(source);
if (payload) {
each(payload, (node) => this.add(node));
}
}
};
// src/AnimatedArray.ts
var AnimatedArray = class extends AnimatedObject {
constructor(source) {
super(source);
}
/** @internal */
static create(source) {
return new AnimatedArray(source);
}
getValue() {
return this.source.map((node) => node.getValue());
}
setValue(source) {
const payload = this.getPayload();
if (source.length == payload.length) {
return payload.map((node, i) => node.setValue(source[i])).some(Boolean);
}
super.setValue(source.map(makeAnimated));
return true;
}
};
function makeAnimated(value) {
const nodeType = isAnimatedString(value) ? AnimatedString : AnimatedValue;
return nodeType.create(value);
}
// src/getAnimatedType.ts
import { is as is3, isAnimatedString as isAnimatedString2 } from "@react-spring/shared";
function getAnimatedType(value) {
const parentNode = getAnimated(value);
return parentNode ? parentNode.constructor : is3.arr(value) ? AnimatedArray : isAnimatedString2(value) ? AnimatedString : AnimatedValue;
}
// src/createHost.ts
import { is as is5, eachProp as eachProp2 } from "@react-spring/shared";
// src/withAnimated.tsx
import * as React from "react";
import { forwardRef, useRef, useCallback, useEffect } from "react";
import {
is as is4,
each as each2,
raf,
useForceUpdate,
useOnce,
addFluidObserver,
removeFluidObserver,
useIsomorphicLayoutEffect
} from "@react-spring/shared";
var withAnimated = (Component, host) => {
const hasInstance = (
// Function components must use "forwardRef" to avoid being
// re-rendered on every animation frame.
!is4.fun(Component) || Component.prototype && Component.prototype.isReactComponent
);
return forwardRef((givenProps, givenRef) => {
const instanceRef = useRef(null);
const ref = hasInstance && // eslint-disable-next-line react-hooks/rules-of-hooks
useCallback(
(value) => {
instanceRef.current = updateRef(givenRef, value);
},
[givenRef]
);
const [props, deps] = getAnimatedState(givenProps, host);
const forceUpdate = useForceUpdate();
const callback = () => {
const instance = instanceRef.current;
if (hasInstance && !instance) {
return;
}
const didUpdate = instance ? host.applyAnimatedValues(instance, props.getValue(true)) : false;
if (didUpdate === false) {
forceUpdate();
}
};
const observer = new PropsObserver(callback, deps);
const observerRef = useRef();
useIsomorphicLayoutEffect(() => {
observerRef.current = observer;
each2(deps, (dep) => addFluidObserver(dep, observer));
return () => {
if (observerRef.current) {
each2(
observerRef.current.deps,
(dep) => removeFluidObserver(dep, observerRef.current)
);
raf.cancel(observerRef.current.update);
}
};
});
useEffect(callback, []);
useOnce(() => () => {
const observer2 = observerRef.current;
each2(observer2.deps, (dep) => removeFluidObserver(dep, observer2));
});
const usedProps = host.getComponentProps(props.getValue());
return /* @__PURE__ */ React.createElement(Component, { ...usedProps, ref });
});
};
var PropsObserver = class {
constructor(update, deps) {
this.update = update;
this.deps = deps;
}
eventObserved(event) {
if (event.type == "change") {
raf.write(this.update);
}
}
};
function getAnimatedState(props, host) {
const dependencies = /* @__PURE__ */ new Set();
TreeContext.dependencies = dependencies;
if (props.style)
props = {
...props,
style: host.createAnimatedStyle(props.style)
};
props = new AnimatedObject(props);
TreeContext.dependencies = null;
return [props, dependencies];
}
function updateRef(ref, value) {
if (ref) {
if (is4.fun(ref))
ref(value);
else
ref.current = value;
}
return value;
}
// src/createHost.ts
var cacheKey = Symbol.for("AnimatedComponent");
var createHost = (components, {
applyAnimatedValues = () => false,
createAnimatedStyle = (style) => new AnimatedObject(style),
getComponentProps = (props) => props
} = {}) => {
const hostConfig = {
applyAnimatedValues,
createAnimatedStyle,
getComponentProps
};
const animated = (Component) => {
const displayName = getDisplayName(Component) || "Anonymous";
if (is5.str(Component)) {
Component = animated[Component] || (animated[Component] = withAnimated(Component, hostConfig));
} else {
Component = Component[cacheKey] || (Component[cacheKey] = withAnimated(Component, hostConfig));
}
Component.displayName = `Animated(${displayName})`;
return Component;
};
eachProp2(components, (Component, key) => {
if (is5.arr(components)) {
key = getDisplayName(Component);
}
animated[key] = animated(Component);
});
return {
animated
};
};
var getDisplayName = (arg) => is5.str(arg) ? arg : arg && is5.str(arg.displayName) ? arg.displayName : is5.fun(arg) && arg.name || null;
export {
Animated,
AnimatedArray,
AnimatedObject,
AnimatedString,
AnimatedValue,
createHost,
getAnimated,
getAnimatedType,
getPayload,
isAnimated,
setAnimated
};
//# sourceMappingURL=react-spring_animated.modern.mjs.map
webpack://frontend-mybets/../../node_modules/@react-spring/web/dist/react-spring_web.modern.mjs
// src/index.ts
import { Globals } from "@react-spring/core";
import { unstable_batchedUpdates } from "react-dom";
import { createStringInterpolator, colors } from "@react-spring/shared";
import { createHost } from "@react-spring/animated";
// src/applyAnimatedValues.ts
var isCustomPropRE = /^--/;
function dangerousStyleValue(name, value) {
if (value == null || typeof value === "boolean" || value === "")
return "";
if (typeof value === "number" && value !== 0 && !isCustomPropRE.test(name) && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]))
return value + "px";
return ("" + value).trim();
}
var attributeCache = {};
function applyAnimatedValues(instance, props) {
if (!instance.nodeType || !instance.setAttribute) {
return false;
}
const isFilterElement = instance.nodeName === "filter" || instance.parentNode && instance.parentNode.nodeName === "filter";
const {
className,
style,
children,
scrollTop,
scrollLeft,
viewBox,
...attributes
} = props;
const values = Object.values(attributes);
const names = Object.keys(attributes).map(
(name) => isFilterElement || instance.hasAttribute(name) ? name : attributeCache[name] || (attributeCache[name] = name.replace(
/([A-Z])/g,
// Attributes are written in dash case
(n) => "-" + n.toLowerCase()
))
);
if (children !== void 0) {
instance.textContent = children;
}
for (const name in style) {
if (style.hasOwnProperty(name)) {
const value = dangerousStyleValue(name, style[name]);
if (isCustomPropRE.test(name)) {
instance.style.setProperty(name, value);
} else {
instance.style[name] = value;
}
}
}
names.forEach((name, i) => {
instance.setAttribute(name, values[i]);
});
if (className !== void 0) {
instance.className = className;
}
if (scrollTop !== void 0) {
instance.scrollTop = scrollTop;
}
if (scrollLeft !== void 0) {
instance.scrollLeft = scrollLeft;
}
if (viewBox !== void 0) {
instance.setAttribute("viewBox", viewBox);
}
}
var isUnitlessNumber = {
animationIterationCount: true,
borderImageOutset: true,
borderImageSlice: true,
borderImageWidth: true,
boxFlex: true,
boxFlexGroup: true,
boxOrdinalGroup: true,
columnCount: true,
columns: true,
flex: true,
flexGrow: true,
flexPositive: true,
flexShrink: true,
flexNegative: true,
flexOrder: true,
gridRow: true,
gridRowEnd: true,
gridRowSpan: true,
gridRowStart: true,
gridColumn: true,
gridColumnEnd: true,
gridColumnSpan: true,
gridColumnStart: true,
fontWeight: true,
lineClamp: true,
lineHeight: true,
opacity: true,
order: true,
orphans: true,
tabSize: true,
widows: true,
zIndex: true,
zoom: true,
// SVG-related properties
fillOpacity: true,
floodOpacity: true,
stopOpacity: true,
strokeDasharray: true,
strokeDashoffset: true,
strokeMiterlimit: true,
strokeOpacity: true,
strokeWidth: true
};
var prefixKey = (prefix, key) => prefix + key.charAt(0).toUpperCase() + key.substring(1);
var prefixes = ["Webkit", "Ms", "Moz", "O"];
isUnitlessNumber = Object.keys(isUnitlessNumber).reduce((acc, prop) => {
prefixes.forEach((prefix) => acc[prefixKey(prefix, prop)] = acc[prop]);
return acc;
}, isUnitlessNumber);
// src/AnimatedStyle.ts
import { AnimatedObject } from "@react-spring/animated";
import {
is,
each,
toArray,
eachProp,
FluidValue,
getFluidValue,
callFluidObservers,
hasFluidValue,
addFluidObserver,
removeFluidObserver
} from "@react-spring/shared";
var domTransforms = /^(matrix|translate|scale|rotate|skew)/;
var pxTransforms = /^(translate)/;
var degTransforms = /^(rotate|skew)/;
var addUnit = (value, unit) => is.num(value) && value !== 0 ? value + unit : value;
var isValueIdentity = (value, id) => is.arr(value) ? value.every((v) => isValueIdentity(v, id)) : is.num(value) ? value === id : parseFloat(value) === id;
var AnimatedStyle = class extends AnimatedObject {
constructor({ x, y, z, ...style }) {
const inputs = [];
const transforms = [];
if (x || y || z) {
inputs.push([x || 0, y || 0, z || 0]);
transforms.push((xyz) => [
`translate3d(${xyz.map((v) => addUnit(v, "px")).join(",")})`,
// prettier-ignore
isValueIdentity(xyz, 0)
]);
}
eachProp(style, (value, key) => {
if (key === "transform") {
inputs.push([value || ""]);
transforms.push((transform) => [transform, transform === ""]);
} else if (domTransforms.test(key)) {
delete style[key];
if (is.und(value))
return;
const unit = pxTransforms.test(key) ? "px" : degTransforms.test(key) ? "deg" : "";
inputs.push(toArray(value));
transforms.push(
key === "rotate3d" ? ([x2, y2, z2, deg]) => [
`rotate3d(${x2},${y2},${z2},${addUnit(deg, unit)})`,
isValueIdentity(deg, 0)
] : (input) => [
`${key}(${input.map((v) => addUnit(v, unit)).join(",")})`,
isValueIdentity(input, key.startsWith("scale") ? 1 : 0)
]
);
}
});
if (inputs.length) {
style.transform = new FluidTransform(inputs, transforms);
}
super(style);
}
};
var FluidTransform = class extends FluidValue {
constructor(inputs, transforms) {
super();
this.inputs = inputs;
this.transforms = transforms;
this._value = null;
}
get() {
return this._value || (this._value = this._get());
}
_get() {
let transform = "";
let identity = true;
each(this.inputs, (input, i) => {
const arg1 = getFluidValue(input[0]);
const [t, id] = this.transforms[i](
is.arr(arg1) ? arg1 : input.map(getFluidValue)
);
transform += " " + t;
identity = identity && id;
});
return identity ? "none" : transform;
}
// Start observing our inputs once we have an observer.
observerAdded(count) {
if (count == 1)
each(
this.inputs,
(input) => each(
input,
(value) => hasFluidValue(value) && addFluidObserver(value, this)
)
);
}
// Stop observing our inputs once we have no observers.
observerRemoved(count) {
if (count == 0)
each(
this.inputs,
(input) => each(
input,
(value) => hasFluidValue(value) && removeFluidObserver(value, this)
)
);
}
eventObserved(event) {
if (event.type == "change") {
this._value = null;
}
callFluidObservers(this, event);
}
};
// src/primitives.ts
var primitives = [
"a",
"abbr",
"address",
"area",
"article",
"aside",
"audio",
"b",
"base",
"bdi",
"bdo",
"big",
"blockquote",
"body",
"br",
"button",
"canvas",
"caption",
"cite",
"code",
"col",
"colgroup",
"data",
"datalist",
"dd",
"del",
"details",
"dfn",
"dialog",
"div",
"dl",
"dt",
"em",
"embed",
"fieldset",
"figcaption",
"figure",
"footer",
"form",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"head",
"header",
"hgroup",
"hr",
"html",
"i",
"iframe",
"img",
"input",
"ins",
"kbd",
"keygen",
"label",
"legend",
"li",
"link",
"main",
"map",
"mark",
"menu",
"menuitem",
"meta",
"meter",
"nav",
"noscript",
"object",
"ol",
"optgroup",
"option",
"output",
"p",
"param",
"picture",
"pre",
"progress",
"q",
"rp",
"rt",
"ruby",
"s",
"samp",
"script",
"section",
"select",
"small",
"source",
"span",
"strong",
"style",
"sub",
"summary",
"sup",
"table",
"tbody",
"td",
"textarea",
"tfoot",
"th",
"thead",
"time",
"title",
"tr",
"track",
"u",
"ul",
"var",
"video",
"wbr",
// SVG
"circle",
"clipPath",
"defs",
"ellipse",
"foreignObject",
"g",
"image",
"line",
"linearGradient",
"mask",
"path",
"pattern",
"polygon",
"polyline",
"radialGradient",
"rect",
"stop",
"svg",
"text",
"tspan"
];
// src/index.ts
export * from "@react-spring/core";
Globals.assign({
batchedUpdates: unstable_batchedUpdates,
createStringInterpolator,
colors
});
var host = createHost(primitives, {
applyAnimatedValues,
createAnimatedStyle: (style) => new AnimatedStyle(style),
// eslint-disable-next-line @typescript-eslint/no-unused-vars
getComponentProps: ({ scrollTop, scrollLeft, ...props }) => props
});
var animated = host.animated;
export {
animated as a,
animated
};
//# sourceMappingURL=react-spring_web.modern.mjs.map
webpack://frontend-mybets/webpack/bootstrap
// The module cache
var __webpack_module_cache__ = {};
// The require function
function __webpack_require__(moduleId) {
// Check if module is in cache
var cachedModule = __webpack_module_cache__[moduleId];
if (cachedModule !== undefined) {
return cachedModule.exports;
}
// Create a new module (and put it into the cache)
var module = __webpack_module_cache__[moduleId] = {
id: moduleId,
loaded: false,
exports: {}
};
// Execute the module function
__webpack_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 = __webpack_modules__;
webpack://frontend-mybets/webpack/runtime/amd define
__webpack_require__.amdD = function () {
throw new Error('define cannot be used indirect');
};
webpack://frontend-mybets/webpack/runtime/amd options
__webpack_require__.amdO = {};
webpack://frontend-mybets/webpack/runtime/compat get default export
// getDefaultExport function for compatibility with non-harmony modules
__webpack_require__.n = (module) => {
var getter = module && module.__esModule ?
() => (module['default']) :
() => (module);
__webpack_require__.d(getter, { a: getter });
return getter;
};
webpack://frontend-mybets/webpack/runtime/define property getters
// define getter functions for harmony exports
__webpack_require__.d = (exports, definition) => {
for(var key in definition) {
if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
}
}
};
webpack://frontend-mybets/webpack/runtime/ensure chunk
__webpack_require__.f = {};
// This file contains only the entry chunk.
// The chunk loading function for additional chunks
__webpack_require__.e = (chunkId) => {
return Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {
__webpack_require__.f[key](chunkId, promises);
return promises;
}, []));
};
webpack://frontend-mybets/webpack/runtime/get javascript chunk filename
// This function allow to reference async chunks
__webpack_require__.u = (chunkId) => {
// return url for filenames based on template
return "" + chunkId + "." + __webpack_require__.h() + ".js";
};
webpack://frontend-mybets/webpack/runtime/get mini-css chunk filename
// This function allow to reference async chunks
__webpack_require__.miniCssF = (chunkId) => {
// return url for filenames based on template
return undefined;
};
webpack://frontend-mybets/webpack/runtime/getFullHash
__webpack_require__.h = () => ("c682591e30ec7093fdf7")
webpack://frontend-mybets/webpack/runtime/global
__webpack_require__.g = (function() {
if (typeof globalThis === 'object') return globalThis;
try {
return this || new Function('return this')();
} catch (e) {
if (typeof window === 'object') return window;
}
})();
webpack://frontend-mybets/webpack/runtime/hasOwnProperty shorthand
__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
webpack://frontend-mybets/webpack/runtime/make namespace object
// define __esModule on exports
__webpack_require__.r = (exports) => {
if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
}
Object.defineProperty(exports, '__esModule', { value: true });
};
webpack://frontend-mybets/webpack/runtime/node module decorator
__webpack_require__.nmd = (module) => {
module.paths = [];
if (!module.children) module.children = [];
return module;
};
webpack://frontend-mybets/webpack/runtime/publicPath
__webpack_require__.p = "/mybets/assets/";
webpack://frontend-mybets/webpack/runtime/jsonp chunk loading
// no baseURI
// object to store loaded and loading chunks
// undefined = chunk not loaded, null = chunk preloaded/prefetched
// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded
var installedChunks = {
892: 0
};
__webpack_require__.f.j = (chunkId, promises) => {
// JSONP chunk loading for javascript
var installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;
if(installedChunkData !== 0) { // 0 means "already installed".
// a Promise means "currently loading".
if(installedChunkData) {
promises.push(installedChunkData[2]);
} else {
if(true) { // all chunks have JS
// setup Promise in chunk cache
var promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));
promises.push(installedChunkData[2] = promise);
// start chunk loading
var url = __webpack_require__.p + __webpack_require__.u(chunkId);
// create error before stack unwound to get useful stacktrace later
var error = new Error();
var loadingEnded = (event) => {
if(__webpack_require__.o(installedChunks, chunkId)) {
installedChunkData = installedChunks[chunkId];
if(installedChunkData !== 0) installedChunks[chunkId] = undefined;
if(installedChunkData) {
var errorType = event && (event.type === 'load' ? 'missing' : event.type);
var realSrc = event && event.target && event.target.src;
error.message = 'Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')';
error.name = 'ChunkLoadError';
error.type = errorType;
error.request = realSrc;
installedChunkData[1](error);
}
}
};
__webpack_require__.l(url, loadingEnded, "chunk-" + chunkId, chunkId);
}
}
}
};
// no prefetching
// no preloaded
// no HMR
// no HMR manifest
// no on chunks loaded
// install a JSONP callback for chunk loading
var webpackJsonpCallback = (parentChunkLoadingFunction, data) => {
var [chunkIds, moreModules, runtime] = data;
// add "moreModules" to the modules object,
// then flag all "chunkIds" as loaded and fire callback
var moduleId, chunkId, i = 0;
if(chunkIds.some((id) => (installedChunks[id] !== 0))) {
for(moduleId in moreModules) {
if(__webpack_require__.o(moreModules, moduleId)) {
__webpack_require__.m[moduleId] = moreModules[moduleId];
}
}
if(runtime) var result = runtime(__webpack_require__);
}
if(parentChunkLoadingFunction) parentChunkLoadingFunction(data);
for(;i < chunkIds.length; i++) {
chunkId = chunkIds[i];
if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {
installedChunks[chunkId][0]();
}
installedChunks[chunkId] = 0;
}
}
var chunkLoadingGlobal = self["mybetsJsonOutput"] = self["mybetsJsonOutput"] || [];
chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));
chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));
webpack://frontend-mybets/../../node_modules/tslib/tslib.es6.mjs
/******************************************************************************
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.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
export function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
export var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
}
return __assign.apply(this, arguments);
}
export 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;
}
export function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
export function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
export function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
var _, done = false;
for (var i = decorators.length - 1; i >= 0; i--) {
var context = {};
for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
for (var p in contextIn.access) context.access[p] = contextIn.access[p];
context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
if (kind === "accessor") {
if (result === void 0) continue;
if (result === null || typeof result !== "object") throw new TypeError("Object expected");
if (_ = accept(result.get)) descriptor.get = _;
if (_ = accept(result.set)) descriptor.set = _;
if (_ = accept(result.init)) initializers.unshift(_);
}
else if (_ = accept(result)) {
if (kind === "field") initializers.unshift(_);
else descriptor[key] = _;
}
}
if (target) Object.defineProperty(target, contextIn.name, descriptor);
done = true;
};
export function __runInitializers(thisArg, initializers, value) {
var useValue = arguments.length > 2;
for (var i = 0; i < initializers.length; i++) {
value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
}
return useValue ? value : void 0;
};
export function __propKey(x) {
return typeof x === "symbol" ? x : "".concat(x);
};
export function __setFunctionName(f, name, prefix) {
if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
};
export function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
export function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
export function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
export var __createBinding = Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
});
export function __exportStar(m, o) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
}
export function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
export function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
/** @deprecated */
export function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
/** @deprecated */
export function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
}
export function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
export function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
export function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
export function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
}
export function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
export function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
var __setModuleDefault = Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
};
export function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
}
export function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
export function __classPrivateFieldGet(receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}
export function __classPrivateFieldSet(receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
}
export function __classPrivateFieldIn(state, receiver) {
if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
return typeof state === "function" ? receiver === state : state.has(receiver);
}
export function __addDisposableResource(env, value, async) {
if (value !== null && value !== void 0) {
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
var dispose;
if (async) {
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
dispose = value[Symbol.asyncDispose];
}
if (dispose === void 0) {
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
dispose = value[Symbol.dispose];
}
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
env.stack.push({ value: value, dispose: dispose, async: async });
}
else if (async) {
env.stack.push({ async: true });
}
return value;
}
var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
export function __disposeResources(env) {
function fail(e) {
env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
env.hasError = true;
}
function next() {
while (env.stack.length) {
var rec = env.stack.pop();
try {
var result = rec.dispose && rec.dispose.call(rec.value);
if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
}
catch (e) {
fail(e);
}
}
if (env.hasError) throw env.error;
}
return next();
}
export default {
__extends,
__assign,
__rest,
__decorate,
__param,
__metadata,
__awaiter,
__generator,
__createBinding,
__exportStar,
__values,
__read,
__spread,
__spreadArrays,
__spreadArray,
__await,
__asyncGenerator,
__asyncDelegator,
__asyncValues,
__makeTemplateObject,
__importStar,
__importDefault,
__classPrivateFieldGet,
__classPrivateFieldSet,
__classPrivateFieldIn,
__addDisposableResource,
__disposeResources,
};
webpack://frontend-mybets/../../node_modules/ts-invariant/lib/invariant.js
import { __extends } from "tslib";
var genericMessage = "Invariant Violation";
var _a = Object.setPrototypeOf, setPrototypeOf = _a === void 0 ? function (obj, proto) {
obj.__proto__ = proto;
return obj;
} : _a;
var InvariantError = /** @class */ (function (_super) {
__extends(InvariantError, _super);
function InvariantError(message) {
if (message === void 0) { message = genericMessage; }
var _this = _super.call(this, typeof message === "number"
? genericMessage + ": " + message + " (see https://github.com/apollographql/invariant-packages)"
: message) || this;
_this.framesToPop = 1;
_this.name = genericMessage;
setPrototypeOf(_this, InvariantError.prototype);
return _this;
}
return InvariantError;
}(Error));
export { InvariantError };
export function invariant(condition, message) {
if (!condition) {
throw new InvariantError(message);
}
}
var verbosityLevels = ["debug", "log", "warn", "error", "silent"];
var verbosityLevel = verbosityLevels.indexOf("log");
function wrapConsoleMethod(name) {
return function () {
if (verbosityLevels.indexOf(name) >= verbosityLevel) {
// Default to console.log if this host environment happens not to provide
// all the console.* methods we need.
var method = console[name] || console.log;
return method.apply(console, arguments);
}
};
}
(function (invariant) {
invariant.debug = wrapConsoleMethod("debug");
invariant.log = wrapConsoleMethod("log");
invariant.warn = wrapConsoleMethod("warn");
invariant.error = wrapConsoleMethod("error");
})(invariant || (invariant = {}));
export function setVerbosity(level) {
var old = verbosityLevels[verbosityLevel];
verbosityLevel = Math.max(0, verbosityLevels.indexOf(level));
return old;
}
export default invariant;
//# sourceMappingURL=invariant.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/version.js
export var version = "3.9.4"; //# sourceMappingURL=version.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/globals/maybe.js
export function maybe(thunk) {
try {
return thunk();
}
catch (_a) { }
}
//# sourceMappingURL=maybe.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/globals/global.js
import { maybe } from "./maybe.js";
export default (maybe(function () { return globalThis; }) ||
maybe(function () { return window; }) ||
maybe(function () { return self; }) ||
maybe(function () { return global; }) || // We don't expect the Function constructor ever to be invoked at runtime, as
// long as at least one of globalThis, window, self, or global is defined, so
// we are under no obligation to make it easy for static analysis tools to
// detect syntactic usage of the Function constructor. If you think you can
// improve your static analysis to detect this obfuscation, think again. This
// is an arms race you cannot win, at least not in JavaScript.
maybe(function () {
return maybe.constructor("return this")();
}));
//# sourceMappingURL=global.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/common/makeUniqueId.js
var prefixCounts = new Map();
// These IDs won't be globally unique, but they will be unique within this
// process, thanks to the counter, and unguessable thanks to the random suffix.
export function makeUniqueId(prefix) {
var count = prefixCounts.get(prefix) || 1;
prefixCounts.set(prefix, count + 1);
return "".concat(prefix, ":").concat(count, ":").concat(Math.random().toString(36).slice(2));
}
//# sourceMappingURL=makeUniqueId.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/common/stringifyForDisplay.js
import { makeUniqueId } from "./makeUniqueId.js";
export function stringifyForDisplay(value, space) {
if (space === void 0) { space = 0; }
var undefId = makeUniqueId("stringifyForDisplay");
return JSON.stringify(value, function (key, value) {
return value === void 0 ? undefId : value;
}, space)
.split(JSON.stringify(undefId))
.join("<undefined>");
}
//# sourceMappingURL=stringifyForDisplay.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/globals/invariantWrappers.js
import { invariant as originalInvariant, InvariantError } from "ts-invariant";
import { version } from "../../version.js";
import global from "./global.js";
import { stringifyForDisplay } from "../common/stringifyForDisplay.js";
function wrap(fn) {
return function (message) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
if (typeof message === "number") {
var arg0 = message;
message = getHandledErrorMsg(arg0);
if (!message) {
message = getFallbackErrorMsg(arg0, args);
args = [];
}
}
fn.apply(void 0, [message].concat(args));
};
}
var invariant = Object.assign(function invariant(condition, message) {
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
if (!condition) {
originalInvariant(condition, getHandledErrorMsg(message, args) || getFallbackErrorMsg(message, args));
}
}, {
debug: wrap(originalInvariant.debug),
log: wrap(originalInvariant.log),
warn: wrap(originalInvariant.warn),
error: wrap(originalInvariant.error),
});
/**
* Returns an InvariantError.
*
* `message` can only be a string, a concatenation of strings, or a ternary statement
* that results in a string. This will be enforced on build, where the message will
* be replaced with a message number.
* String substitutions with %s are supported and will also return
* pretty-stringified objects.
* Excess `optionalParams` will be swallowed.
*/
function newInvariantError(message) {
var optionalParams = [];
for (var _i = 1; _i < arguments.length; _i++) {
optionalParams[_i - 1] = arguments[_i];
}
return new InvariantError(getHandledErrorMsg(message, optionalParams) ||
getFallbackErrorMsg(message, optionalParams));
}
var ApolloErrorMessageHandler = Symbol.for("ApolloErrorMessageHandler_" + version);
function stringify(arg) {
return typeof arg == "string" ? arg : (stringifyForDisplay(arg, 2).slice(0, 1000));
}
function getHandledErrorMsg(message, messageArgs) {
if (messageArgs === void 0) { messageArgs = []; }
if (!message)
return;
return (global[ApolloErrorMessageHandler] &&
global[ApolloErrorMessageHandler](message, messageArgs.map(stringify)));
}
function getFallbackErrorMsg(message, messageArgs) {
if (messageArgs === void 0) { messageArgs = []; }
if (!message)
return;
return "An error occurred! For more details, see the full error text at https://go.apollo.dev/c/err#".concat(encodeURIComponent(JSON.stringify({
version: version,
message: message,
args: messageArgs.map(stringify),
})));
}
export { invariant, InvariantError, newInvariantError, ApolloErrorMessageHandler, };
//# sourceMappingURL=invariantWrappers.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/globals/index.js
import { invariant, newInvariantError, InvariantError, } from "./invariantWrappers.js";
export { maybe } from "./maybe.js";
export { default as global } from "./global.js";
export { invariant, newInvariantError, InvariantError };
/**
* @deprecated we do not use this internally anymore,
* it is just exported for backwards compatibility
*/
// this file is extempt from automatic `__DEV__` replacement
// so we have to write it out here
// @ts-ignore
export var DEV = globalThis.__DEV__ !== false;
export { DEV as __DEV__ };
//# sourceMappingURL=index.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/common/canUse.js
import { maybe } from "../globals/index.js";
export var canUseWeakMap = typeof WeakMap === "function" &&
!maybe(function () { return navigator.product == "ReactNative" && !global.HermesInternal; });
export var canUseWeakSet = typeof WeakSet === "function";
export var canUseSymbol = typeof Symbol === "function" && typeof Symbol.for === "function";
export var canUseAsyncIteratorSymbol = canUseSymbol && Symbol.asyncIterator;
export var canUseDOM = typeof maybe(function () { return window.document.createElement; }) === "function";
var usingJSDOM =
// Following advice found in this comment from @domenic (maintainer of jsdom):
// https://github.com/jsdom/jsdom/issues/1537#issuecomment-229405327
//
// Since we control the version of Jest and jsdom used when running Apollo
// Client tests, and that version is recent enought to include " jsdom/x.y.z"
// at the end of the user agent string, I believe this case is all we need to
// check. Testing for "Node.js" was recommended for backwards compatibility
// with older version of jsdom, but we don't have that problem.
maybe(function () { return navigator.userAgent.indexOf("jsdom") >= 0; }) || false;
// Our tests should all continue to pass if we remove this !usingJSDOM
// condition, thereby allowing useLayoutEffect when using jsdom. Unfortunately,
// if we allow useLayoutEffect, then useSyncExternalStore generates many
// warnings about useLayoutEffect doing nothing on the server. While these
// warnings are harmless, this !usingJSDOM condition seems to be the best way to
// prevent them (i.e. skipping useLayoutEffect when using jsdom).
export var canUseLayoutEffect = canUseDOM && !usingJSDOM;
//# sourceMappingURL=canUse.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/react/context/ApolloContext.js
import * as React from "rehackt";
import { canUseSymbol } from "../../utilities/index.js";
import { invariant } from "../../utilities/globals/index.js";
// To make sure Apollo Client doesn't create more than one React context
// (which can lead to problems like having an Apollo Client instance added
// in one context, then attempting to retrieve it from another different
// context), a single Apollo context is created and tracked in global state.
var contextKey = canUseSymbol ? Symbol.for("__APOLLO_CONTEXT__") : "__APOLLO_CONTEXT__";
export function getApolloContext() {
invariant("createContext" in React, 45);
var context = React.createContext[contextKey];
if (!context) {
Object.defineProperty(React.createContext, contextKey, {
value: (context = React.createContext({})),
enumerable: false,
writable: false,
configurable: true,
});
context.displayName = "ApolloContext";
}
return context;
}
/**
* @deprecated This function has no "resetting" effect since Apollo Client 3.4.12,
* and will be removed in the next major version of Apollo Client.
* If you want to get the Apollo Context, use `getApolloContext` instead.
*/
export var resetApolloContext = getApolloContext;
//# sourceMappingURL=ApolloContext.js.map
webpack://frontend-mybets/../../node_modules/@remix-run/router/dist/router.js
/**
* @remix-run/router v1.0.2
*
* Copyright (c) Remix Software Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
function _extends() {
_extends = Object.assign ? Object.assign.bind() : 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);
}
////////////////////////////////////////////////////////////////////////////////
//#region Types and Constants
////////////////////////////////////////////////////////////////////////////////
/**
* Actions represent the type of change to a location value.
*/
var Action;
(function (Action) {
/**
* A POP indicates a change to an arbitrary index in the history stack, such
* as a back or forward navigation. It does not describe the direction of the
* navigation, only that the current index changed.
*
* Note: This is the default action for newly created history objects.
*/
Action["Pop"] = "POP";
/**
* A PUSH indicates a new entry being added to the history stack, such as when
* a link is clicked and a new page loads. When this happens, all subsequent
* entries in the stack are lost.
*/
Action["Push"] = "PUSH";
/**
* A REPLACE indicates the entry at the current index in the history stack
* being replaced by a new one.
*/
Action["Replace"] = "REPLACE";
})(Action || (Action = {}));
const PopStateEventType = "popstate";
/**
* Memory history stores the current location in memory. It is designed for use
* in stateful non-browser environments like tests and React Native.
*/
function createMemoryHistory(options) {
if (options === void 0) {
options = {};
}
let {
initialEntries = ["/"],
initialIndex,
v5Compat = false
} = options;
let entries; // Declare so we can access from createMemoryLocation
entries = initialEntries.map((entry, index) => createMemoryLocation(entry, typeof entry === "string" ? null : entry.state, index === 0 ? "default" : undefined));
let index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex);
let action = Action.Pop;
let listener = null;
function clampIndex(n) {
return Math.min(Math.max(n, 0), entries.length - 1);
}
function getCurrentLocation() {
return entries[index];
}
function createMemoryLocation(to, state, key) {
if (state === void 0) {
state = null;
}
let location = createLocation(entries ? getCurrentLocation().pathname : "/", to, state, key);
warning$1(location.pathname.charAt(0) === "/", "relative pathnames are not supported in memory history: " + JSON.stringify(to));
return location;
}
let history = {
get index() {
return index;
},
get action() {
return action;
},
get location() {
return getCurrentLocation();
},
createHref(to) {
return typeof to === "string" ? to : createPath(to);
},
push(to, state) {
action = Action.Push;
let nextLocation = createMemoryLocation(to, state);
index += 1;
entries.splice(index, entries.length, nextLocation);
if (v5Compat && listener) {
listener({
action,
location: nextLocation
});
}
},
replace(to, state) {
action = Action.Replace;
let nextLocation = createMemoryLocation(to, state);
entries[index] = nextLocation;
if (v5Compat && listener) {
listener({
action,
location: nextLocation
});
}
},
go(delta) {
action = Action.Pop;
index = clampIndex(index + delta);
if (listener) {
listener({
action,
location: getCurrentLocation()
});
}
},
listen(fn) {
listener = fn;
return () => {
listener = null;
};
}
};
return history;
}
/**
* Browser history stores the location in regular URLs. This is the standard for
* most web apps, but it requires some configuration on the server to ensure you
* serve the same app at multiple URLs.
*
* @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory
*/
function createBrowserHistory(options) {
if (options === void 0) {
options = {};
}
function createBrowserLocation(window, globalHistory) {
let {
pathname,
search,
hash
} = window.location;
return createLocation("", {
pathname,
search,
hash
}, // state defaults to `null` because `window.history.state` does
globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default");
}
function createBrowserHref(window, to) {
return typeof to === "string" ? to : createPath(to);
}
return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options);
}
/**
* Hash history stores the location in window.location.hash. This makes it ideal
* for situations where you don't want to send the location to the server for
* some reason, either because you do cannot configure it or the URL space is
* reserved for something else.
*
* @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory
*/
function createHashHistory(options) {
if (options === void 0) {
options = {};
}
function createHashLocation(window, globalHistory) {
let {
pathname = "/",
search = "",
hash = ""
} = parsePath(window.location.hash.substr(1));
return createLocation("", {
pathname,
search,
hash
}, // state defaults to `null` because `window.history.state` does
globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default");
}
function createHashHref(window, to) {
let base = window.document.querySelector("base");
let href = "";
if (base && base.getAttribute("href")) {
let url = window.location.href;
let hashIndex = url.indexOf("#");
href = hashIndex === -1 ? url : url.slice(0, hashIndex);
}
return href + "#" + (typeof to === "string" ? to : createPath(to));
}
function validateHashLocation(location, to) {
warning$1(location.pathname.charAt(0) === "/", "relative pathnames are not supported in hash history.push(" + JSON.stringify(to) + ")");
}
return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options);
} //#endregion
////////////////////////////////////////////////////////////////////////////////
//#region UTILS
////////////////////////////////////////////////////////////////////////////////
function warning$1(cond, message) {
if (!cond) {
// eslint-disable-next-line no-console
if (typeof console !== "undefined") console.warn(message);
try {
// Welcome to debugging history!
//
// This error is thrown as a convenience so you can more easily
// find the source for a warning that appears in the console by
// enabling "pause on exceptions" in your JavaScript debugger.
throw new Error(message); // eslint-disable-next-line no-empty
} catch (e) {}
}
}
function createKey() {
return Math.random().toString(36).substr(2, 8);
}
/**
* For browser-based histories, we combine the state and key into an object
*/
function getHistoryState(location) {
return {
usr: location.state,
key: location.key
};
}
/**
* Creates a Location object with a unique key from the given Path
*/
function createLocation(current, to, state, key) {
if (state === void 0) {
state = null;
}
let location = _extends({
pathname: typeof current === "string" ? current : current.pathname,
search: "",
hash: ""
}, typeof to === "string" ? parsePath(to) : to, {
state,
// TODO: This could be cleaned up. push/replace should probably just take
// full Locations now and avoid the need to run through this flow at all
// But that's a pretty big refactor to the current test suite so going to
// keep as is for the time being and just let any incoming keys take precedence
key: to && to.key || key || createKey()
});
return location;
}
/**
* Creates a string URL path from the given pathname, search, and hash components.
*/
function createPath(_ref) {
let {
pathname = "/",
search = "",
hash = ""
} = _ref;
if (search && search !== "?") pathname += search.charAt(0) === "?" ? search : "?" + search;
if (hash && hash !== "#") pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
return pathname;
}
/**
* Parses a string URL path into its separate pathname, search, and hash components.
*/
function parsePath(path) {
let parsedPath = {};
if (path) {
let hashIndex = path.indexOf("#");
if (hashIndex >= 0) {
parsedPath.hash = path.substr(hashIndex);
path = path.substr(0, hashIndex);
}
let searchIndex = path.indexOf("?");
if (searchIndex >= 0) {
parsedPath.search = path.substr(searchIndex);
path = path.substr(0, searchIndex);
}
if (path) {
parsedPath.pathname = path;
}
}
return parsedPath;
}
function getUrlBasedHistory(getLocation, createHref, validateLocation, options) {
if (options === void 0) {
options = {};
}
let {
window = document.defaultView,
v5Compat = false
} = options;
let globalHistory = window.history;
let action = Action.Pop;
let listener = null;
function handlePop() {
action = Action.Pop;
if (listener) {
listener({
action,
location: history.location
});
}
}
function push(to, state) {
action = Action.Push;
let location = createLocation(history.location, to, state);
if (validateLocation) validateLocation(location, to);
let historyState = getHistoryState(location);
let url = history.createHref(location); // try...catch because iOS limits us to 100 pushState calls :/
try {
globalHistory.pushState(historyState, "", url);
} catch (error) {
// They are going to lose state here, but there is no real
// way to warn them about it since the page will refresh...
window.location.assign(url);
}
if (v5Compat && listener) {
listener({
action,
location
});
}
}
function replace(to, state) {
action = Action.Replace;
let location = createLocation(history.location, to, state);
if (validateLocation) validateLocation(location, to);
let historyState = getHistoryState(location);
let url = history.createHref(location);
globalHistory.replaceState(historyState, "", url);
if (v5Compat && listener) {
listener({
action,
location: location
});
}
}
let history = {
get action() {
return action;
},
get location() {
return getLocation(window, globalHistory);
},
listen(fn) {
if (listener) {
throw new Error("A history only accepts one active listener");
}
window.addEventListener(PopStateEventType, handlePop);
listener = fn;
return () => {
window.removeEventListener(PopStateEventType, handlePop);
listener = null;
};
},
createHref(to) {
return createHref(window, to);
},
push,
replace,
go(n) {
return globalHistory.go(n);
}
};
return history;
} //#endregion
var ResultType;
(function (ResultType) {
ResultType["data"] = "data";
ResultType["deferred"] = "deferred";
ResultType["redirect"] = "redirect";
ResultType["error"] = "error";
})(ResultType || (ResultType = {}));
function isIndexRoute(route) {
return route.index === true;
} // Walk the route tree generating unique IDs where necessary so we are working
// solely with AgnosticDataRouteObject's within the Router
function convertRoutesToDataRoutes(routes, parentPath, allIds) {
if (parentPath === void 0) {
parentPath = [];
}
if (allIds === void 0) {
allIds = new Set();
}
return routes.map((route, index) => {
let treePath = [...parentPath, index];
let id = typeof route.id === "string" ? route.id : treePath.join("-");
invariant(route.index !== true || !route.children, "Cannot specify children on an index route");
invariant(!allIds.has(id), "Found a route id collision on id \"" + id + "\". Route " + "id's must be globally unique within Data Router usages");
allIds.add(id);
if (isIndexRoute(route)) {
let indexRoute = _extends({}, route, {
id
});
return indexRoute;
} else {
let pathOrLayoutRoute = _extends({}, route, {
id,
children: route.children ? convertRoutesToDataRoutes(route.children, treePath, allIds) : undefined
});
return pathOrLayoutRoute;
}
});
}
/**
* Matches the given routes to a location and returns the match data.
*
* @see https://reactrouter.com/docs/en/v6/utils/match-routes
*/
function matchRoutes(routes, locationArg, basename) {
if (basename === void 0) {
basename = "/";
}
let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
let pathname = stripBasename(location.pathname || "/", basename);
if (pathname == null) {
return null;
}
let branches = flattenRoutes(routes);
rankRouteBranches(branches);
let matches = null;
for (let i = 0; matches == null && i < branches.length; ++i) {
matches = matchRouteBranch(branches[i], pathname);
}
return matches;
}
function flattenRoutes(routes, branches, parentsMeta, parentPath) {
if (branches === void 0) {
branches = [];
}
if (parentsMeta === void 0) {
parentsMeta = [];
}
if (parentPath === void 0) {
parentPath = "";
}
routes.forEach((route, index) => {
let meta = {
relativePath: route.path || "",
caseSensitive: route.caseSensitive === true,
childrenIndex: index,
route
};
if (meta.relativePath.startsWith("/")) {
invariant(meta.relativePath.startsWith(parentPath), "Absolute route path \"" + meta.relativePath + "\" nested under path " + ("\"" + parentPath + "\" is not valid. An absolute child route path ") + "must start with the combined path of all its parent routes.");
meta.relativePath = meta.relativePath.slice(parentPath.length);
}
let path = joinPaths([parentPath, meta.relativePath]);
let routesMeta = parentsMeta.concat(meta); // Add the children before adding this route to the array so we traverse the
// route tree depth-first and child routes appear before their parents in
// the "flattened" version.
if (route.children && route.children.length > 0) {
invariant( // Our types know better, but runtime JS may not!
// @ts-expect-error
route.index !== true, "Index routes must not have child routes. Please remove " + ("all child routes from route path \"" + path + "\"."));
flattenRoutes(route.children, branches, routesMeta, path);
} // Routes without a path shouldn't ever match by themselves unless they are
// index routes, so don't add them to the list of possible branches.
if (route.path == null && !route.index) {
return;
}
branches.push({
path,
score: computeScore(path, route.index),
routesMeta
});
});
return branches;
}
function rankRouteBranches(branches) {
branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first
: compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex)));
}
const paramRe = /^:\w+$/;
const dynamicSegmentValue = 3;
const indexRouteValue = 2;
const emptySegmentValue = 1;
const staticSegmentValue = 10;
const splatPenalty = -2;
const isSplat = s => s === "*";
function computeScore(path, index) {
let segments = path.split("/");
let initialScore = segments.length;
if (segments.some(isSplat)) {
initialScore += splatPenalty;
}
if (index) {
initialScore += indexRouteValue;
}
return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore);
}
function compareIndexes(a, b) {
let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
return siblings ? // If two routes are siblings, we should try to match the earlier sibling
// first. This allows people to have fine-grained control over the matching
// behavior by simply putting routes with identical paths in the order they
// want them tried.
a[a.length - 1] - b[b.length - 1] : // Otherwise, it doesn't really make sense to rank non-siblings by index,
// so they sort equally.
0;
}
function matchRouteBranch(branch, pathname) {
let {
routesMeta
} = branch;
let matchedParams = {};
let matchedPathname = "/";
let matches = [];
for (let i = 0; i < routesMeta.length; ++i) {
let meta = routesMeta[i];
let end = i === routesMeta.length - 1;
let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
let match = matchPath({
path: meta.relativePath,
caseSensitive: meta.caseSensitive,
end
}, remainingPathname);
if (!match) return null;
Object.assign(matchedParams, match.params);
let route = meta.route;
matches.push({
// TODO: Can this as be avoided?
params: matchedParams,
pathname: joinPaths([matchedPathname, match.pathname]),
pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),
route
});
if (match.pathnameBase !== "/") {
matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
}
}
return matches;
}
/**
* Returns a path with params interpolated.
*
* @see https://reactrouter.com/docs/en/v6/utils/generate-path
*/
function generatePath(path, params) {
if (params === void 0) {
params = {};
}
return path.replace(/:(\w+)/g, (_, key) => {
invariant(params[key] != null, "Missing \":" + key + "\" param");
return params[key];
}).replace(/(\/?)\*/, (_, prefix, __, str) => {
const star = "*";
if (params[star] == null) {
// If no splat was provided, trim the trailing slash _unless_ it's
// the entire path
return str === "/*" ? "/" : "";
} // Apply the splat
return "" + prefix + params[star];
});
}
/**
* Performs pattern matching on a URL pathname and returns information about
* the match.
*
* @see https://reactrouter.com/docs/en/v6/utils/match-path
*/
function matchPath(pattern, pathname) {
if (typeof pattern === "string") {
pattern = {
path: pattern,
caseSensitive: false,
end: true
};
}
let [matcher, paramNames] = compilePath(pattern.path, pattern.caseSensitive, pattern.end);
let match = pathname.match(matcher);
if (!match) return null;
let matchedPathname = match[0];
let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
let captureGroups = match.slice(1);
let params = paramNames.reduce((memo, paramName, index) => {
// We need to compute the pathnameBase here using the raw splat value
// instead of using params["*"] later because it will be decoded then
if (paramName === "*") {
let splatValue = captureGroups[index] || "";
pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
}
memo[paramName] = safelyDecodeURIComponent(captureGroups[index] || "", paramName);
return memo;
}, {});
return {
params,
pathname: matchedPathname,
pathnameBase,
pattern
};
}
function compilePath(path, caseSensitive, end) {
if (caseSensitive === void 0) {
caseSensitive = false;
}
if (end === void 0) {
end = true;
}
warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\"."));
let paramNames = [];
let regexpSource = "^" + path.replace(/\/*\*?$/, "") // Ignore trailing / and /*, we'll handle it below
.replace(/^\/*/, "/") // Make sure it has a leading /
.replace(/[\\.*+^$?{}|()[\]]/g, "\\$&") // Escape special regex chars
.replace(/:(\w+)/g, (_, paramName) => {
paramNames.push(paramName);
return "([^\\/]+)";
});
if (path.endsWith("*")) {
paramNames.push("*");
regexpSource += path === "*" || path === "/*" ? "(.*)$" // Already matched the initial /, just match the rest
: "(?:\\/(.+)|\\/*)$"; // Don't include the / in params["*"]
} else if (end) {
// When matching to the end, ignore trailing slashes
regexpSource += "\\/*$";
} else if (path !== "" && path !== "/") {
// If our path is non-empty and contains anything beyond an initial slash,
// then we have _some_ form of path in our regex so we should expect to
// match only if we find the end of this path segment. Look for an optional
// non-captured trailing slash (to match a portion of the URL) or the end
// of the path (if we've matched to the end). We used to do this with a
// word boundary but that gives false positives on routes like
// /user-preferences since `-` counts as a word boundary.
regexpSource += "(?:(?=\\/|$))";
} else ;
let matcher = new RegExp(regexpSource, caseSensitive ? undefined : "i");
return [matcher, paramNames];
}
function safelyDecodeURIComponent(value, paramName) {
try {
return decodeURIComponent(value);
} catch (error) {
warning(false, "The value for the URL param \"" + paramName + "\" will not be decoded because" + (" the string \"" + value + "\" is a malformed URL segment. This is probably") + (" due to a bad percent encoding (" + error + ")."));
return value;
}
}
/**
* @private
*/
function stripBasename(pathname, basename) {
if (basename === "/") return pathname;
if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
return null;
} // We want to leave trailing slash behavior in the user's control, so if they
// specify a basename with a trailing slash, we should support it
let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
let nextChar = pathname.charAt(startIndex);
if (nextChar && nextChar !== "/") {
// pathname does not start with basename/
return null;
}
return pathname.slice(startIndex) || "/";
}
function invariant(value, message) {
if (value === false || value === null || typeof value === "undefined") {
throw new Error(message);
}
}
/**
* @private
*/
function warning(cond, message) {
if (!cond) {
// eslint-disable-next-line no-console
if (typeof console !== "undefined") console.warn(message);
try {
// Welcome to debugging React Router!
//
// This error is thrown as a convenience so you can more easily
// find the source for a warning that appears in the console by
// enabling "pause on exceptions" in your JavaScript debugger.
throw new Error(message); // eslint-disable-next-line no-empty
} catch (e) {}
}
}
/**
* Returns a resolved path object relative to the given pathname.
*
* @see https://reactrouter.com/docs/en/v6/utils/resolve-path
*/
function resolvePath(to, fromPathname) {
if (fromPathname === void 0) {
fromPathname = "/";
}
let {
pathname: toPathname,
search = "",
hash = ""
} = typeof to === "string" ? parsePath(to) : to;
let pathname = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname;
return {
pathname,
search: normalizeSearch(search),
hash: normalizeHash(hash)
};
}
function resolvePathname(relativePath, fromPathname) {
let segments = fromPathname.replace(/\/+$/, "").split("/");
let relativeSegments = relativePath.split("/");
relativeSegments.forEach(segment => {
if (segment === "..") {
// Keep the root "" segment so the pathname starts at /
if (segments.length > 1) segments.pop();
} else if (segment !== ".") {
segments.push(segment);
}
});
return segments.length > 1 ? segments.join("/") : "/";
}
function getInvalidPathError(char, field, dest, path) {
return "Cannot include a '" + char + "' character in a manually specified " + ("`to." + field + "` field [" + JSON.stringify(path) + "]. Please separate it out to the ") + ("`to." + dest + "` field. Alternatively you may provide the full path as ") + "a string in <Link to=\"...\"> and the router will parse it for you.";
}
/**
* @private
*/
function resolveTo(toArg, routePathnames, locationPathname, isPathRelative) {
if (isPathRelative === void 0) {
isPathRelative = false;
}
let to;
if (typeof toArg === "string") {
to = parsePath(toArg);
} else {
to = _extends({}, toArg);
invariant(!to.pathname || !to.pathname.includes("?"), getInvalidPathError("?", "pathname", "search", to));
invariant(!to.pathname || !to.pathname.includes("#"), getInvalidPathError("#", "pathname", "hash", to));
invariant(!to.search || !to.search.includes("#"), getInvalidPathError("#", "search", "hash", to));
}
let isEmptyPath = toArg === "" || to.pathname === "";
let toPathname = isEmptyPath ? "/" : to.pathname;
let from; // Routing is relative to the current pathname if explicitly requested.
//
// If a pathname is explicitly provided in `to`, it should be relative to the
// route context. This is explained in `Note on `<Link to>` values` in our
// migration guide from v5 as a means of disambiguation between `to` values
// that begin with `/` and those that do not. However, this is problematic for
// `to` values that do not provide a pathname. `to` can simply be a search or
// hash string, in which case we should assume that the navigation is relative
// to the current location's pathname and *not* the route pathname.
if (isPathRelative || toPathname == null) {
from = locationPathname;
} else {
let routePathnameIndex = routePathnames.length - 1;
if (toPathname.startsWith("..")) {
let toSegments = toPathname.split("/"); // Each leading .. segment means "go up one route" instead of "go up one
// URL segment". This is a key difference from how <a href> works and a
// major reason we call this a "to" value instead of a "href".
while (toSegments[0] === "..") {
toSegments.shift();
routePathnameIndex -= 1;
}
to.pathname = toSegments.join("/");
} // If there are more ".." segments than parent routes, resolve relative to
// the root / URL.
from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
}
let path = resolvePath(to, from); // Ensure the pathname has a trailing slash if the original "to" had one
let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/"); // Or if this was a link to the current path which has a trailing slash
let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
path.pathname += "/";
}
return path;
}
/**
* @private
*/
function getToPathname(to) {
// Empty strings should be treated the same as / paths
return to === "" || to.pathname === "" ? "/" : typeof to === "string" ? parsePath(to).pathname : to.pathname;
}
/**
* @private
*/
const joinPaths = paths => paths.join("/").replace(/\/\/+/g, "/");
/**
* @private
*/
const normalizePathname = pathname => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
/**
* @private
*/
const normalizeSearch = search => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
/**
* @private
*/
const normalizeHash = hash => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
/**
* This is a shortcut for creating `application/json` responses. Converts `data`
* to JSON and sets the `Content-Type` header.
*/
const json = function json(data, init) {
if (init === void 0) {
init = {};
}
let responseInit = typeof init === "number" ? {
status: init
} : init;
let headers = new Headers(responseInit.headers);
if (!headers.has("Content-Type")) {
headers.set("Content-Type", "application/json; charset=utf-8");
}
return new Response(JSON.stringify(data), _extends({}, responseInit, {
headers
}));
};
class AbortedDeferredError extends Error {}
class DeferredData {
constructor(data) {
this.pendingKeys = new Set();
this.subscriber = undefined;
invariant(data && typeof data === "object" && !Array.isArray(data), "defer() only accepts plain objects"); // Set up an AbortController + Promise we can race against to exit early
// cancellation
let reject;
this.abortPromise = new Promise((_, r) => reject = r);
this.controller = new AbortController();
let onAbort = () => reject(new AbortedDeferredError("Deferred data aborted"));
this.unlistenAbortSignal = () => this.controller.signal.removeEventListener("abort", onAbort);
this.controller.signal.addEventListener("abort", onAbort);
this.data = Object.entries(data).reduce((acc, _ref) => {
let [key, value] = _ref;
return Object.assign(acc, {
[key]: this.trackPromise(key, value)
});
}, {});
}
trackPromise(key, value) {
if (!(value instanceof Promise)) {
return value;
}
this.pendingKeys.add(key); // We store a little wrapper promise that will be extended with
// _data/_error props upon resolve/reject
let promise = Promise.race([value, this.abortPromise]).then(data => this.onSettle(promise, key, null, data), error => this.onSettle(promise, key, error)); // Register rejection listeners to avoid uncaught promise rejections on
// errors or aborted deferred values
promise.catch(() => {});
Object.defineProperty(promise, "_tracked", {
get: () => true
});
return promise;
}
onSettle(promise, key, error, data) {
if (this.controller.signal.aborted && error instanceof AbortedDeferredError) {
this.unlistenAbortSignal();
Object.defineProperty(promise, "_error", {
get: () => error
});
return Promise.reject(error);
}
this.pendingKeys.delete(key);
if (this.done) {
// Nothing left to abort!
this.unlistenAbortSignal();
}
const subscriber = this.subscriber;
if (error) {
Object.defineProperty(promise, "_error", {
get: () => error
});
subscriber && subscriber(false);
return Promise.reject(error);
}
Object.defineProperty(promise, "_data", {
get: () => data
});
subscriber && subscriber(false);
return data;
}
subscribe(fn) {
this.subscriber = fn;
}
cancel() {
this.controller.abort();
this.pendingKeys.forEach((v, k) => this.pendingKeys.delete(k));
let subscriber = this.subscriber;
subscriber && subscriber(true);
}
async resolveData(signal) {
let aborted = false;
if (!this.done) {
let onAbort = () => this.cancel();
signal.addEventListener("abort", onAbort);
aborted = await new Promise(resolve => {
this.subscribe(aborted => {
signal.removeEventListener("abort", onAbort);
if (aborted || this.done) {
resolve(aborted);
}
});
});
}
return aborted;
}
get done() {
return this.pendingKeys.size === 0;
}
get unwrappedData() {
invariant(this.data !== null && this.done, "Can only unwrap data on initialized and settled deferreds");
return Object.entries(this.data).reduce((acc, _ref2) => {
let [key, value] = _ref2;
return Object.assign(acc, {
[key]: unwrapTrackedPromise(value)
});
}, {});
}
}
function isTrackedPromise(value) {
return value instanceof Promise && value._tracked === true;
}
function unwrapTrackedPromise(value) {
if (!isTrackedPromise(value)) {
return value;
}
if (value._error) {
throw value._error;
}
return value._data;
}
function defer(data) {
return new DeferredData(data);
}
/**
* A redirect response. Sets the status code and the `Location` header.
* Defaults to "302 Found".
*/
const redirect = function redirect(url, init) {
if (init === void 0) {
init = 302;
}
let responseInit = init;
if (typeof responseInit === "number") {
responseInit = {
status: responseInit
};
} else if (typeof responseInit.status === "undefined") {
responseInit.status = 302;
}
let headers = new Headers(responseInit.headers);
headers.set("Location", url);
return new Response(null, _extends({}, responseInit, {
headers
}));
};
/**
* @private
* Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies
*/
class ErrorResponse {
constructor(status, statusText, data) {
this.status = status;
this.statusText = statusText || "";
this.data = data;
}
}
/**
* Check if the given error is an ErrorResponse generated from a 4xx/5xx
* Response throw from an action/loader
*/
function isRouteErrorResponse(e) {
return e instanceof ErrorResponse;
}
const IDLE_NAVIGATION = {
state: "idle",
location: undefined,
formMethod: undefined,
formAction: undefined,
formEncType: undefined,
formData: undefined
};
const IDLE_FETCHER = {
state: "idle",
data: undefined,
formMethod: undefined,
formAction: undefined,
formEncType: undefined,
formData: undefined
}; //#endregion
////////////////////////////////////////////////////////////////////////////////
//#region createRouter
////////////////////////////////////////////////////////////////////////////////
/**
* Create a router and listen to history POP navigations
*/
function createRouter(init) {
invariant(init.routes.length > 0, "You must provide a non-empty routes array to createRouter");
let dataRoutes = convertRoutesToDataRoutes(init.routes); // Cleanup function for history
let unlistenHistory = null; // Externally-provided functions to call on all state changes
let subscribers = new Set(); // Externally-provided object to hold scroll restoration locations during routing
let savedScrollPositions = null; // Externally-provided function to get scroll restoration keys
let getScrollRestorationKey = null; // Externally-provided function to get current scroll position
let getScrollPosition = null; // One-time flag to control the initial hydration scroll restoration. Because
// we don't get the saved positions from <ScrollRestoration /> until _after_
// the initial render, we need to manually trigger a separate updateState to
// send along the restoreScrollPosition
let initialScrollRestored = false;
let initialMatches = matchRoutes(dataRoutes, init.history.location, init.basename);
let initialErrors = null;
if (initialMatches == null) {
// If we do not match a user-provided-route, fall back to the root
// to allow the error boundary to take over
let {
matches,
route,
error
} = getNotFoundMatches(dataRoutes);
initialMatches = matches;
initialErrors = {
[route.id]: error
};
}
let initialized = !initialMatches.some(m => m.route.loader) || init.hydrationData != null;
let router;
let state = {
historyAction: init.history.action,
location: init.history.location,
matches: initialMatches,
initialized,
navigation: IDLE_NAVIGATION,
restoreScrollPosition: null,
preventScrollReset: false,
revalidation: "idle",
loaderData: init.hydrationData && init.hydrationData.loaderData || {},
actionData: init.hydrationData && init.hydrationData.actionData || null,
errors: init.hydrationData && init.hydrationData.errors || initialErrors,
fetchers: new Map()
}; // -- Stateful internal variables to manage navigations --
// Current navigation in progress (to be committed in completeNavigation)
let pendingAction = Action.Pop; // Should the current navigation prevent the scroll reset if scroll cannot
// be restored?
let pendingPreventScrollReset = false; // AbortController for the active navigation
let pendingNavigationController; // We use this to avoid touching history in completeNavigation if a
// revalidation is entirely uninterrupted
let isUninterruptedRevalidation = false; // Use this internal flag to force revalidation of all loaders:
// - submissions (completed or interrupted)
// - useRevalidate()
// - X-Remix-Revalidate (from redirect)
let isRevalidationRequired = false; // Use this internal array to capture routes that require revalidation due
// to a cancelled deferred on action submission
let cancelledDeferredRoutes = []; // Use this internal array to capture fetcher loads that were cancelled by an
// action navigation and require revalidation
let cancelledFetcherLoads = []; // AbortControllers for any in-flight fetchers
let fetchControllers = new Map(); // Track loads based on the order in which they started
let incrementingLoadId = 0; // Track the outstanding pending navigation data load to be compared against
// the globally incrementing load when a fetcher load lands after a completed
// navigation
let pendingNavigationLoadId = -1; // Fetchers that triggered data reloads as a result of their actions
let fetchReloadIds = new Map(); // Fetchers that triggered redirect navigations from their actions
let fetchRedirectIds = new Set(); // Most recent href/match for fetcher.load calls for fetchers
let fetchLoadMatches = new Map(); // Store DeferredData instances for active route matches. When a
// route loader returns defer() we stick one in here. Then, when a nested
// promise resolves we update loaderData. If a new navigation starts we
// cancel active deferreds for eliminated routes.
let activeDeferreds = new Map(); // Initialize the router, all side effects should be kicked off from here.
// Implemented as a Fluent API for ease of:
// let router = createRouter(init).initialize();
function initialize() {
// If history informs us of a POP navigation, start the navigation but do not update
// state. We'll update our own state once the navigation completes
unlistenHistory = init.history.listen(_ref => {
let {
action: historyAction,
location
} = _ref;
return startNavigation(historyAction, location);
}); // Kick off initial data load if needed. Use Pop to avoid modifying history
if (!state.initialized) {
startNavigation(Action.Pop, state.location);
}
return router;
} // Clean up a router and it's side effects
function dispose() {
if (unlistenHistory) {
unlistenHistory();
}
subscribers.clear();
pendingNavigationController && pendingNavigationController.abort();
state.fetchers.forEach((_, key) => deleteFetcher(key));
} // Subscribe to state updates for the router
function subscribe(fn) {
subscribers.add(fn);
return () => subscribers.delete(fn);
} // Update our state and notify the calling context of the change
function updateState(newState) {
state = _extends({}, state, newState);
subscribers.forEach(subscriber => subscriber(state));
} // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION
// and setting state.[historyAction/location/matches] to the new route.
// - Location is a required param
// - Navigation will always be set to IDLE_NAVIGATION
// - Can pass any other state in newState
function completeNavigation(location, newState) {
var _state$navigation$for;
// Deduce if we're in a loading/actionReload state:
// - We have committed actionData in the store
// - The current navigation was a submission
// - We're past the submitting state and into the loading state
// - The location we've finished loading is different from the submission
// location, indicating we redirected from the action (avoids false
// positives for loading/submissionRedirect when actionData returned
// on a prior submission)
let isActionReload = state.actionData != null && state.navigation.formMethod != null && state.navigation.state === "loading" && ((_state$navigation$for = state.navigation.formAction) == null ? void 0 : _state$navigation$for.split("?")[0]) === location.pathname; // Always preserve any existing loaderData from re-used routes
let newLoaderData = newState.loaderData ? {
loaderData: mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [])
} : {};
updateState(_extends({}, isActionReload ? {} : {
actionData: null
}, newState, newLoaderData, {
historyAction: pendingAction,
location,
initialized: true,
navigation: IDLE_NAVIGATION,
revalidation: "idle",
// Don't restore on submission navigations
restoreScrollPosition: state.navigation.formData ? false : getSavedScrollPosition(location, newState.matches || state.matches),
preventScrollReset: pendingPreventScrollReset
}));
if (isUninterruptedRevalidation) ; else if (pendingAction === Action.Pop) ; else if (pendingAction === Action.Push) {
init.history.push(location, location.state);
} else if (pendingAction === Action.Replace) {
init.history.replace(location, location.state);
} // Reset stateful navigation vars
pendingAction = Action.Pop;
pendingPreventScrollReset = false;
isUninterruptedRevalidation = false;
isRevalidationRequired = false;
cancelledDeferredRoutes = [];
cancelledFetcherLoads = [];
} // Trigger a navigation event, which can either be a numerical POP or a PUSH
// replace with an optional submission
async function navigate(to, opts) {
if (typeof to === "number") {
init.history.go(to);
return;
}
let {
path,
submission,
error
} = normalizeNavigateOptions(to, opts);
let location = createLocation(state.location, path, opts && opts.state);
let historyAction = (opts && opts.replace) === true || submission != null ? Action.Replace : Action.Push;
let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : undefined;
return await startNavigation(historyAction, location, {
submission,
// Send through the formData serialization error if we have one so we can
// render at the right error boundary after we match routes
pendingError: error,
preventScrollReset,
replace: opts && opts.replace
});
} // Revalidate all current loaders. If a navigation is in progress or if this
// is interrupted by a navigation, allow this to "succeed" by calling all
// loaders during the next loader round
function revalidate() {
interruptActiveLoads();
updateState({
revalidation: "loading"
}); // If we're currently submitting an action, we don't need to start a new
// navigation, we'll just let the follow up loader execution call all loaders
if (state.navigation.state === "submitting") {
return;
} // If we're currently in an idle state, start a new navigation for the current
// action/location and mark it as uninterrupted, which will skip the history
// update in completeNavigation
if (state.navigation.state === "idle") {
startNavigation(state.historyAction, state.location, {
startUninterruptedRevalidation: true
});
return;
} // Otherwise, if we're currently in a loading state, just start a new
// navigation to the navigation.location but do not trigger an uninterrupted
// revalidation so that history correctly updates once the navigation completes
startNavigation(pendingAction || state.historyAction, state.navigation.location, {
overrideNavigation: state.navigation
});
} // Start a navigation to the given action/location. Can optionally provide a
// overrideNavigation which will override the normalLoad in the case of a redirect
// navigation
async function startNavigation(historyAction, location, opts) {
// Abort any in-progress navigations and start a new one. Unset any ongoing
// uninterrupted revalidations unless told otherwise, since we want this
// new navigation to update history normally
pendingNavigationController && pendingNavigationController.abort();
pendingNavigationController = null;
pendingAction = historyAction;
isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true; // Save the current scroll position every time we start a new navigation,
// and track whether we should reset scroll on completion
saveScrollPosition(state.location, state.matches);
pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;
let loadingNavigation = opts && opts.overrideNavigation;
let matches = matchRoutes(dataRoutes, location, init.basename); // Short circuit with a 404 on the root error boundary if we match nothing
if (!matches) {
let {
matches: notFoundMatches,
route,
error
} = getNotFoundMatches(dataRoutes); // Cancel all pending deferred on 404s since we don't keep any routes
cancelActiveDeferreds();
completeNavigation(location, {
matches: notFoundMatches,
loaderData: {},
errors: {
[route.id]: error
}
});
return;
} // Short circuit if it's only a hash change
if (isHashChangeOnly(state.location, location)) {
completeNavigation(location, {
matches
});
return;
} // Create a controller/Request for this navigation
pendingNavigationController = new AbortController();
let request = createRequest(location, pendingNavigationController.signal, opts && opts.submission);
let pendingActionData;
let pendingError;
if (opts && opts.pendingError) {
// If we have a pendingError, it means the user attempted a GET submission
// with binary FormData so assign here and skip to handleLoaders. That
// way we handle calling loaders above the boundary etc. It's not really
// different from an actionError in that sense.
pendingError = {
[findNearestBoundary(matches).route.id]: opts.pendingError
};
} else if (opts && opts.submission) {
// Call action if we received an action submission
let actionOutput = await handleAction(request, location, opts.submission, matches, {
replace: opts.replace
});
if (actionOutput.shortCircuited) {
return;
}
pendingActionData = actionOutput.pendingActionData;
pendingError = actionOutput.pendingActionError;
let navigation = _extends({
state: "loading",
location
}, opts.submission);
loadingNavigation = navigation;
} // Call loaders
let {
shortCircuited,
loaderData,
errors
} = await handleLoaders(request, location, matches, loadingNavigation, opts && opts.submission, opts && opts.replace, pendingActionData, pendingError);
if (shortCircuited) {
return;
} // Clean up now that the action/loaders have completed. Don't clean up if
// we short circuited because pendingNavigationController will have already
// been assigned to a new controller for the next navigation
pendingNavigationController = null;
completeNavigation(location, {
matches,
loaderData,
errors
});
} // Call the action matched by the leaf route for this navigation and handle
// redirects/errors
async function handleAction(request, location, submission, matches, opts) {
interruptActiveLoads(); // Put us in a submitting state
let navigation = _extends({
state: "submitting",
location
}, submission);
updateState({
navigation
}); // Call our action and get the result
let result;
let actionMatch = getTargetMatch(matches, location);
if (!actionMatch.route.action) {
result = getMethodNotAllowedResult(location);
} else {
result = await callLoaderOrAction("action", request, actionMatch);
if (request.signal.aborted) {
return {
shortCircuited: true
};
}
}
if (isRedirectResult(result)) {
let redirectNavigation = _extends({
state: "loading",
location: createLocation(state.location, result.location)
}, submission);
await startRedirectNavigation(result, redirectNavigation, opts && opts.replace);
return {
shortCircuited: true
};
}
if (isErrorResult(result)) {
// Store off the pending error - we use it to determine which loaders
// to call and will commit it when we complete the navigation
let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id); // By default, all submissions are REPLACE navigations, but if the
// action threw an error that'll be rendered in an errorElement, we fall
// back to PUSH so that the user can use the back button to get back to
// the pre-submission form location to try again
if ((opts && opts.replace) !== true) {
pendingAction = Action.Push;
}
return {
pendingActionError: {
[boundaryMatch.route.id]: result.error
}
};
}
if (isDeferredResult(result)) {
throw new Error("defer() is not supported in actions");
}
return {
pendingActionData: {
[actionMatch.route.id]: result.data
}
};
} // Call all applicable loaders for the given matches, handling redirects,
// errors, etc.
async function handleLoaders(request, location, matches, overrideNavigation, submission, replace, pendingActionData, pendingError) {
// Figure out the right navigation we want to use for data loading
let loadingNavigation = overrideNavigation;
if (!loadingNavigation) {
let navigation = {
state: "loading",
location,
formMethod: undefined,
formAction: undefined,
formEncType: undefined,
formData: undefined
};
loadingNavigation = navigation;
}
let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(state, matches, submission, location, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, pendingActionData, pendingError, fetchLoadMatches); // Cancel pending deferreds for no-longer-matched routes or routes we're
// about to reload. Note that if this is an action reload we would have
// already cancelled all pending deferreds so this would be a no-op
cancelActiveDeferreds(routeId => !(matches && matches.some(m => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some(m => m.route.id === routeId)); // Short circuit if we have no loaders to run
if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {
completeNavigation(location, {
matches,
loaderData: mergeLoaderData(state.loaderData, {}, matches),
// Commit pending error if we're short circuiting
errors: pendingError || null,
actionData: pendingActionData || null
});
return {
shortCircuited: true
};
} // If this is an uninterrupted revalidation, we remain in our current idle
// state. If not, we need to switch to our loading state and load data,
// preserving any new action data or existing action data (in the case of
// a revalidation interrupting an actionReload)
if (!isUninterruptedRevalidation) {
revalidatingFetchers.forEach(_ref2 => {
let [key] = _ref2;
const fetcher = state.fetchers.get(key);
let revalidatingFetcher = {
state: "loading",
data: fetcher && fetcher.data,
formMethod: undefined,
formAction: undefined,
formEncType: undefined,
formData: undefined
};
state.fetchers.set(key, revalidatingFetcher);
});
updateState(_extends({
navigation: loadingNavigation,
actionData: pendingActionData || state.actionData || null
}, revalidatingFetchers.length > 0 ? {
fetchers: new Map(state.fetchers)
} : {}));
}
pendingNavigationLoadId = ++incrementingLoadId;
revalidatingFetchers.forEach(_ref3 => {
let [key] = _ref3;
return fetchControllers.set(key, pendingNavigationController);
});
let {
results,
loaderResults,
fetcherResults
} = await callLoadersAndMaybeResolveData(state.matches, matchesToLoad, revalidatingFetchers, request);
if (request.signal.aborted) {
return {
shortCircuited: true
};
} // Clean up _after_ loaders have completed. Don't clean up if we short
// circuited because fetchControllers would have been aborted and
// reassigned to new controllers for the next navigation
revalidatingFetchers.forEach(_ref4 => {
let [key] = _ref4;
return fetchControllers.delete(key);
}); // If any loaders returned a redirect Response, start a new REPLACE navigation
let redirect = findRedirect(results);
if (redirect) {
let redirectNavigation = getLoaderRedirect(state, redirect);
await startRedirectNavigation(redirect, redirectNavigation, replace);
return {
shortCircuited: true
};
} // Process and commit output from loaders
let {
loaderData,
errors
} = processLoaderData(state, matches, matchesToLoad, loaderResults, pendingError, revalidatingFetchers, fetcherResults, activeDeferreds); // Wire up subscribers to update loaderData as promises settle
activeDeferreds.forEach((deferredData, routeId) => {
deferredData.subscribe(aborted => {
// Note: No need to updateState here since the TrackedPromise on
// loaderData is stable across resolve/reject
// Remove this instance if we were aborted or if promises have settled
if (aborted || deferredData.done) {
activeDeferreds.delete(routeId);
}
});
});
markFetchRedirectsDone();
let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);
return _extends({
loaderData,
errors
}, didAbortFetchLoads || revalidatingFetchers.length > 0 ? {
fetchers: new Map(state.fetchers)
} : {});
}
function getFetcher(key) {
return state.fetchers.get(key) || IDLE_FETCHER;
} // Trigger a fetcher load/submit for the given fetcher key
function fetch(key, routeId, href, opts) {
if (typeof AbortController === "undefined") {
throw new Error("router.fetch() was called during the server render, but it shouldn't be. " + "You are likely calling a useFetcher() method in the body of your component. " + "Try moving it to a useEffect or a callback.");
}
if (fetchControllers.has(key)) abortFetcher(key);
let matches = matchRoutes(dataRoutes, href, init.basename);
if (!matches) {
setFetcherError(key, routeId, new ErrorResponse(404, "Not Found", null));
return;
}
let {
path,
submission
} = normalizeNavigateOptions(href, opts, true);
let match = getTargetMatch(matches, path);
if (submission) {
handleFetcherAction(key, routeId, path, match, submission);
return;
} // Store off the match so we can call it's shouldRevalidate on subsequent
// revalidations
fetchLoadMatches.set(key, [path, match]);
handleFetcherLoader(key, routeId, path, match);
} // Call the action for the matched fetcher.submit(), and then handle redirects,
// errors, and revalidation
async function handleFetcherAction(key, routeId, path, match, submission) {
interruptActiveLoads();
fetchLoadMatches.delete(key);
if (!match.route.action) {
let {
error
} = getMethodNotAllowedResult(path);
setFetcherError(key, routeId, error);
return;
} // Put this fetcher into it's submitting state
let existingFetcher = state.fetchers.get(key);
let fetcher = _extends({
state: "submitting"
}, submission, {
data: existingFetcher && existingFetcher.data
});
state.fetchers.set(key, fetcher);
updateState({
fetchers: new Map(state.fetchers)
}); // Call the action for the fetcher
let abortController = new AbortController();
let fetchRequest = createRequest(path, abortController.signal, submission);
fetchControllers.set(key, abortController);
let actionResult = await callLoaderOrAction("action", fetchRequest, match);
if (fetchRequest.signal.aborted) {
// We can delete this so long as we weren't aborted by ou our own fetcher
// re-submit which would have put _new_ controller is in fetchControllers
if (fetchControllers.get(key) === abortController) {
fetchControllers.delete(key);
}
return;
}
if (isRedirectResult(actionResult)) {
fetchControllers.delete(key);
fetchRedirectIds.add(key);
let loadingFetcher = _extends({
state: "loading"
}, submission, {
data: undefined
});
state.fetchers.set(key, loadingFetcher);
updateState({
fetchers: new Map(state.fetchers)
});
let redirectNavigation = _extends({
state: "loading",
location: createLocation(state.location, actionResult.location)
}, submission);
await startRedirectNavigation(actionResult, redirectNavigation);
return;
} // Process any non-redirect errors thrown
if (isErrorResult(actionResult)) {
setFetcherError(key, routeId, actionResult.error);
return;
}
if (isDeferredResult(actionResult)) {
invariant(false, "defer() is not supported in actions");
} // Start the data load for current matches, or the next location if we're
// in the middle of a navigation
let nextLocation = state.navigation.location || state.location;
let revalidationRequest = createRequest(nextLocation, abortController.signal);
let matches = state.navigation.state !== "idle" ? matchRoutes(dataRoutes, state.navigation.location, init.basename) : state.matches;
invariant(matches, "Didn't find any matches after fetcher action");
let loadId = ++incrementingLoadId;
fetchReloadIds.set(key, loadId);
let loadFetcher = _extends({
state: "loading",
data: actionResult.data
}, submission);
state.fetchers.set(key, loadFetcher);
let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(state, matches, submission, nextLocation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, {
[match.route.id]: actionResult.data
}, undefined, // No need to send through errors since we short circuit above
fetchLoadMatches); // Put all revalidating fetchers into the loading state, except for the
// current fetcher which we want to keep in it's current loading state which
// contains it's action submission info + action data
revalidatingFetchers.filter(_ref5 => {
let [staleKey] = _ref5;
return staleKey !== key;
}).forEach(_ref6 => {
let [staleKey] = _ref6;
let existingFetcher = state.fetchers.get(staleKey);
let revalidatingFetcher = {
state: "loading",
data: existingFetcher && existingFetcher.data,
formMethod: undefined,
formAction: undefined,
formEncType: undefined,
formData: undefined
};
state.fetchers.set(staleKey, revalidatingFetcher);
fetchControllers.set(staleKey, abortController);
});
updateState({
fetchers: new Map(state.fetchers)
});
let {
results,
loaderResults,
fetcherResults
} = await callLoadersAndMaybeResolveData(state.matches, matchesToLoad, revalidatingFetchers, revalidationRequest);
if (abortController.signal.aborted) {
return;
}
fetchReloadIds.delete(key);
fetchControllers.delete(key);
revalidatingFetchers.forEach(_ref7 => {
let [staleKey] = _ref7;
return fetchControllers.delete(staleKey);
});
let redirect = findRedirect(results);
if (redirect) {
let redirectNavigation = getLoaderRedirect(state, redirect);
await startRedirectNavigation(redirect, redirectNavigation);
return;
} // Process and commit output from loaders
let {
loaderData,
errors
} = processLoaderData(state, state.matches, matchesToLoad, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds);
let doneFetcher = {
state: "idle",
data: actionResult.data,
formMethod: undefined,
formAction: undefined,
formEncType: undefined,
formData: undefined
};
state.fetchers.set(key, doneFetcher);
let didAbortFetchLoads = abortStaleFetchLoads(loadId); // If we are currently in a navigation loading state and this fetcher is
// more recent than the navigation, we want the newer data so abort the
// navigation and complete it with the fetcher data
if (state.navigation.state === "loading" && loadId > pendingNavigationLoadId) {
invariant(pendingAction, "Expected pending action");
pendingNavigationController && pendingNavigationController.abort();
completeNavigation(state.navigation.location, {
matches,
loaderData,
errors,
fetchers: new Map(state.fetchers)
});
} else {
// otherwise just update with the fetcher data, preserving any existing
// loaderData for loaders that did not need to reload. We have to
// manually merge here since we aren't going through completeNavigation
updateState(_extends({
errors,
loaderData: mergeLoaderData(state.loaderData, loaderData, matches)
}, didAbortFetchLoads ? {
fetchers: new Map(state.fetchers)
} : {}));
isRevalidationRequired = false;
}
} // Call the matched loader for fetcher.load(), handling redirects, errors, etc.
async function handleFetcherLoader(key, routeId, path, match) {
let existingFetcher = state.fetchers.get(key); // Put this fetcher into it's loading state
let loadingFetcher = {
state: "loading",
formMethod: undefined,
formAction: undefined,
formEncType: undefined,
formData: undefined,
data: existingFetcher && existingFetcher.data
};
state.fetchers.set(key, loadingFetcher);
updateState({
fetchers: new Map(state.fetchers)
}); // Call the loader for this fetcher route match
let abortController = new AbortController();
let fetchRequest = createRequest(path, abortController.signal);
fetchControllers.set(key, abortController);
let result = await callLoaderOrAction("loader", fetchRequest, match); // Deferred isn't supported or fetcher loads, await everything and treat it
// as a normal load. resolveDeferredData will return undefined if this
// fetcher gets aborted, so we just leave result untouched and short circuit
// below if that happens
if (isDeferredResult(result)) {
result = (await resolveDeferredData(result, fetchRequest.signal, true)) || result;
} // We can delete this so long as we weren't aborted by ou our own fetcher
// re-load which would have put _new_ controller is in fetchControllers
if (fetchControllers.get(key) === abortController) {
fetchControllers.delete(key);
}
if (fetchRequest.signal.aborted) {
return;
} // If the loader threw a redirect Response, start a new REPLACE navigation
if (isRedirectResult(result)) {
let redirectNavigation = getLoaderRedirect(state, result);
await startRedirectNavigation(result, redirectNavigation);
return;
} // Process any non-redirect errors thrown
if (isErrorResult(result)) {
let boundaryMatch = findNearestBoundary(state.matches, routeId);
state.fetchers.delete(key); // TODO: In remix, this would reset to IDLE_NAVIGATION if it was a catch -
// do we need to behave any differently with our non-redirect errors?
// What if it was a non-redirect Response?
updateState({
fetchers: new Map(state.fetchers),
errors: {
[boundaryMatch.route.id]: result.error
}
});
return;
}
invariant(!isDeferredResult(result), "Unhandled fetcher deferred data"); // Put the fetcher back into an idle state
let doneFetcher = {
state: "idle",
data: result.data,
formMethod: undefined,
formAction: undefined,
formEncType: undefined,
formData: undefined
};
state.fetchers.set(key, doneFetcher);
updateState({
fetchers: new Map(state.fetchers)
});
}
/**
* Utility function to handle redirects returned from an action or loader.
* Normally, a redirect "replaces" the navigation that triggered it. So, for
* example:
*
* - user is on /a
* - user clicks a link to /b
* - loader for /b redirects to /c
*
* In a non-JS app the browser would track the in-flight navigation to /b and
* then replace it with /c when it encountered the redirect response. In
* the end it would only ever update the URL bar with /c.
*
* In client-side routing using pushState/replaceState, we aim to emulate
* this behavior and we also do not update history until the end of the
* navigation (including processed redirects). This means that we never
* actually touch history until we've processed redirects, so we just use
* the history action from the original navigation (PUSH or REPLACE).
*/
async function startRedirectNavigation(redirect, navigation, replace) {
if (redirect.revalidate) {
isRevalidationRequired = true;
}
invariant(navigation.location, "Expected a location on the redirect navigation"); // There's no need to abort on redirects, since we don't detect the
// redirect until the action/loaders have settled
pendingNavigationController = null;
let redirectHistoryAction = replace === true ? Action.Replace : Action.Push;
await startNavigation(redirectHistoryAction, navigation.location, {
overrideNavigation: navigation
});
}
async function callLoadersAndMaybeResolveData(currentMatches, matchesToLoad, fetchersToLoad, request) {
// Call all navigation loaders and revalidating fetcher loaders in parallel,
// then slice off the results into separate arrays so we can handle them
// accordingly
let results = await Promise.all([...matchesToLoad.map(m => callLoaderOrAction("loader", request, m)), ...fetchersToLoad.map(_ref8 => {
let [, href, match] = _ref8;
return callLoaderOrAction("loader", createRequest(href, request.signal), match);
})]);
let loaderResults = results.slice(0, matchesToLoad.length);
let fetcherResults = results.slice(matchesToLoad.length);
await Promise.all([resolveDeferredResults(currentMatches, matchesToLoad, loaderResults, request.signal, false, state.loaderData), resolveDeferredResults(currentMatches, fetchersToLoad.map(_ref9 => {
let [,, match] = _ref9;
return match;
}), fetcherResults, request.signal, true)]);
return {
results,
loaderResults,
fetcherResults
};
}
function interruptActiveLoads() {
// Every interruption triggers a revalidation
isRevalidationRequired = true; // Cancel pending route-level deferreds and mark cancelled routes for
// revalidation
cancelledDeferredRoutes.push(...cancelActiveDeferreds()); // Abort in-flight fetcher loads
fetchLoadMatches.forEach((_, key) => {
if (fetchControllers.has(key)) {
cancelledFetcherLoads.push(key);
abortFetcher(key);
}
});
}
function setFetcherError(key, routeId, error) {
let boundaryMatch = findNearestBoundary(state.matches, routeId);
deleteFetcher(key);
updateState({
errors: {
[boundaryMatch.route.id]: error
},
fetchers: new Map(state.fetchers)
});
}
function deleteFetcher(key) {
if (fetchControllers.has(key)) abortFetcher(key);
fetchLoadMatches.delete(key);
fetchReloadIds.delete(key);
fetchRedirectIds.delete(key);
state.fetchers.delete(key);
}
function abortFetcher(key) {
let controller = fetchControllers.get(key);
invariant(controller, "Expected fetch controller: " + key);
controller.abort();
fetchControllers.delete(key);
}
function markFetchersDone(keys) {
for (let key of keys) {
let fetcher = getFetcher(key);
let doneFetcher = {
state: "idle",
data: fetcher.data,
formMethod: undefined,
formAction: undefined,
formEncType: undefined,
formData: undefined
};
state.fetchers.set(key, doneFetcher);
}
}
function markFetchRedirectsDone() {
let doneKeys = [];
for (let key of fetchRedirectIds) {
let fetcher = state.fetchers.get(key);
invariant(fetcher, "Expected fetcher: " + key);
if (fetcher.state === "loading") {
fetchRedirectIds.delete(key);
doneKeys.push(key);
}
}
markFetchersDone(doneKeys);
}
function abortStaleFetchLoads(landedId) {
let yeetedKeys = [];
for (let [key, id] of fetchReloadIds) {
if (id < landedId) {
let fetcher = state.fetchers.get(key);
invariant(fetcher, "Expected fetcher: " + key);
if (fetcher.state === "loading") {
abortFetcher(key);
fetchReloadIds.delete(key);
yeetedKeys.push(key);
}
}
}
markFetchersDone(yeetedKeys);
return yeetedKeys.length > 0;
}
function cancelActiveDeferreds(predicate) {
let cancelledRouteIds = [];
activeDeferreds.forEach((dfd, routeId) => {
if (!predicate || predicate(routeId)) {
// Cancel the deferred - but do not remove from activeDeferreds here -
// we rely on the subscribers to do that so our tests can assert proper
// cleanup via _internalActiveDeferreds
dfd.cancel();
cancelledRouteIds.push(routeId);
activeDeferreds.delete(routeId);
}
});
return cancelledRouteIds;
} // Opt in to capturing and reporting scroll positions during navigations,
// used by the <ScrollRestoration> component
function enableScrollRestoration(positions, getPosition, getKey) {
savedScrollPositions = positions;
getScrollPosition = getPosition;
getScrollRestorationKey = getKey || (location => location.key); // Perform initial hydration scroll restoration, since we miss the boat on
// the initial updateState() because we've not yet rendered <ScrollRestoration/>
// and therefore have no savedScrollPositions available
if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {
initialScrollRestored = true;
let y = getSavedScrollPosition(state.location, state.matches);
if (y != null) {
updateState({
restoreScrollPosition: y
});
}
}
return () => {
savedScrollPositions = null;
getScrollPosition = null;
getScrollRestorationKey = null;
};
}
function saveScrollPosition(location, matches) {
if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {
let userMatches = matches.map(m => createUseMatchesMatch(m, state.loaderData));
let key = getScrollRestorationKey(location, userMatches) || location.key;
savedScrollPositions[key] = getScrollPosition();
}
}
function getSavedScrollPosition(location, matches) {
if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {
let userMatches = matches.map(m => createUseMatchesMatch(m, state.loaderData));
let key = getScrollRestorationKey(location, userMatches) || location.key;
let y = savedScrollPositions[key];
if (typeof y === "number") {
return y;
}
}
return null;
}
router = {
get basename() {
return init.basename;
},
get state() {
return state;
},
get routes() {
return dataRoutes;
},
initialize,
subscribe,
enableScrollRestoration,
navigate,
fetch,
revalidate,
createHref,
getFetcher,
deleteFetcher,
dispose,
_internalFetchControllers: fetchControllers,
_internalActiveDeferreds: activeDeferreds
};
return router;
} //#endregion
////////////////////////////////////////////////////////////////////////////////
//#region createStaticHandler
////////////////////////////////////////////////////////////////////////////////
function unstable_createStaticHandler(routes) {
invariant(routes.length > 0, "You must provide a non-empty routes array to unstable_createStaticHandler");
let dataRoutes = convertRoutesToDataRoutes(routes);
async function query(request) {
let {
location,
result
} = await queryImpl(request);
if (result instanceof Response) {
return result;
} // When returning StaticHandlerContext, we patch back in the location here
// since we need it for React Context. But this helps keep our submit and
// loadRouteData operating on a Request instead of a Location
return _extends({
location
}, result);
}
async function queryRoute(request, routeId) {
let {
result
} = await queryImpl(request, routeId);
if (result instanceof Response) {
return result;
}
let error = result.errors ? Object.values(result.errors)[0] : undefined;
if (error !== undefined) {
// While we always re-throw Responses returned from loaders/actions
// directly for route requests and prevent the unwrapping into an
// ErrorResponse, we still need this for error cases _prior_ the
// execution of the loader/action, such as a 404/405 error.
if (isRouteErrorResponse(error)) {
return new Response(error.data, {
status: error.status,
statusText: error.statusText
});
} // If we got back result.errors, that means the loader/action threw
// _something_ that wasn't a Response, but it's not guaranteed/required
// to be an `instanceof Error` either, so we have to use throw here to
// preserve the "error" state outside of queryImpl.
throw error;
} // Pick off the right state value to return
let routeData = [result.actionData, result.loaderData].find(v => v);
let value = Object.values(routeData || {})[0];
if (isRouteErrorResponse(value)) {
return new Response(value.data, {
status: value.status,
statusText: value.statusText
});
}
return value;
}
async function queryImpl(request, routeId) {
invariant(request.method !== "HEAD", "query()/queryRoute() do not support HEAD requests");
invariant(request.signal, "query()/queryRoute() requests must contain an AbortController signal");
let {
location,
matches,
shortCircuitState
} = matchRequest(request, routeId);
try {
if (shortCircuitState) {
return {
location,
result: shortCircuitState
};
}
if (request.method !== "GET") {
let result = await submit(request, matches, getTargetMatch(matches, location), routeId != null);
return {
location,
result
};
}
let result = await loadRouteData(request, matches, routeId != null);
return {
location,
result: _extends({}, result, {
actionData: null,
actionHeaders: {}
})
};
} catch (e) {
if (e instanceof Response) {
return {
location,
result: e
};
}
throw e;
}
}
async function submit(request, matches, actionMatch, isRouteRequest) {
let result;
if (!actionMatch.route.action) {
let href = createHref(new URL(request.url));
result = getMethodNotAllowedResult(href);
} else {
result = await callLoaderOrAction("action", request, actionMatch, true, isRouteRequest);
if (request.signal.aborted) {
let method = isRouteRequest ? "queryRoute" : "query";
throw new Error(method + "() call aborted");
}
}
if (isRedirectResult(result)) {
// Uhhhh - this should never happen, we should always throw these from
// calLoaderOrAction, but the type narrowing here keeps TS happy and we
// can get back on the "throw all redirect responses" train here should
// this ever happen :/
throw new Response(null, {
status: result.status,
headers: {
Location: result.location
}
});
}
if (isDeferredResult(result)) {
throw new Error("defer() is not supported in actions");
}
if (isRouteRequest) {
if (isErrorResult(result)) {
let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);
return {
matches: [actionMatch],
loaderData: {},
actionData: null,
errors: {
[boundaryMatch.route.id]: result.error
},
// Note: statusCode + headers are unused here since queryRoute will
// return the raw Response or value
statusCode: 500,
loaderHeaders: {},
actionHeaders: {}
};
}
return {
matches: [actionMatch],
loaderData: {},
actionData: {
[actionMatch.route.id]: result.data
},
errors: null,
// Note: statusCode + headers are unused here since queryRoute will
// return the raw Response or value
statusCode: 200,
loaderHeaders: {},
actionHeaders: {}
};
}
if (isErrorResult(result)) {
// Store off the pending error - we use it to determine which loaders
// to call and will commit it when we complete the navigation
let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);
let context = await loadRouteData(request, matches, isRouteRequest, {
[boundaryMatch.route.id]: result.error
}); // action status codes take precedence over loader status codes
return _extends({}, context, {
statusCode: isRouteErrorResponse(result.error) ? result.error.status : 500,
actionData: null,
actionHeaders: _extends({}, result.headers ? {
[actionMatch.route.id]: result.headers
} : {})
});
}
let context = await loadRouteData(request, matches, isRouteRequest);
return _extends({}, context, result.statusCode ? {
statusCode: result.statusCode
} : {}, {
actionData: {
[actionMatch.route.id]: result.data
},
actionHeaders: _extends({}, result.headers ? {
[actionMatch.route.id]: result.headers
} : {})
});
}
async function loadRouteData(request, matches, isRouteRequest, pendingActionError) {
let matchesToLoad = getLoaderMatchesUntilBoundary(matches, Object.keys(pendingActionError || {})[0]).filter(m => m.route.loader); // Short circuit if we have no loaders to run
if (matchesToLoad.length === 0) {
return {
matches,
loaderData: {},
errors: pendingActionError || null,
statusCode: 200,
loaderHeaders: {}
};
}
let results = await Promise.all([...matchesToLoad.map(m => callLoaderOrAction("loader", request, m, true, isRouteRequest))]);
if (request.signal.aborted) {
let method = isRouteRequest ? "queryRoute" : "query";
throw new Error(method + "() call aborted");
} // Can't do anything with these without the Remix side of things, so just
// cancel them for now
results.forEach(result => {
if (isDeferredResult(result)) {
result.deferredData.cancel();
}
}); // Process and commit output from loaders
let context = processRouteLoaderData(matches, matchesToLoad, results, pendingActionError);
return _extends({}, context, {
matches
});
}
function matchRequest(req, routeId) {
let url = new URL(req.url);
let location = createLocation("", createPath(url), null, "default");
let matches = matchRoutes(dataRoutes, location);
if (matches && routeId) {
matches = matches.filter(m => m.route.id === routeId);
} // Short circuit with a 404 if we match nothing
if (!matches) {
let {
matches: notFoundMatches,
route,
error
} = getNotFoundMatches(dataRoutes);
return {
location,
matches: notFoundMatches,
shortCircuitState: {
matches: notFoundMatches,
loaderData: {},
actionData: null,
errors: {
[route.id]: error
},
statusCode: 404,
loaderHeaders: {},
actionHeaders: {}
}
};
}
return {
location,
matches
};
}
return {
dataRoutes,
query,
queryRoute
};
} //#endregion
////////////////////////////////////////////////////////////////////////////////
//#region Helpers
////////////////////////////////////////////////////////////////////////////////
/**
* Given an existing StaticHandlerContext and an error thrown at render time,
* provide an updated StaticHandlerContext suitable for a second SSR render
*/
function getStaticContextFromError(routes, context, error) {
let newContext = _extends({}, context, {
statusCode: 500,
errors: {
[context._deepestRenderedBoundaryId || routes[0].id]: error
}
});
return newContext;
} // Normalize navigation options by converting formMethod=GET formData objects to
// URLSearchParams so they behave identically to links with query params
function normalizeNavigateOptions(to, opts, isFetcher) {
if (isFetcher === void 0) {
isFetcher = false;
}
let path = typeof to === "string" ? to : createPath(to); // Return location verbatim on non-submission navigations
if (!opts || !("formMethod" in opts) && !("formData" in opts)) {
return {
path
};
} // Create a Submission on non-GET navigations
if (opts.formMethod != null && opts.formMethod !== "get") {
return {
path,
submission: {
formMethod: opts.formMethod,
formAction: createHref(parsePath(path)),
formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded",
formData: opts.formData
}
};
} // No formData to flatten for GET submission
if (!opts.formData) {
return {
path
};
} // Flatten submission onto URLSearchParams for GET submissions
let parsedPath = parsePath(path);
try {
let searchParams = convertFormDataToSearchParams(opts.formData); // Since fetcher GET submissions only run a single loader (as opposed to
// navigation GET submissions which run all loaders), we need to preserve
// any incoming ?index params
if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {
searchParams.append("index", "");
}
parsedPath.search = "?" + searchParams;
} catch (e) {
return {
path,
error: new ErrorResponse(400, "Bad Request", "Cannot submit binary form data using GET")
};
}
return {
path: createPath(parsedPath)
};
}
function getLoaderRedirect(state, redirect) {
let {
formMethod,
formAction,
formEncType,
formData
} = state.navigation;
let navigation = {
state: "loading",
location: createLocation(state.location, redirect.location),
formMethod: formMethod || undefined,
formAction: formAction || undefined,
formEncType: formEncType || undefined,
formData: formData || undefined
};
return navigation;
} // Filter out all routes below any caught error as they aren't going to
// render so we don't need to load them
function getLoaderMatchesUntilBoundary(matches, boundaryId) {
let boundaryMatches = matches;
if (boundaryId) {
let index = matches.findIndex(m => m.route.id === boundaryId);
if (index >= 0) {
boundaryMatches = matches.slice(0, index);
}
}
return boundaryMatches;
}
function getMatchesToLoad(state, matches, submission, location, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, pendingActionData, pendingError, fetchLoadMatches) {
let actionResult = pendingError ? Object.values(pendingError)[0] : pendingActionData ? Object.values(pendingActionData)[0] : null; // Pick navigation matches that are net-new or qualify for revalidation
let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined;
let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);
let navigationMatches = boundaryMatches.filter((match, index) => match.route.loader != null && (isNewLoader(state.loaderData, state.matches[index], match) || // If this route had a pending deferred cancelled it must be revalidated
cancelledDeferredRoutes.some(id => id === match.route.id) || shouldRevalidateLoader(state.location, state.matches[index], submission, location, match, isRevalidationRequired, actionResult))); // Pick fetcher.loads that need to be revalidated
let revalidatingFetchers = [];
fetchLoadMatches && fetchLoadMatches.forEach((_ref10, key) => {
let [href, match] = _ref10;
// This fetcher was cancelled from a prior action submission - force reload
if (cancelledFetcherLoads.includes(key)) {
revalidatingFetchers.push([key, href, match]);
} else if (isRevalidationRequired) {
let shouldRevalidate = shouldRevalidateLoader(href, match, submission, href, match, isRevalidationRequired, actionResult);
if (shouldRevalidate) {
revalidatingFetchers.push([key, href, match]);
}
}
});
return [navigationMatches, revalidatingFetchers];
}
function isNewLoader(currentLoaderData, currentMatch, match) {
let isNew = // [a] -> [a, b]
!currentMatch || // [a, b] -> [a, c]
match.route.id !== currentMatch.route.id; // Handle the case that we don't have data for a re-used route, potentially
// from a prior error or from a cancelled pending deferred
let isMissingData = currentLoaderData[match.route.id] === undefined; // Always load if this is a net-new route or we don't yet have data
return isNew || isMissingData;
}
function isNewRouteInstance(currentMatch, match) {
let currentPath = currentMatch.route.path;
return (// param change for this match, /users/123 -> /users/456
currentMatch.pathname !== match.pathname || // splat param changed, which is not present in match.path
// e.g. /files/images/avatar.jpg -> files/finances.xls
currentPath && currentPath.endsWith("*") && currentMatch.params["*"] !== match.params["*"]
);
}
function shouldRevalidateLoader(currentLocation, currentMatch, submission, location, match, isRevalidationRequired, actionResult) {
let currentUrl = createURL(currentLocation);
let currentParams = currentMatch.params;
let nextUrl = createURL(location);
let nextParams = match.params; // This is the default implementation as to when we revalidate. If the route
// provides it's own implementation, then we give them full control but
// provide this value so they can leverage it if needed after they check
// their own specific use cases
// Note that fetchers always provide the same current/next locations so the
// URL-based checks here don't apply to fetcher shouldRevalidate calls
let defaultShouldRevalidate = isNewRouteInstance(currentMatch, match) || // Clicked the same link, resubmitted a GET form
currentUrl.toString() === nextUrl.toString() || // Search params affect all loaders
currentUrl.search !== nextUrl.search || // Forced revalidation due to submission, useRevalidate, or X-Remix-Revalidate
isRevalidationRequired;
if (match.route.shouldRevalidate) {
let routeChoice = match.route.shouldRevalidate(_extends({
currentUrl,
currentParams,
nextUrl,
nextParams
}, submission, {
actionResult,
defaultShouldRevalidate
}));
if (typeof routeChoice === "boolean") {
return routeChoice;
}
}
return defaultShouldRevalidate;
}
async function callLoaderOrAction(type, request, match, skipRedirects, isRouteRequest) {
if (skipRedirects === void 0) {
skipRedirects = false;
}
if (isRouteRequest === void 0) {
isRouteRequest = false;
}
let resultType;
let result; // Setup a promise we can race against so that abort signals short circuit
let reject;
let abortPromise = new Promise((_, r) => reject = r);
let onReject = () => reject();
request.signal.addEventListener("abort", onReject);
try {
let handler = match.route[type];
invariant(handler, "Could not find the " + type + " to run on the \"" + match.route.id + "\" route");
result = await Promise.race([handler({
request,
params: match.params
}), abortPromise]);
} catch (e) {
resultType = ResultType.error;
result = e;
} finally {
request.signal.removeEventListener("abort", onReject);
}
if (result instanceof Response) {
// Process redirects
let status = result.status;
let location = result.headers.get("Location"); // For SSR single-route requests, we want to hand Responses back directly
// without unwrapping
if (isRouteRequest) {
throw result;
}
if (status >= 300 && status <= 399 && location != null) {
// Don't process redirects in the router during SSR document requests.
// Instead, throw the Response and let the server handle it with an HTTP
// redirect
if (skipRedirects) {
throw result;
}
return {
type: ResultType.redirect,
status,
location,
revalidate: result.headers.get("X-Remix-Revalidate") !== null
};
}
let data;
let contentType = result.headers.get("Content-Type");
if (contentType && contentType.startsWith("application/json")) {
data = await result.json();
} else {
data = await result.text();
}
if (resultType === ResultType.error) {
return {
type: resultType,
error: new ErrorResponse(status, result.statusText, data),
headers: result.headers
};
}
return {
type: ResultType.data,
data,
statusCode: result.status,
headers: result.headers
};
}
if (resultType === ResultType.error) {
return {
type: resultType,
error: result
};
}
if (result instanceof DeferredData) {
return {
type: ResultType.deferred,
deferredData: result
};
}
return {
type: ResultType.data,
data: result
};
}
function createRequest(location, signal, submission) {
let url = createURL(location).toString();
let init = {
signal
};
if (submission) {
let {
formMethod,
formEncType,
formData
} = submission;
init.method = formMethod.toUpperCase();
init.body = formEncType === "application/x-www-form-urlencoded" ? convertFormDataToSearchParams(formData) : formData;
} // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
return new Request(url, init);
}
function convertFormDataToSearchParams(formData) {
let searchParams = new URLSearchParams();
for (let [key, value] of formData.entries()) {
invariant(typeof value === "string", 'File inputs are not supported with encType "application/x-www-form-urlencoded", ' + 'please use "multipart/form-data" instead.');
searchParams.append(key, value);
}
return searchParams;
}
function processRouteLoaderData(matches, matchesToLoad, results, pendingError, activeDeferreds) {
// Fill in loaderData/errors from our loaders
let loaderData = {};
let errors = null;
let statusCode;
let foundError = false;
let loaderHeaders = {}; // Process loader results into state.loaderData/state.errors
results.forEach((result, index) => {
let id = matchesToLoad[index].route.id;
invariant(!isRedirectResult(result), "Cannot handle redirect results in processLoaderData");
if (isErrorResult(result)) {
// Look upwards from the matched route for the closest ancestor
// error boundary, defaulting to the root match
let boundaryMatch = findNearestBoundary(matches, id);
let error = result.error; // If we have a pending action error, we report it at the highest-route
// that throws a loader error, and then clear it out to indicate that
// it was consumed
if (pendingError) {
error = Object.values(pendingError)[0];
pendingError = undefined;
}
errors = Object.assign(errors || {}, {
[boundaryMatch.route.id]: error
}); // Once we find our first (highest) error, we set the status code and
// prevent deeper status codes from overriding
if (!foundError) {
foundError = true;
statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;
}
if (result.headers) {
loaderHeaders[id] = result.headers;
}
} else if (isDeferredResult(result)) {
activeDeferreds && activeDeferreds.set(id, result.deferredData);
loaderData[id] = result.deferredData.data; // TODO: Add statusCode/headers once we wire up streaming in Remix
} else {
loaderData[id] = result.data; // Error status codes always override success status codes, but if all
// loaders are successful we take the deepest status code.
if (result.statusCode != null && result.statusCode !== 200 && !foundError) {
statusCode = result.statusCode;
}
if (result.headers) {
loaderHeaders[id] = result.headers;
}
}
}); // If we didn't consume the pending action error (i.e., all loaders
// resolved), then consume it here
if (pendingError) {
errors = pendingError;
}
return {
loaderData,
errors,
statusCode: statusCode || 200,
loaderHeaders
};
}
function processLoaderData(state, matches, matchesToLoad, results, pendingError, revalidatingFetchers, fetcherResults, activeDeferreds) {
let {
loaderData,
errors
} = processRouteLoaderData(matches, matchesToLoad, results, pendingError, activeDeferreds); // Process results from our revalidating fetchers
for (let index = 0; index < revalidatingFetchers.length; index++) {
let [key,, match] = revalidatingFetchers[index];
invariant(fetcherResults !== undefined && fetcherResults[index] !== undefined, "Did not find corresponding fetcher result");
let result = fetcherResults[index]; // Process fetcher non-redirect errors
if (isErrorResult(result)) {
let boundaryMatch = findNearestBoundary(state.matches, match.route.id);
if (!(errors && errors[boundaryMatch.route.id])) {
errors = _extends({}, errors, {
[boundaryMatch.route.id]: result.error
});
}
state.fetchers.delete(key);
} else if (isRedirectResult(result)) {
// Should never get here, redirects should get processed above, but we
// keep this to type narrow to a success result in the else
throw new Error("Unhandled fetcher revalidation redirect");
} else if (isDeferredResult(result)) {
// Should never get here, deferred data should be awaited for fetchers
// in resolveDeferredResults
throw new Error("Unhandled fetcher deferred data");
} else {
let doneFetcher = {
state: "idle",
data: result.data,
formMethod: undefined,
formAction: undefined,
formEncType: undefined,
formData: undefined
};
state.fetchers.set(key, doneFetcher);
}
}
return {
loaderData,
errors
};
}
function mergeLoaderData(loaderData, newLoaderData, matches) {
let mergedLoaderData = _extends({}, newLoaderData);
matches.forEach(match => {
let id = match.route.id;
if (newLoaderData[id] === undefined && loaderData[id] !== undefined) {
mergedLoaderData[id] = loaderData[id];
}
});
return mergedLoaderData;
} // Find the nearest error boundary, looking upwards from the leaf route (or the
// route specified by routeId) for the closest ancestor error boundary,
// defaulting to the root match
function findNearestBoundary(matches, routeId) {
let eligibleMatches = routeId ? matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1) : [...matches];
return eligibleMatches.reverse().find(m => m.route.hasErrorBoundary === true) || matches[0];
}
function getNotFoundMatches(routes) {
// Prefer a root layout route if present, otherwise shim in a route object
let route = routes.find(r => r.index || r.path === "" || r.path === "/") || {
id: "__shim-404-route__"
};
return {
matches: [{
params: {},
pathname: "",
pathnameBase: "",
route
}],
route,
error: new ErrorResponse(404, "Not Found", null)
};
}
function getMethodNotAllowedResult(path) {
let href = typeof path === "string" ? path : createHref(path);
console.warn("You're trying to submit to a route that does not have an action. To " + "fix this, please add an `action` function to the route for " + ("[" + href + "]"));
return {
type: ResultType.error,
error: new ErrorResponse(405, "Method Not Allowed", "No action found for [" + href + "]")
};
} // Find any returned redirect errors, starting from the lowest match
function findRedirect(results) {
for (let i = results.length - 1; i >= 0; i--) {
let result = results[i];
if (isRedirectResult(result)) {
return result;
}
}
} // Create an href to represent a "server" URL without the hash
function createHref(location) {
return (location.pathname || "") + (location.search || "");
}
function isHashChangeOnly(a, b) {
return a.pathname === b.pathname && a.search === b.search && a.hash !== b.hash;
}
function isDeferredResult(result) {
return result.type === ResultType.deferred;
}
function isErrorResult(result) {
return result.type === ResultType.error;
}
function isRedirectResult(result) {
return (result && result.type) === ResultType.redirect;
}
async function resolveDeferredResults(currentMatches, matchesToLoad, results, signal, isFetcher, currentLoaderData) {
for (let index = 0; index < results.length; index++) {
let result = results[index];
let match = matchesToLoad[index];
let currentMatch = currentMatches.find(m => m.route.id === match.route.id);
let isRevalidatingLoader = currentMatch != null && !isNewRouteInstance(currentMatch, match) && (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;
if (isDeferredResult(result) && (isFetcher || isRevalidatingLoader)) {
// Note: we do not have to touch activeDeferreds here since we race them
// against the signal in resolveDeferredData and they'll get aborted
// there if needed
await resolveDeferredData(result, signal, isFetcher).then(result => {
if (result) {
results[index] = result || results[index];
}
});
}
}
}
async function resolveDeferredData(result, signal, unwrap) {
if (unwrap === void 0) {
unwrap = false;
}
let aborted = await result.deferredData.resolveData(signal);
if (aborted) {
return;
}
if (unwrap) {
try {
return {
type: ResultType.data,
data: result.deferredData.unwrappedData
};
} catch (e) {
// Handle any TrackedPromise._error values encountered while unwrapping
return {
type: ResultType.error,
error: e
};
}
}
return {
type: ResultType.data,
data: result.deferredData.data
};
}
function hasNakedIndexQuery(search) {
return new URLSearchParams(search).getAll("index").some(v => v === "");
} // Note: This should match the format exported by useMatches, so if you change
// this please also change that :) Eventually we'll DRY this up
function createUseMatchesMatch(match, loaderData) {
let {
route,
pathname,
params
} = match;
return {
id: route.id,
pathname,
params,
data: loaderData[route.id],
handle: route.handle
};
}
function getTargetMatch(matches, location) {
let search = typeof location === "string" ? parsePath(location).search : location.search;
if (matches[matches.length - 1].route.index && !hasNakedIndexQuery(search || "")) {
return matches.slice(-2)[0];
}
return matches.slice(-1)[0];
}
function createURL(location) {
let base = typeof window !== "undefined" && typeof window.location !== "undefined" ? window.location.origin : "unknown://unknown";
let href = typeof location === "string" ? location : createHref(location);
return new URL(href, base);
} //#endregion
export { AbortedDeferredError, Action, ErrorResponse, IDLE_FETCHER, IDLE_NAVIGATION, convertRoutesToDataRoutes as UNSAFE_convertRoutesToDataRoutes, createBrowserHistory, createHashHistory, createMemoryHistory, createPath, createRouter, defer, generatePath, getStaticContextFromError, getToPathname, invariant, isRouteErrorResponse, joinPaths, json, matchPath, matchRoutes, normalizePathname, parsePath, redirect, resolvePath, resolveTo, stripBasename, unstable_createStaticHandler, warning };
//# sourceMappingURL=router.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/react/context/ApolloProvider.js
import { __assign } from "tslib";
import { invariant } from "../../utilities/globals/index.js";
import * as React from "rehackt";
import { getApolloContext } from "./ApolloContext.js";
export var ApolloProvider = function (_a) {
var client = _a.client, children = _a.children;
var ApolloContext = getApolloContext();
var parentContext = React.useContext(ApolloContext);
var context = React.useMemo(function () {
return __assign(__assign({}, parentContext), { client: client || parentContext.client });
}, [parentContext, client]);
invariant(context.client, 46);
return (React.createElement(ApolloContext.Provider, { value: context }, children));
};
//# sourceMappingURL=ApolloProvider.js.map
webpack://frontend-mybets/../../node_modules/react-router/dist/index.js
/**
* React Router v6.4.2
*
* Copyright (c) Remix Software Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
import { invariant, resolveTo, joinPaths, matchPath, warning, parsePath, matchRoutes, Action, isRouteErrorResponse, createMemoryHistory, stripBasename, AbortedDeferredError, createRouter } from '@remix-run/router';
export { AbortedDeferredError, Action as NavigationType, createPath, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, resolvePath } from '@remix-run/router';
import * as React from 'react';
function _extends() {
_extends = Object.assign ? Object.assign.bind() : 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) 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.
*/
/**
* 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 isPolyfill(x, y) {
return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
;
}
const is = typeof Object.is === "function" ? Object.is : isPolyfill; // Intentionally not using named imports because Rollup uses dynamic
// dispatch for CommonJS interop named imports.
const {
useState,
useEffect,
useLayoutEffect,
useDebugValue
} = React;
let didWarnOld18Alpha = false;
let didWarnUncachedGetSnapshot = false; // Disclaimer: This shim breaks many of the rules of React, and only works
// because of a very particular set of implementation details and assumptions
// -- change any one of them and it will break. The most important assumption
// is that updates are always synchronous, because concurrent rendering is
// only available in versions of React that also have a built-in
// useSyncExternalStore API. And we only use this shim when the built-in API
// does not exist.
//
// Do not assume that the clever hacks used by this hook also work in general.
// The point of this shim is to replace the need for hacks by other libraries.
function useSyncExternalStore$2(subscribe, getSnapshot, // Note: The shim does not use getServerSnapshot, because pre-18 versions of
// React do not expose a way to check if we're hydrating. So users of the shim
// will need to track that themselves and return the correct value
// from `getSnapshot`.
getServerSnapshot) {
if (process.env.NODE_ENV !== "production") {
if (!didWarnOld18Alpha) {
if ("startTransition" in React) {
didWarnOld18Alpha = true;
console.error("You are using an outdated, pre-release alpha of React 18 that " + "does not support useSyncExternalStore. The " + "use-sync-external-store shim will not work correctly. Upgrade " + "to a newer pre-release.");
}
}
} // Read the current snapshot from the store on every render. Again, this
// breaks the rules of React, and only works here because of specific
// implementation details, most importantly that updates are
// always synchronous.
const value = getSnapshot();
if (process.env.NODE_ENV !== "production") {
if (!didWarnUncachedGetSnapshot) {
const cachedValue = getSnapshot();
if (!is(value, cachedValue)) {
console.error("The result of getSnapshot should be cached to avoid an infinite loop");
didWarnUncachedGetSnapshot = true;
}
}
} // Because updates are synchronous, we don't queue them. Instead we force a
// re-render whenever the subscribed state changes by updating an some
// arbitrary useState hook. Then, during render, we call getSnapshot to read
// the current value.
//
// Because we don't actually use the state returned by the useState hook, we
// can save a bit of memory by storing other stuff in that slot.
//
// To implement the early bailout, we need to track some things on a mutable
// object. Usually, we would put that in a useRef hook, but we can stash it in
// our useState hook instead.
//
// To force a re-render, we call forceUpdate({inst}). That works because the
// new object always fails an equality check.
const [{
inst
}, forceUpdate] = useState({
inst: {
value,
getSnapshot
}
}); // Track the latest getSnapshot function with a ref. This needs to be updated
// in the layout phase so we can access it during the tearing check that
// happens on subscribe.
useLayoutEffect(() => {
inst.value = value;
inst.getSnapshot = getSnapshot; // Whenever getSnapshot or subscribe changes, we need to check in the
// commit phase if there was an interleaved mutation. In concurrent mode
// this can happen all the time, but even in synchronous mode, an earlier
// effect may have mutated the store.
if (checkIfSnapshotChanged(inst)) {
// Force a re-render.
forceUpdate({
inst
});
} // eslint-disable-next-line react-hooks/exhaustive-deps
}, [subscribe, value, getSnapshot]);
useEffect(() => {
// Check for changes right before subscribing. Subsequent changes will be
// detected in the subscription handler.
if (checkIfSnapshotChanged(inst)) {
// Force a re-render.
forceUpdate({
inst
});
}
const handleStoreChange = () => {
// TODO: Because there is no cross-renderer API for batching updates, it's
// up to the consumer of this library to wrap their subscription event
// with unstable_batchedUpdates. Should we try to detect when this isn't
// the case and print a warning in development?
// The store changed. Check if the snapshot changed since the last time we
// read from the store.
if (checkIfSnapshotChanged(inst)) {
// Force a re-render.
forceUpdate({
inst
});
}
}; // Subscribe to the store and return a clean-up function.
return subscribe(handleStoreChange); // eslint-disable-next-line react-hooks/exhaustive-deps
}, [subscribe]);
useDebugValue(value);
return value;
}
function checkIfSnapshotChanged(inst) {
const latestGetSnapshot = inst.getSnapshot;
const prevValue = inst.value;
try {
const nextValue = latestGetSnapshot();
return !is(prevValue, nextValue);
} catch (error) {
return true;
}
}
/**
* 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.
*
* @flow
*/
function useSyncExternalStore$1(subscribe, getSnapshot, getServerSnapshot) {
// Note: The shim does not use getServerSnapshot, because pre-18 versions of
// React do not expose a way to check if we're hydrating. So users of the shim
// will need to track that themselves and return the correct value
// from `getSnapshot`.
return getSnapshot();
}
/**
* Inlined into the react-router repo since use-sync-external-store does not
* provide a UMD-compatible package, so we need this to be able to distribute
* UMD react-router bundles
*/
const canUseDOM = !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined");
const isServerEnvironment = !canUseDOM;
const shim = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore$2;
const useSyncExternalStore = "useSyncExternalStore" in React ? (module => module.useSyncExternalStore)(React) : shim;
// Contexts for data routers
const DataStaticRouterContext = /*#__PURE__*/React.createContext(null);
if (process.env.NODE_ENV !== "production") {
DataStaticRouterContext.displayName = "DataStaticRouterContext";
}
const DataRouterContext = /*#__PURE__*/React.createContext(null);
if (process.env.NODE_ENV !== "production") {
DataRouterContext.displayName = "DataRouter";
}
const DataRouterStateContext = /*#__PURE__*/React.createContext(null);
if (process.env.NODE_ENV !== "production") {
DataRouterStateContext.displayName = "DataRouterState";
}
const AwaitContext = /*#__PURE__*/React.createContext(null);
if (process.env.NODE_ENV !== "production") {
AwaitContext.displayName = "Await";
}
const NavigationContext = /*#__PURE__*/React.createContext(null);
if (process.env.NODE_ENV !== "production") {
NavigationContext.displayName = "Navigation";
}
const LocationContext = /*#__PURE__*/React.createContext(null);
if (process.env.NODE_ENV !== "production") {
LocationContext.displayName = "Location";
}
const RouteContext = /*#__PURE__*/React.createContext({
outlet: null,
matches: []
});
if (process.env.NODE_ENV !== "production") {
RouteContext.displayName = "Route";
}
const RouteErrorContext = /*#__PURE__*/React.createContext(null);
if (process.env.NODE_ENV !== "production") {
RouteErrorContext.displayName = "RouteError";
}
/**
* Returns the full href for the given "to" value. This is useful for building
* custom links that are also accessible and preserve right-click behavior.
*
* @see https://reactrouter.com/docs/en/v6/hooks/use-href
*/
function useHref(to, _temp) {
let {
relative
} = _temp === void 0 ? {} : _temp;
!useInRouterContext() ? process.env.NODE_ENV !== "production" ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
// router loaded. We can help them understand how to avoid that.
"useHref() may be used only in the context of a <Router> component.") : invariant(false) : void 0;
let {
basename,
navigator
} = React.useContext(NavigationContext);
let {
hash,
pathname,
search
} = useResolvedPath(to, {
relative
});
let joinedPathname = pathname; // If we're operating within a basename, prepend it to the pathname prior
// to creating the href. If this is a root navigation, then just use the raw
// basename which allows the basename to have full control over the presence
// of a trailing slash on root links
if (basename !== "/") {
joinedPathname = pathname === "/" ? basename : joinPaths([basename, pathname]);
}
return navigator.createHref({
pathname: joinedPathname,
search,
hash
});
}
/**
* Returns true if this component is a descendant of a <Router>.
*
* @see https://reactrouter.com/docs/en/v6/hooks/use-in-router-context
*/
function useInRouterContext() {
return React.useContext(LocationContext) != null;
}
/**
* Returns the current location object, which represents the current URL in web
* browsers.
*
* Note: If you're using this it may mean you're doing some of your own
* "routing" in your app, and we'd like to know what your use case is. We may
* be able to provide something higher-level to better suit your needs.
*
* @see https://reactrouter.com/docs/en/v6/hooks/use-location
*/
function useLocation() {
!useInRouterContext() ? process.env.NODE_ENV !== "production" ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
// router loaded. We can help them understand how to avoid that.
"useLocation() may be used only in the context of a <Router> component.") : invariant(false) : void 0;
return React.useContext(LocationContext).location;
}
/**
* Returns the current navigation action which describes how the router came to
* the current location, either by a pop, push, or replace on the history stack.
*
* @see https://reactrouter.com/docs/en/v6/hooks/use-navigation-type
*/
function useNavigationType() {
return React.useContext(LocationContext).navigationType;
}
/**
* Returns true if the URL for the given "to" value matches the current URL.
* This is useful for components that need to know "active" state, e.g.
* <NavLink>.
*
* @see https://reactrouter.com/docs/en/v6/hooks/use-match
*/
function useMatch(pattern) {
!useInRouterContext() ? process.env.NODE_ENV !== "production" ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
// router loaded. We can help them understand how to avoid that.
"useMatch() may be used only in the context of a <Router> component.") : invariant(false) : void 0;
let {
pathname
} = useLocation();
return React.useMemo(() => matchPath(pattern, pathname), [pathname, pattern]);
}
/**
* The interface for the navigate() function returned from useNavigate().
*/
/**
* When processing relative navigation we want to ignore ancestor routes that
* do not contribute to the path, such that index/pathless layout routes don't
* interfere.
*
* For example, when moving a route element into an index route and/or a
* pathless layout route, relative link behavior contained within should stay
* the same. Both of the following examples should link back to the root:
*
* <Route path="/">
* <Route path="accounts" element={<Link to=".."}>
* </Route>
*
* <Route path="/">
* <Route path="accounts">
* <Route element={<AccountsLayout />}> // <-- Does not contribute
* <Route index element={<Link to=".."} /> // <-- Does not contribute
* </Route
* </Route>
* </Route>
*/
function getPathContributingMatches(matches) {
return matches.filter((match, index) => index === 0 || !match.route.index && match.pathnameBase !== matches[index - 1].pathnameBase);
}
/**
* Returns an imperative method for changing the location. Used by <Link>s, but
* may also be used by other elements to change the location.
*
* @see https://reactrouter.com/docs/en/v6/hooks/use-navigate
*/
function useNavigate() {
!useInRouterContext() ? process.env.NODE_ENV !== "production" ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
// router loaded. We can help them understand how to avoid that.
"useNavigate() may be used only in the context of a <Router> component.") : invariant(false) : void 0;
let {
basename,
navigator
} = React.useContext(NavigationContext);
let {
matches
} = React.useContext(RouteContext);
let {
pathname: locationPathname
} = useLocation();
let routePathnamesJson = JSON.stringify(getPathContributingMatches(matches).map(match => match.pathnameBase));
let activeRef = React.useRef(false);
React.useEffect(() => {
activeRef.current = true;
});
let navigate = React.useCallback(function (to, options) {
if (options === void 0) {
options = {};
}
process.env.NODE_ENV !== "production" ? warning(activeRef.current, "You should call navigate() in a React.useEffect(), not when " + "your component is first rendered.") : void 0;
if (!activeRef.current) return;
if (typeof to === "number") {
navigator.go(to);
return;
}
let path = resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, options.relative === "path"); // If we're operating within a basename, prepend it to the pathname prior
// to handing off to history. If this is a root navigation, then we
// navigate to the raw basename which allows the basename to have full
// control over the presence of a trailing slash on root links
if (basename !== "/") {
path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
}
(!!options.replace ? navigator.replace : navigator.push)(path, options.state, options);
}, [basename, navigator, routePathnamesJson, locationPathname]);
return navigate;
}
const OutletContext = /*#__PURE__*/React.createContext(null);
/**
* Returns the context (if provided) for the child route at this level of the route
* hierarchy.
* @see https://reactrouter.com/docs/en/v6/hooks/use-outlet-context
*/
function useOutletContext() {
return React.useContext(OutletContext);
}
/**
* Returns the element for the child route at this level of the route
* hierarchy. Used internally by <Outlet> to render child routes.
*
* @see https://reactrouter.com/docs/en/v6/hooks/use-outlet
*/
function useOutlet(context) {
let outlet = React.useContext(RouteContext).outlet;
if (outlet) {
return /*#__PURE__*/React.createElement(OutletContext.Provider, {
value: context
}, outlet);
}
return outlet;
}
/**
* Returns an object of key/value pairs of the dynamic params from the current
* URL that were matched by the route path.
*
* @see https://reactrouter.com/docs/en/v6/hooks/use-params
*/
function useParams() {
let {
matches
} = React.useContext(RouteContext);
let routeMatch = matches[matches.length - 1];
return routeMatch ? routeMatch.params : {};
}
/**
* Resolves the pathname of the given `to` value against the current location.
*
* @see https://reactrouter.com/docs/en/v6/hooks/use-resolved-path
*/
function useResolvedPath(to, _temp2) {
let {
relative
} = _temp2 === void 0 ? {} : _temp2;
let {
matches
} = React.useContext(RouteContext);
let {
pathname: locationPathname
} = useLocation();
let routePathnamesJson = JSON.stringify(getPathContributingMatches(matches).map(match => match.pathnameBase));
return React.useMemo(() => resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, relative === "path"), [to, routePathnamesJson, locationPathname, relative]);
}
/**
* Returns the element of the route that matched the current location, prepared
* with the correct context to render the remainder of the route tree. Route
* elements in the tree must render an <Outlet> to render their child route's
* element.
*
* @see https://reactrouter.com/docs/en/v6/hooks/use-routes
*/
function useRoutes(routes, locationArg) {
!useInRouterContext() ? process.env.NODE_ENV !== "production" ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
// router loaded. We can help them understand how to avoid that.
"useRoutes() may be used only in the context of a <Router> component.") : invariant(false) : void 0;
let dataRouterStateContext = React.useContext(DataRouterStateContext);
let {
matches: parentMatches
} = React.useContext(RouteContext);
let routeMatch = parentMatches[parentMatches.length - 1];
let parentParams = routeMatch ? routeMatch.params : {};
let parentPathname = routeMatch ? routeMatch.pathname : "/";
let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
let parentRoute = routeMatch && routeMatch.route;
if (process.env.NODE_ENV !== "production") {
// You won't get a warning about 2 different <Routes> under a <Route>
// without a trailing *, but this is a best-effort warning anyway since we
// cannot even give the warning unless they land at the parent route.
//
// Example:
//
// <Routes>
// {/* This route path MUST end with /* because otherwise
// it will never match /blog/post/123 */}
// <Route path="blog" element={<Blog />} />
// <Route path="blog/feed" element={<BlogFeed />} />
// </Routes>
//
// function Blog() {
// return (
// <Routes>
// <Route path="post/:id" element={<Post />} />
// </Routes>
// );
// }
let parentPath = parentRoute && parentRoute.path || "";
warningOnce(parentPathname, !parentRoute || parentPath.endsWith("*"), "You rendered descendant <Routes> (or called `useRoutes()`) at " + ("\"" + parentPathname + "\" (under <Route path=\"" + parentPath + "\">) but the ") + "parent route path has no trailing \"*\". This means if you navigate " + "deeper, the parent won't match anymore and therefore the child " + "routes will never render.\n\n" + ("Please change the parent <Route path=\"" + parentPath + "\"> to <Route ") + ("path=\"" + (parentPath === "/" ? "*" : parentPath + "/*") + "\">."));
}
let locationFromContext = useLocation();
let location;
if (locationArg) {
var _parsedLocationArg$pa;
let parsedLocationArg = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
!(parentPathnameBase === "/" || ((_parsedLocationArg$pa = parsedLocationArg.pathname) == null ? void 0 : _parsedLocationArg$pa.startsWith(parentPathnameBase))) ? process.env.NODE_ENV !== "production" ? invariant(false, "When overriding the location using `<Routes location>` or `useRoutes(routes, location)`, " + "the location pathname must begin with the portion of the URL pathname that was " + ("matched by all parent routes. The current pathname base is \"" + parentPathnameBase + "\" ") + ("but pathname \"" + parsedLocationArg.pathname + "\" was given in the `location` prop.")) : invariant(false) : void 0;
location = parsedLocationArg;
} else {
location = locationFromContext;
}
let pathname = location.pathname || "/";
let remainingPathname = parentPathnameBase === "/" ? pathname : pathname.slice(parentPathnameBase.length) || "/";
let matches = matchRoutes(routes, {
pathname: remainingPathname
});
if (process.env.NODE_ENV !== "production") {
process.env.NODE_ENV !== "production" ? warning(parentRoute || matches != null, "No routes matched location \"" + location.pathname + location.search + location.hash + "\" ") : void 0;
process.env.NODE_ENV !== "production" ? warning(matches == null || matches[matches.length - 1].route.element !== undefined, "Matched leaf route at location \"" + location.pathname + location.search + location.hash + "\" does not have an element. " + "This means it will render an <Outlet /> with a null value by default resulting in an \"empty\" page.") : void 0;
}
let renderedMatches = _renderMatches(matches && matches.map(match => Object.assign({}, match, {
params: Object.assign({}, parentParams, match.params),
pathname: joinPaths([parentPathnameBase, match.pathname]),
pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([parentPathnameBase, match.pathnameBase])
})), parentMatches, dataRouterStateContext || undefined); // When a user passes in a `locationArg`, the associated routes need to
// be wrapped in a new `LocationContext.Provider` in order for `useLocation`
// to use the scoped location instead of the global location.
if (locationArg) {
return /*#__PURE__*/React.createElement(LocationContext.Provider, {
value: {
location: _extends({
pathname: "/",
search: "",
hash: "",
state: null,
key: "default"
}, location),
navigationType: Action.Pop
}
}, renderedMatches);
}
return renderedMatches;
}
function DefaultErrorElement() {
let error = useRouteError();
let message = isRouteErrorResponse(error) ? error.status + " " + error.statusText : error instanceof Error ? error.message : JSON.stringify(error);
let stack = error instanceof Error ? error.stack : null;
let lightgrey = "rgba(200,200,200, 0.5)";
let preStyles = {
padding: "0.5rem",
backgroundColor: lightgrey
};
let codeStyles = {
padding: "2px 4px",
backgroundColor: lightgrey
};
return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("h2", null, "Unhandled Thrown Error!"), /*#__PURE__*/React.createElement("h3", {
style: {
fontStyle: "italic"
}
}, message), stack ? /*#__PURE__*/React.createElement("pre", {
style: preStyles
}, stack) : null, /*#__PURE__*/React.createElement("p", null, "\uD83D\uDCBF Hey developer \uD83D\uDC4B"), /*#__PURE__*/React.createElement("p", null, "You can provide a way better UX than this when your app throws errors by providing your own\xA0", /*#__PURE__*/React.createElement("code", {
style: codeStyles
}, "errorElement"), " props on\xA0", /*#__PURE__*/React.createElement("code", {
style: codeStyles
}, "<Route>")));
}
class RenderErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = {
location: props.location,
error: props.error
};
}
static getDerivedStateFromError(error) {
return {
error: error
};
}
static getDerivedStateFromProps(props, state) {
// When we get into an error state, the user will likely click "back" to the
// previous page that didn't have an error. Because this wraps the entire
// application, that will have no effect--the error page continues to display.
// This gives us a mechanism to recover from the error when the location changes.
//
// Whether we're in an error state or not, we update the location in state
// so that when we are in an error state, it gets reset when a new location
// comes in and the user recovers from the error.
if (state.location !== props.location) {
return {
error: props.error,
location: props.location
};
} // If we're not changing locations, preserve the location but still surface
// any new errors that may come through. We retain the existing error, we do
// this because the error provided from the app state may be cleared without
// the location changing.
return {
error: props.error || state.error,
location: state.location
};
}
componentDidCatch(error, errorInfo) {
console.error("React Router caught the following error during render", error, errorInfo);
}
render() {
return this.state.error ? /*#__PURE__*/React.createElement(RouteErrorContext.Provider, {
value: this.state.error,
children: this.props.component
}) : this.props.children;
}
}
function RenderedRoute(_ref) {
let {
routeContext,
match,
children
} = _ref;
let dataStaticRouterContext = React.useContext(DataStaticRouterContext); // Track how deep we got in our render pass to emulate SSR componentDidCatch
// in a DataStaticRouter
if (dataStaticRouterContext && match.route.errorElement) {
dataStaticRouterContext._deepestRenderedBoundaryId = match.route.id;
}
return /*#__PURE__*/React.createElement(RouteContext.Provider, {
value: routeContext
}, children);
}
function _renderMatches(matches, parentMatches, dataRouterState) {
if (parentMatches === void 0) {
parentMatches = [];
}
if (matches == null) {
if (dataRouterState != null && dataRouterState.errors) {
// Don't bail if we have data router errors so we can render them in the
// boundary. Use the pre-matched (or shimmed) matches
matches = dataRouterState.matches;
} else {
return null;
}
}
let renderedMatches = matches; // If we have data errors, trim matches to the highest error boundary
let errors = dataRouterState == null ? void 0 : dataRouterState.errors;
if (errors != null) {
let errorIndex = renderedMatches.findIndex(m => m.route.id && (errors == null ? void 0 : errors[m.route.id]));
!(errorIndex >= 0) ? process.env.NODE_ENV !== "production" ? invariant(false, "Could not find a matching route for the current errors: " + errors) : invariant(false) : void 0;
renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1));
}
return renderedMatches.reduceRight((outlet, match, index) => {
let error = match.route.id ? errors == null ? void 0 : errors[match.route.id] : null; // Only data routers handle errors
let errorElement = dataRouterState ? match.route.errorElement || /*#__PURE__*/React.createElement(DefaultErrorElement, null) : null;
let getChildren = () => /*#__PURE__*/React.createElement(RenderedRoute, {
match: match,
routeContext: {
outlet,
matches: parentMatches.concat(renderedMatches.slice(0, index + 1))
}
}, error ? errorElement : match.route.element !== undefined ? match.route.element : outlet); // Only wrap in an error boundary within data router usages when we have an
// errorElement on this route. Otherwise let it bubble up to an ancestor
// errorElement
return dataRouterState && (match.route.errorElement || index === 0) ? /*#__PURE__*/React.createElement(RenderErrorBoundary, {
location: dataRouterState.location,
component: errorElement,
error: error,
children: getChildren()
}) : getChildren();
}, null);
}
var DataRouterHook;
(function (DataRouterHook) {
DataRouterHook["UseRevalidator"] = "useRevalidator";
})(DataRouterHook || (DataRouterHook = {}));
var DataRouterStateHook;
(function (DataRouterStateHook) {
DataRouterStateHook["UseLoaderData"] = "useLoaderData";
DataRouterStateHook["UseActionData"] = "useActionData";
DataRouterStateHook["UseRouteError"] = "useRouteError";
DataRouterStateHook["UseNavigation"] = "useNavigation";
DataRouterStateHook["UseRouteLoaderData"] = "useRouteLoaderData";
DataRouterStateHook["UseMatches"] = "useMatches";
DataRouterStateHook["UseRevalidator"] = "useRevalidator";
})(DataRouterStateHook || (DataRouterStateHook = {}));
function getDataRouterConsoleError(hookName) {
return hookName + " must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.";
}
function useDataRouterContext(hookName) {
let ctx = React.useContext(DataRouterContext);
!ctx ? process.env.NODE_ENV !== "production" ? invariant(false, getDataRouterConsoleError(hookName)) : invariant(false) : void 0;
return ctx;
}
function useDataRouterState(hookName) {
let state = React.useContext(DataRouterStateContext);
!state ? process.env.NODE_ENV !== "production" ? invariant(false, getDataRouterConsoleError(hookName)) : invariant(false) : void 0;
return state;
}
/**
* Returns the current navigation, defaulting to an "idle" navigation when
* no navigation is in progress
*/
function useNavigation() {
let state = useDataRouterState(DataRouterStateHook.UseNavigation);
return state.navigation;
}
/**
* Returns a revalidate function for manually triggering revalidation, as well
* as the current state of any manual revalidations
*/
function useRevalidator() {
let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);
let state = useDataRouterState(DataRouterStateHook.UseRevalidator);
return {
revalidate: dataRouterContext.router.revalidate,
state: state.revalidation
};
}
/**
* Returns the active route matches, useful for accessing loaderData for
* parent/child routes or the route "handle" property
*/
function useMatches() {
let {
matches,
loaderData
} = useDataRouterState(DataRouterStateHook.UseMatches);
return React.useMemo(() => matches.map(match => {
let {
pathname,
params
} = match; // Note: This structure matches that created by createUseMatchesMatch
// in the @remix-run/router , so if you change this please also change
// that :) Eventually we'll DRY this up
return {
id: match.route.id,
pathname,
params,
data: loaderData[match.route.id],
handle: match.route.handle
};
}), [matches, loaderData]);
}
/**
* Returns the loader data for the nearest ancestor Route loader
*/
function useLoaderData() {
let state = useDataRouterState(DataRouterStateHook.UseLoaderData);
let route = React.useContext(RouteContext);
!route ? process.env.NODE_ENV !== "production" ? invariant(false, "useLoaderData must be used inside a RouteContext") : invariant(false) : void 0;
let thisRoute = route.matches[route.matches.length - 1];
!thisRoute.route.id ? process.env.NODE_ENV !== "production" ? invariant(false, "useLoaderData can only be used on routes that contain a unique \"id\"") : invariant(false) : void 0;
return state.loaderData[thisRoute.route.id];
}
/**
* Returns the loaderData for the given routeId
*/
function useRouteLoaderData(routeId) {
let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);
return state.loaderData[routeId];
}
/**
* Returns the action data for the nearest ancestor Route action
*/
function useActionData() {
let state = useDataRouterState(DataRouterStateHook.UseActionData);
let route = React.useContext(RouteContext);
!route ? process.env.NODE_ENV !== "production" ? invariant(false, "useActionData must be used inside a RouteContext") : invariant(false) : void 0;
return Object.values((state == null ? void 0 : state.actionData) || {})[0];
}
/**
* Returns the nearest ancestor Route error, which could be a loader/action
* error or a render error. This is intended to be called from your
* errorElement to display a proper error message.
*/
function useRouteError() {
var _state$errors;
let error = React.useContext(RouteErrorContext);
let state = useDataRouterState(DataRouterStateHook.UseRouteError);
let route = React.useContext(RouteContext);
let thisRoute = route.matches[route.matches.length - 1]; // If this was a render error, we put it in a RouteError context inside
// of RenderErrorBoundary
if (error) {
return error;
}
!route ? process.env.NODE_ENV !== "production" ? invariant(false, "useRouteError must be used inside a RouteContext") : invariant(false) : void 0;
!thisRoute.route.id ? process.env.NODE_ENV !== "production" ? invariant(false, "useRouteError can only be used on routes that contain a unique \"id\"") : invariant(false) : void 0; // Otherwise look for errors from our data router state
return (_state$errors = state.errors) == null ? void 0 : _state$errors[thisRoute.route.id];
}
/**
* Returns the happy-path data from the nearest ancestor <Await /> value
*/
function useAsyncValue() {
let value = React.useContext(AwaitContext);
return value == null ? void 0 : value._data;
}
/**
* Returns the error from the nearest ancestor <Await /> value
*/
function useAsyncError() {
let value = React.useContext(AwaitContext);
return value == null ? void 0 : value._error;
}
const alreadyWarned = {};
function warningOnce(key, cond, message) {
if (!cond && !alreadyWarned[key]) {
alreadyWarned[key] = true;
process.env.NODE_ENV !== "production" ? warning(false, message) : void 0;
}
}
/**
* Given a Remix Router instance, render the appropriate UI
*/
function RouterProvider(_ref) {
let {
fallbackElement,
router
} = _ref;
// Sync router state to our component state to force re-renders
let state = useSyncExternalStore(router.subscribe, () => router.state, // We have to provide this so React@18 doesn't complain during hydration,
// but we pass our serialized hydration data into the router so state here
// is already synced with what the server saw
() => router.state);
let navigator = React.useMemo(() => {
return {
createHref: router.createHref,
go: n => router.navigate(n),
push: (to, state, opts) => router.navigate(to, {
state,
preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
}),
replace: (to, state, opts) => router.navigate(to, {
replace: true,
state,
preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
})
};
}, [router]);
let basename = router.basename || "/";
return /*#__PURE__*/React.createElement(DataRouterContext.Provider, {
value: {
router,
navigator,
static: false,
// Do we need this?
basename
}
}, /*#__PURE__*/React.createElement(DataRouterStateContext.Provider, {
value: state
}, /*#__PURE__*/React.createElement(Router, {
basename: router.basename,
location: router.state.location,
navigationType: router.state.historyAction,
navigator: navigator
}, router.state.initialized ? /*#__PURE__*/React.createElement(Routes, null) : fallbackElement)));
}
/**
* A <Router> that stores all entries in memory.
*
* @see https://reactrouter.com/docs/en/v6/routers/memory-router
*/
function MemoryRouter(_ref2) {
let {
basename,
children,
initialEntries,
initialIndex
} = _ref2;
let historyRef = React.useRef();
if (historyRef.current == null) {
historyRef.current = createMemoryHistory({
initialEntries,
initialIndex,
v5Compat: true
});
}
let history = historyRef.current;
let [state, setState] = React.useState({
action: history.action,
location: history.location
});
React.useLayoutEffect(() => history.listen(setState), [history]);
return /*#__PURE__*/React.createElement(Router, {
basename: basename,
children: children,
location: state.location,
navigationType: state.action,
navigator: history
});
}
/**
* Changes the current location.
*
* Note: This API is mostly useful in React.Component subclasses that are not
* able to use hooks. In functional components, we recommend you use the
* `useNavigate` hook instead.
*
* @see https://reactrouter.com/docs/en/v6/components/navigate
*/
function Navigate(_ref3) {
let {
to,
replace,
state,
relative
} = _ref3;
!useInRouterContext() ? process.env.NODE_ENV !== "production" ? invariant(false, // TODO: This error is probably because they somehow have 2 versions of
// the router loaded. We can help them understand how to avoid that.
"<Navigate> may be used only in the context of a <Router> component.") : invariant(false) : void 0;
process.env.NODE_ENV !== "production" ? warning(!React.useContext(NavigationContext).static, "<Navigate> must not be used on the initial render in a <StaticRouter>. " + "This is a no-op, but you should modify your code so the <Navigate> is " + "only ever rendered in response to some user interaction or state change.") : void 0;
let dataRouterState = React.useContext(DataRouterStateContext);
let navigate = useNavigate();
React.useEffect(() => {
// Avoid kicking off multiple navigations if we're in the middle of a
// data-router navigation, since components get re-rendered when we enter
// a submitting/loading state
if (dataRouterState && dataRouterState.navigation.state !== "idle") {
return;
}
navigate(to, {
replace,
state,
relative
});
});
return null;
}
/**
* Renders the child route's element, if there is one.
*
* @see https://reactrouter.com/docs/en/v6/components/outlet
*/
function Outlet(props) {
return useOutlet(props.context);
}
/**
* Declares an element that should be rendered at a certain URL path.
*
* @see https://reactrouter.com/docs/en/v6/components/route
*/
function Route(_props) {
process.env.NODE_ENV !== "production" ? invariant(false, "A <Route> is only ever to be used as the child of <Routes> element, " + "never rendered directly. Please wrap your <Route> in a <Routes>.") : invariant(false) ;
}
/**
* Provides location context for the rest of the app.
*
* Note: You usually won't render a <Router> directly. Instead, you'll render a
* router that is more specific to your environment such as a <BrowserRouter>
* in web browsers or a <StaticRouter> for server rendering.
*
* @see https://reactrouter.com/docs/en/v6/routers/router
*/
function Router(_ref4) {
let {
basename: basenameProp = "/",
children = null,
location: locationProp,
navigationType = Action.Pop,
navigator,
static: staticProp = false
} = _ref4;
!!useInRouterContext() ? process.env.NODE_ENV !== "production" ? invariant(false, "You cannot render a <Router> inside another <Router>." + " You should never have more than one in your app.") : invariant(false) : void 0; // Preserve trailing slashes on basename, so we can let the user control
// the enforcement of trailing slashes throughout the app
let basename = basenameProp.replace(/^\/*/, "/");
let navigationContext = React.useMemo(() => ({
basename,
navigator,
static: staticProp
}), [basename, navigator, staticProp]);
if (typeof locationProp === "string") {
locationProp = parsePath(locationProp);
}
let {
pathname = "/",
search = "",
hash = "",
state = null,
key = "default"
} = locationProp;
let location = React.useMemo(() => {
let trailingPathname = stripBasename(pathname, basename);
if (trailingPathname == null) {
return null;
}
return {
pathname: trailingPathname,
search,
hash,
state,
key
};
}, [basename, pathname, search, hash, state, key]);
process.env.NODE_ENV !== "production" ? warning(location != null, "<Router basename=\"" + basename + "\"> is not able to match the URL " + ("\"" + pathname + search + hash + "\" because it does not start with the ") + "basename, so the <Router> won't render anything.") : void 0;
if (location == null) {
return null;
}
return /*#__PURE__*/React.createElement(NavigationContext.Provider, {
value: navigationContext
}, /*#__PURE__*/React.createElement(LocationContext.Provider, {
children: children,
value: {
location,
navigationType
}
}));
}
/**
* A container for a nested tree of <Route> elements that renders the branch
* that best matches the current location.
*
* @see https://reactrouter.com/docs/en/v6/components/routes
*/
function Routes(_ref5) {
let {
children,
location
} = _ref5;
let dataRouterContext = React.useContext(DataRouterContext); // When in a DataRouterContext _without_ children, we use the router routes
// directly. If we have children, then we're in a descendant tree and we
// need to use child routes.
let routes = dataRouterContext && !children ? dataRouterContext.router.routes : createRoutesFromChildren(children);
return useRoutes(routes, location);
}
/**
* Component to use for rendering lazily loaded data from returning defer()
* in a loader function
*/
function Await(_ref6) {
let {
children,
errorElement,
resolve
} = _ref6;
return /*#__PURE__*/React.createElement(AwaitErrorBoundary, {
resolve: resolve,
errorElement: errorElement
}, /*#__PURE__*/React.createElement(ResolveAwait, null, children));
}
var AwaitRenderStatus;
(function (AwaitRenderStatus) {
AwaitRenderStatus[AwaitRenderStatus["pending"] = 0] = "pending";
AwaitRenderStatus[AwaitRenderStatus["success"] = 1] = "success";
AwaitRenderStatus[AwaitRenderStatus["error"] = 2] = "error";
})(AwaitRenderStatus || (AwaitRenderStatus = {}));
const neverSettledPromise = new Promise(() => {});
class AwaitErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null
};
}
static getDerivedStateFromError(error) {
return {
error
};
}
componentDidCatch(error, errorInfo) {
console.error("<Await> caught the following error during render", error, errorInfo);
}
render() {
let {
children,
errorElement,
resolve
} = this.props;
let promise = null;
let status = AwaitRenderStatus.pending;
if (!(resolve instanceof Promise)) {
// Didn't get a promise - provide as a resolved promise
status = AwaitRenderStatus.success;
promise = Promise.resolve();
Object.defineProperty(promise, "_tracked", {
get: () => true
});
Object.defineProperty(promise, "_data", {
get: () => resolve
});
} else if (this.state.error) {
// Caught a render error, provide it as a rejected promise
status = AwaitRenderStatus.error;
let renderError = this.state.error;
promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings
Object.defineProperty(promise, "_tracked", {
get: () => true
});
Object.defineProperty(promise, "_error", {
get: () => renderError
});
} else if (resolve._tracked) {
// Already tracked promise - check contents
promise = resolve;
status = promise._error !== undefined ? AwaitRenderStatus.error : promise._data !== undefined ? AwaitRenderStatus.success : AwaitRenderStatus.pending;
} else {
// Raw (untracked) promise - track it
status = AwaitRenderStatus.pending;
Object.defineProperty(resolve, "_tracked", {
get: () => true
});
promise = resolve.then(data => Object.defineProperty(resolve, "_data", {
get: () => data
}), error => Object.defineProperty(resolve, "_error", {
get: () => error
}));
}
if (status === AwaitRenderStatus.error && promise._error instanceof AbortedDeferredError) {
// Freeze the UI by throwing a never resolved promise
throw neverSettledPromise;
}
if (status === AwaitRenderStatus.error && !errorElement) {
// No errorElement, throw to the nearest route-level error boundary
throw promise._error;
}
if (status === AwaitRenderStatus.error) {
// Render via our errorElement
return /*#__PURE__*/React.createElement(AwaitContext.Provider, {
value: promise,
children: errorElement
});
}
if (status === AwaitRenderStatus.success) {
// Render children with resolved value
return /*#__PURE__*/React.createElement(AwaitContext.Provider, {
value: promise,
children: children
});
} // Throw to the suspense boundary
throw promise;
}
}
/**
* @private
* Indirection to leverage useAsyncValue for a render-prop API on <Await>
*/
function ResolveAwait(_ref7) {
let {
children
} = _ref7;
let data = useAsyncValue();
if (typeof children === "function") {
return children(data);
}
return /*#__PURE__*/React.createElement(React.Fragment, null, children);
} ///////////////////////////////////////////////////////////////////////////////
// UTILS
///////////////////////////////////////////////////////////////////////////////
/**
* Creates a route config from a React "children" object, which is usually
* either a `<Route>` element or an array of them. Used internally by
* `<Routes>` to create a route config from its children.
*
* @see https://reactrouter.com/docs/en/v6/utils/create-routes-from-children
*/
function createRoutesFromChildren(children, parentPath) {
if (parentPath === void 0) {
parentPath = [];
}
let routes = [];
React.Children.forEach(children, (element, index) => {
if (! /*#__PURE__*/React.isValidElement(element)) {
// Ignore non-elements. This allows people to more easily inline
// conditionals in their route config.
return;
}
if (element.type === React.Fragment) {
// Transparently support React.Fragment and its children.
routes.push.apply(routes, createRoutesFromChildren(element.props.children, parentPath));
return;
}
!(element.type === Route) ? process.env.NODE_ENV !== "production" ? invariant(false, "[" + (typeof element.type === "string" ? element.type : element.type.name) + "] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>") : invariant(false) : void 0;
!(!element.props.index || !element.props.children) ? process.env.NODE_ENV !== "production" ? invariant(false, "An index route cannot have child routes.") : invariant(false) : void 0;
let treePath = [...parentPath, index];
let route = {
id: element.props.id || treePath.join("-"),
caseSensitive: element.props.caseSensitive,
element: element.props.element,
index: element.props.index,
path: element.props.path,
loader: element.props.loader,
action: element.props.action,
errorElement: element.props.errorElement,
hasErrorBoundary: element.props.errorElement != null,
shouldRevalidate: element.props.shouldRevalidate,
handle: element.props.handle
};
if (element.props.children) {
route.children = createRoutesFromChildren(element.props.children, treePath);
}
routes.push(route);
});
return routes;
}
/**
* Renders the result of `matchRoutes()` into a React element.
*/
function renderMatches(matches) {
return _renderMatches(matches);
}
/**
* @private
* Walk the route tree and add hasErrorBoundary if it's not provided, so that
* users providing manual route arrays can just specify errorElement
*/
function enhanceManualRouteObjects(routes) {
return routes.map(route => {
let routeClone = _extends({}, route);
if (routeClone.hasErrorBoundary == null) {
routeClone.hasErrorBoundary = routeClone.errorElement != null;
}
if (routeClone.children) {
routeClone.children = enhanceManualRouteObjects(routeClone.children);
}
return routeClone;
});
}
function createMemoryRouter(routes, opts) {
return createRouter({
basename: opts == null ? void 0 : opts.basename,
history: createMemoryHistory({
initialEntries: opts == null ? void 0 : opts.initialEntries,
initialIndex: opts == null ? void 0 : opts.initialIndex
}),
hydrationData: opts == null ? void 0 : opts.hydrationData,
routes: enhanceManualRouteObjects(routes)
}).initialize();
} ///////////////////////////////////////////////////////////////////////////////
export { Await, MemoryRouter, Navigate, Outlet, Route, Router, RouterProvider, Routes, DataRouterContext as UNSAFE_DataRouterContext, DataRouterStateContext as UNSAFE_DataRouterStateContext, DataStaticRouterContext as UNSAFE_DataStaticRouterContext, LocationContext as UNSAFE_LocationContext, NavigationContext as UNSAFE_NavigationContext, RouteContext as UNSAFE_RouteContext, enhanceManualRouteObjects as UNSAFE_enhanceManualRouteObjects, createMemoryRouter, createRoutesFromChildren, createRoutesFromChildren as createRoutesFromElements, renderMatches, useActionData, useAsyncError, useAsyncValue, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes };
//# sourceMappingURL=index.js.map
webpack://frontend-mybets/../../node_modules/react-router-dom/dist/index.js
/**
* React Router DOM v6.4.2
*
* Copyright (c) Remix Software Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
import * as React from 'react';
import { UNSAFE_enhanceManualRouteObjects, Router, useHref, createPath, useResolvedPath, useMatch, UNSAFE_DataRouterStateContext, useNavigate, useLocation, UNSAFE_NavigationContext, UNSAFE_RouteContext, useMatches, useNavigation, UNSAFE_DataRouterContext } from 'react-router';
export { AbortedDeferredError, Await, MemoryRouter, Navigate, NavigationType, Outlet, Route, Router, RouterProvider, Routes, UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, UNSAFE_DataStaticRouterContext, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, UNSAFE_enhanceManualRouteObjects, createMemoryRouter, createPath, createRoutesFromChildren, createRoutesFromElements, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, renderMatches, resolvePath, useActionData, useAsyncError, useAsyncValue, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes } from 'react-router';
import { createRouter, createBrowserHistory, createHashHistory, matchPath, invariant, joinPaths } from '@remix-run/router';
function _extends() {
_extends = Object.assign ? Object.assign.bind() : 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;
}
const defaultMethod = "get";
const defaultEncType = "application/x-www-form-urlencoded";
function isHtmlElement(object) {
return object != null && typeof object.tagName === "string";
}
function isButtonElement(object) {
return isHtmlElement(object) && object.tagName.toLowerCase() === "button";
}
function isFormElement(object) {
return isHtmlElement(object) && object.tagName.toLowerCase() === "form";
}
function isInputElement(object) {
return isHtmlElement(object) && object.tagName.toLowerCase() === "input";
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
function shouldProcessLinkClick(event, target) {
return event.button === 0 && ( // Ignore everything but left clicks
!target || target === "_self") && // Let browser handle "target=_blank" etc.
!isModifiedEvent(event) // Ignore clicks with modifier keys
;
}
/**
* Creates a URLSearchParams object using the given initializer.
*
* This is identical to `new URLSearchParams(init)` except it also
* supports arrays as values in the object form of the initializer
* instead of just strings. This is convenient when you need multiple
* values for a given key, but don't want to use an array initializer.
*
* For example, instead of:
*
* let searchParams = new URLSearchParams([
* ['sort', 'name'],
* ['sort', 'price']
* ]);
*
* you can do:
*
* let searchParams = createSearchParams({
* sort: ['name', 'price']
* });
*/
function createSearchParams(init) {
if (init === void 0) {
init = "";
}
return new URLSearchParams(typeof init === "string" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo, key) => {
let value = init[key];
return memo.concat(Array.isArray(value) ? value.map(v => [key, v]) : [[key, value]]);
}, []));
}
function getSearchParamsForLocation(locationSearch, defaultSearchParams) {
let searchParams = createSearchParams(locationSearch);
for (let key of defaultSearchParams.keys()) {
if (!searchParams.has(key)) {
defaultSearchParams.getAll(key).forEach(value => {
searchParams.append(key, value);
});
}
}
return searchParams;
}
function getFormSubmissionInfo(target, defaultAction, options) {
let method;
let action;
let encType;
let formData;
if (isFormElement(target)) {
let submissionTrigger = options.submissionTrigger;
method = options.method || target.getAttribute("method") || defaultMethod;
action = options.action || target.getAttribute("action") || defaultAction;
encType = options.encType || target.getAttribute("enctype") || defaultEncType;
formData = new FormData(target);
if (submissionTrigger && submissionTrigger.name) {
formData.append(submissionTrigger.name, submissionTrigger.value);
}
} else if (isButtonElement(target) || isInputElement(target) && (target.type === "submit" || target.type === "image")) {
let form = target.form;
if (form == null) {
throw new Error("Cannot submit a <button> or <input type=\"submit\"> without a <form>");
} // <button>/<input type="submit"> may override attributes of <form>
method = options.method || target.getAttribute("formmethod") || form.getAttribute("method") || defaultMethod;
action = options.action || target.getAttribute("formaction") || form.getAttribute("action") || defaultAction;
encType = options.encType || target.getAttribute("formenctype") || form.getAttribute("enctype") || defaultEncType;
formData = new FormData(form); // Include name + value from a <button>, appending in case the button name
// matches an existing input name
if (target.name) {
formData.append(target.name, target.value);
}
} else if (isHtmlElement(target)) {
throw new Error("Cannot submit element that is not <form>, <button>, or " + "<input type=\"submit|image\">");
} else {
method = options.method || defaultMethod;
action = options.action || defaultAction;
encType = options.encType || defaultEncType;
if (target instanceof FormData) {
formData = target;
} else {
formData = new FormData();
if (target instanceof URLSearchParams) {
for (let [name, value] of target) {
formData.append(name, value);
}
} else if (target != null) {
for (let name of Object.keys(target)) {
formData.append(name, target[name]);
}
}
}
}
let {
protocol,
host
} = window.location;
let url = new URL(action, protocol + "//" + host);
return {
url,
method,
encType,
formData
};
}
const _excluded = ["onClick", "relative", "reloadDocument", "replace", "state", "target", "to", "preventScrollReset"],
_excluded2 = ["aria-current", "caseSensitive", "className", "end", "style", "to", "children"],
_excluded3 = ["reloadDocument", "replace", "method", "action", "onSubmit", "fetcherKey", "routeId", "relative"];
//#region Routers
////////////////////////////////////////////////////////////////////////////////
function createBrowserRouter(routes, opts) {
var _window;
return createRouter({
basename: opts == null ? void 0 : opts.basename,
history: createBrowserHistory({
window: opts == null ? void 0 : opts.window
}),
hydrationData: (opts == null ? void 0 : opts.hydrationData) || ((_window = window) == null ? void 0 : _window.__staticRouterHydrationData),
routes: UNSAFE_enhanceManualRouteObjects(routes)
}).initialize();
}
function createHashRouter(routes, opts) {
var _window2;
return createRouter({
basename: opts == null ? void 0 : opts.basename,
history: createHashHistory({
window: opts == null ? void 0 : opts.window
}),
hydrationData: (opts == null ? void 0 : opts.hydrationData) || ((_window2 = window) == null ? void 0 : _window2.__staticRouterHydrationData),
routes: UNSAFE_enhanceManualRouteObjects(routes)
}).initialize();
}
/**
* A `<Router>` for use in web browsers. Provides the cleanest URLs.
*/
function BrowserRouter(_ref) {
let {
basename,
children,
window
} = _ref;
let historyRef = React.useRef();
if (historyRef.current == null) {
historyRef.current = createBrowserHistory({
window,
v5Compat: true
});
}
let history = historyRef.current;
let [state, setState] = React.useState({
action: history.action,
location: history.location
});
React.useLayoutEffect(() => history.listen(setState), [history]);
return /*#__PURE__*/React.createElement(Router, {
basename: basename,
children: children,
location: state.location,
navigationType: state.action,
navigator: history
});
}
/**
* A `<Router>` for use in web browsers. Stores the location in the hash
* portion of the URL so it is not sent to the server.
*/
function HashRouter(_ref2) {
let {
basename,
children,
window
} = _ref2;
let historyRef = React.useRef();
if (historyRef.current == null) {
historyRef.current = createHashHistory({
window,
v5Compat: true
});
}
let history = historyRef.current;
let [state, setState] = React.useState({
action: history.action,
location: history.location
});
React.useLayoutEffect(() => history.listen(setState), [history]);
return /*#__PURE__*/React.createElement(Router, {
basename: basename,
children: children,
location: state.location,
navigationType: state.action,
navigator: history
});
}
/**
* A `<Router>` that accepts a pre-instantiated history object. It's important
* to note that using your own history object is highly discouraged and may add
* two versions of the history library to your bundles unless you use the same
* version of the history library that React Router uses internally.
*/
function HistoryRouter(_ref3) {
let {
basename,
children,
history
} = _ref3;
const [state, setState] = React.useState({
action: history.action,
location: history.location
});
React.useLayoutEffect(() => history.listen(setState), [history]);
return /*#__PURE__*/React.createElement(Router, {
basename: basename,
children: children,
location: state.location,
navigationType: state.action,
navigator: history
});
}
if (process.env.NODE_ENV !== "production") {
HistoryRouter.displayName = "unstable_HistoryRouter";
}
/**
* The public API for rendering a history-aware <a>.
*/
const Link = /*#__PURE__*/React.forwardRef(function LinkWithRef(_ref4, ref) {
let {
onClick,
relative,
reloadDocument,
replace,
state,
target,
to,
preventScrollReset
} = _ref4,
rest = _objectWithoutPropertiesLoose(_ref4, _excluded);
let href = useHref(to, {
relative
});
let internalOnClick = useLinkClickHandler(to, {
replace,
state,
target,
preventScrollReset,
relative
});
function handleClick(event) {
if (onClick) onClick(event);
if (!event.defaultPrevented) {
internalOnClick(event);
}
}
return (
/*#__PURE__*/
// eslint-disable-next-line jsx-a11y/anchor-has-content
React.createElement("a", _extends({}, rest, {
href: href,
onClick: reloadDocument ? onClick : handleClick,
ref: ref,
target: target
}))
);
});
if (process.env.NODE_ENV !== "production") {
Link.displayName = "Link";
}
/**
* A <Link> wrapper that knows if it's "active" or not.
*/
const NavLink = /*#__PURE__*/React.forwardRef(function NavLinkWithRef(_ref5, ref) {
let {
"aria-current": ariaCurrentProp = "page",
caseSensitive = false,
className: classNameProp = "",
end = false,
style: styleProp,
to,
children
} = _ref5,
rest = _objectWithoutPropertiesLoose(_ref5, _excluded2);
let path = useResolvedPath(to);
let match = useMatch({
path: path.pathname,
end,
caseSensitive
});
let routerState = React.useContext(UNSAFE_DataRouterStateContext);
let nextLocation = routerState == null ? void 0 : routerState.navigation.location;
let nextPath = useResolvedPath(nextLocation || "");
let nextMatch = React.useMemo(() => nextLocation ? matchPath({
path: path.pathname,
end,
caseSensitive
}, nextPath.pathname) : null, [nextLocation, path.pathname, caseSensitive, end, nextPath.pathname]);
let isPending = nextMatch != null;
let isActive = match != null;
let ariaCurrent = isActive ? ariaCurrentProp : undefined;
let className;
if (typeof classNameProp === "function") {
className = classNameProp({
isActive,
isPending
});
} else {
// If the className prop is not a function, we use a default `active`
// class for <NavLink />s that are active. In v5 `active` was the default
// value for `activeClassName`, but we are removing that API and can still
// use the old default behavior for a cleaner upgrade path and keep the
// simple styling rules working as they currently do.
className = [classNameProp, isActive ? "active" : null, isPending ? "pending" : null].filter(Boolean).join(" ");
}
let style = typeof styleProp === "function" ? styleProp({
isActive,
isPending
}) : styleProp;
return /*#__PURE__*/React.createElement(Link, _extends({}, rest, {
"aria-current": ariaCurrent,
className: className,
ref: ref,
style: style,
to: to
}), typeof children === "function" ? children({
isActive,
isPending
}) : children);
});
if (process.env.NODE_ENV !== "production") {
NavLink.displayName = "NavLink";
}
/**
* A `@remix-run/router`-aware `<form>`. It behaves like a normal form except
* that the interaction with the server is with `fetch` instead of new document
* requests, allowing components to add nicer UX to the page as the form is
* submitted and returns with data.
*/
const Form = /*#__PURE__*/React.forwardRef((props, ref) => {
return /*#__PURE__*/React.createElement(FormImpl, _extends({}, props, {
ref: ref
}));
});
if (process.env.NODE_ENV !== "production") {
Form.displayName = "Form";
}
const FormImpl = /*#__PURE__*/React.forwardRef((_ref6, forwardedRef) => {
let {
reloadDocument,
replace,
method = defaultMethod,
action,
onSubmit,
fetcherKey,
routeId,
relative
} = _ref6,
props = _objectWithoutPropertiesLoose(_ref6, _excluded3);
let submit = useSubmitImpl(fetcherKey, routeId);
let formMethod = method.toLowerCase() === "get" ? "get" : "post";
let formAction = useFormAction(action, {
relative
});
let submitHandler = event => {
onSubmit && onSubmit(event);
if (event.defaultPrevented) return;
event.preventDefault();
let submitter = event.nativeEvent.submitter;
submit(submitter || event.currentTarget, {
method,
replace,
relative
});
};
return /*#__PURE__*/React.createElement("form", _extends({
ref: forwardedRef,
method: formMethod,
action: formAction,
onSubmit: reloadDocument ? onSubmit : submitHandler
}, props));
});
if (process.env.NODE_ENV !== "production") {
Form.displayName = "Form";
}
/**
* This component will emulate the browser's scroll restoration on location
* changes.
*/
function ScrollRestoration(_ref7) {
let {
getKey,
storageKey
} = _ref7;
useScrollRestoration({
getKey,
storageKey
});
return null;
}
if (process.env.NODE_ENV !== "production") {
ScrollRestoration.displayName = "ScrollRestoration";
} //#endregion
////////////////////////////////////////////////////////////////////////////////
//#region Hooks
////////////////////////////////////////////////////////////////////////////////
var DataRouterHook;
(function (DataRouterHook) {
DataRouterHook["UseScrollRestoration"] = "useScrollRestoration";
DataRouterHook["UseSubmitImpl"] = "useSubmitImpl";
DataRouterHook["UseFetcher"] = "useFetcher";
})(DataRouterHook || (DataRouterHook = {}));
var DataRouterStateHook;
(function (DataRouterStateHook) {
DataRouterStateHook["UseFetchers"] = "useFetchers";
DataRouterStateHook["UseScrollRestoration"] = "useScrollRestoration";
})(DataRouterStateHook || (DataRouterStateHook = {}));
function getDataRouterConsoleError(hookName) {
return hookName + " must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.";
}
function useDataRouterContext(hookName) {
let ctx = React.useContext(UNSAFE_DataRouterContext);
!ctx ? process.env.NODE_ENV !== "production" ? invariant(false, getDataRouterConsoleError(hookName)) : invariant(false) : void 0;
return ctx;
}
function useDataRouterState(hookName) {
let state = React.useContext(UNSAFE_DataRouterStateContext);
!state ? process.env.NODE_ENV !== "production" ? invariant(false, getDataRouterConsoleError(hookName)) : invariant(false) : void 0;
return state;
}
/**
* Handles the click behavior for router `<Link>` components. This is useful if
* you need to create custom `<Link>` components with the same click behavior we
* use in our exported `<Link>`.
*/
function useLinkClickHandler(to, _temp) {
let {
target,
replace: replaceProp,
state,
preventScrollReset,
relative
} = _temp === void 0 ? {} : _temp;
let navigate = useNavigate();
let location = useLocation();
let path = useResolvedPath(to, {
relative
});
return React.useCallback(event => {
if (shouldProcessLinkClick(event, target)) {
event.preventDefault(); // If the URL hasn't changed, a regular <a> will do a replace instead of
// a push, so do the same here unless the replace prop is explicitly set
let replace = replaceProp !== undefined ? replaceProp : createPath(location) === createPath(path);
navigate(to, {
replace,
state,
preventScrollReset,
relative
});
}
}, [location, navigate, path, replaceProp, state, target, to, preventScrollReset, relative]);
}
/**
* A convenient wrapper for reading and writing search parameters via the
* URLSearchParams interface.
*/
function useSearchParams(defaultInit) {
process.env.NODE_ENV !== "production" ? warning(typeof URLSearchParams !== "undefined", "You cannot use the `useSearchParams` hook in a browser that does not " + "support the URLSearchParams API. If you need to support Internet " + "Explorer 11, we recommend you load a polyfill such as " + "https://github.com/ungap/url-search-params\n\n" + "If you're unsure how to load polyfills, we recommend you check out " + "https://polyfill.io/v3/ which provides some recommendations about how " + "to load polyfills only for users that need them, instead of for every " + "user.") : void 0;
let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));
let location = useLocation();
let searchParams = React.useMemo(() => getSearchParamsForLocation(location.search, defaultSearchParamsRef.current), [location.search]);
let navigate = useNavigate();
let setSearchParams = React.useCallback((nextInit, navigateOptions) => {
const newSearchParams = createSearchParams(typeof nextInit === "function" ? nextInit(searchParams) : nextInit);
navigate("?" + newSearchParams, navigateOptions);
}, [navigate, searchParams]);
return [searchParams, setSearchParams];
}
/**
* Returns a function that may be used to programmatically submit a form (or
* some arbitrary data) to the server.
*/
function useSubmit() {
return useSubmitImpl();
}
function useSubmitImpl(fetcherKey, routeId) {
let {
router
} = useDataRouterContext(DataRouterHook.UseSubmitImpl);
let defaultAction = useFormAction();
return React.useCallback(function (target, options) {
if (options === void 0) {
options = {};
}
if (typeof document === "undefined") {
throw new Error("You are calling submit during the server render. " + "Try calling submit within a `useEffect` or callback instead.");
}
let {
method,
encType,
formData,
url
} = getFormSubmissionInfo(target, defaultAction, options);
let href = url.pathname + url.search;
let opts = {
replace: options.replace,
formData,
formMethod: method,
formEncType: encType
};
if (fetcherKey) {
!(routeId != null) ? process.env.NODE_ENV !== "production" ? invariant(false, "No routeId available for useFetcher()") : invariant(false) : void 0;
router.fetch(fetcherKey, routeId, href, opts);
} else {
router.navigate(href, opts);
}
}, [defaultAction, router, fetcherKey, routeId]);
}
function useFormAction(action, _temp2) {
let {
relative
} = _temp2 === void 0 ? {} : _temp2;
let {
basename
} = React.useContext(UNSAFE_NavigationContext);
let routeContext = React.useContext(UNSAFE_RouteContext);
!routeContext ? process.env.NODE_ENV !== "production" ? invariant(false, "useFormAction must be used inside a RouteContext") : invariant(false) : void 0;
let [match] = routeContext.matches.slice(-1);
let resolvedAction = action != null ? action : "."; // Shallow clone path so we can modify it below, otherwise we modify the
// object referenced by useMemo inside useResolvedPath
let path = _extends({}, useResolvedPath(resolvedAction, {
relative
})); // Previously we set the default action to ".". The problem with this is that
// `useResolvedPath(".")` excludes search params and the hash of the resolved
// URL. This is the intended behavior of when "." is specifically provided as
// the form action, but inconsistent w/ browsers when the action is omitted.
// https://github.com/remix-run/remix/issues/927
let location = useLocation();
if (action == null) {
// Safe to write to these directly here since if action was undefined, we
// would have called useResolvedPath(".") which will never include a search
// or hash
path.search = location.search;
path.hash = location.hash; // When grabbing search params from the URL, remove the automatically
// inserted ?index param so we match the useResolvedPath search behavior
// which would not include ?index
if (match.route.index) {
let params = new URLSearchParams(path.search);
params.delete("index");
path.search = params.toString() ? "?" + params.toString() : "";
}
}
if ((!action || action === ".") && match.route.index) {
path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
} // If we're operating within a basename, prepend it to the pathname prior
// to creating the form action. If this is a root navigation, then just use
// the raw basename which allows the basename to have full control over the
// presence of a trailing slash on root actions
if (basename !== "/") {
path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
}
return createPath(path);
}
function createFetcherForm(fetcherKey, routeId) {
let FetcherForm = /*#__PURE__*/React.forwardRef((props, ref) => {
return /*#__PURE__*/React.createElement(FormImpl, _extends({}, props, {
ref: ref,
fetcherKey: fetcherKey,
routeId: routeId
}));
});
if (process.env.NODE_ENV !== "production") {
FetcherForm.displayName = "fetcher.Form";
}
return FetcherForm;
}
let fetcherId = 0;
/**
* Interacts with route loaders and actions without causing a navigation. Great
* for any interaction that stays on the same page.
*/
function useFetcher() {
var _route$matches;
let {
router
} = useDataRouterContext(DataRouterHook.UseFetcher);
let route = React.useContext(UNSAFE_RouteContext);
!route ? process.env.NODE_ENV !== "production" ? invariant(false, "useFetcher must be used inside a RouteContext") : invariant(false) : void 0;
let routeId = (_route$matches = route.matches[route.matches.length - 1]) == null ? void 0 : _route$matches.route.id;
!(routeId != null) ? process.env.NODE_ENV !== "production" ? invariant(false, "useFetcher can only be used on routes that contain a unique \"id\"") : invariant(false) : void 0;
let [fetcherKey] = React.useState(() => String(++fetcherId));
let [Form] = React.useState(() => {
!routeId ? process.env.NODE_ENV !== "production" ? invariant(false, "No routeId available for fetcher.Form()") : invariant(false) : void 0;
return createFetcherForm(fetcherKey, routeId);
});
let [load] = React.useState(() => href => {
!router ? process.env.NODE_ENV !== "production" ? invariant(false, "No router available for fetcher.load()") : invariant(false) : void 0;
!routeId ? process.env.NODE_ENV !== "production" ? invariant(false, "No routeId available for fetcher.load()") : invariant(false) : void 0;
router.fetch(fetcherKey, routeId, href);
});
let submit = useSubmitImpl(fetcherKey, routeId);
let fetcher = router.getFetcher(fetcherKey);
let fetcherWithComponents = React.useMemo(() => _extends({
Form,
submit,
load
}, fetcher), [fetcher, Form, submit, load]);
React.useEffect(() => {
// Is this busted when the React team gets real weird and calls effects
// twice on mount? We really just need to garbage collect here when this
// fetcher is no longer around.
return () => {
if (!router) {
console.warn("No fetcher available to clean up from useFetcher()");
return;
}
router.deleteFetcher(fetcherKey);
};
}, [router, fetcherKey]);
return fetcherWithComponents;
}
/**
* Provides all fetchers currently on the page. Useful for layouts and parent
* routes that need to provide pending/optimistic UI regarding the fetch.
*/
function useFetchers() {
let state = useDataRouterState(DataRouterStateHook.UseFetchers);
return [...state.fetchers.values()];
}
const SCROLL_RESTORATION_STORAGE_KEY = "react-router-scroll-positions";
let savedScrollPositions = {};
/**
* When rendered inside a RouterProvider, will restore scroll positions on navigations
*/
function useScrollRestoration(_temp3) {
let {
getKey,
storageKey
} = _temp3 === void 0 ? {} : _temp3;
let {
router
} = useDataRouterContext(DataRouterHook.UseScrollRestoration);
let {
restoreScrollPosition,
preventScrollReset
} = useDataRouterState(DataRouterStateHook.UseScrollRestoration);
let location = useLocation();
let matches = useMatches();
let navigation = useNavigation(); // Trigger manual scroll restoration while we're active
React.useEffect(() => {
window.history.scrollRestoration = "manual";
return () => {
window.history.scrollRestoration = "auto";
};
}, []); // Save positions on unload
useBeforeUnload(React.useCallback(() => {
if (navigation.state === "idle") {
let key = (getKey ? getKey(location, matches) : null) || location.key;
savedScrollPositions[key] = window.scrollY;
}
sessionStorage.setItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY, JSON.stringify(savedScrollPositions));
window.history.scrollRestoration = "auto";
}, [storageKey, getKey, navigation.state, location, matches])); // Read in any saved scroll locations
React.useLayoutEffect(() => {
try {
let sessionPositions = sessionStorage.getItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY);
if (sessionPositions) {
savedScrollPositions = JSON.parse(sessionPositions);
}
} catch (e) {// no-op, use default empty object
}
}, [storageKey]); // Enable scroll restoration in the router
React.useLayoutEffect(() => {
let disableScrollRestoration = router == null ? void 0 : router.enableScrollRestoration(savedScrollPositions, () => window.scrollY, getKey);
return () => disableScrollRestoration && disableScrollRestoration();
}, [router, getKey]); // Restore scrolling when state.restoreScrollPosition changes
React.useLayoutEffect(() => {
// Explicit false means don't do anything (used for submissions)
if (restoreScrollPosition === false) {
return;
} // been here before, scroll to it
if (typeof restoreScrollPosition === "number") {
window.scrollTo(0, restoreScrollPosition);
return;
} // try to scroll to the hash
if (location.hash) {
let el = document.getElementById(location.hash.slice(1));
if (el) {
el.scrollIntoView();
return;
}
} // Opt out of scroll reset if this link requested it
if (preventScrollReset === true) {
return;
} // otherwise go to the top on new locations
window.scrollTo(0, 0);
}, [location, restoreScrollPosition, preventScrollReset]);
}
function useBeforeUnload(callback) {
React.useEffect(() => {
window.addEventListener("beforeunload", callback);
return () => {
window.removeEventListener("beforeunload", callback);
};
}, [callback]);
} //#endregion
////////////////////////////////////////////////////////////////////////////////
//#region Utils
////////////////////////////////////////////////////////////////////////////////
function warning(cond, message) {
if (!cond) {
// eslint-disable-next-line no-console
if (typeof console !== "undefined") console.warn(message);
try {
// Welcome to debugging React Router!
//
// This error is thrown as a convenience so you can more easily
// find the source for a warning that appears in the console by
// enabling "pause on exceptions" in your JavaScript debugger.
throw new Error(message); // eslint-disable-next-line no-empty
} catch (e) {}
}
} //#endregion
export { BrowserRouter, Form, HashRouter, Link, NavLink, ScrollRestoration, createBrowserRouter, createHashRouter, createSearchParams, HistoryRouter as unstable_HistoryRouter, useFetcher, useFetchers, useFormAction, useLinkClickHandler, useSearchParams, useSubmit };
//# sourceMappingURL=index.js.map
webpack://frontend-mybets/../../packages/tvg-lib-utils/apolloContext.js
import React from "react";
const ApolloContext = React.createContext({
fcpClient: null,
rdaClient: null,
behgClient: null
});
export default ApolloContext;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/theme/FormationTokens.ts
// IMPORTANT: This file is automatically generated by tools/formation-tokens-auto-upgrade/main.sh
import { createGlobalStyle } from "styled-components";
export const FormationTokens = createGlobalStyle`
/**
* Do not edit directly
* Generated on Fri, 18 Oct 2024 14:02:52 GMT
*/
:root {
--fd-colors-product-colors-tertiary-d-4: #D78027;
--fd-colors-product-colors-tertiary-d-3: #E49627;
--fd-colors-product-colors-tertiary-d-2: #EFAC27;
--fd-colors-product-colors-tertiary-d-1: #F8C429;
--fd-colors-product-colors-tertiary: #FFDC2E;
--fd-colors-product-colors-tertiary-l-1: #FFEDA0;
--fd-colors-product-colors-tertiary-l-2: #FFF1B3;
--fd-colors-product-colors-tertiary-l-3: #FFF4C6;
--fd-colors-product-colors-tertiary-l-4: #FFF8D9;
--fd-colors-product-colors-tertiary-l-5: #FFFBEC;
--fd-text-theme-name: Fanduel Light;
--fd-border-styles-border-style-dashed-style: dashed;
--fd-border-styles-border-style-solid-style: solid;
--fd-radii-border-radius-050: 24px;
--fd-radii-border-radius-040: 12px;
--fd-radii-border-radius-030: 8px;
--fd-radii-border-radius-020: 4px;
--fd-radii-border-radius-010: 2px;
--fd-radii-border-radius-circle: 9999px;
--fd-radii-border-radius-sharp: 0;
--fd-border-widths-border-width-040: 8px;
--fd-border-widths-border-width-030: 4px;
--fd-border-widths-border-width-020: 2px;
--fd-border-widths-border-width-010: 1px;
--fd-border-widths-border-width-000: 0;
--fd-space-space-base: 4px;
--fd-sizes-max-content-width: 1400px;
--fd-text-decoration-text-decoration-line-through: line-through;
--fd-text-decoration-text-decoration-underline: underline;
--fd-text-decoration-text-decoration-none: none;
--fd-text-case-text-case-none: none;
--fd-text-case-text-case-lowercase: lowercase;
--fd-text-case-text-case-capitalize: capitalize;
--fd-text-case-text-case-uppercase: uppercase;
--fd-letter-spacings-letter-spacing-030: 1px;
--fd-letter-spacings-letter-spacing-020: 0.5px;
--fd-letter-spacings-letter-spacing-010: 0;
--fd-font-sizes-font-size-150: 60px;
--fd-font-sizes-font-size-140: 48px;
--fd-font-sizes-font-size-130: 40px;
--fd-font-sizes-font-size-120: 36px;
--fd-font-sizes-font-size-110: 32px;
--fd-font-sizes-font-size-100: 28px;
--fd-font-sizes-font-size-090: 24px;
--fd-font-sizes-font-size-080: 22px;
--fd-font-sizes-font-size-070: 20px;
--fd-font-sizes-font-size-060: 18px;
--fd-font-sizes-font-size-050: 16px;
--fd-font-sizes-font-size-040: 14px;
--fd-font-sizes-font-size-030: 12px;
--fd-font-sizes-font-size-020: 10px;
--fd-font-sizes-font-size-010: 8px;
--fd-line-heights-line-height-040: 1.5;
--fd-line-heights-line-height-030: 1.25;
--fd-line-heights-line-height-020: 1.1;
--fd-line-heights-line-height-010: 1;
--fd-font-weights-font-weight-090: 900;
--fd-font-weights-font-weight-080: 800;
--fd-font-weights-font-weight-070: 800;
--fd-font-weights-font-weight-060: 700;
--fd-font-weights-font-weight-050: 700;
--fd-font-weights-font-weight-040: 600;
--fd-font-weights-font-weight-030: 500;
--fd-font-weights-font-weight-020: 400;
--fd-font-weights-font-weight-010: 300;
--fd-fonts-font-family-050: Roboto Condensed;
--fd-fonts-font-family-040: Inter;
--fd-fonts-font-family-030: Proxima Nova Condensed;
--fd-fonts-font-family-020: Shentox;
--fd-fonts-font-family-010: Proxima Nova;
--fd-colors-core-transparent-black: #0a0a0a00;
--fd-colors-core-transparent-white: #ffffff00;
--fd-colors-core-white-tint-090: #ffffffe6;
--fd-colors-core-white-tint-080: #ffffffcc;
--fd-colors-core-white-tint-070: #ffffffb3;
--fd-colors-core-white-tint-060: #ffffff99;
--fd-colors-core-white-tint-050: #ffffff80;
--fd-colors-core-white-tint-040: #ffffff66;
--fd-colors-core-white-tint-030: #ffffff4d;
--fd-colors-core-white-tint-020: #ffffff33;
--fd-colors-core-white-tint-010: #ffffff1a;
--fd-colors-core-white-tint-005: #ffffff0d;
--fd-colors-core-black-tint-090: #0a0a0ae6;
--fd-colors-core-black-tint-080: #0a0a0acc;
--fd-colors-core-black-tint-070: #0a0a0ab3;
--fd-colors-core-black-tint-060: #0a0a0a99;
--fd-colors-core-black-tint-050: #0a0a0a80;
--fd-colors-core-black-tint-040: #0a0a0a66;
--fd-colors-core-black-tint-030: #0a0a0a4d;
--fd-colors-core-black-tint-020: #0a0a0a33;
--fd-colors-core-black-tint-010: #0a0a0a1a;
--fd-colors-core-black-tint-005: #0a0a0a0d;
--fd-colors-core-black: #0a0a0a;
--fd-colors-core-grey-d-4: #1C1D1D;
--fd-colors-core-grey-d-3: #2B2D2E;
--fd-colors-core-grey-d-2: #3C3E40;
--fd-colors-core-grey-d-1: #4D5153;
--fd-colors-core-grey: #6A6F73;
--fd-colors-core-grey-l-1: #969DA3;
--fd-colors-core-grey-l-2: #B0B7BF;
--fd-colors-core-grey-l-3: #CED4DB;
--fd-colors-core-grey-l-4: #EAF0F6;
--fd-colors-core-grey-l-5: #F7FBFF;
--fd-colors-core-white: #ffffff;
--fd-colors-core-teal-d-4: #003328;
--fd-colors-core-teal-d-3: #004435;
--fd-colors-core-teal-d-2: #005F48;
--fd-colors-core-teal-d-1: #00735A;
--fd-colors-core-teal: #008568;
--fd-colors-core-teal-l-1: #00C898;
--fd-colors-core-teal-l-2: #00E5B4;
--fd-colors-core-teal-l-3: #75EBD2;
--fd-colors-core-teal-l-4: #9CF7E4;
--fd-colors-core-teal-l-5: #D4FAF2;
--fd-colors-core-purple-d-4: #36005B;
--fd-colors-core-purple-d-3: #61019B;
--fd-colors-core-purple-d-2: #7401B7;
--fd-colors-core-purple-d-1: #8F02E1;
--fd-colors-core-purple: #A530F3;
--fd-colors-core-purple-l-1: #B265FE;
--fd-colors-core-purple-l-2: #C18FFE;
--fd-colors-core-purple-l-3: #D4B6FE;
--fd-colors-core-purple-l-4: #E6D6FE;
--fd-colors-core-purple-l-5: #F6F1FE;
--fd-colors-core-yellow-d-4: #2E2600;
--fd-colors-core-yellow-d-3: #4B3F00;
--fd-colors-core-yellow-d-2: #5F4F00;
--fd-colors-core-yellow-d-1: #756100;
--fd-colors-core-yellow: #8A7000;
--fd-colors-core-yellow-l-1: #A98E00;
--fd-colors-core-yellow-l-2: #C9A800;
--fd-colors-core-yellow-l-3: #EAC300;
--fd-colors-core-yellow-l-4: #FFDC2E;
--fd-colors-core-yellow-l-5: #FFF6BD;
--fd-colors-core-orange-d-4: #401D00;
--fd-colors-core-orange-d-3: #692E00;
--fd-colors-core-orange-d-2: #843B00;
--fd-colors-core-orange-d-1: #A44800;
--fd-colors-core-orange: #C15400;
--fd-colors-core-orange-l-1: #F87A1E;
--fd-colors-core-orange-l-2: #FF8C31;
--fd-colors-core-orange-l-3: #FFB77E;
--fd-colors-core-orange-l-4: #FFD8B9;
--fd-colors-core-orange-l-5: #FFF1E6;
--fd-colors-core-red-d-4: #40020D;
--fd-colors-core-red-d-3: #83001C;
--fd-colors-core-red-d-2: #A40023;
--fd-colors-core-red-d-1: #C8002B;
--fd-colors-core-red: #D22839;
--fd-colors-core-red-l-1: #EB4758;
--fd-colors-core-red-l-2: #EA6875;
--fd-colors-core-red-l-3: #F198A1;
--fd-colors-core-red-l-4: #F9C9CE;
--fd-colors-core-red-l-5: #FDECED;
--fd-colors-core-navy-d-4: #011638;
--fd-colors-core-navy-d-3: #05285A;
--fd-colors-core-navy-d-2: #103469;
--fd-colors-core-navy-d-1: #14417A;
--fd-colors-core-navy: #184C8B;
--fd-colors-core-navy-l-1: #6682A2;
--fd-colors-core-navy-l-2: #819CBB;
--fd-colors-core-navy-l-3: #9CB1CB;
--fd-colors-core-navy-l-4: #C6D3E1;
--fd-colors-core-navy-l-5: #EBF2FA;
--fd-colors-core-blue-d-4: #002650;
--fd-colors-core-blue-d-3: #003D81;
--fd-colors-core-blue-d-2: #004EA3;
--fd-colors-core-blue-d-1: #005FC8;
--fd-colors-core-blue: #0070EB;
--fd-colors-core-blue-l-1: #2B90FF;
--fd-colors-core-blue-l-2: #64AEFF;
--fd-colors-core-blue-l-3: #99CAFF;
--fd-colors-core-blue-l-4: #C8E2FF;
--fd-colors-core-blue-l-5: #EAF4FF;
--fd-colors-core-green-d-4: #002E11;
--fd-colors-core-green-d-3: #00491C;
--fd-colors-core-green-d-2: #005D23;
--fd-colors-core-green-d-1: #00732C;
--fd-colors-core-green: #128000;
--fd-colors-core-green-l-1: #1BB152;
--fd-colors-core-green-l-2: #31C268;
--fd-colors-core-green-l-3: #7FD9A1;
--fd-colors-core-green-l-4: #BCEBCE;
--fd-colors-core-green-l-5: #E9F8EF;
--fd-z-indices-high: 3;
--fd-z-indices-mid: 2;
--fd-z-indices-low: 1;
--fd-z-indices-none: 0;
--fd-transitions-acceleration: all 250ms cubic-bezier(0.4, 0, 1, 1) 0ms;
--fd-transitions-deceleration: all 250ms cubic-bezier(0, 0, 0.2, 1) 0ms;
--fd-transitions-standard: all 250ms cubic-bezier(0.4, 0, 0.2, 1) 0ms;
--fd-breakpoints-desktop: 1024;
--fd-breakpoints-tablet-landscape: 960;
--fd-breakpoints-tablet-portrait: 640;
--fd-breakpoints-mobile: 375;
--fd-colors-component-pill-inverse-background-disabled: var(--fd-colors-core-grey-l-4);
--fd-colors-component-pill-inverse-background-active: var(--fd-colors-core-blue-d-1);
--fd-colors-component-pill-inverse-background-selected: var(--fd-colors-core-blue);
--fd-colors-component-pill-inverse-background-hover: var(--fd-colors-core-grey-l-3);
--fd-colors-component-pill-inverse-content-disabled: var(--fd-colors-core-grey-l-2);
--fd-colors-component-pill-inverse-content-active: var(--fd-colors-core-white);
--fd-colors-component-pill-inverse-content-selected: var(--fd-colors-core-white);
--fd-colors-component-pill-inverse-content-hover: var(--fd-colors-core-navy-d-4);
--fd-colors-component-pill-inverse-content-base: var(--fd-colors-core-white);
--fd-colors-component-pill-primary-background-disabled: var(--fd-colors-core-grey-l-4);
--fd-colors-component-pill-primary-background-active: var(--fd-colors-core-blue-d-1);
--fd-colors-component-pill-primary-background-selected: var(--fd-colors-core-blue);
--fd-colors-component-pill-primary-background-hover: var(--fd-colors-core-grey-l-3);
--fd-colors-component-pill-primary-background-base: var(--fd-colors-core-grey-l-4);
--fd-colors-component-pill-primary-content-disabled: var(--fd-colors-core-grey-l-2);
--fd-colors-component-pill-primary-content-active: var(--fd-colors-core-white);
--fd-colors-component-pill-primary-content-selected: var(--fd-colors-core-white);
--fd-colors-component-pill-primary-content-hover: var(--fd-colors-core-navy-d-4);
--fd-colors-component-pill-primary-content-base: var(--fd-colors-core-navy-d-4);
--fd-colors-component-selection-control-foreground-unselected: var(--fd-colors-core-transparent-white);
--fd-colors-component-selection-control-foreground-active: var(--fd-colors-core-blue);
--fd-colors-component-selection-control-foreground-hover: var(--fd-colors-core-transparent-white);
--fd-colors-component-selection-control-foreground-base: var(--fd-colors-core-transparent-white);
--fd-colors-component-selection-control-border-error: var(--fd-colors-core-red);
--fd-colors-component-selection-control-border-success: var(--fd-colors-core-green);
--fd-colors-component-selection-control-border-unselected: var(--fd-colors-core-grey-l-3);
--fd-colors-component-selection-control-border-selected-active: var(--fd-colors-core-blue-d-2);
--fd-colors-component-selection-control-border-selected-hover: var(--fd-colors-core-blue-d-2);
--fd-colors-component-selection-control-border-selected: var(--fd-colors-core-blue-d-1);
--fd-colors-component-selection-control-border-active: var(--fd-colors-core-blue);
--fd-colors-component-selection-control-border-hover: var(--fd-colors-core-blue);
--fd-colors-component-selection-control-background-error: var(--fd-colors-core-red);
--fd-colors-component-selection-control-background-success: var(--fd-colors-core-green);
--fd-colors-component-selection-control-background-unselected: var(--fd-colors-core-grey-l-3);
--fd-colors-component-selection-control-background-selected-active: var(--fd-colors-core-blue-d-2);
--fd-colors-component-selection-control-background-selected-hover: var(--fd-colors-core-blue-d-2);
--fd-colors-component-selection-control-background-selected: var(--fd-colors-core-blue-d-1);
--fd-colors-component-selection-control-background-active: var(--fd-colors-core-blue);
--fd-colors-component-selection-control-background-hover: var(--fd-colors-core-blue-l-5);
--fd-colors-component-button-button-link-border-active: var(--fd-colors-core-transparent-white);
--fd-colors-component-button-button-link-border-hover: var(--fd-colors-core-transparent-white);
--fd-colors-component-button-button-link-border-base: var(--fd-colors-core-transparent-white);
--fd-colors-component-button-button-link-background-disabled: var(--fd-colors-core-transparent-white);
--fd-colors-component-button-button-link-background-active: var(--fd-colors-core-blue-d-1);
--fd-colors-component-button-button-link-background-hover: var(--fd-colors-core-blue-l-5);
--fd-colors-component-button-button-link-background-base: var(--fd-colors-core-transparent-white);
--fd-colors-component-button-button-link-content-active: var(--fd-colors-core-white);
--fd-colors-component-button-button-link-content-hover: var(--fd-colors-core-blue-d-2);
--fd-colors-component-button-button-link-content-base: var(--fd-colors-core-blue);
--fd-colors-component-button-destructive-border-active: var(--fd-colors-core-red-d-2);
--fd-colors-component-button-destructive-border-hover: var(--fd-colors-core-red-d-1);
--fd-colors-component-button-destructive-border-base: var(--fd-colors-core-red);
--fd-colors-component-button-destructive-background-active: var(--fd-colors-core-red-d-2);
--fd-colors-component-button-destructive-background-hover: var(--fd-colors-core-red-d-1);
--fd-colors-component-button-destructive-background-base: var(--fd-colors-core-red);
--fd-colors-component-button-destructive-content-active: var(--fd-colors-core-white);
--fd-colors-component-button-destructive-content-hover: var(--fd-colors-core-white);
--fd-colors-component-button-destructive-content-base: var(--fd-colors-core-white);
--fd-colors-component-button-transparent-border-disabled: var(--fd-colors-core-white-tint-020);
--fd-colors-component-button-transparent-border-active: var(--fd-colors-core-transparent-white);
--fd-colors-component-button-transparent-border-hover: var(--fd-colors-core-white);
--fd-colors-component-button-transparent-border-base: var(--fd-colors-core-white);
--fd-colors-component-button-transparent-background-disabled: var(--fd-colors-core-transparent-white);
--fd-colors-component-button-transparent-background-active: var(--fd-colors-core-blue);
--fd-colors-component-button-transparent-background-hover: var(--fd-colors-core-white-tint-010);
--fd-colors-component-button-transparent-background-base: var(--fd-colors-core-transparent-white);
--fd-colors-component-button-transparent-content-disabled: var(--fd-colors-core-white-tint-020);
--fd-colors-component-button-transparent-content-active: var(--fd-colors-core-white);
--fd-colors-component-button-transparent-content-hover: var(--fd-colors-core-white);
--fd-colors-component-button-transparent-content-base: var(--fd-colors-core-white);
--fd-colors-component-button-tertiary-border-active: var(--fd-colors-core-blue);
--fd-colors-component-button-tertiary-border-hover: var(--fd-colors-core-blue);
--fd-colors-component-button-tertiary-border-base: var(--fd-colors-core-blue);
--fd-colors-component-button-tertiary-background-disabled: var(--fd-colors-core-transparent-white);
--fd-colors-component-button-tertiary-background-active: var(--fd-colors-core-blue);
--fd-colors-component-button-tertiary-background-hover: var(--fd-colors-core-blue-l-5);
--fd-colors-component-button-tertiary-background-base: var(--fd-colors-core-transparent-white);
--fd-colors-component-button-tertiary-content-active: var(--fd-colors-core-white);
--fd-colors-component-button-tertiary-content-hover: var(--fd-colors-core-blue);
--fd-colors-component-button-tertiary-content-base: var(--fd-colors-core-blue);
--fd-colors-component-button-secondary-border-active: var(--fd-colors-core-blue-d-2);
--fd-colors-component-button-secondary-border-hover: var(--fd-colors-core-blue-d-1);
--fd-colors-component-button-secondary-border-base: var(--fd-colors-core-blue);
--fd-colors-component-button-secondary-background-active: var(--fd-colors-core-blue-d-2);
--fd-colors-component-button-secondary-background-hover: var(--fd-colors-core-blue-d-1);
--fd-colors-component-button-secondary-background-base: var(--fd-colors-core-blue);
--fd-colors-component-button-secondary-content-active: var(--fd-colors-core-white);
--fd-colors-component-button-secondary-content-hover: var(--fd-colors-core-white);
--fd-colors-component-button-secondary-content-base: var(--fd-colors-core-white);
--fd-colors-component-button-primary-border-active: var(--fd-colors-core-green-d-2);
--fd-colors-component-button-primary-border-hover: var(--fd-colors-core-green-d-1);
--fd-colors-component-button-primary-border-base: var(--fd-colors-core-green);
--fd-colors-component-button-primary-background-active: var(--fd-colors-core-green-d-2);
--fd-colors-component-button-primary-background-hover: var(--fd-colors-core-green-d-1);
--fd-colors-component-button-primary-background-base: var(--fd-colors-core-green);
--fd-colors-component-button-primary-content-active: var(--fd-colors-core-white);
--fd-colors-component-button-primary-content-hover: var(--fd-colors-core-white);
--fd-colors-component-button-primary-content-base: var(--fd-colors-core-white);
--fd-colors-system-verification-content-accent: var(--fd-colors-core-purple-d-2);
--fd-colors-system-verification-border-default: var(--fd-colors-core-purple-d-1);
--fd-colors-system-verification-background-subtle: var(--fd-colors-core-purple-l-5);
--fd-colors-system-verification-background-default: var(--fd-colors-core-purple-d-1);
--fd-colors-system-neutral-content-accent: var(--fd-colors-core-grey);
--fd-colors-system-neutral-border-default: var(--fd-colors-core-grey-l-2);
--fd-colors-system-neutral-background-subtle: var(--fd-colors-core-grey-l-4);
--fd-colors-system-neutral-background-default: var(--fd-colors-core-grey-l-2);
--fd-colors-system-important-content-accent: var(--fd-colors-core-red-d-1);
--fd-colors-system-important-border-default: var(--fd-colors-core-red);
--fd-colors-system-important-background-subtle: var(--fd-colors-core-red-l-5);
--fd-colors-system-important-background-default: var(--fd-colors-core-red);
--fd-colors-system-warning-content-accent: var(--fd-colors-core-orange-d-1);
--fd-colors-system-warning-border-default: var(--fd-colors-core-orange-l-2);
--fd-colors-system-warning-background-subtle: var(--fd-colors-core-orange-l-5);
--fd-colors-system-warning-background-default: var(--fd-colors-core-orange-l-2);
--fd-colors-system-alert-content-accent: var(--fd-colors-core-yellow-d-1);
--fd-colors-system-alert-border-default: var(--fd-colors-core-yellow-l-4);
--fd-colors-system-alert-background-subtle: var(--fd-colors-core-yellow-l-5);
--fd-colors-system-alert-background-default: var(--fd-colors-core-yellow-l-4);
--fd-colors-system-positive-content-accent: var(--fd-colors-core-green-d-1);
--fd-colors-system-positive-border-default: var(--fd-colors-core-green);
--fd-colors-system-positive-background-subtle: var(--fd-colors-core-green-l-5);
--fd-colors-system-positive-background-default: var(--fd-colors-core-green);
--fd-colors-system-info-content-accent: var(--fd-colors-core-blue-d-2);
--fd-colors-system-info-border-default: var(--fd-colors-core-blue-d-1);
--fd-colors-system-info-background-subtle: var(--fd-colors-core-blue-l-5);
--fd-colors-system-info-background-default: var(--fd-colors-core-blue-d-1);
--fd-colors-link-inverse-destructive-hover: var(--fd-colors-core-red);
--fd-colors-link-inverse-destructive-base: var(--fd-colors-core-red-l-2);
--fd-colors-link-inverse-default-hover: var(--fd-colors-core-blue-l-4);
--fd-colors-link-inverse-default-base: var(--fd-colors-core-white);
--fd-colors-link-destructive-hover: var(--fd-colors-core-red-d-2);
--fd-colors-link-destructive-base: var(--fd-colors-core-red);
--fd-colors-link-default-hover: var(--fd-colors-core-blue-d-2);
--fd-colors-link-default-base: var(--fd-colors-core-blue);
--fd-colors-border-inverse: var(--fd-colors-core-white);
--fd-colors-border-disabled: var(--fd-colors-core-black-tint-010);
--fd-colors-border-active: var(--fd-colors-core-blue);
--fd-colors-border-subtle: var(--fd-colors-core-navy-l-4);
--fd-colors-border-default: var(--fd-colors-core-grey-l-2);
--fd-colors-background-promotional: var(--fd-colors-core-navy-d-4);
--fd-colors-background-secondary: var(--fd-colors-core-navy);
--fd-colors-background-primary: var(--fd-colors-core-blue);
--fd-colors-background-transparent: var(--fd-colors-core-transparent-white);
--fd-colors-background-disabled: var(--fd-colors-core-grey-l-4);
--fd-colors-background-active: var(--fd-colors-core-blue);
--fd-colors-background-hover: var(--fd-colors-core-blue-l-5);
--fd-colors-background-accent: var(--fd-colors-core-black-tint-005);
--fd-colors-background-layer: var(--fd-colors-core-grey-l-5);
--fd-colors-background-surface: var(--fd-colors-core-white);
--fd-colors-background-base: var(--fd-colors-core-grey-l-4);
--fd-colors-content-loading-inverse: var(--fd-colors-core-white-tint-010);
--fd-colors-content-loading-default: var(--fd-colors-core-black-tint-005);
--fd-colors-content-on-dark: var(--fd-colors-core-white);
--fd-colors-content-on-light: var(--fd-colors-core-navy-d-3);
--fd-colors-content-disabled: var(--fd-colors-core-black-tint-020);
--fd-colors-content-subtle: var(--fd-colors-core-grey);
--fd-colors-content-default: var(--fd-colors-core-grey-d-4);
--fd-colors-content-strong: var(--fd-colors-core-navy-d-3);
--fd-colors-product-colors-secondary-d-4: var(--fd-colors-core-navy-d-4);
--fd-colors-product-colors-secondary-d-3: var(--fd-colors-core-navy-d-3);
--fd-colors-product-colors-secondary-d-2: var(--fd-colors-core-navy-d-2);
--fd-colors-product-colors-secondary-d-1: var(--fd-colors-core-navy-d-1);
--fd-colors-product-colors-secondary: var(--fd-colors-core-navy);
--fd-colors-product-colors-secondary-l-1: var(--fd-colors-core-navy-l-1);
--fd-colors-product-colors-secondary-l-2: var(--fd-colors-core-navy-l-2);
--fd-colors-product-colors-secondary-l-3: var(--fd-colors-core-navy-l-3);
--fd-colors-product-colors-secondary-l-4: var(--fd-colors-core-navy-l-4);
--fd-colors-product-colors-secondary-l-5: var(--fd-colors-core-navy-l-5);
--fd-colors-product-colors-primary-d-4: var(--fd-colors-core-blue-d-4);
--fd-colors-product-colors-primary-d-3: var(--fd-colors-core-blue-d-3);
--fd-colors-product-colors-primary-d-2: var(--fd-colors-core-blue-d-2);
--fd-colors-product-colors-primary-d-1: var(--fd-colors-core-blue-d-1);
--fd-colors-product-colors-primary: var(--fd-colors-core-blue);
--fd-colors-product-colors-primary-l-1: var(--fd-colors-core-blue-l-1);
--fd-colors-product-colors-primary-l-2: var(--fd-colors-core-blue-l-2);
--fd-colors-product-colors-primary-l-3: var(--fd-colors-core-blue-l-3);
--fd-colors-product-colors-primary-l-4: var(--fd-colors-core-blue-l-4);
--fd-colors-product-colors-primary-l-5: var(--fd-colors-core-blue-l-5);
--fd-colors-brand-gradient-color-stops-end: var(--fd-colors-core-blue-d-3);
--fd-colors-brand-gradient-color-stops-start: var(--fd-colors-core-blue-d-1);
--fd-colors-brand-tertiary-shade: var(--fd-colors-product-colors-tertiary-d-4);
--fd-colors-brand-tertiary-tint: var(--fd-colors-product-colors-tertiary-l-4);
--fd-colors-brand-tertiary-default: var(--fd-colors-product-colors-tertiary);
--fd-text-decoration-label-x-small: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-label-x-small: var(--fd-text-case-text-case-uppercase);
--fd-letter-spacings-label-x-small: var(--fd-letter-spacings-letter-spacing-030);
--fd-font-sizes-label-x-small: var(--fd-font-sizes-font-size-010);
--fd-line-heights-label-x-small: var(--fd-line-heights-line-height-030);
--fd-font-weights-label-x-small: var(--fd-font-weights-font-weight-020);
--fd-fonts-label-x-small: var(--fd-fonts-font-family-030);
--fd-text-decoration-label-small: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-label-small: var(--fd-text-case-text-case-uppercase);
--fd-letter-spacings-label-small: var(--fd-letter-spacings-letter-spacing-030);
--fd-font-sizes-label-small: var(--fd-font-sizes-font-size-020);
--fd-line-heights-label-small: var(--fd-line-heights-line-height-030);
--fd-font-weights-label-small: var(--fd-font-weights-font-weight-020);
--fd-fonts-label-small: var(--fd-fonts-font-family-030);
--fd-text-decoration-label-medium: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-label-medium: var(--fd-text-case-text-case-uppercase);
--fd-letter-spacings-label-medium: var(--fd-letter-spacings-letter-spacing-030);
--fd-font-sizes-label-medium: var(--fd-font-sizes-font-size-030);
--fd-line-heights-label-medium: var(--fd-line-heights-line-height-030);
--fd-font-weights-label-medium: var(--fd-font-weights-font-weight-020);
--fd-fonts-label-medium: var(--fd-fonts-font-family-030);
--fd-text-decoration-metadata-small: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-metadata-small: var(--fd-text-case-text-case-uppercase);
--fd-letter-spacings-metadata-small: var(--fd-letter-spacings-letter-spacing-030);
--fd-font-sizes-metadata-small: var(--fd-font-sizes-font-size-020);
--fd-line-heights-metadata-small: var(--fd-line-heights-line-height-030);
--fd-font-weights-metadata-small: var(--fd-font-weights-font-weight-020);
--fd-fonts-metadata-small: var(--fd-fonts-font-family-030);
--fd-text-decoration-metadata-medium: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-metadata-medium: var(--fd-text-case-text-case-uppercase);
--fd-letter-spacings-metadata-medium: var(--fd-letter-spacings-letter-spacing-030);
--fd-font-sizes-metadata-medium: var(--fd-font-sizes-font-size-030);
--fd-line-heights-metadata-medium: var(--fd-line-heights-line-height-030);
--fd-font-weights-metadata-medium: var(--fd-font-weights-font-weight-020);
--fd-fonts-metadata-medium: var(--fd-fonts-font-family-030);
--fd-text-decoration-button-x-small-strong: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-button-x-small-strong: var(--fd-text-case-text-case-none);
--fd-letter-spacings-button-x-small-strong: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-button-x-small-strong: var(--fd-font-sizes-font-size-020);
--fd-line-heights-button-x-small-strong: var(--fd-line-heights-line-height-030);
--fd-font-weights-button-x-small-strong: var(--fd-font-weights-font-weight-050);
--fd-fonts-button-x-small-strong: var(--fd-fonts-font-family-010);
--fd-text-decoration-button-x-small-regular: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-button-x-small-regular: var(--fd-text-case-text-case-none);
--fd-letter-spacings-button-x-small-regular: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-button-x-small-regular: var(--fd-font-sizes-font-size-020);
--fd-line-heights-button-x-small-regular: var(--fd-line-heights-line-height-030);
--fd-font-weights-button-x-small-regular: var(--fd-font-weights-font-weight-020);
--fd-fonts-button-x-small-regular: var(--fd-fonts-font-family-010);
--fd-text-decoration-button-small-strong: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-button-small-strong: var(--fd-text-case-text-case-none);
--fd-letter-spacings-button-small-strong: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-button-small-strong: var(--fd-font-sizes-font-size-030);
--fd-line-heights-button-small-strong: var(--fd-line-heights-line-height-030);
--fd-font-weights-button-small-strong: var(--fd-font-weights-font-weight-050);
--fd-fonts-button-small-strong: var(--fd-fonts-font-family-010);
--fd-text-decoration-button-small-regular: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-button-small-regular: var(--fd-text-case-text-case-none);
--fd-letter-spacings-button-small-regular: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-button-small-regular: var(--fd-font-sizes-font-size-030);
--fd-line-heights-button-small-regular: var(--fd-line-heights-line-height-030);
--fd-font-weights-button-small-regular: var(--fd-font-weights-font-weight-020);
--fd-fonts-button-small-regular: var(--fd-fonts-font-family-010);
--fd-text-decoration-button-medium-strong: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-button-medium-strong: var(--fd-text-case-text-case-none);
--fd-letter-spacings-button-medium-strong: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-button-medium-strong: var(--fd-font-sizes-font-size-040);
--fd-line-heights-button-medium-strong: var(--fd-line-heights-line-height-030);
--fd-font-weights-button-medium-strong: var(--fd-font-weights-font-weight-050);
--fd-fonts-button-medium-strong: var(--fd-fonts-font-family-010);
--fd-text-decoration-button-medium-regular: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-button-medium-regular: var(--fd-text-case-text-case-none);
--fd-letter-spacings-button-medium-regular: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-button-medium-regular: var(--fd-font-sizes-font-size-040);
--fd-line-heights-button-medium-regular: var(--fd-line-heights-line-height-030);
--fd-font-weights-button-medium-regular: var(--fd-font-weights-font-weight-020);
--fd-fonts-button-medium-regular: var(--fd-fonts-font-family-010);
--fd-text-decoration-button-large-strong: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-button-large-strong: var(--fd-text-case-text-case-none);
--fd-letter-spacings-button-large-strong: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-button-large-strong: var(--fd-font-sizes-font-size-050);
--fd-line-heights-button-large-strong: var(--fd-line-heights-line-height-030);
--fd-font-weights-button-large-strong: var(--fd-font-weights-font-weight-050);
--fd-fonts-button-large-strong: var(--fd-fonts-font-family-010);
--fd-text-decoration-button-large-regular: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-button-large-regular: var(--fd-text-case-text-case-none);
--fd-letter-spacings-button-large-regular: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-button-large-regular: var(--fd-font-sizes-font-size-050);
--fd-line-heights-button-large-regular: var(--fd-line-heights-line-height-030);
--fd-font-weights-button-large-regular: var(--fd-font-weights-font-weight-020);
--fd-fonts-button-large-regular: var(--fd-fonts-font-family-010);
--fd-text-decoration-body-x-small-strong-strikethrough: var(--fd-text-decoration-text-decoration-line-through);
--fd-text-case-body-x-small-strong-strikethrough: var(--fd-text-case-text-case-none);
--fd-letter-spacings-body-x-small-strong-strikethrough: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-body-x-small-strong-strikethrough: var(--fd-font-sizes-font-size-020);
--fd-line-heights-body-x-small-strong-strikethrough: var(--fd-line-heights-line-height-030);
--fd-font-weights-body-x-small-strong-strikethrough: var(--fd-font-weights-font-weight-050);
--fd-fonts-body-x-small-strong-strikethrough: var(--fd-fonts-font-family-010);
--fd-text-decoration-body-x-small-regular-strikethrough: var(--fd-text-decoration-text-decoration-line-through);
--fd-text-case-body-x-small-regular-strikethrough: var(--fd-text-case-text-case-none);
--fd-letter-spacings-body-x-small-regular-strikethrough: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-body-x-small-regular-strikethrough: var(--fd-font-sizes-font-size-020);
--fd-line-heights-body-x-small-regular-strikethrough: var(--fd-line-heights-line-height-030);
--fd-font-weights-body-x-small-regular-strikethrough: var(--fd-font-weights-font-weight-020);
--fd-fonts-body-x-small-regular-strikethrough: var(--fd-fonts-font-family-010);
--fd-text-decoration-body-x-small-strong: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-body-x-small-strong: var(--fd-text-case-text-case-none);
--fd-letter-spacings-body-x-small-strong: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-body-x-small-strong: var(--fd-font-sizes-font-size-020);
--fd-line-heights-body-x-small-strong: var(--fd-line-heights-line-height-030);
--fd-font-weights-body-x-small-strong: var(--fd-font-weights-font-weight-050);
--fd-fonts-body-x-small-strong: var(--fd-fonts-font-family-010);
--fd-text-decoration-body-x-small-regular: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-body-x-small-regular: var(--fd-text-case-text-case-none);
--fd-letter-spacings-body-x-small-regular: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-body-x-small-regular: var(--fd-font-sizes-font-size-020);
--fd-line-heights-body-x-small-regular: var(--fd-line-heights-line-height-030);
--fd-font-weights-body-x-small-regular: var(--fd-font-weights-font-weight-020);
--fd-fonts-body-x-small-regular: var(--fd-fonts-font-family-010);
--fd-text-decoration-body-small-strong-strikethrough: var(--fd-text-decoration-text-decoration-line-through);
--fd-text-case-body-small-strong-strikethrough: var(--fd-text-case-text-case-none);
--fd-letter-spacings-body-small-strong-strikethrough: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-body-small-strong-strikethrough: var(--fd-font-sizes-font-size-030);
--fd-line-heights-body-small-strong-strikethrough: var(--fd-line-heights-line-height-030);
--fd-font-weights-body-small-strong-strikethrough: var(--fd-font-weights-font-weight-050);
--fd-fonts-body-small-strong-strikethrough: var(--fd-fonts-font-family-010);
--fd-text-decoration-body-small-regular-strikethrough: var(--fd-text-decoration-text-decoration-line-through);
--fd-text-case-body-small-regular-strikethrough: var(--fd-text-case-text-case-none);
--fd-letter-spacings-body-small-regular-strikethrough: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-body-small-regular-strikethrough: var(--fd-font-sizes-font-size-030);
--fd-line-heights-body-small-regular-strikethrough: var(--fd-line-heights-line-height-030);
--fd-font-weights-body-small-regular-strikethrough: var(--fd-font-weights-font-weight-020);
--fd-fonts-body-small-regular-strikethrough: var(--fd-fonts-font-family-010);
--fd-text-decoration-body-small-strong: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-body-small-strong: var(--fd-text-case-text-case-none);
--fd-letter-spacings-body-small-strong: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-body-small-strong: var(--fd-font-sizes-font-size-030);
--fd-line-heights-body-small-strong: var(--fd-line-heights-line-height-030);
--fd-font-weights-body-small-strong: var(--fd-font-weights-font-weight-050);
--fd-fonts-body-small-strong: var(--fd-fonts-font-family-010);
--fd-text-decoration-body-small-regular: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-body-small-regular: var(--fd-text-case-text-case-none);
--fd-letter-spacings-body-small-regular: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-body-small-regular: var(--fd-font-sizes-font-size-030);
--fd-line-heights-body-small-regular: var(--fd-line-heights-line-height-030);
--fd-font-weights-body-small-regular: var(--fd-font-weights-font-weight-020);
--fd-fonts-body-small-regular: var(--fd-fonts-font-family-010);
--fd-text-decoration-body-medium-strong-strikethrough: var(--fd-text-decoration-text-decoration-line-through);
--fd-text-case-body-medium-strong-strikethrough: var(--fd-text-case-text-case-none);
--fd-letter-spacings-body-medium-strong-strikethrough: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-body-medium-strong-strikethrough: var(--fd-font-sizes-font-size-040);
--fd-line-heights-body-medium-strong-strikethrough: var(--fd-line-heights-line-height-030);
--fd-font-weights-body-medium-strong-strikethrough: var(--fd-font-weights-font-weight-050);
--fd-fonts-body-medium-strong-strikethrough: var(--fd-fonts-font-family-010);
--fd-text-decoration-body-medium-regular-strikethrough: var(--fd-text-decoration-text-decoration-line-through);
--fd-text-case-body-medium-regular-strikethrough: var(--fd-text-case-text-case-none);
--fd-letter-spacings-body-medium-regular-strikethrough: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-body-medium-regular-strikethrough: var(--fd-font-sizes-font-size-040);
--fd-line-heights-body-medium-regular-strikethrough: var(--fd-line-heights-line-height-030);
--fd-font-weights-body-medium-regular-strikethrough: var(--fd-font-weights-font-weight-020);
--fd-fonts-body-medium-regular-strikethrough: var(--fd-fonts-font-family-010);
--fd-text-decoration-body-medium-strong: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-body-medium-strong: var(--fd-text-case-text-case-none);
--fd-letter-spacings-body-medium-strong: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-body-medium-strong: var(--fd-font-sizes-font-size-040);
--fd-line-heights-body-medium-strong: var(--fd-line-heights-line-height-030);
--fd-font-weights-body-medium-strong: var(--fd-font-weights-font-weight-050);
--fd-fonts-body-medium-strong: var(--fd-fonts-font-family-010);
--fd-text-decoration-body-medium-regular: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-body-medium-regular: var(--fd-text-case-text-case-none);
--fd-letter-spacings-body-medium-regular: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-body-medium-regular: var(--fd-font-sizes-font-size-040);
--fd-line-heights-body-medium-regular: var(--fd-line-heights-line-height-030);
--fd-font-weights-body-medium-regular: var(--fd-font-weights-font-weight-020);
--fd-fonts-body-medium-regular: var(--fd-fonts-font-family-010);
--fd-text-decoration-body-large-strong-strikethrough: var(--fd-text-decoration-text-decoration-line-through);
--fd-text-case-body-large-strong-strikethrough: var(--fd-text-case-text-case-none);
--fd-letter-spacings-body-large-strong-strikethrough: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-body-large-strong-strikethrough: var(--fd-font-sizes-font-size-050);
--fd-line-heights-body-large-strong-strikethrough: var(--fd-line-heights-line-height-030);
--fd-font-weights-body-large-strong-strikethrough: var(--fd-font-weights-font-weight-050);
--fd-fonts-body-large-strong-strikethrough: var(--fd-fonts-font-family-010);
--fd-text-decoration-body-large-regular-strikethrough: var(--fd-text-decoration-text-decoration-line-through);
--fd-text-case-body-large-regular-strikethrough: var(--fd-text-case-text-case-none);
--fd-letter-spacings-body-large-regular-strikethrough: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-body-large-regular-strikethrough: var(--fd-font-sizes-font-size-050);
--fd-line-heights-body-large-regular-strikethrough: var(--fd-line-heights-line-height-030);
--fd-font-weights-body-large-regular-strikethrough: var(--fd-font-weights-font-weight-020);
--fd-fonts-body-large-regular-strikethrough: var(--fd-fonts-font-family-010);
--fd-text-decoration-body-large-strong: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-body-large-strong: var(--fd-text-case-text-case-none);
--fd-letter-spacings-body-large-strong: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-body-large-strong: var(--fd-font-sizes-font-size-050);
--fd-line-heights-body-large-strong: var(--fd-line-heights-line-height-030);
--fd-font-weights-body-large-strong: var(--fd-font-weights-font-weight-050);
--fd-fonts-body-large-strong: var(--fd-fonts-font-family-010);
--fd-text-decoration-body-large-regular: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-body-large-regular: var(--fd-text-case-text-case-none);
--fd-letter-spacings-body-large-regular: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-body-large-regular: var(--fd-font-sizes-font-size-050);
--fd-line-heights-body-large-regular: var(--fd-line-heights-line-height-030);
--fd-font-weights-body-large-regular: var(--fd-font-weights-font-weight-020);
--fd-fonts-body-large-regular: var(--fd-fonts-font-family-010);
--fd-text-decoration-body-x-large-strong-strikethrough: var(--fd-text-decoration-text-decoration-line-through);
--fd-text-case-body-x-large-strong-strikethrough: var(--fd-text-case-text-case-none);
--fd-letter-spacings-body-x-large-strong-strikethrough: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-body-x-large-strong-strikethrough: var(--fd-font-sizes-font-size-060);
--fd-line-heights-body-x-large-strong-strikethrough: var(--fd-line-heights-line-height-030);
--fd-font-weights-body-x-large-strong-strikethrough: var(--fd-font-weights-font-weight-050);
--fd-fonts-body-x-large-strong-strikethrough: var(--fd-fonts-font-family-010);
--fd-text-decoration-body-x-large-regular-strikethrough: var(--fd-text-decoration-text-decoration-line-through);
--fd-text-case-body-x-large-regular-strikethrough: var(--fd-text-case-text-case-none);
--fd-letter-spacings-body-x-large-regular-strikethrough: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-body-x-large-regular-strikethrough: var(--fd-font-sizes-font-size-060);
--fd-line-heights-body-x-large-regular-strikethrough: var(--fd-line-heights-line-height-030);
--fd-font-weights-body-x-large-regular-strikethrough: var(--fd-font-weights-font-weight-020);
--fd-fonts-body-x-large-regular-strikethrough: var(--fd-fonts-font-family-010);
--fd-text-decoration-body-x-large-strong: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-body-x-large-strong: var(--fd-text-case-text-case-none);
--fd-letter-spacings-body-x-large-strong: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-body-x-large-strong: var(--fd-font-sizes-font-size-060);
--fd-line-heights-body-x-large-strong: var(--fd-line-heights-line-height-030);
--fd-font-weights-body-x-large-strong: var(--fd-font-weights-font-weight-050);
--fd-fonts-body-x-large-strong: var(--fd-fonts-font-family-010);
--fd-text-decoration-body-x-large-regular: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-body-x-large-regular: var(--fd-text-case-text-case-none);
--fd-letter-spacings-body-x-large-regular: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-body-x-large-regular: var(--fd-font-sizes-font-size-060);
--fd-line-heights-body-x-large-regular: var(--fd-line-heights-line-height-030);
--fd-font-weights-body-x-large-regular: var(--fd-font-weights-font-weight-020);
--fd-fonts-body-x-large-regular: var(--fd-fonts-font-family-010);
--fd-text-decoration-heading-x-small: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-heading-x-small: var(--fd-text-case-text-case-none);
--fd-letter-spacings-heading-x-small: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-heading-x-small: var(--fd-font-sizes-font-size-030);
--fd-line-heights-heading-x-small: var(--fd-line-heights-line-height-030);
--fd-font-weights-heading-x-small: var(--fd-font-weights-font-weight-050);
--fd-fonts-heading-x-small: var(--fd-fonts-font-family-010);
--fd-text-decoration-heading-small: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-heading-small: var(--fd-text-case-text-case-none);
--fd-letter-spacings-heading-small: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-heading-small: var(--fd-font-sizes-font-size-040);
--fd-line-heights-heading-small: var(--fd-line-heights-line-height-030);
--fd-font-weights-heading-small: var(--fd-font-weights-font-weight-050);
--fd-fonts-heading-small: var(--fd-fonts-font-family-010);
--fd-text-decoration-heading-medium: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-heading-medium: var(--fd-text-case-text-case-none);
--fd-letter-spacings-heading-medium: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-heading-medium: var(--fd-font-sizes-font-size-050);
--fd-line-heights-heading-medium: var(--fd-line-heights-line-height-030);
--fd-font-weights-heading-medium: var(--fd-font-weights-font-weight-050);
--fd-fonts-heading-medium: var(--fd-fonts-font-family-010);
--fd-text-decoration-heading-large: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-heading-large: var(--fd-text-case-text-case-none);
--fd-letter-spacings-heading-large: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-heading-large: var(--fd-font-sizes-font-size-060);
--fd-line-heights-heading-large: var(--fd-line-heights-line-height-030);
--fd-font-weights-heading-large: var(--fd-font-weights-font-weight-050);
--fd-fonts-heading-large: var(--fd-fonts-font-family-010);
--fd-text-decoration-heading-x-large: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-heading-x-large: var(--fd-text-case-text-case-none);
--fd-letter-spacings-heading-x-large: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-heading-x-large: var(--fd-font-sizes-font-size-070);
--fd-line-heights-heading-x-large: var(--fd-line-heights-line-height-030);
--fd-font-weights-heading-x-large: var(--fd-font-weights-font-weight-050);
--fd-fonts-heading-x-large: var(--fd-fonts-font-family-010);
--fd-text-decoration-heading-xx-large: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-heading-xx-large: var(--fd-text-case-text-case-none);
--fd-letter-spacings-heading-xx-large: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-heading-xx-large: var(--fd-font-sizes-font-size-080);
--fd-line-heights-heading-xx-large: var(--fd-line-heights-line-height-030);
--fd-font-weights-heading-xx-large: var(--fd-font-weights-font-weight-050);
--fd-fonts-heading-xx-large: var(--fd-fonts-font-family-010);
--fd-text-decoration-jumbo-small: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-jumbo-small: var(--fd-text-case-text-case-none);
--fd-letter-spacings-jumbo-small: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-jumbo-small: var(--fd-font-sizes-font-size-090);
--fd-line-heights-jumbo-small: var(--fd-line-heights-line-height-030);
--fd-font-weights-jumbo-small: var(--fd-font-weights-font-weight-050);
--fd-fonts-jumbo-small: var(--fd-fonts-font-family-010);
--fd-text-decoration-jumbo-medium: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-jumbo-medium: var(--fd-text-case-text-case-none);
--fd-letter-spacings-jumbo-medium: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-jumbo-medium: var(--fd-font-sizes-font-size-100);
--fd-line-heights-jumbo-medium: var(--fd-line-heights-line-height-030);
--fd-font-weights-jumbo-medium: var(--fd-font-weights-font-weight-050);
--fd-fonts-jumbo-medium: var(--fd-fonts-font-family-010);
--fd-text-decoration-jumbo-large: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-jumbo-large: var(--fd-text-case-text-case-none);
--fd-letter-spacings-jumbo-large: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-jumbo-large: var(--fd-font-sizes-font-size-110);
--fd-line-heights-jumbo-large: var(--fd-line-heights-line-height-030);
--fd-font-weights-jumbo-large: var(--fd-font-weights-font-weight-050);
--fd-fonts-jumbo-large: var(--fd-fonts-font-family-010);
--fd-text-decoration-jumbo-x-large: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-jumbo-x-large: var(--fd-text-case-text-case-none);
--fd-letter-spacings-jumbo-x-large: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-jumbo-x-large: var(--fd-font-sizes-font-size-130);
--fd-line-heights-jumbo-x-large: var(--fd-line-heights-line-height-020);
--fd-font-weights-jumbo-x-large: var(--fd-font-weights-font-weight-050);
--fd-fonts-jumbo-x-large: var(--fd-fonts-font-family-010);
--fd-text-decoration-jumbo-xx-large: var(--fd-text-decoration-text-decoration-none);
--fd-text-case-jumbo-xx-large: var(--fd-text-case-text-case-none);
--fd-letter-spacings-jumbo-xx-large: var(--fd-letter-spacings-letter-spacing-010);
--fd-font-sizes-jumbo-xx-large: var(--fd-font-sizes-font-size-140);
--fd-line-heights-jumbo-xx-large: var(--fd-line-heights-line-height-020);
--fd-font-weights-jumbo-xx-large: var(--fd-font-weights-font-weight-050);
--fd-fonts-jumbo-xx-large: var(--fd-fonts-font-family-010);
--fd-radii-border-radius-default: var(--fd-radii-border-radius-020);
--fd-border-widths-border-width-default: var(--fd-border-widths-border-width-010);
--fd-shadows-elevations-all-around-high: 0 0 16px 2px var(--fd-colors-core-black-tint-030);
--fd-shadows-elevations-all-around-mid: 0 0 8px 2px var(--fd-colors-core-black-tint-020);
--fd-shadows-elevations-all-around-low: 0 0 4px 2px var(--fd-colors-core-black-tint-010);
--fd-shadows-elevations-bottom-high: 0 8px 16px 0 var(--fd-colors-core-black-tint-030);
--fd-shadows-elevations-bottom-mid: 0 4px 8px 0 var(--fd-colors-core-black-tint-020);
--fd-shadows-elevations-bottom-low: 0 2px 4px 0 var(--fd-colors-core-black-tint-010);
--fd-shadows-elevations-top-high: 0 -8px 16px 0 var(--fd-colors-core-black-tint-030);
--fd-shadows-elevations-top-mid: 0 -4px 8px 0 var(--fd-colors-core-black-tint-020);
--fd-shadows-elevations-top-low: 0 -2px 4px 0 var(--fd-colors-core-black-tint-010);
--fd-space-space-40: calc(var(--fd-space-space-base) * 40);
--fd-space-space-30: calc(var(--fd-space-space-base) * 30);
--fd-space-space-20: calc(var(--fd-space-space-base) * 20);
--fd-space-space-16: calc(var(--fd-space-space-base) * 16);
--fd-space-space-12: calc(var(--fd-space-space-base) * 12);
--fd-space-space-10: calc(var(--fd-space-space-base) * 10);
--fd-space-space-8: calc(var(--fd-space-space-base) * 8);
--fd-space-space-6: calc(var(--fd-space-space-base) * 6);
--fd-space-space-5: calc(var(--fd-space-space-base) * 5);
--fd-space-space-4: calc(var(--fd-space-space-base) * 4);
--fd-space-space-3: calc(var(--fd-space-space-base) * 3);
--fd-space-space-2: calc(var(--fd-space-space-base) * 2);
--fd-space-space-1: calc(var(--fd-space-space-base) * 1);
--fd-space-space-05: calc(var(--fd-space-space-base) * 0.5);
--fd-space-space-025: calc(var(--fd-space-space-base) * 0.25);
--fd-space-space-0: calc(var(--fd-space-space-base) * 0);
--fd-colors-product-gradients-faceoff: linear-gradient(125deg, var(--fd-colors-core-teal-l-2) 0%, var(--fd-colors-core-blue) 100%);
--fd-colors-product-gradients-casino: linear-gradient(125deg, var(--fd-colors-core-purple-d-3) 0%, var(--fd-colors-core-blue-d-1) 100%);
--fd-colors-product-gradients-sports: linear-gradient(125deg, var(--fd-colors-core-blue-d-1) 0%, var(--fd-colors-core-blue-d-3) 100%);
--fd-colors-component-pill-inverse-background-base: var(--fd-colors-background-transparent);
--fd-colors-component-data-input-icon-disabled: var(--fd-colors-content-disabled);
--fd-colors-component-data-input-icon-error: var(--fd-colors-system-important-content-accent);
--fd-colors-component-data-input-icon-active: var(--fd-colors-system-info-content-accent);
--fd-colors-component-data-input-icon-base: var(--fd-colors-content-subtle);
--fd-colors-component-data-input-password-meter-great: var(--fd-colors-system-positive-background-default);
--fd-colors-component-data-input-password-meter-good: var(--fd-colors-system-info-background-default);
--fd-colors-component-data-input-password-meter-fair: var(--fd-colors-system-warning-background-default);
--fd-colors-component-data-input-password-meter-weak: var(--fd-colors-system-important-background-default);
--fd-colors-component-data-input-password-meter-empty: var(--fd-colors-system-neutral-background-default);
--fd-colors-component-data-input-label-disabled: var(--fd-colors-content-disabled);
--fd-colors-component-data-input-label-error: var(--fd-colors-system-important-content-accent);
--fd-colors-component-data-input-label-active: var(--fd-colors-system-info-content-accent);
--fd-colors-component-data-input-label-base: var(--fd-colors-content-strong);
--fd-colors-component-data-input-content-disabled: var(--fd-colors-content-disabled);
--fd-colors-component-data-input-content-error: var(--fd-colors-system-important-content-accent);
--fd-colors-component-data-input-content-hover: var(--fd-colors-system-info-content-accent);
--fd-colors-component-data-input-content-subtle: var(--fd-colors-content-subtle);
--fd-colors-component-data-input-content-base: var(--fd-colors-content-default);
--fd-colors-component-data-input-border-disabled: var(--fd-colors-border-disabled);
--fd-colors-component-data-input-border-error: var(--fd-colors-system-important-border-default);
--fd-colors-component-data-input-border-active: var(--fd-colors-system-info-border-default);
--fd-colors-component-data-input-border-base: var(--fd-colors-border-default);
--fd-colors-component-data-input-background-disabled: var(--fd-colors-background-disabled);
--fd-colors-component-data-input-background-error: var(--fd-colors-system-important-background-subtle);
--fd-colors-component-data-input-background-hover: var(--fd-colors-background-hover);
--fd-colors-component-data-input-background-layer: var(--fd-colors-background-layer);
--fd-colors-component-data-input-background-base: var(--fd-colors-background-surface);
--fd-colors-component-selection-control-foreground-error: var(--fd-colors-content-on-dark);
--fd-colors-component-selection-control-foreground-success: var(--fd-colors-content-on-dark);
--fd-colors-component-selection-control-foreground-disabled: var(--fd-colors-content-disabled);
--fd-colors-component-selection-control-foreground-selected-active: var(--fd-colors-content-on-dark);
--fd-colors-component-selection-control-foreground-selected-hover: var(--fd-colors-content-on-dark);
--fd-colors-component-selection-control-foreground-selected: var(--fd-colors-content-on-dark);
--fd-colors-component-selection-control-border-disabled: var(--fd-colors-border-disabled);
--fd-colors-component-selection-control-border-base: var(--fd-colors-border-default);
--fd-colors-component-selection-control-background-disabled: var(--fd-colors-background-disabled);
--fd-colors-component-selection-control-background-base: var(--fd-colors-background-surface);
--fd-colors-component-button-button-link-border-disabled: var(--fd-colors-border-disabled);
--fd-colors-component-button-button-link-content-disabled: var(--fd-colors-content-disabled);
--fd-colors-component-button-destructive-border-disabled: var(--fd-colors-border-disabled);
--fd-colors-component-button-destructive-background-disabled: var(--fd-colors-background-disabled);
--fd-colors-component-button-destructive-content-disabled: var(--fd-colors-content-disabled);
--fd-colors-component-button-tertiary-border-disabled: var(--fd-colors-border-disabled);
--fd-colors-component-button-tertiary-content-disabled: var(--fd-colors-content-disabled);
--fd-colors-component-button-secondary-border-disabled: var(--fd-colors-border-disabled);
--fd-colors-component-button-secondary-background-disabled: var(--fd-colors-background-disabled);
--fd-colors-component-button-secondary-content-disabled: var(--fd-colors-content-disabled);
--fd-colors-component-button-primary-border-disabled: var(--fd-colors-border-disabled);
--fd-colors-component-button-primary-background-disabled: var(--fd-colors-background-disabled);
--fd-colors-component-button-primary-content-disabled: var(--fd-colors-content-disabled);
--fd-colors-system-verification-link-on-subtle: var(--fd-colors-link-default-base);
--fd-colors-system-verification-link-on-default: var(--fd-colors-content-on-dark);
--fd-colors-system-verification-content-on-subtle: var(--fd-colors-content-on-light);
--fd-colors-system-verification-content-on-default: var(--fd-colors-content-on-dark);
--fd-colors-system-neutral-link-on-subtle: var(--fd-colors-link-default-base);
--fd-colors-system-neutral-link-on-default: var(--fd-colors-content-on-light);
--fd-colors-system-neutral-content-on-subtle: var(--fd-colors-content-on-light);
--fd-colors-system-neutral-content-on-default: var(--fd-colors-content-on-light);
--fd-colors-system-important-link-on-subtle: var(--fd-colors-link-default-base);
--fd-colors-system-important-link-on-default: var(--fd-colors-content-on-dark);
--fd-colors-system-important-content-on-subtle: var(--fd-colors-content-on-light);
--fd-colors-system-important-content-on-default: var(--fd-colors-content-on-dark);
--fd-colors-system-warning-link-on-subtle: var(--fd-colors-link-default-base);
--fd-colors-system-warning-link-on-default: var(--fd-colors-content-on-light);
--fd-colors-system-warning-content-on-subtle: var(--fd-colors-content-on-light);
--fd-colors-system-warning-content-on-default: var(--fd-colors-content-on-light);
--fd-colors-system-alert-link-on-subtle: var(--fd-colors-link-default-base);
--fd-colors-system-alert-link-on-default: var(--fd-colors-content-on-light);
--fd-colors-system-alert-content-on-subtle: var(--fd-colors-content-on-light);
--fd-colors-system-alert-content-on-default: var(--fd-colors-content-on-light);
--fd-colors-system-positive-link-on-subtle: var(--fd-colors-link-default-base);
--fd-colors-system-positive-link-on-default: var(--fd-colors-content-on-dark);
--fd-colors-system-positive-content-on-subtle: var(--fd-colors-content-on-light);
--fd-colors-system-positive-content-on-default: var(--fd-colors-content-on-dark);
--fd-colors-system-info-link-on-subtle: var(--fd-colors-link-default-base);
--fd-colors-system-info-link-on-default: var(--fd-colors-content-on-dark);
--fd-colors-system-info-content-on-subtle: var(--fd-colors-content-on-light);
--fd-colors-system-info-content-on-default: var(--fd-colors-content-on-dark);
--fd-colors-background-gradient-color-stops-end: var(--fd-colors-background-surface);
--fd-colors-background-gradient-color-stops-start: var(--fd-colors-background-transparent);
--fd-colors-content-link-active: var(--fd-colors-link-default-hover);
--fd-colors-content-link: var(--fd-colors-link-default-base);
--fd-colors-brand-gradient-default: linear-gradient(125deg, var(--fd-colors-brand-gradient-color-stops-start) 0%, var(--fd-colors-brand-gradient-color-stops-end) 100%);
--fd-colors-brand-secondary-shade: var(--fd-colors-product-colors-secondary-d-4);
--fd-colors-brand-secondary-tint: var(--fd-colors-product-colors-secondary-l-4);
--fd-colors-brand-secondary-default: var(--fd-colors-product-colors-secondary);
--fd-colors-brand-primary-shade: var(--fd-colors-product-colors-primary-d-2);
--fd-colors-brand-primary-tint: var(--fd-colors-product-colors-primary-l-4);
--fd-colors-brand-primary-default: var(--fd-colors-product-colors-primary);
--fd-colors-border-brand: var(--fd-colors-brand-primary-default);
--fd-colors-background-gradient-surface-fade-bottom: linear-gradient(180deg, var(--fd-colors-background-gradient-color-stops-start) 0%, var(--fd-colors-background-gradient-color-stops-end) 100%);
--fd-colors-background-gradient-surface-fade-end: linear-gradient(90deg, var(--fd-colors-background-gradient-color-stops-start) 0%, var(--fd-colors-background-gradient-color-stops-end) 100%);
--fd-colors-background-brand: var(--fd-colors-brand-primary-default);
--fd-colors-content-brand-secondary: var(--fd-colors-brand-secondary-default);
--fd-colors-content-brand-primary: var(--fd-colors-brand-primary-default);
}
/**
* Do not edit directly
* Generated on Fri, 18 Oct 2024 14:02:53 GMT
*/
*[data-mode="dark"] {
--fd-text-theme-name: Fanduel Dark;
--fd-colors-component-pill-inverse-background-disabled: var(--fd-colors-core-grey-d-3);
--fd-colors-component-pill-inverse-background-active: var(--fd-colors-core-blue-l-1);
--fd-colors-component-pill-inverse-background-selected: var(--fd-colors-core-blue-l-2);
--fd-colors-component-pill-inverse-background-hover: var(--fd-colors-core-white-tint-030);
--fd-colors-component-pill-inverse-content-disabled: var(--fd-colors-core-black);
--fd-colors-component-pill-inverse-content-active: var(--fd-colors-core-navy-d-4);
--fd-colors-component-pill-inverse-content-selected: var(--fd-colors-core-navy-d-4);
--fd-colors-component-pill-inverse-content-hover: var(--fd-colors-core-white);
--fd-colors-component-pill-primary-background-disabled: var(--fd-colors-core-grey-d-3);
--fd-colors-component-pill-primary-background-active: var(--fd-colors-core-blue-l-1);
--fd-colors-component-pill-primary-background-selected: var(--fd-colors-core-blue-l-2);
--fd-colors-component-pill-primary-background-hover: var(--fd-colors-core-white-tint-030);
--fd-colors-component-pill-primary-background-base: var(--fd-colors-core-white-tint-010);
--fd-colors-component-pill-primary-content-disabled: var(--fd-colors-core-black);
--fd-colors-component-pill-primary-content-active: var(--fd-colors-core-navy-d-4);
--fd-colors-component-pill-primary-content-selected: var(--fd-colors-core-navy-d-4);
--fd-colors-component-pill-primary-content-hover: var(--fd-colors-core-white);
--fd-colors-component-pill-primary-content-base: var(--fd-colors-core-white);
--fd-colors-component-selection-control-foreground-unselected: var(--fd-colors-core-transparent-black);
--fd-colors-component-selection-control-foreground-active: var(--fd-colors-core-transparent-black);
--fd-colors-component-selection-control-foreground-hover: var(--fd-colors-core-transparent-black);
--fd-colors-component-selection-control-foreground-base: var(--fd-colors-core-transparent-black);
--fd-colors-component-selection-control-border-error: var(--fd-colors-core-red-l-1);
--fd-colors-component-selection-control-border-success: var(--fd-colors-core-green-l-1);
--fd-colors-component-selection-control-border-unselected: var(--fd-colors-core-grey-d-1);
--fd-colors-component-selection-control-border-selected-active: var(--fd-colors-core-blue-l-3);
--fd-colors-component-selection-control-border-selected-hover: var(--fd-colors-core-blue-l-3);
--fd-colors-component-selection-control-border-selected: var(--fd-colors-core-blue-l-2);
--fd-colors-component-selection-control-border-active: var(--fd-colors-core-blue-l-2);
--fd-colors-component-selection-control-border-hover: var(--fd-colors-core-blue-l-2);
--fd-colors-component-selection-control-background-error: var(--fd-colors-core-red-l-2);
--fd-colors-component-selection-control-background-success: var(--fd-colors-core-green-l-2);
--fd-colors-component-selection-control-background-unselected: var(--fd-colors-core-grey-d-1);
--fd-colors-component-selection-control-background-selected-active: var(--fd-colors-core-blue-l-3);
--fd-colors-component-selection-control-background-selected-hover: var(--fd-colors-core-blue-l-3);
--fd-colors-component-selection-control-background-selected: var(--fd-colors-core-blue-l-2);
--fd-colors-component-selection-control-background-active: var(--fd-colors-core-blue-l-1);
--fd-colors-component-selection-control-background-hover: var(--fd-colors-core-blue-d-4);
--fd-colors-component-button-button-link-border-active: var(--fd-colors-core-transparent-black);
--fd-colors-component-button-button-link-border-hover: var(--fd-colors-core-transparent-black);
--fd-colors-component-button-button-link-border-base: var(--fd-colors-core-transparent-black);
--fd-colors-component-button-button-link-background-disabled: var(--fd-colors-core-transparent-black);
--fd-colors-component-button-button-link-background-hover: var(--fd-colors-core-blue-d-4);
--fd-colors-component-button-button-link-background-base: var(--fd-colors-core-transparent-black);
--fd-colors-component-button-button-link-content-disabled: var(--fd-colors-core-grey-d-2);
--fd-colors-component-button-button-link-content-hover: var(--fd-colors-core-blue);
--fd-colors-component-button-button-link-content-base: var(--fd-colors-core-blue-l-2);
--fd-colors-component-button-destructive-border-active: var(--fd-colors-core-red-d-3);
--fd-colors-component-button-destructive-border-hover: var(--fd-colors-core-red-d-2);
--fd-colors-component-button-destructive-background-active: var(--fd-colors-core-red-d-3);
--fd-colors-component-button-destructive-background-hover: var(--fd-colors-core-red-d-2);
--fd-colors-component-button-transparent-border-active: var(--fd-colors-core-transparent-black);
--fd-colors-component-button-transparent-background-disabled: var(--fd-colors-core-transparent-black);
--fd-colors-component-button-transparent-background-active: var(--fd-colors-core-blue-d-1);
--fd-colors-component-button-transparent-background-base: var(--fd-colors-core-transparent-black);
--fd-colors-component-button-tertiary-border-active: var(--fd-colors-core-blue-d-1);
--fd-colors-component-button-tertiary-border-hover: var(--fd-colors-core-blue-l-1);
--fd-colors-component-button-tertiary-border-base: var(--fd-colors-core-blue-l-2);
--fd-colors-component-button-tertiary-background-disabled: var(--fd-colors-core-transparent-black);
--fd-colors-component-button-tertiary-background-active: var(--fd-colors-core-blue-d-1);
--fd-colors-component-button-tertiary-background-hover: var(--fd-colors-core-blue-d-4);
--fd-colors-component-button-tertiary-background-base: var(--fd-colors-core-transparent-black);
--fd-colors-component-button-tertiary-content-hover: var(--fd-colors-core-blue-l-1);
--fd-colors-component-button-tertiary-content-base: var(--fd-colors-core-blue-l-2);
--fd-colors-system-verification-content-accent: var(--fd-colors-core-purple-l-3);
--fd-colors-system-verification-border-default: var(--fd-colors-core-purple-d-3);
--fd-colors-system-verification-background-subtle: var(--fd-colors-core-purple-d-4);
--fd-colors-system-verification-background-default: var(--fd-colors-core-purple-d-3);
--fd-colors-system-neutral-content-accent: var(--fd-colors-core-grey-l-3);
--fd-colors-system-neutral-border-default: var(--fd-colors-core-grey);
--fd-colors-system-neutral-background-subtle: var(--fd-colors-core-grey-d-3);
--fd-colors-system-neutral-background-default: var(--fd-colors-core-grey);
--fd-colors-system-important-content-accent: var(--fd-colors-core-red-l-3);
--fd-colors-system-important-border-default: var(--fd-colors-core-red-d-2);
--fd-colors-system-important-background-subtle: var(--fd-colors-core-red-d-4);
--fd-colors-system-important-background-default: var(--fd-colors-core-red-d-2);
--fd-colors-system-warning-content-accent: var(--fd-colors-core-orange-l-3);
--fd-colors-system-warning-border-default: var(--fd-colors-core-orange-d-1);
--fd-colors-system-warning-background-subtle: var(--fd-colors-core-orange-d-3);
--fd-colors-system-warning-background-default: var(--fd-colors-core-orange-d-1);
--fd-colors-system-alert-content-accent: var(--fd-colors-core-yellow-l-4);
--fd-colors-system-alert-border-default: var(--fd-colors-core-yellow-d-1);
--fd-colors-system-alert-background-subtle: var(--fd-colors-core-yellow-d-3);
--fd-colors-system-alert-background-default: var(--fd-colors-core-yellow-d-1);
--fd-colors-system-positive-content-accent: var(--fd-colors-core-green-l-3);
--fd-colors-system-positive-border-default: var(--fd-colors-core-green-d-2);
--fd-colors-system-positive-background-subtle: var(--fd-colors-core-green-d-4);
--fd-colors-system-positive-background-default: var(--fd-colors-core-green-d-2);
--fd-colors-system-info-content-accent: var(--fd-colors-core-blue-l-3);
--fd-colors-system-info-border-default: var(--fd-colors-core-blue-d-2);
--fd-colors-system-info-background-subtle: var(--fd-colors-core-blue-d-4);
--fd-colors-system-info-background-default: var(--fd-colors-core-blue-d-2);
--fd-colors-link-destructive-hover: var(--fd-colors-core-red);
--fd-colors-link-destructive-base: var(--fd-colors-core-red-l-2);
--fd-colors-link-default-hover: var(--fd-colors-core-blue);
--fd-colors-link-default-base: var(--fd-colors-core-blue-l-2);
--fd-colors-border-inverse: var(--fd-colors-core-grey-l-4);
--fd-colors-border-disabled: var(--fd-colors-core-white-tint-010);
--fd-colors-border-active: var(--fd-colors-core-blue-l-2);
--fd-colors-border-subtle: var(--fd-colors-core-grey-d-1);
--fd-colors-border-default: var(--fd-colors-core-grey);
--fd-colors-background-secondary: var(--fd-colors-core-black);
--fd-colors-background-transparent: var(--fd-colors-core-transparent-black);
--fd-colors-background-disabled: var(--fd-colors-core-grey-d-2);
--fd-colors-background-hover: var(--fd-colors-core-grey-d-2);
--fd-colors-background-accent: var(--fd-colors-core-white-tint-005);
--fd-colors-background-layer: var(--fd-colors-core-grey-d-3);
--fd-colors-background-surface: var(--fd-colors-core-grey-d-4);
--fd-colors-background-base: var(--fd-colors-core-black);
--fd-colors-content-loading-inverse: var(--fd-colors-core-black-tint-005);
--fd-colors-content-loading-default: var(--fd-colors-core-white-tint-005);
--fd-colors-content-on-light: var(--fd-colors-core-navy-d-4);
--fd-colors-content-disabled: var(--fd-colors-core-white-tint-020);
--fd-colors-content-subtle: var(--fd-colors-core-grey-l-1);
--fd-colors-content-default: var(--fd-colors-core-grey-l-3);
--fd-colors-content-strong: var(--fd-colors-core-white);
--fd-colors-component-pill-inverse-background-base: var(--fd-colors-background-transparent);
--fd-colors-component-data-input-icon-disabled: var(--fd-colors-content-disabled);
--fd-colors-component-data-input-icon-error: var(--fd-colors-system-important-content-accent);
--fd-colors-component-data-input-icon-active: var(--fd-colors-system-info-content-accent);
--fd-colors-component-data-input-icon-base: var(--fd-colors-content-subtle);
--fd-colors-component-data-input-password-meter-great: var(--fd-colors-system-positive-background-default);
--fd-colors-component-data-input-password-meter-good: var(--fd-colors-system-info-background-default);
--fd-colors-component-data-input-password-meter-fair: var(--fd-colors-system-warning-background-default);
--fd-colors-component-data-input-password-meter-weak: var(--fd-colors-system-important-background-default);
--fd-colors-component-data-input-password-meter-empty: var(--fd-colors-system-neutral-background-default);
--fd-colors-component-data-input-label-disabled: var(--fd-colors-content-disabled);
--fd-colors-component-data-input-label-error: var(--fd-colors-system-important-content-accent);
--fd-colors-component-data-input-label-active: var(--fd-colors-system-info-content-accent);
--fd-colors-component-data-input-label-base: var(--fd-colors-content-strong);
--fd-colors-component-data-input-content-disabled: var(--fd-colors-content-disabled);
--fd-colors-component-data-input-content-error: var(--fd-colors-system-important-content-accent);
--fd-colors-component-data-input-content-hover: var(--fd-colors-system-info-content-accent);
--fd-colors-component-data-input-content-subtle: var(--fd-colors-content-subtle);
--fd-colors-component-data-input-content-base: var(--fd-colors-content-default);
--fd-colors-component-data-input-border-disabled: var(--fd-colors-border-disabled);
--fd-colors-component-data-input-border-error: var(--fd-colors-system-important-border-default);
--fd-colors-component-data-input-border-active: var(--fd-colors-system-info-border-default);
--fd-colors-component-data-input-border-base: var(--fd-colors-border-default);
--fd-colors-component-data-input-background-disabled: var(--fd-colors-background-disabled);
--fd-colors-component-data-input-background-error: var(--fd-colors-system-important-background-subtle);
--fd-colors-component-data-input-background-hover: var(--fd-colors-background-hover);
--fd-colors-component-data-input-background-layer: var(--fd-colors-background-layer);
--fd-colors-component-data-input-background-base: var(--fd-colors-background-surface);
--fd-colors-component-selection-control-foreground-error: var(--fd-colors-content-on-light);
--fd-colors-component-selection-control-foreground-success: var(--fd-colors-content-on-light);
--fd-colors-component-selection-control-foreground-disabled: var(--fd-colors-content-disabled);
--fd-colors-component-selection-control-foreground-selected-active: var(--fd-colors-content-on-light);
--fd-colors-component-selection-control-foreground-selected-hover: var(--fd-colors-content-on-light);
--fd-colors-component-selection-control-foreground-selected: var(--fd-colors-content-on-light);
--fd-colors-component-selection-control-border-disabled: var(--fd-colors-border-disabled);
--fd-colors-component-selection-control-border-base: var(--fd-colors-border-default);
--fd-colors-component-selection-control-background-disabled: var(--fd-colors-background-disabled);
--fd-colors-component-selection-control-background-base: var(--fd-colors-background-surface);
--fd-colors-component-button-button-link-border-disabled: var(--fd-colors-border-disabled);
--fd-colors-component-button-destructive-border-disabled: var(--fd-colors-border-disabled);
--fd-colors-component-button-destructive-background-disabled: var(--fd-colors-background-disabled);
--fd-colors-component-button-destructive-content-disabled: var(--fd-colors-content-disabled);
--fd-colors-component-button-transparent-border-disabled: var(--fd-colors-border-disabled);
--fd-colors-component-button-transparent-content-disabled: var(--fd-colors-content-disabled);
--fd-colors-component-button-tertiary-border-disabled: var(--fd-colors-border-disabled);
--fd-colors-component-button-tertiary-content-disabled: var(--fd-colors-content-disabled);
--fd-colors-component-button-secondary-border-disabled: var(--fd-colors-border-disabled);
--fd-colors-component-button-secondary-background-disabled: var(--fd-colors-background-disabled);
--fd-colors-component-button-secondary-content-disabled: var(--fd-colors-content-disabled);
--fd-colors-component-button-primary-border-disabled: var(--fd-colors-border-disabled);
--fd-colors-component-button-primary-background-disabled: var(--fd-colors-background-disabled);
--fd-colors-component-button-primary-content-disabled: var(--fd-colors-content-disabled);
--fd-colors-system-verification-link-on-subtle: var(--fd-colors-content-on-dark);
--fd-colors-system-verification-content-on-subtle: var(--fd-colors-content-on-dark);
--fd-colors-system-neutral-link-on-subtle: var(--fd-colors-content-on-dark);
--fd-colors-system-neutral-link-on-default: var(--fd-colors-content-on-dark);
--fd-colors-system-neutral-content-on-subtle: var(--fd-colors-content-on-dark);
--fd-colors-system-neutral-content-on-default: var(--fd-colors-content-on-dark);
--fd-colors-system-important-link-on-subtle: var(--fd-colors-content-on-dark);
--fd-colors-system-important-content-on-subtle: var(--fd-colors-content-on-dark);
--fd-colors-system-warning-link-on-subtle: var(--fd-colors-content-on-dark);
--fd-colors-system-warning-link-on-default: var(--fd-colors-content-on-dark);
--fd-colors-system-warning-content-on-subtle: var(--fd-colors-content-on-dark);
--fd-colors-system-warning-content-on-default: var(--fd-colors-content-on-dark);
--fd-colors-system-alert-link-on-subtle: var(--fd-colors-content-on-dark);
--fd-colors-system-alert-link-on-default: var(--fd-colors-content-on-dark);
--fd-colors-system-alert-content-on-subtle: var(--fd-colors-content-on-dark);
--fd-colors-system-alert-content-on-default: var(--fd-colors-content-on-dark);
--fd-colors-system-positive-link-on-subtle: var(--fd-colors-content-on-dark);
--fd-colors-system-positive-content-on-subtle: var(--fd-colors-content-on-dark);
--fd-colors-system-info-link-on-subtle: var(--fd-colors-content-on-dark);
--fd-colors-system-info-content-on-subtle: var(--fd-colors-content-on-dark);
--fd-colors-background-gradient-color-stops-end: var(--fd-colors-background-surface);
--fd-colors-background-gradient-color-stops-start: var(--fd-colors-background-transparent);
--fd-colors-content-link-active: var(--fd-colors-link-default-hover);
--fd-colors-content-link: var(--fd-colors-link-default-base);
--fd-colors-brand-primary-shade: var(--fd-colors-product-colors-primary-d-3);
--fd-colors-brand-primary-tint: var(--fd-colors-product-colors-primary-l-3);
--fd-colors-brand-primary-default: var(--fd-colors-product-colors-primary-l-1);
--fd-colors-border-brand: var(--fd-colors-brand-primary-default);
--fd-colors-background-gradient-surface-fade-bottom: linear-gradient(180deg, var(--fd-colors-background-gradient-color-stops-start) 0%, var(--fd-colors-background-gradient-color-stops-end) 100%);
--fd-colors-background-gradient-surface-fade-end: linear-gradient(90deg, var(--fd-colors-background-gradient-color-stops-start) 0%, var(--fd-colors-background-gradient-color-stops-end) 100%);
--fd-colors-background-brand: var(--fd-colors-brand-primary-default);
--fd-colors-content-brand-secondary: var(--fd-colors-brand-secondary-tint);
--fd-colors-content-brand-primary: var(--fd-colors-brand-primary-default);
}
/**
* This file is for adding custom tokens to the design system.
*/
:root {
--fd-colors-system-component-mtp-content-race-off: var(
--fd-colors-core-green
);
--fd-colors-system-component-mtp-content-resulted: var(--fd-colors-core-grey);
--fd-colors-system-component-mtp-more-than-six-minutes: var(
--fd-colors-core-navy
);
--fd-colors-system-component-mtp-less-than-six-minutes: var(
--fd-colors-core-red
);
--fd-colors-system-component-mtp-content-more-than-six-minutes: var(
--fd-colors-core-navy
);
--fd-colors-system-component-mtp-content-less-than-six-minutes: var(
--fd-colors-core-red
);
--fd-colors-racing-background-default: var(--fd-colors-core-navy-d-3);
--fd-colors-racing-betslip-background: var(--fd-colors-core-navy-d-3);
--fd-colors-racing-betslip-selections-background: var(
--fd-colors-core-navy-d-4
);
}
*[data-mode="dark"] {
--fd-colors-system-component-mtp-content-race-off: var(
--fd-colors-core-green-l-2
);
--fd-colors-system-component-mtp-content-resulted: var(
--fd-colors-core-grey-l-3
);
--fd-colors-system-component-mtp-more-than-six-minutes: var(
--fd-colors-core-navy-l-3
);
--fd-colors-system-component-mtp-less-than-six-minutes: var(
--fd-colors-core-red-l-2
);
}
`;
webpack://frontend-mybets/../../node_modules/zen-observable-ts/module.js
function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
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 _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; }
// === Symbol Support ===
var hasSymbols = function () {
return typeof Symbol === 'function';
};
var hasSymbol = function (name) {
return hasSymbols() && Boolean(Symbol[name]);
};
var getSymbol = function (name) {
return hasSymbol(name) ? Symbol[name] : '@@' + name;
};
if (hasSymbols() && !hasSymbol('observable')) {
Symbol.observable = Symbol('observable');
}
var SymbolIterator = getSymbol('iterator');
var SymbolObservable = getSymbol('observable');
var SymbolSpecies = getSymbol('species'); // === Abstract Operations ===
function getMethod(obj, key) {
var value = obj[key];
if (value == null) return undefined;
if (typeof value !== 'function') throw new TypeError(value + ' is not a function');
return value;
}
function getSpecies(obj) {
var ctor = obj.constructor;
if (ctor !== undefined) {
ctor = ctor[SymbolSpecies];
if (ctor === null) {
ctor = undefined;
}
}
return ctor !== undefined ? ctor : Observable;
}
function isObservable(x) {
return x instanceof Observable; // SPEC: Brand check
}
function hostReportError(e) {
if (hostReportError.log) {
hostReportError.log(e);
} else {
setTimeout(function () {
throw e;
});
}
}
function enqueue(fn) {
Promise.resolve().then(function () {
try {
fn();
} catch (e) {
hostReportError(e);
}
});
}
function cleanupSubscription(subscription) {
var cleanup = subscription._cleanup;
if (cleanup === undefined) return;
subscription._cleanup = undefined;
if (!cleanup) {
return;
}
try {
if (typeof cleanup === 'function') {
cleanup();
} else {
var unsubscribe = getMethod(cleanup, 'unsubscribe');
if (unsubscribe) {
unsubscribe.call(cleanup);
}
}
} catch (e) {
hostReportError(e);
}
}
function closeSubscription(subscription) {
subscription._observer = undefined;
subscription._queue = undefined;
subscription._state = 'closed';
}
function flushSubscription(subscription) {
var queue = subscription._queue;
if (!queue) {
return;
}
subscription._queue = undefined;
subscription._state = 'ready';
for (var i = 0; i < queue.length; ++i) {
notifySubscription(subscription, queue[i].type, queue[i].value);
if (subscription._state === 'closed') break;
}
}
function notifySubscription(subscription, type, value) {
subscription._state = 'running';
var observer = subscription._observer;
try {
var m = getMethod(observer, type);
switch (type) {
case 'next':
if (m) m.call(observer, value);
break;
case 'error':
closeSubscription(subscription);
if (m) m.call(observer, value);else throw value;
break;
case 'complete':
closeSubscription(subscription);
if (m) m.call(observer);
break;
}
} catch (e) {
hostReportError(e);
}
if (subscription._state === 'closed') cleanupSubscription(subscription);else if (subscription._state === 'running') subscription._state = 'ready';
}
function onNotify(subscription, type, value) {
if (subscription._state === 'closed') return;
if (subscription._state === 'buffering') {
subscription._queue.push({
type: type,
value: value
});
return;
}
if (subscription._state !== 'ready') {
subscription._state = 'buffering';
subscription._queue = [{
type: type,
value: value
}];
enqueue(function () {
return flushSubscription(subscription);
});
return;
}
notifySubscription(subscription, type, value);
}
var Subscription = /*#__PURE__*/function () {
function Subscription(observer, subscriber) {
// ASSERT: observer is an object
// ASSERT: subscriber is callable
this._cleanup = undefined;
this._observer = observer;
this._queue = undefined;
this._state = 'initializing';
var subscriptionObserver = new SubscriptionObserver(this);
try {
this._cleanup = subscriber.call(undefined, subscriptionObserver);
} catch (e) {
subscriptionObserver.error(e);
}
if (this._state === 'initializing') this._state = 'ready';
}
var _proto = Subscription.prototype;
_proto.unsubscribe = function unsubscribe() {
if (this._state !== 'closed') {
closeSubscription(this);
cleanupSubscription(this);
}
};
_createClass(Subscription, [{
key: "closed",
get: function () {
return this._state === 'closed';
}
}]);
return Subscription;
}();
var SubscriptionObserver = /*#__PURE__*/function () {
function SubscriptionObserver(subscription) {
this._subscription = subscription;
}
var _proto2 = SubscriptionObserver.prototype;
_proto2.next = function next(value) {
onNotify(this._subscription, 'next', value);
};
_proto2.error = function error(value) {
onNotify(this._subscription, 'error', value);
};
_proto2.complete = function complete() {
onNotify(this._subscription, 'complete');
};
_createClass(SubscriptionObserver, [{
key: "closed",
get: function () {
return this._subscription._state === 'closed';
}
}]);
return SubscriptionObserver;
}();
var Observable = /*#__PURE__*/function () {
function Observable(subscriber) {
if (!(this instanceof Observable)) throw new TypeError('Observable cannot be called as a function');
if (typeof subscriber !== 'function') throw new TypeError('Observable initializer must be a function');
this._subscriber = subscriber;
}
var _proto3 = Observable.prototype;
_proto3.subscribe = function subscribe(observer) {
if (typeof observer !== 'object' || observer === null) {
observer = {
next: observer,
error: arguments[1],
complete: arguments[2]
};
}
return new Subscription(observer, this._subscriber);
};
_proto3.forEach = function forEach(fn) {
var _this = this;
return new Promise(function (resolve, reject) {
if (typeof fn !== 'function') {
reject(new TypeError(fn + ' is not a function'));
return;
}
function done() {
subscription.unsubscribe();
resolve();
}
var subscription = _this.subscribe({
next: function (value) {
try {
fn(value, done);
} catch (e) {
reject(e);
subscription.unsubscribe();
}
},
error: reject,
complete: resolve
});
});
};
_proto3.map = function map(fn) {
var _this2 = this;
if (typeof fn !== 'function') throw new TypeError(fn + ' is not a function');
var C = getSpecies(this);
return new C(function (observer) {
return _this2.subscribe({
next: function (value) {
try {
value = fn(value);
} catch (e) {
return observer.error(e);
}
observer.next(value);
},
error: function (e) {
observer.error(e);
},
complete: function () {
observer.complete();
}
});
});
};
_proto3.filter = function filter(fn) {
var _this3 = this;
if (typeof fn !== 'function') throw new TypeError(fn + ' is not a function');
var C = getSpecies(this);
return new C(function (observer) {
return _this3.subscribe({
next: function (value) {
try {
if (!fn(value)) return;
} catch (e) {
return observer.error(e);
}
observer.next(value);
},
error: function (e) {
observer.error(e);
},
complete: function () {
observer.complete();
}
});
});
};
_proto3.reduce = function reduce(fn) {
var _this4 = this;
if (typeof fn !== 'function') throw new TypeError(fn + ' is not a function');
var C = getSpecies(this);
var hasSeed = arguments.length > 1;
var hasValue = false;
var seed = arguments[1];
var acc = seed;
return new C(function (observer) {
return _this4.subscribe({
next: function (value) {
var first = !hasValue;
hasValue = true;
if (!first || hasSeed) {
try {
acc = fn(acc, value);
} catch (e) {
return observer.error(e);
}
} else {
acc = value;
}
},
error: function (e) {
observer.error(e);
},
complete: function () {
if (!hasValue && !hasSeed) return observer.error(new TypeError('Cannot reduce an empty sequence'));
observer.next(acc);
observer.complete();
}
});
});
};
_proto3.concat = function concat() {
var _this5 = this;
for (var _len = arguments.length, sources = new Array(_len), _key = 0; _key < _len; _key++) {
sources[_key] = arguments[_key];
}
var C = getSpecies(this);
return new C(function (observer) {
var subscription;
var index = 0;
function startNext(next) {
subscription = next.subscribe({
next: function (v) {
observer.next(v);
},
error: function (e) {
observer.error(e);
},
complete: function () {
if (index === sources.length) {
subscription = undefined;
observer.complete();
} else {
startNext(C.from(sources[index++]));
}
}
});
}
startNext(_this5);
return function () {
if (subscription) {
subscription.unsubscribe();
subscription = undefined;
}
};
});
};
_proto3.flatMap = function flatMap(fn) {
var _this6 = this;
if (typeof fn !== 'function') throw new TypeError(fn + ' is not a function');
var C = getSpecies(this);
return new C(function (observer) {
var subscriptions = [];
var outer = _this6.subscribe({
next: function (value) {
if (fn) {
try {
value = fn(value);
} catch (e) {
return observer.error(e);
}
}
var inner = C.from(value).subscribe({
next: function (value) {
observer.next(value);
},
error: function (e) {
observer.error(e);
},
complete: function () {
var i = subscriptions.indexOf(inner);
if (i >= 0) subscriptions.splice(i, 1);
completeIfDone();
}
});
subscriptions.push(inner);
},
error: function (e) {
observer.error(e);
},
complete: function () {
completeIfDone();
}
});
function completeIfDone() {
if (outer.closed && subscriptions.length === 0) observer.complete();
}
return function () {
subscriptions.forEach(function (s) {
return s.unsubscribe();
});
outer.unsubscribe();
};
});
};
_proto3[SymbolObservable] = function () {
return this;
};
Observable.from = function from(x) {
var C = typeof this === 'function' ? this : Observable;
if (x == null) throw new TypeError(x + ' is not an object');
var method = getMethod(x, SymbolObservable);
if (method) {
var observable = method.call(x);
if (Object(observable) !== observable) throw new TypeError(observable + ' is not an object');
if (isObservable(observable) && observable.constructor === C) return observable;
return new C(function (observer) {
return observable.subscribe(observer);
});
}
if (hasSymbol('iterator')) {
method = getMethod(x, SymbolIterator);
if (method) {
return new C(function (observer) {
enqueue(function () {
if (observer.closed) return;
for (var _iterator = _createForOfIteratorHelperLoose(method.call(x)), _step; !(_step = _iterator()).done;) {
var item = _step.value;
observer.next(item);
if (observer.closed) return;
}
observer.complete();
});
});
}
}
if (Array.isArray(x)) {
return new C(function (observer) {
enqueue(function () {
if (observer.closed) return;
for (var i = 0; i < x.length; ++i) {
observer.next(x[i]);
if (observer.closed) return;
}
observer.complete();
});
});
}
throw new TypeError(x + ' is not observable');
};
Observable.of = function of() {
for (var _len2 = arguments.length, items = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
items[_key2] = arguments[_key2];
}
var C = typeof this === 'function' ? this : Observable;
return new C(function (observer) {
enqueue(function () {
if (observer.closed) return;
for (var i = 0; i < items.length; ++i) {
observer.next(items[i]);
if (observer.closed) return;
}
observer.complete();
});
});
};
_createClass(Observable, null, [{
key: SymbolSpecies,
get: function () {
return this;
}
}]);
return Observable;
}();
if (hasSymbols()) {
Object.defineProperty(Observable, Symbol('extensions'), {
value: {
symbol: SymbolObservable,
hostReportError: hostReportError
},
configurable: true
});
}
export { Observable };
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/common/objects.js
export function isNonNullObject(obj) {
return obj !== null && typeof obj === "object";
}
export function isPlainObject(obj) {
return (obj !== null &&
typeof obj === "object" &&
(Object.getPrototypeOf(obj) === Object.prototype ||
Object.getPrototypeOf(obj) === null));
}
//# sourceMappingURL=objects.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/graphql/fragments.js
import { __assign, __spreadArray } from "tslib";
import { invariant, newInvariantError } from "../globals/index.js";
/**
* Returns a query document which adds a single query operation that only
* spreads the target fragment inside of it.
*
* So for example a document of:
*
* ```graphql
* fragment foo on Foo { a b c }
* ```
*
* Turns into:
*
* ```graphql
* { ...foo }
*
* fragment foo on Foo { a b c }
* ```
*
* The target fragment will either be the only fragment in the document, or a
* fragment specified by the provided `fragmentName`. If there is more than one
* fragment, but a `fragmentName` was not defined then an error will be thrown.
*/
export function getFragmentQueryDocument(document, fragmentName) {
var actualFragmentName = fragmentName;
// Build an array of all our fragment definitions that will be used for
// validations. We also do some validations on the other definitions in the
// document while building this list.
var fragments = [];
document.definitions.forEach(function (definition) {
// Throw an error if we encounter an operation definition because we will
// define our own operation definition later on.
if (definition.kind === "OperationDefinition") {
throw newInvariantError(
71,
definition.operation,
definition.name ? " named '".concat(definition.name.value, "'") : ""
);
}
// Add our definition to the fragments array if it is a fragment
// definition.
if (definition.kind === "FragmentDefinition") {
fragments.push(definition);
}
});
// If the user did not give us a fragment name then let us try to get a
// name from a single fragment in the definition.
if (typeof actualFragmentName === "undefined") {
invariant(fragments.length === 1, 72, fragments.length);
actualFragmentName = fragments[0].name.value;
}
// Generate a query document with an operation that simply spreads the
// fragment inside of it.
var query = __assign(__assign({}, document), { definitions: __spreadArray([
{
kind: "OperationDefinition",
// OperationTypeNode is an enum
operation: "query",
selectionSet: {
kind: "SelectionSet",
selections: [
{
kind: "FragmentSpread",
name: {
kind: "Name",
value: actualFragmentName,
},
},
],
},
}
], document.definitions, true) });
return query;
}
// Utility function that takes a list of fragment definitions and makes a hash out of them
// that maps the name of the fragment to the fragment definition.
export function createFragmentMap(fragments) {
if (fragments === void 0) { fragments = []; }
var symTable = {};
fragments.forEach(function (fragment) {
symTable[fragment.name.value] = fragment;
});
return symTable;
}
export function getFragmentFromSelection(selection, fragmentMap) {
switch (selection.kind) {
case "InlineFragment":
return selection;
case "FragmentSpread": {
var fragmentName = selection.name.value;
if (typeof fragmentMap === "function") {
return fragmentMap(fragmentName);
}
var fragment = fragmentMap && fragmentMap[fragmentName];
invariant(fragment, 73, fragmentName);
return fragment || null;
}
default:
return null;
}
}
//# sourceMappingURL=fragments.js.map
webpack://frontend-mybets/../../node_modules/@wry/caches/lib/weak.js
function noop() { }
const defaultDispose = noop;
const _WeakRef = typeof WeakRef !== "undefined"
? WeakRef
: function (value) {
return { deref: () => value };
};
const _WeakMap = typeof WeakMap !== "undefined" ? WeakMap : Map;
const _FinalizationRegistry = typeof FinalizationRegistry !== "undefined"
? FinalizationRegistry
: function () {
return {
register: noop,
unregister: noop,
};
};
const finalizationBatchSize = 10024;
export class WeakCache {
constructor(max = Infinity, dispose = defaultDispose) {
this.max = max;
this.dispose = dispose;
this.map = new _WeakMap();
this.newest = null;
this.oldest = null;
this.unfinalizedNodes = new Set();
this.finalizationScheduled = false;
this.size = 0;
this.finalize = () => {
const iterator = this.unfinalizedNodes.values();
for (let i = 0; i < finalizationBatchSize; i++) {
const node = iterator.next().value;
if (!node)
break;
this.unfinalizedNodes.delete(node);
const key = node.key;
delete node.key;
node.keyRef = new _WeakRef(key);
this.registry.register(key, node, node);
}
if (this.unfinalizedNodes.size > 0) {
queueMicrotask(this.finalize);
}
else {
this.finalizationScheduled = false;
}
};
this.registry = new _FinalizationRegistry(this.deleteNode.bind(this));
}
has(key) {
return this.map.has(key);
}
get(key) {
const node = this.getNode(key);
return node && node.value;
}
getNode(key) {
const node = this.map.get(key);
if (node && node !== this.newest) {
const { older, newer } = node;
if (newer) {
newer.older = older;
}
if (older) {
older.newer = newer;
}
node.older = this.newest;
node.older.newer = node;
node.newer = null;
this.newest = node;
if (node === this.oldest) {
this.oldest = newer;
}
}
return node;
}
set(key, value) {
let node = this.getNode(key);
if (node) {
return (node.value = value);
}
node = {
key,
value,
newer: null,
older: this.newest,
};
if (this.newest) {
this.newest.newer = node;
}
this.newest = node;
this.oldest = this.oldest || node;
this.scheduleFinalization(node);
this.map.set(key, node);
this.size++;
return node.value;
}
clean() {
while (this.oldest && this.size > this.max) {
this.deleteNode(this.oldest);
}
}
deleteNode(node) {
if (node === this.newest) {
this.newest = node.older;
}
if (node === this.oldest) {
this.oldest = node.newer;
}
if (node.newer) {
node.newer.older = node.older;
}
if (node.older) {
node.older.newer = node.newer;
}
this.size--;
const key = node.key || (node.keyRef && node.keyRef.deref());
this.dispose(node.value, key);
if (!node.keyRef) {
this.unfinalizedNodes.delete(node);
}
else {
this.registry.unregister(node);
}
if (key)
this.map.delete(key);
}
delete(key) {
const node = this.map.get(key);
if (node) {
this.deleteNode(node);
return true;
}
return false;
}
scheduleFinalization(node) {
this.unfinalizedNodes.add(node);
if (!this.finalizationScheduled) {
this.finalizationScheduled = true;
queueMicrotask(this.finalize);
}
}
}
//# sourceMappingURL=weak.js.map
webpack://frontend-mybets/../../node_modules/@wry/caches/lib/strong.js
function defaultDispose() { }
export class StrongCache {
constructor(max = Infinity, dispose = defaultDispose) {
this.max = max;
this.dispose = dispose;
this.map = new Map();
this.newest = null;
this.oldest = null;
}
has(key) {
return this.map.has(key);
}
get(key) {
const node = this.getNode(key);
return node && node.value;
}
get size() {
return this.map.size;
}
getNode(key) {
const node = this.map.get(key);
if (node && node !== this.newest) {
const { older, newer } = node;
if (newer) {
newer.older = older;
}
if (older) {
older.newer = newer;
}
node.older = this.newest;
node.older.newer = node;
node.newer = null;
this.newest = node;
if (node === this.oldest) {
this.oldest = newer;
}
}
return node;
}
set(key, value) {
let node = this.getNode(key);
if (node) {
return node.value = value;
}
node = {
key,
value,
newer: null,
older: this.newest
};
if (this.newest) {
this.newest.newer = node;
}
this.newest = node;
this.oldest = this.oldest || node;
this.map.set(key, node);
return node.value;
}
clean() {
while (this.oldest && this.map.size > this.max) {
this.delete(this.oldest.key);
}
}
delete(key) {
const node = this.map.get(key);
if (node) {
if (node === this.newest) {
this.newest = node.older;
}
if (node === this.oldest) {
this.oldest = node.newer;
}
if (node.newer) {
node.newer.older = node.older;
}
if (node.older) {
node.older.newer = node.newer;
}
this.map.delete(key);
this.dispose(node.value, key);
return true;
}
return false;
}
}
//# sourceMappingURL=strong.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/caching/caches.js
import { WeakCache, StrongCache } from "@wry/caches";
var scheduledCleanup = new WeakSet();
function schedule(cache) {
if (!scheduledCleanup.has(cache)) {
scheduledCleanup.add(cache);
setTimeout(function () {
cache.clean();
scheduledCleanup.delete(cache);
}, 100);
}
}
/**
* @internal
* A version of WeakCache that will auto-schedule a cleanup of the cache when
* a new item is added.
* Throttled to once per 100ms.
*
* @privateRemarks
* Should be used throughout the rest of the codebase instead of WeakCache,
* with the notable exception of usage in `wrap` from `optimism` - that one
* already handles cleanup and should remain a `WeakCache`.
*/
export var AutoCleanedWeakCache = function (max, dispose) {
/*
Some builds of `WeakCache` are function prototypes, some are classes.
This library still builds with an ES5 target, so we can't extend the
real classes.
Instead, we have to use this workaround until we switch to a newer build
target.
*/
var cache = new WeakCache(max, dispose);
cache.set = function (key, value) {
schedule(this);
return WeakCache.prototype.set.call(this, key, value);
};
return cache;
};
/**
* @internal
* A version of StrongCache that will auto-schedule a cleanup of the cache when
* a new item is added.
* Throttled to once per 100ms.
*
* @privateRemarks
* Should be used throughout the rest of the codebase instead of StrongCache,
* with the notable exception of usage in `wrap` from `optimism` - that one
* already handles cleanup and should remain a `StrongCache`.
*/
export var AutoCleanedStrongCache = function (max, dispose) {
/*
Some builds of `StrongCache` are function prototypes, some are classes.
This library still builds with an ES5 target, so we can't extend the
real classes.
Instead, we have to use this workaround until we switch to a newer build
target.
*/
var cache = new StrongCache(max, dispose);
cache.set = function (key, value) {
schedule(this);
return StrongCache.prototype.set.call(this, key, value);
};
return cache;
};
//# sourceMappingURL=caches.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/caching/sizes.js
import { __assign } from "tslib";
import { global } from "../globals/index.js";
var cacheSizeSymbol = Symbol.for("apollo.cacheSize");
/**
*
* The global cache size configuration for Apollo Client.
*
* @remarks
*
* You can directly modify this object, but any modification will
* only have an effect on caches that are created after the modification.
*
* So for global caches, such as `parser`, `canonicalStringify` and `print`,
* you might need to call `.reset` on them, which will essentially re-create them.
*
* Alternatively, you can set `globalThis[Symbol.for("apollo.cacheSize")]` before
* you load the Apollo Client package:
*
* @example
* ```ts
* globalThis[Symbol.for("apollo.cacheSize")] = {
* parser: 100
* } satisfies Partial<CacheSizes> // the `satisfies` is optional if using TypeScript
* ```
*/
export var cacheSizes = __assign({}, global[cacheSizeSymbol]);
//# sourceMappingURL=sizes.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/caching/getMemoryInternals.js
import { __assign, __spreadArray } from "tslib";
import { cacheSizes } from "./sizes.js";
var globalCaches = {};
export function registerGlobalCache(name, getSize) {
globalCaches[name] = getSize;
}
/**
* For internal purposes only - please call `ApolloClient.getMemoryInternals` instead
* @internal
*/
export var getApolloClientMemoryInternals = globalThis.__DEV__ !== false ?
_getApolloClientMemoryInternals
: undefined;
/**
* For internal purposes only - please call `ApolloClient.getMemoryInternals` instead
* @internal
*/
export var getInMemoryCacheMemoryInternals = globalThis.__DEV__ !== false ?
_getInMemoryCacheMemoryInternals
: undefined;
/**
* For internal purposes only - please call `ApolloClient.getMemoryInternals` instead
* @internal
*/
export var getApolloCacheMemoryInternals = globalThis.__DEV__ !== false ?
_getApolloCacheMemoryInternals
: undefined;
function getCurrentCacheSizes() {
// `defaultCacheSizes` is a `const enum` that will be inlined during build, so we have to reconstruct it's shape here
var defaults = {
parser: 1000 /* defaultCacheSizes["parser"] */,
canonicalStringify: 1000 /* defaultCacheSizes["canonicalStringify"] */,
print: 2000 /* defaultCacheSizes["print"] */,
"documentTransform.cache": 2000 /* defaultCacheSizes["documentTransform.cache"] */,
"queryManager.getDocumentInfo": 2000 /* defaultCacheSizes["queryManager.getDocumentInfo"] */,
"PersistedQueryLink.persistedQueryHashes": 2000 /* defaultCacheSizes["PersistedQueryLink.persistedQueryHashes"] */,
"fragmentRegistry.transform": 2000 /* defaultCacheSizes["fragmentRegistry.transform"] */,
"fragmentRegistry.lookup": 1000 /* defaultCacheSizes["fragmentRegistry.lookup"] */,
"fragmentRegistry.findFragmentSpreads": 4000 /* defaultCacheSizes["fragmentRegistry.findFragmentSpreads"] */,
"cache.fragmentQueryDocuments": 1000 /* defaultCacheSizes["cache.fragmentQueryDocuments"] */,
"removeTypenameFromVariables.getVariableDefinitions": 2000 /* defaultCacheSizes["removeTypenameFromVariables.getVariableDefinitions"] */,
"inMemoryCache.maybeBroadcastWatch": 5000 /* defaultCacheSizes["inMemoryCache.maybeBroadcastWatch"] */,
"inMemoryCache.executeSelectionSet": 50000 /* defaultCacheSizes["inMemoryCache.executeSelectionSet"] */,
"inMemoryCache.executeSubSelectedArray": 10000 /* defaultCacheSizes["inMemoryCache.executeSubSelectedArray"] */,
};
return Object.fromEntries(Object.entries(defaults).map(function (_a) {
var k = _a[0], v = _a[1];
return [
k,
cacheSizes[k] || v,
];
}));
}
function _getApolloClientMemoryInternals() {
var _a, _b, _c, _d, _e;
if (!(globalThis.__DEV__ !== false))
throw new Error("only supported in development mode");
return {
limits: getCurrentCacheSizes(),
sizes: __assign({ print: (_a = globalCaches.print) === null || _a === void 0 ? void 0 : _a.call(globalCaches), parser: (_b = globalCaches.parser) === null || _b === void 0 ? void 0 : _b.call(globalCaches), canonicalStringify: (_c = globalCaches.canonicalStringify) === null || _c === void 0 ? void 0 : _c.call(globalCaches), links: linkInfo(this.link), queryManager: {
getDocumentInfo: this["queryManager"]["transformCache"].size,
documentTransforms: transformInfo(this["queryManager"].documentTransform),
} }, (_e = (_d = this.cache).getMemoryInternals) === null || _e === void 0 ? void 0 : _e.call(_d)),
};
}
function _getApolloCacheMemoryInternals() {
return {
cache: {
fragmentQueryDocuments: getWrapperInformation(this["getFragmentDoc"]),
},
};
}
function _getInMemoryCacheMemoryInternals() {
var fragments = this.config.fragments;
return __assign(__assign({}, _getApolloCacheMemoryInternals.apply(this)), { addTypenameDocumentTransform: transformInfo(this["addTypenameTransform"]), inMemoryCache: {
executeSelectionSet: getWrapperInformation(this["storeReader"]["executeSelectionSet"]),
executeSubSelectedArray: getWrapperInformation(this["storeReader"]["executeSubSelectedArray"]),
maybeBroadcastWatch: getWrapperInformation(this["maybeBroadcastWatch"]),
}, fragmentRegistry: {
findFragmentSpreads: getWrapperInformation(fragments === null || fragments === void 0 ? void 0 : fragments.findFragmentSpreads),
lookup: getWrapperInformation(fragments === null || fragments === void 0 ? void 0 : fragments.lookup),
transform: getWrapperInformation(fragments === null || fragments === void 0 ? void 0 : fragments.transform),
} });
}
function isWrapper(f) {
return !!f && "dirtyKey" in f;
}
function getWrapperInformation(f) {
return isWrapper(f) ? f.size : undefined;
}
function isDefined(value) {
return value != null;
}
function transformInfo(transform) {
return recurseTransformInfo(transform).map(function (cache) { return ({ cache: cache }); });
}
function recurseTransformInfo(transform) {
return transform ?
__spreadArray(__spreadArray([
getWrapperInformation(transform === null || transform === void 0 ? void 0 : transform["performWork"])
], recurseTransformInfo(transform === null || transform === void 0 ? void 0 : transform["left"]), true), recurseTransformInfo(transform === null || transform === void 0 ? void 0 : transform["right"]), true).filter(isDefined)
: [];
}
function linkInfo(link) {
var _a;
return link ?
__spreadArray(__spreadArray([
(_a = link === null || link === void 0 ? void 0 : link.getMemoryInternals) === null || _a === void 0 ? void 0 : _a.call(link)
], linkInfo(link === null || link === void 0 ? void 0 : link.left), true), linkInfo(link === null || link === void 0 ? void 0 : link.right), true).filter(isDefined)
: [];
}
//# sourceMappingURL=getMemoryInternals.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/common/canonicalStringify.js
import { AutoCleanedStrongCache, cacheSizes, } from "../../utilities/caching/index.js";
import { registerGlobalCache } from "../caching/getMemoryInternals.js";
/**
* Like JSON.stringify, but with object keys always sorted in the same order.
*
* To achieve performant sorting, this function uses a Map from JSON-serialized
* arrays of keys (in any order) to sorted arrays of the same keys, with a
* single sorted array reference shared by all permutations of the keys.
*
* As a drawback, this function will add a little bit more memory for every
* object encountered that has different (more, less, a different order of) keys
* than in the past.
*
* In a typical application, this extra memory usage should not play a
* significant role, as `canonicalStringify` will be called for only a limited
* number of object shapes, and the cache will not grow beyond a certain point.
* But in some edge cases, this could be a problem, so we provide
* canonicalStringify.reset() as a way of clearing the cache.
* */
export var canonicalStringify = Object.assign(function canonicalStringify(value) {
return JSON.stringify(value, stableObjectReplacer);
}, {
reset: function () {
// Clearing the sortingMap will reclaim all cached memory, without
// affecting the logical results of canonicalStringify, but potentially
// sacrificing performance until the cache is refilled.
sortingMap = new AutoCleanedStrongCache(cacheSizes.canonicalStringify || 1000 /* defaultCacheSizes.canonicalStringify */);
},
});
if (globalThis.__DEV__ !== false) {
registerGlobalCache("canonicalStringify", function () { return sortingMap.size; });
}
// Values are JSON-serialized arrays of object keys (in any order), and values
// are sorted arrays of the same keys.
var sortingMap;
canonicalStringify.reset();
// The JSON.stringify function takes an optional second argument called a
// replacer function. This function is called for each key-value pair in the
// object being stringified, and its return value is used instead of the
// original value. If the replacer function returns a new value, that value is
// stringified as JSON instead of the original value of the property.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_replacer_parameter
function stableObjectReplacer(key, value) {
if (value && typeof value === "object") {
var proto = Object.getPrototypeOf(value);
// We don't want to mess with objects that are not "plain" objects, which
// means their prototype is either Object.prototype or null. This check also
// prevents needlessly rearranging the indices of arrays.
if (proto === Object.prototype || proto === null) {
var keys = Object.keys(value);
// If keys is already sorted, let JSON.stringify serialize the original
// value instead of creating a new object with keys in the same order.
if (keys.every(everyKeyInOrder))
return value;
var unsortedKey = JSON.stringify(keys);
var sortedKeys = sortingMap.get(unsortedKey);
if (!sortedKeys) {
keys.sort();
var sortedKey = JSON.stringify(keys);
// Checking for sortedKey in the sortingMap allows us to share the same
// sorted array reference for all permutations of the same set of keys.
sortedKeys = sortingMap.get(sortedKey) || keys;
sortingMap.set(unsortedKey, sortedKeys);
sortingMap.set(sortedKey, sortedKeys);
}
var sortedObject_1 = Object.create(proto);
// Reassigning the keys in sorted order will cause JSON.stringify to
// serialize them in sorted order.
sortedKeys.forEach(function (key) {
sortedObject_1[key] = value[key];
});
return sortedObject_1;
}
}
return value;
}
// Since everything that happens in stableObjectReplacer benefits from being as
// efficient as possible, we use a static function as the callback for
// keys.every in order to test if the provided keys are already sorted without
// allocating extra memory for a callback.
function everyKeyInOrder(key, i, keys) {
return i === 0 || keys[i - 1] <= key;
}
//# sourceMappingURL=canonicalStringify.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/graphql/storeUtils.js
import { newInvariantError } from "../globals/index.js";
import { isNonNullObject } from "../common/objects.js";
import { getFragmentFromSelection } from "./fragments.js";
import { canonicalStringify } from "../common/canonicalStringify.js";
export function makeReference(id) {
return { __ref: String(id) };
}
export function isReference(obj) {
return Boolean(obj && typeof obj === "object" && typeof obj.__ref === "string");
}
export function isDocumentNode(value) {
return (isNonNullObject(value) &&
value.kind === "Document" &&
Array.isArray(value.definitions));
}
function isStringValue(value) {
return value.kind === "StringValue";
}
function isBooleanValue(value) {
return value.kind === "BooleanValue";
}
function isIntValue(value) {
return value.kind === "IntValue";
}
function isFloatValue(value) {
return value.kind === "FloatValue";
}
function isVariable(value) {
return value.kind === "Variable";
}
function isObjectValue(value) {
return value.kind === "ObjectValue";
}
function isListValue(value) {
return value.kind === "ListValue";
}
function isEnumValue(value) {
return value.kind === "EnumValue";
}
function isNullValue(value) {
return value.kind === "NullValue";
}
export function valueToObjectRepresentation(argObj, name, value, variables) {
if (isIntValue(value) || isFloatValue(value)) {
argObj[name.value] = Number(value.value);
}
else if (isBooleanValue(value) || isStringValue(value)) {
argObj[name.value] = value.value;
}
else if (isObjectValue(value)) {
var nestedArgObj_1 = {};
value.fields.map(function (obj) {
return valueToObjectRepresentation(nestedArgObj_1, obj.name, obj.value, variables);
});
argObj[name.value] = nestedArgObj_1;
}
else if (isVariable(value)) {
var variableValue = (variables || {})[value.name.value];
argObj[name.value] = variableValue;
}
else if (isListValue(value)) {
argObj[name.value] = value.values.map(function (listValue) {
var nestedArgArrayObj = {};
valueToObjectRepresentation(nestedArgArrayObj, name, listValue, variables);
return nestedArgArrayObj[name.value];
});
}
else if (isEnumValue(value)) {
argObj[name.value] = value.value;
}
else if (isNullValue(value)) {
argObj[name.value] = null;
}
else {
throw newInvariantError(82, name.value, value.kind);
}
}
export function storeKeyNameFromField(field, variables) {
var directivesObj = null;
if (field.directives) {
directivesObj = {};
field.directives.forEach(function (directive) {
directivesObj[directive.name.value] = {};
if (directive.arguments) {
directive.arguments.forEach(function (_a) {
var name = _a.name, value = _a.value;
return valueToObjectRepresentation(directivesObj[directive.name.value], name, value, variables);
});
}
});
}
var argObj = null;
if (field.arguments && field.arguments.length) {
argObj = {};
field.arguments.forEach(function (_a) {
var name = _a.name, value = _a.value;
return valueToObjectRepresentation(argObj, name, value, variables);
});
}
return getStoreKeyName(field.name.value, argObj, directivesObj);
}
var KNOWN_DIRECTIVES = [
"connection",
"include",
"skip",
"client",
"rest",
"export",
"nonreactive",
];
// Default stable JSON.stringify implementation used by getStoreKeyName. Can be
// updated/replaced with something better by calling
// getStoreKeyName.setStringify(newStringifyFunction).
var storeKeyNameStringify = canonicalStringify;
export var getStoreKeyName = Object.assign(function (fieldName, args, directives) {
if (args &&
directives &&
directives["connection"] &&
directives["connection"]["key"]) {
if (directives["connection"]["filter"] &&
directives["connection"]["filter"].length > 0) {
var filterKeys = directives["connection"]["filter"] ?
directives["connection"]["filter"]
: [];
filterKeys.sort();
var filteredArgs_1 = {};
filterKeys.forEach(function (key) {
filteredArgs_1[key] = args[key];
});
return "".concat(directives["connection"]["key"], "(").concat(storeKeyNameStringify(filteredArgs_1), ")");
}
else {
return directives["connection"]["key"];
}
}
var completeFieldName = fieldName;
if (args) {
// We can't use `JSON.stringify` here since it's non-deterministic,
// and can lead to different store key names being created even though
// the `args` object used during creation has the same properties/values.
var stringifiedArgs = storeKeyNameStringify(args);
completeFieldName += "(".concat(stringifiedArgs, ")");
}
if (directives) {
Object.keys(directives).forEach(function (key) {
if (KNOWN_DIRECTIVES.indexOf(key) !== -1)
return;
if (directives[key] && Object.keys(directives[key]).length) {
completeFieldName += "@".concat(key, "(").concat(storeKeyNameStringify(directives[key]), ")");
}
else {
completeFieldName += "@".concat(key);
}
});
}
return completeFieldName;
}, {
setStringify: function (s) {
var previous = storeKeyNameStringify;
storeKeyNameStringify = s;
return previous;
},
});
export function argumentsObjectFromField(field, variables) {
if (field.arguments && field.arguments.length) {
var argObj_1 = {};
field.arguments.forEach(function (_a) {
var name = _a.name, value = _a.value;
return valueToObjectRepresentation(argObj_1, name, value, variables);
});
return argObj_1;
}
return null;
}
export function resultKeyNameFromField(field) {
return field.alias ? field.alias.value : field.name.value;
}
export function getTypenameFromResult(result, selectionSet, fragmentMap) {
var fragments;
for (var _i = 0, _a = selectionSet.selections; _i < _a.length; _i++) {
var selection = _a[_i];
if (isField(selection)) {
if (selection.name.value === "__typename") {
return result[resultKeyNameFromField(selection)];
}
}
else if (fragments) {
fragments.push(selection);
}
else {
fragments = [selection];
}
}
if (typeof result.__typename === "string") {
return result.__typename;
}
if (fragments) {
for (var _b = 0, fragments_1 = fragments; _b < fragments_1.length; _b++) {
var selection = fragments_1[_b];
var typename = getTypenameFromResult(result, getFragmentFromSelection(selection, fragmentMap).selectionSet, fragmentMap);
if (typeof typename === "string") {
return typename;
}
}
}
}
export function isField(selection) {
return selection.kind === "Field";
}
export function isInlineFragment(selection) {
return selection.kind === "InlineFragment";
}
//# sourceMappingURL=storeUtils.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/graphql/getFromAST.js
import { invariant, newInvariantError } from "../globals/index.js";
import { valueToObjectRepresentation } from "./storeUtils.js";
// Checks the document for errors and throws an exception if there is an error.
export function checkDocument(doc) {
invariant(doc && doc.kind === "Document", 74);
var operations = doc.definitions
.filter(function (d) { return d.kind !== "FragmentDefinition"; })
.map(function (definition) {
if (definition.kind !== "OperationDefinition") {
throw newInvariantError(75, definition.kind);
}
return definition;
});
invariant(operations.length <= 1, 76, operations.length);
return doc;
}
export function getOperationDefinition(doc) {
checkDocument(doc);
return doc.definitions.filter(function (definition) {
return definition.kind === "OperationDefinition";
})[0];
}
export function getOperationName(doc) {
return (doc.definitions
.filter(function (definition) {
return definition.kind === "OperationDefinition" && !!definition.name;
})
.map(function (x) { return x.name.value; })[0] || null);
}
// Returns the FragmentDefinitions from a particular document as an array
export function getFragmentDefinitions(doc) {
return doc.definitions.filter(function (definition) {
return definition.kind === "FragmentDefinition";
});
}
export function getQueryDefinition(doc) {
var queryDef = getOperationDefinition(doc);
invariant(queryDef && queryDef.operation === "query", 77);
return queryDef;
}
export function getFragmentDefinition(doc) {
invariant(doc.kind === "Document", 78);
invariant(doc.definitions.length <= 1, 79);
var fragmentDef = doc.definitions[0];
invariant(fragmentDef.kind === "FragmentDefinition", 80);
return fragmentDef;
}
/**
* Returns the first operation definition found in this document.
* If no operation definition is found, the first fragment definition will be returned.
* If no definitions are found, an error will be thrown.
*/
export function getMainDefinition(queryDoc) {
checkDocument(queryDoc);
var fragmentDefinition;
for (var _i = 0, _a = queryDoc.definitions; _i < _a.length; _i++) {
var definition = _a[_i];
if (definition.kind === "OperationDefinition") {
var operation = definition.operation;
if (operation === "query" ||
operation === "mutation" ||
operation === "subscription") {
return definition;
}
}
if (definition.kind === "FragmentDefinition" && !fragmentDefinition) {
// we do this because we want to allow multiple fragment definitions
// to precede an operation definition.
fragmentDefinition = definition;
}
}
if (fragmentDefinition) {
return fragmentDefinition;
}
throw newInvariantError(81);
}
export function getDefaultValues(definition) {
var defaultValues = Object.create(null);
var defs = definition && definition.variableDefinitions;
if (defs && defs.length) {
defs.forEach(function (def) {
if (def.defaultValue) {
valueToObjectRepresentation(defaultValues, def.variable.name, def.defaultValue);
}
});
}
return defaultValues;
}
//# sourceMappingURL=getFromAST.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/link/core/ApolloLink.js
import { newInvariantError, invariant } from "../../utilities/globals/index.js";
import { Observable } from "../../utilities/index.js";
import { validateOperation, createOperation, transformOperation, } from "../utils/index.js";
function passthrough(op, forward) {
return (forward ? forward(op) : Observable.of());
}
function toLink(handler) {
return typeof handler === "function" ? new ApolloLink(handler) : handler;
}
function isTerminating(link) {
return link.request.length <= 1;
}
var ApolloLink = /** @class */ (function () {
function ApolloLink(request) {
if (request)
this.request = request;
}
ApolloLink.empty = function () {
return new ApolloLink(function () { return Observable.of(); });
};
ApolloLink.from = function (links) {
if (links.length === 0)
return ApolloLink.empty();
return links.map(toLink).reduce(function (x, y) { return x.concat(y); });
};
ApolloLink.split = function (test, left, right) {
var leftLink = toLink(left);
var rightLink = toLink(right || new ApolloLink(passthrough));
var ret;
if (isTerminating(leftLink) && isTerminating(rightLink)) {
ret = new ApolloLink(function (operation) {
return test(operation) ?
leftLink.request(operation) || Observable.of()
: rightLink.request(operation) || Observable.of();
});
}
else {
ret = new ApolloLink(function (operation, forward) {
return test(operation) ?
leftLink.request(operation, forward) || Observable.of()
: rightLink.request(operation, forward) || Observable.of();
});
}
return Object.assign(ret, { left: leftLink, right: rightLink });
};
ApolloLink.execute = function (link, operation) {
return (link.request(createOperation(operation.context, transformOperation(validateOperation(operation)))) || Observable.of());
};
ApolloLink.concat = function (first, second) {
var firstLink = toLink(first);
if (isTerminating(firstLink)) {
globalThis.__DEV__ !== false && invariant.warn(35, firstLink);
return firstLink;
}
var nextLink = toLink(second);
var ret;
if (isTerminating(nextLink)) {
ret = new ApolloLink(function (operation) {
return firstLink.request(operation, function (op) { return nextLink.request(op) || Observable.of(); }) || Observable.of();
});
}
else {
ret = new ApolloLink(function (operation, forward) {
return (firstLink.request(operation, function (op) {
return nextLink.request(op, forward) || Observable.of();
}) || Observable.of());
});
}
return Object.assign(ret, { left: firstLink, right: nextLink });
};
ApolloLink.prototype.split = function (test, left, right) {
return this.concat(ApolloLink.split(test, left, right || new ApolloLink(passthrough)));
};
ApolloLink.prototype.concat = function (next) {
return ApolloLink.concat(this, next);
};
ApolloLink.prototype.request = function (operation, forward) {
throw newInvariantError(36);
};
ApolloLink.prototype.onError = function (error, observer) {
if (observer && observer.error) {
observer.error(error);
// Returning false indicates that observer.error does not need to be
// called again, since it was already called (on the previous line).
// Calling observer.error again would not cause any real problems,
// since only the first call matters, but custom onError functions
// might have other reasons for wanting to prevent the default
// behavior by returning false.
return false;
}
// Throw errors will be passed to observer.error.
throw error;
};
ApolloLink.prototype.setOnError = function (fn) {
this.onError = fn;
return this;
};
return ApolloLink;
}());
export { ApolloLink };
//# sourceMappingURL=ApolloLink.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/link/utils/createOperation.js
import { __assign } from "tslib";
export function createOperation(starting, operation) {
var context = __assign({}, starting);
var setContext = function (next) {
if (typeof next === "function") {
context = __assign(__assign({}, context), next(context));
}
else {
context = __assign(__assign({}, context), next);
}
};
var getContext = function () { return (__assign({}, context)); };
Object.defineProperty(operation, "setContext", {
enumerable: false,
value: setContext,
});
Object.defineProperty(operation, "getContext", {
enumerable: false,
value: getContext,
});
return operation;
}
//# sourceMappingURL=createOperation.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/link/utils/transformOperation.js
import { getOperationName } from "../../utilities/index.js";
export function transformOperation(operation) {
var transformedOperation = {
variables: operation.variables || {},
extensions: operation.extensions || {},
operationName: operation.operationName,
query: operation.query,
};
// Best guess at an operation name
if (!transformedOperation.operationName) {
transformedOperation.operationName =
typeof transformedOperation.query !== "string" ?
getOperationName(transformedOperation.query) || undefined
: "";
}
return transformedOperation;
}
//# sourceMappingURL=transformOperation.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/link/utils/validateOperation.js
import { newInvariantError } from "../../utilities/globals/index.js";
export function validateOperation(operation) {
var OPERATION_FIELDS = [
"query",
"operationName",
"variables",
"extensions",
"context",
];
for (var _i = 0, _a = Object.keys(operation); _i < _a.length; _i++) {
var key = _a[_i];
if (OPERATION_FIELDS.indexOf(key) < 0) {
throw newInvariantError(43, key);
}
}
return operation;
}
//# sourceMappingURL=validateOperation.js.map
webpack://frontend-mybets/../../node_modules/graphql/jsutils/nodejsCustomInspectSymbol.mjs
// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')
var nodejsCustomInspectSymbol = typeof Symbol === 'function' && typeof Symbol.for === 'function' ? Symbol.for('nodejs.util.inspect.custom') : undefined;
export default nodejsCustomInspectSymbol;
webpack://frontend-mybets/../../node_modules/graphql/jsutils/inspect.mjs
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); }
/* eslint-disable flowtype/no-weak-types */
import nodejsCustomInspectSymbol from "./nodejsCustomInspectSymbol.mjs";
var MAX_ARRAY_LENGTH = 10;
var MAX_RECURSIVE_DEPTH = 2;
/**
* Used to print values in error messages.
*/
export default function inspect(value) {
return formatValue(value, []);
}
function formatValue(value, seenValues) {
switch (_typeof(value)) {
case 'string':
return JSON.stringify(value);
case 'function':
return value.name ? "[function ".concat(value.name, "]") : '[function]';
case 'object':
if (value === null) {
return 'null';
}
return formatObjectValue(value, seenValues);
default:
return String(value);
}
}
function formatObjectValue(value, previouslySeenValues) {
if (previouslySeenValues.indexOf(value) !== -1) {
return '[Circular]';
}
var seenValues = [].concat(previouslySeenValues, [value]);
var customInspectFn = getCustomFn(value);
if (customInspectFn !== undefined) {
var customValue = customInspectFn.call(value); // check for infinite recursion
if (customValue !== value) {
return typeof customValue === 'string' ? customValue : formatValue(customValue, seenValues);
}
} else if (Array.isArray(value)) {
return formatArray(value, seenValues);
}
return formatObject(value, seenValues);
}
function formatObject(object, seenValues) {
var keys = Object.keys(object);
if (keys.length === 0) {
return '{}';
}
if (seenValues.length > MAX_RECURSIVE_DEPTH) {
return '[' + getObjectTag(object) + ']';
}
var properties = keys.map(function (key) {
var value = formatValue(object[key], seenValues);
return key + ': ' + value;
});
return '{ ' + properties.join(', ') + ' }';
}
function formatArray(array, seenValues) {
if (array.length === 0) {
return '[]';
}
if (seenValues.length > MAX_RECURSIVE_DEPTH) {
return '[Array]';
}
var len = Math.min(MAX_ARRAY_LENGTH, array.length);
var remaining = array.length - len;
var items = [];
for (var i = 0; i < len; ++i) {
items.push(formatValue(array[i], seenValues));
}
if (remaining === 1) {
items.push('... 1 more item');
} else if (remaining > 1) {
items.push("... ".concat(remaining, " more items"));
}
return '[' + items.join(', ') + ']';
}
function getCustomFn(object) {
var customInspectFn = object[String(nodejsCustomInspectSymbol)];
if (typeof customInspectFn === 'function') {
return customInspectFn;
}
if (typeof object.inspect === 'function') {
return object.inspect;
}
}
function getObjectTag(object) {
var tag = Object.prototype.toString.call(object).replace(/^\[object /, '').replace(/]$/, '');
if (tag === 'Object' && typeof object.constructor === 'function') {
var name = object.constructor.name;
if (typeof name === 'string' && name !== '') {
return name;
}
}
return tag;
}
webpack://frontend-mybets/../../node_modules/graphql/jsutils/defineInspect.mjs
import invariant from "./invariant.mjs";
import nodejsCustomInspectSymbol from "./nodejsCustomInspectSymbol.mjs";
/**
* The `defineInspect()` function defines `inspect()` prototype method as alias of `toJSON`
*/
export default function defineInspect(classObject) {
var fn = classObject.prototype.toJSON;
typeof fn === 'function' || invariant(0);
classObject.prototype.inspect = fn; // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2317')
if (nodejsCustomInspectSymbol) {
classObject.prototype[nodejsCustomInspectSymbol] = fn;
}
}
webpack://frontend-mybets/../../node_modules/graphql/jsutils/invariant.mjs
export default function invariant(condition, message) {
var booleanCondition = Boolean(condition); // istanbul ignore else (See transformation done in './resources/inlineInvariant.js')
if (!booleanCondition) {
throw new Error(message != null ? message : 'Unexpected invariant triggered.');
}
}
webpack://frontend-mybets/../../node_modules/graphql/language/ast.mjs
import defineInspect from "../jsutils/defineInspect.mjs";
/**
* Contains a range of UTF-8 character offsets and token references that
* identify the region of the source from which the AST derived.
*/
export var Location = /*#__PURE__*/function () {
/**
* The character offset at which this Node begins.
*/
/**
* The character offset at which this Node ends.
*/
/**
* The Token at which this Node begins.
*/
/**
* The Token at which this Node ends.
*/
/**
* The Source document the AST represents.
*/
function Location(startToken, endToken, source) {
this.start = startToken.start;
this.end = endToken.end;
this.startToken = startToken;
this.endToken = endToken;
this.source = source;
}
var _proto = Location.prototype;
_proto.toJSON = function toJSON() {
return {
start: this.start,
end: this.end
};
};
return Location;
}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.
defineInspect(Location);
/**
* Represents a range of characters represented by a lexical token
* within a Source.
*/
export var Token = /*#__PURE__*/function () {
/**
* The kind of Token.
*/
/**
* The character offset at which this Node begins.
*/
/**
* The character offset at which this Node ends.
*/
/**
* The 1-indexed line number on which this Token appears.
*/
/**
* The 1-indexed column number at which this Token begins.
*/
/**
* For non-punctuation tokens, represents the interpreted value of the token.
*/
/**
* Tokens exist as nodes in a double-linked-list amongst all tokens
* including ignored tokens. <SOF> is always the first node and <EOF>
* the last.
*/
function Token(kind, start, end, line, column, prev, value) {
this.kind = kind;
this.start = start;
this.end = end;
this.line = line;
this.column = column;
this.value = value;
this.prev = prev;
this.next = null;
}
var _proto2 = Token.prototype;
_proto2.toJSON = function toJSON() {
return {
kind: this.kind,
value: this.value,
line: this.line,
column: this.column
};
};
return Token;
}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.
defineInspect(Token);
/**
* @internal
*/
export function isNode(maybeNode) {
return maybeNode != null && typeof maybeNode.kind === 'string';
}
/**
* The list of all possible AST node types.
*/
webpack://frontend-mybets/../../node_modules/graphql/language/visitor.mjs
import inspect from "../jsutils/inspect.mjs";
import { isNode } from "./ast.mjs";
/**
* A visitor is provided to visit, it contains the collection of
* relevant functions to be called during the visitor's traversal.
*/
export var QueryDocumentKeys = {
Name: [],
Document: ['definitions'],
OperationDefinition: ['name', 'variableDefinitions', 'directives', 'selectionSet'],
VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'],
Variable: ['name'],
SelectionSet: ['selections'],
Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'],
Argument: ['name', 'value'],
FragmentSpread: ['name', 'directives'],
InlineFragment: ['typeCondition', 'directives', 'selectionSet'],
FragmentDefinition: ['name', // Note: fragment variable definitions are experimental and may be changed
// or removed in the future.
'variableDefinitions', 'typeCondition', 'directives', 'selectionSet'],
IntValue: [],
FloatValue: [],
StringValue: [],
BooleanValue: [],
NullValue: [],
EnumValue: [],
ListValue: ['values'],
ObjectValue: ['fields'],
ObjectField: ['name', 'value'],
Directive: ['name', 'arguments'],
NamedType: ['name'],
ListType: ['type'],
NonNullType: ['type'],
SchemaDefinition: ['description', 'directives', 'operationTypes'],
OperationTypeDefinition: ['type'],
ScalarTypeDefinition: ['description', 'name', 'directives'],
ObjectTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'],
FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'],
InputValueDefinition: ['description', 'name', 'type', 'defaultValue', 'directives'],
InterfaceTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'],
UnionTypeDefinition: ['description', 'name', 'directives', 'types'],
EnumTypeDefinition: ['description', 'name', 'directives', 'values'],
EnumValueDefinition: ['description', 'name', 'directives'],
InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'],
DirectiveDefinition: ['description', 'name', 'arguments', 'locations'],
SchemaExtension: ['directives', 'operationTypes'],
ScalarTypeExtension: ['name', 'directives'],
ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'],
InterfaceTypeExtension: ['name', 'interfaces', 'directives', 'fields'],
UnionTypeExtension: ['name', 'directives', 'types'],
EnumTypeExtension: ['name', 'directives', 'values'],
InputObjectTypeExtension: ['name', 'directives', 'fields']
};
export var BREAK = Object.freeze({});
/**
* visit() will walk through an AST using a depth-first traversal, calling
* the visitor's enter function at each node in the traversal, and calling the
* leave function after visiting that node and all of its child nodes.
*
* By returning different values from the enter and leave functions, the
* behavior of the visitor can be altered, including skipping over a sub-tree of
* the AST (by returning false), editing the AST by returning a value or null
* to remove the value, or to stop the whole traversal by returning BREAK.
*
* When using visit() to edit an AST, the original AST will not be modified, and
* a new version of the AST with the changes applied will be returned from the
* visit function.
*
* const editedAST = visit(ast, {
* enter(node, key, parent, path, ancestors) {
* // @return
* // undefined: no action
* // false: skip visiting this node
* // visitor.BREAK: stop visiting altogether
* // null: delete this node
* // any value: replace this node with the returned value
* },
* leave(node, key, parent, path, ancestors) {
* // @return
* // undefined: no action
* // false: no action
* // visitor.BREAK: stop visiting altogether
* // null: delete this node
* // any value: replace this node with the returned value
* }
* });
*
* Alternatively to providing enter() and leave() functions, a visitor can
* instead provide functions named the same as the kinds of AST nodes, or
* enter/leave visitors at a named key, leading to four permutations of the
* visitor API:
*
* 1) Named visitors triggered when entering a node of a specific kind.
*
* visit(ast, {
* Kind(node) {
* // enter the "Kind" node
* }
* })
*
* 2) Named visitors that trigger upon entering and leaving a node of
* a specific kind.
*
* visit(ast, {
* Kind: {
* enter(node) {
* // enter the "Kind" node
* }
* leave(node) {
* // leave the "Kind" node
* }
* }
* })
*
* 3) Generic visitors that trigger upon entering and leaving any node.
*
* visit(ast, {
* enter(node) {
* // enter any node
* },
* leave(node) {
* // leave any node
* }
* })
*
* 4) Parallel visitors for entering and leaving nodes of a specific kind.
*
* visit(ast, {
* enter: {
* Kind(node) {
* // enter the "Kind" node
* }
* },
* leave: {
* Kind(node) {
* // leave the "Kind" node
* }
* }
* })
*/
export function visit(root, visitor) {
var visitorKeys = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : QueryDocumentKeys;
/* eslint-disable no-undef-init */
var stack = undefined;
var inArray = Array.isArray(root);
var keys = [root];
var index = -1;
var edits = [];
var node = undefined;
var key = undefined;
var parent = undefined;
var path = [];
var ancestors = [];
var newRoot = root;
/* eslint-enable no-undef-init */
do {
index++;
var isLeaving = index === keys.length;
var isEdited = isLeaving && edits.length !== 0;
if (isLeaving) {
key = ancestors.length === 0 ? undefined : path[path.length - 1];
node = parent;
parent = ancestors.pop();
if (isEdited) {
if (inArray) {
node = node.slice();
} else {
var clone = {};
for (var _i2 = 0, _Object$keys2 = Object.keys(node); _i2 < _Object$keys2.length; _i2++) {
var k = _Object$keys2[_i2];
clone[k] = node[k];
}
node = clone;
}
var editOffset = 0;
for (var ii = 0; ii < edits.length; ii++) {
var editKey = edits[ii][0];
var editValue = edits[ii][1];
if (inArray) {
editKey -= editOffset;
}
if (inArray && editValue === null) {
node.splice(editKey, 1);
editOffset++;
} else {
node[editKey] = editValue;
}
}
}
index = stack.index;
keys = stack.keys;
edits = stack.edits;
inArray = stack.inArray;
stack = stack.prev;
} else {
key = parent ? inArray ? index : keys[index] : undefined;
node = parent ? parent[key] : newRoot;
if (node === null || node === undefined) {
continue;
}
if (parent) {
path.push(key);
}
}
var result = void 0;
if (!Array.isArray(node)) {
if (!isNode(node)) {
throw new Error("Invalid AST Node: ".concat(inspect(node), "."));
}
var visitFn = getVisitFn(visitor, node.kind, isLeaving);
if (visitFn) {
result = visitFn.call(visitor, node, key, parent, path, ancestors);
if (result === BREAK) {
break;
}
if (result === false) {
if (!isLeaving) {
path.pop();
continue;
}
} else if (result !== undefined) {
edits.push([key, result]);
if (!isLeaving) {
if (isNode(result)) {
node = result;
} else {
path.pop();
continue;
}
}
}
}
}
if (result === undefined && isEdited) {
edits.push([key, node]);
}
if (isLeaving) {
path.pop();
} else {
var _visitorKeys$node$kin;
stack = {
inArray: inArray,
index: index,
keys: keys,
edits: edits,
prev: stack
};
inArray = Array.isArray(node);
keys = inArray ? node : (_visitorKeys$node$kin = visitorKeys[node.kind]) !== null && _visitorKeys$node$kin !== void 0 ? _visitorKeys$node$kin : [];
index = -1;
edits = [];
if (parent) {
ancestors.push(parent);
}
parent = node;
}
} while (stack !== undefined);
if (edits.length !== 0) {
newRoot = edits[edits.length - 1][1];
}
return newRoot;
}
/**
* Creates a new visitor instance which delegates to many visitors to run in
* parallel. Each visitor will be visited for each node before moving on.
*
* If a prior visitor edits a node, no following visitors will see that node.
*/
export function visitInParallel(visitors) {
var skipping = new Array(visitors.length);
return {
enter: function enter(node) {
for (var i = 0; i < visitors.length; i++) {
if (skipping[i] == null) {
var fn = getVisitFn(visitors[i], node.kind,
/* isLeaving */
false);
if (fn) {
var result = fn.apply(visitors[i], arguments);
if (result === false) {
skipping[i] = node;
} else if (result === BREAK) {
skipping[i] = BREAK;
} else if (result !== undefined) {
return result;
}
}
}
}
},
leave: function leave(node) {
for (var i = 0; i < visitors.length; i++) {
if (skipping[i] == null) {
var fn = getVisitFn(visitors[i], node.kind,
/* isLeaving */
true);
if (fn) {
var result = fn.apply(visitors[i], arguments);
if (result === BREAK) {
skipping[i] = BREAK;
} else if (result !== undefined && result !== false) {
return result;
}
}
} else if (skipping[i] === node) {
skipping[i] = null;
}
}
}
};
}
/**
* Given a visitor instance, if it is leaving or not, and a node kind, return
* the function the visitor runtime should call.
*/
export function getVisitFn(visitor, kind, isLeaving) {
var kindVisitor = visitor[kind];
if (kindVisitor) {
if (!isLeaving && typeof kindVisitor === 'function') {
// { Kind() {} }
return kindVisitor;
}
var kindSpecificVisitor = isLeaving ? kindVisitor.leave : kindVisitor.enter;
if (typeof kindSpecificVisitor === 'function') {
// { Kind: { enter() {}, leave() {} } }
return kindSpecificVisitor;
}
} else {
var specificVisitor = isLeaving ? visitor.leave : visitor.enter;
if (specificVisitor) {
if (typeof specificVisitor === 'function') {
// { enter() {}, leave() {} }
return specificVisitor;
}
var specificKindVisitor = specificVisitor[kind];
if (typeof specificKindVisitor === 'function') {
// { enter: { Kind() {} }, leave: { Kind() {} } }
return specificKindVisitor;
}
}
}
}
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/graphql/directives.js
import { invariant } from "../globals/index.js";
import { visit, BREAK } from "graphql";
export function shouldInclude(_a, variables) {
var directives = _a.directives;
if (!directives || !directives.length) {
return true;
}
return getInclusionDirectives(directives).every(function (_a) {
var directive = _a.directive, ifArgument = _a.ifArgument;
var evaledValue = false;
if (ifArgument.value.kind === "Variable") {
evaledValue =
variables && variables[ifArgument.value.name.value];
invariant(evaledValue !== void 0, 67, directive.name.value);
}
else {
evaledValue = ifArgument.value.value;
}
return directive.name.value === "skip" ? !evaledValue : evaledValue;
});
}
export function getDirectiveNames(root) {
var names = [];
visit(root, {
Directive: function (node) {
names.push(node.name.value);
},
});
return names;
}
export var hasAnyDirectives = function (names, root) {
return hasDirectives(names, root, false);
};
export var hasAllDirectives = function (names, root) {
return hasDirectives(names, root, true);
};
export function hasDirectives(names, root, all) {
var nameSet = new Set(names);
var uniqueCount = nameSet.size;
visit(root, {
Directive: function (node) {
if (nameSet.delete(node.name.value) && (!all || !nameSet.size)) {
return BREAK;
}
},
});
// If we found all the names, nameSet will be empty. If we only care about
// finding some of them, the < condition is sufficient.
return all ? !nameSet.size : nameSet.size < uniqueCount;
}
export function hasClientExports(document) {
return document && hasDirectives(["client", "export"], document, true);
}
function isInclusionDirective(_a) {
var value = _a.name.value;
return value === "skip" || value === "include";
}
export function getInclusionDirectives(directives) {
var result = [];
if (directives && directives.length) {
directives.forEach(function (directive) {
if (!isInclusionDirective(directive))
return;
var directiveArguments = directive.arguments;
var directiveName = directive.name.value;
invariant(directiveArguments && directiveArguments.length === 1, 68, directiveName);
var ifArgument = directiveArguments[0];
invariant(ifArgument.name && ifArgument.name.value === "if", 69, directiveName);
var ifValue = ifArgument.value;
// means it has to be a variable value if this is a valid @skip or @include directive
invariant(ifValue &&
(ifValue.kind === "Variable" || ifValue.kind === "BooleanValue"), 70, directiveName);
result.push({ directive: directive, ifArgument: ifArgument });
});
}
return result;
}
//# sourceMappingURL=directives.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/link/http/serializeFetchParameter.js
import { newInvariantError } from "../../utilities/globals/index.js";
export var serializeFetchParameter = function (p, label) {
var serialized;
try {
serialized = JSON.stringify(p);
}
catch (e) {
var parseError = newInvariantError(39, label, e.message);
parseError.parseError = e;
throw parseError;
}
return serialized;
};
//# sourceMappingURL=serializeFetchParameter.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/link/http/iterators/reader.js
/**
* Original source:
* https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/reader.ts
*/
import { canUseAsyncIteratorSymbol } from "../../../utilities/index.js";
export default function readerIterator(reader) {
var iterator = {
next: function () {
return reader.read();
},
};
if (canUseAsyncIteratorSymbol) {
iterator[Symbol.asyncIterator] = function () {
return this;
};
}
return iterator;
}
//# sourceMappingURL=reader.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/link/http/responseIterator.js
/**
* Original source:
* https://github.com/kmalakoff/response-iterator/blob/master/src/index.ts
*/
import { canUseAsyncIteratorSymbol } from "../../utilities/index.js";
import asyncIterator from "./iterators/async.js";
import nodeStreamIterator from "./iterators/nodeStream.js";
import promiseIterator from "./iterators/promise.js";
import readerIterator from "./iterators/reader.js";
function isNodeResponse(value) {
return !!value.body;
}
function isReadableStream(value) {
return !!value.getReader;
}
function isAsyncIterableIterator(value) {
return !!(canUseAsyncIteratorSymbol &&
value[Symbol.asyncIterator]);
}
function isStreamableBlob(value) {
return !!value.stream;
}
function isBlob(value) {
return !!value.arrayBuffer;
}
function isNodeReadableStream(value) {
return !!value.pipe;
}
export function responseIterator(response) {
var body = response;
if (isNodeResponse(response))
body = response.body;
if (isAsyncIterableIterator(body))
return asyncIterator(body);
if (isReadableStream(body))
return readerIterator(body.getReader());
// this errors without casting to ReadableStream<T>
// because Blob.stream() returns a NodeJS ReadableStream
if (isStreamableBlob(body)) {
return readerIterator(body.stream().getReader());
}
if (isBlob(body))
return promiseIterator(body.arrayBuffer());
if (isNodeReadableStream(body))
return nodeStreamIterator(body);
throw new Error("Unknown body type for responseIterator. Please pass a streamable response.");
}
//# sourceMappingURL=responseIterator.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/link/http/iterators/promise.js
/**
* Original source:
* https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/promise.ts
*/
import { canUseAsyncIteratorSymbol } from "../../../utilities/index.js";
export default function promiseIterator(promise) {
var resolved = false;
var iterator = {
next: function () {
if (resolved)
return Promise.resolve({
value: undefined,
done: true,
});
resolved = true;
return new Promise(function (resolve, reject) {
promise
.then(function (value) {
resolve({ value: value, done: false });
})
.catch(reject);
});
},
};
if (canUseAsyncIteratorSymbol) {
iterator[Symbol.asyncIterator] = function () {
return this;
};
}
return iterator;
}
//# sourceMappingURL=promise.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/link/http/iterators/async.js
/**
* Original source:
* https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/async.ts
*/
export default function asyncIterator(source) {
var _a;
var iterator = source[Symbol.asyncIterator]();
return _a = {
next: function () {
return iterator.next();
}
},
_a[Symbol.asyncIterator] = function () {
return this;
},
_a;
}
//# sourceMappingURL=async.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/link/http/iterators/nodeStream.js
/**
* Original source:
* https://github.com/kmalakoff/response-iterator/blob/master/src/iterators/nodeStream.ts
*/
import { canUseAsyncIteratorSymbol } from "../../../utilities/index.js";
export default function nodeStreamIterator(stream) {
var cleanup = null;
var error = null;
var done = false;
var data = [];
var waiting = [];
function onData(chunk) {
if (error)
return;
if (waiting.length) {
var shiftedArr = waiting.shift();
if (Array.isArray(shiftedArr) && shiftedArr[0]) {
return shiftedArr[0]({ value: chunk, done: false });
}
}
data.push(chunk);
}
function onError(err) {
error = err;
var all = waiting.slice();
all.forEach(function (pair) {
pair[1](err);
});
!cleanup || cleanup();
}
function onEnd() {
done = true;
var all = waiting.slice();
all.forEach(function (pair) {
pair[0]({ value: undefined, done: true });
});
!cleanup || cleanup();
}
cleanup = function () {
cleanup = null;
stream.removeListener("data", onData);
stream.removeListener("error", onError);
stream.removeListener("end", onEnd);
stream.removeListener("finish", onEnd);
stream.removeListener("close", onEnd);
};
stream.on("data", onData);
stream.on("error", onError);
stream.on("end", onEnd);
stream.on("finish", onEnd);
stream.on("close", onEnd);
function getNext() {
return new Promise(function (resolve, reject) {
if (error)
return reject(error);
if (data.length)
return resolve({ value: data.shift(), done: false });
if (done)
return resolve({ value: undefined, done: true });
waiting.push([resolve, reject]);
});
}
var iterator = {
next: function () {
return getNext();
},
};
if (canUseAsyncIteratorSymbol) {
iterator[Symbol.asyncIterator] = function () {
return this;
};
}
return iterator;
}
//# sourceMappingURL=nodeStream.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/link/utils/throwServerError.js
export var throwServerError = function (response, result, message) {
var error = new Error(message);
error.name = "ServerError";
error.response = response;
error.statusCode = response.status;
error.result = result;
throw error;
};
//# sourceMappingURL=throwServerError.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/errors/index.js
import { __extends, __spreadArray } from "tslib";
import "../utilities/globals/index.js";
import { isNonNullObject } from "../utilities/index.js";
// This Symbol allows us to pass transport-specific errors from the link chain
// into QueryManager/client internals without risking a naming collision within
// extensions (which implementers can use as they see fit).
export var PROTOCOL_ERRORS_SYMBOL = Symbol();
export function graphQLResultHasProtocolErrors(result) {
if (result.extensions) {
return Array.isArray(result.extensions[PROTOCOL_ERRORS_SYMBOL]);
}
return false;
}
export function isApolloError(err) {
return err.hasOwnProperty("graphQLErrors");
}
// Sets the error message on this error according to the
// the GraphQL and network errors that are present.
// If the error message has already been set through the
// constructor or otherwise, this function is a nop.
var generateErrorMessage = function (err) {
var errors = __spreadArray(__spreadArray(__spreadArray([], err.graphQLErrors, true), err.clientErrors, true), err.protocolErrors, true);
if (err.networkError)
errors.push(err.networkError);
return (errors
// The rest of the code sometimes unsafely types non-Error objects as GraphQLErrors
.map(function (err) {
return (isNonNullObject(err) && err.message) || "Error message not found.";
})
.join("\n"));
};
var ApolloError = /** @class */ (function (_super) {
__extends(ApolloError, _super);
// Constructs an instance of ApolloError given a GraphQLError
// or a network error. Note that one of these has to be a valid
// value or the constructed error will be meaningless.
function ApolloError(_a) {
var graphQLErrors = _a.graphQLErrors, protocolErrors = _a.protocolErrors, clientErrors = _a.clientErrors, networkError = _a.networkError, errorMessage = _a.errorMessage, extraInfo = _a.extraInfo;
var _this = _super.call(this, errorMessage) || this;
_this.name = "ApolloError";
_this.graphQLErrors = graphQLErrors || [];
_this.protocolErrors = protocolErrors || [];
_this.clientErrors = clientErrors || [];
_this.networkError = networkError || null;
_this.message = errorMessage || generateErrorMessage(_this);
_this.extraInfo = extraInfo;
// We're not using `Object.setPrototypeOf` here as it isn't fully
// supported on Android (see issue #3236).
_this.__proto__ = ApolloError.prototype;
return _this;
}
return ApolloError;
}(Error));
export { ApolloError };
//# sourceMappingURL=index.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/common/arrays.js
// A version of Array.isArray that works better with readonly arrays.
export var isArray = Array.isArray;
export function isNonEmptyArray(value) {
return Array.isArray(value) && value.length > 0;
}
//# sourceMappingURL=arrays.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/common/mergeDeep.js
import { __assign, __spreadArray } from "tslib";
import { isNonNullObject } from "./objects.js";
var hasOwnProperty = Object.prototype.hasOwnProperty;
export function mergeDeep() {
var sources = [];
for (var _i = 0; _i < arguments.length; _i++) {
sources[_i] = arguments[_i];
}
return mergeDeepArray(sources);
}
// In almost any situation where you could succeed in getting the
// TypeScript compiler to infer a tuple type for the sources array, you
// could just use mergeDeep instead of mergeDeepArray, so instead of
// trying to convert T[] to an intersection type we just infer the array
// element type, which works perfectly when the sources array has a
// consistent element type.
export function mergeDeepArray(sources) {
var target = sources[0] || {};
var count = sources.length;
if (count > 1) {
var merger = new DeepMerger();
for (var i = 1; i < count; ++i) {
target = merger.merge(target, sources[i]);
}
}
return target;
}
var defaultReconciler = function (target, source, property) {
return this.merge(target[property], source[property]);
};
var DeepMerger = /** @class */ (function () {
function DeepMerger(reconciler) {
if (reconciler === void 0) { reconciler = defaultReconciler; }
this.reconciler = reconciler;
this.isObject = isNonNullObject;
this.pastCopies = new Set();
}
DeepMerger.prototype.merge = function (target, source) {
var _this = this;
var context = [];
for (var _i = 2; _i < arguments.length; _i++) {
context[_i - 2] = arguments[_i];
}
if (isNonNullObject(source) && isNonNullObject(target)) {
Object.keys(source).forEach(function (sourceKey) {
if (hasOwnProperty.call(target, sourceKey)) {
var targetValue = target[sourceKey];
if (source[sourceKey] !== targetValue) {
var result = _this.reconciler.apply(_this, __spreadArray([target,
source,
sourceKey], context, false));
// A well-implemented reconciler may return targetValue to indicate
// the merge changed nothing about the structure of the target.
if (result !== targetValue) {
target = _this.shallowCopyForMerge(target);
target[sourceKey] = result;
}
}
}
else {
// If there is no collision, the target can safely share memory with
// the source, and the recursion can terminate here.
target = _this.shallowCopyForMerge(target);
target[sourceKey] = source[sourceKey];
}
});
return target;
}
// If source (or target) is not an object, let source replace target.
return source;
};
DeepMerger.prototype.shallowCopyForMerge = function (value) {
if (isNonNullObject(value)) {
if (!this.pastCopies.has(value)) {
if (Array.isArray(value)) {
value = value.slice(0);
}
else {
value = __assign({ __proto__: Object.getPrototypeOf(value) }, value);
}
this.pastCopies.add(value);
}
}
return value;
};
return DeepMerger;
}());
export { DeepMerger };
//# sourceMappingURL=mergeDeep.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/common/incrementalResult.js
import { isNonNullObject } from "./objects.js";
import { isNonEmptyArray } from "./arrays.js";
import { DeepMerger } from "./mergeDeep.js";
export function isExecutionPatchIncrementalResult(value) {
return "incremental" in value;
}
export function isExecutionPatchInitialResult(value) {
return "hasNext" in value && "data" in value;
}
export function isExecutionPatchResult(value) {
return (isExecutionPatchIncrementalResult(value) ||
isExecutionPatchInitialResult(value));
}
// This function detects an Apollo payload result before it is transformed
// into a FetchResult via HttpLink; it cannot detect an ApolloPayloadResult
// once it leaves the link chain.
export function isApolloPayloadResult(value) {
return isNonNullObject(value) && "payload" in value;
}
export function mergeIncrementalData(prevResult, result) {
var mergedData = prevResult;
var merger = new DeepMerger();
if (isExecutionPatchIncrementalResult(result) &&
isNonEmptyArray(result.incremental)) {
result.incremental.forEach(function (_a) {
var data = _a.data, path = _a.path;
for (var i = path.length - 1; i >= 0; --i) {
var key = path[i];
var isNumericKey = !isNaN(+key);
var parent_1 = isNumericKey ? [] : {};
parent_1[key] = data;
data = parent_1;
}
mergedData = merger.merge(mergedData, data);
});
}
return mergedData;
}
//# sourceMappingURL=incrementalResult.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/link/http/parseAndCheckHttpResponse.js
import { __assign, __awaiter, __generator } from "tslib";
import { responseIterator } from "./responseIterator.js";
import { throwServerError } from "../utils/index.js";
import { PROTOCOL_ERRORS_SYMBOL } from "../../errors/index.js";
import { isApolloPayloadResult } from "../../utilities/common/incrementalResult.js";
var hasOwnProperty = Object.prototype.hasOwnProperty;
export function readMultipartBody(response, nextValue) {
var _a;
return __awaiter(this, void 0, void 0, function () {
var decoder, contentType, delimiter, boundaryVal, boundary, buffer, iterator, running, _b, value, done, chunk, searchFrom, bi, message, i, headers, contentType_1, body, result, next;
var _c, _d;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
if (TextDecoder === undefined) {
throw new Error("TextDecoder must be defined in the environment: please import a polyfill.");
}
decoder = new TextDecoder("utf-8");
contentType = (_a = response.headers) === null || _a === void 0 ? void 0 : _a.get("content-type");
delimiter = "boundary=";
boundaryVal = (contentType === null || contentType === void 0 ? void 0 : contentType.includes(delimiter)) ?
contentType === null || contentType === void 0 ? void 0 : contentType.substring((contentType === null || contentType === void 0 ? void 0 : contentType.indexOf(delimiter)) + delimiter.length).replace(/['"]/g, "").replace(/\;(.*)/gm, "").trim()
: "-";
boundary = "\r\n--".concat(boundaryVal);
buffer = "";
iterator = responseIterator(response);
running = true;
_e.label = 1;
case 1:
if (!running) return [3 /*break*/, 3];
return [4 /*yield*/, iterator.next()];
case 2:
_b = _e.sent(), value = _b.value, done = _b.done;
chunk = typeof value === "string" ? value : decoder.decode(value);
searchFrom = buffer.length - boundary.length + 1;
running = !done;
buffer += chunk;
bi = buffer.indexOf(boundary, searchFrom);
while (bi > -1) {
message = void 0;
_c = [
buffer.slice(0, bi),
buffer.slice(bi + boundary.length),
], message = _c[0], buffer = _c[1];
i = message.indexOf("\r\n\r\n");
headers = parseHeaders(message.slice(0, i));
contentType_1 = headers["content-type"];
if (contentType_1 &&
contentType_1.toLowerCase().indexOf("application/json") === -1) {
throw new Error("Unsupported patch content type: application/json is required.");
}
body = message.slice(i);
if (body) {
result = parseJsonBody(response, body);
if (Object.keys(result).length > 1 ||
"data" in result ||
"incremental" in result ||
"errors" in result ||
"payload" in result) {
if (isApolloPayloadResult(result)) {
next = {};
if ("payload" in result) {
next = __assign({}, result.payload);
}
if ("errors" in result) {
next = __assign(__assign({}, next), { extensions: __assign(__assign({}, ("extensions" in next ? next.extensions : null)), (_d = {}, _d[PROTOCOL_ERRORS_SYMBOL] = result.errors, _d)) });
}
nextValue(next);
}
else {
// for the last chunk with only `hasNext: false`
// we don't need to call observer.next as there is no data/errors
nextValue(result);
}
}
else if (
// If the chunk contains only a "hasNext: false", we can call
// observer.complete() immediately.
Object.keys(result).length === 1 &&
"hasNext" in result &&
!result.hasNext) {
return [2 /*return*/];
}
}
bi = buffer.indexOf(boundary);
}
return [3 /*break*/, 1];
case 3: return [2 /*return*/];
}
});
});
}
export function parseHeaders(headerText) {
var headersInit = {};
headerText.split("\n").forEach(function (line) {
var i = line.indexOf(":");
if (i > -1) {
// normalize headers to lowercase
var name_1 = line.slice(0, i).trim().toLowerCase();
var value = line.slice(i + 1).trim();
headersInit[name_1] = value;
}
});
return headersInit;
}
export function parseJsonBody(response, bodyText) {
if (response.status >= 300) {
// Network error
var getResult = function () {
try {
return JSON.parse(bodyText);
}
catch (err) {
return bodyText;
}
};
throwServerError(response, getResult(), "Response not successful: Received status code ".concat(response.status));
}
try {
return JSON.parse(bodyText);
}
catch (err) {
var parseError = err;
parseError.name = "ServerParseError";
parseError.response = response;
parseError.statusCode = response.status;
parseError.bodyText = bodyText;
throw parseError;
}
}
export function handleError(err, observer) {
// if it is a network error, BUT there is graphql result info fire
// the next observer before calling error this gives apollo-client
// (and react-apollo) the `graphqlErrors` and `networkErrors` to
// pass to UI this should only happen if we *also* have data as
// part of the response key per the spec
if (err.result && err.result.errors && err.result.data) {
// if we don't call next, the UI can only show networkError
// because AC didn't get any graphqlErrors this is graphql
// execution result info (i.e errors and possibly data) this is
// because there is no formal spec how errors should translate to
// http status codes. So an auth error (401) could have both data
// from a public field, errors from a private field, and a status
// of 401
// {
// user { // this will have errors
// firstName
// }
// products { // this is public so will have data
// cost
// }
// }
//
// the result of above *could* look like this:
// {
// data: { products: [{ cost: "$10" }] },
// errors: [{
// message: 'your session has timed out',
// path: []
// }]
// }
// status code of above would be a 401
// in the UI you want to show data where you can, errors as data where you can
// and use correct http status codes
observer.next(err.result);
}
observer.error(err);
}
export function parseAndCheckHttpResponse(operations) {
return function (response) {
return response
.text()
.then(function (bodyText) { return parseJsonBody(response, bodyText); })
.then(function (result) {
if (!Array.isArray(result) &&
!hasOwnProperty.call(result, "data") &&
!hasOwnProperty.call(result, "errors")) {
// Data error
throwServerError(response, result, "Server response was missing for query '".concat(Array.isArray(operations) ?
operations.map(function (op) { return op.operationName; })
: operations.operationName, "'."));
}
return result;
});
};
}
//# sourceMappingURL=parseAndCheckHttpResponse.js.map
webpack://frontend-mybets/../../node_modules/graphql/language/blockString.mjs
/**
* Produces the value of a block string from its parsed raw value, similar to
* CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc.
*
* This implements the GraphQL spec's BlockStringValue() static algorithm.
*
* @internal
*/
export function dedentBlockStringValue(rawString) {
// Expand a block string's raw value into independent lines.
var lines = rawString.split(/\r\n|[\n\r]/g); // Remove common indentation from all lines but first.
var commonIndent = getBlockStringIndentation(rawString);
if (commonIndent !== 0) {
for (var i = 1; i < lines.length; i++) {
lines[i] = lines[i].slice(commonIndent);
}
} // Remove leading and trailing blank lines.
var startLine = 0;
while (startLine < lines.length && isBlank(lines[startLine])) {
++startLine;
}
var endLine = lines.length;
while (endLine > startLine && isBlank(lines[endLine - 1])) {
--endLine;
} // Return a string of the lines joined with U+000A.
return lines.slice(startLine, endLine).join('\n');
}
function isBlank(str) {
for (var i = 0; i < str.length; ++i) {
if (str[i] !== ' ' && str[i] !== '\t') {
return false;
}
}
return true;
}
/**
* @internal
*/
export function getBlockStringIndentation(value) {
var _commonIndent;
var isFirstLine = true;
var isEmptyLine = true;
var indent = 0;
var commonIndent = null;
for (var i = 0; i < value.length; ++i) {
switch (value.charCodeAt(i)) {
case 13:
// \r
if (value.charCodeAt(i + 1) === 10) {
++i; // skip \r\n as one symbol
}
// falls through
case 10:
// \n
isFirstLine = false;
isEmptyLine = true;
indent = 0;
break;
case 9: // \t
case 32:
// <space>
++indent;
break;
default:
if (isEmptyLine && !isFirstLine && (commonIndent === null || indent < commonIndent)) {
commonIndent = indent;
}
isEmptyLine = false;
}
}
return (_commonIndent = commonIndent) !== null && _commonIndent !== void 0 ? _commonIndent : 0;
}
/**
* Print a block string in the indented block form by adding a leading and
* trailing blank line. However, if a block string starts with whitespace and is
* a single-line, adding a leading blank line would strip that whitespace.
*
* @internal
*/
export function printBlockString(value) {
var indentation = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var preferMultipleLines = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var isSingleLine = value.indexOf('\n') === -1;
var hasLeadingSpace = value[0] === ' ' || value[0] === '\t';
var hasTrailingQuote = value[value.length - 1] === '"';
var hasTrailingSlash = value[value.length - 1] === '\\';
var printAsMultipleLines = !isSingleLine || hasTrailingQuote || hasTrailingSlash || preferMultipleLines;
var result = ''; // Format a multi-line block quote to account for leading space.
if (printAsMultipleLines && !(isSingleLine && hasLeadingSpace)) {
result += '\n' + indentation;
}
result += indentation ? value.replace(/\n/g, '\n' + indentation) : value;
if (printAsMultipleLines) {
result += '\n';
}
return '"""' + result.replace(/"""/g, '\\"""') + '"""';
}
webpack://frontend-mybets/../../node_modules/graphql/language/printer.mjs
import { visit } from "./visitor.mjs";
import { printBlockString } from "./blockString.mjs";
/**
* Converts an AST into a string, using one set of reasonable
* formatting rules.
*/
export function print(ast) {
return visit(ast, {
leave: printDocASTReducer
});
}
var MAX_LINE_LENGTH = 80; // TODO: provide better type coverage in future
var printDocASTReducer = {
Name: function Name(node) {
return node.value;
},
Variable: function Variable(node) {
return '$' + node.name;
},
// Document
Document: function Document(node) {
return join(node.definitions, '\n\n') + '\n';
},
OperationDefinition: function OperationDefinition(node) {
var op = node.operation;
var name = node.name;
var varDefs = wrap('(', join(node.variableDefinitions, ', '), ')');
var directives = join(node.directives, ' ');
var selectionSet = node.selectionSet; // Anonymous queries with no directives or variable definitions can use
// the query short form.
return !name && !directives && !varDefs && op === 'query' ? selectionSet : join([op, join([name, varDefs]), directives, selectionSet], ' ');
},
VariableDefinition: function VariableDefinition(_ref) {
var variable = _ref.variable,
type = _ref.type,
defaultValue = _ref.defaultValue,
directives = _ref.directives;
return variable + ': ' + type + wrap(' = ', defaultValue) + wrap(' ', join(directives, ' '));
},
SelectionSet: function SelectionSet(_ref2) {
var selections = _ref2.selections;
return block(selections);
},
Field: function Field(_ref3) {
var alias = _ref3.alias,
name = _ref3.name,
args = _ref3.arguments,
directives = _ref3.directives,
selectionSet = _ref3.selectionSet;
var prefix = wrap('', alias, ': ') + name;
var argsLine = prefix + wrap('(', join(args, ', '), ')');
if (argsLine.length > MAX_LINE_LENGTH) {
argsLine = prefix + wrap('(\n', indent(join(args, '\n')), '\n)');
}
return join([argsLine, join(directives, ' '), selectionSet], ' ');
},
Argument: function Argument(_ref4) {
var name = _ref4.name,
value = _ref4.value;
return name + ': ' + value;
},
// Fragments
FragmentSpread: function FragmentSpread(_ref5) {
var name = _ref5.name,
directives = _ref5.directives;
return '...' + name + wrap(' ', join(directives, ' '));
},
InlineFragment: function InlineFragment(_ref6) {
var typeCondition = _ref6.typeCondition,
directives = _ref6.directives,
selectionSet = _ref6.selectionSet;
return join(['...', wrap('on ', typeCondition), join(directives, ' '), selectionSet], ' ');
},
FragmentDefinition: function FragmentDefinition(_ref7) {
var name = _ref7.name,
typeCondition = _ref7.typeCondition,
variableDefinitions = _ref7.variableDefinitions,
directives = _ref7.directives,
selectionSet = _ref7.selectionSet;
return (// Note: fragment variable definitions are experimental and may be changed
// or removed in the future.
"fragment ".concat(name).concat(wrap('(', join(variableDefinitions, ', '), ')'), " ") + "on ".concat(typeCondition, " ").concat(wrap('', join(directives, ' '), ' ')) + selectionSet
);
},
// Value
IntValue: function IntValue(_ref8) {
var value = _ref8.value;
return value;
},
FloatValue: function FloatValue(_ref9) {
var value = _ref9.value;
return value;
},
StringValue: function StringValue(_ref10, key) {
var value = _ref10.value,
isBlockString = _ref10.block;
return isBlockString ? printBlockString(value, key === 'description' ? '' : ' ') : JSON.stringify(value);
},
BooleanValue: function BooleanValue(_ref11) {
var value = _ref11.value;
return value ? 'true' : 'false';
},
NullValue: function NullValue() {
return 'null';
},
EnumValue: function EnumValue(_ref12) {
var value = _ref12.value;
return value;
},
ListValue: function ListValue(_ref13) {
var values = _ref13.values;
return '[' + join(values, ', ') + ']';
},
ObjectValue: function ObjectValue(_ref14) {
var fields = _ref14.fields;
return '{' + join(fields, ', ') + '}';
},
ObjectField: function ObjectField(_ref15) {
var name = _ref15.name,
value = _ref15.value;
return name + ': ' + value;
},
// Directive
Directive: function Directive(_ref16) {
var name = _ref16.name,
args = _ref16.arguments;
return '@' + name + wrap('(', join(args, ', '), ')');
},
// Type
NamedType: function NamedType(_ref17) {
var name = _ref17.name;
return name;
},
ListType: function ListType(_ref18) {
var type = _ref18.type;
return '[' + type + ']';
},
NonNullType: function NonNullType(_ref19) {
var type = _ref19.type;
return type + '!';
},
// Type System Definitions
SchemaDefinition: addDescription(function (_ref20) {
var directives = _ref20.directives,
operationTypes = _ref20.operationTypes;
return join(['schema', join(directives, ' '), block(operationTypes)], ' ');
}),
OperationTypeDefinition: function OperationTypeDefinition(_ref21) {
var operation = _ref21.operation,
type = _ref21.type;
return operation + ': ' + type;
},
ScalarTypeDefinition: addDescription(function (_ref22) {
var name = _ref22.name,
directives = _ref22.directives;
return join(['scalar', name, join(directives, ' ')], ' ');
}),
ObjectTypeDefinition: addDescription(function (_ref23) {
var name = _ref23.name,
interfaces = _ref23.interfaces,
directives = _ref23.directives,
fields = _ref23.fields;
return join(['type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ');
}),
FieldDefinition: addDescription(function (_ref24) {
var name = _ref24.name,
args = _ref24.arguments,
type = _ref24.type,
directives = _ref24.directives;
return name + (hasMultilineItems(args) ? wrap('(\n', indent(join(args, '\n')), '\n)') : wrap('(', join(args, ', '), ')')) + ': ' + type + wrap(' ', join(directives, ' '));
}),
InputValueDefinition: addDescription(function (_ref25) {
var name = _ref25.name,
type = _ref25.type,
defaultValue = _ref25.defaultValue,
directives = _ref25.directives;
return join([name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')], ' ');
}),
InterfaceTypeDefinition: addDescription(function (_ref26) {
var name = _ref26.name,
interfaces = _ref26.interfaces,
directives = _ref26.directives,
fields = _ref26.fields;
return join(['interface', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ');
}),
UnionTypeDefinition: addDescription(function (_ref27) {
var name = _ref27.name,
directives = _ref27.directives,
types = _ref27.types;
return join(['union', name, join(directives, ' '), types && types.length !== 0 ? '= ' + join(types, ' | ') : ''], ' ');
}),
EnumTypeDefinition: addDescription(function (_ref28) {
var name = _ref28.name,
directives = _ref28.directives,
values = _ref28.values;
return join(['enum', name, join(directives, ' '), block(values)], ' ');
}),
EnumValueDefinition: addDescription(function (_ref29) {
var name = _ref29.name,
directives = _ref29.directives;
return join([name, join(directives, ' ')], ' ');
}),
InputObjectTypeDefinition: addDescription(function (_ref30) {
var name = _ref30.name,
directives = _ref30.directives,
fields = _ref30.fields;
return join(['input', name, join(directives, ' '), block(fields)], ' ');
}),
DirectiveDefinition: addDescription(function (_ref31) {
var name = _ref31.name,
args = _ref31.arguments,
repeatable = _ref31.repeatable,
locations = _ref31.locations;
return 'directive @' + name + (hasMultilineItems(args) ? wrap('(\n', indent(join(args, '\n')), '\n)') : wrap('(', join(args, ', '), ')')) + (repeatable ? ' repeatable' : '') + ' on ' + join(locations, ' | ');
}),
SchemaExtension: function SchemaExtension(_ref32) {
var directives = _ref32.directives,
operationTypes = _ref32.operationTypes;
return join(['extend schema', join(directives, ' '), block(operationTypes)], ' ');
},
ScalarTypeExtension: function ScalarTypeExtension(_ref33) {
var name = _ref33.name,
directives = _ref33.directives;
return join(['extend scalar', name, join(directives, ' ')], ' ');
},
ObjectTypeExtension: function ObjectTypeExtension(_ref34) {
var name = _ref34.name,
interfaces = _ref34.interfaces,
directives = _ref34.directives,
fields = _ref34.fields;
return join(['extend type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ');
},
InterfaceTypeExtension: function InterfaceTypeExtension(_ref35) {
var name = _ref35.name,
interfaces = _ref35.interfaces,
directives = _ref35.directives,
fields = _ref35.fields;
return join(['extend interface', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ');
},
UnionTypeExtension: function UnionTypeExtension(_ref36) {
var name = _ref36.name,
directives = _ref36.directives,
types = _ref36.types;
return join(['extend union', name, join(directives, ' '), types && types.length !== 0 ? '= ' + join(types, ' | ') : ''], ' ');
},
EnumTypeExtension: function EnumTypeExtension(_ref37) {
var name = _ref37.name,
directives = _ref37.directives,
values = _ref37.values;
return join(['extend enum', name, join(directives, ' '), block(values)], ' ');
},
InputObjectTypeExtension: function InputObjectTypeExtension(_ref38) {
var name = _ref38.name,
directives = _ref38.directives,
fields = _ref38.fields;
return join(['extend input', name, join(directives, ' '), block(fields)], ' ');
}
};
function addDescription(cb) {
return function (node) {
return join([node.description, cb(node)], '\n');
};
}
/**
* Given maybeArray, print an empty string if it is null or empty, otherwise
* print all items together separated by separator if provided
*/
function join(maybeArray) {
var _maybeArray$filter$jo;
var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
return (_maybeArray$filter$jo = maybeArray === null || maybeArray === void 0 ? void 0 : maybeArray.filter(function (x) {
return x;
}).join(separator)) !== null && _maybeArray$filter$jo !== void 0 ? _maybeArray$filter$jo : '';
}
/**
* Given array, print each item on its own line, wrapped in an
* indented "{ }" block.
*/
function block(array) {
return wrap('{\n', indent(join(array, '\n')), '\n}');
}
/**
* If maybeString is not null or empty, then wrap with start and end, otherwise print an empty string.
*/
function wrap(start, maybeString) {
var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
return maybeString != null && maybeString !== '' ? start + maybeString + end : '';
}
function indent(str) {
return wrap(' ', str.replace(/\n/g, '\n '));
}
function isMultiline(str) {
return str.indexOf('\n') !== -1;
}
function hasMultilineItems(maybeArray) {
return maybeArray != null && maybeArray.some(isMultiline);
}
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/graphql/print.js
import { print as origPrint } from "graphql";
import { AutoCleanedWeakCache, cacheSizes, } from "../caching/index.js";
import { registerGlobalCache } from "../caching/getMemoryInternals.js";
var printCache;
export var print = Object.assign(function (ast) {
var result = printCache.get(ast);
if (!result) {
result = origPrint(ast);
printCache.set(ast, result);
}
return result;
}, {
reset: function () {
printCache = new AutoCleanedWeakCache(cacheSizes.print || 2000 /* defaultCacheSizes.print */);
},
});
print.reset();
if (globalThis.__DEV__ !== false) {
registerGlobalCache("print", function () { return (printCache ? printCache.size : 0); });
}
//# sourceMappingURL=print.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/link/http/selectHttpOptionsAndBody.js
import { __assign, __spreadArray } from "tslib";
import { print } from "../../utilities/index.js";
var defaultHttpOptions = {
includeQuery: true,
includeExtensions: false,
preserveHeaderCase: false,
};
var defaultHeaders = {
// headers are case insensitive (https://stackoverflow.com/a/5259004)
accept: "*/*",
// The content-type header describes the type of the body of the request, and
// so it typically only is sent with requests that actually have bodies. One
// could imagine that Apollo Client would remove this header when constructing
// a GET request (which has no body), but we historically have not done that.
// This means that browsers will preflight all Apollo Client requests (even
// GET requests). Apollo Server's CSRF prevention feature (introduced in
// AS3.7) takes advantage of this fact and does not block requests with this
// header. If you want to drop this header from GET requests, then you should
// probably replace it with a `apollo-require-preflight` header, or servers
// with CSRF prevention enabled might block your GET request. See
// https://www.apollographql.com/docs/apollo-server/security/cors/#preventing-cross-site-request-forgery-csrf
// for more details.
"content-type": "application/json",
};
var defaultOptions = {
method: "POST",
};
export var fallbackHttpConfig = {
http: defaultHttpOptions,
headers: defaultHeaders,
options: defaultOptions,
};
export var defaultPrinter = function (ast, printer) { return printer(ast); };
export function selectHttpOptionsAndBody(operation, fallbackConfig) {
var configs = [];
for (var _i = 2; _i < arguments.length; _i++) {
configs[_i - 2] = arguments[_i];
}
configs.unshift(fallbackConfig);
return selectHttpOptionsAndBodyInternal.apply(void 0, __spreadArray([operation,
defaultPrinter], configs, false));
}
export function selectHttpOptionsAndBodyInternal(operation, printer) {
var configs = [];
for (var _i = 2; _i < arguments.length; _i++) {
configs[_i - 2] = arguments[_i];
}
var options = {};
var http = {};
configs.forEach(function (config) {
options = __assign(__assign(__assign({}, options), config.options), { headers: __assign(__assign({}, options.headers), config.headers) });
if (config.credentials) {
options.credentials = config.credentials;
}
http = __assign(__assign({}, http), config.http);
});
if (options.headers) {
options.headers = removeDuplicateHeaders(options.headers, http.preserveHeaderCase);
}
//The body depends on the http options
var operationName = operation.operationName, extensions = operation.extensions, variables = operation.variables, query = operation.query;
var body = { operationName: operationName, variables: variables };
if (http.includeExtensions)
body.extensions = extensions;
// not sending the query (i.e persisted queries)
if (http.includeQuery)
body.query = printer(query, print);
return {
options: options,
body: body,
};
}
// Remove potential duplicate header names, preserving last (by insertion order).
// This is done to prevent unintentionally duplicating a header instead of
// overwriting it (See #8447 and #8449).
function removeDuplicateHeaders(headers, preserveHeaderCase) {
// If we're not preserving the case, just remove duplicates w/ normalization.
if (!preserveHeaderCase) {
var normalizedHeaders_1 = Object.create(null);
Object.keys(Object(headers)).forEach(function (name) {
normalizedHeaders_1[name.toLowerCase()] = headers[name];
});
return normalizedHeaders_1;
}
// If we are preserving the case, remove duplicates w/ normalization,
// preserving the original name.
// This allows for non-http-spec-compliant servers that expect intentionally
// capitalized header names (See #6741).
var headerData = Object.create(null);
Object.keys(Object(headers)).forEach(function (name) {
headerData[name.toLowerCase()] = {
originalName: name,
value: headers[name],
};
});
var normalizedHeaders = Object.create(null);
Object.keys(headerData).forEach(function (name) {
normalizedHeaders[headerData[name].originalName] = headerData[name].value;
});
return normalizedHeaders;
}
//# sourceMappingURL=selectHttpOptionsAndBody.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/link/utils/fromError.js
import { Observable } from "../../utilities/index.js";
export function fromError(errorValue) {
return new Observable(function (observer) {
observer.error(errorValue);
});
}
//# sourceMappingURL=fromError.js.map
webpack://frontend-mybets/../../node_modules/graphql/language/kinds.mjs
/**
* The set of allowed kind values for AST nodes.
*/
export var Kind = Object.freeze({
// Name
NAME: 'Name',
// Document
DOCUMENT: 'Document',
OPERATION_DEFINITION: 'OperationDefinition',
VARIABLE_DEFINITION: 'VariableDefinition',
SELECTION_SET: 'SelectionSet',
FIELD: 'Field',
ARGUMENT: 'Argument',
// Fragments
FRAGMENT_SPREAD: 'FragmentSpread',
INLINE_FRAGMENT: 'InlineFragment',
FRAGMENT_DEFINITION: 'FragmentDefinition',
// Values
VARIABLE: 'Variable',
INT: 'IntValue',
FLOAT: 'FloatValue',
STRING: 'StringValue',
BOOLEAN: 'BooleanValue',
NULL: 'NullValue',
ENUM: 'EnumValue',
LIST: 'ListValue',
OBJECT: 'ObjectValue',
OBJECT_FIELD: 'ObjectField',
// Directives
DIRECTIVE: 'Directive',
// Types
NAMED_TYPE: 'NamedType',
LIST_TYPE: 'ListType',
NON_NULL_TYPE: 'NonNullType',
// Type System Definitions
SCHEMA_DEFINITION: 'SchemaDefinition',
OPERATION_TYPE_DEFINITION: 'OperationTypeDefinition',
// Type Definitions
SCALAR_TYPE_DEFINITION: 'ScalarTypeDefinition',
OBJECT_TYPE_DEFINITION: 'ObjectTypeDefinition',
FIELD_DEFINITION: 'FieldDefinition',
INPUT_VALUE_DEFINITION: 'InputValueDefinition',
INTERFACE_TYPE_DEFINITION: 'InterfaceTypeDefinition',
UNION_TYPE_DEFINITION: 'UnionTypeDefinition',
ENUM_TYPE_DEFINITION: 'EnumTypeDefinition',
ENUM_VALUE_DEFINITION: 'EnumValueDefinition',
INPUT_OBJECT_TYPE_DEFINITION: 'InputObjectTypeDefinition',
// Directive Definitions
DIRECTIVE_DEFINITION: 'DirectiveDefinition',
// Type System Extensions
SCHEMA_EXTENSION: 'SchemaExtension',
// Type Extensions
SCALAR_TYPE_EXTENSION: 'ScalarTypeExtension',
OBJECT_TYPE_EXTENSION: 'ObjectTypeExtension',
INTERFACE_TYPE_EXTENSION: 'InterfaceTypeExtension',
UNION_TYPE_EXTENSION: 'UnionTypeExtension',
ENUM_TYPE_EXTENSION: 'EnumTypeExtension',
INPUT_OBJECT_TYPE_EXTENSION: 'InputObjectTypeExtension'
});
/**
* The enum type representing the possible kind values of AST nodes.
*/
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/graphql/transform.js
import { __assign, __spreadArray } from "tslib";
import { invariant } from "../globals/index.js";
import { visit, Kind } from "graphql";
import { checkDocument, getOperationDefinition, getFragmentDefinition, getFragmentDefinitions, getMainDefinition, } from "./getFromAST.js";
import { isField } from "./storeUtils.js";
import { createFragmentMap } from "./fragments.js";
import { isArray, isNonEmptyArray } from "../common/arrays.js";
var TYPENAME_FIELD = {
kind: Kind.FIELD,
name: {
kind: Kind.NAME,
value: "__typename",
},
};
function isEmpty(op, fragmentMap) {
return (!op ||
op.selectionSet.selections.every(function (selection) {
return selection.kind === Kind.FRAGMENT_SPREAD &&
isEmpty(fragmentMap[selection.name.value], fragmentMap);
}));
}
function nullIfDocIsEmpty(doc) {
return (isEmpty(getOperationDefinition(doc) || getFragmentDefinition(doc), createFragmentMap(getFragmentDefinitions(doc)))) ?
null
: doc;
}
function getDirectiveMatcher(configs) {
var names = new Map();
var tests = new Map();
configs.forEach(function (directive) {
if (directive) {
if (directive.name) {
names.set(directive.name, directive);
}
else if (directive.test) {
tests.set(directive.test, directive);
}
}
});
return function (directive) {
var config = names.get(directive.name.value);
if (!config && tests.size) {
tests.forEach(function (testConfig, test) {
if (test(directive)) {
config = testConfig;
}
});
}
return config;
};
}
function makeInUseGetterFunction(defaultKey) {
var map = new Map();
return function inUseGetterFunction(key) {
if (key === void 0) { key = defaultKey; }
var inUse = map.get(key);
if (!inUse) {
map.set(key, (inUse = {
// Variable and fragment spread names used directly within this
// operation or fragment definition, as identified by key. These sets
// will be populated during the first traversal of the document in
// removeDirectivesFromDocument below.
variables: new Set(),
fragmentSpreads: new Set(),
}));
}
return inUse;
};
}
export function removeDirectivesFromDocument(directives, doc) {
checkDocument(doc);
// Passing empty strings to makeInUseGetterFunction means we handle anonymous
// operations as if their names were "". Anonymous fragment definitions are
// not supposed to be possible, but the same default naming strategy seems
// appropriate for that case as well.
var getInUseByOperationName = makeInUseGetterFunction("");
var getInUseByFragmentName = makeInUseGetterFunction("");
var getInUse = function (ancestors) {
for (var p = 0, ancestor = void 0; p < ancestors.length && (ancestor = ancestors[p]); ++p) {
if (isArray(ancestor))
continue;
if (ancestor.kind === Kind.OPERATION_DEFINITION) {
// If an operation is anonymous, we use the empty string as its key.
return getInUseByOperationName(ancestor.name && ancestor.name.value);
}
if (ancestor.kind === Kind.FRAGMENT_DEFINITION) {
return getInUseByFragmentName(ancestor.name.value);
}
}
globalThis.__DEV__ !== false && invariant.error(83);
return null;
};
var operationCount = 0;
for (var i = doc.definitions.length - 1; i >= 0; --i) {
if (doc.definitions[i].kind === Kind.OPERATION_DEFINITION) {
++operationCount;
}
}
var directiveMatcher = getDirectiveMatcher(directives);
var shouldRemoveField = function (nodeDirectives) {
return isNonEmptyArray(nodeDirectives) &&
nodeDirectives
.map(directiveMatcher)
.some(function (config) { return config && config.remove; });
};
var originalFragmentDefsByPath = new Map();
// Any time the first traversal of the document below makes a change like
// removing a fragment (by returning null), this variable should be set to
// true. Once it becomes true, it should never be set to false again. If this
// variable remains false throughout the traversal, then we can return the
// original doc immediately without any modifications.
var firstVisitMadeChanges = false;
var fieldOrInlineFragmentVisitor = {
enter: function (node) {
if (shouldRemoveField(node.directives)) {
firstVisitMadeChanges = true;
return null;
}
},
};
var docWithoutDirectiveSubtrees = visit(doc, {
// These two AST node types share the same implementation, defined above.
Field: fieldOrInlineFragmentVisitor,
InlineFragment: fieldOrInlineFragmentVisitor,
VariableDefinition: {
enter: function () {
// VariableDefinition nodes do not count as variables in use, though
// they do contain Variable nodes that might be visited below. To avoid
// counting variable declarations as usages, we skip visiting the
// contents of this VariableDefinition node by returning false.
return false;
},
},
Variable: {
enter: function (node, _key, _parent, _path, ancestors) {
var inUse = getInUse(ancestors);
if (inUse) {
inUse.variables.add(node.name.value);
}
},
},
FragmentSpread: {
enter: function (node, _key, _parent, _path, ancestors) {
if (shouldRemoveField(node.directives)) {
firstVisitMadeChanges = true;
return null;
}
var inUse = getInUse(ancestors);
if (inUse) {
inUse.fragmentSpreads.add(node.name.value);
}
// We might like to remove this FragmentSpread by returning null here if
// the corresponding FragmentDefinition node is also going to be removed
// by the logic below, but we can't control the relative order of those
// events, so we have to postpone the removal of dangling FragmentSpread
// nodes until after the current visit of the document has finished.
},
},
FragmentDefinition: {
enter: function (node, _key, _parent, path) {
originalFragmentDefsByPath.set(JSON.stringify(path), node);
},
leave: function (node, _key, _parent, path) {
var originalNode = originalFragmentDefsByPath.get(JSON.stringify(path));
if (node === originalNode) {
// If the FragmentNode received by this leave function is identical to
// the one received by the corresponding enter function (above), then
// the visitor must not have made any changes within this
// FragmentDefinition node. This fragment definition may still be
// removed if there are no ...spread references to it, but it won't be
// removed just because it has only a __typename field.
return node;
}
if (
// This logic applies only if the document contains one or more
// operations, since removing all fragments from a document containing
// only fragments makes the document useless.
operationCount > 0 &&
node.selectionSet.selections.every(function (selection) {
return selection.kind === Kind.FIELD &&
selection.name.value === "__typename";
})) {
// This is a somewhat opinionated choice: if a FragmentDefinition ends
// up having no fields other than __typename, we remove the whole
// fragment definition, and later prune ...spread references to it.
getInUseByFragmentName(node.name.value).removed = true;
firstVisitMadeChanges = true;
return null;
}
},
},
Directive: {
leave: function (node) {
// If a matching directive is found, remove the directive itself. Note
// that this does not remove the target (field, argument, etc) of the
// directive, but only the directive itself.
if (directiveMatcher(node)) {
firstVisitMadeChanges = true;
return null;
}
},
},
});
if (!firstVisitMadeChanges) {
// If our first pass did not change anything about the document, then there
// is no cleanup we need to do, and we can return the original doc.
return doc;
}
// Utility for making sure inUse.transitiveVars is recursively populated.
// Because this logic assumes inUse.fragmentSpreads has been completely
// populated and inUse.removed has been set if appropriate,
// populateTransitiveVars must be called after that information has been
// collected by the first traversal of the document.
var populateTransitiveVars = function (inUse) {
if (!inUse.transitiveVars) {
inUse.transitiveVars = new Set(inUse.variables);
if (!inUse.removed) {
inUse.fragmentSpreads.forEach(function (childFragmentName) {
populateTransitiveVars(getInUseByFragmentName(childFragmentName)).transitiveVars.forEach(function (varName) {
inUse.transitiveVars.add(varName);
});
});
}
}
return inUse;
};
// Since we've been keeping track of fragment spreads used by particular
// operations and fragment definitions, we now need to compute the set of all
// spreads used (transitively) by any operations in the document.
var allFragmentNamesUsed = new Set();
docWithoutDirectiveSubtrees.definitions.forEach(function (def) {
if (def.kind === Kind.OPERATION_DEFINITION) {
populateTransitiveVars(getInUseByOperationName(def.name && def.name.value)).fragmentSpreads.forEach(function (childFragmentName) {
allFragmentNamesUsed.add(childFragmentName);
});
}
else if (def.kind === Kind.FRAGMENT_DEFINITION &&
// If there are no operations in the document, then all fragment
// definitions count as usages of their own fragment names. This heuristic
// prevents accidentally removing all fragment definitions from the
// document just because it contains no operations that use the fragments.
operationCount === 0 &&
!getInUseByFragmentName(def.name.value).removed) {
allFragmentNamesUsed.add(def.name.value);
}
});
// Now that we have added all fragment spreads used by operations to the
// allFragmentNamesUsed set, we can complete the set by transitively adding
// all fragment spreads used by those fragments, and so on.
allFragmentNamesUsed.forEach(function (fragmentName) {
// Once all the childFragmentName strings added here have been seen already,
// the top-level allFragmentNamesUsed.forEach loop will terminate.
populateTransitiveVars(getInUseByFragmentName(fragmentName)).fragmentSpreads.forEach(function (childFragmentName) {
allFragmentNamesUsed.add(childFragmentName);
});
});
var fragmentWillBeRemoved = function (fragmentName) {
return !!(
// A fragment definition will be removed if there are no spreads that refer
// to it, or the fragment was explicitly removed because it had no fields
// other than __typename.
(!allFragmentNamesUsed.has(fragmentName) ||
getInUseByFragmentName(fragmentName).removed));
};
var enterVisitor = {
enter: function (node) {
if (fragmentWillBeRemoved(node.name.value)) {
return null;
}
},
};
return nullIfDocIsEmpty(visit(docWithoutDirectiveSubtrees, {
// If the fragment is going to be removed, then leaving any dangling
// FragmentSpread nodes with the same name would be a mistake.
FragmentSpread: enterVisitor,
// This is where the fragment definition is actually removed.
FragmentDefinition: enterVisitor,
OperationDefinition: {
leave: function (node) {
// Upon leaving each operation in the depth-first AST traversal, prune
// any variables that are declared by the operation but unused within.
if (node.variableDefinitions) {
var usedVariableNames_1 = populateTransitiveVars(
// If an operation is anonymous, we use the empty string as its key.
getInUseByOperationName(node.name && node.name.value)).transitiveVars;
// According to the GraphQL spec, all variables declared by an
// operation must either be used by that operation or used by some
// fragment included transitively into that operation:
// https://spec.graphql.org/draft/#sec-All-Variables-Used
//
// To stay on the right side of this validation rule, if/when we
// remove the last $var references from an operation or its fragments,
// we must also remove the corresponding $var declaration from the
// enclosing operation. This pruning applies only to operations and
// not fragment definitions, at the moment. Fragments may be able to
// declare variables eventually, but today they can only consume them.
if (usedVariableNames_1.size < node.variableDefinitions.length) {
return __assign(__assign({}, node), { variableDefinitions: node.variableDefinitions.filter(function (varDef) {
return usedVariableNames_1.has(varDef.variable.name.value);
}) });
}
}
},
},
}));
}
export var addTypenameToDocument = Object.assign(function (doc) {
return visit(doc, {
SelectionSet: {
enter: function (node, _key, parent) {
// Don't add __typename to OperationDefinitions.
if (parent &&
parent.kind ===
Kind.OPERATION_DEFINITION) {
return;
}
// No changes if no selections.
var selections = node.selections;
if (!selections) {
return;
}
// If selections already have a __typename, or are part of an
// introspection query, do nothing.
var skip = selections.some(function (selection) {
return (isField(selection) &&
(selection.name.value === "__typename" ||
selection.name.value.lastIndexOf("__", 0) === 0));
});
if (skip) {
return;
}
// If this SelectionSet is @export-ed as an input variable, it should
// not have a __typename field (see issue #4691).
var field = parent;
if (isField(field) &&
field.directives &&
field.directives.some(function (d) { return d.name.value === "export"; })) {
return;
}
// Create and return a new SelectionSet with a __typename Field.
return __assign(__assign({}, node), { selections: __spreadArray(__spreadArray([], selections, true), [TYPENAME_FIELD], false) });
},
},
});
}, {
added: function (field) {
return field === TYPENAME_FIELD;
},
});
var connectionRemoveConfig = {
test: function (directive) {
var willRemove = directive.name.value === "connection";
if (willRemove) {
if (!directive.arguments ||
!directive.arguments.some(function (arg) { return arg.name.value === "key"; })) {
globalThis.__DEV__ !== false && invariant.warn(84);
}
}
return willRemove;
},
};
export function removeConnectionDirectiveFromDocument(doc) {
return removeDirectivesFromDocument([connectionRemoveConfig], checkDocument(doc));
}
function hasDirectivesInSelectionSet(directives, selectionSet, nestedCheck) {
if (nestedCheck === void 0) { nestedCheck = true; }
return (!!selectionSet &&
selectionSet.selections &&
selectionSet.selections.some(function (selection) {
return hasDirectivesInSelection(directives, selection, nestedCheck);
}));
}
function hasDirectivesInSelection(directives, selection, nestedCheck) {
if (nestedCheck === void 0) { nestedCheck = true; }
if (!isField(selection)) {
return true;
}
if (!selection.directives) {
return false;
}
return (selection.directives.some(getDirectiveMatcher(directives)) ||
(nestedCheck &&
hasDirectivesInSelectionSet(directives, selection.selectionSet, nestedCheck)));
}
function getArgumentMatcher(config) {
return function argumentMatcher(argument) {
return config.some(function (aConfig) {
return argument.value &&
argument.value.kind === Kind.VARIABLE &&
argument.value.name &&
(aConfig.name === argument.value.name.value ||
(aConfig.test && aConfig.test(argument)));
});
};
}
export function removeArgumentsFromDocument(config, doc) {
var argMatcher = getArgumentMatcher(config);
return nullIfDocIsEmpty(visit(doc, {
OperationDefinition: {
enter: function (node) {
return __assign(__assign({}, node), {
// Remove matching top level variables definitions.
variableDefinitions: node.variableDefinitions ?
node.variableDefinitions.filter(function (varDef) {
return !config.some(function (arg) { return arg.name === varDef.variable.name.value; });
})
: [] });
},
},
Field: {
enter: function (node) {
// If `remove` is set to true for an argument, and an argument match
// is found for a field, remove the field as well.
var shouldRemoveField = config.some(function (argConfig) { return argConfig.remove; });
if (shouldRemoveField) {
var argMatchCount_1 = 0;
if (node.arguments) {
node.arguments.forEach(function (arg) {
if (argMatcher(arg)) {
argMatchCount_1 += 1;
}
});
}
if (argMatchCount_1 === 1) {
return null;
}
}
},
},
Argument: {
enter: function (node) {
// Remove all matching arguments.
if (argMatcher(node)) {
return null;
}
},
},
}));
}
export function removeFragmentSpreadFromDocument(config, doc) {
function enter(node) {
if (config.some(function (def) { return def.name === node.name.value; })) {
return null;
}
}
return nullIfDocIsEmpty(visit(doc, {
FragmentSpread: { enter: enter },
FragmentDefinition: { enter: enter },
}));
}
// If the incoming document is a query, return it as is. Otherwise, build a
// new document containing a query operation based on the selection set
// of the previous main operation.
export function buildQueryFromSelectionSet(document) {
var definition = getMainDefinition(document);
var definitionOperation = definition.operation;
if (definitionOperation === "query") {
// Already a query, so return the existing document.
return document;
}
// Build a new query using the selection set of the main operation.
var modifiedDoc = visit(document, {
OperationDefinition: {
enter: function (node) {
return __assign(__assign({}, node), { operation: "query" });
},
},
});
return modifiedDoc;
}
// Remove fields / selection sets that include an @client directive.
export function removeClientSetsFromDocument(document) {
checkDocument(document);
var modifiedDoc = removeDirectivesFromDocument([
{
test: function (directive) { return directive.name.value === "client"; },
remove: true,
},
], document);
return modifiedDoc;
}
//# sourceMappingURL=transform.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/link/http/createHttpLink.js
import { __assign, __rest } from "tslib";
import { invariant } from "../../utilities/globals/index.js";
import { ApolloLink } from "../core/index.js";
import { Observable, hasDirectives } from "../../utilities/index.js";
import { serializeFetchParameter } from "./serializeFetchParameter.js";
import { selectURI } from "./selectURI.js";
import { handleError, readMultipartBody, parseAndCheckHttpResponse, } from "./parseAndCheckHttpResponse.js";
import { checkFetcher } from "./checkFetcher.js";
import { selectHttpOptionsAndBodyInternal, defaultPrinter, fallbackHttpConfig, } from "./selectHttpOptionsAndBody.js";
import { rewriteURIForGET } from "./rewriteURIForGET.js";
import { fromError, filterOperationVariables } from "../utils/index.js";
import { maybe, getMainDefinition, removeClientSetsFromDocument, } from "../../utilities/index.js";
var backupFetch = maybe(function () { return fetch; });
export var createHttpLink = function (linkOptions) {
if (linkOptions === void 0) { linkOptions = {}; }
var _a = linkOptions.uri, uri = _a === void 0 ? "/graphql" : _a,
// use default global fetch if nothing passed in
preferredFetch = linkOptions.fetch, _b = linkOptions.print, print = _b === void 0 ? defaultPrinter : _b, includeExtensions = linkOptions.includeExtensions, preserveHeaderCase = linkOptions.preserveHeaderCase, useGETForQueries = linkOptions.useGETForQueries, _c = linkOptions.includeUnusedVariables, includeUnusedVariables = _c === void 0 ? false : _c, requestOptions = __rest(linkOptions, ["uri", "fetch", "print", "includeExtensions", "preserveHeaderCase", "useGETForQueries", "includeUnusedVariables"]);
if (globalThis.__DEV__ !== false) {
// Make sure at least one of preferredFetch, window.fetch, or backupFetch is
// defined, so requests won't fail at runtime.
checkFetcher(preferredFetch || backupFetch);
}
var linkConfig = {
http: { includeExtensions: includeExtensions, preserveHeaderCase: preserveHeaderCase },
options: requestOptions.fetchOptions,
credentials: requestOptions.credentials,
headers: requestOptions.headers,
};
return new ApolloLink(function (operation) {
var chosenURI = selectURI(operation, uri);
var context = operation.getContext();
// `apollographql-client-*` headers are automatically set if a
// `clientAwareness` object is found in the context. These headers are
// set first, followed by the rest of the headers pulled from
// `context.headers`. If desired, `apollographql-client-*` headers set by
// the `clientAwareness` object can be overridden by
// `apollographql-client-*` headers set in `context.headers`.
var clientAwarenessHeaders = {};
if (context.clientAwareness) {
var _a = context.clientAwareness, name_1 = _a.name, version = _a.version;
if (name_1) {
clientAwarenessHeaders["apollographql-client-name"] = name_1;
}
if (version) {
clientAwarenessHeaders["apollographql-client-version"] = version;
}
}
var contextHeaders = __assign(__assign({}, clientAwarenessHeaders), context.headers);
var contextConfig = {
http: context.http,
options: context.fetchOptions,
credentials: context.credentials,
headers: contextHeaders,
};
if (hasDirectives(["client"], operation.query)) {
var transformedQuery = removeClientSetsFromDocument(operation.query);
if (!transformedQuery) {
return fromError(new Error("HttpLink: Trying to send a client-only query to the server. To send to the server, ensure a non-client field is added to the query or set the `transformOptions.removeClientFields` option to `true`."));
}
operation.query = transformedQuery;
}
//uses fallback, link, and then context to build options
var _b = selectHttpOptionsAndBodyInternal(operation, print, fallbackHttpConfig, linkConfig, contextConfig), options = _b.options, body = _b.body;
if (body.variables && !includeUnusedVariables) {
body.variables = filterOperationVariables(body.variables, operation.query);
}
var controller;
if (!options.signal && typeof AbortController !== "undefined") {
controller = new AbortController();
options.signal = controller.signal;
}
// If requested, set method to GET if there are no mutations.
var definitionIsMutation = function (d) {
return d.kind === "OperationDefinition" && d.operation === "mutation";
};
var definitionIsSubscription = function (d) {
return d.kind === "OperationDefinition" && d.operation === "subscription";
};
var isSubscription = definitionIsSubscription(getMainDefinition(operation.query));
// does not match custom directives beginning with @defer
var hasDefer = hasDirectives(["defer"], operation.query);
if (useGETForQueries &&
!operation.query.definitions.some(definitionIsMutation)) {
options.method = "GET";
}
if (hasDefer || isSubscription) {
options.headers = options.headers || {};
var acceptHeader = "multipart/mixed;";
// Omit defer-specific headers if the user attempts to defer a selection
// set on a subscription and log a warning.
if (isSubscription && hasDefer) {
globalThis.__DEV__ !== false && invariant.warn(38);
}
if (isSubscription) {
acceptHeader +=
"boundary=graphql;subscriptionSpec=1.0,application/json";
}
else if (hasDefer) {
acceptHeader += "deferSpec=20220824,application/json";
}
options.headers.accept = acceptHeader;
}
if (options.method === "GET") {
var _c = rewriteURIForGET(chosenURI, body), newURI = _c.newURI, parseError = _c.parseError;
if (parseError) {
return fromError(parseError);
}
chosenURI = newURI;
}
else {
try {
options.body = serializeFetchParameter(body, "Payload");
}
catch (parseError) {
return fromError(parseError);
}
}
return new Observable(function (observer) {
// Prefer linkOptions.fetch (preferredFetch) if provided, and otherwise
// fall back to the *current* global window.fetch function (see issue
// #7832), or (if all else fails) the backupFetch function we saved when
// this module was first evaluated. This last option protects against the
// removal of window.fetch, which is unlikely but not impossible.
var currentFetch = preferredFetch || maybe(function () { return fetch; }) || backupFetch;
var observerNext = observer.next.bind(observer);
currentFetch(chosenURI, options)
.then(function (response) {
var _a;
operation.setContext({ response: response });
var ctype = (_a = response.headers) === null || _a === void 0 ? void 0 : _a.get("content-type");
if (ctype !== null && /^multipart\/mixed/i.test(ctype)) {
return readMultipartBody(response, observerNext);
}
else {
return parseAndCheckHttpResponse(operation)(response).then(observerNext);
}
})
.then(function () {
controller = undefined;
observer.complete();
})
.catch(function (err) {
controller = undefined;
handleError(err, observer);
});
return function () {
// XXX support canceling this request
// https://developers.google.com/web/updates/2017/09/abortable-fetch
if (controller)
controller.abort();
};
});
});
};
//# sourceMappingURL=createHttpLink.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/link/http/checkFetcher.js
import { newInvariantError } from "../../utilities/globals/index.js";
export var checkFetcher = function (fetcher) {
if (!fetcher && typeof fetch === "undefined") {
throw newInvariantError(37);
}
};
//# sourceMappingURL=checkFetcher.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/link/http/selectURI.js
export var selectURI = function (operation, fallbackURI) {
var context = operation.getContext();
var contextURI = context.uri;
if (contextURI) {
return contextURI;
}
else if (typeof fallbackURI === "function") {
return fallbackURI(operation);
}
else {
return fallbackURI || "/graphql";
}
};
//# sourceMappingURL=selectURI.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/link/utils/filterOperationVariables.js
import { __assign } from "tslib";
import { visit } from "graphql";
export function filterOperationVariables(variables, query) {
var result = __assign({}, variables);
var unusedNames = new Set(Object.keys(variables));
visit(query, {
Variable: function (node, _key, parent) {
// A variable type definition at the top level of a query is not
// enough to silence server-side errors about the variable being
// unused, so variable definitions do not count as usage.
// https://spec.graphql.org/draft/#sec-All-Variables-Used
if (parent &&
parent.kind !== "VariableDefinition") {
unusedNames.delete(node.name.value);
}
},
});
unusedNames.forEach(function (name) {
delete result[name];
});
return result;
}
//# sourceMappingURL=filterOperationVariables.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/link/http/rewriteURIForGET.js
import { serializeFetchParameter } from "./serializeFetchParameter.js";
// For GET operations, returns the given URI rewritten with parameters, or a
// parse error.
export function rewriteURIForGET(chosenURI, body) {
// Implement the standard HTTP GET serialization, plus 'extensions'. Note
// the extra level of JSON serialization!
var queryParams = [];
var addQueryParam = function (key, value) {
queryParams.push("".concat(key, "=").concat(encodeURIComponent(value)));
};
if ("query" in body) {
addQueryParam("query", body.query);
}
if (body.operationName) {
addQueryParam("operationName", body.operationName);
}
if (body.variables) {
var serializedVariables = void 0;
try {
serializedVariables = serializeFetchParameter(body.variables, "Variables map");
}
catch (parseError) {
return { parseError: parseError };
}
addQueryParam("variables", serializedVariables);
}
if (body.extensions) {
var serializedExtensions = void 0;
try {
serializedExtensions = serializeFetchParameter(body.extensions, "Extensions map");
}
catch (parseError) {
return { parseError: parseError };
}
addQueryParam("extensions", serializedExtensions);
}
// Reconstruct the URI with added query params.
// XXX This assumes that the URI is well-formed and that it doesn't
// already contain any of these query params. We could instead use the
// URL API and take a polyfill (whatwg-url@6) for older browsers that
// don't support URLSearchParams. Note that some browsers (and
// versions of whatwg-url) support URL but not URLSearchParams!
var fragment = "", preFragment = chosenURI;
var fragmentStart = chosenURI.indexOf("#");
if (fragmentStart !== -1) {
fragment = chosenURI.substr(fragmentStart);
preFragment = chosenURI.substr(0, fragmentStart);
}
var queryParamsPrefix = preFragment.indexOf("?") === -1 ? "?" : "&";
var newURI = preFragment + queryParamsPrefix + queryParams.join("&") + fragment;
return { newURI: newURI };
}
//# sourceMappingURL=rewriteURIForGET.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/link/core/split.js
import { ApolloLink } from "./ApolloLink.js";
export var split = ApolloLink.split;
//# sourceMappingURL=split.js.map
webpack://frontend-mybets/../../node_modules/@wry/trie/lib/index.js
// A [trie](https://en.wikipedia.org/wiki/Trie) data structure that holds
// object keys weakly, yet can also hold non-object keys, unlike the
// native `WeakMap`.
// If no makeData function is supplied, the looked-up data will be an empty,
// null-prototype Object.
const defaultMakeData = () => Object.create(null);
// Useful for processing arguments objects as well as arrays.
const { forEach, slice } = Array.prototype;
const { hasOwnProperty } = Object.prototype;
export class Trie {
constructor(weakness = true, makeData = defaultMakeData) {
this.weakness = weakness;
this.makeData = makeData;
}
lookup() {
return this.lookupArray(arguments);
}
lookupArray(array) {
let node = this;
forEach.call(array, key => node = node.getChildTrie(key));
return hasOwnProperty.call(node, "data")
? node.data
: node.data = this.makeData(slice.call(array));
}
peek() {
return this.peekArray(arguments);
}
peekArray(array) {
let node = this;
for (let i = 0, len = array.length; node && i < len; ++i) {
const map = node.mapFor(array[i], false);
node = map && map.get(array[i]);
}
return node && node.data;
}
remove() {
return this.removeArray(arguments);
}
removeArray(array) {
let data;
if (array.length) {
const head = array[0];
const map = this.mapFor(head, false);
const child = map && map.get(head);
if (child) {
data = child.removeArray(slice.call(array, 1));
if (!child.data && !child.weak && !(child.strong && child.strong.size)) {
map.delete(head);
}
}
}
else {
data = this.data;
delete this.data;
}
return data;
}
getChildTrie(key) {
const map = this.mapFor(key, true);
let child = map.get(key);
if (!child)
map.set(key, child = new Trie(this.weakness, this.makeData));
return child;
}
mapFor(key, create) {
return this.weakness && isObjRef(key)
? this.weak || (create ? this.weak = new WeakMap : void 0)
: this.strong || (create ? this.strong = new Map : void 0);
}
}
function isObjRef(value) {
switch (typeof value) {
case "object":
if (value === null)
break;
// Fall through to return true...
case "function":
return true;
}
return false;
}
//# sourceMappingURL=index.js.map
webpack://frontend-mybets/../../node_modules/@wry/context/lib/slot.js
// This currentContext variable will only be used if the makeSlotClass
// function is called, which happens only if this is the first copy of the
// @wry/context package to be imported.
let currentContext = null;
// This unique internal object is used to denote the absence of a value
// for a given Slot, and is never exposed to outside code.
const MISSING_VALUE = {};
let idCounter = 1;
// Although we can't do anything about the cost of duplicated code from
// accidentally bundling multiple copies of the @wry/context package, we can
// avoid creating the Slot class more than once using makeSlotClass.
const makeSlotClass = () => class Slot {
constructor() {
// If you have a Slot object, you can find out its slot.id, but you cannot
// guess the slot.id of a Slot you don't have access to, thanks to the
// randomized suffix.
this.id = [
"slot",
idCounter++,
Date.now(),
Math.random().toString(36).slice(2),
].join(":");
}
hasValue() {
for (let context = currentContext; context; context = context.parent) {
// We use the Slot object iself as a key to its value, which means the
// value cannot be obtained without a reference to the Slot object.
if (this.id in context.slots) {
const value = context.slots[this.id];
if (value === MISSING_VALUE)
break;
if (context !== currentContext) {
// Cache the value in currentContext.slots so the next lookup will
// be faster. This caching is safe because the tree of contexts and
// the values of the slots are logically immutable.
currentContext.slots[this.id] = value;
}
return true;
}
}
if (currentContext) {
// If a value was not found for this Slot, it's never going to be found
// no matter how many times we look it up, so we might as well cache
// the absence of the value, too.
currentContext.slots[this.id] = MISSING_VALUE;
}
return false;
}
getValue() {
if (this.hasValue()) {
return currentContext.slots[this.id];
}
}
withValue(value, callback,
// Given the prevalence of arrow functions, specifying arguments is likely
// to be much more common than specifying `this`, hence this ordering:
args, thisArg) {
const slots = {
__proto__: null,
[this.id]: value,
};
const parent = currentContext;
currentContext = { parent, slots };
try {
// Function.prototype.apply allows the arguments array argument to be
// omitted or undefined, so args! is fine here.
return callback.apply(thisArg, args);
}
finally {
currentContext = parent;
}
}
// Capture the current context and wrap a callback function so that it
// reestablishes the captured context when called.
static bind(callback) {
const context = currentContext;
return function () {
const saved = currentContext;
try {
currentContext = context;
return callback.apply(this, arguments);
}
finally {
currentContext = saved;
}
};
}
// Immediately run a callback function without any captured context.
static noContext(callback,
// Given the prevalence of arrow functions, specifying arguments is likely
// to be much more common than specifying `this`, hence this ordering:
args, thisArg) {
if (currentContext) {
const saved = currentContext;
try {
currentContext = null;
// Function.prototype.apply allows the arguments array argument to be
// omitted or undefined, so args! is fine here.
return callback.apply(thisArg, args);
}
finally {
currentContext = saved;
}
}
else {
return callback.apply(thisArg, args);
}
}
};
function maybe(fn) {
try {
return fn();
}
catch (ignored) { }
}
// We store a single global implementation of the Slot class as a permanent
// non-enumerable property of the globalThis object. This obfuscation does
// nothing to prevent access to the Slot class, but at least it ensures the
// implementation (i.e. currentContext) cannot be tampered with, and all copies
// of the @wry/context package (hopefully just one) will share the same Slot
// implementation. Since the first copy of the @wry/context package to be
// imported wins, this technique imposes a steep cost for any future breaking
// changes to the Slot class.
const globalKey = "@wry/context:Slot";
const host =
// Prefer globalThis when available.
// https://github.com/benjamn/wryware/issues/347
maybe(() => globalThis) ||
// Fall back to global, which works in Node.js and may be converted by some
// bundlers to the appropriate identifier (window, self, ...) depending on the
// bundling target. https://github.com/endojs/endo/issues/576#issuecomment-1178515224
maybe(() => global) ||
// Otherwise, use a dummy host that's local to this module. We used to fall
// back to using the Array constructor as a namespace, but that was flagged in
// https://github.com/benjamn/wryware/issues/347, and can be avoided.
Object.create(null);
// Whichever globalHost we're using, make TypeScript happy about the additional
// globalKey property.
const globalHost = host;
export const Slot = globalHost[globalKey] ||
// Earlier versions of this package stored the globalKey property on the Array
// constructor, so we check there as well, to prevent Slot class duplication.
Array[globalKey] ||
(function (Slot) {
try {
Object.defineProperty(globalHost, globalKey, {
value: Slot,
enumerable: false,
writable: false,
// When it was possible for globalHost to be the Array constructor (a
// legacy Slot dedup strategy), it was important for the property to be
// configurable:true so it could be deleted. That does not seem to be as
// important when globalHost is the global object, but I don't want to
// cause similar problems again, and configurable:true seems safest.
// https://github.com/endojs/endo/issues/576#issuecomment-1178274008
configurable: true
});
}
finally {
return Slot;
}
})(makeSlotClass());
//# sourceMappingURL=slot.js.map
webpack://frontend-mybets/../../node_modules/@wry/context/lib/index.js
import { Slot } from "./slot.js";
export { Slot };
export const { bind, noContext } = Slot;
// Like global.setTimeout, except the callback runs with captured context.
export { setTimeoutWithContext as setTimeout };
function setTimeoutWithContext(callback, delay) {
return setTimeout(bind(callback), delay);
}
// Turn any generator function into an async function (using yield instead
// of await), with context automatically preserved across yields.
export function asyncFromGen(genFn) {
return function () {
const gen = genFn.apply(this, arguments);
const boundNext = bind(gen.next);
const boundThrow = bind(gen.throw);
return new Promise((resolve, reject) => {
function invoke(method, argument) {
try {
var result = method.call(gen, argument);
}
catch (error) {
return reject(error);
}
const next = result.done ? resolve : invokeNext;
if (isPromiseLike(result.value)) {
result.value.then(next, result.done ? reject : invokeThrow);
}
else {
next(result.value);
}
}
const invokeNext = (value) => invoke(boundNext, value);
const invokeThrow = (error) => invoke(boundThrow, error);
invokeNext();
});
};
}
function isPromiseLike(value) {
return value && typeof value.then === "function";
}
// If you use the fibers npm package to implement coroutines in Node.js,
// you should call this function at least once to ensure context management
// remains coherent across any yields.
const wrappedFibers = [];
export function wrapYieldingFiberMethods(Fiber) {
// There can be only one implementation of Fiber per process, so this array
// should never grow longer than one element.
if (wrappedFibers.indexOf(Fiber) < 0) {
const wrap = (obj, method) => {
const fn = obj[method];
obj[method] = function () {
return noContext(fn, arguments, this);
};
};
// These methods can yield, according to
// https://github.com/laverdet/node-fibers/blob/ddebed9b8ae3883e57f822e2108e6943e5c8d2a8/fibers.js#L97-L100
wrap(Fiber, "yield");
wrap(Fiber.prototype, "run");
wrap(Fiber.prototype, "throwInto");
wrappedFibers.push(Fiber);
}
return Fiber;
}
//# sourceMappingURL=index.js.map
webpack://frontend-mybets/../../node_modules/optimism/lib/context.js
import { Slot } from "@wry/context";
export const parentEntrySlot = new Slot();
export function nonReactive(fn) {
return parentEntrySlot.withValue(void 0, fn);
}
export { Slot };
export { bind as bindContext, noContext, setTimeout, asyncFromGen, } from "@wry/context";
//# sourceMappingURL=context.js.map
webpack://frontend-mybets/../../node_modules/optimism/lib/helpers.js
export const { hasOwnProperty, } = Object.prototype;
export const arrayFromSet = Array.from ||
function (set) {
const array = [];
set.forEach(item => array.push(item));
return array;
};
export function maybeUnsubscribe(entryOrDep) {
const { unsubscribe } = entryOrDep;
if (typeof unsubscribe === "function") {
entryOrDep.unsubscribe = void 0;
unsubscribe();
}
}
//# sourceMappingURL=helpers.js.map
webpack://frontend-mybets/../../node_modules/optimism/lib/entry.js
import { parentEntrySlot } from "./context.js";
import { maybeUnsubscribe, arrayFromSet } from "./helpers.js";
const emptySetPool = [];
const POOL_TARGET_SIZE = 100;
// Since this package might be used browsers, we should avoid using the
// Node built-in assert module.
function assert(condition, optionalMessage) {
if (!condition) {
throw new Error(optionalMessage || "assertion failure");
}
}
function valueIs(a, b) {
const len = a.length;
return (
// Unknown values are not equal to each other.
len > 0 &&
// Both values must be ordinary (or both exceptional) to be equal.
len === b.length &&
// The underlying value or exception must be the same.
a[len - 1] === b[len - 1]);
}
function valueGet(value) {
switch (value.length) {
case 0: throw new Error("unknown value");
case 1: return value[0];
case 2: throw value[1];
}
}
function valueCopy(value) {
return value.slice(0);
}
export class Entry {
constructor(fn) {
this.fn = fn;
this.parents = new Set();
this.childValues = new Map();
// When this Entry has children that are dirty, this property becomes
// a Set containing other Entry objects, borrowed from emptySetPool.
// When the set becomes empty, it gets recycled back to emptySetPool.
this.dirtyChildren = null;
this.dirty = true;
this.recomputing = false;
this.value = [];
this.deps = null;
++Entry.count;
}
peek() {
if (this.value.length === 1 && !mightBeDirty(this)) {
rememberParent(this);
return this.value[0];
}
}
// This is the most important method of the Entry API, because it
// determines whether the cached this.value can be returned immediately,
// or must be recomputed. The overall performance of the caching system
// depends on the truth of the following observations: (1) this.dirty is
// usually false, (2) this.dirtyChildren is usually null/empty, and thus
// (3) valueGet(this.value) is usually returned without recomputation.
recompute(args) {
assert(!this.recomputing, "already recomputing");
rememberParent(this);
return mightBeDirty(this)
? reallyRecompute(this, args)
: valueGet(this.value);
}
setDirty() {
if (this.dirty)
return;
this.dirty = true;
reportDirty(this);
// We can go ahead and unsubscribe here, since any further dirty
// notifications we receive will be redundant, and unsubscribing may
// free up some resources, e.g. file watchers.
maybeUnsubscribe(this);
}
dispose() {
this.setDirty();
// Sever any dependency relationships with our own children, so those
// children don't retain this parent Entry in their child.parents sets,
// thereby preventing it from being fully garbage collected.
forgetChildren(this);
// Because this entry has been kicked out of the cache (in index.js),
// we've lost the ability to find out if/when this entry becomes dirty,
// whether that happens through a subscription, because of a direct call
// to entry.setDirty(), or because one of its children becomes dirty.
// Because of this loss of future information, we have to assume the
// worst (that this entry might have become dirty very soon), so we must
// immediately mark this entry's parents as dirty. Normally we could
// just call entry.setDirty() rather than calling parent.setDirty() for
// each parent, but that would leave this entry in parent.childValues
// and parent.dirtyChildren, which would prevent the child from being
// truly forgotten.
eachParent(this, (parent, child) => {
parent.setDirty();
forgetChild(parent, this);
});
}
forget() {
// The code that creates Entry objects in index.ts will replace this method
// with one that actually removes the Entry from the cache, which will also
// trigger the entry.dispose method.
this.dispose();
}
dependOn(dep) {
dep.add(this);
if (!this.deps) {
this.deps = emptySetPool.pop() || new Set();
}
this.deps.add(dep);
}
forgetDeps() {
if (this.deps) {
arrayFromSet(this.deps).forEach(dep => dep.delete(this));
this.deps.clear();
emptySetPool.push(this.deps);
this.deps = null;
}
}
}
Entry.count = 0;
function rememberParent(child) {
const parent = parentEntrySlot.getValue();
if (parent) {
child.parents.add(parent);
if (!parent.childValues.has(child)) {
parent.childValues.set(child, []);
}
if (mightBeDirty(child)) {
reportDirtyChild(parent, child);
}
else {
reportCleanChild(parent, child);
}
return parent;
}
}
function reallyRecompute(entry, args) {
forgetChildren(entry);
// Set entry as the parent entry while calling recomputeNewValue(entry).
parentEntrySlot.withValue(entry, recomputeNewValue, [entry, args]);
if (maybeSubscribe(entry, args)) {
// If we successfully recomputed entry.value and did not fail to
// (re)subscribe, then this Entry is no longer explicitly dirty.
setClean(entry);
}
return valueGet(entry.value);
}
function recomputeNewValue(entry, args) {
entry.recomputing = true;
const { normalizeResult } = entry;
let oldValueCopy;
if (normalizeResult && entry.value.length === 1) {
oldValueCopy = valueCopy(entry.value);
}
// Make entry.value an empty array, representing an unknown value.
entry.value.length = 0;
try {
// If entry.fn succeeds, entry.value will become a normal Value.
entry.value[0] = entry.fn.apply(null, args);
// If we have a viable oldValueCopy to compare with the (successfully
// recomputed) new entry.value, and they are not already === identical, give
// normalizeResult a chance to pick/choose/reuse parts of oldValueCopy[0]
// and/or entry.value[0] to determine the final cached entry.value.
if (normalizeResult && oldValueCopy && !valueIs(oldValueCopy, entry.value)) {
try {
entry.value[0] = normalizeResult(entry.value[0], oldValueCopy[0]);
}
catch (_a) {
// If normalizeResult throws, just use the newer value, rather than
// saving the exception as entry.value[1].
}
}
}
catch (e) {
// If entry.fn throws, entry.value will hold that exception.
entry.value[1] = e;
}
// Either way, this line is always reached.
entry.recomputing = false;
}
function mightBeDirty(entry) {
return entry.dirty || !!(entry.dirtyChildren && entry.dirtyChildren.size);
}
function setClean(entry) {
entry.dirty = false;
if (mightBeDirty(entry)) {
// This Entry may still have dirty children, in which case we can't
// let our parents know we're clean just yet.
return;
}
reportClean(entry);
}
function reportDirty(child) {
eachParent(child, reportDirtyChild);
}
function reportClean(child) {
eachParent(child, reportCleanChild);
}
function eachParent(child, callback) {
const parentCount = child.parents.size;
if (parentCount) {
const parents = arrayFromSet(child.parents);
for (let i = 0; i < parentCount; ++i) {
callback(parents[i], child);
}
}
}
// Let a parent Entry know that one of its children may be dirty.
function reportDirtyChild(parent, child) {
// Must have called rememberParent(child) before calling
// reportDirtyChild(parent, child).
assert(parent.childValues.has(child));
assert(mightBeDirty(child));
const parentWasClean = !mightBeDirty(parent);
if (!parent.dirtyChildren) {
parent.dirtyChildren = emptySetPool.pop() || new Set;
}
else if (parent.dirtyChildren.has(child)) {
// If we already know this child is dirty, then we must have already
// informed our own parents that we are dirty, so we can terminate
// the recursion early.
return;
}
parent.dirtyChildren.add(child);
// If parent was clean before, it just became (possibly) dirty (according to
// mightBeDirty), since we just added child to parent.dirtyChildren.
if (parentWasClean) {
reportDirty(parent);
}
}
// Let a parent Entry know that one of its children is no longer dirty.
function reportCleanChild(parent, child) {
// Must have called rememberChild(child) before calling
// reportCleanChild(parent, child).
assert(parent.childValues.has(child));
assert(!mightBeDirty(child));
const childValue = parent.childValues.get(child);
if (childValue.length === 0) {
parent.childValues.set(child, valueCopy(child.value));
}
else if (!valueIs(childValue, child.value)) {
parent.setDirty();
}
removeDirtyChild(parent, child);
if (mightBeDirty(parent)) {
return;
}
reportClean(parent);
}
function removeDirtyChild(parent, child) {
const dc = parent.dirtyChildren;
if (dc) {
dc.delete(child);
if (dc.size === 0) {
if (emptySetPool.length < POOL_TARGET_SIZE) {
emptySetPool.push(dc);
}
parent.dirtyChildren = null;
}
}
}
// Removes all children from this entry and returns an array of the
// removed children.
function forgetChildren(parent) {
if (parent.childValues.size > 0) {
parent.childValues.forEach((_value, child) => {
forgetChild(parent, child);
});
}
// Remove this parent Entry from any sets to which it was added by the
// addToSet method.
parent.forgetDeps();
// After we forget all our children, this.dirtyChildren must be empty
// and therefore must have been reset to null.
assert(parent.dirtyChildren === null);
}
function forgetChild(parent, child) {
child.parents.delete(parent);
parent.childValues.delete(child);
removeDirtyChild(parent, child);
}
function maybeSubscribe(entry, args) {
if (typeof entry.subscribe === "function") {
try {
maybeUnsubscribe(entry); // Prevent double subscriptions.
entry.unsubscribe = entry.subscribe.apply(null, args);
}
catch (e) {
// If this Entry has a subscribe function and it threw an exception
// (or an unsubscribe function it previously returned now throws),
// return false to indicate that we were not able to subscribe (or
// unsubscribe), and this Entry should remain dirty.
entry.setDirty();
return false;
}
}
// Returning true indicates either that there was no entry.subscribe
// function or that it succeeded.
return true;
}
//# sourceMappingURL=entry.js.map
webpack://frontend-mybets/../../node_modules/optimism/lib/dep.js
import { parentEntrySlot } from "./context.js";
import { hasOwnProperty, maybeUnsubscribe, arrayFromSet, } from "./helpers.js";
const EntryMethods = {
setDirty: true,
dispose: true,
forget: true, // Fully remove parent Entry from LRU cache and computation graph
};
export function dep(options) {
const depsByKey = new Map();
const subscribe = options && options.subscribe;
function depend(key) {
const parent = parentEntrySlot.getValue();
if (parent) {
let dep = depsByKey.get(key);
if (!dep) {
depsByKey.set(key, dep = new Set);
}
parent.dependOn(dep);
if (typeof subscribe === "function") {
maybeUnsubscribe(dep);
dep.unsubscribe = subscribe(key);
}
}
}
depend.dirty = function dirty(key, entryMethodName) {
const dep = depsByKey.get(key);
if (dep) {
const m = (entryMethodName &&
hasOwnProperty.call(EntryMethods, entryMethodName)) ? entryMethodName : "setDirty";
// We have to use arrayFromSet(dep).forEach instead of dep.forEach,
// because modifying a Set while iterating over it can cause elements in
// the Set to be removed from the Set before they've been iterated over.
arrayFromSet(dep).forEach(entry => entry[m]());
depsByKey.delete(key);
maybeUnsubscribe(dep);
}
};
return depend;
}
//# sourceMappingURL=dep.js.map
webpack://frontend-mybets/../../node_modules/optimism/lib/index.js
import { Trie } from "@wry/trie";
import { StrongCache } from "@wry/caches";
import { Entry } from "./entry.js";
import { parentEntrySlot } from "./context.js";
// These helper functions are important for making optimism work with
// asynchronous code. In order to register parent-child dependencies,
// optimism needs to know about any currently active parent computations.
// In ordinary synchronous code, the parent context is implicit in the
// execution stack, but asynchronous code requires some extra guidance in
// order to propagate context from one async task segment to the next.
export { bindContext, noContext, nonReactive, setTimeout, asyncFromGen, Slot, } from "./context.js";
// A lighter-weight dependency, similar to OptimisticWrapperFunction, except
// with only one argument, no makeCacheKey, no wrapped function to recompute,
// and no result value. Useful for representing dependency leaves in the graph
// of computation. Subscriptions are supported.
export { dep } from "./dep.js";
// The defaultMakeCacheKey function is remarkably powerful, because it gives
// a unique object for any shallow-identical list of arguments. If you need
// to implement a custom makeCacheKey function, you may find it helpful to
// delegate the final work to defaultMakeCacheKey, which is why we export it
// here. However, you may want to avoid defaultMakeCacheKey if your runtime
// does not support WeakMap, or you have the ability to return a string key.
// In those cases, just write your own custom makeCacheKey functions.
let defaultKeyTrie;
export function defaultMakeCacheKey(...args) {
const trie = defaultKeyTrie || (defaultKeyTrie = new Trie(typeof WeakMap === "function"));
return trie.lookupArray(args);
}
// If you're paranoid about memory leaks, or you want to avoid using WeakMap
// under the hood, but you still need the behavior of defaultMakeCacheKey,
// import this constructor to create your own tries.
export { Trie as KeyTrie };
;
const caches = new Set();
export function wrap(originalFunction, { max = Math.pow(2, 16), keyArgs, makeCacheKey = defaultMakeCacheKey, normalizeResult, subscribe, cache: cacheOption = StrongCache, } = Object.create(null)) {
const cache = typeof cacheOption === "function"
? new cacheOption(max, entry => entry.dispose())
: cacheOption;
const optimistic = function () {
const key = makeCacheKey.apply(null, keyArgs ? keyArgs.apply(null, arguments) : arguments);
if (key === void 0) {
return originalFunction.apply(null, arguments);
}
let entry = cache.get(key);
if (!entry) {
cache.set(key, entry = new Entry(originalFunction));
entry.normalizeResult = normalizeResult;
entry.subscribe = subscribe;
// Give the Entry the ability to trigger cache.delete(key), even though
// the Entry itself does not know about key or cache.
entry.forget = () => cache.delete(key);
}
const value = entry.recompute(Array.prototype.slice.call(arguments));
// Move this entry to the front of the least-recently used queue,
// since we just finished computing its value.
cache.set(key, entry);
caches.add(cache);
// Clean up any excess entries in the cache, but only if there is no
// active parent entry, meaning we're not in the middle of a larger
// computation that might be flummoxed by the cleaning.
if (!parentEntrySlot.hasValue()) {
caches.forEach(cache => cache.clean());
caches.clear();
}
return value;
};
Object.defineProperty(optimistic, "size", {
get: () => cache.size,
configurable: false,
enumerable: false,
});
Object.freeze(optimistic.options = {
max,
keyArgs,
makeCacheKey,
normalizeResult,
subscribe,
cache,
});
function dirtyKey(key) {
const entry = key && cache.get(key);
if (entry) {
entry.setDirty();
}
}
optimistic.dirtyKey = dirtyKey;
optimistic.dirty = function dirty() {
dirtyKey(makeCacheKey.apply(null, arguments));
};
function peekKey(key) {
const entry = key && cache.get(key);
if (entry) {
return entry.peek();
}
}
optimistic.peekKey = peekKey;
optimistic.peek = function peek() {
return peekKey(makeCacheKey.apply(null, arguments));
};
function forgetKey(key) {
return key ? cache.delete(key) : false;
}
optimistic.forgetKey = forgetKey;
optimistic.forget = function forget() {
return forgetKey(makeCacheKey.apply(null, arguments));
};
optimistic.makeCacheKey = makeCacheKey;
optimistic.getKey = keyArgs ? function getKey() {
return makeCacheKey.apply(null, keyArgs.apply(null, arguments));
} : makeCacheKey;
return Object.freeze(optimistic);
}
//# sourceMappingURL=index.js.map
webpack://frontend-mybets/../../node_modules/@wry/equality/lib/index.js
const { toString, hasOwnProperty } = Object.prototype;
const fnToStr = Function.prototype.toString;
const previousComparisons = new Map();
/**
* Performs a deep equality check on two JavaScript values, tolerating cycles.
*/
export function equal(a, b) {
try {
return check(a, b);
}
finally {
previousComparisons.clear();
}
}
// Allow default imports as well.
export default equal;
function check(a, b) {
// If the two values are strictly equal, our job is easy.
if (a === b) {
return true;
}
// Object.prototype.toString returns a representation of the runtime type of
// the given value that is considerably more precise than typeof.
const aTag = toString.call(a);
const bTag = toString.call(b);
// If the runtime types of a and b are different, they could maybe be equal
// under some interpretation of equality, but for simplicity and performance
// we just return false instead.
if (aTag !== bTag) {
return false;
}
switch (aTag) {
case '[object Array]':
// Arrays are a lot like other objects, but we can cheaply compare their
// lengths as a short-cut before comparing their elements.
if (a.length !== b.length)
return false;
// Fall through to object case...
case '[object Object]': {
if (previouslyCompared(a, b))
return true;
const aKeys = definedKeys(a);
const bKeys = definedKeys(b);
// If `a` and `b` have a different number of enumerable keys, they
// must be different.
const keyCount = aKeys.length;
if (keyCount !== bKeys.length)
return false;
// Now make sure they have the same keys.
for (let k = 0; k < keyCount; ++k) {
if (!hasOwnProperty.call(b, aKeys[k])) {
return false;
}
}
// Finally, check deep equality of all child properties.
for (let k = 0; k < keyCount; ++k) {
const key = aKeys[k];
if (!check(a[key], b[key])) {
return false;
}
}
return true;
}
case '[object Error]':
return a.name === b.name && a.message === b.message;
case '[object Number]':
// Handle NaN, which is !== itself.
if (a !== a)
return b !== b;
// Fall through to shared +a === +b case...
case '[object Boolean]':
case '[object Date]':
return +a === +b;
case '[object RegExp]':
case '[object String]':
return a == `${b}`;
case '[object Map]':
case '[object Set]': {
if (a.size !== b.size)
return false;
if (previouslyCompared(a, b))
return true;
const aIterator = a.entries();
const isMap = aTag === '[object Map]';
while (true) {
const info = aIterator.next();
if (info.done)
break;
// If a instanceof Set, aValue === aKey.
const [aKey, aValue] = info.value;
// So this works the same way for both Set and Map.
if (!b.has(aKey)) {
return false;
}
// However, we care about deep equality of values only when dealing
// with Map structures.
if (isMap && !check(aValue, b.get(aKey))) {
return false;
}
}
return true;
}
case '[object Uint16Array]':
case '[object Uint8Array]': // Buffer, in Node.js.
case '[object Uint32Array]':
case '[object Int32Array]':
case '[object Int8Array]':
case '[object Int16Array]':
case '[object ArrayBuffer]':
// DataView doesn't need these conversions, but the equality check is
// otherwise the same.
a = new Uint8Array(a);
b = new Uint8Array(b);
// Fall through...
case '[object DataView]': {
let len = a.byteLength;
if (len === b.byteLength) {
while (len-- && a[len] === b[len]) {
// Keep looping as long as the bytes are equal.
}
}
return len === -1;
}
case '[object AsyncFunction]':
case '[object GeneratorFunction]':
case '[object AsyncGeneratorFunction]':
case '[object Function]': {
const aCode = fnToStr.call(a);
if (aCode !== fnToStr.call(b)) {
return false;
}
// We consider non-native functions equal if they have the same code
// (native functions require === because their code is censored).
// Note that this behavior is not entirely sound, since !== function
// objects with the same code can behave differently depending on
// their closure scope. However, any function can behave differently
// depending on the values of its input arguments (including this)
// and its calling context (including its closure scope), even
// though the function object is === to itself; and it is entirely
// possible for functions that are not === to behave exactly the
// same under all conceivable circumstances. Because none of these
// factors are statically decidable in JavaScript, JS function
// equality is not well-defined. This ambiguity allows us to
// consider the best possible heuristic among various imperfect
// options, and equating non-native functions that have the same
// code has enormous practical benefits, such as when comparing
// functions that are repeatedly passed as fresh function
// expressions within objects that are otherwise deeply equal. Since
// any function created from the same syntactic expression (in the
// same code location) will always stringify to the same code
// according to fnToStr.call, we can reasonably expect these
// repeatedly passed function expressions to have the same code, and
// thus behave "the same" (with all the caveats mentioned above),
// even though the runtime function objects are !== to one another.
return !endsWith(aCode, nativeCodeSuffix);
}
}
// Otherwise the values are not equal.
return false;
}
function definedKeys(obj) {
// Remember that the second argument to Array.prototype.filter will be
// used as `this` within the callback function.
return Object.keys(obj).filter(isDefinedKey, obj);
}
function isDefinedKey(key) {
return this[key] !== void 0;
}
const nativeCodeSuffix = "{ [native code] }";
function endsWith(full, suffix) {
const fromIndex = full.length - suffix.length;
return fromIndex >= 0 &&
full.indexOf(suffix, fromIndex) === fromIndex;
}
function previouslyCompared(a, b) {
// Though cyclic references can make an object graph appear infinite from the
// perspective of a depth-first traversal, the graph still contains a finite
// number of distinct object references. We use the previousComparisons cache
// to avoid comparing the same pair of object references more than once, which
// guarantees termination (even if we end up comparing every object in one
// graph to every object in the other graph, which is extremely unlikely),
// while still allowing weird isomorphic structures (like rings with different
// lengths) a chance to pass the equality test.
let bSet = previousComparisons.get(a);
if (bSet) {
// Return true here because we can be sure false will be returned somewhere
// else if the objects are not equivalent.
if (bSet.has(b))
return true;
}
else {
previousComparisons.set(a, bSet = new Set);
}
bSet.add(b);
return false;
}
//# sourceMappingURL=index.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/cache/core/cache.js
import { __assign, __rest } from "tslib";
import { wrap } from "optimism";
import { cacheSizes, getFragmentQueryDocument, } from "../../utilities/index.js";
import { WeakCache } from "@wry/caches";
import { getApolloCacheMemoryInternals } from "../../utilities/caching/getMemoryInternals.js";
var ApolloCache = /** @class */ (function () {
function ApolloCache() {
this.assumeImmutableResults = false;
// Make sure we compute the same (===) fragment query document every
// time we receive the same fragment in readFragment.
this.getFragmentDoc = wrap(getFragmentQueryDocument, {
max: cacheSizes["cache.fragmentQueryDocuments"] ||
1000 /* defaultCacheSizes["cache.fragmentQueryDocuments"] */,
cache: WeakCache,
});
}
// Transactional API
// The batch method is intended to replace/subsume both performTransaction
// and recordOptimisticTransaction, but performTransaction came first, so we
// provide a default batch implementation that's just another way of calling
// performTransaction. Subclasses of ApolloCache (such as InMemoryCache) can
// override the batch method to do more interesting things with its options.
ApolloCache.prototype.batch = function (options) {
var _this = this;
var optimisticId = typeof options.optimistic === "string" ? options.optimistic
: options.optimistic === false ? null
: void 0;
var updateResult;
this.performTransaction(function () { return (updateResult = options.update(_this)); }, optimisticId);
return updateResult;
};
ApolloCache.prototype.recordOptimisticTransaction = function (transaction, optimisticId) {
this.performTransaction(transaction, optimisticId);
};
// Optional API
// Called once per input document, allowing the cache to make static changes
// to the query, such as adding __typename fields.
ApolloCache.prototype.transformDocument = function (document) {
return document;
};
// Called before each ApolloLink request, allowing the cache to make dynamic
// changes to the query, such as filling in missing fragment definitions.
ApolloCache.prototype.transformForLink = function (document) {
return document;
};
ApolloCache.prototype.identify = function (object) {
return;
};
ApolloCache.prototype.gc = function () {
return [];
};
ApolloCache.prototype.modify = function (options) {
return false;
};
// DataProxy API
ApolloCache.prototype.readQuery = function (options, optimistic) {
if (optimistic === void 0) { optimistic = !!options.optimistic; }
return this.read(__assign(__assign({}, options), { rootId: options.id || "ROOT_QUERY", optimistic: optimistic }));
};
ApolloCache.prototype.readFragment = function (options, optimistic) {
if (optimistic === void 0) { optimistic = !!options.optimistic; }
return this.read(__assign(__assign({}, options), { query: this.getFragmentDoc(options.fragment, options.fragmentName), rootId: options.id, optimistic: optimistic }));
};
ApolloCache.prototype.writeQuery = function (_a) {
var id = _a.id, data = _a.data, options = __rest(_a, ["id", "data"]);
return this.write(Object.assign(options, {
dataId: id || "ROOT_QUERY",
result: data,
}));
};
ApolloCache.prototype.writeFragment = function (_a) {
var id = _a.id, data = _a.data, fragment = _a.fragment, fragmentName = _a.fragmentName, options = __rest(_a, ["id", "data", "fragment", "fragmentName"]);
return this.write(Object.assign(options, {
query: this.getFragmentDoc(fragment, fragmentName),
dataId: id,
result: data,
}));
};
ApolloCache.prototype.updateQuery = function (options, update) {
return this.batch({
update: function (cache) {
var value = cache.readQuery(options);
var data = update(value);
if (data === void 0 || data === null)
return value;
cache.writeQuery(__assign(__assign({}, options), { data: data }));
return data;
},
});
};
ApolloCache.prototype.updateFragment = function (options, update) {
return this.batch({
update: function (cache) {
var value = cache.readFragment(options);
var data = update(value);
if (data === void 0 || data === null)
return value;
cache.writeFragment(__assign(__assign({}, options), { data: data }));
return data;
},
});
};
return ApolloCache;
}());
export { ApolloCache };
if (globalThis.__DEV__ !== false) {
ApolloCache.prototype.getMemoryInternals = getApolloCacheMemoryInternals;
}
//# sourceMappingURL=cache.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/cache/core/types/common.js
import { __extends } from "tslib";
var MissingFieldError = /** @class */ (function (_super) {
__extends(MissingFieldError, _super);
function MissingFieldError(message, path, query, variables) {
var _a;
// 'Error' breaks prototype chain here
var _this = _super.call(this, message) || this;
_this.message = message;
_this.path = path;
_this.query = query;
_this.variables = variables;
if (Array.isArray(_this.path)) {
_this.missing = _this.message;
for (var i = _this.path.length - 1; i >= 0; --i) {
_this.missing = (_a = {}, _a[_this.path[i]] = _this.missing, _a);
}
}
else {
_this.missing = _this.path;
}
// We're not using `Object.setPrototypeOf` here as it isn't fully supported
// on Android (see issue #3236).
_this.__proto__ = MissingFieldError.prototype;
return _this;
}
return MissingFieldError;
}(Error));
export { MissingFieldError };
//# sourceMappingURL=common.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/graphql/DocumentTransform.js
import { Trie } from "@wry/trie";
import { canUseWeakMap, canUseWeakSet } from "../common/canUse.js";
import { checkDocument } from "./getFromAST.js";
import { invariant } from "../globals/index.js";
import { WeakCache } from "@wry/caches";
import { wrap } from "optimism";
import { cacheSizes } from "../caching/index.js";
function identity(document) {
return document;
}
var DocumentTransform = /** @class */ (function () {
function DocumentTransform(transform, options) {
if (options === void 0) { options = Object.create(null); }
this.resultCache = canUseWeakSet ? new WeakSet() : new Set();
this.transform = transform;
if (options.getCacheKey) {
// Override default `getCacheKey` function, which returns [document].
this.getCacheKey = options.getCacheKey;
}
this.cached = options.cache !== false;
this.resetCache();
}
// This default implementation of getCacheKey can be overridden by providing
// options.getCacheKey to the DocumentTransform constructor. In general, a
// getCacheKey function may either return an array of keys (often including
// the document) to be used as a cache key, or undefined to indicate the
// transform for this document should not be cached.
DocumentTransform.prototype.getCacheKey = function (document) {
return [document];
};
DocumentTransform.identity = function () {
// No need to cache this transform since it just returns the document
// unchanged. This should save a bit of memory that would otherwise be
// needed to populate the `documentCache` of this transform.
return new DocumentTransform(identity, { cache: false });
};
DocumentTransform.split = function (predicate, left, right) {
if (right === void 0) { right = DocumentTransform.identity(); }
return Object.assign(new DocumentTransform(function (document) {
var documentTransform = predicate(document) ? left : right;
return documentTransform.transformDocument(document);
},
// Reasonably assume both `left` and `right` transforms handle their own caching
{ cache: false }), { left: left, right: right });
};
/**
* Resets the internal cache of this transform, if it has one.
*/
DocumentTransform.prototype.resetCache = function () {
var _this = this;
if (this.cached) {
var stableCacheKeys_1 = new Trie(canUseWeakMap);
this.performWork = wrap(DocumentTransform.prototype.performWork.bind(this), {
makeCacheKey: function (document) {
var cacheKeys = _this.getCacheKey(document);
if (cacheKeys) {
invariant(Array.isArray(cacheKeys), 66);
return stableCacheKeys_1.lookupArray(cacheKeys);
}
},
max: cacheSizes["documentTransform.cache"],
cache: (WeakCache),
});
}
};
DocumentTransform.prototype.performWork = function (document) {
checkDocument(document);
return this.transform(document);
};
DocumentTransform.prototype.transformDocument = function (document) {
// If a user passes an already transformed result back to this function,
// immediately return it.
if (this.resultCache.has(document)) {
return document;
}
var transformedDocument = this.performWork(document);
this.resultCache.add(transformedDocument);
return transformedDocument;
};
DocumentTransform.prototype.concat = function (otherTransform) {
var _this = this;
return Object.assign(new DocumentTransform(function (document) {
return otherTransform.transformDocument(_this.transformDocument(document));
},
// Reasonably assume both transforms handle their own caching
{ cache: false }), {
left: this,
right: otherTransform,
});
};
return DocumentTransform;
}());
export { DocumentTransform };
//# sourceMappingURL=DocumentTransform.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/common/compact.js
/**
* Merges the provided objects shallowly and removes
* all properties with an `undefined` value
*/
export function compact() {
var objects = [];
for (var _i = 0; _i < arguments.length; _i++) {
objects[_i] = arguments[_i];
}
var result = Object.create(null);
objects.forEach(function (obj) {
if (!obj)
return;
Object.keys(obj).forEach(function (key) {
var value = obj[key];
if (value !== void 0) {
result[key] = value;
}
});
});
return result;
}
//# sourceMappingURL=compact.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/common/maybeDeepFreeze.js
import { isNonNullObject } from "./objects.js";
function deepFreeze(value) {
var workSet = new Set([value]);
workSet.forEach(function (obj) {
if (isNonNullObject(obj) && shallowFreeze(obj) === obj) {
Object.getOwnPropertyNames(obj).forEach(function (name) {
if (isNonNullObject(obj[name]))
workSet.add(obj[name]);
});
}
});
return value;
}
function shallowFreeze(obj) {
if (globalThis.__DEV__ !== false && !Object.isFrozen(obj)) {
try {
Object.freeze(obj);
}
catch (e) {
// Some types like Uint8Array and Node.js's Buffer cannot be frozen, but
// they all throw a TypeError when you try, so we re-throw any exceptions
// that are not TypeErrors, since that would be unexpected.
if (e instanceof TypeError)
return null;
throw e;
}
}
return obj;
}
export function maybeDeepFreeze(obj) {
if (globalThis.__DEV__ !== false) {
deepFreeze(obj);
}
return obj;
}
//# sourceMappingURL=maybeDeepFreeze.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/cache/inmemory/helpers.js
import { isReference, isField, DeepMerger, resultKeyNameFromField, shouldInclude, isNonNullObject, compact, createFragmentMap, getFragmentDefinitions, isArray, } from "../../utilities/index.js";
export var hasOwn = Object.prototype.hasOwnProperty;
export function isNullish(value) {
return value === null || value === void 0;
}
export { isArray };
export function defaultDataIdFromObject(_a, context) {
var __typename = _a.__typename, id = _a.id, _id = _a._id;
if (typeof __typename === "string") {
if (context) {
context.keyObject =
!isNullish(id) ? { id: id }
: !isNullish(_id) ? { _id: _id }
: void 0;
}
// If there is no object.id, fall back to object._id.
if (isNullish(id) && !isNullish(_id)) {
id = _id;
}
if (!isNullish(id)) {
return "".concat(__typename, ":").concat(typeof id === "number" || typeof id === "string" ?
id
: JSON.stringify(id));
}
}
}
var defaultConfig = {
dataIdFromObject: defaultDataIdFromObject,
addTypename: true,
resultCaching: true,
// Thanks to the shouldCanonizeResults helper, this should be the only line
// you have to change to reenable canonization by default in the future.
canonizeResults: false,
};
export function normalizeConfig(config) {
return compact(defaultConfig, config);
}
export function shouldCanonizeResults(config) {
var value = config.canonizeResults;
return value === void 0 ? defaultConfig.canonizeResults : value;
}
export function getTypenameFromStoreObject(store, objectOrReference) {
return isReference(objectOrReference) ?
store.get(objectOrReference.__ref, "__typename")
: objectOrReference && objectOrReference.__typename;
}
export var TypeOrFieldNameRegExp = /^[_a-z][_0-9a-z]*/i;
export function fieldNameFromStoreName(storeFieldName) {
var match = storeFieldName.match(TypeOrFieldNameRegExp);
return match ? match[0] : storeFieldName;
}
export function selectionSetMatchesResult(selectionSet, result, variables) {
if (isNonNullObject(result)) {
return isArray(result) ?
result.every(function (item) {
return selectionSetMatchesResult(selectionSet, item, variables);
})
: selectionSet.selections.every(function (field) {
if (isField(field) && shouldInclude(field, variables)) {
var key = resultKeyNameFromField(field);
return (hasOwn.call(result, key) &&
(!field.selectionSet ||
selectionSetMatchesResult(field.selectionSet, result[key], variables)));
}
// If the selection has been skipped with @skip(true) or
// @include(false), it should not count against the matching. If
// the selection is not a field, it must be a fragment (inline or
// named). We will determine if selectionSetMatchesResult for that
// fragment when we get to it, so for now we return true.
return true;
});
}
return false;
}
export function storeValueIsStoreObject(value) {
return isNonNullObject(value) && !isReference(value) && !isArray(value);
}
export function makeProcessedFieldsMerger() {
return new DeepMerger();
}
export function extractFragmentContext(document, fragments) {
// FragmentMap consisting only of fragments defined directly in document, not
// including other fragments registered in the FragmentRegistry.
var fragmentMap = createFragmentMap(getFragmentDefinitions(document));
return {
fragmentMap: fragmentMap,
lookupFragment: function (name) {
var def = fragmentMap[name];
if (!def && fragments) {
def = fragments.lookup(name);
}
return def || null;
},
};
}
//# sourceMappingURL=helpers.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/cache/inmemory/entityStore.js
import { __assign, __extends, __rest } from "tslib";
import { invariant } from "../../utilities/globals/index.js";
import { dep } from "optimism";
import { equal } from "@wry/equality";
import { Trie } from "@wry/trie";
import { isReference, makeReference, DeepMerger, maybeDeepFreeze, canUseWeakMap, isNonNullObject, } from "../../utilities/index.js";
import { hasOwn, fieldNameFromStoreName } from "./helpers.js";
var DELETE = Object.create(null);
var delModifier = function () { return DELETE; };
var INVALIDATE = Object.create(null);
var EntityStore = /** @class */ (function () {
function EntityStore(policies, group) {
var _this = this;
this.policies = policies;
this.group = group;
this.data = Object.create(null);
// Maps root entity IDs to the number of times they have been retained, minus
// the number of times they have been released. Retained entities keep other
// entities they reference (even indirectly) from being garbage collected.
this.rootIds = Object.create(null);
// Lazily tracks { __ref: <dataId> } strings contained by this.data[dataId].
this.refs = Object.create(null);
// Bound function that can be passed around to provide easy access to fields
// of Reference objects as well as ordinary objects.
this.getFieldValue = function (objectOrReference, storeFieldName) {
return maybeDeepFreeze(isReference(objectOrReference) ?
_this.get(objectOrReference.__ref, storeFieldName)
: objectOrReference && objectOrReference[storeFieldName]);
};
// Returns true for non-normalized StoreObjects and non-dangling
// References, indicating that readField(name, objOrRef) has a chance of
// working. Useful for filtering out dangling references from lists.
this.canRead = function (objOrRef) {
return isReference(objOrRef) ?
_this.has(objOrRef.__ref)
: typeof objOrRef === "object";
};
// Bound function that converts an id or an object with a __typename and
// primary key fields to a Reference object. If called with a Reference object,
// that same Reference object is returned. Pass true for mergeIntoStore to persist
// an object into the store.
this.toReference = function (objOrIdOrRef, mergeIntoStore) {
if (typeof objOrIdOrRef === "string") {
return makeReference(objOrIdOrRef);
}
if (isReference(objOrIdOrRef)) {
return objOrIdOrRef;
}
var id = _this.policies.identify(objOrIdOrRef)[0];
if (id) {
var ref = makeReference(id);
if (mergeIntoStore) {
_this.merge(id, objOrIdOrRef);
}
return ref;
}
};
}
// Although the EntityStore class is abstract, it contains concrete
// implementations of the various NormalizedCache interface methods that
// are inherited by the Root and Layer subclasses.
EntityStore.prototype.toObject = function () {
return __assign({}, this.data);
};
EntityStore.prototype.has = function (dataId) {
return this.lookup(dataId, true) !== void 0;
};
EntityStore.prototype.get = function (dataId, fieldName) {
this.group.depend(dataId, fieldName);
if (hasOwn.call(this.data, dataId)) {
var storeObject = this.data[dataId];
if (storeObject && hasOwn.call(storeObject, fieldName)) {
return storeObject[fieldName];
}
}
if (fieldName === "__typename" &&
hasOwn.call(this.policies.rootTypenamesById, dataId)) {
return this.policies.rootTypenamesById[dataId];
}
if (this instanceof Layer) {
return this.parent.get(dataId, fieldName);
}
};
EntityStore.prototype.lookup = function (dataId, dependOnExistence) {
// The has method (above) calls lookup with dependOnExistence = true, so
// that it can later be invalidated when we add or remove a StoreObject for
// this dataId. Any consumer who cares about the contents of the StoreObject
// should not rely on this dependency, since the contents could change
// without the object being added or removed.
if (dependOnExistence)
this.group.depend(dataId, "__exists");
if (hasOwn.call(this.data, dataId)) {
return this.data[dataId];
}
if (this instanceof Layer) {
return this.parent.lookup(dataId, dependOnExistence);
}
if (this.policies.rootTypenamesById[dataId]) {
return Object.create(null);
}
};
EntityStore.prototype.merge = function (older, newer) {
var _this = this;
var dataId;
// Convert unexpected references to ID strings.
if (isReference(older))
older = older.__ref;
if (isReference(newer))
newer = newer.__ref;
var existing = typeof older === "string" ? this.lookup((dataId = older)) : older;
var incoming = typeof newer === "string" ? this.lookup((dataId = newer)) : newer;
// If newer was a string ID, but that ID was not defined in this store,
// then there are no fields to be merged, so we're done.
if (!incoming)
return;
invariant(typeof dataId === "string", 1);
var merged = new DeepMerger(storeObjectReconciler).merge(existing, incoming);
// Even if merged === existing, existing may have come from a lower
// layer, so we always need to set this.data[dataId] on this level.
this.data[dataId] = merged;
if (merged !== existing) {
delete this.refs[dataId];
if (this.group.caching) {
var fieldsToDirty_1 = Object.create(null);
// If we added a new StoreObject where there was previously none, dirty
// anything that depended on the existence of this dataId, such as the
// EntityStore#has method.
if (!existing)
fieldsToDirty_1.__exists = 1;
// Now invalidate dependents who called getFieldValue for any fields
// that are changing as a result of this merge.
Object.keys(incoming).forEach(function (storeFieldName) {
if (!existing ||
existing[storeFieldName] !== merged[storeFieldName]) {
// Always dirty the full storeFieldName, which may include
// serialized arguments following the fieldName prefix.
fieldsToDirty_1[storeFieldName] = 1;
// Also dirty fieldNameFromStoreName(storeFieldName) if it's
// different from storeFieldName and this field does not have
// keyArgs configured, because that means the cache can't make
// any assumptions about how field values with the same field
// name but different arguments might be interrelated, so it
// must err on the side of invalidating all field values that
// share the same short fieldName, regardless of arguments.
var fieldName = fieldNameFromStoreName(storeFieldName);
if (fieldName !== storeFieldName &&
!_this.policies.hasKeyArgs(merged.__typename, fieldName)) {
fieldsToDirty_1[fieldName] = 1;
}
// If merged[storeFieldName] has become undefined, and this is the
// Root layer, actually delete the property from the merged object,
// which is guaranteed to have been created fresh in this method.
if (merged[storeFieldName] === void 0 && !(_this instanceof Layer)) {
delete merged[storeFieldName];
}
}
});
if (fieldsToDirty_1.__typename &&
!(existing && existing.__typename) &&
// Since we return default root __typename strings
// automatically from store.get, we don't need to dirty the
// ROOT_QUERY.__typename field if merged.__typename is equal
// to the default string (usually "Query").
this.policies.rootTypenamesById[dataId] === merged.__typename) {
delete fieldsToDirty_1.__typename;
}
Object.keys(fieldsToDirty_1).forEach(function (fieldName) {
return _this.group.dirty(dataId, fieldName);
});
}
}
};
EntityStore.prototype.modify = function (dataId, fields) {
var _this = this;
var storeObject = this.lookup(dataId);
if (storeObject) {
var changedFields_1 = Object.create(null);
var needToMerge_1 = false;
var allDeleted_1 = true;
var sharedDetails_1 = {
DELETE: DELETE,
INVALIDATE: INVALIDATE,
isReference: isReference,
toReference: this.toReference,
canRead: this.canRead,
readField: function (fieldNameOrOptions, from) {
return _this.policies.readField(typeof fieldNameOrOptions === "string" ?
{
fieldName: fieldNameOrOptions,
from: from || makeReference(dataId),
}
: fieldNameOrOptions, { store: _this });
},
};
Object.keys(storeObject).forEach(function (storeFieldName) {
var fieldName = fieldNameFromStoreName(storeFieldName);
var fieldValue = storeObject[storeFieldName];
if (fieldValue === void 0)
return;
var modify = typeof fields === "function" ? fields : (fields[storeFieldName] || fields[fieldName]);
if (modify) {
var newValue = modify === delModifier ? DELETE : (modify(maybeDeepFreeze(fieldValue), __assign(__assign({}, sharedDetails_1), { fieldName: fieldName, storeFieldName: storeFieldName, storage: _this.getStorage(dataId, storeFieldName) })));
if (newValue === INVALIDATE) {
_this.group.dirty(dataId, storeFieldName);
}
else {
if (newValue === DELETE)
newValue = void 0;
if (newValue !== fieldValue) {
changedFields_1[storeFieldName] = newValue;
needToMerge_1 = true;
fieldValue = newValue;
if (globalThis.__DEV__ !== false) {
var checkReference = function (ref) {
if (_this.lookup(ref.__ref) === undefined) {
globalThis.__DEV__ !== false && invariant.warn(2, ref);
return true;
}
};
if (isReference(newValue)) {
checkReference(newValue);
}
else if (Array.isArray(newValue)) {
// Warn about writing "mixed" arrays of Reference and non-Reference objects
var seenReference = false;
var someNonReference = void 0;
for (var _i = 0, newValue_1 = newValue; _i < newValue_1.length; _i++) {
var value = newValue_1[_i];
if (isReference(value)) {
seenReference = true;
if (checkReference(value))
break;
}
else {
// Do not warn on primitive values, since those could never be represented
// by a reference. This is a valid (albeit uncommon) use case.
if (typeof value === "object" && !!value) {
var id = _this.policies.identify(value)[0];
// check if object could even be referenced, otherwise we are not interested in it for this warning
if (id) {
someNonReference = value;
}
}
}
if (seenReference && someNonReference !== undefined) {
globalThis.__DEV__ !== false && invariant.warn(3, someNonReference);
break;
}
}
}
}
}
}
}
if (fieldValue !== void 0) {
allDeleted_1 = false;
}
});
if (needToMerge_1) {
this.merge(dataId, changedFields_1);
if (allDeleted_1) {
if (this instanceof Layer) {
this.data[dataId] = void 0;
}
else {
delete this.data[dataId];
}
this.group.dirty(dataId, "__exists");
}
return true;
}
}
return false;
};
// If called with only one argument, removes the entire entity
// identified by dataId. If called with a fieldName as well, removes all
// fields of that entity whose names match fieldName according to the
// fieldNameFromStoreName helper function. If called with a fieldName
// and variables, removes all fields of that entity whose names match fieldName
// and whose arguments when cached exactly match the variables passed.
EntityStore.prototype.delete = function (dataId, fieldName, args) {
var _a;
var storeObject = this.lookup(dataId);
if (storeObject) {
var typename = this.getFieldValue(storeObject, "__typename");
var storeFieldName = fieldName && args ?
this.policies.getStoreFieldName({ typename: typename, fieldName: fieldName, args: args })
: fieldName;
return this.modify(dataId, storeFieldName ? (_a = {},
_a[storeFieldName] = delModifier,
_a) : delModifier);
}
return false;
};
EntityStore.prototype.evict = function (options, limit) {
var evicted = false;
if (options.id) {
if (hasOwn.call(this.data, options.id)) {
evicted = this.delete(options.id, options.fieldName, options.args);
}
if (this instanceof Layer && this !== limit) {
evicted = this.parent.evict(options, limit) || evicted;
}
// Always invalidate the field to trigger rereading of watched
// queries, even if no cache data was modified by the eviction,
// because queries may depend on computed fields with custom read
// functions, whose values are not stored in the EntityStore.
if (options.fieldName || evicted) {
this.group.dirty(options.id, options.fieldName || "__exists");
}
}
return evicted;
};
EntityStore.prototype.clear = function () {
this.replace(null);
};
EntityStore.prototype.extract = function () {
var _this = this;
var obj = this.toObject();
var extraRootIds = [];
this.getRootIdSet().forEach(function (id) {
if (!hasOwn.call(_this.policies.rootTypenamesById, id)) {
extraRootIds.push(id);
}
});
if (extraRootIds.length) {
obj.__META = { extraRootIds: extraRootIds.sort() };
}
return obj;
};
EntityStore.prototype.replace = function (newData) {
var _this = this;
Object.keys(this.data).forEach(function (dataId) {
if (!(newData && hasOwn.call(newData, dataId))) {
_this.delete(dataId);
}
});
if (newData) {
var __META = newData.__META, rest_1 = __rest(newData, ["__META"]);
Object.keys(rest_1).forEach(function (dataId) {
_this.merge(dataId, rest_1[dataId]);
});
if (__META) {
__META.extraRootIds.forEach(this.retain, this);
}
}
};
EntityStore.prototype.retain = function (rootId) {
return (this.rootIds[rootId] = (this.rootIds[rootId] || 0) + 1);
};
EntityStore.prototype.release = function (rootId) {
if (this.rootIds[rootId] > 0) {
var count = --this.rootIds[rootId];
if (!count)
delete this.rootIds[rootId];
return count;
}
return 0;
};
// Return a Set<string> of all the ID strings that have been retained by
// this layer/root *and* any layers/roots beneath it.
EntityStore.prototype.getRootIdSet = function (ids) {
if (ids === void 0) { ids = new Set(); }
Object.keys(this.rootIds).forEach(ids.add, ids);
if (this instanceof Layer) {
this.parent.getRootIdSet(ids);
}
else {
// Official singleton IDs like ROOT_QUERY and ROOT_MUTATION are
// always considered roots for garbage collection, regardless of
// their retainment counts in this.rootIds.
Object.keys(this.policies.rootTypenamesById).forEach(ids.add, ids);
}
return ids;
};
// The goal of garbage collection is to remove IDs from the Root layer of the
// store that are no longer reachable starting from any IDs that have been
// explicitly retained (see retain and release, above). Returns an array of
// dataId strings that were removed from the store.
EntityStore.prototype.gc = function () {
var _this = this;
var ids = this.getRootIdSet();
var snapshot = this.toObject();
ids.forEach(function (id) {
if (hasOwn.call(snapshot, id)) {
// Because we are iterating over an ECMAScript Set, the IDs we add here
// will be visited in later iterations of the forEach loop only if they
// were not previously contained by the Set.
Object.keys(_this.findChildRefIds(id)).forEach(ids.add, ids);
// By removing IDs from the snapshot object here, we protect them from
// getting removed from the root store layer below.
delete snapshot[id];
}
});
var idsToRemove = Object.keys(snapshot);
if (idsToRemove.length) {
var root_1 = this;
while (root_1 instanceof Layer)
root_1 = root_1.parent;
idsToRemove.forEach(function (id) { return root_1.delete(id); });
}
return idsToRemove;
};
EntityStore.prototype.findChildRefIds = function (dataId) {
if (!hasOwn.call(this.refs, dataId)) {
var found_1 = (this.refs[dataId] = Object.create(null));
var root = this.data[dataId];
if (!root)
return found_1;
var workSet_1 = new Set([root]);
// Within the store, only arrays and objects can contain child entity
// references, so we can prune the traversal using this predicate:
workSet_1.forEach(function (obj) {
if (isReference(obj)) {
found_1[obj.__ref] = true;
// In rare cases, a { __ref } Reference object may have other fields.
// This often indicates a mismerging of References with StoreObjects,
// but garbage collection should not be fooled by a stray __ref
// property in a StoreObject (ignoring all the other fields just
// because the StoreObject looks like a Reference). To avoid this
// premature termination of findChildRefIds recursion, we fall through
// to the code below, which will handle any other properties of obj.
}
if (isNonNullObject(obj)) {
Object.keys(obj).forEach(function (key) {
var child = obj[key];
// No need to add primitive values to the workSet, since they cannot
// contain reference objects.
if (isNonNullObject(child)) {
workSet_1.add(child);
}
});
}
});
}
return this.refs[dataId];
};
EntityStore.prototype.makeCacheKey = function () {
return this.group.keyMaker.lookupArray(arguments);
};
return EntityStore;
}());
export { EntityStore };
// A single CacheGroup represents a set of one or more EntityStore objects,
// typically the Root store in a CacheGroup by itself, and all active Layer
// stores in a group together. A single EntityStore object belongs to only
// one CacheGroup, store.group. The CacheGroup is responsible for tracking
// dependencies, so store.group is helpful for generating unique keys for
// cached results that need to be invalidated when/if those dependencies
// change. If we used the EntityStore objects themselves as cache keys (that
// is, store rather than store.group), the cache would become unnecessarily
// fragmented by all the different Layer objects. Instead, the CacheGroup
// approach allows all optimistic Layer objects in the same linked list to
// belong to one CacheGroup, with the non-optimistic Root object belonging
// to another CacheGroup, allowing resultCaching dependencies to be tracked
// separately for optimistic and non-optimistic entity data.
var CacheGroup = /** @class */ (function () {
function CacheGroup(caching, parent) {
if (parent === void 0) { parent = null; }
this.caching = caching;
this.parent = parent;
this.d = null;
this.resetCaching();
}
CacheGroup.prototype.resetCaching = function () {
this.d = this.caching ? dep() : null;
this.keyMaker = new Trie(canUseWeakMap);
};
CacheGroup.prototype.depend = function (dataId, storeFieldName) {
if (this.d) {
this.d(makeDepKey(dataId, storeFieldName));
var fieldName = fieldNameFromStoreName(storeFieldName);
if (fieldName !== storeFieldName) {
// Fields with arguments that contribute extra identifying
// information to the fieldName (thus forming the storeFieldName)
// depend not only on the full storeFieldName but also on the
// short fieldName, so the field can be invalidated using either
// level of specificity.
this.d(makeDepKey(dataId, fieldName));
}
if (this.parent) {
this.parent.depend(dataId, storeFieldName);
}
}
};
CacheGroup.prototype.dirty = function (dataId, storeFieldName) {
if (this.d) {
this.d.dirty(makeDepKey(dataId, storeFieldName),
// When storeFieldName === "__exists", that means the entity identified
// by dataId has either disappeared from the cache or was newly added,
// so the result caching system would do well to "forget everything it
// knows" about that object. To achieve that kind of invalidation, we
// not only dirty the associated result cache entry, but also remove it
// completely from the dependency graph. For the optimism implementation
// details, see https://github.com/benjamn/optimism/pull/195.
storeFieldName === "__exists" ? "forget" : "setDirty");
}
};
return CacheGroup;
}());
function makeDepKey(dataId, storeFieldName) {
// Since field names cannot have '#' characters in them, this method
// of joining the field name and the ID should be unambiguous, and much
// cheaper than JSON.stringify([dataId, fieldName]).
return storeFieldName + "#" + dataId;
}
export function maybeDependOnExistenceOfEntity(store, entityId) {
if (supportsResultCaching(store)) {
// We use this pseudo-field __exists elsewhere in the EntityStore code to
// represent changes in the existence of the entity object identified by
// entityId. This dependency gets reliably dirtied whenever an object with
// this ID is deleted (or newly created) within this group, so any result
// cache entries (for example, StoreReader#executeSelectionSet results) that
// depend on __exists for this entityId will get dirtied as well, leading to
// the eventual recomputation (instead of reuse) of those result objects the
// next time someone reads them from the cache.
store.group.depend(entityId, "__exists");
}
}
(function (EntityStore) {
// Refer to this class as EntityStore.Root outside this namespace.
var Root = /** @class */ (function (_super) {
__extends(Root, _super);
function Root(_a) {
var policies = _a.policies, _b = _a.resultCaching, resultCaching = _b === void 0 ? true : _b, seed = _a.seed;
var _this = _super.call(this, policies, new CacheGroup(resultCaching)) || this;
_this.stump = new Stump(_this);
_this.storageTrie = new Trie(canUseWeakMap);
if (seed)
_this.replace(seed);
return _this;
}
Root.prototype.addLayer = function (layerId, replay) {
// Adding an optimistic Layer on top of the Root actually adds the Layer
// on top of the Stump, so the Stump always comes between the Root and
// any Layer objects that we've added.
return this.stump.addLayer(layerId, replay);
};
Root.prototype.removeLayer = function () {
// Never remove the root layer.
return this;
};
Root.prototype.getStorage = function () {
return this.storageTrie.lookupArray(arguments);
};
return Root;
}(EntityStore));
EntityStore.Root = Root;
})(EntityStore || (EntityStore = {}));
// Not exported, since all Layer instances are created by the addLayer method
// of the EntityStore.Root class.
var Layer = /** @class */ (function (_super) {
__extends(Layer, _super);
function Layer(id, parent, replay, group) {
var _this = _super.call(this, parent.policies, group) || this;
_this.id = id;
_this.parent = parent;
_this.replay = replay;
_this.group = group;
replay(_this);
return _this;
}
Layer.prototype.addLayer = function (layerId, replay) {
return new Layer(layerId, this, replay, this.group);
};
Layer.prototype.removeLayer = function (layerId) {
var _this = this;
// Remove all instances of the given id, not just the first one.
var parent = this.parent.removeLayer(layerId);
if (layerId === this.id) {
if (this.group.caching) {
// Dirty every ID we're removing. Technically we might be able to avoid
// dirtying fields that have values in higher layers, but we don't have
// easy access to higher layers here, and we're about to recreate those
// layers anyway (see parent.addLayer below).
Object.keys(this.data).forEach(function (dataId) {
var ownStoreObject = _this.data[dataId];
var parentStoreObject = parent["lookup"](dataId);
if (!parentStoreObject) {
// The StoreObject identified by dataId was defined in this layer
// but will be undefined in the parent layer, so we can delete the
// whole entity using this.delete(dataId). Since we're about to
// throw this layer away, the only goal of this deletion is to dirty
// the removed fields.
_this.delete(dataId);
}
else if (!ownStoreObject) {
// This layer had an entry for dataId but it was undefined, which
// means the entity was deleted in this layer, and it's about to
// become undeleted when we remove this layer, so we need to dirty
// all fields that are about to be reexposed.
_this.group.dirty(dataId, "__exists");
Object.keys(parentStoreObject).forEach(function (storeFieldName) {
_this.group.dirty(dataId, storeFieldName);
});
}
else if (ownStoreObject !== parentStoreObject) {
// If ownStoreObject is not exactly the same as parentStoreObject,
// dirty any fields whose values will change as a result of this
// removal.
Object.keys(ownStoreObject).forEach(function (storeFieldName) {
if (!equal(ownStoreObject[storeFieldName], parentStoreObject[storeFieldName])) {
_this.group.dirty(dataId, storeFieldName);
}
});
}
});
}
return parent;
}
// No changes are necessary if the parent chain remains identical.
if (parent === this.parent)
return this;
// Recreate this layer on top of the new parent.
return parent.addLayer(this.id, this.replay);
};
Layer.prototype.toObject = function () {
return __assign(__assign({}, this.parent.toObject()), this.data);
};
Layer.prototype.findChildRefIds = function (dataId) {
var fromParent = this.parent.findChildRefIds(dataId);
return hasOwn.call(this.data, dataId) ? __assign(__assign({}, fromParent), _super.prototype.findChildRefIds.call(this, dataId)) : fromParent;
};
Layer.prototype.getStorage = function () {
var p = this.parent;
while (p.parent)
p = p.parent;
return p.getStorage.apply(p,
// @ts-expect-error
arguments);
};
return Layer;
}(EntityStore));
// Represents a Layer permanently installed just above the Root, which allows
// reading optimistically (and registering optimistic dependencies) even when
// no optimistic layers are currently active. The stump.group CacheGroup object
// is shared by any/all Layer objects added on top of the Stump.
var Stump = /** @class */ (function (_super) {
__extends(Stump, _super);
function Stump(root) {
return _super.call(this, "EntityStore.Stump", root, function () { }, new CacheGroup(root.group.caching, root.group)) || this;
}
Stump.prototype.removeLayer = function () {
// Never remove the Stump layer.
return this;
};
Stump.prototype.merge = function (older, newer) {
// We never want to write any data into the Stump, so we forward any merge
// calls to the Root instead. Another option here would be to throw an
// exception, but the toReference(object, true) function can sometimes
// trigger Stump writes (which used to be Root writes, before the Stump
// concept was introduced).
return this.parent.merge(older, newer);
};
return Stump;
}(Layer));
function storeObjectReconciler(existingObject, incomingObject, property) {
var existingValue = existingObject[property];
var incomingValue = incomingObject[property];
// Wherever there is a key collision, prefer the incoming value, unless
// it is deeply equal to the existing value. It's worth checking deep
// equality here (even though blindly returning incoming would be
// logically correct) because preserving the referential identity of
// existing data can prevent needless rereading and rerendering.
return equal(existingValue, incomingValue) ? existingValue : incomingValue;
}
export function supportsResultCaching(store) {
// When result caching is disabled, store.depend will be null.
return !!(store instanceof EntityStore && store.group.caching);
}
//# sourceMappingURL=entityStore.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/cache/inmemory/object-canon.js
import { __assign } from "tslib";
import { Trie } from "@wry/trie";
import { canUseWeakMap, canUseWeakSet, isNonNullObject as isObjectOrArray, } from "../../utilities/index.js";
import { isArray } from "./helpers.js";
function shallowCopy(value) {
if (isObjectOrArray(value)) {
return isArray(value) ?
value.slice(0)
: __assign({ __proto__: Object.getPrototypeOf(value) }, value);
}
return value;
}
// When programmers talk about the "canonical form" of an object, they
// usually have the following meaning in mind, which I've copied from
// https://en.wiktionary.org/wiki/canonical_form:
//
// 1. A standard or normal presentation of a mathematical entity [or
// object]. A canonical form is an element of a set of representatives
// of equivalence classes of forms such that there is a function or
// procedure which projects every element of each equivalence class
// onto that one element, the canonical form of that equivalence
// class. The canonical form is expected to be simpler than the rest of
// the forms in some way.
//
// That's a long-winded way of saying any two objects that have the same
// canonical form may be considered equivalent, even if they are !==,
// which usually means the objects are structurally equivalent (deeply
// equal), but don't necessarily use the same memory.
//
// Like a literary or musical canon, this ObjectCanon class represents a
// collection of unique canonical items (JavaScript objects), with the
// important property that canon.admit(a) === canon.admit(b) if a and b
// are deeply equal to each other. In terms of the definition above, the
// canon.admit method is the "function or procedure which projects every"
// object "onto that one element, the canonical form."
//
// In the worst case, the canonicalization process may involve looking at
// every property in the provided object tree, so it takes the same order
// of time as deep equality checking. Fortunately, already-canonicalized
// objects are returned immediately from canon.admit, so the presence of
// canonical subtrees tends to speed up canonicalization.
//
// Since consumers of canonical objects can check for deep equality in
// constant time, canonicalizing cache results can massively improve the
// performance of application code that skips re-rendering unchanged
// results, such as "pure" UI components in a framework like React.
//
// Of course, since canonical objects may be shared widely between
// unrelated consumers, it's important to think of them as immutable, even
// though they are not actually frozen with Object.freeze in production,
// due to the extra performance overhead that comes with frozen objects.
//
// Custom scalar objects whose internal class name is neither Array nor
// Object can be included safely in the admitted tree, but they will not
// be replaced with a canonical version (to put it another way, they are
// assumed to be canonical already).
//
// If we ignore custom objects, no detection of cycles or repeated object
// references is currently required by the StoreReader class, since
// GraphQL result objects are JSON-serializable trees (and thus contain
// neither cycles nor repeated subtrees), so we can avoid the complexity
// of keeping track of objects we've already seen during the recursion of
// the admit method.
//
// In the future, we may consider adding additional cases to the switch
// statement to handle other common object types, such as "[object Date]"
// objects, as needed.
var ObjectCanon = /** @class */ (function () {
function ObjectCanon() {
// Set of all canonical objects this ObjectCanon has admitted, allowing
// canon.admit to return previously-canonicalized objects immediately.
this.known = new (canUseWeakSet ? WeakSet : Set)();
// Efficient storage/lookup structure for canonical objects.
this.pool = new Trie(canUseWeakMap);
// Make the ObjectCanon assume this value has already been
// canonicalized.
this.passes = new WeakMap();
// Arrays that contain the same elements in a different order can share
// the same SortedKeysInfo object, to save memory.
this.keysByJSON = new Map();
// This has to come last because it depends on keysByJSON.
this.empty = this.admit({});
}
ObjectCanon.prototype.isKnown = function (value) {
return isObjectOrArray(value) && this.known.has(value);
};
ObjectCanon.prototype.pass = function (value) {
if (isObjectOrArray(value)) {
var copy = shallowCopy(value);
this.passes.set(copy, value);
return copy;
}
return value;
};
ObjectCanon.prototype.admit = function (value) {
var _this = this;
if (isObjectOrArray(value)) {
var original = this.passes.get(value);
if (original)
return original;
var proto = Object.getPrototypeOf(value);
switch (proto) {
case Array.prototype: {
if (this.known.has(value))
return value;
var array = value.map(this.admit, this);
// Arrays are looked up in the Trie using their recursively
// canonicalized elements, and the known version of the array is
// preserved as node.array.
var node = this.pool.lookupArray(array);
if (!node.array) {
this.known.add((node.array = array));
// Since canonical arrays may be shared widely between
// unrelated consumers, it's important to regard them as
// immutable, even if they are not frozen in production.
if (globalThis.__DEV__ !== false) {
Object.freeze(array);
}
}
return node.array;
}
case null:
case Object.prototype: {
if (this.known.has(value))
return value;
var proto_1 = Object.getPrototypeOf(value);
var array_1 = [proto_1];
var keys = this.sortedKeys(value);
array_1.push(keys.json);
var firstValueIndex_1 = array_1.length;
keys.sorted.forEach(function (key) {
array_1.push(_this.admit(value[key]));
});
// Objects are looked up in the Trie by their prototype (which
// is *not* recursively canonicalized), followed by a JSON
// representation of their (sorted) keys, followed by the
// sequence of recursively canonicalized values corresponding to
// those keys. To keep the final results unambiguous with other
// sequences (such as arrays that just happen to contain [proto,
// keys.json, value1, value2, ...]), the known version of the
// object is stored as node.object.
var node = this.pool.lookupArray(array_1);
if (!node.object) {
var obj_1 = (node.object = Object.create(proto_1));
this.known.add(obj_1);
keys.sorted.forEach(function (key, i) {
obj_1[key] = array_1[firstValueIndex_1 + i];
});
// Since canonical objects may be shared widely between
// unrelated consumers, it's important to regard them as
// immutable, even if they are not frozen in production.
if (globalThis.__DEV__ !== false) {
Object.freeze(obj_1);
}
}
return node.object;
}
}
}
return value;
};
// It's worthwhile to cache the sorting of arrays of strings, since the
// same initial unsorted arrays tend to be encountered many times.
// Fortunately, we can reuse the Trie machinery to look up the sorted
// arrays in linear time (which is faster than sorting large arrays).
ObjectCanon.prototype.sortedKeys = function (obj) {
var keys = Object.keys(obj);
var node = this.pool.lookupArray(keys);
if (!node.keys) {
keys.sort();
var json = JSON.stringify(keys);
if (!(node.keys = this.keysByJSON.get(json))) {
this.keysByJSON.set(json, (node.keys = { sorted: keys, json: json }));
}
}
return node.keys;
};
return ObjectCanon;
}());
export { ObjectCanon };
//# sourceMappingURL=object-canon.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/cache/inmemory/readFromStore.js
import { __assign } from "tslib";
import { invariant, newInvariantError } from "../../utilities/globals/index.js";
import { Kind } from "graphql";
import { wrap } from "optimism";
import { isField, resultKeyNameFromField, isReference, makeReference, shouldInclude, addTypenameToDocument, getDefaultValues, getMainDefinition, getQueryDefinition, getFragmentFromSelection, maybeDeepFreeze, mergeDeepArray, DeepMerger, isNonNullObject, canUseWeakMap, compact, canonicalStringify, cacheSizes, } from "../../utilities/index.js";
import { maybeDependOnExistenceOfEntity, supportsResultCaching, } from "./entityStore.js";
import { isArray, extractFragmentContext, getTypenameFromStoreObject, shouldCanonizeResults, } from "./helpers.js";
import { MissingFieldError } from "../core/types/common.js";
import { ObjectCanon } from "./object-canon.js";
function execSelectionSetKeyArgs(options) {
return [
options.selectionSet,
options.objectOrReference,
options.context,
// We split out this property so we can pass different values
// independently without modifying options.context itself.
options.context.canonizeResults,
];
}
var StoreReader = /** @class */ (function () {
function StoreReader(config) {
var _this = this;
this.knownResults = new (canUseWeakMap ? WeakMap : Map)();
this.config = compact(config, {
addTypename: config.addTypename !== false,
canonizeResults: shouldCanonizeResults(config),
});
this.canon = config.canon || new ObjectCanon();
// memoized functions in this class will be "garbage-collected"
// by recreating the whole `StoreReader` in
// `InMemoryCache.resetResultsCache`
// (triggered from `InMemoryCache.gc` with `resetResultCache: true`)
this.executeSelectionSet = wrap(function (options) {
var _a;
var canonizeResults = options.context.canonizeResults;
var peekArgs = execSelectionSetKeyArgs(options);
// Negate this boolean option so we can find out if we've already read
// this result using the other boolean value.
peekArgs[3] = !canonizeResults;
var other = (_a = _this.executeSelectionSet).peek.apply(_a, peekArgs);
if (other) {
if (canonizeResults) {
return __assign(__assign({}, other), {
// If we previously read this result without canonizing it, we can
// reuse that result simply by canonizing it now.
result: _this.canon.admit(other.result) });
}
// If we previously read this result with canonization enabled, we can
// return that canonized result as-is.
return other;
}
maybeDependOnExistenceOfEntity(options.context.store, options.enclosingRef.__ref);
// Finally, if we didn't find any useful previous results, run the real
// execSelectionSetImpl method with the given options.
return _this.execSelectionSetImpl(options);
}, {
max: this.config.resultCacheMaxSize ||
cacheSizes["inMemoryCache.executeSelectionSet"] ||
50000 /* defaultCacheSizes["inMemoryCache.executeSelectionSet"] */,
keyArgs: execSelectionSetKeyArgs,
// Note that the parameters of makeCacheKey are determined by the
// array returned by keyArgs.
makeCacheKey: function (selectionSet, parent, context, canonizeResults) {
if (supportsResultCaching(context.store)) {
return context.store.makeCacheKey(selectionSet, isReference(parent) ? parent.__ref : parent, context.varString, canonizeResults);
}
},
});
this.executeSubSelectedArray = wrap(function (options) {
maybeDependOnExistenceOfEntity(options.context.store, options.enclosingRef.__ref);
return _this.execSubSelectedArrayImpl(options);
}, {
max: this.config.resultCacheMaxSize ||
cacheSizes["inMemoryCache.executeSubSelectedArray"] ||
10000 /* defaultCacheSizes["inMemoryCache.executeSubSelectedArray"] */,
makeCacheKey: function (_a) {
var field = _a.field, array = _a.array, context = _a.context;
if (supportsResultCaching(context.store)) {
return context.store.makeCacheKey(field, array, context.varString);
}
},
});
}
StoreReader.prototype.resetCanon = function () {
this.canon = new ObjectCanon();
};
/**
* Given a store and a query, return as much of the result as possible and
* identify if any data was missing from the store.
*/
StoreReader.prototype.diffQueryAgainstStore = function (_a) {
var store = _a.store, query = _a.query, _b = _a.rootId, rootId = _b === void 0 ? "ROOT_QUERY" : _b, variables = _a.variables, _c = _a.returnPartialData, returnPartialData = _c === void 0 ? true : _c, _d = _a.canonizeResults, canonizeResults = _d === void 0 ? this.config.canonizeResults : _d;
var policies = this.config.cache.policies;
variables = __assign(__assign({}, getDefaultValues(getQueryDefinition(query))), variables);
var rootRef = makeReference(rootId);
var execResult = this.executeSelectionSet({
selectionSet: getMainDefinition(query).selectionSet,
objectOrReference: rootRef,
enclosingRef: rootRef,
context: __assign({ store: store, query: query, policies: policies, variables: variables, varString: canonicalStringify(variables), canonizeResults: canonizeResults }, extractFragmentContext(query, this.config.fragments)),
});
var missing;
if (execResult.missing) {
// For backwards compatibility we still report an array of
// MissingFieldError objects, even though there will only ever be at most
// one of them, now that all missing field error messages are grouped
// together in the execResult.missing tree.
missing = [
new MissingFieldError(firstMissing(execResult.missing), execResult.missing, query, variables),
];
if (!returnPartialData) {
throw missing[0];
}
}
return {
result: execResult.result,
complete: !missing,
missing: missing,
};
};
StoreReader.prototype.isFresh = function (result, parent, selectionSet, context) {
if (supportsResultCaching(context.store) &&
this.knownResults.get(result) === selectionSet) {
var latest = this.executeSelectionSet.peek(selectionSet, parent, context,
// If result is canonical, then it could only have been previously
// cached by the canonizing version of executeSelectionSet, so we can
// avoid checking both possibilities here.
this.canon.isKnown(result));
if (latest && result === latest.result) {
return true;
}
}
return false;
};
// Uncached version of executeSelectionSet.
StoreReader.prototype.execSelectionSetImpl = function (_a) {
var _this = this;
var selectionSet = _a.selectionSet, objectOrReference = _a.objectOrReference, enclosingRef = _a.enclosingRef, context = _a.context;
if (isReference(objectOrReference) &&
!context.policies.rootTypenamesById[objectOrReference.__ref] &&
!context.store.has(objectOrReference.__ref)) {
return {
result: this.canon.empty,
missing: "Dangling reference to missing ".concat(objectOrReference.__ref, " object"),
};
}
var variables = context.variables, policies = context.policies, store = context.store;
var typename = store.getFieldValue(objectOrReference, "__typename");
var objectsToMerge = [];
var missing;
var missingMerger = new DeepMerger();
if (this.config.addTypename &&
typeof typename === "string" &&
!policies.rootIdsByTypename[typename]) {
// Ensure we always include a default value for the __typename
// field, if we have one, and this.config.addTypename is true. Note
// that this field can be overridden by other merged objects.
objectsToMerge.push({ __typename: typename });
}
function handleMissing(result, resultName) {
var _a;
if (result.missing) {
missing = missingMerger.merge(missing, (_a = {},
_a[resultName] = result.missing,
_a));
}
return result.result;
}
var workSet = new Set(selectionSet.selections);
workSet.forEach(function (selection) {
var _a, _b;
// Omit fields with directives @skip(if: <truthy value>) or
// @include(if: <falsy value>).
if (!shouldInclude(selection, variables))
return;
if (isField(selection)) {
var fieldValue = policies.readField({
fieldName: selection.name.value,
field: selection,
variables: context.variables,
from: objectOrReference,
}, context);
var resultName = resultKeyNameFromField(selection);
if (fieldValue === void 0) {
if (!addTypenameToDocument.added(selection)) {
missing = missingMerger.merge(missing, (_a = {},
_a[resultName] = "Can't find field '".concat(selection.name.value, "' on ").concat(isReference(objectOrReference) ?
objectOrReference.__ref + " object"
: "object " + JSON.stringify(objectOrReference, null, 2)),
_a));
}
}
else if (isArray(fieldValue)) {
fieldValue = handleMissing(_this.executeSubSelectedArray({
field: selection,
array: fieldValue,
enclosingRef: enclosingRef,
context: context,
}), resultName);
}
else if (!selection.selectionSet) {
// If the field does not have a selection set, then we handle it
// as a scalar value. To keep this.canon from canonicalizing
// this value, we use this.canon.pass to wrap fieldValue in a
// Pass object that this.canon.admit will later unwrap as-is.
if (context.canonizeResults) {
fieldValue = _this.canon.pass(fieldValue);
}
}
else if (fieldValue != null) {
// In this case, because we know the field has a selection set,
// it must be trying to query a GraphQLObjectType, which is why
// fieldValue must be != null.
fieldValue = handleMissing(_this.executeSelectionSet({
selectionSet: selection.selectionSet,
objectOrReference: fieldValue,
enclosingRef: isReference(fieldValue) ? fieldValue : enclosingRef,
context: context,
}), resultName);
}
if (fieldValue !== void 0) {
objectsToMerge.push((_b = {}, _b[resultName] = fieldValue, _b));
}
}
else {
var fragment = getFragmentFromSelection(selection, context.lookupFragment);
if (!fragment && selection.kind === Kind.FRAGMENT_SPREAD) {
throw newInvariantError(9, selection.name.value);
}
if (fragment && policies.fragmentMatches(fragment, typename)) {
fragment.selectionSet.selections.forEach(workSet.add, workSet);
}
}
});
var result = mergeDeepArray(objectsToMerge);
var finalResult = { result: result, missing: missing };
var frozen = context.canonizeResults ?
this.canon.admit(finalResult)
// Since this.canon is normally responsible for freezing results (only in
// development), freeze them manually if canonization is disabled.
: maybeDeepFreeze(finalResult);
// Store this result with its selection set so that we can quickly
// recognize it again in the StoreReader#isFresh method.
if (frozen.result) {
this.knownResults.set(frozen.result, selectionSet);
}
return frozen;
};
// Uncached version of executeSubSelectedArray.
StoreReader.prototype.execSubSelectedArrayImpl = function (_a) {
var _this = this;
var field = _a.field, array = _a.array, enclosingRef = _a.enclosingRef, context = _a.context;
var missing;
var missingMerger = new DeepMerger();
function handleMissing(childResult, i) {
var _a;
if (childResult.missing) {
missing = missingMerger.merge(missing, (_a = {}, _a[i] = childResult.missing, _a));
}
return childResult.result;
}
if (field.selectionSet) {
array = array.filter(context.store.canRead);
}
array = array.map(function (item, i) {
// null value in array
if (item === null) {
return null;
}
// This is a nested array, recurse
if (isArray(item)) {
return handleMissing(_this.executeSubSelectedArray({
field: field,
array: item,
enclosingRef: enclosingRef,
context: context,
}), i);
}
// This is an object, run the selection set on it
if (field.selectionSet) {
return handleMissing(_this.executeSelectionSet({
selectionSet: field.selectionSet,
objectOrReference: item,
enclosingRef: isReference(item) ? item : enclosingRef,
context: context,
}), i);
}
if (globalThis.__DEV__ !== false) {
assertSelectionSetForIdValue(context.store, field, item);
}
return item;
});
return {
result: context.canonizeResults ? this.canon.admit(array) : array,
missing: missing,
};
};
return StoreReader;
}());
export { StoreReader };
function firstMissing(tree) {
try {
JSON.stringify(tree, function (_, value) {
if (typeof value === "string")
throw value;
return value;
});
}
catch (result) {
return result;
}
}
function assertSelectionSetForIdValue(store, field, fieldValue) {
if (!field.selectionSet) {
var workSet_1 = new Set([fieldValue]);
workSet_1.forEach(function (value) {
if (isNonNullObject(value)) {
invariant(
!isReference(value),
10,
getTypenameFromStoreObject(store, value),
field.name.value
);
Object.values(value).forEach(workSet_1.add, workSet_1);
}
});
}
}
//# sourceMappingURL=readFromStore.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/common/cloneDeep.js
var toString = Object.prototype.toString;
/**
* Deeply clones a value to create a new instance.
*/
export function cloneDeep(value) {
return cloneDeepHelper(value);
}
function cloneDeepHelper(val, seen) {
switch (toString.call(val)) {
case "[object Array]": {
seen = seen || new Map();
if (seen.has(val))
return seen.get(val);
var copy_1 = val.slice(0);
seen.set(val, copy_1);
copy_1.forEach(function (child, i) {
copy_1[i] = cloneDeepHelper(child, seen);
});
return copy_1;
}
case "[object Object]": {
seen = seen || new Map();
if (seen.has(val))
return seen.get(val);
// High fidelity polyfills of Object.create and Object.getPrototypeOf are
// possible in all JS environments, so we will assume they exist/work.
var copy_2 = Object.create(Object.getPrototypeOf(val));
seen.set(val, copy_2);
Object.keys(val).forEach(function (key) {
copy_2[key] = cloneDeepHelper(val[key], seen);
});
return copy_2;
}
default:
return val;
}
}
//# sourceMappingURL=cloneDeep.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/cache/inmemory/reactiveVars.js
import { dep, Slot } from "optimism";
// Contextual Slot that acquires its value when custom read functions are
// called in Policies#readField.
export var cacheSlot = new Slot();
var cacheInfoMap = new WeakMap();
function getCacheInfo(cache) {
var info = cacheInfoMap.get(cache);
if (!info) {
cacheInfoMap.set(cache, (info = {
vars: new Set(),
dep: dep(),
}));
}
return info;
}
export function forgetCache(cache) {
getCacheInfo(cache).vars.forEach(function (rv) { return rv.forgetCache(cache); });
}
// Calling forgetCache(cache) serves to silence broadcasts and allows the
// cache to be garbage collected. However, the varsByCache WeakMap
// preserves the set of reactive variables that were previously associated
// with this cache, which makes it possible to "recall" the cache at a
// later time, by reattaching it to those variables. If the cache has been
// garbage collected in the meantime, because it is no longer reachable,
// you won't be able to call recallCache(cache), and the cache will
// automatically disappear from the varsByCache WeakMap.
export function recallCache(cache) {
getCacheInfo(cache).vars.forEach(function (rv) { return rv.attachCache(cache); });
}
export function makeVar(value) {
var caches = new Set();
var listeners = new Set();
var rv = function (newValue) {
if (arguments.length > 0) {
if (value !== newValue) {
value = newValue;
caches.forEach(function (cache) {
// Invalidate any fields with custom read functions that
// consumed this variable, so query results involving those
// fields will be recomputed the next time we read them.
getCacheInfo(cache).dep.dirty(rv);
// Broadcast changes to any caches that have previously read
// from this variable.
broadcast(cache);
});
// Finally, notify any listeners added via rv.onNextChange.
var oldListeners = Array.from(listeners);
listeners.clear();
oldListeners.forEach(function (listener) { return listener(value); });
}
}
else {
// When reading from the variable, obtain the current cache from
// context via cacheSlot. This isn't entirely foolproof, but it's
// the same system that powers varDep.
var cache = cacheSlot.getValue();
if (cache) {
attach(cache);
getCacheInfo(cache).dep(rv);
}
}
return value;
};
rv.onNextChange = function (listener) {
listeners.add(listener);
return function () {
listeners.delete(listener);
};
};
var attach = (rv.attachCache = function (cache) {
caches.add(cache);
getCacheInfo(cache).vars.add(rv);
return rv;
});
rv.forgetCache = function (cache) { return caches.delete(cache); };
return rv;
}
function broadcast(cache) {
if (cache.broadcastWatches) {
cache.broadcastWatches();
}
}
//# sourceMappingURL=reactiveVars.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/cache/inmemory/key-extractor.js
import { invariant } from "../../utilities/globals/index.js";
import { argumentsObjectFromField, DeepMerger, isNonEmptyArray, isNonNullObject, } from "../../utilities/index.js";
import { hasOwn, isArray } from "./helpers.js";
// Mapping from JSON-encoded KeySpecifier strings to associated information.
var specifierInfoCache = Object.create(null);
function lookupSpecifierInfo(spec) {
// It's safe to encode KeySpecifier arrays with JSON.stringify, since they're
// just arrays of strings or nested KeySpecifier arrays, and the order of the
// array elements is important (and suitably preserved by JSON.stringify).
var cacheKey = JSON.stringify(spec);
return (specifierInfoCache[cacheKey] ||
(specifierInfoCache[cacheKey] = Object.create(null)));
}
export function keyFieldsFnFromSpecifier(specifier) {
var info = lookupSpecifierInfo(specifier);
return (info.keyFieldsFn || (info.keyFieldsFn = function (object, context) {
var extract = function (from, key) {
return context.readField(key, from);
};
var keyObject = (context.keyObject = collectSpecifierPaths(specifier, function (schemaKeyPath) {
var extracted = extractKeyPath(context.storeObject, schemaKeyPath,
// Using context.readField to extract paths from context.storeObject
// allows the extraction to see through Reference objects and respect
// custom read functions.
extract);
if (extracted === void 0 &&
object !== context.storeObject &&
hasOwn.call(object, schemaKeyPath[0])) {
// If context.storeObject fails to provide a value for the requested
// path, fall back to the raw result object, if it has a top-level key
// matching the first key in the path (schemaKeyPath[0]). This allows
// key fields included in the written data to be saved in the cache
// even if they are not selected explicitly in context.selectionSet.
// Not being mentioned by context.selectionSet is convenient here,
// since it means these extra fields cannot be affected by field
// aliasing, which is why we can use extractKey instead of
// context.readField for this extraction.
extracted = extractKeyPath(object, schemaKeyPath, extractKey);
}
invariant(extracted !== void 0, 4, schemaKeyPath.join("."), object);
return extracted;
}));
return "".concat(context.typename, ":").concat(JSON.stringify(keyObject));
}));
}
// The keyArgs extraction process is roughly analogous to keyFields extraction,
// but there are no aliases involved, missing fields are tolerated (by merely
// omitting them from the key), and drawing from field.directives or variables
// is allowed (in addition to drawing from the field's arguments object).
// Concretely, these differences mean passing a different key path extractor
// function to collectSpecifierPaths, reusing the shared extractKeyPath helper
// wherever possible.
export function keyArgsFnFromSpecifier(specifier) {
var info = lookupSpecifierInfo(specifier);
return (info.keyArgsFn ||
(info.keyArgsFn = function (args, _a) {
var field = _a.field, variables = _a.variables, fieldName = _a.fieldName;
var collected = collectSpecifierPaths(specifier, function (keyPath) {
var firstKey = keyPath[0];
var firstChar = firstKey.charAt(0);
if (firstChar === "@") {
if (field && isNonEmptyArray(field.directives)) {
var directiveName_1 = firstKey.slice(1);
// If the directive appears multiple times, only the first
// occurrence's arguments will be used. TODO Allow repetition?
// TODO Cache this work somehow, a la aliasMap?
var d = field.directives.find(function (d) { return d.name.value === directiveName_1; });
// Fortunately argumentsObjectFromField works for DirectiveNode!
var directiveArgs = d && argumentsObjectFromField(d, variables);
// For directives without arguments (d defined, but directiveArgs ===
// null), the presence or absence of the directive still counts as
// part of the field key, so we return null in those cases. If no
// directive with this name was found for this field (d undefined and
// thus directiveArgs undefined), we return undefined, which causes
// this value to be omitted from the key object returned by
// collectSpecifierPaths.
return (directiveArgs &&
extractKeyPath(directiveArgs,
// If keyPath.length === 1, this code calls extractKeyPath with an
// empty path, which works because it uses directiveArgs as the
// extracted value.
keyPath.slice(1)));
}
// If the key started with @ but there was no corresponding directive,
// we want to omit this value from the key object, not fall through to
// treating @whatever as a normal argument name.
return;
}
if (firstChar === "$") {
var variableName = firstKey.slice(1);
if (variables && hasOwn.call(variables, variableName)) {
var varKeyPath = keyPath.slice(0);
varKeyPath[0] = variableName;
return extractKeyPath(variables, varKeyPath);
}
// If the key started with $ but there was no corresponding variable, we
// want to omit this value from the key object, not fall through to
// treating $whatever as a normal argument name.
return;
}
if (args) {
return extractKeyPath(args, keyPath);
}
});
var suffix = JSON.stringify(collected);
// If no arguments were passed to this field, and it didn't have any other
// field key contributions from directives or variables, hide the empty
// :{} suffix from the field key. However, a field passed no arguments can
// still end up with a non-empty :{...} suffix if its key configuration
// refers to directives or variables.
if (args || suffix !== "{}") {
fieldName += ":" + suffix;
}
return fieldName;
}));
}
export function collectSpecifierPaths(specifier, extractor) {
// For each path specified by specifier, invoke the extractor, and repeatedly
// merge the results together, with appropriate ancestor context.
var merger = new DeepMerger();
return getSpecifierPaths(specifier).reduce(function (collected, path) {
var _a;
var toMerge = extractor(path);
if (toMerge !== void 0) {
// This path is not expected to contain array indexes, so the toMerge
// reconstruction will not contain arrays. TODO Fix this?
for (var i = path.length - 1; i >= 0; --i) {
toMerge = (_a = {}, _a[path[i]] = toMerge, _a);
}
collected = merger.merge(collected, toMerge);
}
return collected;
}, Object.create(null));
}
export function getSpecifierPaths(spec) {
var info = lookupSpecifierInfo(spec);
if (!info.paths) {
var paths_1 = (info.paths = []);
var currentPath_1 = [];
spec.forEach(function (s, i) {
if (isArray(s)) {
getSpecifierPaths(s).forEach(function (p) { return paths_1.push(currentPath_1.concat(p)); });
currentPath_1.length = 0;
}
else {
currentPath_1.push(s);
if (!isArray(spec[i + 1])) {
paths_1.push(currentPath_1.slice(0));
currentPath_1.length = 0;
}
}
});
}
return info.paths;
}
function extractKey(object, key) {
return object[key];
}
export function extractKeyPath(object, path, extract) {
// For each key in path, extract the corresponding child property from obj,
// flattening arrays if encountered (uncommon for keyFields and keyArgs, but
// possible). The final result of path.reduce is normalized so unexpected leaf
// objects have their keys safely sorted. That final result is difficult to
// type as anything other than any. You're welcome to try to improve the
// return type, but keep in mind extractKeyPath is not a public function
// (exported only for testing), so the effort may not be worthwhile unless the
// limited set of actual callers (see above) pass arguments that TypeScript
// can statically type. If we know only that path is some array of strings
// (and not, say, a specific tuple of statically known strings), any (or
// possibly unknown) is the honest answer.
extract = extract || extractKey;
return normalize(path.reduce(function reducer(obj, key) {
return isArray(obj) ?
obj.map(function (child) { return reducer(child, key); })
: obj && extract(obj, key);
}, object));
}
function normalize(value) {
// Usually the extracted value will be a scalar value, since most primary
// key fields are scalar, but just in case we get an object or an array, we
// need to do some normalization of the order of (nested) keys.
if (isNonNullObject(value)) {
if (isArray(value)) {
return value.map(normalize);
}
return collectSpecifierPaths(Object.keys(value).sort(), function (path) {
return extractKeyPath(value, path);
});
}
return value;
}
//# sourceMappingURL=key-extractor.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/cache/inmemory/policies.js
import { __assign, __rest } from "tslib";
import { invariant, newInvariantError } from "../../utilities/globals/index.js";
import { storeKeyNameFromField, argumentsObjectFromField, isReference, getStoreKeyName, isNonNullObject, stringifyForDisplay, } from "../../utilities/index.js";
import { hasOwn, fieldNameFromStoreName, storeValueIsStoreObject, selectionSetMatchesResult, TypeOrFieldNameRegExp, defaultDataIdFromObject, isArray, } from "./helpers.js";
import { cacheSlot } from "./reactiveVars.js";
import { keyArgsFnFromSpecifier, keyFieldsFnFromSpecifier, } from "./key-extractor.js";
function argsFromFieldSpecifier(spec) {
return (spec.args !== void 0 ? spec.args
: spec.field ? argumentsObjectFromField(spec.field, spec.variables)
: null);
}
var nullKeyFieldsFn = function () { return void 0; };
var simpleKeyArgsFn = function (_args, context) { return context.fieldName; };
// These merge functions can be selected by specifying merge:true or
// merge:false in a field policy.
var mergeTrueFn = function (existing, incoming, _a) {
var mergeObjects = _a.mergeObjects;
return mergeObjects(existing, incoming);
};
var mergeFalseFn = function (_, incoming) { return incoming; };
var Policies = /** @class */ (function () {
function Policies(config) {
this.config = config;
this.typePolicies = Object.create(null);
this.toBeAdded = Object.create(null);
// Map from subtype names to sets of supertype names. Note that this
// representation inverts the structure of possibleTypes (whose keys are
// supertypes and whose values are arrays of subtypes) because it tends
// to be much more efficient to search upwards than downwards.
this.supertypeMap = new Map();
// Any fuzzy subtypes specified by possibleTypes will be converted to
// RegExp objects and recorded here. Every key of this map can also be
// found in supertypeMap. In many cases this Map will be empty, which
// means no fuzzy subtype checking will happen in fragmentMatches.
this.fuzzySubtypes = new Map();
this.rootIdsByTypename = Object.create(null);
this.rootTypenamesById = Object.create(null);
this.usingPossibleTypes = false;
this.config = __assign({ dataIdFromObject: defaultDataIdFromObject }, config);
this.cache = this.config.cache;
this.setRootTypename("Query");
this.setRootTypename("Mutation");
this.setRootTypename("Subscription");
if (config.possibleTypes) {
this.addPossibleTypes(config.possibleTypes);
}
if (config.typePolicies) {
this.addTypePolicies(config.typePolicies);
}
}
Policies.prototype.identify = function (object, partialContext) {
var _a;
var policies = this;
var typename = (partialContext &&
(partialContext.typename || ((_a = partialContext.storeObject) === null || _a === void 0 ? void 0 : _a.__typename))) ||
object.__typename;
// It should be possible to write root Query fields with writeFragment,
// using { __typename: "Query", ... } as the data, but it does not make
// sense to allow the same identification behavior for the Mutation and
// Subscription types, since application code should never be writing
// directly to (or reading directly from) those root objects.
if (typename === this.rootTypenamesById.ROOT_QUERY) {
return ["ROOT_QUERY"];
}
// Default context.storeObject to object if not otherwise provided.
var storeObject = (partialContext && partialContext.storeObject) || object;
var context = __assign(__assign({}, partialContext), { typename: typename, storeObject: storeObject, readField: (partialContext && partialContext.readField) ||
function () {
var options = normalizeReadFieldOptions(arguments, storeObject);
return policies.readField(options, {
store: policies.cache["data"],
variables: options.variables,
});
} });
var id;
var policy = typename && this.getTypePolicy(typename);
var keyFn = (policy && policy.keyFn) || this.config.dataIdFromObject;
while (keyFn) {
var specifierOrId = keyFn(__assign(__assign({}, object), storeObject), context);
if (isArray(specifierOrId)) {
keyFn = keyFieldsFnFromSpecifier(specifierOrId);
}
else {
id = specifierOrId;
break;
}
}
id = id ? String(id) : void 0;
return context.keyObject ? [id, context.keyObject] : [id];
};
Policies.prototype.addTypePolicies = function (typePolicies) {
var _this = this;
Object.keys(typePolicies).forEach(function (typename) {
var _a = typePolicies[typename], queryType = _a.queryType, mutationType = _a.mutationType, subscriptionType = _a.subscriptionType, incoming = __rest(_a, ["queryType", "mutationType", "subscriptionType"]);
// Though {query,mutation,subscription}Type configurations are rare,
// it's important to call setRootTypename as early as possible,
// since these configurations should apply consistently for the
// entire lifetime of the cache. Also, since only one __typename can
// qualify as one of these root types, these three properties cannot
// be inherited, unlike the rest of the incoming properties. That
// restriction is convenient, because the purpose of this.toBeAdded
// is to delay the processing of type/field policies until the first
// time they're used, allowing policies to be added in any order as
// long as all relevant policies (including policies for supertypes)
// have been added by the time a given policy is used for the first
// time. In other words, since inheritance doesn't matter for these
// properties, there's also no need to delay their processing using
// the this.toBeAdded queue.
if (queryType)
_this.setRootTypename("Query", typename);
if (mutationType)
_this.setRootTypename("Mutation", typename);
if (subscriptionType)
_this.setRootTypename("Subscription", typename);
if (hasOwn.call(_this.toBeAdded, typename)) {
_this.toBeAdded[typename].push(incoming);
}
else {
_this.toBeAdded[typename] = [incoming];
}
});
};
Policies.prototype.updateTypePolicy = function (typename, incoming) {
var _this = this;
var existing = this.getTypePolicy(typename);
var keyFields = incoming.keyFields, fields = incoming.fields;
function setMerge(existing, merge) {
existing.merge =
typeof merge === "function" ? merge
// Pass merge:true as a shorthand for a merge implementation
// that returns options.mergeObjects(existing, incoming).
: merge === true ? mergeTrueFn
// Pass merge:false to make incoming always replace existing
// without any warnings about data clobbering.
: merge === false ? mergeFalseFn
: existing.merge;
}
// Type policies can define merge functions, as an alternative to
// using field policies to merge child objects.
setMerge(existing, incoming.merge);
existing.keyFn =
// Pass false to disable normalization for this typename.
keyFields === false ? nullKeyFieldsFn
// Pass an array of strings to use those fields to compute a
// composite ID for objects of this typename.
: isArray(keyFields) ? keyFieldsFnFromSpecifier(keyFields)
// Pass a function to take full control over identification.
: typeof keyFields === "function" ? keyFields
// Leave existing.keyFn unchanged if above cases fail.
: existing.keyFn;
if (fields) {
Object.keys(fields).forEach(function (fieldName) {
var existing = _this.getFieldPolicy(typename, fieldName, true);
var incoming = fields[fieldName];
if (typeof incoming === "function") {
existing.read = incoming;
}
else {
var keyArgs = incoming.keyArgs, read = incoming.read, merge = incoming.merge;
existing.keyFn =
// Pass false to disable argument-based differentiation of
// field identities.
keyArgs === false ? simpleKeyArgsFn
// Pass an array of strings to use named arguments to
// compute a composite identity for the field.
: isArray(keyArgs) ? keyArgsFnFromSpecifier(keyArgs)
// Pass a function to take full control over field identity.
: typeof keyArgs === "function" ? keyArgs
// Leave existing.keyFn unchanged if above cases fail.
: existing.keyFn;
if (typeof read === "function") {
existing.read = read;
}
setMerge(existing, merge);
}
if (existing.read && existing.merge) {
// If we have both a read and a merge function, assume
// keyArgs:false, because read and merge together can take
// responsibility for interpreting arguments in and out. This
// default assumption can always be overridden by specifying
// keyArgs explicitly in the FieldPolicy.
existing.keyFn = existing.keyFn || simpleKeyArgsFn;
}
});
}
};
Policies.prototype.setRootTypename = function (which, typename) {
if (typename === void 0) { typename = which; }
var rootId = "ROOT_" + which.toUpperCase();
var old = this.rootTypenamesById[rootId];
if (typename !== old) {
invariant(!old || old === which, 5, which);
// First, delete any old __typename associated with this rootId from
// rootIdsByTypename.
if (old)
delete this.rootIdsByTypename[old];
// Now make this the only __typename that maps to this rootId.
this.rootIdsByTypename[typename] = rootId;
// Finally, update the __typename associated with this rootId.
this.rootTypenamesById[rootId] = typename;
}
};
Policies.prototype.addPossibleTypes = function (possibleTypes) {
var _this = this;
this.usingPossibleTypes = true;
Object.keys(possibleTypes).forEach(function (supertype) {
// Make sure all types have an entry in this.supertypeMap, even if
// their supertype set is empty, so we can return false immediately
// from policies.fragmentMatches for unknown supertypes.
_this.getSupertypeSet(supertype, true);
possibleTypes[supertype].forEach(function (subtype) {
_this.getSupertypeSet(subtype, true).add(supertype);
var match = subtype.match(TypeOrFieldNameRegExp);
if (!match || match[0] !== subtype) {
// TODO Don't interpret just any invalid typename as a RegExp.
_this.fuzzySubtypes.set(subtype, new RegExp(subtype));
}
});
});
};
Policies.prototype.getTypePolicy = function (typename) {
var _this = this;
if (!hasOwn.call(this.typePolicies, typename)) {
var policy_1 = (this.typePolicies[typename] = Object.create(null));
policy_1.fields = Object.create(null);
// When the TypePolicy for typename is first accessed, instead of
// starting with an empty policy object, inherit any properties or
// fields from the type policies of the supertypes of typename.
//
// Any properties or fields defined explicitly within the TypePolicy
// for typename will take precedence, and if there are multiple
// supertypes, the properties of policies whose types were added
// later via addPossibleTypes will take precedence over those of
// earlier supertypes. TODO Perhaps we should warn about these
// conflicts in development, and recommend defining the property
// explicitly in the subtype policy?
//
// Field policy inheritance is atomic/shallow: you can't inherit a
// field policy and then override just its read function, since read
// and merge functions often need to cooperate, so changing only one
// of them would be a recipe for inconsistency.
//
// Once the TypePolicy for typename has been accessed, its properties can
// still be updated directly using addTypePolicies, but future changes to
// inherited supertype policies will not be reflected in this subtype
// policy, because this code runs at most once per typename.
var supertypes_1 = this.supertypeMap.get(typename);
if (!supertypes_1 && this.fuzzySubtypes.size) {
// To make the inheritance logic work for unknown typename strings that
// may have fuzzy supertypes, we give this typename an empty supertype
// set and then populate it with any fuzzy supertypes that match.
supertypes_1 = this.getSupertypeSet(typename, true);
// This only works for typenames that are directly matched by a fuzzy
// supertype. What if there is an intermediate chain of supertypes?
// While possible, that situation can only be solved effectively by
// specifying the intermediate relationships via possibleTypes, manually
// and in a non-fuzzy way.
this.fuzzySubtypes.forEach(function (regExp, fuzzy) {
if (regExp.test(typename)) {
// The fuzzy parameter is just the original string version of regExp
// (not a valid __typename string), but we can look up the
// associated supertype(s) in this.supertypeMap.
var fuzzySupertypes = _this.supertypeMap.get(fuzzy);
if (fuzzySupertypes) {
fuzzySupertypes.forEach(function (supertype) {
return supertypes_1.add(supertype);
});
}
}
});
}
if (supertypes_1 && supertypes_1.size) {
supertypes_1.forEach(function (supertype) {
var _a = _this.getTypePolicy(supertype), fields = _a.fields, rest = __rest(_a, ["fields"]);
Object.assign(policy_1, rest);
Object.assign(policy_1.fields, fields);
});
}
}
var inbox = this.toBeAdded[typename];
if (inbox && inbox.length) {
// Merge the pending policies into this.typePolicies, in the order they
// were originally passed to addTypePolicy.
inbox.splice(0).forEach(function (policy) {
_this.updateTypePolicy(typename, policy);
});
}
return this.typePolicies[typename];
};
Policies.prototype.getFieldPolicy = function (typename, fieldName, createIfMissing) {
if (typename) {
var fieldPolicies = this.getTypePolicy(typename).fields;
return (fieldPolicies[fieldName] ||
(createIfMissing && (fieldPolicies[fieldName] = Object.create(null))));
}
};
Policies.prototype.getSupertypeSet = function (subtype, createIfMissing) {
var supertypeSet = this.supertypeMap.get(subtype);
if (!supertypeSet && createIfMissing) {
this.supertypeMap.set(subtype, (supertypeSet = new Set()));
}
return supertypeSet;
};
Policies.prototype.fragmentMatches = function (fragment, typename, result, variables) {
var _this = this;
if (!fragment.typeCondition)
return true;
// If the fragment has a type condition but the object we're matching
// against does not have a __typename, the fragment cannot match.
if (!typename)
return false;
var supertype = fragment.typeCondition.name.value;
// Common case: fragment type condition and __typename are the same.
if (typename === supertype)
return true;
if (this.usingPossibleTypes && this.supertypeMap.has(supertype)) {
var typenameSupertypeSet = this.getSupertypeSet(typename, true);
var workQueue_1 = [typenameSupertypeSet];
var maybeEnqueue_1 = function (subtype) {
var supertypeSet = _this.getSupertypeSet(subtype, false);
if (supertypeSet &&
supertypeSet.size &&
workQueue_1.indexOf(supertypeSet) < 0) {
workQueue_1.push(supertypeSet);
}
};
// We need to check fuzzy subtypes only if we encountered fuzzy
// subtype strings in addPossibleTypes, and only while writing to
// the cache, since that's when selectionSetMatchesResult gives a
// strong signal of fragment matching. The StoreReader class calls
// policies.fragmentMatches without passing a result object, so
// needToCheckFuzzySubtypes is always false while reading.
var needToCheckFuzzySubtypes = !!(result && this.fuzzySubtypes.size);
var checkingFuzzySubtypes = false;
// It's important to keep evaluating workQueue.length each time through
// the loop, because the queue can grow while we're iterating over it.
for (var i = 0; i < workQueue_1.length; ++i) {
var supertypeSet = workQueue_1[i];
if (supertypeSet.has(supertype)) {
if (!typenameSupertypeSet.has(supertype)) {
if (checkingFuzzySubtypes) {
globalThis.__DEV__ !== false && invariant.warn(6, typename, supertype);
}
// Record positive results for faster future lookup.
// Unfortunately, we cannot safely cache negative results,
// because new possibleTypes data could always be added to the
// Policies class.
typenameSupertypeSet.add(supertype);
}
return true;
}
supertypeSet.forEach(maybeEnqueue_1);
if (needToCheckFuzzySubtypes &&
// Start checking fuzzy subtypes only after exhausting all
// non-fuzzy subtypes (after the final iteration of the loop).
i === workQueue_1.length - 1 &&
// We could wait to compare fragment.selectionSet to result
// after we verify the supertype, but this check is often less
// expensive than that search, and we will have to do the
// comparison anyway whenever we find a potential match.
selectionSetMatchesResult(fragment.selectionSet, result, variables)) {
// We don't always need to check fuzzy subtypes (if no result
// was provided, or !this.fuzzySubtypes.size), but, when we do,
// we only want to check them once.
needToCheckFuzzySubtypes = false;
checkingFuzzySubtypes = true;
// If we find any fuzzy subtypes that match typename, extend the
// workQueue to search through the supertypes of those fuzzy
// subtypes. Otherwise the for-loop will terminate and we'll
// return false below.
this.fuzzySubtypes.forEach(function (regExp, fuzzyString) {
var match = typename.match(regExp);
if (match && match[0] === typename) {
maybeEnqueue_1(fuzzyString);
}
});
}
}
}
return false;
};
Policies.prototype.hasKeyArgs = function (typename, fieldName) {
var policy = this.getFieldPolicy(typename, fieldName, false);
return !!(policy && policy.keyFn);
};
Policies.prototype.getStoreFieldName = function (fieldSpec) {
var typename = fieldSpec.typename, fieldName = fieldSpec.fieldName;
var policy = this.getFieldPolicy(typename, fieldName, false);
var storeFieldName;
var keyFn = policy && policy.keyFn;
if (keyFn && typename) {
var context = {
typename: typename,
fieldName: fieldName,
field: fieldSpec.field || null,
variables: fieldSpec.variables,
};
var args = argsFromFieldSpecifier(fieldSpec);
while (keyFn) {
var specifierOrString = keyFn(args, context);
if (isArray(specifierOrString)) {
keyFn = keyArgsFnFromSpecifier(specifierOrString);
}
else {
// If the custom keyFn returns a falsy value, fall back to
// fieldName instead.
storeFieldName = specifierOrString || fieldName;
break;
}
}
}
if (storeFieldName === void 0) {
storeFieldName =
fieldSpec.field ?
storeKeyNameFromField(fieldSpec.field, fieldSpec.variables)
: getStoreKeyName(fieldName, argsFromFieldSpecifier(fieldSpec));
}
// Returning false from a keyArgs function is like configuring
// keyArgs: false, but more dynamic.
if (storeFieldName === false) {
return fieldName;
}
// Make sure custom field names start with the actual field.name.value
// of the field, so we can always figure out which properties of a
// StoreObject correspond to which original field names.
return fieldName === fieldNameFromStoreName(storeFieldName) ? storeFieldName
: fieldName + ":" + storeFieldName;
};
Policies.prototype.readField = function (options, context) {
var objectOrReference = options.from;
if (!objectOrReference)
return;
var nameOrField = options.field || options.fieldName;
if (!nameOrField)
return;
if (options.typename === void 0) {
var typename = context.store.getFieldValue(objectOrReference, "__typename");
if (typename)
options.typename = typename;
}
var storeFieldName = this.getStoreFieldName(options);
var fieldName = fieldNameFromStoreName(storeFieldName);
var existing = context.store.getFieldValue(objectOrReference, storeFieldName);
var policy = this.getFieldPolicy(options.typename, fieldName, false);
var read = policy && policy.read;
if (read) {
var readOptions = makeFieldFunctionOptions(this, objectOrReference, options, context, context.store.getStorage(isReference(objectOrReference) ?
objectOrReference.__ref
: objectOrReference, storeFieldName));
// Call read(existing, readOptions) with cacheSlot holding this.cache.
return cacheSlot.withValue(this.cache, read, [
existing,
readOptions,
]);
}
return existing;
};
Policies.prototype.getReadFunction = function (typename, fieldName) {
var policy = this.getFieldPolicy(typename, fieldName, false);
return policy && policy.read;
};
Policies.prototype.getMergeFunction = function (parentTypename, fieldName, childTypename) {
var policy = this.getFieldPolicy(parentTypename, fieldName, false);
var merge = policy && policy.merge;
if (!merge && childTypename) {
policy = this.getTypePolicy(childTypename);
merge = policy && policy.merge;
}
return merge;
};
Policies.prototype.runMergeFunction = function (existing, incoming, _a, context, storage) {
var field = _a.field, typename = _a.typename, merge = _a.merge;
if (merge === mergeTrueFn) {
// Instead of going to the trouble of creating a full
// FieldFunctionOptions object and calling mergeTrueFn, we can
// simply call mergeObjects, as mergeTrueFn would.
return makeMergeObjectsFunction(context.store)(existing, incoming);
}
if (merge === mergeFalseFn) {
// Likewise for mergeFalseFn, whose implementation is even simpler.
return incoming;
}
// If cache.writeQuery or cache.writeFragment was called with
// options.overwrite set to true, we still call merge functions, but
// the existing data is always undefined, so the merge function will
// not attempt to combine the incoming data with the existing data.
if (context.overwrite) {
existing = void 0;
}
return merge(existing, incoming, makeFieldFunctionOptions(this,
// Unlike options.readField for read functions, we do not fall
// back to the current object if no foreignObjOrRef is provided,
// because it's not clear what the current object should be for
// merge functions: the (possibly undefined) existing object, or
// the incoming object? If you think your merge function needs
// to read sibling fields in order to produce a new value for
// the current field, you might want to rethink your strategy,
// because that's a recipe for making merge behavior sensitive
// to the order in which fields are written into the cache.
// However, readField(name, ref) is useful for merge functions
// that need to deduplicate child objects and references.
void 0, {
typename: typename,
fieldName: field.name.value,
field: field,
variables: context.variables,
}, context, storage || Object.create(null)));
};
return Policies;
}());
export { Policies };
function makeFieldFunctionOptions(policies, objectOrReference, fieldSpec, context, storage) {
var storeFieldName = policies.getStoreFieldName(fieldSpec);
var fieldName = fieldNameFromStoreName(storeFieldName);
var variables = fieldSpec.variables || context.variables;
var _a = context.store, toReference = _a.toReference, canRead = _a.canRead;
return {
args: argsFromFieldSpecifier(fieldSpec),
field: fieldSpec.field || null,
fieldName: fieldName,
storeFieldName: storeFieldName,
variables: variables,
isReference: isReference,
toReference: toReference,
storage: storage,
cache: policies.cache,
canRead: canRead,
readField: function () {
return policies.readField(normalizeReadFieldOptions(arguments, objectOrReference, variables), context);
},
mergeObjects: makeMergeObjectsFunction(context.store),
};
}
export function normalizeReadFieldOptions(readFieldArgs, objectOrReference, variables) {
var fieldNameOrOptions = readFieldArgs[0], from = readFieldArgs[1], argc = readFieldArgs.length;
var options;
if (typeof fieldNameOrOptions === "string") {
options = {
fieldName: fieldNameOrOptions,
// Default to objectOrReference only when no second argument was
// passed for the from parameter, not when undefined is explicitly
// passed as the second argument.
from: argc > 1 ? from : objectOrReference,
};
}
else {
options = __assign({}, fieldNameOrOptions);
// Default to objectOrReference only when fieldNameOrOptions.from is
// actually omitted, rather than just undefined.
if (!hasOwn.call(options, "from")) {
options.from = objectOrReference;
}
}
if (globalThis.__DEV__ !== false && options.from === void 0) {
globalThis.__DEV__ !== false && invariant.warn(7, stringifyForDisplay(Array.from(readFieldArgs)));
}
if (void 0 === options.variables) {
options.variables = variables;
}
return options;
}
function makeMergeObjectsFunction(store) {
return function mergeObjects(existing, incoming) {
if (isArray(existing) || isArray(incoming)) {
throw newInvariantError(8);
}
// These dynamic checks are necessary because the parameters of a
// custom merge function can easily have the any type, so the type
// system cannot always enforce the StoreObject | Reference parameter
// types of options.mergeObjects.
if (isNonNullObject(existing) && isNonNullObject(incoming)) {
var eType = store.getFieldValue(existing, "__typename");
var iType = store.getFieldValue(incoming, "__typename");
var typesDiffer = eType && iType && eType !== iType;
if (typesDiffer) {
return incoming;
}
if (isReference(existing) && storeValueIsStoreObject(incoming)) {
// Update the normalized EntityStore for the entity identified by
// existing.__ref, preferring/overwriting any fields contributed by the
// newer incoming StoreObject.
store.merge(existing.__ref, incoming);
return existing;
}
if (storeValueIsStoreObject(existing) && isReference(incoming)) {
// Update the normalized EntityStore for the entity identified by
// incoming.__ref, taking fields from the older existing object only if
// those fields are not already present in the newer StoreObject
// identified by incoming.__ref.
store.merge(existing, incoming.__ref);
return incoming;
}
if (storeValueIsStoreObject(existing) &&
storeValueIsStoreObject(incoming)) {
return __assign(__assign({}, existing), incoming);
}
}
return incoming;
};
}
//# sourceMappingURL=policies.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/cache/inmemory/writeToStore.js
import { __assign } from "tslib";
import { invariant, newInvariantError } from "../../utilities/globals/index.js";
import { equal } from "@wry/equality";
import { Trie } from "@wry/trie";
import { Kind } from "graphql";
import { getFragmentFromSelection, getDefaultValues, getOperationDefinition, getTypenameFromResult, makeReference, isField, resultKeyNameFromField, isReference, shouldInclude, cloneDeep, addTypenameToDocument, isNonEmptyArray, argumentsObjectFromField, canonicalStringify, } from "../../utilities/index.js";
import { isArray, makeProcessedFieldsMerger, fieldNameFromStoreName, storeValueIsStoreObject, extractFragmentContext, } from "./helpers.js";
import { normalizeReadFieldOptions } from "./policies.js";
// Since there are only four possible combinations of context.clientOnly and
// context.deferred values, we should need at most four "flavors" of any given
// WriteContext. To avoid creating multiple copies of the same context, we cache
// the contexts in the context.flavors Map (shared by all flavors) according to
// their clientOnly and deferred values (always in that order).
function getContextFlavor(context, clientOnly, deferred) {
var key = "".concat(clientOnly).concat(deferred);
var flavored = context.flavors.get(key);
if (!flavored) {
context.flavors.set(key, (flavored =
context.clientOnly === clientOnly && context.deferred === deferred ?
context
: __assign(__assign({}, context), { clientOnly: clientOnly, deferred: deferred })));
}
return flavored;
}
var StoreWriter = /** @class */ (function () {
function StoreWriter(cache, reader, fragments) {
this.cache = cache;
this.reader = reader;
this.fragments = fragments;
}
StoreWriter.prototype.writeToStore = function (store, _a) {
var _this = this;
var query = _a.query, result = _a.result, dataId = _a.dataId, variables = _a.variables, overwrite = _a.overwrite;
var operationDefinition = getOperationDefinition(query);
var merger = makeProcessedFieldsMerger();
variables = __assign(__assign({}, getDefaultValues(operationDefinition)), variables);
var context = __assign(__assign({ store: store, written: Object.create(null), merge: function (existing, incoming) {
return merger.merge(existing, incoming);
}, variables: variables, varString: canonicalStringify(variables) }, extractFragmentContext(query, this.fragments)), { overwrite: !!overwrite, incomingById: new Map(), clientOnly: false, deferred: false, flavors: new Map() });
var ref = this.processSelectionSet({
result: result || Object.create(null),
dataId: dataId,
selectionSet: operationDefinition.selectionSet,
mergeTree: { map: new Map() },
context: context,
});
if (!isReference(ref)) {
throw newInvariantError(11, result);
}
// So far, the store has not been modified, so now it's time to process
// context.incomingById and merge those incoming fields into context.store.
context.incomingById.forEach(function (_a, dataId) {
var storeObject = _a.storeObject, mergeTree = _a.mergeTree, fieldNodeSet = _a.fieldNodeSet;
var entityRef = makeReference(dataId);
if (mergeTree && mergeTree.map.size) {
var applied = _this.applyMerges(mergeTree, entityRef, storeObject, context);
if (isReference(applied)) {
// Assume References returned by applyMerges have already been merged
// into the store. See makeMergeObjectsFunction in policies.ts for an
// example of how this can happen.
return;
}
// Otherwise, applyMerges returned a StoreObject, whose fields we should
// merge into the store (see store.merge statement below).
storeObject = applied;
}
if (globalThis.__DEV__ !== false && !context.overwrite) {
var fieldsWithSelectionSets_1 = Object.create(null);
fieldNodeSet.forEach(function (field) {
if (field.selectionSet) {
fieldsWithSelectionSets_1[field.name.value] = true;
}
});
var hasSelectionSet_1 = function (storeFieldName) {
return fieldsWithSelectionSets_1[fieldNameFromStoreName(storeFieldName)] ===
true;
};
var hasMergeFunction_1 = function (storeFieldName) {
var childTree = mergeTree && mergeTree.map.get(storeFieldName);
return Boolean(childTree && childTree.info && childTree.info.merge);
};
Object.keys(storeObject).forEach(function (storeFieldName) {
// If a merge function was defined for this field, trust that it
// did the right thing about (not) clobbering data. If the field
// has no selection set, it's a scalar field, so it doesn't need
// a merge function (even if it's an object, like JSON data).
if (hasSelectionSet_1(storeFieldName) &&
!hasMergeFunction_1(storeFieldName)) {
warnAboutDataLoss(entityRef, storeObject, storeFieldName, context.store);
}
});
}
store.merge(dataId, storeObject);
});
// Any IDs written explicitly to the cache will be retained as
// reachable root IDs for garbage collection purposes. Although this
// logic includes root IDs like ROOT_QUERY and ROOT_MUTATION, their
// retainment counts are effectively ignored because cache.gc() always
// includes them in its root ID set.
store.retain(ref.__ref);
return ref;
};
StoreWriter.prototype.processSelectionSet = function (_a) {
var _this = this;
var dataId = _a.dataId, result = _a.result, selectionSet = _a.selectionSet, context = _a.context,
// This object allows processSelectionSet to report useful information
// to its callers without explicitly returning that information.
mergeTree = _a.mergeTree;
var policies = this.cache.policies;
// This variable will be repeatedly updated using context.merge to
// accumulate all fields that need to be written into the store.
var incoming = Object.create(null);
// If typename was not passed in, infer it. Note that typename is
// always passed in for tricky-to-infer cases such as "Query" for
// ROOT_QUERY.
var typename = (dataId && policies.rootTypenamesById[dataId]) ||
getTypenameFromResult(result, selectionSet, context.fragmentMap) ||
(dataId && context.store.get(dataId, "__typename"));
if ("string" === typeof typename) {
incoming.__typename = typename;
}
// This readField function will be passed as context.readField in the
// KeyFieldsContext object created within policies.identify (called below).
// In addition to reading from the existing context.store (thanks to the
// policies.readField(options, context) line at the very bottom), this
// version of readField can read from Reference objects that are currently
// pending in context.incomingById, which is important whenever keyFields
// need to be extracted from a child object that processSelectionSet has
// turned into a Reference.
var readField = function () {
var options = normalizeReadFieldOptions(arguments, incoming, context.variables);
if (isReference(options.from)) {
var info = context.incomingById.get(options.from.__ref);
if (info) {
var result_1 = policies.readField(__assign(__assign({}, options), { from: info.storeObject }), context);
if (result_1 !== void 0) {
return result_1;
}
}
}
return policies.readField(options, context);
};
var fieldNodeSet = new Set();
this.flattenFields(selectionSet, result,
// This WriteContext will be the default context value for fields returned
// by the flattenFields method, but some fields may be assigned a modified
// context, depending on the presence of @client and other directives.
context, typename).forEach(function (context, field) {
var _a;
var resultFieldKey = resultKeyNameFromField(field);
var value = result[resultFieldKey];
fieldNodeSet.add(field);
if (value !== void 0) {
var storeFieldName = policies.getStoreFieldName({
typename: typename,
fieldName: field.name.value,
field: field,
variables: context.variables,
});
var childTree = getChildMergeTree(mergeTree, storeFieldName);
var incomingValue = _this.processFieldValue(value, field,
// Reset context.clientOnly and context.deferred to their default
// values before processing nested selection sets.
field.selectionSet ?
getContextFlavor(context, false, false)
: context, childTree);
// To determine if this field holds a child object with a merge function
// defined in its type policy (see PR #7070), we need to figure out the
// child object's __typename.
var childTypename = void 0;
// The field's value can be an object that has a __typename only if the
// field has a selection set. Otherwise incomingValue is scalar.
if (field.selectionSet &&
(isReference(incomingValue) || storeValueIsStoreObject(incomingValue))) {
childTypename = readField("__typename", incomingValue);
}
var merge = policies.getMergeFunction(typename, field.name.value, childTypename);
if (merge) {
childTree.info = {
// TODO Check compatibility against any existing childTree.field?
field: field,
typename: typename,
merge: merge,
};
}
else {
maybeRecycleChildMergeTree(mergeTree, storeFieldName);
}
incoming = context.merge(incoming, (_a = {},
_a[storeFieldName] = incomingValue,
_a));
}
else if (globalThis.__DEV__ !== false &&
!context.clientOnly &&
!context.deferred &&
!addTypenameToDocument.added(field) &&
// If the field has a read function, it may be a synthetic field or
// provide a default value, so its absence from the written data should
// not be cause for alarm.
!policies.getReadFunction(typename, field.name.value)) {
globalThis.__DEV__ !== false && invariant.error(12, resultKeyNameFromField(field), result);
}
});
// Identify the result object, even if dataId was already provided,
// since we always need keyObject below.
try {
var _b = policies.identify(result, {
typename: typename,
selectionSet: selectionSet,
fragmentMap: context.fragmentMap,
storeObject: incoming,
readField: readField,
}), id = _b[0], keyObject = _b[1];
// If dataId was not provided, fall back to the id just generated by
// policies.identify.
dataId = dataId || id;
// Write any key fields that were used during identification, even if
// they were not mentioned in the original query.
if (keyObject) {
// TODO Reverse the order of the arguments?
incoming = context.merge(incoming, keyObject);
}
}
catch (e) {
// If dataId was provided, tolerate failure of policies.identify.
if (!dataId)
throw e;
}
if ("string" === typeof dataId) {
var dataRef = makeReference(dataId);
// Avoid processing the same entity object using the same selection
// set more than once. We use an array instead of a Set since most
// entity IDs will be written using only one selection set, so the
// size of this array is likely to be very small, meaning indexOf is
// likely to be faster than Set.prototype.has.
var sets = context.written[dataId] || (context.written[dataId] = []);
if (sets.indexOf(selectionSet) >= 0)
return dataRef;
sets.push(selectionSet);
// If we're about to write a result object into the store, but we
// happen to know that the exact same (===) result object would be
// returned if we were to reread the result with the same inputs,
// then we can skip the rest of the processSelectionSet work for
// this object, and immediately return a Reference to it.
if (this.reader &&
this.reader.isFresh(result, dataRef, selectionSet, context)) {
return dataRef;
}
var previous_1 = context.incomingById.get(dataId);
if (previous_1) {
previous_1.storeObject = context.merge(previous_1.storeObject, incoming);
previous_1.mergeTree = mergeMergeTrees(previous_1.mergeTree, mergeTree);
fieldNodeSet.forEach(function (field) { return previous_1.fieldNodeSet.add(field); });
}
else {
context.incomingById.set(dataId, {
storeObject: incoming,
// Save a reference to mergeTree only if it is not empty, because
// empty MergeTrees may be recycled by maybeRecycleChildMergeTree and
// reused for entirely different parts of the result tree.
mergeTree: mergeTreeIsEmpty(mergeTree) ? void 0 : mergeTree,
fieldNodeSet: fieldNodeSet,
});
}
return dataRef;
}
return incoming;
};
StoreWriter.prototype.processFieldValue = function (value, field, context, mergeTree) {
var _this = this;
if (!field.selectionSet || value === null) {
// In development, we need to clone scalar values so that they can be
// safely frozen with maybeDeepFreeze in readFromStore.ts. In production,
// it's cheaper to store the scalar values directly in the cache.
return globalThis.__DEV__ !== false ? cloneDeep(value) : value;
}
if (isArray(value)) {
return value.map(function (item, i) {
var value = _this.processFieldValue(item, field, context, getChildMergeTree(mergeTree, i));
maybeRecycleChildMergeTree(mergeTree, i);
return value;
});
}
return this.processSelectionSet({
result: value,
selectionSet: field.selectionSet,
context: context,
mergeTree: mergeTree,
});
};
// Implements https://spec.graphql.org/draft/#sec-Field-Collection, but with
// some additions for tracking @client and @defer directives.
StoreWriter.prototype.flattenFields = function (selectionSet, result, context, typename) {
if (typename === void 0) { typename = getTypenameFromResult(result, selectionSet, context.fragmentMap); }
var fieldMap = new Map();
var policies = this.cache.policies;
var limitingTrie = new Trie(false); // No need for WeakMap, since limitingTrie does not escape.
(function flatten(selectionSet, inheritedContext) {
var visitedNode = limitingTrie.lookup(selectionSet,
// Because we take inheritedClientOnly and inheritedDeferred into
// consideration here (in addition to selectionSet), it's possible for
// the same selection set to be flattened more than once, if it appears
// in the query with different @client and/or @directive configurations.
inheritedContext.clientOnly, inheritedContext.deferred);
if (visitedNode.visited)
return;
visitedNode.visited = true;
selectionSet.selections.forEach(function (selection) {
if (!shouldInclude(selection, context.variables))
return;
var clientOnly = inheritedContext.clientOnly, deferred = inheritedContext.deferred;
if (
// Since the presence of @client or @defer on this field can only
// cause clientOnly or deferred to become true, we can skip the
// forEach loop if both clientOnly and deferred are already true.
!(clientOnly && deferred) &&
isNonEmptyArray(selection.directives)) {
selection.directives.forEach(function (dir) {
var name = dir.name.value;
if (name === "client")
clientOnly = true;
if (name === "defer") {
var args = argumentsObjectFromField(dir, context.variables);
// The @defer directive takes an optional args.if boolean
// argument, similar to @include(if: boolean). Note that
// @defer(if: false) does not make context.deferred false, but
// instead behaves as if there was no @defer directive.
if (!args || args.if !== false) {
deferred = true;
}
// TODO In the future, we may want to record args.label using
// context.deferred, if a label is specified.
}
});
}
if (isField(selection)) {
var existing = fieldMap.get(selection);
if (existing) {
// If this field has been visited along another recursive path
// before, the final context should have clientOnly or deferred set
// to true only if *all* paths have the directive (hence the &&).
clientOnly = clientOnly && existing.clientOnly;
deferred = deferred && existing.deferred;
}
fieldMap.set(selection, getContextFlavor(context, clientOnly, deferred));
}
else {
var fragment = getFragmentFromSelection(selection, context.lookupFragment);
if (!fragment && selection.kind === Kind.FRAGMENT_SPREAD) {
throw newInvariantError(13, selection.name.value);
}
if (fragment &&
policies.fragmentMatches(fragment, typename, result, context.variables)) {
flatten(fragment.selectionSet, getContextFlavor(context, clientOnly, deferred));
}
}
});
})(selectionSet, context);
return fieldMap;
};
StoreWriter.prototype.applyMerges = function (mergeTree, existing, incoming, context, getStorageArgs) {
var _a;
var _this = this;
if (mergeTree.map.size && !isReference(incoming)) {
var e_1 =
// Items in the same position in different arrays are not
// necessarily related to each other, so when incoming is an array
// we process its elements as if there was no existing data.
(!isArray(incoming) &&
// Likewise, existing must be either a Reference or a StoreObject
// in order for its fields to be safe to merge with the fields of
// the incoming object.
(isReference(existing) || storeValueIsStoreObject(existing))) ?
existing
: void 0;
// This narrowing is implied by mergeTree.map.size > 0 and
// !isReference(incoming), though TypeScript understandably cannot
// hope to infer this type.
var i_1 = incoming;
// The options.storage objects provided to read and merge functions
// are derived from the identity of the parent object plus a
// sequence of storeFieldName strings/numbers identifying the nested
// field name path of each field value to be merged.
if (e_1 && !getStorageArgs) {
getStorageArgs = [isReference(e_1) ? e_1.__ref : e_1];
}
// It's possible that applying merge functions to this subtree will
// not change the incoming data, so this variable tracks the fields
// that did change, so we can create a new incoming object when (and
// only when) at least one incoming field has changed. We use a Map
// to preserve the type of numeric keys.
var changedFields_1;
var getValue_1 = function (from, name) {
return (isArray(from) ?
typeof name === "number" ?
from[name]
: void 0
: context.store.getFieldValue(from, String(name)));
};
mergeTree.map.forEach(function (childTree, storeFieldName) {
var eVal = getValue_1(e_1, storeFieldName);
var iVal = getValue_1(i_1, storeFieldName);
// If we have no incoming data, leave any existing data untouched.
if (void 0 === iVal)
return;
if (getStorageArgs) {
getStorageArgs.push(storeFieldName);
}
var aVal = _this.applyMerges(childTree, eVal, iVal, context, getStorageArgs);
if (aVal !== iVal) {
changedFields_1 = changedFields_1 || new Map();
changedFields_1.set(storeFieldName, aVal);
}
if (getStorageArgs) {
invariant(getStorageArgs.pop() === storeFieldName);
}
});
if (changedFields_1) {
// Shallow clone i so we can add changed fields to it.
incoming = (isArray(i_1) ? i_1.slice(0) : __assign({}, i_1));
changedFields_1.forEach(function (value, name) {
incoming[name] = value;
});
}
}
if (mergeTree.info) {
return this.cache.policies.runMergeFunction(existing, incoming, mergeTree.info, context, getStorageArgs && (_a = context.store).getStorage.apply(_a, getStorageArgs));
}
return incoming;
};
return StoreWriter;
}());
export { StoreWriter };
var emptyMergeTreePool = [];
function getChildMergeTree(_a, name) {
var map = _a.map;
if (!map.has(name)) {
map.set(name, emptyMergeTreePool.pop() || { map: new Map() });
}
return map.get(name);
}
function mergeMergeTrees(left, right) {
if (left === right || !right || mergeTreeIsEmpty(right))
return left;
if (!left || mergeTreeIsEmpty(left))
return right;
var info = left.info && right.info ? __assign(__assign({}, left.info), right.info) : left.info || right.info;
var needToMergeMaps = left.map.size && right.map.size;
var map = needToMergeMaps ? new Map()
: left.map.size ? left.map
: right.map;
var merged = { info: info, map: map };
if (needToMergeMaps) {
var remainingRightKeys_1 = new Set(right.map.keys());
left.map.forEach(function (leftTree, key) {
merged.map.set(key, mergeMergeTrees(leftTree, right.map.get(key)));
remainingRightKeys_1.delete(key);
});
remainingRightKeys_1.forEach(function (key) {
merged.map.set(key, mergeMergeTrees(right.map.get(key), left.map.get(key)));
});
}
return merged;
}
function mergeTreeIsEmpty(tree) {
return !tree || !(tree.info || tree.map.size);
}
function maybeRecycleChildMergeTree(_a, name) {
var map = _a.map;
var childTree = map.get(name);
if (childTree && mergeTreeIsEmpty(childTree)) {
emptyMergeTreePool.push(childTree);
map.delete(name);
}
}
var warnings = new Set();
// Note that this function is unused in production, and thus should be
// pruned by any well-configured minifier.
function warnAboutDataLoss(existingRef, incomingObj, storeFieldName, store) {
var getChild = function (objOrRef) {
var child = store.getFieldValue(objOrRef, storeFieldName);
return typeof child === "object" && child;
};
var existing = getChild(existingRef);
if (!existing)
return;
var incoming = getChild(incomingObj);
if (!incoming)
return;
// It's always safe to replace a reference, since it refers to data
// safely stored elsewhere.
if (isReference(existing))
return;
// If the values are structurally equivalent, we do not need to worry
// about incoming replacing existing.
if (equal(existing, incoming))
return;
// If we're replacing every key of the existing object, then the
// existing data would be overwritten even if the objects were
// normalized, so warning would not be helpful here.
if (Object.keys(existing).every(function (key) { return store.getFieldValue(incoming, key) !== void 0; })) {
return;
}
var parentType = store.getFieldValue(existingRef, "__typename") ||
store.getFieldValue(incomingObj, "__typename");
var fieldName = fieldNameFromStoreName(storeFieldName);
var typeDotName = "".concat(parentType, ".").concat(fieldName);
// Avoid warning more than once for the same type and field name.
if (warnings.has(typeDotName))
return;
warnings.add(typeDotName);
var childTypenames = [];
// Arrays do not have __typename fields, and always need a custom merge
// function, even if their elements are normalized entities.
if (!isArray(existing) && !isArray(incoming)) {
[existing, incoming].forEach(function (child) {
var typename = store.getFieldValue(child, "__typename");
if (typeof typename === "string" && !childTypenames.includes(typename)) {
childTypenames.push(typename);
}
});
}
globalThis.__DEV__ !== false && invariant.warn(14, fieldName, parentType, childTypenames.length ?
"either ensure all objects of type " +
childTypenames.join(" and ") +
" have an ID or a custom merge function, or "
: "", typeDotName, existing, incoming);
}
//# sourceMappingURL=writeToStore.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/cache/inmemory/inMemoryCache.js
import { __assign, __extends } from "tslib";
import { invariant } from "../../utilities/globals/index.js";
// Make builtins like Map and Set safe to use with non-extensible objects.
import "./fixPolyfills.js";
import { wrap } from "optimism";
import { equal } from "@wry/equality";
import { ApolloCache } from "../core/cache.js";
import { MissingFieldError } from "../core/types/common.js";
import { addTypenameToDocument, isReference, DocumentTransform, canonicalStringify, print, cacheSizes, } from "../../utilities/index.js";
import { StoreReader } from "./readFromStore.js";
import { StoreWriter } from "./writeToStore.js";
import { EntityStore, supportsResultCaching } from "./entityStore.js";
import { makeVar, forgetCache, recallCache } from "./reactiveVars.js";
import { Policies } from "./policies.js";
import { hasOwn, normalizeConfig, shouldCanonizeResults } from "./helpers.js";
import { getInMemoryCacheMemoryInternals } from "../../utilities/caching/getMemoryInternals.js";
var InMemoryCache = /** @class */ (function (_super) {
__extends(InMemoryCache, _super);
function InMemoryCache(config) {
if (config === void 0) { config = {}; }
var _this = _super.call(this) || this;
_this.watches = new Set();
_this.addTypenameTransform = new DocumentTransform(addTypenameToDocument);
// Override the default value, since InMemoryCache result objects are frozen
// in development and expected to remain logically immutable in production.
_this.assumeImmutableResults = true;
_this.makeVar = makeVar;
_this.txCount = 0;
_this.config = normalizeConfig(config);
_this.addTypename = !!_this.config.addTypename;
_this.policies = new Policies({
cache: _this,
dataIdFromObject: _this.config.dataIdFromObject,
possibleTypes: _this.config.possibleTypes,
typePolicies: _this.config.typePolicies,
});
_this.init();
return _this;
}
InMemoryCache.prototype.init = function () {
// Passing { resultCaching: false } in the InMemoryCache constructor options
// will completely disable dependency tracking, which will improve memory
// usage but worsen the performance of repeated reads.
var rootStore = (this.data = new EntityStore.Root({
policies: this.policies,
resultCaching: this.config.resultCaching,
}));
// When no optimistic writes are currently active, cache.optimisticData ===
// cache.data, so there are no additional layers on top of the actual data.
// When an optimistic update happens, this.optimisticData will become a
// linked list of EntityStore Layer objects that terminates with the
// original this.data cache object.
this.optimisticData = rootStore.stump;
this.resetResultCache();
};
InMemoryCache.prototype.resetResultCache = function (resetResultIdentities) {
var _this = this;
var previousReader = this.storeReader;
var fragments = this.config.fragments;
// The StoreWriter is mostly stateless and so doesn't really need to be
// reset, but it does need to have its writer.storeReader reference updated,
// so it's simpler to update this.storeWriter as well.
this.storeWriter = new StoreWriter(this, (this.storeReader = new StoreReader({
cache: this,
addTypename: this.addTypename,
resultCacheMaxSize: this.config.resultCacheMaxSize,
canonizeResults: shouldCanonizeResults(this.config),
canon: resetResultIdentities ? void 0 : (previousReader && previousReader.canon),
fragments: fragments,
})), fragments);
this.maybeBroadcastWatch = wrap(function (c, options) {
return _this.broadcastWatch(c, options);
}, {
max: this.config.resultCacheMaxSize ||
cacheSizes["inMemoryCache.maybeBroadcastWatch"] ||
5000 /* defaultCacheSizes["inMemoryCache.maybeBroadcastWatch"] */,
makeCacheKey: function (c) {
// Return a cache key (thus enabling result caching) only if we're
// currently using a data store that can track cache dependencies.
var store = c.optimistic ? _this.optimisticData : _this.data;
if (supportsResultCaching(store)) {
var optimistic = c.optimistic, id = c.id, variables = c.variables;
return store.makeCacheKey(c.query,
// Different watches can have the same query, optimistic
// status, rootId, and variables, but if their callbacks are
// different, the (identical) result needs to be delivered to
// each distinct callback. The easiest way to achieve that
// separation is to include c.callback in the cache key for
// maybeBroadcastWatch calls. See issue #5733.
c.callback, canonicalStringify({ optimistic: optimistic, id: id, variables: variables }));
}
},
});
// Since we have thrown away all the cached functions that depend on the
// CacheGroup dependencies maintained by EntityStore, we should also reset
// all CacheGroup dependency information.
new Set([this.data.group, this.optimisticData.group]).forEach(function (group) {
return group.resetCaching();
});
};
InMemoryCache.prototype.restore = function (data) {
this.init();
// Since calling this.init() discards/replaces the entire StoreReader, along
// with the result caches it maintains, this.data.replace(data) won't have
// to bother deleting the old data.
if (data)
this.data.replace(data);
return this;
};
InMemoryCache.prototype.extract = function (optimistic) {
if (optimistic === void 0) { optimistic = false; }
return (optimistic ? this.optimisticData : this.data).extract();
};
InMemoryCache.prototype.read = function (options) {
var
// Since read returns data or null, without any additional metadata
// about whether/where there might have been missing fields, the
// default behavior cannot be returnPartialData = true (like it is
// for the diff method), since defaulting to true would violate the
// integrity of the T in the return type. However, partial data may
// be useful in some cases, so returnPartialData:true may be
// specified explicitly.
_a = options.returnPartialData,
// Since read returns data or null, without any additional metadata
// about whether/where there might have been missing fields, the
// default behavior cannot be returnPartialData = true (like it is
// for the diff method), since defaulting to true would violate the
// integrity of the T in the return type. However, partial data may
// be useful in some cases, so returnPartialData:true may be
// specified explicitly.
returnPartialData = _a === void 0 ? false : _a;
try {
return (this.storeReader.diffQueryAgainstStore(__assign(__assign({}, options), { store: options.optimistic ? this.optimisticData : this.data, config: this.config, returnPartialData: returnPartialData })).result || null);
}
catch (e) {
if (e instanceof MissingFieldError) {
// Swallow MissingFieldError and return null, so callers do not need to
// worry about catching "normal" exceptions resulting from incomplete
// cache data. Unexpected errors will be re-thrown. If you need more
// information about which fields were missing, use cache.diff instead,
// and examine diffResult.missing.
return null;
}
throw e;
}
};
InMemoryCache.prototype.write = function (options) {
try {
++this.txCount;
return this.storeWriter.writeToStore(this.data, options);
}
finally {
if (!--this.txCount && options.broadcast !== false) {
this.broadcastWatches();
}
}
};
InMemoryCache.prototype.modify = function (options) {
if (hasOwn.call(options, "id") && !options.id) {
// To my knowledge, TypeScript does not currently provide a way to
// enforce that an optional property?:type must *not* be undefined
// when present. That ability would be useful here, because we want
// options.id to default to ROOT_QUERY only when no options.id was
// provided. If the caller attempts to pass options.id with a
// falsy/undefined value (perhaps because cache.identify failed), we
// should not assume the goal was to modify the ROOT_QUERY object.
// We could throw, but it seems natural to return false to indicate
// that nothing was modified.
return false;
}
var store = ((options.optimistic) // Defaults to false.
) ?
this.optimisticData
: this.data;
try {
++this.txCount;
return store.modify(options.id || "ROOT_QUERY", options.fields);
}
finally {
if (!--this.txCount && options.broadcast !== false) {
this.broadcastWatches();
}
}
};
InMemoryCache.prototype.diff = function (options) {
return this.storeReader.diffQueryAgainstStore(__assign(__assign({}, options), { store: options.optimistic ? this.optimisticData : this.data, rootId: options.id || "ROOT_QUERY", config: this.config }));
};
InMemoryCache.prototype.watch = function (watch) {
var _this = this;
if (!this.watches.size) {
// In case we previously called forgetCache(this) because
// this.watches became empty (see below), reattach this cache to any
// reactive variables on which it previously depended. It might seem
// paradoxical that we're able to recall something we supposedly
// forgot, but the point of calling forgetCache(this) is to silence
// useless broadcasts while this.watches is empty, and to allow the
// cache to be garbage collected. If, however, we manage to call
// recallCache(this) here, this cache object must not have been
// garbage collected yet, and should resume receiving updates from
// reactive variables, now that it has a watcher to notify.
recallCache(this);
}
this.watches.add(watch);
if (watch.immediate) {
this.maybeBroadcastWatch(watch);
}
return function () {
// Once we remove the last watch from this.watches, cache.broadcastWatches
// no longer does anything, so we preemptively tell the reactive variable
// system to exclude this cache from future broadcasts.
if (_this.watches.delete(watch) && !_this.watches.size) {
forgetCache(_this);
}
// Remove this watch from the LRU cache managed by the
// maybeBroadcastWatch OptimisticWrapperFunction, to prevent memory
// leaks involving the closure of watch.callback.
_this.maybeBroadcastWatch.forget(watch);
};
};
InMemoryCache.prototype.gc = function (options) {
var _a;
canonicalStringify.reset();
print.reset();
this.addTypenameTransform.resetCache();
(_a = this.config.fragments) === null || _a === void 0 ? void 0 : _a.resetCaches();
var ids = this.optimisticData.gc();
if (options && !this.txCount) {
if (options.resetResultCache) {
this.resetResultCache(options.resetResultIdentities);
}
else if (options.resetResultIdentities) {
this.storeReader.resetCanon();
}
}
return ids;
};
// Call this method to ensure the given root ID remains in the cache after
// garbage collection, along with its transitive child entities. Note that
// the cache automatically retains all directly written entities. By default,
// the retainment persists after optimistic updates are removed. Pass true
// for the optimistic argument if you would prefer for the retainment to be
// discarded when the top-most optimistic layer is removed. Returns the
// resulting (non-negative) retainment count.
InMemoryCache.prototype.retain = function (rootId, optimistic) {
return (optimistic ? this.optimisticData : this.data).retain(rootId);
};
// Call this method to undo the effect of the retain method, above. Once the
// retainment count falls to zero, the given ID will no longer be preserved
// during garbage collection, though it may still be preserved by other safe
// entities that refer to it. Returns the resulting (non-negative) retainment
// count, in case that's useful.
InMemoryCache.prototype.release = function (rootId, optimistic) {
return (optimistic ? this.optimisticData : this.data).release(rootId);
};
// Returns the canonical ID for a given StoreObject, obeying typePolicies
// and keyFields (and dataIdFromObject, if you still use that). At minimum,
// the object must contain a __typename and any primary key fields required
// to identify entities of that type. If you pass a query result object, be
// sure that none of the primary key fields have been renamed by aliasing.
// If you pass a Reference object, its __ref ID string will be returned.
InMemoryCache.prototype.identify = function (object) {
if (isReference(object))
return object.__ref;
try {
return this.policies.identify(object)[0];
}
catch (e) {
globalThis.__DEV__ !== false && invariant.warn(e);
}
};
InMemoryCache.prototype.evict = function (options) {
if (!options.id) {
if (hasOwn.call(options, "id")) {
// See comment in modify method about why we return false when
// options.id exists but is falsy/undefined.
return false;
}
options = __assign(__assign({}, options), { id: "ROOT_QUERY" });
}
try {
// It's unlikely that the eviction will end up invoking any other
// cache update operations while it's running, but {in,de}crementing
// this.txCount still seems like a good idea, for uniformity with
// the other update methods.
++this.txCount;
// Pass this.data as a limit on the depth of the eviction, so evictions
// during optimistic updates (when this.data is temporarily set equal to
// this.optimisticData) do not escape their optimistic Layer.
return this.optimisticData.evict(options, this.data);
}
finally {
if (!--this.txCount && options.broadcast !== false) {
this.broadcastWatches();
}
}
};
InMemoryCache.prototype.reset = function (options) {
var _this = this;
this.init();
canonicalStringify.reset();
if (options && options.discardWatches) {
// Similar to what happens in the unsubscribe function returned by
// cache.watch, applied to all current watches.
this.watches.forEach(function (watch) { return _this.maybeBroadcastWatch.forget(watch); });
this.watches.clear();
forgetCache(this);
}
else {
// Calling this.init() above unblocks all maybeBroadcastWatch caching, so
// this.broadcastWatches() triggers a broadcast to every current watcher
// (letting them know their data is now missing). This default behavior is
// convenient because it means the watches do not have to be manually
// reestablished after resetting the cache. To prevent this broadcast and
// cancel all watches, pass true for options.discardWatches.
this.broadcastWatches();
}
return Promise.resolve();
};
InMemoryCache.prototype.removeOptimistic = function (idToRemove) {
var newOptimisticData = this.optimisticData.removeLayer(idToRemove);
if (newOptimisticData !== this.optimisticData) {
this.optimisticData = newOptimisticData;
this.broadcastWatches();
}
};
InMemoryCache.prototype.batch = function (options) {
var _this = this;
var update = options.update, _a = options.optimistic, optimistic = _a === void 0 ? true : _a, removeOptimistic = options.removeOptimistic, onWatchUpdated = options.onWatchUpdated;
var updateResult;
var perform = function (layer) {
var _a = _this, data = _a.data, optimisticData = _a.optimisticData;
++_this.txCount;
if (layer) {
_this.data = _this.optimisticData = layer;
}
try {
return (updateResult = update(_this));
}
finally {
--_this.txCount;
_this.data = data;
_this.optimisticData = optimisticData;
}
};
var alreadyDirty = new Set();
if (onWatchUpdated && !this.txCount) {
// If an options.onWatchUpdated callback is provided, we want to call it
// with only the Cache.WatchOptions objects affected by options.update,
// but there might be dirty watchers already waiting to be broadcast that
// have nothing to do with the update. To prevent including those watchers
// in the post-update broadcast, we perform this initial broadcast to
// collect the dirty watchers, so we can re-dirty them later, after the
// post-update broadcast, allowing them to receive their pending
// broadcasts the next time broadcastWatches is called, just as they would
// if we never called cache.batch.
this.broadcastWatches(__assign(__assign({}, options), { onWatchUpdated: function (watch) {
alreadyDirty.add(watch);
return false;
} }));
}
if (typeof optimistic === "string") {
// Note that there can be multiple layers with the same optimistic ID.
// When removeOptimistic(id) is called for that id, all matching layers
// will be removed, and the remaining layers will be reapplied.
this.optimisticData = this.optimisticData.addLayer(optimistic, perform);
}
else if (optimistic === false) {
// Ensure both this.data and this.optimisticData refer to the root
// (non-optimistic) layer of the cache during the update. Note that
// this.data could be a Layer if we are currently executing an optimistic
// update function, but otherwise will always be an EntityStore.Root
// instance.
perform(this.data);
}
else {
// Otherwise, leave this.data and this.optimisticData unchanged and run
// the update with broadcast batching.
perform();
}
if (typeof removeOptimistic === "string") {
this.optimisticData = this.optimisticData.removeLayer(removeOptimistic);
}
// Note: if this.txCount > 0, then alreadyDirty.size === 0, so this code
// takes the else branch and calls this.broadcastWatches(options), which
// does nothing when this.txCount > 0.
if (onWatchUpdated && alreadyDirty.size) {
this.broadcastWatches(__assign(__assign({}, options), { onWatchUpdated: function (watch, diff) {
var result = onWatchUpdated.call(this, watch, diff);
if (result !== false) {
// Since onWatchUpdated did not return false, this diff is
// about to be broadcast to watch.callback, so we don't need
// to re-dirty it with the other alreadyDirty watches below.
alreadyDirty.delete(watch);
}
return result;
} }));
// Silently re-dirty any watches that were already dirty before the update
// was performed, and were not broadcast just now.
if (alreadyDirty.size) {
alreadyDirty.forEach(function (watch) { return _this.maybeBroadcastWatch.dirty(watch); });
}
}
else {
// If alreadyDirty is empty or we don't have an onWatchUpdated
// function, we don't need to go to the trouble of wrapping
// options.onWatchUpdated.
this.broadcastWatches(options);
}
return updateResult;
};
InMemoryCache.prototype.performTransaction = function (update, optimisticId) {
return this.batch({
update: update,
optimistic: optimisticId || optimisticId !== null,
});
};
InMemoryCache.prototype.transformDocument = function (document) {
return this.addTypenameToDocument(this.addFragmentsToDocument(document));
};
InMemoryCache.prototype.broadcastWatches = function (options) {
var _this = this;
if (!this.txCount) {
this.watches.forEach(function (c) { return _this.maybeBroadcastWatch(c, options); });
}
};
InMemoryCache.prototype.addFragmentsToDocument = function (document) {
var fragments = this.config.fragments;
return fragments ? fragments.transform(document) : document;
};
InMemoryCache.prototype.addTypenameToDocument = function (document) {
if (this.addTypename) {
return this.addTypenameTransform.transformDocument(document);
}
return document;
};
// This method is wrapped by maybeBroadcastWatch, which is called by
// broadcastWatches, so that we compute and broadcast results only when
// the data that would be broadcast might have changed. It would be
// simpler to check for changes after recomputing a result but before
// broadcasting it, but this wrapping approach allows us to skip both
// the recomputation and the broadcast, in most cases.
InMemoryCache.prototype.broadcastWatch = function (c, options) {
var lastDiff = c.lastDiff;
// Both WatchOptions and DiffOptions extend ReadOptions, and DiffOptions
// currently requires no additional properties, so we can use c (a
// WatchOptions object) as DiffOptions, without having to allocate a new
// object, and without having to enumerate the relevant properties (query,
// variables, etc.) explicitly. There will be some additional properties
// (lastDiff, callback, etc.), but cache.diff ignores them.
var diff = this.diff(c);
if (options) {
if (c.optimistic && typeof options.optimistic === "string") {
diff.fromOptimisticTransaction = true;
}
if (options.onWatchUpdated &&
options.onWatchUpdated.call(this, c, diff, lastDiff) === false) {
// Returning false from the onWatchUpdated callback will prevent
// calling c.callback(diff) for this watcher.
return;
}
}
if (!lastDiff || !equal(lastDiff.result, diff.result)) {
c.callback((c.lastDiff = diff), lastDiff);
}
};
return InMemoryCache;
}(ApolloCache));
export { InMemoryCache };
if (globalThis.__DEV__ !== false) {
InMemoryCache.prototype.getMemoryInternals = getInMemoryCacheMemoryInternals;
}
//# sourceMappingURL=inMemoryCache.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/link/core/execute.js
import { ApolloLink } from "./ApolloLink.js";
export var execute = ApolloLink.execute;
//# sourceMappingURL=execute.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/link/http/HttpLink.js
import { __extends } from "tslib";
import { ApolloLink } from "../core/index.js";
import { createHttpLink } from "./createHttpLink.js";
var HttpLink = /** @class */ (function (_super) {
__extends(HttpLink, _super);
function HttpLink(options) {
if (options === void 0) { options = {}; }
var _this = _super.call(this, createHttpLink(options).request) || this;
_this.options = options;
return _this;
}
return HttpLink;
}(ApolloLink));
export { HttpLink };
//# sourceMappingURL=HttpLink.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/observables/asyncMap.js
import { Observable } from "./Observable.js";
// Like Observable.prototype.map, except that the mapping function can
// optionally return a Promise (or be async).
export function asyncMap(observable, mapFn, catchFn) {
return new Observable(function (observer) {
var promiseQueue = {
// Normally we would initialize promiseQueue to Promise.resolve(), but
// in this case, for backwards compatibility, we need to be careful to
// invoke the first callback synchronously.
then: function (callback) {
return new Promise(function (resolve) { return resolve(callback()); });
},
};
function makeCallback(examiner, key) {
return function (arg) {
if (examiner) {
var both = function () {
// If the observer is closed, we don't want to continue calling the
// mapping function - it's result will be swallowed anyways.
return observer.closed ?
/* will be swallowed */ 0
: examiner(arg);
};
promiseQueue = promiseQueue.then(both, both).then(function (result) { return observer.next(result); }, function (error) { return observer.error(error); });
}
else {
observer[key](arg);
}
};
}
var handler = {
next: makeCallback(mapFn, "next"),
error: makeCallback(catchFn, "error"),
complete: function () {
// no need to reassign `promiseQueue`, after `observer.complete`,
// the observer will be closed and short-circuit everything anyways
/*promiseQueue = */ promiseQueue.then(function () { return observer.complete(); });
},
};
var sub = observable.subscribe(handler);
return function () { return sub.unsubscribe(); };
});
}
//# sourceMappingURL=asyncMap.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/common/errorHandling.js
import { isNonEmptyArray } from "./arrays.js";
import { isExecutionPatchIncrementalResult } from "./incrementalResult.js";
export function graphQLResultHasError(result) {
var errors = getGraphQLErrorsFromResult(result);
return isNonEmptyArray(errors);
}
export function getGraphQLErrorsFromResult(result) {
var graphQLErrors = isNonEmptyArray(result.errors) ? result.errors.slice(0) : [];
if (isExecutionPatchIncrementalResult(result) &&
isNonEmptyArray(result.incremental)) {
result.incremental.forEach(function (incrementalResult) {
if (incrementalResult.errors) {
graphQLErrors.push.apply(graphQLErrors, incrementalResult.errors);
}
});
}
return graphQLErrors;
}
//# sourceMappingURL=errorHandling.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/observables/iteration.js
export function iterateObserversSafely(observers, method, argument) {
// In case observers is modified during iteration, we need to commit to the
// original elements, which also provides an opportunity to filter them down
// to just the observers with the given method.
var observersWithMethod = [];
observers.forEach(function (obs) { return obs[method] && observersWithMethod.push(obs); });
observersWithMethod.forEach(function (obs) { return obs[method](argument); });
}
//# sourceMappingURL=iteration.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/observables/subclassing.js
import { Observable } from "./Observable.js";
import { canUseSymbol } from "../common/canUse.js";
// Generic implementations of Observable.prototype methods like map and
// filter need to know how to create a new Observable from an Observable
// subclass (like Concast or ObservableQuery). Those methods assume
// (perhaps unwisely?) that they can call the subtype's constructor with a
// Subscriber function, even though the subclass constructor might expect
// different parameters. Defining this static Symbol.species property on
// the subclass is a hint to generic Observable code to use the default
// constructor instead of trying to do `new Subclass(observer => ...)`.
export function fixObservableSubclass(subclass) {
function set(key) {
// Object.defineProperty is necessary because the Symbol.species
// property is a getter by default in modern JS environments, so we
// can't assign to it with a normal assignment expression.
Object.defineProperty(subclass, key, { value: Observable });
}
if (canUseSymbol && Symbol.species) {
set(Symbol.species);
}
// The "@@species" string is used as a fake Symbol.species value in some
// polyfill systems (including the SymbolSpecies variable used by
// zen-observable), so we should set it as well, to be safe.
set("@@species");
return subclass;
}
//# sourceMappingURL=subclassing.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/observables/Concast.js
import { __extends } from "tslib";
import { Observable } from "./Observable.js";
import { iterateObserversSafely } from "./iteration.js";
import { fixObservableSubclass } from "./subclassing.js";
function isPromiseLike(value) {
return value && typeof value.then === "function";
}
// A Concast<T> observable concatenates the given sources into a single
// non-overlapping sequence of Ts, automatically unwrapping any promises,
// and broadcasts the T elements of that sequence to any number of
// subscribers, all without creating a bunch of intermediary Observable
// wrapper objects.
//
// Even though any number of observers can subscribe to the Concast, each
// source observable is guaranteed to receive at most one subscribe call,
// and the results are multicast to all observers.
//
// In addition to broadcasting every next/error message to this.observers,
// the Concast stores the most recent message using this.latest, so any
// new observers can immediately receive the latest message, even if it
// was originally delivered in the past. This behavior means we can assume
// every active observer in this.observers has received the same most
// recent message.
//
// With the exception of this.latest replay, a Concast is a "hot"
// observable in the sense that it does not replay past results from the
// beginning of time for each new observer.
//
// Could we have used some existing RxJS class instead? Concast<T> is
// similar to a BehaviorSubject<T>, because it is multicast and redelivers
// the latest next/error message to new subscribers. Unlike Subject<T>,
// Concast<T> does not expose an Observer<T> interface (this.handlers is
// intentionally private), since Concast<T> gets its inputs from the
// concatenated sources. If we ever switch to RxJS, there may be some
// value in reusing their code, but for now we use zen-observable, which
// does not contain any Subject implementations.
var Concast = /** @class */ (function (_super) {
__extends(Concast, _super);
// Not only can the individual elements of the iterable be promises, but
// also the iterable itself can be wrapped in a promise.
function Concast(sources) {
var _this = _super.call(this, function (observer) {
_this.addObserver(observer);
return function () { return _this.removeObserver(observer); };
}) || this;
// Active observers receiving broadcast messages. Thanks to this.latest,
// we can assume all observers in this Set have received the same most
// recent message, though possibly at different times in the past.
_this.observers = new Set();
_this.promise = new Promise(function (resolve, reject) {
_this.resolve = resolve;
_this.reject = reject;
});
// Bound handler functions that can be reused for every internal
// subscription.
_this.handlers = {
next: function (result) {
if (_this.sub !== null) {
_this.latest = ["next", result];
_this.notify("next", result);
iterateObserversSafely(_this.observers, "next", result);
}
},
error: function (error) {
var sub = _this.sub;
if (sub !== null) {
// Delay unsubscribing from the underlying subscription slightly,
// so that immediately subscribing another observer can keep the
// subscription active.
if (sub)
setTimeout(function () { return sub.unsubscribe(); });
_this.sub = null;
_this.latest = ["error", error];
_this.reject(error);
_this.notify("error", error);
iterateObserversSafely(_this.observers, "error", error);
}
},
complete: function () {
var _a = _this, sub = _a.sub, _b = _a.sources, sources = _b === void 0 ? [] : _b;
if (sub !== null) {
// If complete is called before concast.start, this.sources may be
// undefined, so we use a default value of [] for sources. That works
// here because it falls into the if (!value) {...} block, which
// appropriately terminates the Concast, even if this.sources might
// eventually have been initialized to a non-empty array.
var value = sources.shift();
if (!value) {
if (sub)
setTimeout(function () { return sub.unsubscribe(); });
_this.sub = null;
if (_this.latest && _this.latest[0] === "next") {
_this.resolve(_this.latest[1]);
}
else {
_this.resolve();
}
_this.notify("complete");
// We do not store this.latest = ["complete"], because doing so
// discards useful information about the previous next (or
// error) message. Instead, if new observers subscribe after
// this Concast has completed, they will receive the final
// 'next' message (unless there was an error) immediately
// followed by a 'complete' message (see addObserver).
iterateObserversSafely(_this.observers, "complete");
}
else if (isPromiseLike(value)) {
value.then(function (obs) { return (_this.sub = obs.subscribe(_this.handlers)); }, _this.handlers.error);
}
else {
_this.sub = value.subscribe(_this.handlers);
}
}
},
};
_this.nextResultListeners = new Set();
// A public way to abort observation and broadcast.
_this.cancel = function (reason) {
_this.reject(reason);
_this.sources = [];
_this.handlers.complete();
};
// Suppress rejection warnings for this.promise, since it's perfectly
// acceptable to pay no attention to this.promise if you're consuming
// the results through the normal observable API.
_this.promise.catch(function (_) { });
// If someone accidentally tries to create a Concast using a subscriber
// function, recover by creating an Observable from that subscriber and
// using it as the source.
if (typeof sources === "function") {
sources = [new Observable(sources)];
}
if (isPromiseLike(sources)) {
sources.then(function (iterable) { return _this.start(iterable); }, _this.handlers.error);
}
else {
_this.start(sources);
}
return _this;
}
Concast.prototype.start = function (sources) {
if (this.sub !== void 0)
return;
// In practice, sources is most often simply an Array of observables.
// TODO Consider using sources[Symbol.iterator]() to take advantage
// of the laziness of non-Array iterables.
this.sources = Array.from(sources);
// Calling this.handlers.complete() kicks off consumption of the first
// source observable. It's tempting to do this step lazily in
// addObserver, but this.promise can be accessed without calling
// addObserver, so consumption needs to begin eagerly.
this.handlers.complete();
};
Concast.prototype.deliverLastMessage = function (observer) {
if (this.latest) {
var nextOrError = this.latest[0];
var method = observer[nextOrError];
if (method) {
method.call(observer, this.latest[1]);
}
// If the subscription is already closed, and the last message was
// a 'next' message, simulate delivery of the final 'complete'
// message again.
if (this.sub === null && nextOrError === "next" && observer.complete) {
observer.complete();
}
}
};
Concast.prototype.addObserver = function (observer) {
if (!this.observers.has(observer)) {
// Immediately deliver the most recent message, so we can always
// be sure all observers have the latest information.
this.deliverLastMessage(observer);
this.observers.add(observer);
}
};
Concast.prototype.removeObserver = function (observer) {
if (this.observers.delete(observer) && this.observers.size < 1) {
// In case there are still any listeners in this.nextResultListeners, and
// no error or completion has been broadcast yet, make sure those
// observers have a chance to run and then remove themselves from
// this.observers.
this.handlers.complete();
}
};
Concast.prototype.notify = function (method, arg) {
var nextResultListeners = this.nextResultListeners;
if (nextResultListeners.size) {
// Replacing this.nextResultListeners first ensures it does not grow while
// we are iterating over it, potentially leading to infinite loops.
this.nextResultListeners = new Set();
nextResultListeners.forEach(function (listener) { return listener(method, arg); });
}
};
// We need a way to run callbacks just *before* the next result (or error or
// completion) is delivered by this Concast, so we can be sure any code that
// runs as a result of delivering that result/error observes the effects of
// running the callback(s). It was tempting to reuse the Observer type instead
// of introducing NextResultListener, but that messes with the sizing and
// maintenance of this.observers, and ends up being more code overall.
Concast.prototype.beforeNext = function (callback) {
var called = false;
this.nextResultListeners.add(function (method, arg) {
if (!called) {
called = true;
callback(method, arg);
}
});
};
return Concast;
}(Observable));
export { Concast };
// Necessary because the Concast constructor has a different signature
// than the Observable constructor.
fixObservableSubclass(Concast);
//# sourceMappingURL=Concast.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/core/networkStatus.js
/**
* The current status of a query’s execution in our system.
*/
export var NetworkStatus;
(function (NetworkStatus) {
/**
* The query has never been run before and the query is now currently running. A query will still
* have this network status even if a partial data result was returned from the cache, but a
* query was dispatched anyway.
*/
NetworkStatus[NetworkStatus["loading"] = 1] = "loading";
/**
* If `setVariables` was called and a query was fired because of that then the network status
* will be `setVariables` until the result of that query comes back.
*/
NetworkStatus[NetworkStatus["setVariables"] = 2] = "setVariables";
/**
* Indicates that `fetchMore` was called on this query and that the query created is currently in
* flight.
*/
NetworkStatus[NetworkStatus["fetchMore"] = 3] = "fetchMore";
/**
* Similar to the `setVariables` network status. It means that `refetch` was called on a query
* and the refetch request is currently in flight.
*/
NetworkStatus[NetworkStatus["refetch"] = 4] = "refetch";
/**
* Indicates that a polling query is currently in flight. So for example if you are polling a
* query every 10 seconds then the network status will switch to `poll` every 10 seconds whenever
* a poll request has been sent but not resolved.
*/
NetworkStatus[NetworkStatus["poll"] = 6] = "poll";
/**
* No request is in flight for this query, and no errors happened. Everything is OK.
*/
NetworkStatus[NetworkStatus["ready"] = 7] = "ready";
/**
* No request is in flight for this query, but one or more errors were detected.
*/
NetworkStatus[NetworkStatus["error"] = 8] = "error";
})(NetworkStatus || (NetworkStatus = {}));
/**
* Returns true if there is currently a network request in flight according to a given network
* status.
*/
export function isNetworkRequestInFlight(networkStatus) {
return networkStatus ? networkStatus < 7 : false;
}
/**
* Returns true if the network request is in ready or error state according to a given network
* status.
*/
export function isNetworkRequestSettled(networkStatus) {
return networkStatus === 7 || networkStatus === 8;
}
//# sourceMappingURL=networkStatus.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/core/equalByQuery.js
import { __rest } from "tslib";
import equal from "@wry/equality";
import { createFragmentMap, getFragmentDefinitions, getFragmentFromSelection, getMainDefinition, isField, resultKeyNameFromField, shouldInclude, } from "../utilities/index.js";
// Returns true if aResult and bResult are deeply equal according to the fields
// selected by the given query, ignoring any fields marked as @nonreactive.
export function equalByQuery(query, _a, _b, variables) {
var aData = _a.data, aRest = __rest(_a, ["data"]);
var bData = _b.data, bRest = __rest(_b, ["data"]);
return (equal(aRest, bRest) &&
equalBySelectionSet(getMainDefinition(query).selectionSet, aData, bData, {
fragmentMap: createFragmentMap(getFragmentDefinitions(query)),
variables: variables,
}));
}
function equalBySelectionSet(selectionSet, aResult, bResult, context) {
if (aResult === bResult) {
return true;
}
var seenSelections = new Set();
// Returning true from this Array.prototype.every callback function skips the
// current field/subtree. Returning false aborts the entire traversal
// immediately, causing equalBySelectionSet to return false.
return selectionSet.selections.every(function (selection) {
// Avoid re-processing the same selection at the same level of recursion, in
// case the same field gets included via multiple indirect fragment spreads.
if (seenSelections.has(selection))
return true;
seenSelections.add(selection);
// Ignore @skip(if: true) and @include(if: false) fields.
if (!shouldInclude(selection, context.variables))
return true;
// If the field or (named) fragment spread has a @nonreactive directive on
// it, we don't care if it's different, so we pretend it's the same.
if (selectionHasNonreactiveDirective(selection))
return true;
if (isField(selection)) {
var resultKey = resultKeyNameFromField(selection);
var aResultChild = aResult && aResult[resultKey];
var bResultChild = bResult && bResult[resultKey];
var childSelectionSet = selection.selectionSet;
if (!childSelectionSet) {
// These are scalar values, so we can compare them with deep equal
// without redoing the main recursive work.
return equal(aResultChild, bResultChild);
}
var aChildIsArray = Array.isArray(aResultChild);
var bChildIsArray = Array.isArray(bResultChild);
if (aChildIsArray !== bChildIsArray)
return false;
if (aChildIsArray && bChildIsArray) {
var length_1 = aResultChild.length;
if (bResultChild.length !== length_1) {
return false;
}
for (var i = 0; i < length_1; ++i) {
if (!equalBySelectionSet(childSelectionSet, aResultChild[i], bResultChild[i], context)) {
return false;
}
}
return true;
}
return equalBySelectionSet(childSelectionSet, aResultChild, bResultChild, context);
}
else {
var fragment = getFragmentFromSelection(selection, context.fragmentMap);
if (fragment) {
// The fragment might === selection if it's an inline fragment, but
// could be !== if it's a named fragment ...spread.
if (selectionHasNonreactiveDirective(fragment))
return true;
return equalBySelectionSet(fragment.selectionSet,
// Notice that we reuse the same aResult and bResult values here,
// since the fragment ...spread does not specify a field name, but
// consists of multiple fields (within the fragment's selection set)
// that should be applied to the current result value(s).
aResult, bResult, context);
}
}
});
}
function selectionHasNonreactiveDirective(selection) {
return (!!selection.directives && selection.directives.some(directiveIsNonreactive));
}
function directiveIsNonreactive(dir) {
return dir.name.value === "nonreactive";
}
//# sourceMappingURL=equalByQuery.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/core/ObservableQuery.js
import { __assign, __extends } from "tslib";
import { invariant } from "../utilities/globals/index.js";
import { equal } from "@wry/equality";
import { NetworkStatus, isNetworkRequestInFlight } from "./networkStatus.js";
import { cloneDeep, compact, getOperationDefinition, Observable, iterateObserversSafely, fixObservableSubclass, getQueryDefinition, } from "../utilities/index.js";
import { equalByQuery } from "./equalByQuery.js";
var assign = Object.assign, hasOwnProperty = Object.hasOwnProperty;
var ObservableQuery = /** @class */ (function (_super) {
__extends(ObservableQuery, _super);
function ObservableQuery(_a) {
var queryManager = _a.queryManager, queryInfo = _a.queryInfo, options = _a.options;
var _this = _super.call(this, function (observer) {
// Zen Observable has its own error function, so in order to log correctly
// we need to provide a custom error callback.
try {
var subObserver = observer._subscription._observer;
if (subObserver && !subObserver.error) {
subObserver.error = defaultSubscriptionObserverErrorCallback;
}
}
catch (_a) { }
var first = !_this.observers.size;
_this.observers.add(observer);
// Deliver most recent error or result.
var last = _this.last;
if (last && last.error) {
observer.error && observer.error(last.error);
}
else if (last && last.result) {
observer.next && observer.next(last.result);
}
// Initiate observation of this query if it hasn't been reported to
// the QueryManager yet.
if (first) {
// Blindly catching here prevents unhandled promise rejections,
// and is safe because the ObservableQuery handles this error with
// this.observer.error, so we're not just swallowing the error by
// ignoring it here.
_this.reobserve().catch(function () { });
}
return function () {
if (_this.observers.delete(observer) && !_this.observers.size) {
_this.tearDownQuery();
}
};
}) || this;
_this.observers = new Set();
_this.subscriptions = new Set();
// related classes
_this.queryInfo = queryInfo;
_this.queryManager = queryManager;
// active state
_this.waitForOwnResult = skipCacheDataFor(options.fetchPolicy);
_this.isTornDown = false;
var _b = queryManager.defaultOptions.watchQuery, _c = _b === void 0 ? {} : _b, _d = _c.fetchPolicy, defaultFetchPolicy = _d === void 0 ? "cache-first" : _d;
var _e = options.fetchPolicy, fetchPolicy = _e === void 0 ? defaultFetchPolicy : _e,
// Make sure we don't store "standby" as the initialFetchPolicy.
_f = options.initialFetchPolicy,
// Make sure we don't store "standby" as the initialFetchPolicy.
initialFetchPolicy = _f === void 0 ? fetchPolicy === "standby" ? defaultFetchPolicy : (fetchPolicy) : _f;
_this.options = __assign(__assign({}, options), {
// Remember the initial options.fetchPolicy so we can revert back to this
// policy when variables change. This information can also be specified
// (or overridden) by providing options.initialFetchPolicy explicitly.
initialFetchPolicy: initialFetchPolicy,
// This ensures this.options.fetchPolicy always has a string value, in
// case options.fetchPolicy was not provided.
fetchPolicy: fetchPolicy });
_this.queryId = queryInfo.queryId || queryManager.generateQueryId();
var opDef = getOperationDefinition(_this.query);
_this.queryName = opDef && opDef.name && opDef.name.value;
return _this;
}
Object.defineProperty(ObservableQuery.prototype, "query", {
// The `query` computed property will always reflect the document transformed
// by the last run query. `this.options.query` will always reflect the raw
// untransformed query to ensure document transforms with runtime conditionals
// are run on the original document.
get: function () {
return this.lastQuery || this.options.query;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ObservableQuery.prototype, "variables", {
// Computed shorthand for this.options.variables, preserved for
// backwards compatibility.
/**
* An object containing the variables that were provided for the query.
*/
get: function () {
return this.options.variables;
},
enumerable: false,
configurable: true
});
ObservableQuery.prototype.result = function () {
var _this = this;
return new Promise(function (resolve, reject) {
// TODO: this code doesn’t actually make sense insofar as the observer
// will never exist in this.observers due how zen-observable wraps observables.
// https://github.com/zenparsing/zen-observable/blob/master/src/Observable.js#L169
var observer = {
next: function (result) {
resolve(result);
// Stop the query within the QueryManager if we can before
// this function returns.
//
// We do this in order to prevent observers piling up within
// the QueryManager. Notice that we only fully unsubscribe
// from the subscription in a setTimeout(..., 0) call. This call can
// actually be handled by the browser at a much later time. If queries
// are fired in the meantime, observers that should have been removed
// from the QueryManager will continue to fire, causing an unnecessary
// performance hit.
_this.observers.delete(observer);
if (!_this.observers.size) {
_this.queryManager.removeQuery(_this.queryId);
}
setTimeout(function () {
subscription.unsubscribe();
}, 0);
},
error: reject,
};
var subscription = _this.subscribe(observer);
});
};
/** @internal */
ObservableQuery.prototype.resetDiff = function () {
this.queryInfo.resetDiff();
};
ObservableQuery.prototype.getCurrentResult = function (saveAsLastResult) {
if (saveAsLastResult === void 0) { saveAsLastResult = true; }
// Use the last result as long as the variables match this.variables.
var lastResult = this.getLastResult(true);
var networkStatus = this.queryInfo.networkStatus ||
(lastResult && lastResult.networkStatus) ||
NetworkStatus.ready;
var result = __assign(__assign({}, lastResult), { loading: isNetworkRequestInFlight(networkStatus), networkStatus: networkStatus });
var _a = this.options.fetchPolicy, fetchPolicy = _a === void 0 ? "cache-first" : _a;
if (
// These fetch policies should never deliver data from the cache, unless
// redelivering a previously delivered result.
skipCacheDataFor(fetchPolicy) ||
// If this.options.query has @client(always: true) fields, we cannot
// trust diff.result, since it was read from the cache without running
// local resolvers (and it's too late to run resolvers now, since we must
// return a result synchronously).
this.queryManager.getDocumentInfo(this.query).hasForcedResolvers) {
// Fall through.
}
else if (this.waitForOwnResult) {
// This would usually be a part of `QueryInfo.getDiff()`.
// which we skip in the waitForOwnResult case since we are not
// interested in the diff.
this.queryInfo["updateWatch"]();
}
else {
var diff = this.queryInfo.getDiff();
if (diff.complete || this.options.returnPartialData) {
result.data = diff.result;
}
if (equal(result.data, {})) {
result.data = void 0;
}
if (diff.complete) {
// Similar to setting result.partial to false, but taking advantage of the
// falsiness of missing fields.
delete result.partial;
// If the diff is complete, and we're using a FetchPolicy that
// terminates after a complete cache read, we can assume the next result
// we receive will have NetworkStatus.ready and !loading.
if (diff.complete &&
result.networkStatus === NetworkStatus.loading &&
(fetchPolicy === "cache-first" || fetchPolicy === "cache-only")) {
result.networkStatus = NetworkStatus.ready;
result.loading = false;
}
}
else {
result.partial = true;
}
if (globalThis.__DEV__ !== false &&
!diff.complete &&
!this.options.partialRefetch &&
!result.loading &&
!result.data &&
!result.error) {
logMissingFieldErrors(diff.missing);
}
}
if (saveAsLastResult) {
this.updateLastResult(result);
}
return result;
};
// Compares newResult to the snapshot we took of this.lastResult when it was
// first received.
ObservableQuery.prototype.isDifferentFromLastResult = function (newResult, variables) {
if (!this.last) {
return true;
}
var resultIsDifferent = this.queryManager.getDocumentInfo(this.query).hasNonreactiveDirective ?
!equalByQuery(this.query, this.last.result, newResult, this.variables)
: !equal(this.last.result, newResult);
return (resultIsDifferent || (variables && !equal(this.last.variables, variables)));
};
ObservableQuery.prototype.getLast = function (key, variablesMustMatch) {
var last = this.last;
if (last &&
last[key] &&
(!variablesMustMatch || equal(last.variables, this.variables))) {
return last[key];
}
};
ObservableQuery.prototype.getLastResult = function (variablesMustMatch) {
return this.getLast("result", variablesMustMatch);
};
ObservableQuery.prototype.getLastError = function (variablesMustMatch) {
return this.getLast("error", variablesMustMatch);
};
ObservableQuery.prototype.resetLastResults = function () {
delete this.last;
this.isTornDown = false;
};
ObservableQuery.prototype.resetQueryStoreErrors = function () {
this.queryManager.resetErrors(this.queryId);
};
/**
* Update the variables of this observable query, and fetch the new results.
* This method should be preferred over `setVariables` in most use cases.
*
* @param variables - The new set of variables. If there are missing variables,
* the previous values of those variables will be used.
*/
ObservableQuery.prototype.refetch = function (variables) {
var _a;
var reobserveOptions = {
// Always disable polling for refetches.
pollInterval: 0,
};
// Unless the provided fetchPolicy always consults the network
// (no-cache, network-only, or cache-and-network), override it with
// network-only to force the refetch for this fetchQuery call.
var fetchPolicy = this.options.fetchPolicy;
if (fetchPolicy === "cache-and-network") {
reobserveOptions.fetchPolicy = fetchPolicy;
}
else if (fetchPolicy === "no-cache") {
reobserveOptions.fetchPolicy = "no-cache";
}
else {
reobserveOptions.fetchPolicy = "network-only";
}
if (globalThis.__DEV__ !== false && variables && hasOwnProperty.call(variables, "variables")) {
var queryDef = getQueryDefinition(this.query);
var vars = queryDef.variableDefinitions;
if (!vars || !vars.some(function (v) { return v.variable.name.value === "variables"; })) {
globalThis.__DEV__ !== false && invariant.warn(
20,
variables,
((_a = queryDef.name) === null || _a === void 0 ? void 0 : _a.value) || queryDef
);
}
}
if (variables && !equal(this.options.variables, variables)) {
// Update the existing options with new variables
reobserveOptions.variables = this.options.variables = __assign(__assign({}, this.options.variables), variables);
}
this.queryInfo.resetLastWrite();
return this.reobserve(reobserveOptions, NetworkStatus.refetch);
};
/**
* A function that helps you fetch the next set of results for a [paginated list field](https://www.apollographql.com/docs/react/pagination/core-api/).
*/
ObservableQuery.prototype.fetchMore = function (fetchMoreOptions) {
var _this = this;
var combinedOptions = __assign(__assign({}, (fetchMoreOptions.query ? fetchMoreOptions : (__assign(__assign(__assign(__assign({}, this.options), { query: this.options.query }), fetchMoreOptions), { variables: __assign(__assign({}, this.options.variables), fetchMoreOptions.variables) })))), {
// The fetchMore request goes immediately to the network and does
// not automatically write its result to the cache (hence no-cache
// instead of network-only), because we allow the caller of
// fetchMore to provide an updateQuery callback that determines how
// the data gets written to the cache.
fetchPolicy: "no-cache" });
combinedOptions.query = this.transformDocument(combinedOptions.query);
var qid = this.queryManager.generateQueryId();
// If a temporary query is passed to `fetchMore`, we don't want to store
// it as the last query result since it may be an optimized query for
// pagination. We will however run the transforms on the original document
// as well as the document passed in `fetchMoreOptions` to ensure the cache
// uses the most up-to-date document which may rely on runtime conditionals.
this.lastQuery =
fetchMoreOptions.query ?
this.transformDocument(this.options.query)
: combinedOptions.query;
// Simulate a loading result for the original query with
// result.networkStatus === NetworkStatus.fetchMore.
var queryInfo = this.queryInfo;
var originalNetworkStatus = queryInfo.networkStatus;
queryInfo.networkStatus = NetworkStatus.fetchMore;
if (combinedOptions.notifyOnNetworkStatusChange) {
this.observe();
}
var updatedQuerySet = new Set();
return this.queryManager
.fetchQuery(qid, combinedOptions, NetworkStatus.fetchMore)
.then(function (fetchMoreResult) {
_this.queryManager.removeQuery(qid);
if (queryInfo.networkStatus === NetworkStatus.fetchMore) {
queryInfo.networkStatus = originalNetworkStatus;
}
// Performing this cache update inside a cache.batch transaction ensures
// any affected cache.watch watchers are notified at most once about any
// updates. Most watchers will be using the QueryInfo class, which
// responds to notifications by calling reobserveCacheFirst to deliver
// fetchMore cache results back to this ObservableQuery.
_this.queryManager.cache.batch({
update: function (cache) {
var updateQuery = fetchMoreOptions.updateQuery;
if (updateQuery) {
cache.updateQuery({
query: _this.query,
variables: _this.variables,
returnPartialData: true,
optimistic: false,
}, function (previous) {
return updateQuery(previous, {
fetchMoreResult: fetchMoreResult.data,
variables: combinedOptions.variables,
});
});
}
else {
// If we're using a field policy instead of updateQuery, the only
// thing we need to do is write the new data to the cache using
// combinedOptions.variables (instead of this.variables, which is
// what this.updateQuery uses, because it works by abusing the
// original field value, keyed by the original variables).
cache.writeQuery({
query: combinedOptions.query,
variables: combinedOptions.variables,
data: fetchMoreResult.data,
});
}
},
onWatchUpdated: function (watch) {
// Record the DocumentNode associated with any watched query whose
// data were updated by the cache writes above.
updatedQuerySet.add(watch.query);
},
});
return fetchMoreResult;
})
.finally(function () {
// In case the cache writes above did not generate a broadcast
// notification (which would have been intercepted by onWatchUpdated),
// likely because the written data were the same as what was already in
// the cache, we still want fetchMore to deliver its final loading:false
// result with the unchanged data.
if (!updatedQuerySet.has(_this.query)) {
reobserveCacheFirst(_this);
}
});
};
// XXX the subscription variables are separate from the query variables.
// if you want to update subscription variables, right now you have to do that separately,
// and you can only do it by stopping the subscription and then subscribing again with new variables.
/**
* A function that enables you to execute a [subscription](https://www.apollographql.com/docs/react/data/subscriptions/), usually to subscribe to specific fields that were included in the query.
*
* This function returns _another_ function that you can call to terminate the subscription.
*/
ObservableQuery.prototype.subscribeToMore = function (options) {
var _this = this;
var subscription = this.queryManager
.startGraphQLSubscription({
query: options.document,
variables: options.variables,
context: options.context,
})
.subscribe({
next: function (subscriptionData) {
var updateQuery = options.updateQuery;
if (updateQuery) {
_this.updateQuery(function (previous, _a) {
var variables = _a.variables;
return updateQuery(previous, {
subscriptionData: subscriptionData,
variables: variables,
});
});
}
},
error: function (err) {
if (options.onError) {
options.onError(err);
return;
}
globalThis.__DEV__ !== false && invariant.error(21, err);
},
});
this.subscriptions.add(subscription);
return function () {
if (_this.subscriptions.delete(subscription)) {
subscription.unsubscribe();
}
};
};
ObservableQuery.prototype.setOptions = function (newOptions) {
return this.reobserve(newOptions);
};
ObservableQuery.prototype.silentSetOptions = function (newOptions) {
var mergedOptions = compact(this.options, newOptions || {});
assign(this.options, mergedOptions);
};
/**
* Update the variables of this observable query, and fetch the new results
* if they've changed. Most users should prefer `refetch` instead of
* `setVariables` in order to to be properly notified of results even when
* they come from the cache.
*
* Note: the `next` callback will *not* fire if the variables have not changed
* or if the result is coming from cache.
*
* Note: the promise will return the old results immediately if the variables
* have not changed.
*
* Note: the promise will return null immediately if the query is not active
* (there are no subscribers).
*
* @param variables - The new set of variables. If there are missing variables,
* the previous values of those variables will be used.
*/
ObservableQuery.prototype.setVariables = function (variables) {
if (equal(this.variables, variables)) {
// If we have no observers, then we don't actually want to make a network
// request. As soon as someone observes the query, the request will kick
// off. For now, we just store any changes. (See #1077)
return this.observers.size ? this.result() : Promise.resolve();
}
this.options.variables = variables;
// See comment above
if (!this.observers.size) {
return Promise.resolve();
}
return this.reobserve({
// Reset options.fetchPolicy to its original value.
fetchPolicy: this.options.initialFetchPolicy,
variables: variables,
}, NetworkStatus.setVariables);
};
/**
* A function that enables you to update the query's cached result without executing a followup GraphQL operation.
*
* See [using updateQuery and updateFragment](https://www.apollographql.com/docs/react/caching/cache-interaction/#using-updatequery-and-updatefragment) for additional information.
*/
ObservableQuery.prototype.updateQuery = function (mapFn) {
var queryManager = this.queryManager;
var result = queryManager.cache.diff({
query: this.options.query,
variables: this.variables,
returnPartialData: true,
optimistic: false,
}).result;
var newResult = mapFn(result, {
variables: this.variables,
});
if (newResult) {
queryManager.cache.writeQuery({
query: this.options.query,
data: newResult,
variables: this.variables,
});
queryManager.broadcastQueries();
}
};
/**
* A function that instructs the query to begin re-executing at a specified interval (in milliseconds).
*/
ObservableQuery.prototype.startPolling = function (pollInterval) {
this.options.pollInterval = pollInterval;
this.updatePolling();
};
/**
* A function that instructs the query to stop polling after a previous call to `startPolling`.
*/
ObservableQuery.prototype.stopPolling = function () {
this.options.pollInterval = 0;
this.updatePolling();
};
// Update options.fetchPolicy according to options.nextFetchPolicy.
ObservableQuery.prototype.applyNextFetchPolicy = function (reason,
// It's possible to use this method to apply options.nextFetchPolicy to
// options.fetchPolicy even if options !== this.options, though that happens
// most often when the options are temporary, used for only one request and
// then thrown away, so nextFetchPolicy may not end up mattering.
options) {
if (options.nextFetchPolicy) {
var _a = options.fetchPolicy, fetchPolicy = _a === void 0 ? "cache-first" : _a, _b = options.initialFetchPolicy, initialFetchPolicy = _b === void 0 ? fetchPolicy : _b;
if (fetchPolicy === "standby") {
// Do nothing, leaving options.fetchPolicy unchanged.
}
else if (typeof options.nextFetchPolicy === "function") {
// When someone chooses "cache-and-network" or "network-only" as their
// initial FetchPolicy, they often do not want future cache updates to
// trigger unconditional network requests, which is what repeatedly
// applying the "cache-and-network" or "network-only" policies would
// seem to imply. Instead, when the cache reports an update after the
// initial network request, it may be desirable for subsequent network
// requests to be triggered only if the cache result is incomplete. To
// that end, the options.nextFetchPolicy option provides an easy way to
// update options.fetchPolicy after the initial network request, without
// having to call observableQuery.setOptions.
options.fetchPolicy = options.nextFetchPolicy(fetchPolicy, {
reason: reason,
options: options,
observable: this,
initialFetchPolicy: initialFetchPolicy,
});
}
else if (reason === "variables-changed") {
options.fetchPolicy = initialFetchPolicy;
}
else {
options.fetchPolicy = options.nextFetchPolicy;
}
}
return options.fetchPolicy;
};
ObservableQuery.prototype.fetch = function (options, newNetworkStatus, query) {
// TODO Make sure we update the networkStatus (and infer fetchVariables)
// before actually committing to the fetch.
this.queryManager.setObservableQuery(this);
return this.queryManager["fetchConcastWithInfo"](this.queryId, options, newNetworkStatus, query);
};
// Turns polling on or off based on this.options.pollInterval.
ObservableQuery.prototype.updatePolling = function () {
var _this = this;
// Avoid polling in SSR mode
if (this.queryManager.ssrMode) {
return;
}
var _a = this, pollingInfo = _a.pollingInfo, pollInterval = _a.options.pollInterval;
if (!pollInterval) {
if (pollingInfo) {
clearTimeout(pollingInfo.timeout);
delete this.pollingInfo;
}
return;
}
if (pollingInfo && pollingInfo.interval === pollInterval) {
return;
}
invariant(pollInterval, 22);
var info = pollingInfo || (this.pollingInfo = {});
info.interval = pollInterval;
var maybeFetch = function () {
var _a, _b;
if (_this.pollingInfo) {
if (!isNetworkRequestInFlight(_this.queryInfo.networkStatus) &&
!((_b = (_a = _this.options).skipPollAttempt) === null || _b === void 0 ? void 0 : _b.call(_a))) {
_this.reobserve({
// Most fetchPolicy options don't make sense to use in a polling context, as
// users wouldn't want to be polling the cache directly. However, network-only and
// no-cache are both useful for when the user wants to control whether or not the
// polled results are written to the cache.
fetchPolicy: _this.options.initialFetchPolicy === "no-cache" ?
"no-cache"
: "network-only",
}, NetworkStatus.poll).then(poll, poll);
}
else {
poll();
}
}
};
var poll = function () {
var info = _this.pollingInfo;
if (info) {
clearTimeout(info.timeout);
info.timeout = setTimeout(maybeFetch, info.interval);
}
};
poll();
};
ObservableQuery.prototype.updateLastResult = function (newResult, variables) {
if (variables === void 0) { variables = this.variables; }
var error = this.getLastError();
// Preserve this.last.error unless the variables have changed.
if (error && this.last && !equal(variables, this.last.variables)) {
error = void 0;
}
return (this.last = __assign({ result: this.queryManager.assumeImmutableResults ?
newResult
: cloneDeep(newResult), variables: variables }, (error ? { error: error } : null)));
};
ObservableQuery.prototype.reobserveAsConcast = function (newOptions, newNetworkStatus) {
var _this = this;
this.isTornDown = false;
var useDisposableConcast =
// Refetching uses a disposable Concast to allow refetches using different
// options/variables, without permanently altering the options of the
// original ObservableQuery.
newNetworkStatus === NetworkStatus.refetch ||
// The fetchMore method does not actually call the reobserve method, but,
// if it did, it would definitely use a disposable Concast.
newNetworkStatus === NetworkStatus.fetchMore ||
// Polling uses a disposable Concast so the polling options (which force
// fetchPolicy to be "network-only" or "no-cache") won't override the original options.
newNetworkStatus === NetworkStatus.poll;
// Save the old variables, since Object.assign may modify them below.
var oldVariables = this.options.variables;
var oldFetchPolicy = this.options.fetchPolicy;
var mergedOptions = compact(this.options, newOptions || {});
var options = useDisposableConcast ?
// Disposable Concast fetches receive a shallow copy of this.options
// (merged with newOptions), leaving this.options unmodified.
mergedOptions
: assign(this.options, mergedOptions);
// Don't update options.query with the transformed query to avoid
// overwriting this.options.query when we aren't using a disposable concast.
// We want to ensure we can re-run the custom document transforms the next
// time a request is made against the original query.
var query = this.transformDocument(options.query);
this.lastQuery = query;
if (!useDisposableConcast) {
// We can skip calling updatePolling if we're not changing this.options.
this.updatePolling();
// Reset options.fetchPolicy to its original value when variables change,
// unless a new fetchPolicy was provided by newOptions.
if (newOptions &&
newOptions.variables &&
!equal(newOptions.variables, oldVariables) &&
// Don't mess with the fetchPolicy if it's currently "standby".
options.fetchPolicy !== "standby" &&
// If we're changing the fetchPolicy anyway, don't try to change it here
// using applyNextFetchPolicy. The explicit options.fetchPolicy wins.
options.fetchPolicy === oldFetchPolicy) {
this.applyNextFetchPolicy("variables-changed", options);
if (newNetworkStatus === void 0) {
newNetworkStatus = NetworkStatus.setVariables;
}
}
}
this.waitForOwnResult && (this.waitForOwnResult = skipCacheDataFor(options.fetchPolicy));
var finishWaitingForOwnResult = function () {
if (_this.concast === concast) {
_this.waitForOwnResult = false;
}
};
var variables = options.variables && __assign({}, options.variables);
var _a = this.fetch(options, newNetworkStatus, query), concast = _a.concast, fromLink = _a.fromLink;
var observer = {
next: function (result) {
if (equal(_this.variables, variables)) {
finishWaitingForOwnResult();
_this.reportResult(result, variables);
}
},
error: function (error) {
if (equal(_this.variables, variables)) {
finishWaitingForOwnResult();
_this.reportError(error, variables);
}
},
};
if (!useDisposableConcast && (fromLink || !this.concast)) {
// We use the {add,remove}Observer methods directly to avoid wrapping
// observer with an unnecessary SubscriptionObserver object.
if (this.concast && this.observer) {
this.concast.removeObserver(this.observer);
}
this.concast = concast;
this.observer = observer;
}
concast.addObserver(observer);
return concast;
};
ObservableQuery.prototype.reobserve = function (newOptions, newNetworkStatus) {
return this.reobserveAsConcast(newOptions, newNetworkStatus)
.promise;
};
ObservableQuery.prototype.resubscribeAfterError = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
// If `lastError` is set in the current when the subscription is re-created,
// the subscription will immediately receive the error, which will
// cause it to terminate again. To avoid this, we first clear
// the last error/result from the `observableQuery` before re-starting
// the subscription, and restore the last value afterwards so that the
// subscription has a chance to stay open.
var last = this.last;
this.resetLastResults();
var subscription = this.subscribe.apply(this, args);
this.last = last;
return subscription;
};
// (Re)deliver the current result to this.observers without applying fetch
// policies or making network requests.
ObservableQuery.prototype.observe = function () {
this.reportResult(
// Passing false is important so that this.getCurrentResult doesn't
// save the fetchMore result as this.lastResult, causing it to be
// ignored due to the this.isDifferentFromLastResult check in
// this.reportResult.
this.getCurrentResult(false), this.variables);
};
ObservableQuery.prototype.reportResult = function (result, variables) {
var lastError = this.getLastError();
var isDifferent = this.isDifferentFromLastResult(result, variables);
// Update the last result even when isDifferentFromLastResult returns false,
// because the query may be using the @nonreactive directive, and we want to
// save the the latest version of any nonreactive subtrees (in case
// getCurrentResult is called), even though we skip broadcasting changes.
if (lastError || !result.partial || this.options.returnPartialData) {
this.updateLastResult(result, variables);
}
if (lastError || isDifferent) {
iterateObserversSafely(this.observers, "next", result);
}
};
ObservableQuery.prototype.reportError = function (error, variables) {
// Since we don't get the current result on errors, only the error, we
// must mirror the updates that occur in QueryStore.markQueryError here
var errorResult = __assign(__assign({}, this.getLastResult()), { error: error, errors: error.graphQLErrors, networkStatus: NetworkStatus.error, loading: false });
this.updateLastResult(errorResult, variables);
iterateObserversSafely(this.observers, "error", (this.last.error = error));
};
ObservableQuery.prototype.hasObservers = function () {
return this.observers.size > 0;
};
ObservableQuery.prototype.tearDownQuery = function () {
if (this.isTornDown)
return;
if (this.concast && this.observer) {
this.concast.removeObserver(this.observer);
delete this.concast;
delete this.observer;
}
this.stopPolling();
// stop all active GraphQL subscriptions
this.subscriptions.forEach(function (sub) { return sub.unsubscribe(); });
this.subscriptions.clear();
this.queryManager.stopQuery(this.queryId);
this.observers.clear();
this.isTornDown = true;
};
ObservableQuery.prototype.transformDocument = function (document) {
return this.queryManager.transform(document);
};
return ObservableQuery;
}(Observable));
export { ObservableQuery };
// Necessary because the ObservableQuery constructor has a different
// signature than the Observable constructor.
fixObservableSubclass(ObservableQuery);
// Reobserve with fetchPolicy effectively set to "cache-first", triggering
// delivery of any new data from the cache, possibly falling back to the network
// if any cache data are missing. This allows _complete_ cache results to be
// delivered without also kicking off unnecessary network requests when
// this.options.fetchPolicy is "cache-and-network" or "network-only". When
// this.options.fetchPolicy is any other policy ("cache-first", "cache-only",
// "standby", or "no-cache"), we call this.reobserve() as usual.
export function reobserveCacheFirst(obsQuery) {
var _a = obsQuery.options, fetchPolicy = _a.fetchPolicy, nextFetchPolicy = _a.nextFetchPolicy;
if (fetchPolicy === "cache-and-network" || fetchPolicy === "network-only") {
return obsQuery.reobserve({
fetchPolicy: "cache-first",
// Use a temporary nextFetchPolicy function that replaces itself with the
// previous nextFetchPolicy value and returns the original fetchPolicy.
nextFetchPolicy: function (currentFetchPolicy, context) {
// Replace this nextFetchPolicy function in the options object with the
// original this.options.nextFetchPolicy value.
this.nextFetchPolicy = nextFetchPolicy;
// If the original nextFetchPolicy value was a function, give it a
// chance to decide what happens here.
if (typeof this.nextFetchPolicy === "function") {
return this.nextFetchPolicy(currentFetchPolicy, context);
}
// Otherwise go back to the original this.options.fetchPolicy.
return fetchPolicy;
},
});
}
return obsQuery.reobserve();
}
function defaultSubscriptionObserverErrorCallback(error) {
globalThis.__DEV__ !== false && invariant.error(23, error.message, error.stack);
}
export function logMissingFieldErrors(missing) {
if (globalThis.__DEV__ !== false && missing) {
globalThis.__DEV__ !== false && invariant.debug(24, missing);
}
}
function skipCacheDataFor(fetchPolicy /* `undefined` would mean `"cache-first"` */) {
return (fetchPolicy === "network-only" ||
fetchPolicy === "no-cache" ||
fetchPolicy === "standby");
}
//# sourceMappingURL=ObservableQuery.js.map
webpack://frontend-mybets/../../node_modules/graphql/language/predicates.mjs
import { Kind } from "./kinds.mjs";
export function isDefinitionNode(node) {
return isExecutableDefinitionNode(node) || isTypeSystemDefinitionNode(node) || isTypeSystemExtensionNode(node);
}
export function isExecutableDefinitionNode(node) {
return node.kind === Kind.OPERATION_DEFINITION || node.kind === Kind.FRAGMENT_DEFINITION;
}
export function isSelectionNode(node) {
return node.kind === Kind.FIELD || node.kind === Kind.FRAGMENT_SPREAD || node.kind === Kind.INLINE_FRAGMENT;
}
export function isValueNode(node) {
return node.kind === Kind.VARIABLE || node.kind === Kind.INT || node.kind === Kind.FLOAT || node.kind === Kind.STRING || node.kind === Kind.BOOLEAN || node.kind === Kind.NULL || node.kind === Kind.ENUM || node.kind === Kind.LIST || node.kind === Kind.OBJECT;
}
export function isTypeNode(node) {
return node.kind === Kind.NAMED_TYPE || node.kind === Kind.LIST_TYPE || node.kind === Kind.NON_NULL_TYPE;
}
export function isTypeSystemDefinitionNode(node) {
return node.kind === Kind.SCHEMA_DEFINITION || isTypeDefinitionNode(node) || node.kind === Kind.DIRECTIVE_DEFINITION;
}
export function isTypeDefinitionNode(node) {
return node.kind === Kind.SCALAR_TYPE_DEFINITION || node.kind === Kind.OBJECT_TYPE_DEFINITION || node.kind === Kind.INTERFACE_TYPE_DEFINITION || node.kind === Kind.UNION_TYPE_DEFINITION || node.kind === Kind.ENUM_TYPE_DEFINITION || node.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION;
}
export function isTypeSystemExtensionNode(node) {
return node.kind === Kind.SCHEMA_EXTENSION || isTypeExtensionNode(node);
}
export function isTypeExtensionNode(node) {
return node.kind === Kind.SCALAR_TYPE_EXTENSION || node.kind === Kind.OBJECT_TYPE_EXTENSION || node.kind === Kind.INTERFACE_TYPE_EXTENSION || node.kind === Kind.UNION_TYPE_EXTENSION || node.kind === Kind.ENUM_TYPE_EXTENSION || node.kind === Kind.INPUT_OBJECT_TYPE_EXTENSION;
}
webpack://frontend-mybets/../../node_modules/@apollo/client/core/LocalState.js
import { __assign, __awaiter, __generator } from "tslib";
import { invariant } from "../utilities/globals/index.js";
import { visit, BREAK, isSelectionNode } from "graphql";
import { argumentsObjectFromField, buildQueryFromSelectionSet, createFragmentMap, getFragmentDefinitions, getMainDefinition, hasDirectives, isField, isInlineFragment, mergeDeep, mergeDeepArray, removeClientSetsFromDocument, resultKeyNameFromField, shouldInclude, } from "../utilities/index.js";
import { cacheSlot } from "../cache/index.js";
var LocalState = /** @class */ (function () {
function LocalState(_a) {
var cache = _a.cache, client = _a.client, resolvers = _a.resolvers, fragmentMatcher = _a.fragmentMatcher;
this.selectionsToResolveCache = new WeakMap();
this.cache = cache;
if (client) {
this.client = client;
}
if (resolvers) {
this.addResolvers(resolvers);
}
if (fragmentMatcher) {
this.setFragmentMatcher(fragmentMatcher);
}
}
LocalState.prototype.addResolvers = function (resolvers) {
var _this = this;
this.resolvers = this.resolvers || {};
if (Array.isArray(resolvers)) {
resolvers.forEach(function (resolverGroup) {
_this.resolvers = mergeDeep(_this.resolvers, resolverGroup);
});
}
else {
this.resolvers = mergeDeep(this.resolvers, resolvers);
}
};
LocalState.prototype.setResolvers = function (resolvers) {
this.resolvers = {};
this.addResolvers(resolvers);
};
LocalState.prototype.getResolvers = function () {
return this.resolvers || {};
};
// Run local client resolvers against the incoming query and remote data.
// Locally resolved field values are merged with the incoming remote data,
// and returned. Note that locally resolved fields will overwrite
// remote data using the same field name.
LocalState.prototype.runResolvers = function (_a) {
var document = _a.document, remoteResult = _a.remoteResult, context = _a.context, variables = _a.variables, _b = _a.onlyRunForcedResolvers, onlyRunForcedResolvers = _b === void 0 ? false : _b;
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_c) {
if (document) {
return [2 /*return*/, this.resolveDocument(document, remoteResult.data, context, variables, this.fragmentMatcher, onlyRunForcedResolvers).then(function (localResult) { return (__assign(__assign({}, remoteResult), { data: localResult.result })); })];
}
return [2 /*return*/, remoteResult];
});
});
};
LocalState.prototype.setFragmentMatcher = function (fragmentMatcher) {
this.fragmentMatcher = fragmentMatcher;
};
LocalState.prototype.getFragmentMatcher = function () {
return this.fragmentMatcher;
};
// Client queries contain everything in the incoming document (if a @client
// directive is found).
LocalState.prototype.clientQuery = function (document) {
if (hasDirectives(["client"], document)) {
if (this.resolvers) {
return document;
}
}
return null;
};
// Server queries are stripped of all @client based selection sets.
LocalState.prototype.serverQuery = function (document) {
return removeClientSetsFromDocument(document);
};
LocalState.prototype.prepareContext = function (context) {
var cache = this.cache;
return __assign(__assign({}, context), { cache: cache,
// Getting an entry's cache key is useful for local state resolvers.
getCacheKey: function (obj) {
return cache.identify(obj);
} });
};
// To support `@client @export(as: "someVar")` syntax, we'll first resolve
// @client @export fields locally, then pass the resolved values back to be
// used alongside the original operation variables.
LocalState.prototype.addExportedVariables = function (document, variables, context) {
if (variables === void 0) { variables = {}; }
if (context === void 0) { context = {}; }
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
if (document) {
return [2 /*return*/, this.resolveDocument(document, this.buildRootValueFromCache(document, variables) || {}, this.prepareContext(context), variables).then(function (data) { return (__assign(__assign({}, variables), data.exportedVariables)); })];
}
return [2 /*return*/, __assign({}, variables)];
});
});
};
LocalState.prototype.shouldForceResolvers = function (document) {
var forceResolvers = false;
visit(document, {
Directive: {
enter: function (node) {
if (node.name.value === "client" && node.arguments) {
forceResolvers = node.arguments.some(function (arg) {
return arg.name.value === "always" &&
arg.value.kind === "BooleanValue" &&
arg.value.value === true;
});
if (forceResolvers) {
return BREAK;
}
}
},
},
});
return forceResolvers;
};
// Query the cache and return matching data.
LocalState.prototype.buildRootValueFromCache = function (document, variables) {
return this.cache.diff({
query: buildQueryFromSelectionSet(document),
variables: variables,
returnPartialData: true,
optimistic: false,
}).result;
};
LocalState.prototype.resolveDocument = function (document, rootValue, context, variables, fragmentMatcher, onlyRunForcedResolvers) {
if (context === void 0) { context = {}; }
if (variables === void 0) { variables = {}; }
if (fragmentMatcher === void 0) { fragmentMatcher = function () { return true; }; }
if (onlyRunForcedResolvers === void 0) { onlyRunForcedResolvers = false; }
return __awaiter(this, void 0, void 0, function () {
var mainDefinition, fragments, fragmentMap, selectionsToResolve, definitionOperation, defaultOperationType, _a, cache, client, execContext, isClientFieldDescendant;
return __generator(this, function (_b) {
mainDefinition = getMainDefinition(document);
fragments = getFragmentDefinitions(document);
fragmentMap = createFragmentMap(fragments);
selectionsToResolve = this.collectSelectionsToResolve(mainDefinition, fragmentMap);
definitionOperation = mainDefinition.operation;
defaultOperationType = definitionOperation ?
definitionOperation.charAt(0).toUpperCase() +
definitionOperation.slice(1)
: "Query";
_a = this, cache = _a.cache, client = _a.client;
execContext = {
fragmentMap: fragmentMap,
context: __assign(__assign({}, context), { cache: cache, client: client }),
variables: variables,
fragmentMatcher: fragmentMatcher,
defaultOperationType: defaultOperationType,
exportedVariables: {},
selectionsToResolve: selectionsToResolve,
onlyRunForcedResolvers: onlyRunForcedResolvers,
};
isClientFieldDescendant = false;
return [2 /*return*/, this.resolveSelectionSet(mainDefinition.selectionSet, isClientFieldDescendant, rootValue, execContext).then(function (result) { return ({
result: result,
exportedVariables: execContext.exportedVariables,
}); })];
});
});
};
LocalState.prototype.resolveSelectionSet = function (selectionSet, isClientFieldDescendant, rootValue, execContext) {
return __awaiter(this, void 0, void 0, function () {
var fragmentMap, context, variables, resultsToMerge, execute;
var _this = this;
return __generator(this, function (_a) {
fragmentMap = execContext.fragmentMap, context = execContext.context, variables = execContext.variables;
resultsToMerge = [rootValue];
execute = function (selection) { return __awaiter(_this, void 0, void 0, function () {
var fragment, typeCondition;
return __generator(this, function (_a) {
if (!isClientFieldDescendant &&
!execContext.selectionsToResolve.has(selection)) {
// Skip selections without @client directives
// (still processing if one of the ancestors or one of the child fields has @client directive)
return [2 /*return*/];
}
if (!shouldInclude(selection, variables)) {
// Skip this entirely.
return [2 /*return*/];
}
if (isField(selection)) {
return [2 /*return*/, this.resolveField(selection, isClientFieldDescendant, rootValue, execContext).then(function (fieldResult) {
var _a;
if (typeof fieldResult !== "undefined") {
resultsToMerge.push((_a = {},
_a[resultKeyNameFromField(selection)] = fieldResult,
_a));
}
})];
}
if (isInlineFragment(selection)) {
fragment = selection;
}
else {
// This is a named fragment.
fragment = fragmentMap[selection.name.value];
invariant(fragment, 18, selection.name.value);
}
if (fragment && fragment.typeCondition) {
typeCondition = fragment.typeCondition.name.value;
if (execContext.fragmentMatcher(rootValue, typeCondition, context)) {
return [2 /*return*/, this.resolveSelectionSet(fragment.selectionSet, isClientFieldDescendant, rootValue, execContext).then(function (fragmentResult) {
resultsToMerge.push(fragmentResult);
})];
}
}
return [2 /*return*/];
});
}); };
return [2 /*return*/, Promise.all(selectionSet.selections.map(execute)).then(function () {
return mergeDeepArray(resultsToMerge);
})];
});
});
};
LocalState.prototype.resolveField = function (field, isClientFieldDescendant, rootValue, execContext) {
return __awaiter(this, void 0, void 0, function () {
var variables, fieldName, aliasedFieldName, aliasUsed, defaultResult, resultPromise, resolverType, resolverMap, resolve;
var _this = this;
return __generator(this, function (_a) {
if (!rootValue) {
return [2 /*return*/, null];
}
variables = execContext.variables;
fieldName = field.name.value;
aliasedFieldName = resultKeyNameFromField(field);
aliasUsed = fieldName !== aliasedFieldName;
defaultResult = rootValue[aliasedFieldName] || rootValue[fieldName];
resultPromise = Promise.resolve(defaultResult);
// Usually all local resolvers are run when passing through here, but
// if we've specifically identified that we only want to run forced
// resolvers (that is, resolvers for fields marked with
// `@client(always: true)`), then we'll skip running non-forced resolvers.
if (!execContext.onlyRunForcedResolvers ||
this.shouldForceResolvers(field)) {
resolverType = rootValue.__typename || execContext.defaultOperationType;
resolverMap = this.resolvers && this.resolvers[resolverType];
if (resolverMap) {
resolve = resolverMap[aliasUsed ? fieldName : aliasedFieldName];
if (resolve) {
resultPromise = Promise.resolve(
// In case the resolve function accesses reactive variables,
// set cacheSlot to the current cache instance.
cacheSlot.withValue(this.cache, resolve, [
rootValue,
argumentsObjectFromField(field, variables),
execContext.context,
{ field: field, fragmentMap: execContext.fragmentMap },
]));
}
}
}
return [2 /*return*/, resultPromise.then(function (result) {
var _a, _b;
if (result === void 0) { result = defaultResult; }
// If an @export directive is associated with the current field, store
// the `as` export variable name and current result for later use.
if (field.directives) {
field.directives.forEach(function (directive) {
if (directive.name.value === "export" && directive.arguments) {
directive.arguments.forEach(function (arg) {
if (arg.name.value === "as" && arg.value.kind === "StringValue") {
execContext.exportedVariables[arg.value.value] = result;
}
});
}
});
}
// Handle all scalar types here.
if (!field.selectionSet) {
return result;
}
// From here down, the field has a selection set, which means it's trying
// to query a GraphQLObjectType.
if (result == null) {
// Basically any field in a GraphQL response can be null, or missing
return result;
}
var isClientField = (_b = (_a = field.directives) === null || _a === void 0 ? void 0 : _a.some(function (d) { return d.name.value === "client"; })) !== null && _b !== void 0 ? _b : false;
if (Array.isArray(result)) {
return _this.resolveSubSelectedArray(field, isClientFieldDescendant || isClientField, result, execContext);
}
// Returned value is an object, and the query has a sub-selection. Recurse.
if (field.selectionSet) {
return _this.resolveSelectionSet(field.selectionSet, isClientFieldDescendant || isClientField, result, execContext);
}
})];
});
});
};
LocalState.prototype.resolveSubSelectedArray = function (field, isClientFieldDescendant, result, execContext) {
var _this = this;
return Promise.all(result.map(function (item) {
if (item === null) {
return null;
}
// This is a nested array, recurse.
if (Array.isArray(item)) {
return _this.resolveSubSelectedArray(field, isClientFieldDescendant, item, execContext);
}
// This is an object, run the selection set on it.
if (field.selectionSet) {
return _this.resolveSelectionSet(field.selectionSet, isClientFieldDescendant, item, execContext);
}
}));
};
// Collect selection nodes on paths from document root down to all @client directives.
// This function takes into account transitive fragment spreads.
// Complexity equals to a single `visit` over the full document.
LocalState.prototype.collectSelectionsToResolve = function (mainDefinition, fragmentMap) {
var isSingleASTNode = function (node) { return !Array.isArray(node); };
var selectionsToResolveCache = this.selectionsToResolveCache;
function collectByDefinition(definitionNode) {
if (!selectionsToResolveCache.has(definitionNode)) {
var matches_1 = new Set();
selectionsToResolveCache.set(definitionNode, matches_1);
visit(definitionNode, {
Directive: function (node, _, __, ___, ancestors) {
if (node.name.value === "client") {
ancestors.forEach(function (node) {
if (isSingleASTNode(node) && isSelectionNode(node)) {
matches_1.add(node);
}
});
}
},
FragmentSpread: function (spread, _, __, ___, ancestors) {
var fragment = fragmentMap[spread.name.value];
invariant(fragment, 19, spread.name.value);
var fragmentSelections = collectByDefinition(fragment);
if (fragmentSelections.size > 0) {
// Fragment for this spread contains @client directive (either directly or transitively)
// Collect selection nodes on paths from the root down to fields with the @client directive
ancestors.forEach(function (node) {
if (isSingleASTNode(node) && isSelectionNode(node)) {
matches_1.add(node);
}
});
matches_1.add(spread);
fragmentSelections.forEach(function (selection) {
matches_1.add(selection);
});
}
},
});
}
return selectionsToResolveCache.get(definitionNode);
}
return collectByDefinition(mainDefinition);
};
return LocalState;
}());
export { LocalState };
//# sourceMappingURL=LocalState.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/core/QueryInfo.js
import { __assign } from "tslib";
import { equal } from "@wry/equality";
import { DeepMerger } from "../utilities/index.js";
import { mergeIncrementalData } from "../utilities/index.js";
import { reobserveCacheFirst } from "./ObservableQuery.js";
import { isNonEmptyArray, graphQLResultHasError, canUseWeakMap, } from "../utilities/index.js";
import { NetworkStatus, isNetworkRequestInFlight } from "./networkStatus.js";
var destructiveMethodCounts = new (canUseWeakMap ? WeakMap : Map)();
function wrapDestructiveCacheMethod(cache, methodName) {
var original = cache[methodName];
if (typeof original === "function") {
// @ts-expect-error this is just too generic to be typed correctly
cache[methodName] = function () {
destructiveMethodCounts.set(cache,
// The %1e15 allows the count to wrap around to 0 safely every
// quadrillion evictions, so there's no risk of overflow. To be
// clear, this is more of a pedantic principle than something
// that matters in any conceivable practical scenario.
(destructiveMethodCounts.get(cache) + 1) % 1e15);
// @ts-expect-error this is just too generic to be typed correctly
return original.apply(this, arguments);
};
}
}
function cancelNotifyTimeout(info) {
if (info["notifyTimeout"]) {
clearTimeout(info["notifyTimeout"]);
info["notifyTimeout"] = void 0;
}
}
// A QueryInfo object represents a single query managed by the
// QueryManager, which tracks all QueryInfo objects by queryId in its
// this.queries Map. QueryInfo objects store the latest results and errors
// for the given query, and are responsible for reporting those results to
// the corresponding ObservableQuery, via the QueryInfo.notify method.
// Results are reported asynchronously whenever setDiff marks the
// QueryInfo object as dirty, though a call to the QueryManager's
// broadcastQueries method may trigger the notification before it happens
// automatically. This class used to be a simple interface type without
// any field privacy or meaningful methods, which is why it still has so
// many public fields. The effort to lock down and simplify the QueryInfo
// interface is ongoing, and further improvements are welcome.
var QueryInfo = /** @class */ (function () {
function QueryInfo(queryManager, queryId) {
if (queryId === void 0) { queryId = queryManager.generateQueryId(); }
this.queryId = queryId;
this.listeners = new Set();
this.document = null;
this.lastRequestId = 1;
this.stopped = false;
this.dirty = false;
this.observableQuery = null;
var cache = (this.cache = queryManager.cache);
// Track how often cache.evict is called, since we want eviction to
// override the feud-stopping logic in the markResult method, by
// causing shouldWrite to return true. Wrapping the cache.evict method
// is a bit of a hack, but it saves us from having to make eviction
// counting an official part of the ApolloCache API.
if (!destructiveMethodCounts.has(cache)) {
destructiveMethodCounts.set(cache, 0);
wrapDestructiveCacheMethod(cache, "evict");
wrapDestructiveCacheMethod(cache, "modify");
wrapDestructiveCacheMethod(cache, "reset");
}
}
QueryInfo.prototype.init = function (query) {
var networkStatus = query.networkStatus || NetworkStatus.loading;
if (this.variables &&
this.networkStatus !== NetworkStatus.loading &&
!equal(this.variables, query.variables)) {
networkStatus = NetworkStatus.setVariables;
}
if (!equal(query.variables, this.variables)) {
this.lastDiff = void 0;
}
Object.assign(this, {
document: query.document,
variables: query.variables,
networkError: null,
graphQLErrors: this.graphQLErrors || [],
networkStatus: networkStatus,
});
if (query.observableQuery) {
this.setObservableQuery(query.observableQuery);
}
if (query.lastRequestId) {
this.lastRequestId = query.lastRequestId;
}
return this;
};
QueryInfo.prototype.reset = function () {
cancelNotifyTimeout(this);
this.dirty = false;
};
QueryInfo.prototype.resetDiff = function () {
this.lastDiff = void 0;
};
QueryInfo.prototype.getDiff = function () {
var options = this.getDiffOptions();
if (this.lastDiff && equal(options, this.lastDiff.options)) {
return this.lastDiff.diff;
}
this.updateWatch(this.variables);
var oq = this.observableQuery;
if (oq && oq.options.fetchPolicy === "no-cache") {
return { complete: false };
}
var diff = this.cache.diff(options);
this.updateLastDiff(diff, options);
return diff;
};
QueryInfo.prototype.updateLastDiff = function (diff, options) {
this.lastDiff =
diff ?
{
diff: diff,
options: options || this.getDiffOptions(),
}
: void 0;
};
QueryInfo.prototype.getDiffOptions = function (variables) {
var _a;
if (variables === void 0) { variables = this.variables; }
return {
query: this.document,
variables: variables,
returnPartialData: true,
optimistic: true,
canonizeResults: (_a = this.observableQuery) === null || _a === void 0 ? void 0 : _a.options.canonizeResults,
};
};
QueryInfo.prototype.setDiff = function (diff) {
var _this = this;
var oldDiff = this.lastDiff && this.lastDiff.diff;
this.updateLastDiff(diff);
if (!this.dirty && !equal(oldDiff && oldDiff.result, diff && diff.result)) {
this.dirty = true;
if (!this.notifyTimeout) {
this.notifyTimeout = setTimeout(function () { return _this.notify(); }, 0);
}
}
};
QueryInfo.prototype.setObservableQuery = function (oq) {
var _this = this;
if (oq === this.observableQuery)
return;
if (this.oqListener) {
this.listeners.delete(this.oqListener);
}
this.observableQuery = oq;
if (oq) {
oq["queryInfo"] = this;
this.listeners.add((this.oqListener = function () {
var diff = _this.getDiff();
if (diff.fromOptimisticTransaction) {
// If this diff came from an optimistic transaction, deliver the
// current cache data to the ObservableQuery, but don't perform a
// reobservation, since oq.reobserveCacheFirst might make a network
// request, and we never want to trigger network requests in the
// middle of optimistic updates.
oq["observe"]();
}
else {
// Otherwise, make the ObservableQuery "reobserve" the latest data
// using a temporary fetch policy of "cache-first", so complete cache
// results have a chance to be delivered without triggering additional
// network requests, even when options.fetchPolicy is "network-only"
// or "cache-and-network". All other fetch policies are preserved by
// this method, and are handled by calling oq.reobserve(). If this
// reobservation is spurious, isDifferentFromLastResult still has a
// chance to catch it before delivery to ObservableQuery subscribers.
reobserveCacheFirst(oq);
}
}));
}
else {
delete this.oqListener;
}
};
QueryInfo.prototype.notify = function () {
var _this = this;
cancelNotifyTimeout(this);
if (this.shouldNotify()) {
this.listeners.forEach(function (listener) { return listener(_this); });
}
this.dirty = false;
};
QueryInfo.prototype.shouldNotify = function () {
if (!this.dirty || !this.listeners.size) {
return false;
}
if (isNetworkRequestInFlight(this.networkStatus) && this.observableQuery) {
var fetchPolicy = this.observableQuery.options.fetchPolicy;
if (fetchPolicy !== "cache-only" && fetchPolicy !== "cache-and-network") {
return false;
}
}
return true;
};
QueryInfo.prototype.stop = function () {
if (!this.stopped) {
this.stopped = true;
// Cancel the pending notify timeout
this.reset();
this.cancel();
// Revert back to the no-op version of cancel inherited from
// QueryInfo.prototype.
this.cancel = QueryInfo.prototype.cancel;
var oq = this.observableQuery;
if (oq)
oq.stopPolling();
}
};
// This method is a no-op by default, until/unless overridden by the
// updateWatch method.
QueryInfo.prototype.cancel = function () { };
QueryInfo.prototype.updateWatch = function (variables) {
var _this = this;
if (variables === void 0) { variables = this.variables; }
var oq = this.observableQuery;
if (oq && oq.options.fetchPolicy === "no-cache") {
return;
}
var watchOptions = __assign(__assign({}, this.getDiffOptions(variables)), { watcher: this, callback: function (diff) { return _this.setDiff(diff); } });
if (!this.lastWatch || !equal(watchOptions, this.lastWatch)) {
this.cancel();
this.cancel = this.cache.watch((this.lastWatch = watchOptions));
}
};
QueryInfo.prototype.resetLastWrite = function () {
this.lastWrite = void 0;
};
QueryInfo.prototype.shouldWrite = function (result, variables) {
var lastWrite = this.lastWrite;
return !(lastWrite &&
// If cache.evict has been called since the last time we wrote this
// data into the cache, there's a chance writing this result into
// the cache will repair what was evicted.
lastWrite.dmCount === destructiveMethodCounts.get(this.cache) &&
equal(variables, lastWrite.variables) &&
equal(result.data, lastWrite.result.data));
};
QueryInfo.prototype.markResult = function (result, document, options, cacheWriteBehavior) {
var _this = this;
var merger = new DeepMerger();
var graphQLErrors = isNonEmptyArray(result.errors) ? result.errors.slice(0) : [];
// Cancel the pending notify timeout (if it exists) to prevent extraneous network
// requests. To allow future notify timeouts, diff and dirty are reset as well.
this.reset();
if ("incremental" in result && isNonEmptyArray(result.incremental)) {
var mergedData = mergeIncrementalData(this.getDiff().result, result);
result.data = mergedData;
// Detect the first chunk of a deferred query and merge it with existing
// cache data. This ensures a `cache-first` fetch policy that returns
// partial cache data or a `cache-and-network` fetch policy that already
// has full data in the cache does not complain when trying to merge the
// initial deferred server data with existing cache data.
}
else if ("hasNext" in result && result.hasNext) {
var diff = this.getDiff();
result.data = merger.merge(diff.result, result.data);
}
this.graphQLErrors = graphQLErrors;
if (options.fetchPolicy === "no-cache") {
this.updateLastDiff({ result: result.data, complete: true }, this.getDiffOptions(options.variables));
}
else if (cacheWriteBehavior !== 0 /* CacheWriteBehavior.FORBID */) {
if (shouldWriteResult(result, options.errorPolicy)) {
// Using a transaction here so we have a chance to read the result
// back from the cache before the watch callback fires as a result
// of writeQuery, so we can store the new diff quietly and ignore
// it when we receive it redundantly from the watch callback.
this.cache.performTransaction(function (cache) {
if (_this.shouldWrite(result, options.variables)) {
cache.writeQuery({
query: document,
data: result.data,
variables: options.variables,
overwrite: cacheWriteBehavior === 1 /* CacheWriteBehavior.OVERWRITE */,
});
_this.lastWrite = {
result: result,
variables: options.variables,
dmCount: destructiveMethodCounts.get(_this.cache),
};
}
else {
// If result is the same as the last result we received from
// the network (and the variables match too), avoid writing
// result into the cache again. The wisdom of skipping this
// cache write is far from obvious, since any cache write
// could be the one that puts the cache back into a desired
// state, fixing corruption or missing data. However, if we
// always write every network result into the cache, we enable
// feuds between queries competing to update the same data in
// incompatible ways, which can lead to an endless cycle of
// cache broadcasts and useless network requests. As with any
// feud, eventually one side must step back from the brink,
// letting the other side(s) have the last word(s). There may
// be other points where we could break this cycle, such as
// silencing the broadcast for cache.writeQuery (not a good
// idea, since it just delays the feud a bit) or somehow
// avoiding the network request that just happened (also bad,
// because the server could return useful new data). All
// options considered, skipping this cache write seems to be
// the least damaging place to break the cycle, because it
// reflects the intuition that we recently wrote this exact
// result into the cache, so the cache *should* already/still
// contain this data. If some other query has clobbered that
// data in the meantime, that's too bad, but there will be no
// winners if every query blindly reverts to its own version
// of the data. This approach also gives the network a chance
// to return new data, which will be written into the cache as
// usual, notifying only those queries that are directly
// affected by the cache updates, as usual. In the future, an
// even more sophisticated cache could perhaps prevent or
// mitigate the clobbering somehow, but that would make this
// particular cache write even less important, and thus
// skipping it would be even safer than it is today.
if (_this.lastDiff && _this.lastDiff.diff.complete) {
// Reuse data from the last good (complete) diff that we
// received, when possible.
result.data = _this.lastDiff.diff.result;
return;
}
// If the previous this.diff was incomplete, fall through to
// re-reading the latest data with cache.diff, below.
}
var diffOptions = _this.getDiffOptions(options.variables);
var diff = cache.diff(diffOptions);
// In case the QueryManager stops this QueryInfo before its
// results are delivered, it's important to avoid restarting the
// cache watch when markResult is called. We also avoid updating
// the watch if we are writing a result that doesn't match the current
// variables to avoid race conditions from broadcasting the wrong
// result.
if (!_this.stopped && equal(_this.variables, options.variables)) {
// Any time we're about to update this.diff, we need to make
// sure we've started watching the cache.
_this.updateWatch(options.variables);
}
// If we're allowed to write to the cache, and we can read a
// complete result from the cache, update result.data to be the
// result from the cache, rather than the raw network result.
// Set without setDiff to avoid triggering a notify call, since
// we have other ways of notifying for this result.
_this.updateLastDiff(diff, diffOptions);
if (diff.complete) {
result.data = diff.result;
}
});
}
else {
this.lastWrite = void 0;
}
}
};
QueryInfo.prototype.markReady = function () {
this.networkError = null;
return (this.networkStatus = NetworkStatus.ready);
};
QueryInfo.prototype.markError = function (error) {
this.networkStatus = NetworkStatus.error;
this.lastWrite = void 0;
this.reset();
if (error.graphQLErrors) {
this.graphQLErrors = error.graphQLErrors;
}
if (error.networkError) {
this.networkError = error.networkError;
}
return error;
};
return QueryInfo;
}());
export { QueryInfo };
export function shouldWriteResult(result, errorPolicy) {
if (errorPolicy === void 0) { errorPolicy = "none"; }
var ignoreErrors = errorPolicy === "ignore" || errorPolicy === "all";
var writeWithErrors = !graphQLResultHasError(result);
if (!writeWithErrors && ignoreErrors && result.data) {
writeWithErrors = true;
}
return writeWithErrors;
}
//# sourceMappingURL=QueryInfo.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/core/QueryManager.js
import { __assign, __awaiter, __generator } from "tslib";
import { invariant, newInvariantError } from "../utilities/globals/index.js";
import { equal } from "@wry/equality";
import { execute } from "../link/core/index.js";
import { hasDirectives, isExecutionPatchIncrementalResult, isExecutionPatchResult, removeDirectivesFromDocument, } from "../utilities/index.js";
import { canonicalStringify } from "../cache/index.js";
import { getDefaultValues, getOperationDefinition, getOperationName, hasClientExports, graphQLResultHasError, getGraphQLErrorsFromResult, Observable, asyncMap, isNonEmptyArray, Concast, makeUniqueId, isDocumentNode, isNonNullObject, DocumentTransform, } from "../utilities/index.js";
import { mergeIncrementalData } from "../utilities/common/incrementalResult.js";
import { ApolloError, isApolloError, graphQLResultHasProtocolErrors, } from "../errors/index.js";
import { ObservableQuery, logMissingFieldErrors } from "./ObservableQuery.js";
import { NetworkStatus, isNetworkRequestInFlight } from "./networkStatus.js";
import { LocalState } from "./LocalState.js";
import { QueryInfo, shouldWriteResult, } from "./QueryInfo.js";
import { PROTOCOL_ERRORS_SYMBOL } from "../errors/index.js";
import { print } from "../utilities/index.js";
var hasOwnProperty = Object.prototype.hasOwnProperty;
var IGNORE = Object.create(null);
import { Trie } from "@wry/trie";
import { AutoCleanedWeakCache, cacheSizes } from "../utilities/index.js";
var QueryManager = /** @class */ (function () {
function QueryManager(_a) {
var cache = _a.cache, link = _a.link, defaultOptions = _a.defaultOptions, documentTransform = _a.documentTransform, _b = _a.queryDeduplication, queryDeduplication = _b === void 0 ? false : _b, onBroadcast = _a.onBroadcast, _c = _a.ssrMode, ssrMode = _c === void 0 ? false : _c, _d = _a.clientAwareness, clientAwareness = _d === void 0 ? {} : _d, localState = _a.localState, _e = _a.assumeImmutableResults, assumeImmutableResults = _e === void 0 ? !!cache.assumeImmutableResults : _e, defaultContext = _a.defaultContext;
var _this = this;
this.clientAwareness = {};
// All the queries that the QueryManager is currently managing (not
// including mutations and subscriptions).
this.queries = new Map();
// Maps from queryId strings to Promise rejection functions for
// currently active queries and fetches.
// Use protected instead of private field so
// @apollo/experimental-nextjs-app-support can access type info.
this.fetchCancelFns = new Map();
this.transformCache = new AutoCleanedWeakCache(cacheSizes["queryManager.getDocumentInfo"] ||
2000 /* defaultCacheSizes["queryManager.getDocumentInfo"] */);
this.queryIdCounter = 1;
this.requestIdCounter = 1;
this.mutationIdCounter = 1;
// Use protected instead of private field so
// @apollo/experimental-nextjs-app-support can access type info.
this.inFlightLinkObservables = new Trie(false);
var defaultDocumentTransform = new DocumentTransform(function (document) { return _this.cache.transformDocument(document); },
// Allow the apollo cache to manage its own transform caches
{ cache: false });
this.cache = cache;
this.link = link;
this.defaultOptions = defaultOptions || Object.create(null);
this.queryDeduplication = queryDeduplication;
this.clientAwareness = clientAwareness;
this.localState = localState || new LocalState({ cache: cache });
this.ssrMode = ssrMode;
this.assumeImmutableResults = assumeImmutableResults;
this.documentTransform =
documentTransform ?
defaultDocumentTransform
.concat(documentTransform)
// The custom document transform may add new fragment spreads or new
// field selections, so we want to give the cache a chance to run
// again. For example, the InMemoryCache adds __typename to field
// selections and fragments from the fragment registry.
.concat(defaultDocumentTransform)
: defaultDocumentTransform;
this.defaultContext = defaultContext || Object.create(null);
if ((this.onBroadcast = onBroadcast)) {
this.mutationStore = Object.create(null);
}
}
/**
* Call this method to terminate any active query processes, making it safe
* to dispose of this QueryManager instance.
*/
QueryManager.prototype.stop = function () {
var _this = this;
this.queries.forEach(function (_info, queryId) {
_this.stopQueryNoBroadcast(queryId);
});
this.cancelPendingFetches(newInvariantError(25));
};
QueryManager.prototype.cancelPendingFetches = function (error) {
this.fetchCancelFns.forEach(function (cancel) { return cancel(error); });
this.fetchCancelFns.clear();
};
QueryManager.prototype.mutate = function (_a) {
var _b, _c;
var mutation = _a.mutation, variables = _a.variables, optimisticResponse = _a.optimisticResponse, updateQueries = _a.updateQueries, _d = _a.refetchQueries, refetchQueries = _d === void 0 ? [] : _d, _e = _a.awaitRefetchQueries, awaitRefetchQueries = _e === void 0 ? false : _e, updateWithProxyFn = _a.update, onQueryUpdated = _a.onQueryUpdated, _f = _a.fetchPolicy, fetchPolicy = _f === void 0 ? ((_b = this.defaultOptions.mutate) === null || _b === void 0 ? void 0 : _b.fetchPolicy) || "network-only" : _f, _g = _a.errorPolicy, errorPolicy = _g === void 0 ? ((_c = this.defaultOptions.mutate) === null || _c === void 0 ? void 0 : _c.errorPolicy) || "none" : _g, keepRootFields = _a.keepRootFields, context = _a.context;
return __awaiter(this, void 0, void 0, function () {
var mutationId, hasClientExports, mutationStoreValue, isOptimistic, self;
return __generator(this, function (_h) {
switch (_h.label) {
case 0:
invariant(mutation, 26);
invariant(fetchPolicy === "network-only" || fetchPolicy === "no-cache", 27);
mutationId = this.generateMutationId();
mutation = this.cache.transformForLink(this.transform(mutation));
hasClientExports = this.getDocumentInfo(mutation).hasClientExports;
variables = this.getVariables(mutation, variables);
if (!hasClientExports) return [3 /*break*/, 2];
return [4 /*yield*/, this.localState.addExportedVariables(mutation, variables, context)];
case 1:
variables = (_h.sent());
_h.label = 2;
case 2:
mutationStoreValue = this.mutationStore &&
(this.mutationStore[mutationId] = {
mutation: mutation,
variables: variables,
loading: true,
error: null,
});
isOptimistic = optimisticResponse &&
this.markMutationOptimistic(optimisticResponse, {
mutationId: mutationId,
document: mutation,
variables: variables,
fetchPolicy: fetchPolicy,
errorPolicy: errorPolicy,
context: context,
updateQueries: updateQueries,
update: updateWithProxyFn,
keepRootFields: keepRootFields,
});
this.broadcastQueries();
self = this;
return [2 /*return*/, new Promise(function (resolve, reject) {
return asyncMap(self.getObservableFromLink(mutation, __assign(__assign({}, context), { optimisticResponse: isOptimistic ? optimisticResponse : void 0 }), variables, false), function (result) {
if (graphQLResultHasError(result) && errorPolicy === "none") {
throw new ApolloError({
graphQLErrors: getGraphQLErrorsFromResult(result),
});
}
if (mutationStoreValue) {
mutationStoreValue.loading = false;
mutationStoreValue.error = null;
}
var storeResult = __assign({}, result);
if (typeof refetchQueries === "function") {
refetchQueries = refetchQueries(storeResult);
}
if (errorPolicy === "ignore" && graphQLResultHasError(storeResult)) {
delete storeResult.errors;
}
return self.markMutationResult({
mutationId: mutationId,
result: storeResult,
document: mutation,
variables: variables,
fetchPolicy: fetchPolicy,
errorPolicy: errorPolicy,
context: context,
update: updateWithProxyFn,
updateQueries: updateQueries,
awaitRefetchQueries: awaitRefetchQueries,
refetchQueries: refetchQueries,
removeOptimistic: isOptimistic ? mutationId : void 0,
onQueryUpdated: onQueryUpdated,
keepRootFields: keepRootFields,
});
}).subscribe({
next: function (storeResult) {
self.broadcastQueries();
// Since mutations might receive multiple payloads from the
// ApolloLink chain (e.g. when used with @defer),
// we resolve with a SingleExecutionResult or after the final
// ExecutionPatchResult has arrived and we have assembled the
// multipart response into a single result.
if (!("hasNext" in storeResult) || storeResult.hasNext === false) {
resolve(storeResult);
}
},
error: function (err) {
if (mutationStoreValue) {
mutationStoreValue.loading = false;
mutationStoreValue.error = err;
}
if (isOptimistic) {
self.cache.removeOptimistic(mutationId);
}
self.broadcastQueries();
reject(err instanceof ApolloError ? err : (new ApolloError({
networkError: err,
})));
},
});
})];
}
});
});
};
QueryManager.prototype.markMutationResult = function (mutation, cache) {
var _this = this;
if (cache === void 0) { cache = this.cache; }
var result = mutation.result;
var cacheWrites = [];
var skipCache = mutation.fetchPolicy === "no-cache";
if (!skipCache && shouldWriteResult(result, mutation.errorPolicy)) {
if (!isExecutionPatchIncrementalResult(result)) {
cacheWrites.push({
result: result.data,
dataId: "ROOT_MUTATION",
query: mutation.document,
variables: mutation.variables,
});
}
if (isExecutionPatchIncrementalResult(result) &&
isNonEmptyArray(result.incremental)) {
var diff = cache.diff({
id: "ROOT_MUTATION",
// The cache complains if passed a mutation where it expects a
// query, so we transform mutations and subscriptions to queries
// (only once, thanks to this.transformCache).
query: this.getDocumentInfo(mutation.document).asQuery,
variables: mutation.variables,
optimistic: false,
returnPartialData: true,
});
var mergedData = void 0;
if (diff.result) {
mergedData = mergeIncrementalData(diff.result, result);
}
if (typeof mergedData !== "undefined") {
// cast the ExecutionPatchResult to FetchResult here since
// ExecutionPatchResult never has `data` when returned from the server
result.data = mergedData;
cacheWrites.push({
result: mergedData,
dataId: "ROOT_MUTATION",
query: mutation.document,
variables: mutation.variables,
});
}
}
var updateQueries_1 = mutation.updateQueries;
if (updateQueries_1) {
this.queries.forEach(function (_a, queryId) {
var observableQuery = _a.observableQuery;
var queryName = observableQuery && observableQuery.queryName;
if (!queryName || !hasOwnProperty.call(updateQueries_1, queryName)) {
return;
}
var updater = updateQueries_1[queryName];
var _b = _this.queries.get(queryId), document = _b.document, variables = _b.variables;
// Read the current query result from the store.
var _c = cache.diff({
query: document,
variables: variables,
returnPartialData: true,
optimistic: false,
}), currentQueryResult = _c.result, complete = _c.complete;
if (complete && currentQueryResult) {
// Run our reducer using the current query result and the mutation result.
var nextQueryResult = updater(currentQueryResult, {
mutationResult: result,
queryName: (document && getOperationName(document)) || void 0,
queryVariables: variables,
});
// Write the modified result back into the store if we got a new result.
if (nextQueryResult) {
cacheWrites.push({
result: nextQueryResult,
dataId: "ROOT_QUERY",
query: document,
variables: variables,
});
}
}
});
}
}
if (cacheWrites.length > 0 ||
(mutation.refetchQueries || "").length > 0 ||
mutation.update ||
mutation.onQueryUpdated ||
mutation.removeOptimistic) {
var results_1 = [];
this.refetchQueries({
updateCache: function (cache) {
if (!skipCache) {
cacheWrites.forEach(function (write) { return cache.write(write); });
}
// If the mutation has some writes associated with it then we need to
// apply those writes to the store by running this reducer again with
// a write action.
var update = mutation.update;
// Determine whether result is a SingleExecutionResult,
// or the final ExecutionPatchResult.
var isFinalResult = !isExecutionPatchResult(result) ||
(isExecutionPatchIncrementalResult(result) && !result.hasNext);
if (update) {
if (!skipCache) {
// Re-read the ROOT_MUTATION data we just wrote into the cache
// (the first cache.write call in the cacheWrites.forEach loop
// above), so field read functions have a chance to run for
// fields within mutation result objects.
var diff = cache.diff({
id: "ROOT_MUTATION",
// The cache complains if passed a mutation where it expects a
// query, so we transform mutations and subscriptions to queries
// (only once, thanks to this.transformCache).
query: _this.getDocumentInfo(mutation.document).asQuery,
variables: mutation.variables,
optimistic: false,
returnPartialData: true,
});
if (diff.complete) {
result = __assign(__assign({}, result), { data: diff.result });
if ("incremental" in result) {
delete result.incremental;
}
if ("hasNext" in result) {
delete result.hasNext;
}
}
}
// If we've received the whole response,
// either a SingleExecutionResult or the final ExecutionPatchResult,
// call the update function.
if (isFinalResult) {
update(cache, result, {
context: mutation.context,
variables: mutation.variables,
});
}
}
// TODO Do this with cache.evict({ id: 'ROOT_MUTATION' }) but make it
// shallow to allow rolling back optimistic evictions.
if (!skipCache && !mutation.keepRootFields && isFinalResult) {
cache.modify({
id: "ROOT_MUTATION",
fields: function (value, _a) {
var fieldName = _a.fieldName, DELETE = _a.DELETE;
return fieldName === "__typename" ? value : DELETE;
},
});
}
},
include: mutation.refetchQueries,
// Write the final mutation.result to the root layer of the cache.
optimistic: false,
// Remove the corresponding optimistic layer at the same time as we
// write the final non-optimistic result.
removeOptimistic: mutation.removeOptimistic,
// Let the caller of client.mutate optionally determine the refetching
// behavior for watched queries after the mutation.update function runs.
// If no onQueryUpdated function was provided for this mutation, pass
// null instead of undefined to disable the default refetching behavior.
onQueryUpdated: mutation.onQueryUpdated || null,
}).forEach(function (result) { return results_1.push(result); });
if (mutation.awaitRefetchQueries || mutation.onQueryUpdated) {
// Returning a promise here makes the mutation await that promise, so we
// include results in that promise's work if awaitRefetchQueries or an
// onQueryUpdated function was specified.
return Promise.all(results_1).then(function () { return result; });
}
}
return Promise.resolve(result);
};
QueryManager.prototype.markMutationOptimistic = function (optimisticResponse, mutation) {
var _this = this;
var data = typeof optimisticResponse === "function" ?
optimisticResponse(mutation.variables, { IGNORE: IGNORE })
: optimisticResponse;
if (data === IGNORE) {
return false;
}
this.cache.recordOptimisticTransaction(function (cache) {
try {
_this.markMutationResult(__assign(__assign({}, mutation), { result: { data: data } }), cache);
}
catch (error) {
globalThis.__DEV__ !== false && invariant.error(error);
}
}, mutation.mutationId);
return true;
};
QueryManager.prototype.fetchQuery = function (queryId, options, networkStatus) {
return this.fetchConcastWithInfo(queryId, options, networkStatus).concast
.promise;
};
QueryManager.prototype.getQueryStore = function () {
var store = Object.create(null);
this.queries.forEach(function (info, queryId) {
store[queryId] = {
variables: info.variables,
networkStatus: info.networkStatus,
networkError: info.networkError,
graphQLErrors: info.graphQLErrors,
};
});
return store;
};
QueryManager.prototype.resetErrors = function (queryId) {
var queryInfo = this.queries.get(queryId);
if (queryInfo) {
queryInfo.networkError = undefined;
queryInfo.graphQLErrors = [];
}
};
QueryManager.prototype.transform = function (document) {
return this.documentTransform.transformDocument(document);
};
QueryManager.prototype.getDocumentInfo = function (document) {
var transformCache = this.transformCache;
if (!transformCache.has(document)) {
var cacheEntry = {
// TODO These three calls (hasClientExports, shouldForceResolvers, and
// usesNonreactiveDirective) are performing independent full traversals
// of the transformed document. We should consider merging these
// traversals into a single pass in the future, though the work is
// cached after the first time.
hasClientExports: hasClientExports(document),
hasForcedResolvers: this.localState.shouldForceResolvers(document),
hasNonreactiveDirective: hasDirectives(["nonreactive"], document),
clientQuery: this.localState.clientQuery(document),
serverQuery: removeDirectivesFromDocument([
{ name: "client", remove: true },
{ name: "connection" },
{ name: "nonreactive" },
], document),
defaultVars: getDefaultValues(getOperationDefinition(document)),
// Transform any mutation or subscription operations to query operations
// so we can read/write them from/to the cache.
asQuery: __assign(__assign({}, document), { definitions: document.definitions.map(function (def) {
if (def.kind === "OperationDefinition" &&
def.operation !== "query") {
return __assign(__assign({}, def), { operation: "query" });
}
return def;
}) }),
};
transformCache.set(document, cacheEntry);
}
return transformCache.get(document);
};
QueryManager.prototype.getVariables = function (document, variables) {
return __assign(__assign({}, this.getDocumentInfo(document).defaultVars), variables);
};
QueryManager.prototype.watchQuery = function (options) {
var query = this.transform(options.query);
// assign variable default values if supplied
// NOTE: We don't modify options.query here with the transformed query to
// ensure observable.options.query is set to the raw untransformed query.
options = __assign(__assign({}, options), { variables: this.getVariables(query, options.variables) });
if (typeof options.notifyOnNetworkStatusChange === "undefined") {
options.notifyOnNetworkStatusChange = false;
}
var queryInfo = new QueryInfo(this);
var observable = new ObservableQuery({
queryManager: this,
queryInfo: queryInfo,
options: options,
});
observable["lastQuery"] = query;
this.queries.set(observable.queryId, queryInfo);
// We give queryInfo the transformed query to ensure the first cache diff
// uses the transformed query instead of the raw query
queryInfo.init({
document: query,
observableQuery: observable,
variables: observable.variables,
});
return observable;
};
QueryManager.prototype.query = function (options, queryId) {
var _this = this;
if (queryId === void 0) { queryId = this.generateQueryId(); }
invariant(options.query, 28);
invariant(options.query.kind === "Document", 29);
invariant(!options.returnPartialData, 30);
invariant(!options.pollInterval, 31);
return this.fetchQuery(queryId, __assign(__assign({}, options), { query: this.transform(options.query) })).finally(function () { return _this.stopQuery(queryId); });
};
QueryManager.prototype.generateQueryId = function () {
return String(this.queryIdCounter++);
};
QueryManager.prototype.generateRequestId = function () {
return this.requestIdCounter++;
};
QueryManager.prototype.generateMutationId = function () {
return String(this.mutationIdCounter++);
};
QueryManager.prototype.stopQueryInStore = function (queryId) {
this.stopQueryInStoreNoBroadcast(queryId);
this.broadcastQueries();
};
QueryManager.prototype.stopQueryInStoreNoBroadcast = function (queryId) {
var queryInfo = this.queries.get(queryId);
if (queryInfo)
queryInfo.stop();
};
QueryManager.prototype.clearStore = function (options) {
if (options === void 0) { options = {
discardWatches: true,
}; }
// Before we have sent the reset action to the store, we can no longer
// rely on the results returned by in-flight requests since these may
// depend on values that previously existed in the data portion of the
// store. So, we cancel the promises and observers that we have issued
// so far and not yet resolved (in the case of queries).
this.cancelPendingFetches(newInvariantError(32));
this.queries.forEach(function (queryInfo) {
if (queryInfo.observableQuery) {
// Set loading to true so listeners don't trigger unless they want
// results with partial data.
queryInfo.networkStatus = NetworkStatus.loading;
}
else {
queryInfo.stop();
}
});
if (this.mutationStore) {
this.mutationStore = Object.create(null);
}
// begin removing data from the store
return this.cache.reset(options);
};
QueryManager.prototype.getObservableQueries = function (include) {
var _this = this;
if (include === void 0) { include = "active"; }
var queries = new Map();
var queryNamesAndDocs = new Map();
var legacyQueryOptions = new Set();
if (Array.isArray(include)) {
include.forEach(function (desc) {
if (typeof desc === "string") {
queryNamesAndDocs.set(desc, false);
}
else if (isDocumentNode(desc)) {
queryNamesAndDocs.set(_this.transform(desc), false);
}
else if (isNonNullObject(desc) && desc.query) {
legacyQueryOptions.add(desc);
}
});
}
this.queries.forEach(function (_a, queryId) {
var oq = _a.observableQuery, document = _a.document;
if (oq) {
if (include === "all") {
queries.set(queryId, oq);
return;
}
var queryName = oq.queryName, fetchPolicy = oq.options.fetchPolicy;
if (fetchPolicy === "standby" ||
(include === "active" && !oq.hasObservers())) {
return;
}
if (include === "active" ||
(queryName && queryNamesAndDocs.has(queryName)) ||
(document && queryNamesAndDocs.has(document))) {
queries.set(queryId, oq);
if (queryName)
queryNamesAndDocs.set(queryName, true);
if (document)
queryNamesAndDocs.set(document, true);
}
}
});
if (legacyQueryOptions.size) {
legacyQueryOptions.forEach(function (options) {
// We will be issuing a fresh network request for this query, so we
// pre-allocate a new query ID here, using a special prefix to enable
// cleaning up these temporary queries later, after fetching.
var queryId = makeUniqueId("legacyOneTimeQuery");
var queryInfo = _this.getQuery(queryId).init({
document: options.query,
variables: options.variables,
});
var oq = new ObservableQuery({
queryManager: _this,
queryInfo: queryInfo,
options: __assign(__assign({}, options), { fetchPolicy: "network-only" }),
});
invariant(oq.queryId === queryId);
queryInfo.setObservableQuery(oq);
queries.set(queryId, oq);
});
}
if (globalThis.__DEV__ !== false && queryNamesAndDocs.size) {
queryNamesAndDocs.forEach(function (included, nameOrDoc) {
if (!included) {
globalThis.__DEV__ !== false && invariant.warn(typeof nameOrDoc === "string" ? 33 : 34, nameOrDoc);
}
});
}
return queries;
};
QueryManager.prototype.reFetchObservableQueries = function (includeStandby) {
var _this = this;
if (includeStandby === void 0) { includeStandby = false; }
var observableQueryPromises = [];
this.getObservableQueries(includeStandby ? "all" : "active").forEach(function (observableQuery, queryId) {
var fetchPolicy = observableQuery.options.fetchPolicy;
observableQuery.resetLastResults();
if (includeStandby ||
(fetchPolicy !== "standby" && fetchPolicy !== "cache-only")) {
observableQueryPromises.push(observableQuery.refetch());
}
_this.getQuery(queryId).setDiff(null);
});
this.broadcastQueries();
return Promise.all(observableQueryPromises);
};
QueryManager.prototype.setObservableQuery = function (observableQuery) {
this.getQuery(observableQuery.queryId).setObservableQuery(observableQuery);
};
QueryManager.prototype.startGraphQLSubscription = function (_a) {
var _this = this;
var query = _a.query, fetchPolicy = _a.fetchPolicy, _b = _a.errorPolicy, errorPolicy = _b === void 0 ? "none" : _b, variables = _a.variables, _c = _a.context, context = _c === void 0 ? {} : _c;
query = this.transform(query);
variables = this.getVariables(query, variables);
var makeObservable = function (variables) {
return _this.getObservableFromLink(query, context, variables).map(function (result) {
if (fetchPolicy !== "no-cache") {
// the subscription interface should handle not sending us results we no longer subscribe to.
// XXX I don't think we ever send in an object with errors, but we might in the future...
if (shouldWriteResult(result, errorPolicy)) {
_this.cache.write({
query: query,
result: result.data,
dataId: "ROOT_SUBSCRIPTION",
variables: variables,
});
}
_this.broadcastQueries();
}
var hasErrors = graphQLResultHasError(result);
var hasProtocolErrors = graphQLResultHasProtocolErrors(result);
if (hasErrors || hasProtocolErrors) {
var errors = {};
if (hasErrors) {
errors.graphQLErrors = result.errors;
}
if (hasProtocolErrors) {
errors.protocolErrors = result.extensions[PROTOCOL_ERRORS_SYMBOL];
}
// `errorPolicy` is a mechanism for handling GraphQL errors, according
// to our documentation, so we throw protocol errors regardless of the
// set error policy.
if (errorPolicy === "none" || hasProtocolErrors) {
throw new ApolloError(errors);
}
}
if (errorPolicy === "ignore") {
delete result.errors;
}
return result;
});
};
if (this.getDocumentInfo(query).hasClientExports) {
var observablePromise_1 = this.localState
.addExportedVariables(query, variables, context)
.then(makeObservable);
return new Observable(function (observer) {
var sub = null;
observablePromise_1.then(function (observable) { return (sub = observable.subscribe(observer)); }, observer.error);
return function () { return sub && sub.unsubscribe(); };
});
}
return makeObservable(variables);
};
QueryManager.prototype.stopQuery = function (queryId) {
this.stopQueryNoBroadcast(queryId);
this.broadcastQueries();
};
QueryManager.prototype.stopQueryNoBroadcast = function (queryId) {
this.stopQueryInStoreNoBroadcast(queryId);
this.removeQuery(queryId);
};
QueryManager.prototype.removeQuery = function (queryId) {
// teardown all links
// Both `QueryManager.fetchRequest` and `QueryManager.query` create separate promises
// that each add their reject functions to fetchCancelFns.
// A query created with `QueryManager.query()` could trigger a `QueryManager.fetchRequest`.
// The same queryId could have two rejection fns for two promises
this.fetchCancelFns.delete(queryId);
if (this.queries.has(queryId)) {
this.getQuery(queryId).stop();
this.queries.delete(queryId);
}
};
QueryManager.prototype.broadcastQueries = function () {
if (this.onBroadcast)
this.onBroadcast();
this.queries.forEach(function (info) { return info.notify(); });
};
QueryManager.prototype.getLocalState = function () {
return this.localState;
};
QueryManager.prototype.getObservableFromLink = function (query, context, variables,
// Prefer context.queryDeduplication if specified.
deduplication) {
var _this = this;
var _a;
if (deduplication === void 0) { deduplication = (_a = context === null || context === void 0 ? void 0 : context.queryDeduplication) !== null && _a !== void 0 ? _a : this.queryDeduplication; }
var observable;
var _b = this.getDocumentInfo(query), serverQuery = _b.serverQuery, clientQuery = _b.clientQuery;
if (serverQuery) {
var _c = this, inFlightLinkObservables_1 = _c.inFlightLinkObservables, link = _c.link;
var operation = {
query: serverQuery,
variables: variables,
operationName: getOperationName(serverQuery) || void 0,
context: this.prepareContext(__assign(__assign({}, context), { forceFetch: !deduplication })),
};
context = operation.context;
if (deduplication) {
var printedServerQuery_1 = print(serverQuery);
var varJson_1 = canonicalStringify(variables);
var entry = inFlightLinkObservables_1.lookup(printedServerQuery_1, varJson_1);
observable = entry.observable;
if (!observable) {
var concast = new Concast([
execute(link, operation),
]);
observable = entry.observable = concast;
concast.beforeNext(function () {
inFlightLinkObservables_1.remove(printedServerQuery_1, varJson_1);
});
}
}
else {
observable = new Concast([
execute(link, operation),
]);
}
}
else {
observable = new Concast([Observable.of({ data: {} })]);
context = this.prepareContext(context);
}
if (clientQuery) {
observable = asyncMap(observable, function (result) {
return _this.localState.runResolvers({
document: clientQuery,
remoteResult: result,
context: context,
variables: variables,
});
});
}
return observable;
};
QueryManager.prototype.getResultsFromLink = function (queryInfo, cacheWriteBehavior, options) {
var requestId = (queryInfo.lastRequestId = this.generateRequestId());
// Performing transformForLink here gives this.cache a chance to fill in
// missing fragment definitions (for example) before sending this document
// through the link chain.
var linkDocument = this.cache.transformForLink(options.query);
return asyncMap(this.getObservableFromLink(linkDocument, options.context, options.variables), function (result) {
var graphQLErrors = getGraphQLErrorsFromResult(result);
var hasErrors = graphQLErrors.length > 0;
// If we interrupted this request by calling getResultsFromLink again
// with the same QueryInfo object, we ignore the old results.
if (requestId >= queryInfo.lastRequestId) {
if (hasErrors && options.errorPolicy === "none") {
// Throwing here effectively calls observer.error.
throw queryInfo.markError(new ApolloError({
graphQLErrors: graphQLErrors,
}));
}
// Use linkDocument rather than queryInfo.document so the
// operation/fragments used to write the result are the same as the
// ones used to obtain it from the link.
queryInfo.markResult(result, linkDocument, options, cacheWriteBehavior);
queryInfo.markReady();
}
var aqr = {
data: result.data,
loading: false,
networkStatus: NetworkStatus.ready,
};
if (hasErrors && options.errorPolicy !== "ignore") {
aqr.errors = graphQLErrors;
aqr.networkStatus = NetworkStatus.error;
}
return aqr;
}, function (networkError) {
var error = isApolloError(networkError) ? networkError : (new ApolloError({ networkError: networkError }));
// Avoid storing errors from older interrupted queries.
if (requestId >= queryInfo.lastRequestId) {
queryInfo.markError(error);
}
throw error;
});
};
QueryManager.prototype.fetchConcastWithInfo = function (queryId, options,
// The initial networkStatus for this fetch, most often
// NetworkStatus.loading, but also possibly fetchMore, poll, refetch,
// or setVariables.
networkStatus, query) {
var _this = this;
if (networkStatus === void 0) { networkStatus = NetworkStatus.loading; }
if (query === void 0) { query = options.query; }
var variables = this.getVariables(query, options.variables);
var queryInfo = this.getQuery(queryId);
var defaults = this.defaultOptions.watchQuery;
var _a = options.fetchPolicy, fetchPolicy = _a === void 0 ? (defaults && defaults.fetchPolicy) || "cache-first" : _a, _b = options.errorPolicy, errorPolicy = _b === void 0 ? (defaults && defaults.errorPolicy) || "none" : _b, _c = options.returnPartialData, returnPartialData = _c === void 0 ? false : _c, _d = options.notifyOnNetworkStatusChange, notifyOnNetworkStatusChange = _d === void 0 ? false : _d, _e = options.context, context = _e === void 0 ? {} : _e;
var normalized = Object.assign({}, options, {
query: query,
variables: variables,
fetchPolicy: fetchPolicy,
errorPolicy: errorPolicy,
returnPartialData: returnPartialData,
notifyOnNetworkStatusChange: notifyOnNetworkStatusChange,
context: context,
});
var fromVariables = function (variables) {
// Since normalized is always a fresh copy of options, it's safe to
// modify its properties here, rather than creating yet another new
// WatchQueryOptions object.
normalized.variables = variables;
var sourcesWithInfo = _this.fetchQueryByPolicy(queryInfo, normalized, networkStatus);
if (
// If we're in standby, postpone advancing options.fetchPolicy using
// applyNextFetchPolicy.
normalized.fetchPolicy !== "standby" &&
// The "standby" policy currently returns [] from fetchQueryByPolicy, so
// this is another way to detect when nothing was done/fetched.
sourcesWithInfo.sources.length > 0 &&
queryInfo.observableQuery) {
queryInfo.observableQuery["applyNextFetchPolicy"]("after-fetch", options);
}
return sourcesWithInfo;
};
// This cancel function needs to be set before the concast is created,
// in case concast creation synchronously cancels the request.
var cleanupCancelFn = function () { return _this.fetchCancelFns.delete(queryId); };
this.fetchCancelFns.set(queryId, function (reason) {
cleanupCancelFn();
// This delay ensures the concast variable has been initialized.
setTimeout(function () { return concast.cancel(reason); });
});
var concast, containsDataFromLink;
// If the query has @export(as: ...) directives, then we need to
// process those directives asynchronously. When there are no
// @export directives (the common case), we deliberately avoid
// wrapping the result of this.fetchQueryByPolicy in a Promise,
// since the timing of result delivery is (unfortunately) important
// for backwards compatibility. TODO This code could be simpler if
// we deprecated and removed LocalState.
if (this.getDocumentInfo(normalized.query).hasClientExports) {
concast = new Concast(this.localState
.addExportedVariables(normalized.query, normalized.variables, normalized.context)
.then(fromVariables)
.then(function (sourcesWithInfo) { return sourcesWithInfo.sources; }));
// there is just no way we can synchronously get the *right* value here,
// so we will assume `true`, which is the behaviour before the bug fix in
// #10597. This means that bug is not fixed in that case, and is probably
// un-fixable with reasonable effort for the edge case of @export as
// directives.
containsDataFromLink = true;
}
else {
var sourcesWithInfo = fromVariables(normalized.variables);
containsDataFromLink = sourcesWithInfo.fromLink;
concast = new Concast(sourcesWithInfo.sources);
}
concast.promise.then(cleanupCancelFn, cleanupCancelFn);
return {
concast: concast,
fromLink: containsDataFromLink,
};
};
QueryManager.prototype.refetchQueries = function (_a) {
var _this = this;
var updateCache = _a.updateCache, include = _a.include, _b = _a.optimistic, optimistic = _b === void 0 ? false : _b, _c = _a.removeOptimistic, removeOptimistic = _c === void 0 ? optimistic ? makeUniqueId("refetchQueries") : void 0 : _c, onQueryUpdated = _a.onQueryUpdated;
var includedQueriesById = new Map();
if (include) {
this.getObservableQueries(include).forEach(function (oq, queryId) {
includedQueriesById.set(queryId, {
oq: oq,
lastDiff: _this.getQuery(queryId).getDiff(),
});
});
}
var results = new Map();
if (updateCache) {
this.cache.batch({
update: updateCache,
// Since you can perform any combination of cache reads and/or writes in
// the cache.batch update function, its optimistic option can be either
// a boolean or a string, representing three distinct modes of
// operation:
//
// * false: read/write only the root layer
// * true: read/write the topmost layer
// * string: read/write a fresh optimistic layer with that ID string
//
// When typeof optimistic === "string", a new optimistic layer will be
// temporarily created within cache.batch with that string as its ID. If
// we then pass that same string as the removeOptimistic option, we can
// make cache.batch immediately remove the optimistic layer after
// running the updateCache function, triggering only one broadcast.
//
// However, the refetchQueries method accepts only true or false for its
// optimistic option (not string). We interpret true to mean a temporary
// optimistic layer should be created, to allow efficiently rolling back
// the effect of the updateCache function, which involves passing a
// string instead of true as the optimistic option to cache.batch, when
// refetchQueries receives optimistic: true.
//
// In other words, we are deliberately not supporting the use case of
// writing to an *existing* optimistic layer (using the refetchQueries
// updateCache function), since that would potentially interfere with
// other optimistic updates in progress. Instead, you can read/write
// only the root layer by passing optimistic: false to refetchQueries,
// or you can read/write a brand new optimistic layer that will be
// automatically removed by passing optimistic: true.
optimistic: (optimistic && removeOptimistic) || false,
// The removeOptimistic option can also be provided by itself, even if
// optimistic === false, to remove some previously-added optimistic
// layer safely and efficiently, like we do in markMutationResult.
//
// If an explicit removeOptimistic string is provided with optimistic:
// true, the removeOptimistic string will determine the ID of the
// temporary optimistic layer, in case that ever matters.
removeOptimistic: removeOptimistic,
onWatchUpdated: function (watch, diff, lastDiff) {
var oq = watch.watcher instanceof QueryInfo && watch.watcher.observableQuery;
if (oq) {
if (onQueryUpdated) {
// Since we're about to handle this query now, remove it from
// includedQueriesById, in case it was added earlier because of
// options.include.
includedQueriesById.delete(oq.queryId);
var result = onQueryUpdated(oq, diff, lastDiff);
if (result === true) {
// The onQueryUpdated function requested the default refetching
// behavior by returning true.
result = oq.refetch();
}
// Record the result in the results Map, as long as onQueryUpdated
// did not return false to skip/ignore this result.
if (result !== false) {
results.set(oq, result);
}
// Allow the default cache broadcast to happen, except when
// onQueryUpdated returns false.
return result;
}
if (onQueryUpdated !== null) {
// If we don't have an onQueryUpdated function, and onQueryUpdated
// was not disabled by passing null, make sure this query is
// "included" like any other options.include-specified query.
includedQueriesById.set(oq.queryId, { oq: oq, lastDiff: lastDiff, diff: diff });
}
}
},
});
}
if (includedQueriesById.size) {
includedQueriesById.forEach(function (_a, queryId) {
var oq = _a.oq, lastDiff = _a.lastDiff, diff = _a.diff;
var result;
// If onQueryUpdated is provided, we want to use it for all included
// queries, even the QueryOptions ones.
if (onQueryUpdated) {
if (!diff) {
var info = oq["queryInfo"];
info.reset(); // Force info.getDiff() to read from cache.
diff = info.getDiff();
}
result = onQueryUpdated(oq, diff, lastDiff);
}
// Otherwise, we fall back to refetching.
if (!onQueryUpdated || result === true) {
result = oq.refetch();
}
if (result !== false) {
results.set(oq, result);
}
if (queryId.indexOf("legacyOneTimeQuery") >= 0) {
_this.stopQueryNoBroadcast(queryId);
}
});
}
if (removeOptimistic) {
// In case no updateCache callback was provided (so cache.batch was not
// called above, and thus did not already remove the optimistic layer),
// remove it here. Since this is a no-op when the layer has already been
// removed, we do it even if we called cache.batch above, since it's
// possible this.cache is an instance of some ApolloCache subclass other
// than InMemoryCache, and does not fully support the removeOptimistic
// option for cache.batch.
this.cache.removeOptimistic(removeOptimistic);
}
return results;
};
QueryManager.prototype.fetchQueryByPolicy = function (queryInfo, _a,
// The initial networkStatus for this fetch, most often
// NetworkStatus.loading, but also possibly fetchMore, poll, refetch,
// or setVariables.
networkStatus) {
var _this = this;
var query = _a.query, variables = _a.variables, fetchPolicy = _a.fetchPolicy, refetchWritePolicy = _a.refetchWritePolicy, errorPolicy = _a.errorPolicy, returnPartialData = _a.returnPartialData, context = _a.context, notifyOnNetworkStatusChange = _a.notifyOnNetworkStatusChange;
var oldNetworkStatus = queryInfo.networkStatus;
queryInfo.init({
document: query,
variables: variables,
networkStatus: networkStatus,
});
var readCache = function () { return queryInfo.getDiff(); };
var resultsFromCache = function (diff, networkStatus) {
if (networkStatus === void 0) { networkStatus = queryInfo.networkStatus || NetworkStatus.loading; }
var data = diff.result;
if (globalThis.__DEV__ !== false && !returnPartialData && !equal(data, {})) {
logMissingFieldErrors(diff.missing);
}
var fromData = function (data) {
return Observable.of(__assign({ data: data, loading: isNetworkRequestInFlight(networkStatus), networkStatus: networkStatus }, (diff.complete ? null : { partial: true })));
};
if (data && _this.getDocumentInfo(query).hasForcedResolvers) {
return _this.localState
.runResolvers({
document: query,
remoteResult: { data: data },
context: context,
variables: variables,
onlyRunForcedResolvers: true,
})
.then(function (resolved) { return fromData(resolved.data || void 0); });
}
// Resolves https://github.com/apollographql/apollo-client/issues/10317.
// If errorPolicy is 'none' and notifyOnNetworkStatusChange is true,
// data was incorrectly returned from the cache on refetch:
// if diff.missing exists, we should not return cache data.
if (errorPolicy === "none" &&
networkStatus === NetworkStatus.refetch &&
Array.isArray(diff.missing)) {
return fromData(void 0);
}
return fromData(data);
};
var cacheWriteBehavior = fetchPolicy === "no-cache" ? 0 /* CacheWriteBehavior.FORBID */
// Watched queries must opt into overwriting existing data on refetch,
// by passing refetchWritePolicy: "overwrite" in their WatchQueryOptions.
: (networkStatus === NetworkStatus.refetch &&
refetchWritePolicy !== "merge") ?
1 /* CacheWriteBehavior.OVERWRITE */
: 2 /* CacheWriteBehavior.MERGE */;
var resultsFromLink = function () {
return _this.getResultsFromLink(queryInfo, cacheWriteBehavior, {
query: query,
variables: variables,
context: context,
fetchPolicy: fetchPolicy,
errorPolicy: errorPolicy,
});
};
var shouldNotify = notifyOnNetworkStatusChange &&
typeof oldNetworkStatus === "number" &&
oldNetworkStatus !== networkStatus &&
isNetworkRequestInFlight(networkStatus);
switch (fetchPolicy) {
default:
case "cache-first": {
var diff = readCache();
if (diff.complete) {
return {
fromLink: false,
sources: [resultsFromCache(diff, queryInfo.markReady())],
};
}
if (returnPartialData || shouldNotify) {
return {
fromLink: true,
sources: [resultsFromCache(diff), resultsFromLink()],
};
}
return { fromLink: true, sources: [resultsFromLink()] };
}
case "cache-and-network": {
var diff = readCache();
if (diff.complete || returnPartialData || shouldNotify) {
return {
fromLink: true,
sources: [resultsFromCache(diff), resultsFromLink()],
};
}
return { fromLink: true, sources: [resultsFromLink()] };
}
case "cache-only":
return {
fromLink: false,
sources: [resultsFromCache(readCache(), queryInfo.markReady())],
};
case "network-only":
if (shouldNotify) {
return {
fromLink: true,
sources: [resultsFromCache(readCache()), resultsFromLink()],
};
}
return { fromLink: true, sources: [resultsFromLink()] };
case "no-cache":
if (shouldNotify) {
return {
fromLink: true,
// Note that queryInfo.getDiff() for no-cache queries does not call
// cache.diff, but instead returns a { complete: false } stub result
// when there is no queryInfo.diff already defined.
sources: [resultsFromCache(queryInfo.getDiff()), resultsFromLink()],
};
}
return { fromLink: true, sources: [resultsFromLink()] };
case "standby":
return { fromLink: false, sources: [] };
}
};
QueryManager.prototype.getQuery = function (queryId) {
if (queryId && !this.queries.has(queryId)) {
this.queries.set(queryId, new QueryInfo(this, queryId));
}
return this.queries.get(queryId);
};
QueryManager.prototype.prepareContext = function (context) {
if (context === void 0) { context = {}; }
var newContext = this.localState.prepareContext(context);
return __assign(__assign(__assign({}, this.defaultContext), newContext), { clientAwareness: this.clientAwareness });
};
return QueryManager;
}());
export { QueryManager };
//# sourceMappingURL=QueryManager.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/utilities/common/mergeOptions.js
import { __assign } from "tslib";
import { compact } from "./compact.js";
export function mergeOptions(defaults, options) {
return compact(defaults, options, options.variables && {
variables: compact(__assign(__assign({}, (defaults && defaults.variables)), options.variables)),
});
}
//# sourceMappingURL=mergeOptions.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/core/ApolloClient.js
import { __assign } from "tslib";
import { invariant, newInvariantError } from "../utilities/globals/index.js";
import { ApolloLink, execute } from "../link/core/index.js";
import { version } from "../version.js";
import { HttpLink } from "../link/http/index.js";
import { QueryManager } from "./QueryManager.js";
import { LocalState } from "./LocalState.js";
var hasSuggestedDevtools = false;
// Though mergeOptions now resides in @apollo/client/utilities, it was
// previously declared and exported from this module, and then reexported from
// @apollo/client/core. Since we need to preserve that API anyway, the easiest
// solution is to reexport mergeOptions where it was previously declared (here).
import { mergeOptions } from "../utilities/index.js";
import { getApolloClientMemoryInternals } from "../utilities/caching/getMemoryInternals.js";
export { mergeOptions };
/**
* This is the primary Apollo Client class. It is used to send GraphQL documents (i.e. queries
* and mutations) to a GraphQL spec-compliant server over an {@link ApolloLink} instance,
* receive results from the server and cache the results in a store. It also delivers updates
* to GraphQL queries through {@link Observable} instances.
*/
var ApolloClient = /** @class */ (function () {
/**
* Constructs an instance of {@link ApolloClient}.
*
* @example
* ```js
* import { ApolloClient, InMemoryCache } from '@apollo/client';
*
* const cache = new InMemoryCache();
*
* const client = new ApolloClient({
* // Provide required constructor fields
* cache: cache,
* uri: 'http://localhost:4000/',
*
* // Provide some optional constructor fields
* name: 'react-web-client',
* version: '1.3',
* queryDeduplication: false,
* defaultOptions: {
* watchQuery: {
* fetchPolicy: 'cache-and-network',
* },
* },
* });
* ```
*/
function ApolloClient(options) {
var _this = this;
this.resetStoreCallbacks = [];
this.clearStoreCallbacks = [];
if (!options.cache) {
throw newInvariantError(15);
}
var uri = options.uri, credentials = options.credentials, headers = options.headers, cache = options.cache, documentTransform = options.documentTransform, _a = options.ssrMode, ssrMode = _a === void 0 ? false : _a, _b = options.ssrForceFetchDelay, ssrForceFetchDelay = _b === void 0 ? 0 : _b,
// Expose the client instance as window.__APOLLO_CLIENT__ and call
// onBroadcast in queryManager.broadcastQueries to enable browser
// devtools, but disable them by default in production.
_c = options.connectToDevTools,
// Expose the client instance as window.__APOLLO_CLIENT__ and call
// onBroadcast in queryManager.broadcastQueries to enable browser
// devtools, but disable them by default in production.
connectToDevTools = _c === void 0 ? typeof window === "object" &&
!window.__APOLLO_CLIENT__ &&
globalThis.__DEV__ !== false : _c, _d = options.queryDeduplication, queryDeduplication = _d === void 0 ? true : _d, defaultOptions = options.defaultOptions, defaultContext = options.defaultContext, _e = options.assumeImmutableResults, assumeImmutableResults = _e === void 0 ? cache.assumeImmutableResults : _e, resolvers = options.resolvers, typeDefs = options.typeDefs, fragmentMatcher = options.fragmentMatcher, clientAwarenessName = options.name, clientAwarenessVersion = options.version;
var link = options.link;
if (!link) {
link =
uri ? new HttpLink({ uri: uri, credentials: credentials, headers: headers }) : ApolloLink.empty();
}
this.link = link;
this.cache = cache;
this.disableNetworkFetches = ssrMode || ssrForceFetchDelay > 0;
this.queryDeduplication = queryDeduplication;
this.defaultOptions = defaultOptions || Object.create(null);
this.typeDefs = typeDefs;
if (ssrForceFetchDelay) {
setTimeout(function () { return (_this.disableNetworkFetches = false); }, ssrForceFetchDelay);
}
this.watchQuery = this.watchQuery.bind(this);
this.query = this.query.bind(this);
this.mutate = this.mutate.bind(this);
this.resetStore = this.resetStore.bind(this);
this.reFetchObservableQueries = this.reFetchObservableQueries.bind(this);
this.version = version;
this.localState = new LocalState({
cache: cache,
client: this,
resolvers: resolvers,
fragmentMatcher: fragmentMatcher,
});
this.queryManager = new QueryManager({
cache: this.cache,
link: this.link,
defaultOptions: this.defaultOptions,
defaultContext: defaultContext,
documentTransform: documentTransform,
queryDeduplication: queryDeduplication,
ssrMode: ssrMode,
clientAwareness: {
name: clientAwarenessName,
version: clientAwarenessVersion,
},
localState: this.localState,
assumeImmutableResults: assumeImmutableResults,
onBroadcast: connectToDevTools ?
function () {
if (_this.devToolsHookCb) {
_this.devToolsHookCb({
action: {},
state: {
queries: _this.queryManager.getQueryStore(),
mutations: _this.queryManager.mutationStore || {},
},
dataWithOptimisticResults: _this.cache.extract(true),
});
}
}
: void 0,
});
if (connectToDevTools)
this.connectToDevTools();
}
ApolloClient.prototype.connectToDevTools = function () {
if (typeof window === "object") {
var windowWithDevTools = window;
var devtoolsSymbol = Symbol.for("apollo.devtools");
(windowWithDevTools[devtoolsSymbol] =
windowWithDevTools[devtoolsSymbol] || []).push(this);
windowWithDevTools.__APOLLO_CLIENT__ = this;
}
/**
* Suggest installing the devtools for developers who don't have them
*/
if (!hasSuggestedDevtools && globalThis.__DEV__ !== false) {
hasSuggestedDevtools = true;
setTimeout(function () {
if (typeof window !== "undefined" &&
window.document &&
window.top === window.self &&
!window.__APOLLO_DEVTOOLS_GLOBAL_HOOK__) {
var nav = window.navigator;
var ua = nav && nav.userAgent;
var url = void 0;
if (typeof ua === "string") {
if (ua.indexOf("Chrome/") > -1) {
url =
"https://chrome.google.com/webstore/detail/" +
"apollo-client-developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm";
}
else if (ua.indexOf("Firefox/") > -1) {
url =
"https://addons.mozilla.org/en-US/firefox/addon/apollo-developer-tools/";
}
}
if (url) {
globalThis.__DEV__ !== false && invariant.log("Download the Apollo DevTools for a better development " +
"experience: %s", url);
}
}
}, 10000);
}
};
Object.defineProperty(ApolloClient.prototype, "documentTransform", {
/**
* The `DocumentTransform` used to modify GraphQL documents before a request
* is made. If a custom `DocumentTransform` is not provided, this will be the
* default document transform.
*/
get: function () {
return this.queryManager.documentTransform;
},
enumerable: false,
configurable: true
});
/**
* Call this method to terminate any active client processes, making it safe
* to dispose of this `ApolloClient` instance.
*/
ApolloClient.prototype.stop = function () {
this.queryManager.stop();
};
/**
* This watches the cache store of the query according to the options specified and
* returns an {@link ObservableQuery}. We can subscribe to this {@link ObservableQuery} and
* receive updated results through a GraphQL observer when the cache store changes.
*
* Note that this method is not an implementation of GraphQL subscriptions. Rather,
* it uses Apollo's store in order to reactively deliver updates to your query results.
*
* For example, suppose you call watchQuery on a GraphQL query that fetches a person's
* first and last name and this person has a particular object identifier, provided by
* dataIdFromObject. Later, a different query fetches that same person's
* first and last name and the first name has now changed. Then, any observers associated
* with the results of the first query will be updated with a new result object.
*
* Note that if the cache does not change, the subscriber will *not* be notified.
*
* See [here](https://medium.com/apollo-stack/the-concepts-of-graphql-bc68bd819be3#.3mb0cbcmc) for
* a description of store reactivity.
*/
ApolloClient.prototype.watchQuery = function (options) {
if (this.defaultOptions.watchQuery) {
options = mergeOptions(this.defaultOptions.watchQuery, options);
}
// XXX Overwriting options is probably not the best way to do this long term...
if (this.disableNetworkFetches &&
(options.fetchPolicy === "network-only" ||
options.fetchPolicy === "cache-and-network")) {
options = __assign(__assign({}, options), { fetchPolicy: "cache-first" });
}
return this.queryManager.watchQuery(options);
};
/**
* This resolves a single query according to the options specified and
* returns a `Promise` which is either resolved with the resulting data
* or rejected with an error.
*
* @param options - An object of type {@link QueryOptions} that allows us to
* describe how this query should be treated e.g. whether it should hit the
* server at all or just resolve from the cache, etc.
*/
ApolloClient.prototype.query = function (options) {
if (this.defaultOptions.query) {
options = mergeOptions(this.defaultOptions.query, options);
}
invariant(options.fetchPolicy !== "cache-and-network", 16);
if (this.disableNetworkFetches && options.fetchPolicy === "network-only") {
options = __assign(__assign({}, options), { fetchPolicy: "cache-first" });
}
return this.queryManager.query(options);
};
/**
* This resolves a single mutation according to the options specified and returns a
* Promise which is either resolved with the resulting data or rejected with an
* error. In some cases both `data` and `errors` might be undefined, for example
* when `errorPolicy` is set to `'ignore'`.
*
* It takes options as an object with the following keys and values:
*/
ApolloClient.prototype.mutate = function (options) {
if (this.defaultOptions.mutate) {
options = mergeOptions(this.defaultOptions.mutate, options);
}
return this.queryManager.mutate(options);
};
/**
* This subscribes to a graphql subscription according to the options specified and returns an
* {@link Observable} which either emits received data or an error.
*/
ApolloClient.prototype.subscribe = function (options) {
return this.queryManager.startGraphQLSubscription(options);
};
/**
* Tries to read some data from the store in the shape of the provided
* GraphQL query without making a network request. This method will start at
* the root query. To start at a specific id returned by `dataIdFromObject`
* use `readFragment`.
*
* @param optimistic - Set to `true` to allow `readQuery` to return
* optimistic results. Is `false` by default.
*/
ApolloClient.prototype.readQuery = function (options, optimistic) {
if (optimistic === void 0) { optimistic = false; }
return this.cache.readQuery(options, optimistic);
};
/**
* Tries to read some data from the store in the shape of the provided
* GraphQL fragment without making a network request. This method will read a
* GraphQL fragment from any arbitrary id that is currently cached, unlike
* `readQuery` which will only read from the root query.
*
* You must pass in a GraphQL document with a single fragment or a document
* with multiple fragments that represent what you are reading. If you pass
* in a document with multiple fragments then you must also specify a
* `fragmentName`.
*
* @param optimistic - Set to `true` to allow `readFragment` to return
* optimistic results. Is `false` by default.
*/
ApolloClient.prototype.readFragment = function (options, optimistic) {
if (optimistic === void 0) { optimistic = false; }
return this.cache.readFragment(options, optimistic);
};
/**
* Writes some data in the shape of the provided GraphQL query directly to
* the store. This method will start at the root query. To start at a
* specific id returned by `dataIdFromObject` then use `writeFragment`.
*/
ApolloClient.prototype.writeQuery = function (options) {
var ref = this.cache.writeQuery(options);
if (options.broadcast !== false) {
this.queryManager.broadcastQueries();
}
return ref;
};
/**
* Writes some data in the shape of the provided GraphQL fragment directly to
* the store. This method will write to a GraphQL fragment from any arbitrary
* id that is currently cached, unlike `writeQuery` which will only write
* from the root query.
*
* You must pass in a GraphQL document with a single fragment or a document
* with multiple fragments that represent what you are writing. If you pass
* in a document with multiple fragments then you must also specify a
* `fragmentName`.
*/
ApolloClient.prototype.writeFragment = function (options) {
var ref = this.cache.writeFragment(options);
if (options.broadcast !== false) {
this.queryManager.broadcastQueries();
}
return ref;
};
ApolloClient.prototype.__actionHookForDevTools = function (cb) {
this.devToolsHookCb = cb;
};
ApolloClient.prototype.__requestRaw = function (payload) {
return execute(this.link, payload);
};
/**
* Resets your entire store by clearing out your cache and then re-executing
* all of your active queries. This makes it so that you may guarantee that
* there is no data left in your store from a time before you called this
* method.
*
* `resetStore()` is useful when your user just logged out. You’ve removed the
* user session, and you now want to make sure that any references to data you
* might have fetched while the user session was active is gone.
*
* It is important to remember that `resetStore()` *will* refetch any active
* queries. This means that any components that might be mounted will execute
* their queries again using your network interface. If you do not want to
* re-execute any queries then you should make sure to stop watching any
* active queries.
*/
ApolloClient.prototype.resetStore = function () {
var _this = this;
return Promise.resolve()
.then(function () {
return _this.queryManager.clearStore({
discardWatches: false,
});
})
.then(function () { return Promise.all(_this.resetStoreCallbacks.map(function (fn) { return fn(); })); })
.then(function () { return _this.reFetchObservableQueries(); });
};
/**
* Remove all data from the store. Unlike `resetStore`, `clearStore` will
* not refetch any active queries.
*/
ApolloClient.prototype.clearStore = function () {
var _this = this;
return Promise.resolve()
.then(function () {
return _this.queryManager.clearStore({
discardWatches: true,
});
})
.then(function () { return Promise.all(_this.clearStoreCallbacks.map(function (fn) { return fn(); })); });
};
/**
* Allows callbacks to be registered that are executed when the store is
* reset. `onResetStore` returns an unsubscribe function that can be used
* to remove registered callbacks.
*/
ApolloClient.prototype.onResetStore = function (cb) {
var _this = this;
this.resetStoreCallbacks.push(cb);
return function () {
_this.resetStoreCallbacks = _this.resetStoreCallbacks.filter(function (c) { return c !== cb; });
};
};
/**
* Allows callbacks to be registered that are executed when the store is
* cleared. `onClearStore` returns an unsubscribe function that can be used
* to remove registered callbacks.
*/
ApolloClient.prototype.onClearStore = function (cb) {
var _this = this;
this.clearStoreCallbacks.push(cb);
return function () {
_this.clearStoreCallbacks = _this.clearStoreCallbacks.filter(function (c) { return c !== cb; });
};
};
/**
* Refetches all of your active queries.
*
* `reFetchObservableQueries()` is useful if you want to bring the client back to proper state in case of a network outage
*
* It is important to remember that `reFetchObservableQueries()` *will* refetch any active
* queries. This means that any components that might be mounted will execute
* their queries again using your network interface. If you do not want to
* re-execute any queries then you should make sure to stop watching any
* active queries.
* Takes optional parameter `includeStandby` which will include queries in standby-mode when refetching.
*/
ApolloClient.prototype.reFetchObservableQueries = function (includeStandby) {
return this.queryManager.reFetchObservableQueries(includeStandby);
};
/**
* Refetches specified active queries. Similar to "reFetchObservableQueries()" but with a specific list of queries.
*
* `refetchQueries()` is useful for use cases to imperatively refresh a selection of queries.
*
* It is important to remember that `refetchQueries()` *will* refetch specified active
* queries. This means that any components that might be mounted will execute
* their queries again using your network interface. If you do not want to
* re-execute any queries then you should make sure to stop watching any
* active queries.
*/
ApolloClient.prototype.refetchQueries = function (options) {
var map = this.queryManager.refetchQueries(options);
var queries = [];
var results = [];
map.forEach(function (result, obsQuery) {
queries.push(obsQuery);
results.push(result);
});
var result = Promise.all(results);
// In case you need the raw results immediately, without awaiting
// Promise.all(results):
result.queries = queries;
result.results = results;
// If you decide to ignore the result Promise because you're using
// result.queries and result.results instead, you shouldn't have to worry
// about preventing uncaught rejections for the Promise.all result.
result.catch(function (error) {
globalThis.__DEV__ !== false && invariant.debug(17, error);
});
return result;
};
/**
* Get all currently active `ObservableQuery` objects, in a `Map` keyed by
* query ID strings.
*
* An "active" query is one that has observers and a `fetchPolicy` other than
* "standby" or "cache-only".
*
* You can include all `ObservableQuery` objects (including the inactive ones)
* by passing "all" instead of "active", or you can include just a subset of
* active queries by passing an array of query names or DocumentNode objects.
*/
ApolloClient.prototype.getObservableQueries = function (include) {
if (include === void 0) { include = "active"; }
return this.queryManager.getObservableQueries(include);
};
/**
* Exposes the cache's complete state, in a serializable format for later restoration.
*/
ApolloClient.prototype.extract = function (optimistic) {
return this.cache.extract(optimistic);
};
/**
* Replaces existing state in the cache (if any) with the values expressed by
* `serializedState`.
*
* Called when hydrating a cache (server side rendering, or offline storage),
* and also (potentially) during hot reloads.
*/
ApolloClient.prototype.restore = function (serializedState) {
return this.cache.restore(serializedState);
};
/**
* Add additional local resolvers.
*/
ApolloClient.prototype.addResolvers = function (resolvers) {
this.localState.addResolvers(resolvers);
};
/**
* Set (override existing) local resolvers.
*/
ApolloClient.prototype.setResolvers = function (resolvers) {
this.localState.setResolvers(resolvers);
};
/**
* Get all registered local resolvers.
*/
ApolloClient.prototype.getResolvers = function () {
return this.localState.getResolvers();
};
/**
* Set a custom local state fragment matcher.
*/
ApolloClient.prototype.setLocalStateFragmentMatcher = function (fragmentMatcher) {
this.localState.setFragmentMatcher(fragmentMatcher);
};
/**
* Define a new ApolloLink (or link chain) that Apollo Client will use.
*/
ApolloClient.prototype.setLink = function (newLink) {
this.link = this.queryManager.link = newLink;
};
Object.defineProperty(ApolloClient.prototype, "defaultContext", {
get: function () {
return this.queryManager.defaultContext;
},
enumerable: false,
configurable: true
});
return ApolloClient;
}());
export { ApolloClient };
if (globalThis.__DEV__ !== false) {
ApolloClient.prototype.getMemoryInternals = getApolloClientMemoryInternals;
}
//# sourceMappingURL=ApolloClient.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/link/retry/retryLink.js
import { __awaiter, __extends, __generator } from "tslib";
import { ApolloLink } from "../core/index.js";
import { Observable } from "../../utilities/index.js";
import { buildDelayFunction } from "./delayFunction.js";
import { buildRetryFunction } from "./retryFunction.js";
/**
* Tracking and management of operations that may be (or currently are) retried.
*/
var RetryableOperation = /** @class */ (function () {
function RetryableOperation(observer, operation, forward, delayFor, retryIf) {
var _this = this;
this.observer = observer;
this.operation = operation;
this.forward = forward;
this.delayFor = delayFor;
this.retryIf = retryIf;
this.retryCount = 0;
this.currentSubscription = null;
this.onError = function (error) { return __awaiter(_this, void 0, void 0, function () {
var shouldRetry;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
this.retryCount += 1;
return [4 /*yield*/, this.retryIf(this.retryCount, this.operation, error)];
case 1:
shouldRetry = _a.sent();
if (shouldRetry) {
this.scheduleRetry(this.delayFor(this.retryCount, this.operation, error));
return [2 /*return*/];
}
this.observer.error(error);
return [2 /*return*/];
}
});
}); };
this.try();
}
/**
* Stop retrying for the operation, and cancel any in-progress requests.
*/
RetryableOperation.prototype.cancel = function () {
if (this.currentSubscription) {
this.currentSubscription.unsubscribe();
}
clearTimeout(this.timerId);
this.timerId = undefined;
this.currentSubscription = null;
};
RetryableOperation.prototype.try = function () {
this.currentSubscription = this.forward(this.operation).subscribe({
next: this.observer.next.bind(this.observer),
error: this.onError,
complete: this.observer.complete.bind(this.observer),
});
};
RetryableOperation.prototype.scheduleRetry = function (delay) {
var _this = this;
if (this.timerId) {
throw new Error("RetryLink BUG! Encountered overlapping retries");
}
this.timerId = setTimeout(function () {
_this.timerId = undefined;
_this.try();
}, delay);
};
return RetryableOperation;
}());
var RetryLink = /** @class */ (function (_super) {
__extends(RetryLink, _super);
function RetryLink(options) {
var _this = _super.call(this) || this;
var _a = options || {}, attempts = _a.attempts, delay = _a.delay;
_this.delayFor =
typeof delay === "function" ? delay : buildDelayFunction(delay);
_this.retryIf =
typeof attempts === "function" ? attempts : buildRetryFunction(attempts);
return _this;
}
RetryLink.prototype.request = function (operation, nextLink) {
var _this = this;
return new Observable(function (observer) {
var retryable = new RetryableOperation(observer, operation, nextLink, _this.delayFor, _this.retryIf);
return function () {
retryable.cancel();
};
});
};
return RetryLink;
}(ApolloLink));
export { RetryLink };
//# sourceMappingURL=retryLink.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/link/retry/delayFunction.js
export function buildDelayFunction(delayOptions) {
var _a = delayOptions || {}, _b = _a.initial, initial = _b === void 0 ? 300 : _b, _c = _a.jitter, jitter = _c === void 0 ? true : _c, _d = _a.max, max = _d === void 0 ? Infinity : _d;
// If we're jittering, baseDelay is half of the maximum delay for that
// attempt (and is, on average, the delay we will encounter).
// If we're not jittering, adjust baseDelay so that the first attempt
// lines up with initialDelay, for everyone's sanity.
var baseDelay = jitter ? initial : initial / 2;
return function delayFunction(count) {
var delay = Math.min(max, baseDelay * Math.pow(2, count));
if (jitter) {
// We opt for a full jitter approach for a mostly uniform distribution,
// but bound it within initialDelay and delay for everyone's sanity.
delay = Math.random() * delay;
}
return delay;
};
}
//# sourceMappingURL=delayFunction.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/link/retry/retryFunction.js
export function buildRetryFunction(retryOptions) {
var _a = retryOptions || {}, retryIf = _a.retryIf, _b = _a.max, max = _b === void 0 ? 5 : _b;
return function retryFunction(count, operation, error) {
if (count >= max)
return false;
return retryIf ? retryIf(error, operation) : !!error;
};
}
//# sourceMappingURL=retryFunction.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/link/error/index.js
import { __extends } from "tslib";
import { Observable } from "../../utilities/index.js";
import { ApolloLink } from "../core/index.js";
export function onError(errorHandler) {
return new ApolloLink(function (operation, forward) {
return new Observable(function (observer) {
var sub;
var retriedSub;
var retriedResult;
try {
sub = forward(operation).subscribe({
next: function (result) {
if (result.errors) {
retriedResult = errorHandler({
graphQLErrors: result.errors,
response: result,
operation: operation,
forward: forward,
});
if (retriedResult) {
retriedSub = retriedResult.subscribe({
next: observer.next.bind(observer),
error: observer.error.bind(observer),
complete: observer.complete.bind(observer),
});
return;
}
}
observer.next(result);
},
error: function (networkError) {
retriedResult = errorHandler({
operation: operation,
networkError: networkError,
//Network errors can return GraphQL errors on for example a 403
graphQLErrors: networkError &&
networkError.result &&
networkError.result.errors,
forward: forward,
});
if (retriedResult) {
retriedSub = retriedResult.subscribe({
next: observer.next.bind(observer),
error: observer.error.bind(observer),
complete: observer.complete.bind(observer),
});
return;
}
observer.error(networkError);
},
complete: function () {
// disable the previous sub from calling complete on observable
// if retry is in flight.
if (!retriedResult) {
observer.complete.bind(observer)();
}
},
});
}
catch (e) {
errorHandler({ networkError: e, operation: operation, forward: forward });
observer.error(e);
}
return function () {
if (sub)
sub.unsubscribe();
if (retriedSub)
sub.unsubscribe();
};
});
});
}
var ErrorLink = /** @class */ (function (_super) {
__extends(ErrorLink, _super);
function ErrorLink(errorHandler) {
var _this = _super.call(this) || this;
_this.link = onError(errorHandler);
return _this;
}
ErrorLink.prototype.request = function (operation, forward) {
return this.link.request(operation, forward);
};
return ErrorLink;
}(ApolloLink));
export { ErrorLink };
//# sourceMappingURL=index.js.map
webpack://frontend-mybets/../../packages/tvg-lib-utils/apolloPolicies.js
import { merge as lodashMerge, isArray, get } from "lodash";
const safeMergeObjects = (existing, incoming, mergeFunction) => {
if (incoming === null || incoming === undefined) {
return incoming;
}
if (existing === null || existing === undefined) {
return incoming;
}
return mergeFunction(existing, incoming);
};
const mergeObjectWithArrayEntry = (
existing = [],
incoming,
{ mergeObjects }
) => {
const merged = existing ? existing.slice(0) : [];
incoming &&
incoming.forEach((obj, i) => {
if (existing && existing[i]) {
const newvalue = { ...existing[i] };
Object.keys(obj).forEach((entry) => {
if (Array.isArray(obj[entry])) {
newvalue[entry] = mergeObjectWithArrayEntry(
existing[i][entry],
obj[entry],
{ mergeObjects }
);
} else {
newvalue[entry] = safeMergeObjects(
existing[i][entry],
obj[entry],
mergeObjects
);
}
});
merged[i] = newvalue;
} else {
merged.push(obj);
}
});
return merged;
};
const mergeArrayByField = (fieldNames, keyfield) => {
return (existing = [], incoming, { readField, mergeObjects }) => {
const merged = existing ? existing.slice(0) : [];
const objectFieldToIndex = Object.create(null);
if (existing) {
existing.forEach((obj, index) => {
objectFieldToIndex[readField(fieldNames[keyfield], obj)] = index;
});
}
incoming &&
incoming.forEach((obj) => {
const field = readField(fieldNames[keyfield], obj);
const index = objectFieldToIndex[field];
if (typeof index === "number") {
const newvalue = { ...existing[index] };
Object.keys(obj).forEach((entry) => {
if (
Object.keys(fieldNames).some((fieldName) => fieldName === entry)
) {
newvalue[entry] = mergeArrayByField(fieldNames, entry)(
existing[index][entry],
obj[entry],
{ readField, mergeObjects }
);
} else if (Array.isArray(obj[entry])) {
newvalue[entry] = mergeObjectWithArrayEntry(
existing[index][entry],
obj[entry],
{ mergeObjects }
);
} else {
newvalue[entry] = safeMergeObjects(
existing[index][entry],
obj[entry],
mergeObjects
);
}
});
merged[index] = newvalue;
} else {
objectFieldToIndex[fieldNames[keyfield]] = merged.length;
merged.push(obj);
}
});
return merged;
};
};
export const policies = {
typePolicies: {
Subscription: {
fields: {
featuredTrackAndRaceMtpOrStatusUpdate: {
merge(existing, incoming) {
return incoming;
}
}
}
},
Track: {
merge(existing, incoming, { mergeObjects }) {
return safeMergeObjects(existing, incoming, mergeObjects);
},
fields: {
races: {
merge(existing, incoming, { readField, mergeObjects }) {
return mergeArrayByField({ main: "id" }, "main")(
existing,
incoming,
{ readField, mergeObjects }
);
}
},
location: {
merge(existing, incoming, { mergeObjects }) {
return safeMergeObjects(existing, incoming, mergeObjects);
}
}
}
},
Race: {
fields: {
numRaces: {
merge: true
},
status: {
merge(existing, incoming) {
return incoming;
}
},
video: {
merge: true
},
promos: {
merge(existing, incoming) {
return incoming ? [...incoming] : null;
}
},
highlighted: {
merge(existing, incoming) {
return incoming;
}
},
location: {
merge: true
},
surface: {
merge: true
},
type: {
merge: true
},
raceClass: {
merge: true
},
changes: {
surface: {
merge: true
},
horse: {
merge: true
}
},
timeform: { merge: true },
talentPicks: {
merge(existing, incoming) {
return isArray(incoming) ? [...incoming] : [...existing];
}
},
wagerTypes: {
merge(existing, incoming) {
return incoming ? [...incoming] : null;
}
},
racePools: {
merge(existing, incoming) {
return incoming ? [...incoming] : null;
}
},
runnersPools: {
merge(existing, incoming) {
return incoming ? [...incoming] : null;
}
},
willPays: {
type: {
merge: true
},
payouts: {
merge(existing, incoming) {
return incoming ? [...incoming] : null;
}
},
legResults: {
merge(existing, incoming) {
return incoming ? [...incoming] : null;
}
}
},
probables: {
merge(existing, incoming) {
return incoming ? [...incoming] : null;
}
},
results: {
runners: {
merge(existing, incoming) {
return incoming ? [...incoming] : null;
}
},
payoffs: {
merge(existing, incoming) {
return incoming ? [...incoming] : null;
}
}
},
bettingInterests: {
merge(existing, incoming, { args, readField, mergeObjects }) {
return get(args, "page", null) && get(args, "page.results", null)
? [...incoming]
: mergeArrayByField(
{ main: "biNumber", runners: "runnerId" },
"main"
)(existing, incoming, {
readField,
mergeObjects
});
}
}
}
},
PastResultsType: {
fields: {
runners: {
read(runners, { variables }) {
const runnerResult = runners.find(
({ entityRunnerId }) =>
entityRunnerId.toString() === variables?.entityRunnerId
);
if (variables?.entityRunnerId && runnerResult) {
return [runnerResult];
}
return runners.slice().sort((a, b) => {
if (a.finishPosition === null) {
return 1;
}
if (b.finishPosition === null) {
return -1;
}
return a.finishPosition - b.finishPosition;
});
},
merge: mergeArrayByField({ main: "entityRunnerId" }, "main")
}
}
},
WagerHistoryResponse: {
fields: {
totals: {
merge(existing, incoming) {
return lodashMerge({ ...existing }, { ...incoming });
}
},
cancelLimits: {
merge: true
},
wagers: {
merge: mergeArrayByField({ main: "id" }, "main")
},
groupWagers: {
merge(existing = [], incoming = []) {
return incoming ? [...incoming] : [...existing];
}
},
futureWagersList: {
total: { merge: true },
wagers: {
merge(existing, incoming) {
return incoming ? [...incoming] : [...existing];
}
}
},
wagersList: {
totals: {
merge(existing, incoming) {
return lodashMerge({ ...existing }, { ...incoming });
}
},
wagers: {
merge(existing, incoming) {
return incoming ? [...incoming] : [...existing];
}
}
},
groupWagersList: {
total: { merge: true },
groupWagers: {
merge(existing, incoming) {
return incoming ? [...incoming] : [...existing];
}
}
}
}
}
},
resultCaching: false,
canonizeResults: false
};
export default { policies };
webpack://frontend-mybets/../../node_modules/graphql-ws/lib/common.mjs
/**
*
* common
*
*/
import { areGraphQLErrors, extendedTypeof, isObject } from './utils.mjs';
/**
* The WebSocket sub-protocol used for the [GraphQL over WebSocket Protocol](https://github.com/graphql/graphql-over-http/blob/main/rfcs/GraphQLOverWebSocket.md).
*
* @category Common
*/
export const GRAPHQL_TRANSPORT_WS_PROTOCOL = 'graphql-transport-ws';
/**
* The deprecated subprotocol used by [subscriptions-transport-ws](https://github.com/apollographql/subscriptions-transport-ws).
*
* @private
*/
export const DEPRECATED_GRAPHQL_WS_PROTOCOL = 'graphql-ws';
/**
* `graphql-ws` expected and standard close codes of the [GraphQL over WebSocket Protocol](https://github.com/graphql/graphql-over-http/blob/main/rfcs/GraphQLOverWebSocket.md).
*
* @category Common
*/
export var CloseCode;
(function (CloseCode) {
CloseCode[CloseCode["InternalServerError"] = 4500] = "InternalServerError";
CloseCode[CloseCode["InternalClientError"] = 4005] = "InternalClientError";
CloseCode[CloseCode["BadRequest"] = 4400] = "BadRequest";
CloseCode[CloseCode["BadResponse"] = 4004] = "BadResponse";
/** Tried subscribing before connect ack */
CloseCode[CloseCode["Unauthorized"] = 4401] = "Unauthorized";
CloseCode[CloseCode["Forbidden"] = 4403] = "Forbidden";
CloseCode[CloseCode["SubprotocolNotAcceptable"] = 4406] = "SubprotocolNotAcceptable";
CloseCode[CloseCode["ConnectionInitialisationTimeout"] = 4408] = "ConnectionInitialisationTimeout";
CloseCode[CloseCode["ConnectionAcknowledgementTimeout"] = 4504] = "ConnectionAcknowledgementTimeout";
/** Subscriber distinction is very important */
CloseCode[CloseCode["SubscriberAlreadyExists"] = 4409] = "SubscriberAlreadyExists";
CloseCode[CloseCode["TooManyInitialisationRequests"] = 4429] = "TooManyInitialisationRequests";
})(CloseCode || (CloseCode = {}));
/**
* Types of messages allowed to be sent by the client/server over the WS protocol.
*
* @category Common
*/
export var MessageType;
(function (MessageType) {
MessageType["ConnectionInit"] = "connection_init";
MessageType["ConnectionAck"] = "connection_ack";
MessageType["Ping"] = "ping";
MessageType["Pong"] = "pong";
MessageType["Subscribe"] = "subscribe";
MessageType["Next"] = "next";
MessageType["Error"] = "error";
MessageType["Complete"] = "complete";
})(MessageType || (MessageType = {}));
/**
* Validates the message against the GraphQL over WebSocket Protocol.
*
* Invalid messages will throw descriptive errors.
*
* @category Common
*/
export function validateMessage(val) {
if (!isObject(val)) {
throw new Error(`Message is expected to be an object, but got ${extendedTypeof(val)}`);
}
if (!val.type) {
throw new Error(`Message is missing the 'type' property`);
}
if (typeof val.type !== 'string') {
throw new Error(`Message is expects the 'type' property to be a string, but got ${extendedTypeof(val.type)}`);
}
switch (val.type) {
case MessageType.ConnectionInit:
case MessageType.ConnectionAck:
case MessageType.Ping:
case MessageType.Pong: {
if (val.payload != null && !isObject(val.payload)) {
throw new Error(`"${val.type}" message expects the 'payload' property to be an object or nullish or missing, but got "${val.payload}"`);
}
break;
}
case MessageType.Subscribe: {
if (typeof val.id !== 'string') {
throw new Error(`"${val.type}" message expects the 'id' property to be a string, but got ${extendedTypeof(val.id)}`);
}
if (!val.id) {
throw new Error(`"${val.type}" message requires a non-empty 'id' property`);
}
if (!isObject(val.payload)) {
throw new Error(`"${val.type}" message expects the 'payload' property to be an object, but got ${extendedTypeof(val.payload)}`);
}
if (typeof val.payload.query !== 'string') {
throw new Error(`"${val.type}" message payload expects the 'query' property to be a string, but got ${extendedTypeof(val.payload.query)}`);
}
if (val.payload.variables != null && !isObject(val.payload.variables)) {
throw new Error(`"${val.type}" message payload expects the 'variables' property to be a an object or nullish or missing, but got ${extendedTypeof(val.payload.variables)}`);
}
if (val.payload.operationName != null &&
extendedTypeof(val.payload.operationName) !== 'string') {
throw new Error(`"${val.type}" message payload expects the 'operationName' property to be a string or nullish or missing, but got ${extendedTypeof(val.payload.operationName)}`);
}
if (val.payload.extensions != null && !isObject(val.payload.extensions)) {
throw new Error(`"${val.type}" message payload expects the 'extensions' property to be a an object or nullish or missing, but got ${extendedTypeof(val.payload.extensions)}`);
}
break;
}
case MessageType.Next: {
if (typeof val.id !== 'string') {
throw new Error(`"${val.type}" message expects the 'id' property to be a string, but got ${extendedTypeof(val.id)}`);
}
if (!val.id) {
throw new Error(`"${val.type}" message requires a non-empty 'id' property`);
}
if (!isObject(val.payload)) {
throw new Error(`"${val.type}" message expects the 'payload' property to be an object, but got ${extendedTypeof(val.payload)}`);
}
break;
}
case MessageType.Error: {
if (typeof val.id !== 'string') {
throw new Error(`"${val.type}" message expects the 'id' property to be a string, but got ${extendedTypeof(val.id)}`);
}
if (!val.id) {
throw new Error(`"${val.type}" message requires a non-empty 'id' property`);
}
if (!areGraphQLErrors(val.payload)) {
throw new Error(`"${val.type}" message expects the 'payload' property to be an array of GraphQL errors, but got ${JSON.stringify(val.payload)}`);
}
break;
}
case MessageType.Complete: {
if (typeof val.id !== 'string') {
throw new Error(`"${val.type}" message expects the 'id' property to be a string, but got ${extendedTypeof(val.id)}`);
}
if (!val.id) {
throw new Error(`"${val.type}" message requires a non-empty 'id' property`);
}
break;
}
default:
throw new Error(`Invalid message 'type' property "${val.type}"`);
}
return val;
}
/**
* Checks if the provided value is a valid GraphQL over WebSocket message.
*
* @deprecated Use `validateMessage` instead.
*
* @category Common
*/
export function isMessage(val) {
try {
validateMessage(val);
return true;
}
catch (_a) {
return false;
}
}
/**
* Parses the raw websocket message data to a valid message.
*
* @category Common
*/
export function parseMessage(data, reviver) {
return validateMessage(typeof data === 'string' ? JSON.parse(data, reviver) : data);
}
/**
* Stringifies a valid message ready to be sent through the socket.
*
* @category Common
*/
export function stringifyMessage(msg, replacer) {
validateMessage(msg);
return JSON.stringify(msg, replacer);
}
webpack://frontend-mybets/../../node_modules/@apollo/client/link/subscriptions/index.js
// This file is adapted from the graphql-ws npm package:
// https://github.com/enisdenjo/graphql-ws
//
// Most of the file comes from that package's README; some other parts (such as
// isLikeCloseEvent) come from its source.
//
// Here's the license of the original code:
//
// The MIT License (MIT)
//
// Copyright (c) 2020-2021 Denis Badurina
//
// 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.
import { __assign, __extends } from "tslib";
import { print } from "../../utilities/index.js";
import { ApolloLink } from "../core/index.js";
import { isNonNullObject, Observable } from "../../utilities/index.js";
import { ApolloError } from "../../errors/index.js";
// https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close_event
function isLikeCloseEvent(val) {
return isNonNullObject(val) && "code" in val && "reason" in val;
}
// https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/error_event
function isLikeErrorEvent(err) {
var _a;
return isNonNullObject(err) && ((_a = err.target) === null || _a === void 0 ? void 0 : _a.readyState) === WebSocket.CLOSED;
}
var GraphQLWsLink = /** @class */ (function (_super) {
__extends(GraphQLWsLink, _super);
function GraphQLWsLink(client) {
var _this = _super.call(this) || this;
_this.client = client;
return _this;
}
GraphQLWsLink.prototype.request = function (operation) {
var _this = this;
return new Observable(function (observer) {
return _this.client.subscribe(__assign(__assign({}, operation), { query: print(operation.query) }), {
next: observer.next.bind(observer),
complete: observer.complete.bind(observer),
error: function (err) {
if (err instanceof Error) {
return observer.error(err);
}
var likeClose = isLikeCloseEvent(err);
if (likeClose || isLikeErrorEvent(err)) {
return observer.error(
// reason will be available on clean closes
new Error("Socket closed".concat(likeClose ? " with event ".concat(err.code) : "").concat(likeClose ? " ".concat(err.reason) : "")));
}
return observer.error(new ApolloError({
graphQLErrors: Array.isArray(err) ? err : [err],
}));
},
});
});
};
return GraphQLWsLink;
}(ApolloLink));
export { GraphQLWsLink };
//# sourceMappingURL=index.js.map
webpack://frontend-mybets/../../node_modules/graphql-ws/lib/utils.mjs
/** @private */
export function extendedTypeof(val) {
if (val === null) {
return 'null';
}
if (Array.isArray(val)) {
return 'array';
}
return typeof val;
}
/** @private */
export function isObject(val) {
return extendedTypeof(val) === 'object';
}
/** @private */
export function isAsyncIterable(val) {
return typeof Object(val)[Symbol.asyncIterator] === 'function';
}
/** @private */
export function isAsyncGenerator(val) {
return (isObject(val) &&
typeof Object(val)[Symbol.asyncIterator] === 'function' &&
typeof val.return === 'function'
// for lazy ones, we only need the return anyway
// typeof val.throw === 'function' &&
// typeof val.next === 'function'
);
}
/** @private */
export function areGraphQLErrors(obj) {
return (Array.isArray(obj) &&
// must be at least one error
obj.length > 0 &&
// error has at least a message
obj.every((ob) => 'message' in ob));
}
/**
* Limits the WebSocket close event reason to not exceed a length of one frame.
* Reference: https://datatracker.ietf.org/doc/html/rfc6455#section-5.2.
*
* @private
*/
export function limitCloseReason(reason, whenTooLong) {
return reason.length < 124 ? reason : whenTooLong;
}
webpack://frontend-mybets/../../node_modules/graphql-ws/lib/client.mjs
/**
*
* client
*
*/
var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
};
import { GRAPHQL_TRANSPORT_WS_PROTOCOL, CloseCode, MessageType, parseMessage, stringifyMessage, } from './common.mjs';
import { isObject, limitCloseReason } from './utils.mjs';
/** This file is the entry point for browsers, re-export common elements. */
export * from './common.mjs';
/**
* Creates a disposable GraphQL over WebSocket client.
*
* @category Client
*/
export function createClient(options) {
const { url, connectionParams, lazy = true, onNonLazyError = console.error, lazyCloseTimeout: lazyCloseTimeoutMs = 0, keepAlive = 0, disablePong, connectionAckWaitTimeout = 0, retryAttempts = 5, retryWait = async function randomisedExponentialBackoff(retries) {
let retryDelay = 1000; // start with 1s delay
for (let i = 0; i < retries; i++) {
retryDelay *= 2;
}
await new Promise((resolve) => setTimeout(resolve, retryDelay +
// add random timeout from 300ms to 3s
Math.floor(Math.random() * (3000 - 300) + 300)));
}, shouldRetry = isLikeCloseEvent, isFatalConnectionProblem, on, webSocketImpl,
/**
* Generates a v4 UUID to be used as the ID using `Math`
* as the random number generator. Supply your own generator
* in case you need more uniqueness.
*
* Reference: https://gist.github.com/jed/982883
*/
generateID = function generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}, jsonMessageReplacer: replacer, jsonMessageReviver: reviver, } = options;
let ws;
if (webSocketImpl) {
if (!isWebSocket(webSocketImpl)) {
throw new Error('Invalid WebSocket implementation provided');
}
ws = webSocketImpl;
}
else if (typeof WebSocket !== 'undefined') {
ws = WebSocket;
}
else if (typeof global !== 'undefined') {
ws =
global.WebSocket ||
// @ts-expect-error: Support more browsers
global.MozWebSocket;
}
else if (typeof window !== 'undefined') {
ws =
window.WebSocket ||
// @ts-expect-error: Support more browsers
window.MozWebSocket;
}
if (!ws)
throw new Error("WebSocket implementation missing; on Node you can `import WebSocket from 'ws';` and pass `webSocketImpl: WebSocket` to `createClient`");
const WebSocketImpl = ws;
// websocket status emitter, subscriptions are handled differently
const emitter = (() => {
const message = (() => {
const listeners = {};
return {
on(id, listener) {
listeners[id] = listener;
return () => {
delete listeners[id];
};
},
emit(message) {
var _a;
if ('id' in message)
(_a = listeners[message.id]) === null || _a === void 0 ? void 0 : _a.call(listeners, message);
},
};
})();
const listeners = {
connecting: (on === null || on === void 0 ? void 0 : on.connecting) ? [on.connecting] : [],
opened: (on === null || on === void 0 ? void 0 : on.opened) ? [on.opened] : [],
connected: (on === null || on === void 0 ? void 0 : on.connected) ? [on.connected] : [],
ping: (on === null || on === void 0 ? void 0 : on.ping) ? [on.ping] : [],
pong: (on === null || on === void 0 ? void 0 : on.pong) ? [on.pong] : [],
message: (on === null || on === void 0 ? void 0 : on.message) ? [message.emit, on.message] : [message.emit],
closed: (on === null || on === void 0 ? void 0 : on.closed) ? [on.closed] : [],
error: (on === null || on === void 0 ? void 0 : on.error) ? [on.error] : [],
};
return {
onMessage: message.on,
on(event, listener) {
const l = listeners[event];
l.push(listener);
return () => {
l.splice(l.indexOf(listener), 1);
};
},
emit(event, ...args) {
// we copy the listeners so that unlistens dont "pull the rug under our feet"
for (const listener of [...listeners[event]]) {
// @ts-expect-error: The args should fit
listener(...args);
}
},
};
})();
// invokes the callback either when an error or closed event is emitted,
// first one that gets called prevails, other emissions are ignored
function errorOrClosed(cb) {
const listening = [
// errors are fatal and more critical than close events, throw them first
emitter.on('error', (err) => {
listening.forEach((unlisten) => unlisten());
cb(err);
}),
// closes can be graceful and not fatal, throw them second (if error didnt throw)
emitter.on('closed', (event) => {
listening.forEach((unlisten) => unlisten());
cb(event);
}),
];
}
let connecting, locks = 0, lazyCloseTimeout, retrying = false, retries = 0, disposed = false;
async function connect() {
// clear the lazy close timeout immediatelly so that close gets debounced
// see: https://github.com/enisdenjo/graphql-ws/issues/388
clearTimeout(lazyCloseTimeout);
const [socket, throwOnClose] = await (connecting !== null && connecting !== void 0 ? connecting : (connecting = new Promise((connected, denied) => (async () => {
if (retrying) {
await retryWait(retries);
// subscriptions might complete while waiting for retry
if (!locks) {
connecting = undefined;
return denied({ code: 1000, reason: 'All Subscriptions Gone' });
}
retries++;
}
emitter.emit('connecting', retrying);
const socket = new WebSocketImpl(typeof url === 'function' ? await url() : url, GRAPHQL_TRANSPORT_WS_PROTOCOL);
let connectionAckTimeout, queuedPing;
function enqueuePing() {
if (isFinite(keepAlive) && keepAlive > 0) {
clearTimeout(queuedPing); // in case where a pong was received before a ping (this is valid behaviour)
queuedPing = setTimeout(() => {
if (socket.readyState === WebSocketImpl.OPEN) {
socket.send(stringifyMessage({ type: MessageType.Ping }));
emitter.emit('ping', false, undefined);
}
}, keepAlive);
}
}
errorOrClosed((errOrEvent) => {
connecting = undefined;
clearTimeout(connectionAckTimeout);
clearTimeout(queuedPing);
denied(errOrEvent);
if (errOrEvent instanceof TerminatedCloseEvent) {
socket.close(4499, 'Terminated'); // close event is artificial and emitted manually, see `Client.terminate()` below
socket.onerror = null;
socket.onclose = null;
}
});
socket.onerror = (err) => emitter.emit('error', err);
socket.onclose = (event) => emitter.emit('closed', event);
socket.onopen = async () => {
try {
emitter.emit('opened', socket);
const payload = typeof connectionParams === 'function'
? await connectionParams()
: connectionParams;
// connectionParams might take too long causing the server to kick off the client
// the necessary error/close event is already reported - simply stop execution
if (socket.readyState !== WebSocketImpl.OPEN)
return;
socket.send(stringifyMessage(payload
? {
type: MessageType.ConnectionInit,
payload,
}
: {
type: MessageType.ConnectionInit,
// payload is completely absent if not provided
}, replacer));
if (isFinite(connectionAckWaitTimeout) &&
connectionAckWaitTimeout > 0) {
connectionAckTimeout = setTimeout(() => {
socket.close(CloseCode.ConnectionAcknowledgementTimeout, 'Connection acknowledgement timeout');
}, connectionAckWaitTimeout);
}
enqueuePing(); // enqueue ping (noop if disabled)
}
catch (err) {
emitter.emit('error', err);
socket.close(CloseCode.InternalClientError, limitCloseReason(err instanceof Error ? err.message : new Error(err).message, 'Internal client error'));
}
};
let acknowledged = false;
socket.onmessage = ({ data }) => {
try {
const message = parseMessage(data, reviver);
emitter.emit('message', message);
if (message.type === 'ping' || message.type === 'pong') {
emitter.emit(message.type, true, message.payload); // received
if (message.type === 'pong') {
enqueuePing(); // enqueue next ping (noop if disabled)
}
else if (!disablePong) {
// respond with pong on ping
socket.send(stringifyMessage(message.payload
? {
type: MessageType.Pong,
payload: message.payload,
}
: {
type: MessageType.Pong,
// payload is completely absent if not provided
}));
emitter.emit('pong', false, message.payload);
}
return; // ping and pongs can be received whenever
}
if (acknowledged)
return; // already connected and acknowledged
if (message.type !== MessageType.ConnectionAck)
throw new Error(`First message cannot be of type ${message.type}`);
clearTimeout(connectionAckTimeout);
acknowledged = true;
emitter.emit('connected', socket, message.payload, retrying); // connected = socket opened + acknowledged
retrying = false; // future lazy connects are not retries
retries = 0; // reset the retries on connect
connected([
socket,
new Promise((_, reject) => errorOrClosed(reject)),
]);
}
catch (err) {
socket.onmessage = null; // stop reading messages as soon as reading breaks once
emitter.emit('error', err);
socket.close(CloseCode.BadResponse, limitCloseReason(err instanceof Error ? err.message : new Error(err).message, 'Bad response'));
}
};
})())));
// if the provided socket is in a closing state, wait for the throw on close
if (socket.readyState === WebSocketImpl.CLOSING)
await throwOnClose;
let release = () => {
// releases this connection
};
const released = new Promise((resolve) => (release = resolve));
return [
socket,
release,
Promise.race([
// wait for
released.then(() => {
if (!locks) {
// and if no more locks are present, complete the connection
const complete = () => socket.close(1000, 'Normal Closure');
if (isFinite(lazyCloseTimeoutMs) && lazyCloseTimeoutMs > 0) {
// if the keepalive is set, allow for the specified calmdown time and
// then complete if the socket is still open.
lazyCloseTimeout = setTimeout(() => {
if (socket.readyState === WebSocketImpl.OPEN)
complete();
}, lazyCloseTimeoutMs);
}
else {
// otherwise complete immediately
complete();
}
}
}),
// or
throwOnClose,
]),
];
}
/**
* Checks the `connect` problem and evaluates if the client should retry.
*/
function shouldRetryConnectOrThrow(errOrCloseEvent) {
// some close codes are worth reporting immediately
if (isLikeCloseEvent(errOrCloseEvent) &&
(isFatalInternalCloseCode(errOrCloseEvent.code) ||
[
CloseCode.InternalServerError,
CloseCode.InternalClientError,
CloseCode.BadRequest,
CloseCode.BadResponse,
CloseCode.Unauthorized,
// CloseCode.Forbidden, might grant access out after retry
CloseCode.SubprotocolNotAcceptable,
// CloseCode.ConnectionInitialisationTimeout, might not time out after retry
// CloseCode.ConnectionAcknowledgementTimeout, might not time out after retry
CloseCode.SubscriberAlreadyExists,
CloseCode.TooManyInitialisationRequests,
// 4499, // Terminated, probably because the socket froze, we want to retry
].includes(errOrCloseEvent.code)))
throw errOrCloseEvent;
// client was disposed, no retries should proceed regardless
if (disposed)
return false;
// normal closure (possibly all subscriptions have completed)
// if no locks were acquired in the meantime, shouldnt try again
if (isLikeCloseEvent(errOrCloseEvent) && errOrCloseEvent.code === 1000)
return locks > 0;
// retries are not allowed or we tried to many times, report error
if (!retryAttempts || retries >= retryAttempts)
throw errOrCloseEvent;
// throw non-retryable connection problems
if (!shouldRetry(errOrCloseEvent))
throw errOrCloseEvent;
// @deprecated throw fatal connection problems immediately
if (isFatalConnectionProblem === null || isFatalConnectionProblem === void 0 ? void 0 : isFatalConnectionProblem(errOrCloseEvent))
throw errOrCloseEvent;
// looks good, start retrying
return (retrying = true);
}
// in non-lazy (hot?) mode always hold one connection lock to persist the socket
if (!lazy) {
(async () => {
locks++;
for (;;) {
try {
const [, , throwOnClose] = await connect();
await throwOnClose; // will always throw because releaser is not used
}
catch (errOrCloseEvent) {
try {
if (!shouldRetryConnectOrThrow(errOrCloseEvent))
return;
}
catch (errOrCloseEvent) {
// report thrown error, no further retries
return onNonLazyError === null || onNonLazyError === void 0 ? void 0 : onNonLazyError(errOrCloseEvent);
}
}
}
})();
}
function subscribe(payload, sink) {
const id = generateID(payload);
let done = false, errored = false, releaser = () => {
// for handling completions before connect
locks--;
done = true;
};
(async () => {
locks++;
for (;;) {
try {
const [socket, release, waitForReleaseOrThrowOnClose] = await connect();
// if done while waiting for connect, release the connection lock right away
if (done)
return release();
const unlisten = emitter.onMessage(id, (message) => {
switch (message.type) {
case MessageType.Next: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- payload will fit type
sink.next(message.payload);
return;
}
case MessageType.Error: {
(errored = true), (done = true);
sink.error(message.payload);
releaser();
return;
}
case MessageType.Complete: {
done = true;
releaser(); // release completes the sink
return;
}
}
});
socket.send(stringifyMessage({
id,
type: MessageType.Subscribe,
payload,
}, replacer));
releaser = () => {
if (!done && socket.readyState === WebSocketImpl.OPEN)
// if not completed already and socket is open, send complete message to server on release
socket.send(stringifyMessage({
id,
type: MessageType.Complete,
}, replacer));
locks--;
done = true;
release();
};
// either the releaser will be called, connection completed and
// the promise resolved or the socket closed and the promise rejected.
// whatever happens though, we want to stop listening for messages
await waitForReleaseOrThrowOnClose.finally(unlisten);
return; // completed, shouldnt try again
}
catch (errOrCloseEvent) {
if (!shouldRetryConnectOrThrow(errOrCloseEvent))
return;
}
}
})()
.then(() => {
// delivering either an error or a complete terminates the sequence
if (!errored)
sink.complete();
}) // resolves on release or normal closure
.catch((err) => {
sink.error(err);
}); // rejects on close events and errors
return () => {
// dispose only of active subscriptions
if (!done)
releaser();
};
}
return {
on: emitter.on,
subscribe,
iterate(request) {
const pending = [];
const deferred = {
done: false,
error: null,
resolve: () => {
// noop
},
};
const dispose = subscribe(request, {
next(val) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
pending.push(val);
deferred.resolve();
},
error(err) {
deferred.done = true;
deferred.error = err;
deferred.resolve();
},
complete() {
deferred.done = true;
deferred.resolve();
},
});
const iterator = (function iterator() {
return __asyncGenerator(this, arguments, function* iterator_1() {
for (;;) {
if (!pending.length) {
// only wait if there are no pending messages available
yield __await(new Promise((resolve) => (deferred.resolve = resolve)));
}
// first flush
while (pending.length) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
yield yield __await(pending.shift());
}
// then error
if (deferred.error) {
throw deferred.error;
}
// or complete
if (deferred.done) {
return yield __await(void 0);
}
}
});
})();
iterator.throw = async (err) => {
if (!deferred.done) {
deferred.done = true;
deferred.error = err;
deferred.resolve();
}
return { done: true, value: undefined };
};
iterator.return = async () => {
dispose();
return { done: true, value: undefined };
};
return iterator;
},
async dispose() {
disposed = true;
if (connecting) {
// if there is a connection, close it
const [socket] = await connecting;
socket.close(1000, 'Normal Closure');
}
},
terminate() {
if (connecting) {
// only if there is a connection
emitter.emit('closed', new TerminatedCloseEvent());
}
},
};
}
/**
* A syntetic close event `4499: Terminated` is issued to the current to immediately
* close the connection without waiting for the one coming from `WebSocket.onclose`.
*
* Terminating is not considered fatal and a connection retry will occur as expected.
*
* Useful in cases where the WebSocket is stuck and not emitting any events;
* can happen on iOS Safari, see: https://github.com/enisdenjo/graphql-ws/discussions/290.
*/
export class TerminatedCloseEvent extends Error {
constructor() {
super(...arguments);
this.name = 'TerminatedCloseEvent';
this.message = '4499: Terminated';
this.code = 4499;
this.reason = 'Terminated';
this.wasClean = false;
}
}
function isLikeCloseEvent(val) {
return isObject(val) && 'code' in val && 'reason' in val;
}
function isFatalInternalCloseCode(code) {
if ([
1000,
1001,
1006,
1005,
1012,
1013,
1014, // Bad Gateway
].includes(code))
return false;
// all other internal errors are fatal
return code >= 1000 && code <= 1999;
}
function isWebSocket(val) {
return (typeof val === 'function' &&
'constructor' in val &&
'CLOSED' in val &&
'CLOSING' in val &&
'CONNECTING' in val &&
'OPEN' in val);
}
webpack://frontend-mybets/./src/apolloClient/ApolloClient.ts
import {
ApolloClient,
InMemoryCache,
createHttpLink,
split,
NormalizedCacheObject
} from "@apollo/client";
import { getMainDefinition } from "@apollo/client/utilities";
import { RetryLink } from "@apollo/client/link/retry";
import { onError } from "@apollo/client/link/error";
import fetch from "node-fetch";
import { policies } from "@tvg/utils/apolloPolicies";
import TVGConf from "@tvg/conf";
import { GraphQLWsLink } from "@apollo/client/link/subscriptions";
import { createClient } from "graphql-ws";
export type GraphClient = "graph" | "fcp" | "rda" | "gas" | "behg";
const getClientURI = (graphClient: GraphClient): string => {
let uri;
switch (graphClient) {
case "rda":
uri = TVGConf().config().service.rda;
break;
default:
uri = TVGConf().config().service.cosmo;
break;
}
return uri;
};
const getClientWsUri = (graphClient: GraphClient): string | null => {
let uri;
switch (graphClient) {
case "graph":
uri = TVGConf().config().service.cosmoWS;
break;
default:
uri = "";
break;
}
return uri.replace("https:", "").replace("http:", "").replace("//", "wss://");
};
export default {
getClient(
graphClient: GraphClient = "graph"
): ApolloClient<NormalizedCacheObject> {
switch (graphClient) {
case "rda":
// @ts-ignore
return this.rdaClient;
case "fcp":
// @ts-ignore
return this.fcpClient;
case "gas":
// @ts-ignore
return this.gasClient;
case "behg":
// @ts-ignore
return this.behgClient;
default:
// @ts-ignore
return this.graphClient;
}
},
setClient(
client: ApolloClient<NormalizedCacheObject>,
type: GraphClient
): void {
switch (type) {
case "rda":
// @ts-ignore
this.rdaClient = client;
break;
case "fcp":
// @ts-ignore
this.fcpClient = client;
break;
case "gas":
// @ts-ignore
this.gasClient = client;
break;
case "behg":
// @ts-ignore
this.behgClient = client;
break;
default:
// @ts-ignore
this.graphClient = client;
break;
}
},
createClient(
ssrMode: boolean = false,
graphClient: GraphClient = "graph"
): ApolloClient<NormalizedCacheObject> {
const httpLink = createHttpLink({
// @ts-ignore
fetch: typeof window === "undefined" ? fetch : window.fetch,
uri: getClientURI(graphClient).replace("http", "https"),
credentials: "include",
headers: {
"x-tvg-context": TVGConf().context()
}
});
const retryLink = new RetryLink({
attempts: () => true,
delay: (count: number) => {
if (count < 25) {
return 2000 * Math.random();
}
return 15000;
}
});
const errorLink = onError(({ graphQLErrors, networkError, operation }) => {
if (graphQLErrors)
graphQLErrors.map(({ message, locations, path }) =>
// eslint-disable-next-line no-console
console.error(
`[GraphQL error]: Operation: ${operation.operationName}, Message: ${message}, Location: ${locations}, Path: ${path}`
)
);
if (networkError) {
console.error(`[Network error]: ${networkError}`); // eslint-disable-line no-console
}
});
let link;
// @ts-ignore
let wsLink;
if (typeof window === "undefined") {
link = errorLink.concat(httpLink);
} else {
const wsUri = getClientWsUri(graphClient);
if (wsUri !== "") {
// @ts-ignore
let activeSocket;
// @ts-ignore
let timedOut;
wsLink = new GraphQLWsLink(
createClient({
url: wsUri || "",
keepAlive: 20_000, // ping server every 10 seconds
on: {
// eslint-disable-next-line
connected: (socket) => (activeSocket = socket),
ping: (received) => {
if (!received)
// sent
timedOut = setTimeout(() => {
// @ts-ignore
if (activeSocket?.readyState === WebSocket.OPEN)
activeSocket?.close(4408, "Request Timeout");
}, 5_000); // wait 5 seconds for the pong and then close the connection
},
pong: (received) => {
// @ts-ignore
if (received) clearTimeout(timedOut); // pong is received, clear connection close timeout
}
},
// @ts-ignore
error: (err) => console.log(err, "ERROR")
})
);
}
const tmplink = wsLink
? split(
// split based on operation type
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === "OperationDefinition" &&
definition.operation === "subscription"
);
},
wsLink,
httpLink
)
: httpLink;
link = retryLink.concat(errorLink).concat(tmplink);
}
const cache = new InMemoryCache(policies);
if (typeof window !== "undefined") {
// @ts-ignore
cache.restore(window.__APOLLO_STATE__); // eslint-disable-line no-underscore-dangle
}
const client = new ApolloClient({
link,
cache,
// @ts-ignore
addTypename: true,
connectToDevTools: true,
ssrMode
});
this.setClient(client, graphClient);
if (wsLink) {
return {
...client,
// @ts-ignore
subscriptionCosmoClient: wsLink?.client,
/* eslint-disable */ // @ts-ignore
subscribe: client.__proto__.subscribe,
// @ts-ignore
stop: client.__proto__.stop
/* eslint-enable */
};
}
return client;
}
};
webpack://frontend-mybets/../../node_modules/redux-thunk/es/index.js
/** A function that accepts a potential "extra argument" value to be injected later,
* and returns an instance of the thunk middleware that uses that value
*/
function createThunkMiddleware(extraArgument) {
// Standard Redux middleware definition pattern:
// See: https://redux.js.org/tutorials/fundamentals/part-4-store#writing-custom-middleware
var middleware = function middleware(_ref) {
var dispatch = _ref.dispatch,
getState = _ref.getState;
return function (next) {
return function (action) {
// The thunk middleware looks for any functions that were passed to `store.dispatch`.
// If this "action" is really a function, call it and return the result.
if (typeof action === 'function') {
// Inject the store's `dispatch` and `getState` methods, as well as any "extra arg"
return action(dispatch, getState, extraArgument);
} // Otherwise, pass the action down the middleware chain as usual
return next(action);
};
};
};
return middleware;
}
var thunk = createThunkMiddleware(); // Attach the factory function so users can create a customized version
// with whatever "extra arg" they want to inject into their thunks
thunk.withExtraArgument = createThunkMiddleware;
export default thunk;
webpack://frontend-mybets/../../packages/tvg-comp-mtp-update/src/reducers.ts
import type { Actions, MtpStatus } from "./actions";
export type State = {
mtpStatus: MtpStatus[];
raceDate: string;
};
export const initialState = {
mtpStatus: [],
raceDate: ""
};
const updateMtpRaces = (raceList: MtpStatus[], races: MtpStatus[]) => {
const newRaceList = [...raceList];
races.forEach((race) => {
const selectedRaceIndex = raceList.findIndex(
(mtpRace) => mtpRace.tvgRaceId === race.tvgRaceId
);
if (selectedRaceIndex >= 0) {
newRaceList[selectedRaceIndex] = {
...raceList[selectedRaceIndex],
...race
};
} else {
newRaceList.push({ ...race });
}
});
return newRaceList;
};
export default function reducer(
/* @ts-ignore */ /* eslint-disable-next-line */
state: State = initialState,
action: Actions
): State {
switch (action.type) {
case "MTP_STATUS_UPDATE": {
return {
...state,
mtpStatus: action.payload.mtpStatus,
raceDate: action.payload.raceDate
? action.payload.raceDate
: state.raceDate
};
}
case "UPDATE_MTP_RACES": {
return {
...state,
mtpStatus: updateMtpRaces(state.mtpStatus, action.payload.races)
};
}
case "UPDATE_MTP_RACEDATE": {
return {
...state,
raceDate: action.payload.raceDate
};
}
default: {
return state;
}
}
}
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/redux/reducers/index.ts
import { merge } from "lodash";
import { PromoOnboardingFormatted } from "../../types/promoOnboarding";
import { Actions as PromoOnboardingActions } from "../actions/types";
export interface PromoOnboardingState
extends Partial<PromoOnboardingFormatted> {
pollerTime: number;
}
export const initialState = {
pollerTime: 60
} as PromoOnboardingState;
export default function promosOnboardingReducer(
state: PromoOnboardingState = initialState,
action: PromoOnboardingActions
) {
switch (action.type) {
case "SET_STORYBLOK_PROMOS": {
return {
...action.payload,
pollerTime: state.pollerTime
};
}
case "SET_PARTIAL_STORYBLOK_PROMOS": {
return {
...merge(state, action.payload)
};
}
case "RESET_STORYBLOK_PROMOS": {
const { pollerTime } = state;
return {
...initialState,
pollerTime
};
}
case "SET_PROMO_ONBOARDING_POLLER_TIME": {
return {
...state,
pollerTime: action.payload
};
}
default: {
return state;
}
}
}
webpack://frontend-mybets/./src/reducers/App/userDataReducer.ts
import type { UserActions } from "../../actions/user";
import type { UserData } from "../../actions/types";
export type State = UserData;
export const initialState = {
hasRequest: false,
forceSessionUpdate: false,
hasRequested: false,
logging: false,
logged: false,
error: null,
wasLogin: false,
userLogin: false,
userLogout: false,
loginPin: false,
geolocateIn: 0,
user: null
};
// @ts-ignore
const userDataReducer = (state: State = initialState, action: UserActions) => {
switch (action.type) {
case "USER_DATA_UPDATE": {
return { ...state, ...action.payload };
}
case "USER_LOGGED_STATE": {
return { ...state, logged: action.payload.isLogged, hasRequested: true };
}
case "USER_ACCOUNT_NUMBER": {
return {
...state,
user: { ...state.user, accountNumber: action.payload.accountNumber }
};
}
default: {
return state;
}
}
};
export default userDataReducer;
webpack://frontend-mybets/./src/reducers/App/capiReducer.ts
import mediator from "@tvg/mediator";
import type {
MapFeatureToggles,
FeatureToggles,
Messages
} from "../../actions/types";
import type { CapiActions } from "../../actions/capi";
export type State = {
featureToggles: MapFeatureToggles | {};
messages: Messages | [];
features: FeatureToggles | [];
};
export const initialState: State = {
featureToggles: {},
features: [],
messages: []
};
export default function capiReducer(
state: State = initialState,
action: CapiActions
) {
switch (action.type) {
case "FEATURES_GET_SUCCESS": {
mediator.base.dispatch({ type: "FEATURE_TOGGLES_LOADED", payload: {} });
return { ...state, featureToggles: action.payload.featureToggles };
}
case "FEATURES_GET_FAIL": {
return { ...state };
}
case "FEATURES_CHANGE": {
const featureToggles = {
...state.featureToggles,
[action.payload.toggleName]: action.payload.newValue
};
return { ...state, featureToggles };
}
case "FEATURES_RESPONSE": {
return { ...state, features: action.payload.features };
}
case "MESSAGES_GET_SUCCESS":
return { ...state, messages: action.payload.messages };
case "MESSAGES_GET_FAIL": {
return { ...state };
}
default: {
return state;
}
}
}
webpack://frontend-mybets/./src/reducers/index.ts
import { combineReducers } from "redux";
import myBetsStandaloneReducer, {
State as MyBetsStandaloneState,
initialState as initialMyBetsStandaloneState
} from "@tvg/sh-lib-my-bets/redux/reducers";
import mtpStatusReducer, {
State as MtpStatusState,
initialState as initialMtpStatusState
} from "@tvg/mtp-update/src/reducers";
import promosOnboardingReducer, {
PromoOnboardingState,
initialState as initialPromosOnboardingState
} from "@tvg/sh-lib-promos-onboarding/redux/reducers";
import userDataReducer, {
State as UserState,
initialState as initialUserState
} from "./App/userDataReducer";
import capiReducer, {
State as CapiState,
initialState as initialCapiState
} from "./App/capiReducer";
export type State = {
myBetsStandalone: MyBetsStandaloneState;
mtpStatus: MtpStatusState;
userData: UserState;
capi: CapiState;
promosOnboarding: PromoOnboardingState;
};
export const initialState = {
myBetsStandalone: initialMyBetsStandaloneState,
mtpStatus: initialMtpStatusState,
userData: initialUserState,
capi: initialCapiState,
promosOnboarding: initialPromosOnboardingState
};
export default combineReducers({
myBetsStandalone: myBetsStandaloneReducer,
mtpStatus: mtpStatusReducer,
userData: userDataReducer,
capi: capiReducer,
promosOnboarding: promosOnboardingReducer
});
webpack://frontend-mybets/./src/configureStore.ts
import { createStore, applyMiddleware, Store } from "redux";
import thunk from "redux-thunk";
import { composeWithDevTools } from "redux-devtools-extension";
import reducers, { initialState, State } from "./reducers";
const composeEnhancers = composeWithDevTools({
name: "tvg-mybets-desktop"
});
export default (state: State = initialState): Store<State> => {
const middlewares = [thunk];
const enhancer = composeEnhancers(applyMiddleware(...middlewares));
// @ts-ignore
const store = createStore(reducers, state, enhancer);
// @ts-ignore
if (module.hot) {
// @ts-ignore
module.hot.accept("./reducers", () =>
import("./reducers").then((reducerModule) =>
store.replaceReducer(reducerModule.default)
)
);
}
return store;
};
webpack://frontend-mybets/../../packages/tvg-lib-utils/featuresUtils.jsx
import tvgConf from "@tvg/conf";
import { get } from "lodash";
export const getCapiFeatureToggles = (store, key, defaultValue) => {
if (key.includes("-beta") && tvgConf().isProduction) {
return false;
}
return get(store, `capi.featureToggles.${key}`, defaultValue);
};
const calculateFeatureOverride = (
hasFeaturesOverrides,
featureOverrides,
toggle
) => {
const { percentage } = toggle;
const overrides = featureOverrides;
let { enabled } = toggle;
let random = 0;
// Disable feature override if toggle was disabled or percentage is 0
if (
featureOverrides[toggle.name] &&
(!toggle.enabled || toggle.percentage === 0)
) {
enabled = false;
overrides[toggle.name] = { enabled, percentage };
}
// Calculate new feature throttle by percentage or if it was disabled and percentage was increased
if (
(!hasFeaturesOverrides && toggle.enabled && toggle.percentage < 100) ||
(featureOverrides[toggle.name] &&
!featureOverrides[toggle.name].enabled &&
percentage > featureOverrides[toggle.name].percentage)
) {
random = Math.floor(Math.random() * 100 + 1);
enabled = toggle.percentage >= random;
overrides[toggle.name] = { enabled, percentage };
}
return overrides;
};
export default calculateFeatureOverride;
webpack://frontend-mybets/../../legacy/mediator/src/utils.js
// This file is here to replace Lodash.
// Currently we need to import 70Kb (after optimizations) from lodash just to use 6 functions.
// This is not worth it. If the uses cases for lodash increase, we should get
// rid of this.
export const isUndefined = (val) => typeof val === "undefined";
export const curry = (fn) =>
function cf(...args) {
return args.length >= fn.length
? fn(...args)
: (...a) => cf(...[...args, ...a]);
};
export const defaultTo = curry((defaults, value) =>
value === undefined || value === null || Number.isNaN(value)
? defaults
: value
);
export const isDifferent = curry((a, b) => a !== b);
webpack://frontend-mybets/../../legacy/mediator/src/Mediator.js
import { isUndefined, isDifferent } from "./utils";
const createEventHandler = (val) => ({
subscribers: [],
lastValue: val
});
class Mediator {
handlers;
constructor() {
this.handlers = {};
}
subscribe(type, handler) {
this.handlers[type] = this.handlers[type] || createEventHandler();
this.handlers[type].subscribers = [
...this.handlers[type].subscribers,
handler
];
return () => this.unsubscribe(type, handler);
}
subscribeTimes(times, type, handler) {
let count = 0;
const fnTimes = (current, max, val) => {
count += 1;
if (count === times) {
this.unsubscribe(type, fnTimes);
}
return handler(val);
};
this.subscribe(type, fnTimes);
return () => this.unsubscribe(type, fnTimes);
}
subscribeWithPast(type, handler) {
const unsubscribeHandler = this.subscribe(type, handler);
const eventHandler = this.handlers[type];
if (!isUndefined(eventHandler.lastValue)) {
handler(eventHandler.lastValue);
}
return unsubscribeHandler;
}
unsubscribe(type, handler) {
const evtHandler = this.handlers[type];
if (evtHandler) {
evtHandler.subscribers = evtHandler.subscribers.filter(
isDifferent(handler)
);
}
return this;
}
dispatch(type, value) {
const handler = this.handlers[type];
if (handler && handler.subscribers.length) {
handler.subscribers.map((fn) => fn(value));
this.handlers[type].lastValue = value;
} else {
this.handlers[type] = createEventHandler(value);
}
return this;
}
query(type) {
const handler = this.handlers[type];
return handler && handler.lastValue ? handler.lastValue : undefined;
}
}
export default Mediator;
webpack://frontend-mybets/../../legacy/mediator/src/MediatorNoop.js
class MediatorNoop {
handlers;
constructor() {
this.handlers = {};
}
subscribe(type, handler) {
return () => this.unsubscribe(type, handler);
}
subscribeTimes(times, type, handler) {
return () => this.unsubscribe(type, handler);
}
subscribeWithPast(type, handler) {
return () => this.unsubscribe(type, handler);
}
unsubscribe(
type,
handler // eslint-disable-line no-unused-vars
) {
return this;
}
// eslint-disable-next-line no-unused-vars
dispatch(type, value) {
return this;
}
query(type) {
const handler = this.handlers[type];
return handler && handler.lastValue ? handler.lastValue : undefined;
}
}
export default MediatorNoop;
webpack://frontend-mybets/../../legacy/mediator/src/index.js
import { curry } from "./utils";
import Mediator from "./Mediator";
import MediatorNoop from "./MediatorNoop";
const createMediator = () => {
if (typeof window !== "undefined" && !window.mediator) {
window.mediator = new Mediator();
return window.mediator;
}
if (typeof window !== "undefined" && window.mediator) {
return window.mediator;
}
return new MediatorNoop();
};
const instance = createMediator();
export const subscribe = curry((name, handler) =>
instance.subscribe(name, handler)
);
export const subscribeWithPast = curry((name, handler) =>
instance.subscribeWithPast(name, handler)
);
export const subscribeTimes = curry((count, name, handler) =>
instance.subscribeTimes(count, name, handler)
);
export const subscribeOnce = subscribeTimes(1);
export const subscribeTwice = subscribeTimes(2);
export const subscribeThrice = subscribeTimes(3);
export const unsubscribe = curry((name, handler) =>
instance.unsubscribe(name, handler)
);
export const dispatch = curry((type, value) => instance.dispatch(type, value));
export const query = (type) => instance.query(type);
webpack://frontend-mybets/../../packages/tvg-lib-gtm/src/gtmUtils.js
import { startCase } from "lodash";
import tvgConf from "@tvg/conf";
export default (data) => {
if (typeof window !== "undefined" && window.dataLayer) {
window.dataLayer.push(data);
}
};
/* This method aims to remove the dash from international tracks */
export const processTrackName = (trackName) => trackName.replace(" - ", " ");
export const getSiteVersion = (product) => {
if (product === "touch3") {
return "mobile_web";
}
if (product === "ios2") {
return "ios_native";
}
return tvgConf().gaConfig().siteVersion;
};
export const getProduct = (product) => {
const productVersions = {
touch3: "MEP-01",
ios2: "iOS",
fdrmobile: "FDR-01",
fdrios: "FDR-01"
};
return productVersions[product]
? productVersions[product]
: product.toUpperCase();
};
export const setFirstLetterCapital = (tab) => {
if (!tab) {
return undefined;
}
const strArray = tab.toLowerCase().split("_");
return strArray.map((str) => str[0].toUpperCase() + str.slice(1)).join(" ");
};
export const convertMyBetsFilterActive = (selectedTab, selectedSettledTab) => {
const filterActive = selectedSettledTab.toLowerCase().replace("_", " ");
const isPastDayFilters = ["YESTERDAY", "LAST_WEEK", "LAST_MONTH"].includes(
selectedSettledTab
);
return selectedTab.toUpperCase() === "ACTIVE" ||
selectedTab.toUpperCase() === "FUTURES"
? "None"
: startCase(isPastDayFilters ? `Since ${filterActive}` : filterActive);
};
webpack://frontend-mybets/./src/actions/capi.ts
import type { MapFeatureToggles, FeatureToggles, Messages } from "./types";
type FeaturesRequestSuccessAction = {
type: "FEATURES_GET_SUCCESS";
payload: {
featureToggles: MapFeatureToggles | {};
};
};
type FeaturesRequestFailAction = {
type: "FEATURES_GET_FAIL";
payload: Error;
error: true;
};
type FeaturesChange = {
type: "FEATURES_CHANGE";
payload: {
toggleName: string;
newValue: boolean;
};
};
type FeaturesResponseAction = {
type: "FEATURES_RESPONSE";
payload: {
features: FeatureToggles | [];
};
};
type MessagesRequestSuccessAction = {
type: "MESSAGES_GET_SUCCESS";
payload: {
messages: Messages | false;
};
};
type MessagesRequestFailAction = {
type: "MESSAGES_GET_FAIL";
payload: Error;
error: true;
};
export type CapiActions =
| MessagesRequestFailAction
| MessagesRequestSuccessAction
| FeaturesRequestFailAction
| FeaturesRequestSuccessAction
| FeaturesResponseAction
| FeaturesChange;
export const successFeaturesRequest = (
featureToggles: MapFeatureToggles | {}
): FeaturesRequestSuccessAction => ({
type: "FEATURES_GET_SUCCESS",
payload: {
featureToggles
}
});
export const failFeaturesRequest = (err: Error): FeaturesRequestFailAction => ({
type: "FEATURES_GET_FAIL",
payload: err,
error: true
});
export const featuresResponse = (
features: FeatureToggles
): FeaturesResponseAction => ({
type: "FEATURES_RESPONSE",
payload: {
features
}
});
export const successMessagesRequest = (
messagesData: Messages | false
): MessagesRequestSuccessAction => ({
type: "MESSAGES_GET_SUCCESS",
payload: {
messages: messagesData
}
});
export const failMessagesRequest = (err: Error): MessagesRequestFailAction => ({
type: "MESSAGES_GET_FAIL",
payload: err,
error: true
});
webpack://frontend-mybets/../../node_modules/@apollo/client/react/parser/index.js
import { invariant } from "../../utilities/globals/index.js";
import { AutoCleanedWeakCache, cacheSizes, } from "../../utilities/index.js";
import { registerGlobalCache } from "../../utilities/caching/getMemoryInternals.js";
export var DocumentType;
(function (DocumentType) {
DocumentType[DocumentType["Query"] = 0] = "Query";
DocumentType[DocumentType["Mutation"] = 1] = "Mutation";
DocumentType[DocumentType["Subscription"] = 2] = "Subscription";
})(DocumentType || (DocumentType = {}));
var cache;
export function operationName(type) {
var name;
switch (type) {
case DocumentType.Query:
name = "Query";
break;
case DocumentType.Mutation:
name = "Mutation";
break;
case DocumentType.Subscription:
name = "Subscription";
break;
}
return name;
}
// This parser is mostly used to safety check incoming documents.
export function parser(document) {
if (!cache) {
cache = new AutoCleanedWeakCache(cacheSizes.parser || 1000 /* defaultCacheSizes.parser */);
}
var cached = cache.get(document);
if (cached)
return cached;
var variables, type, name;
invariant(!!document && !!document.kind, 59, document);
var fragments = [];
var queries = [];
var mutations = [];
var subscriptions = [];
for (var _i = 0, _a = document.definitions; _i < _a.length; _i++) {
var x = _a[_i];
if (x.kind === "FragmentDefinition") {
fragments.push(x);
continue;
}
if (x.kind === "OperationDefinition") {
switch (x.operation) {
case "query":
queries.push(x);
break;
case "mutation":
mutations.push(x);
break;
case "subscription":
subscriptions.push(x);
break;
}
}
}
invariant(!fragments.length ||
queries.length ||
mutations.length ||
subscriptions.length, 60);
invariant(
queries.length + mutations.length + subscriptions.length <= 1,
61,
document,
queries.length,
subscriptions.length,
mutations.length
);
type = queries.length ? DocumentType.Query : DocumentType.Mutation;
if (!queries.length && !mutations.length)
type = DocumentType.Subscription;
var definitions = queries.length ? queries
: mutations.length ? mutations
: subscriptions;
invariant(definitions.length === 1, 62, document, definitions.length);
var definition = definitions[0];
variables = definition.variableDefinitions || [];
if (definition.name && definition.name.kind === "Name") {
name = definition.name.value;
}
else {
name = "data"; // fallback to using data if no name
}
var payload = { name: name, type: type, variables: variables };
cache.set(document, payload);
return payload;
}
parser.resetCache = function () {
cache = undefined;
};
if (globalThis.__DEV__ !== false) {
registerGlobalCache("parser", function () { return (cache ? cache.size : 0); });
}
export function verifyDocumentType(document, type) {
var operation = parser(document);
var requiredOperationName = operationName(type);
var usedOperationName = operationName(operation.type);
invariant(
operation.type === type,
63,
requiredOperationName,
requiredOperationName,
usedOperationName
);
}
//# sourceMappingURL=index.js.map
webpack://frontend-mybets/./src/actions/user.ts
import type { UserData } from "./types";
export type UserSessionSuccessAction = {
type: "USER_DATA_UPDATE";
payload: UserData;
};
export type SetUserLoggedState = {
type: "USER_LOGGED_STATE";
payload: {
isLogged: boolean;
};
};
export type SetUserAccountNumber = {
type: "USER_ACCOUNT_NUMBER";
payload: {
accountNumber: string;
};
};
export type UserActions =
| UserSessionSuccessAction
| SetUserLoggedState
| SetUserAccountNumber;
export const getUserData = (userData: UserData): UserSessionSuccessAction => ({
type: "USER_DATA_UPDATE",
payload: userData
});
export const setUserLoggedState = (isLogged: boolean): SetUserLoggedState => ({
type: "USER_LOGGED_STATE",
payload: {
isLogged
}
});
export const setUserAccountNumber = (
accountNumber: string
): SetUserAccountNumber => ({
type: "USER_ACCOUNT_NUMBER",
payload: {
accountNumber
}
});
webpack://frontend-mybets/../../node_modules/@apollo/client/react/hooks/useSyncExternalStore.js
import { invariant } from "../../utilities/globals/index.js";
import * as React from "rehackt";
import { canUseLayoutEffect } from "../../utilities/index.js";
var didWarnUncachedGetSnapshot = false;
// Prevent webpack from complaining about our feature detection of the
// useSyncExternalStore property of the React namespace, which is expected not
// to exist when using React 17 and earlier, and that's fine.
var uSESKey = "useSyncExternalStore";
var realHook = React[uSESKey];
// Adapted from https://www.npmjs.com/package/use-sync-external-store, with
// Apollo Client deviations called out by "// DEVIATION ..." comments.
// When/if React.useSyncExternalStore is defined, delegate fully to it.
export var useSyncExternalStore = realHook ||
(function (subscribe, getSnapshot, getServerSnapshot) {
// Read the current snapshot from the store on every render. Again, this
// breaks the rules of React, and only works here because of specific
// implementation details, most importantly that updates are
// always synchronous.
var value = getSnapshot();
if (
// DEVIATION: Using __DEV__
globalThis.__DEV__ !== false &&
!didWarnUncachedGetSnapshot &&
// DEVIATION: Not using Object.is because we know our snapshots will never
// be exotic primitive values like NaN, which is !== itself.
value !== getSnapshot()) {
didWarnUncachedGetSnapshot = true;
// DEVIATION: Using invariant.error instead of console.error directly.
globalThis.__DEV__ !== false && invariant.error(58);
}
// Because updates are synchronous, we don't queue them. Instead we force a
// re-render whenever the subscribed state changes by updating an some
// arbitrary useState hook. Then, during render, we call getSnapshot to read
// the current value.
//
// Because we don't actually use the state returned by the useState hook, we
// can save a bit of memory by storing other stuff in that slot.
//
// To implement the early bailout, we need to track some things on a mutable
// object. Usually, we would put that in a useRef hook, but we can stash it in
// our useState hook instead.
//
// To force a re-render, we call forceUpdate({inst}). That works because the
// new object always fails an equality check.
var _a = React.useState({
inst: { value: value, getSnapshot: getSnapshot },
}), inst = _a[0].inst, forceUpdate = _a[1];
// Track the latest getSnapshot function with a ref. This needs to be updated
// in the layout phase so we can access it during the tearing check that
// happens on subscribe.
if (canUseLayoutEffect) {
// DEVIATION: We avoid calling useLayoutEffect when !canUseLayoutEffect,
// which may seem like a conditional hook, but this code ends up behaving
// unconditionally (one way or the other) because canUseLayoutEffect is
// constant.
React.useLayoutEffect(function () {
Object.assign(inst, { value: value, getSnapshot: getSnapshot });
// Whenever getSnapshot or subscribe changes, we need to check in the
// commit phase if there was an interleaved mutation. In concurrent mode
// this can happen all the time, but even in synchronous mode, an earlier
// effect may have mutated the store.
if (checkIfSnapshotChanged(inst)) {
// Force a re-render.
forceUpdate({ inst: inst });
}
}, [subscribe, value, getSnapshot]);
}
else {
Object.assign(inst, { value: value, getSnapshot: getSnapshot });
}
React.useEffect(function () {
// Check for changes right before subscribing. Subsequent changes will be
// detected in the subscription handler.
if (checkIfSnapshotChanged(inst)) {
// Force a re-render.
forceUpdate({ inst: inst });
}
// Subscribe to the store and return a clean-up function.
return subscribe(function handleStoreChange() {
// TODO: Because there is no cross-renderer API for batching updates, it's
// up to the consumer of this library to wrap their subscription event
// with unstable_batchedUpdates. Should we try to detect when this isn't
// the case and print a warning in development?
// The store changed. Check if the snapshot changed since the last time we
// read from the store.
if (checkIfSnapshotChanged(inst)) {
// Force a re-render.
forceUpdate({ inst: inst });
}
});
}, [subscribe]);
return value;
});
function checkIfSnapshotChanged(_a) {
var value = _a.value, getSnapshot = _a.getSnapshot;
try {
return value !== getSnapshot();
}
catch (_b) {
return true;
}
}
//# sourceMappingURL=useSyncExternalStore.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/react/hooks/useApolloClient.js
import { invariant } from "../../utilities/globals/index.js";
import * as React from "rehackt";
import { getApolloContext } from "../context/index.js";
/**
* @example
* ```jsx
* import { useApolloClient } from '@apollo/client';
*
* function SomeComponent() {
* const client = useApolloClient();
* // `client` is now set to the `ApolloClient` instance being used by the
* // application (that was configured using something like `ApolloProvider`)
* }
* ```
*
* @since 3.0.0
* @returns The `ApolloClient` instance being used by the application.
*/
export function useApolloClient(override) {
var context = React.useContext(getApolloContext());
var client = override || context.client;
invariant(!!client, 49);
return client;
}
//# sourceMappingURL=useApolloClient.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/react/hooks/useQuery.js
import { __assign, __rest } from "tslib";
import { invariant } from "../../utilities/globals/index.js";
import * as React from "rehackt";
import { useSyncExternalStore } from "./useSyncExternalStore.js";
import { equal } from "@wry/equality";
import { mergeOptions } from "../../utilities/index.js";
import { getApolloContext } from "../context/index.js";
import { ApolloError } from "../../errors/index.js";
import { NetworkStatus } from "../../core/index.js";
import { DocumentType, verifyDocumentType } from "../parser/index.js";
import { useApolloClient } from "./useApolloClient.js";
import { canUseWeakMap, compact, isNonEmptyArray, maybeDeepFreeze, } from "../../utilities/index.js";
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* A hook for executing queries in an Apollo application.
*
* To run a query within a React component, call `useQuery` and pass it a GraphQL query document.
*
* When your component renders, `useQuery` returns an object from Apollo Client that contains `loading`, `error`, and `data` properties you can use to render your UI.
*
* > Refer to the [Queries](https://www.apollographql.com/docs/react/data/queries) section for a more in-depth overview of `useQuery`.
*
* @example
* ```jsx
* import { gql, useQuery } from '@apollo/client';
*
* const GET_GREETING = gql`
* query GetGreeting($language: String!) {
* greeting(language: $language) {
* message
* }
* }
* `;
*
* function Hello() {
* const { loading, error, data } = useQuery(GET_GREETING, {
* variables: { language: 'english' },
* });
* if (loading) return <p>Loading ...</p>;
* return <h1>Hello {data.greeting.message}!</h1>;
* }
* ```
* @since 3.0.0
* @param query - A GraphQL query document parsed into an AST by `gql`.
* @param options - Options to control how the query is executed.
* @returns Query result object
*/
export function useQuery(query, options) {
if (options === void 0) { options = Object.create(null); }
return useInternalState(useApolloClient(options.client), query).useQuery(options);
}
export function useInternalState(client, query) {
var stateRef = React.useRef();
if (!stateRef.current ||
client !== stateRef.current.client ||
query !== stateRef.current.query) {
stateRef.current = new InternalState(client, query, stateRef.current);
}
var state = stateRef.current;
// By default, InternalState.prototype.forceUpdate is an empty function, but
// we replace it here (before anyone has had a chance to see this state yet)
// with a function that unconditionally forces an update, using the latest
// setTick function. Updating this state by calling state.forceUpdate is the
// only way we trigger React component updates (no other useState calls within
// the InternalState class).
state.forceUpdateState = React.useReducer(function (tick) { return tick + 1; }, 0)[1];
return state;
}
var InternalState = /** @class */ (function () {
function InternalState(client, query, previous) {
var _this = this;
this.client = client;
this.query = query;
/**
* Will be overwritten by the `useSyncExternalStore` "force update" method
* whenever it is available and reset to `forceUpdateState` when it isn't.
*/
this.forceUpdate = function () { return _this.forceUpdateState(); };
this.ssrDisabledResult = maybeDeepFreeze({
loading: true,
data: void 0,
error: void 0,
networkStatus: NetworkStatus.loading,
});
this.skipStandbyResult = maybeDeepFreeze({
loading: false,
data: void 0,
error: void 0,
networkStatus: NetworkStatus.ready,
});
// This cache allows the referential stability of this.result (as returned by
// getCurrentResult) to translate into referential stability of the resulting
// QueryResult object returned by toQueryResult.
this.toQueryResultCache = new (canUseWeakMap ? WeakMap : Map)();
verifyDocumentType(query, DocumentType.Query);
// Reuse previousData from previous InternalState (if any) to provide
// continuity of previousData even if/when the query or client changes.
var previousResult = previous && previous.result;
var previousData = previousResult && previousResult.data;
if (previousData) {
this.previousData = previousData;
}
}
/**
* Forces an update using local component state.
* As this is not batched with `useSyncExternalStore` updates,
* this is only used as a fallback if the `useSyncExternalStore` "force update"
* method is not registered at the moment.
* See https://github.com/facebook/react/issues/25191
* */
InternalState.prototype.forceUpdateState = function () {
// Replaced (in useInternalState) with a method that triggers an update.
globalThis.__DEV__ !== false && invariant.warn(51);
};
InternalState.prototype.executeQuery = function (options) {
var _this = this;
var _a;
if (options.query) {
Object.assign(this, { query: options.query });
}
this.watchQueryOptions = this.createWatchQueryOptions((this.queryHookOptions = options));
var concast = this.observable.reobserveAsConcast(this.getObsQueryOptions());
// Make sure getCurrentResult returns a fresh ApolloQueryResult<TData>,
// but save the current data as this.previousData, just like setResult
// usually does.
this.previousData = ((_a = this.result) === null || _a === void 0 ? void 0 : _a.data) || this.previousData;
this.result = void 0;
this.forceUpdate();
return new Promise(function (resolve) {
var result;
// Subscribe to the concast independently of the ObservableQuery in case
// the component gets unmounted before the promise resolves. This prevents
// the concast from terminating early and resolving with `undefined` when
// there are no more subscribers for the concast.
concast.subscribe({
next: function (value) {
result = value;
},
error: function () {
resolve(_this.toQueryResult(_this.observable.getCurrentResult()));
},
complete: function () {
resolve(_this.toQueryResult(result));
},
});
});
};
// Methods beginning with use- should be called according to the standard
// rules of React hooks: only at the top level of the calling function, and
// without any dynamic conditional logic.
InternalState.prototype.useQuery = function (options) {
var _this = this;
// The renderPromises field gets initialized here in the useQuery method, at
// the beginning of everything (for a given component rendering, at least),
// so we can safely use this.renderPromises in other/later InternalState
// methods without worrying it might be uninitialized. Even after
// initialization, this.renderPromises is usually undefined (unless SSR is
// happening), but that's fine as long as it has been initialized that way,
// rather than left uninitialized.
this.renderPromises = React.useContext(getApolloContext()).renderPromises;
this.useOptions(options);
var obsQuery = this.useObservableQuery();
var result = useSyncExternalStore(React.useCallback(function (handleStoreChange) {
if (_this.renderPromises) {
return function () { };
}
_this.forceUpdate = handleStoreChange;
var onNext = function () {
var previousResult = _this.result;
// We use `getCurrentResult()` instead of the onNext argument because
// the values differ slightly. Specifically, loading results will have
// an empty object for data instead of `undefined` for some reason.
var result = obsQuery.getCurrentResult();
// Make sure we're not attempting to re-render similar results
if (previousResult &&
previousResult.loading === result.loading &&
previousResult.networkStatus === result.networkStatus &&
equal(previousResult.data, result.data)) {
return;
}
_this.setResult(result);
};
var onError = function (error) {
subscription.unsubscribe();
subscription = obsQuery.resubscribeAfterError(onNext, onError);
if (!hasOwnProperty.call(error, "graphQLErrors")) {
// The error is not a GraphQL error
throw error;
}
var previousResult = _this.result;
if (!previousResult ||
(previousResult && previousResult.loading) ||
!equal(error, previousResult.error)) {
_this.setResult({
data: (previousResult && previousResult.data),
error: error,
loading: false,
networkStatus: NetworkStatus.error,
});
}
};
var subscription = obsQuery.subscribe(onNext, onError);
// Do the "unsubscribe" with a short delay.
// This way, an existing subscription can be reused without an additional
// request if "unsubscribe" and "resubscribe" to the same ObservableQuery
// happen in very fast succession.
return function () {
setTimeout(function () { return subscription.unsubscribe(); });
_this.forceUpdate = function () { return _this.forceUpdateState(); };
};
}, [
// We memoize the subscribe function using useCallback and the following
// dependency keys, because the subscribe function reference is all that
// useSyncExternalStore uses internally as a dependency key for the
// useEffect ultimately responsible for the subscription, so we are
// effectively passing this dependency array to that useEffect buried
// inside useSyncExternalStore, as desired.
obsQuery,
this.renderPromises,
this.client.disableNetworkFetches,
]), function () { return _this.getCurrentResult(); }, function () { return _this.getCurrentResult(); });
// TODO Remove this method when we remove support for options.partialRefetch.
this.unsafeHandlePartialRefetch(result);
return this.toQueryResult(result);
};
InternalState.prototype.useOptions = function (options) {
var _a;
var watchQueryOptions = this.createWatchQueryOptions((this.queryHookOptions = options));
// Update this.watchQueryOptions, but only when they have changed, which
// allows us to depend on the referential stability of
// this.watchQueryOptions elsewhere.
var currentWatchQueryOptions = this.watchQueryOptions;
if (!equal(watchQueryOptions, currentWatchQueryOptions)) {
this.watchQueryOptions = watchQueryOptions;
if (currentWatchQueryOptions && this.observable) {
// Though it might be tempting to postpone this reobserve call to the
// useEffect block, we need getCurrentResult to return an appropriate
// loading:true result synchronously (later within the same call to
// useQuery). Since we already have this.observable here (not true for
// the very first call to useQuery), we are not initiating any new
// subscriptions, though it does feel less than ideal that reobserve
// (potentially) kicks off a network request (for example, when the
// variables have changed), which is technically a side-effect.
this.observable.reobserve(this.getObsQueryOptions());
// Make sure getCurrentResult returns a fresh ApolloQueryResult<TData>,
// but save the current data as this.previousData, just like setResult
// usually does.
this.previousData = ((_a = this.result) === null || _a === void 0 ? void 0 : _a.data) || this.previousData;
this.result = void 0;
}
}
// Make sure state.onCompleted and state.onError always reflect the latest
// options.onCompleted and options.onError callbacks provided to useQuery,
// since those functions are often recreated every time useQuery is called.
// Like the forceUpdate method, the versions of these methods inherited from
// InternalState.prototype are empty no-ops, but we can override them on the
// base state object (without modifying the prototype).
this.onCompleted =
options.onCompleted || InternalState.prototype.onCompleted;
this.onError = options.onError || InternalState.prototype.onError;
if ((this.renderPromises || this.client.disableNetworkFetches) &&
this.queryHookOptions.ssr === false &&
!this.queryHookOptions.skip) {
// If SSR has been explicitly disabled, and this function has been called
// on the server side, return the default loading state.
this.result = this.ssrDisabledResult;
}
else if (this.queryHookOptions.skip ||
this.watchQueryOptions.fetchPolicy === "standby") {
// When skipping a query (ie. we're not querying for data but still want to
// render children), make sure the `data` is cleared out and `loading` is
// set to `false` (since we aren't loading anything).
//
// NOTE: We no longer think this is the correct behavior. Skipping should
// not automatically set `data` to `undefined`, but instead leave the
// previous data in place. In other words, skipping should not mandate that
// previously received data is all of a sudden removed. Unfortunately,
// changing this is breaking, so we'll have to wait until Apollo Client 4.0
// to address this.
this.result = this.skipStandbyResult;
}
else if (this.result === this.ssrDisabledResult ||
this.result === this.skipStandbyResult) {
this.result = void 0;
}
};
InternalState.prototype.getObsQueryOptions = function () {
var toMerge = [];
var globalDefaults = this.client.defaultOptions.watchQuery;
if (globalDefaults)
toMerge.push(globalDefaults);
if (this.queryHookOptions.defaultOptions) {
toMerge.push(this.queryHookOptions.defaultOptions);
}
// We use compact rather than mergeOptions for this part of the merge,
// because we want watchQueryOptions.variables (if defined) to replace
// this.observable.options.variables whole. This replacement allows
// removing variables by removing them from the variables input to
// useQuery. If the variables were always merged together (rather than
// replaced), there would be no way to remove existing variables.
// However, the variables from options.defaultOptions and globalDefaults
// (if provided) should be merged, to ensure individual defaulted
// variables always have values, if not otherwise defined in
// observable.options or watchQueryOptions.
toMerge.push(compact(this.observable && this.observable.options, this.watchQueryOptions));
return toMerge.reduce(mergeOptions);
};
// A function to massage options before passing them to ObservableQuery.
InternalState.prototype.createWatchQueryOptions = function (_a) {
var _b;
if (_a === void 0) { _a = {}; }
var skip = _a.skip, ssr = _a.ssr, onCompleted = _a.onCompleted, onError = _a.onError, defaultOptions = _a.defaultOptions,
// The above options are useQuery-specific, so this ...otherOptions spread
// makes otherOptions almost a WatchQueryOptions object, except for the
// query property that we add below.
otherOptions = __rest(_a, ["skip", "ssr", "onCompleted", "onError", "defaultOptions"]);
// This Object.assign is safe because otherOptions is a fresh ...rest object
// that did not exist until just now, so modifications are still allowed.
var watchQueryOptions = Object.assign(otherOptions, { query: this.query });
if (this.renderPromises &&
(watchQueryOptions.fetchPolicy === "network-only" ||
watchQueryOptions.fetchPolicy === "cache-and-network")) {
// this behavior was added to react-apollo without explanation in this PR
// https://github.com/apollographql/react-apollo/pull/1579
watchQueryOptions.fetchPolicy = "cache-first";
}
if (!watchQueryOptions.variables) {
watchQueryOptions.variables = {};
}
if (skip) {
var _c = watchQueryOptions.fetchPolicy, fetchPolicy = _c === void 0 ? this.getDefaultFetchPolicy() : _c, _d = watchQueryOptions.initialFetchPolicy, initialFetchPolicy = _d === void 0 ? fetchPolicy : _d;
// When skipping, we set watchQueryOptions.fetchPolicy initially to
// "standby", but we also need/want to preserve the initial non-standby
// fetchPolicy that would have been used if not skipping.
Object.assign(watchQueryOptions, {
initialFetchPolicy: initialFetchPolicy,
fetchPolicy: "standby",
});
}
else if (!watchQueryOptions.fetchPolicy) {
watchQueryOptions.fetchPolicy =
((_b = this.observable) === null || _b === void 0 ? void 0 : _b.options.initialFetchPolicy) ||
this.getDefaultFetchPolicy();
}
return watchQueryOptions;
};
InternalState.prototype.getDefaultFetchPolicy = function () {
var _a, _b;
return (((_a = this.queryHookOptions.defaultOptions) === null || _a === void 0 ? void 0 : _a.fetchPolicy) ||
((_b = this.client.defaultOptions.watchQuery) === null || _b === void 0 ? void 0 : _b.fetchPolicy) ||
"cache-first");
};
// Defining these methods as no-ops on the prototype allows us to call
// state.onCompleted and/or state.onError without worrying about whether a
// callback was provided.
InternalState.prototype.onCompleted = function (data) { };
InternalState.prototype.onError = function (error) { };
InternalState.prototype.useObservableQuery = function () {
// See if there is an existing observable that was used to fetch the same
// data and if so, use it instead since it will contain the proper queryId
// to fetch the result set. This is used during SSR.
var obsQuery = (this.observable =
(this.renderPromises &&
this.renderPromises.getSSRObservable(this.watchQueryOptions)) ||
this.observable || // Reuse this.observable if possible (and not SSR)
this.client.watchQuery(this.getObsQueryOptions()));
this.obsQueryFields = React.useMemo(function () { return ({
refetch: obsQuery.refetch.bind(obsQuery),
reobserve: obsQuery.reobserve.bind(obsQuery),
fetchMore: obsQuery.fetchMore.bind(obsQuery),
updateQuery: obsQuery.updateQuery.bind(obsQuery),
startPolling: obsQuery.startPolling.bind(obsQuery),
stopPolling: obsQuery.stopPolling.bind(obsQuery),
subscribeToMore: obsQuery.subscribeToMore.bind(obsQuery),
}); }, [obsQuery]);
var ssrAllowed = !(this.queryHookOptions.ssr === false || this.queryHookOptions.skip);
if (this.renderPromises && ssrAllowed) {
this.renderPromises.registerSSRObservable(obsQuery);
if (obsQuery.getCurrentResult().loading) {
// TODO: This is a legacy API which could probably be cleaned up
this.renderPromises.addObservableQueryPromise(obsQuery);
}
}
return obsQuery;
};
InternalState.prototype.setResult = function (nextResult) {
var previousResult = this.result;
if (previousResult && previousResult.data) {
this.previousData = previousResult.data;
}
this.result = nextResult;
// Calling state.setResult always triggers an update, though some call sites
// perform additional equality checks before committing to an update.
this.forceUpdate();
this.handleErrorOrCompleted(nextResult, previousResult);
};
InternalState.prototype.handleErrorOrCompleted = function (result, previousResult) {
var _this = this;
if (!result.loading) {
var error_1 = this.toApolloError(result);
// wait a tick in case we are in the middle of rendering a component
Promise.resolve()
.then(function () {
if (error_1) {
_this.onError(error_1);
}
else if (result.data &&
(previousResult === null || previousResult === void 0 ? void 0 : previousResult.networkStatus) !== result.networkStatus &&
result.networkStatus === NetworkStatus.ready) {
_this.onCompleted(result.data);
}
})
.catch(function (error) {
globalThis.__DEV__ !== false && invariant.warn(error);
});
}
};
InternalState.prototype.toApolloError = function (result) {
return isNonEmptyArray(result.errors) ?
new ApolloError({ graphQLErrors: result.errors })
: result.error;
};
InternalState.prototype.getCurrentResult = function () {
// Using this.result as a cache ensures getCurrentResult continues returning
// the same (===) result object, unless state.setResult has been called, or
// we're doing server rendering and therefore override the result below.
if (!this.result) {
this.handleErrorOrCompleted((this.result = this.observable.getCurrentResult()));
}
return this.result;
};
InternalState.prototype.toQueryResult = function (result) {
var queryResult = this.toQueryResultCache.get(result);
if (queryResult)
return queryResult;
var data = result.data, partial = result.partial, resultWithoutPartial = __rest(result, ["data", "partial"]);
this.toQueryResultCache.set(result, (queryResult = __assign(__assign(__assign({ data: data }, resultWithoutPartial), this.obsQueryFields), { client: this.client, observable: this.observable, variables: this.observable.variables, called: !this.queryHookOptions.skip, previousData: this.previousData })));
if (!queryResult.error && isNonEmptyArray(result.errors)) {
// Until a set naming convention for networkError and graphQLErrors is
// decided upon, we map errors (graphQLErrors) to the error options.
// TODO: Is it possible for both result.error and result.errors to be
// defined here?
queryResult.error = new ApolloError({ graphQLErrors: result.errors });
}
return queryResult;
};
InternalState.prototype.unsafeHandlePartialRefetch = function (result) {
// WARNING: SIDE-EFFECTS IN THE RENDER FUNCTION
//
// TODO: This code should be removed when the partialRefetch option is
// removed. I was unable to get this hook to behave reasonably in certain
// edge cases when this block was put in an effect.
if (result.partial &&
this.queryHookOptions.partialRefetch &&
!result.loading &&
(!result.data || Object.keys(result.data).length === 0) &&
this.observable.options.fetchPolicy !== "cache-only") {
Object.assign(result, {
loading: true,
networkStatus: NetworkStatus.refetch,
});
this.observable.refetch();
}
};
return InternalState;
}());
//# sourceMappingURL=useQuery.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/react/components/Query.js
import { __rest } from "tslib";
import * as PropTypes from "prop-types";
import { useQuery } from "../hooks/index.js";
/**
* @deprecated
* Official support for React Apollo render prop components ended in March 2020.
* This library is still included in the `@apollo/client` package,
* but it no longer receives feature updates or bug fixes.
*/
export function Query(props) {
var children = props.children, query = props.query, options = __rest(props, ["children", "query"]);
var result = useQuery(query, options);
return result ? children(result) : null;
}
Query.propTypes = {
client: PropTypes.object,
children: PropTypes.func.isRequired,
fetchPolicy: PropTypes.string,
notifyOnNetworkStatusChange: PropTypes.bool,
onCompleted: PropTypes.func,
onError: PropTypes.func,
pollInterval: PropTypes.number,
query: PropTypes.object.isRequired,
variables: PropTypes.object,
ssr: PropTypes.bool,
partialRefetch: PropTypes.bool,
returnPartialData: PropTypes.bool,
};
//# sourceMappingURL=Query.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/react/hoc/hoc-utils.js
import { __extends } from "tslib";
import { invariant } from "../../utilities/globals/index.js";
import * as React from "rehackt";
export var defaultMapPropsToOptions = function () { return ({}); };
export var defaultMapResultToProps = function (props) { return props; };
export var defaultMapPropsToSkip = function () { return false; };
export function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || "Component";
}
export function calculateVariablesFromProps(operation, props) {
var variables = {};
for (var _i = 0, _a = operation.variables; _i < _a.length; _i++) {
var _b = _a[_i], variable = _b.variable, type = _b.type;
if (!variable.name || !variable.name.value)
continue;
var variableName = variable.name.value;
var variableProp = props[variableName];
if (typeof variableProp !== "undefined") {
variables[variableName] = variableProp;
continue;
}
// Allow optional props
if (type.kind !== "NonNullType") {
variables[variableName] = undefined;
}
}
return variables;
}
// base class for hocs to easily manage refs
var GraphQLBase = /** @class */ (function (_super) {
__extends(GraphQLBase, _super);
function GraphQLBase(props) {
var _this = _super.call(this, props) || this;
_this.withRef = false;
_this.setWrappedInstance = _this.setWrappedInstance.bind(_this);
return _this;
}
GraphQLBase.prototype.getWrappedInstance = function () {
invariant(this.withRef, 47);
return this.wrappedInstance;
};
GraphQLBase.prototype.setWrappedInstance = function (ref) {
this.wrappedInstance = ref;
};
return GraphQLBase;
}(React.Component));
export { GraphQLBase };
//# sourceMappingURL=hoc-utils.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/react/components/Mutation.js
import * as PropTypes from "prop-types";
import { useMutation } from "../hooks/index.js";
/**
* @deprecated
* Official support for React Apollo render prop components ended in March 2020.
* This library is still included in the `@apollo/client` package,
* but it no longer receives feature updates or bug fixes.
*/
export function Mutation(props) {
var _a = useMutation(props.mutation, props), runMutation = _a[0], result = _a[1];
return props.children ? props.children(runMutation, result) : null;
}
Mutation.propTypes = {
mutation: PropTypes.object.isRequired,
variables: PropTypes.object,
optimisticResponse: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
refetchQueries: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.string, PropTypes.object])),
PropTypes.func,
]),
awaitRefetchQueries: PropTypes.bool,
update: PropTypes.func,
children: PropTypes.func.isRequired,
onCompleted: PropTypes.func,
onError: PropTypes.func,
fetchPolicy: PropTypes.string,
};
//# sourceMappingURL=Mutation.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/react/hooks/useMutation.js
import { __assign } from "tslib";
import * as React from "rehackt";
import { mergeOptions } from "../../utilities/index.js";
import { equal } from "@wry/equality";
import { DocumentType, verifyDocumentType } from "../parser/index.js";
import { ApolloError } from "../../errors/index.js";
import { useApolloClient } from "./useApolloClient.js";
/**
*
*
* > Refer to the [Mutations](https://www.apollographql.com/docs/react/data/mutations/) section for a more in-depth overview of `useMutation`.
*
* @example
* ```jsx
* import { gql, useMutation } from '@apollo/client';
*
* const ADD_TODO = gql`
* mutation AddTodo($type: String!) {
* addTodo(type: $type) {
* id
* type
* }
* }
* `;
*
* function AddTodo() {
* let input;
* const [addTodo, { data }] = useMutation(ADD_TODO);
*
* return (
* <div>
* <form
* onSubmit={e => {
* e.preventDefault();
* addTodo({ variables: { type: input.value } });
* input.value = '';
* }}
* >
* <input
* ref={node => {
* input = node;
* }}
* />
* <button type="submit">Add Todo</button>
* </form>
* </div>
* );
* }
* ```
* @since 3.0.0
* @param mutation - A GraphQL mutation document parsed into an AST by `gql`.
* @param options - Options to control how the mutation is executed.
* @returns A tuple in the form of `[mutate, result]`
*/
export function useMutation(mutation, options) {
var client = useApolloClient(options === null || options === void 0 ? void 0 : options.client);
verifyDocumentType(mutation, DocumentType.Mutation);
var _a = React.useState({
called: false,
loading: false,
client: client,
}), result = _a[0], setResult = _a[1];
var ref = React.useRef({
result: result,
mutationId: 0,
isMounted: true,
client: client,
mutation: mutation,
options: options,
});
// TODO: Trying to assign these in a useEffect or useLayoutEffect breaks
// higher-order components.
{
Object.assign(ref.current, { client: client, options: options, mutation: mutation });
}
var execute = React.useCallback(function (executeOptions) {
if (executeOptions === void 0) { executeOptions = {}; }
var _a = ref.current, options = _a.options, mutation = _a.mutation;
var baseOptions = __assign(__assign({}, options), { mutation: mutation });
var client = executeOptions.client || ref.current.client;
if (!ref.current.result.loading &&
!baseOptions.ignoreResults &&
ref.current.isMounted) {
setResult((ref.current.result = {
loading: true,
error: void 0,
data: void 0,
called: true,
client: client,
}));
}
var mutationId = ++ref.current.mutationId;
var clientOptions = mergeOptions(baseOptions, executeOptions);
return client
.mutate(clientOptions)
.then(function (response) {
var _a, _b;
var data = response.data, errors = response.errors;
var error = errors && errors.length > 0 ?
new ApolloError({ graphQLErrors: errors })
: void 0;
var onError = executeOptions.onError || ((_a = ref.current.options) === null || _a === void 0 ? void 0 : _a.onError);
if (error && onError) {
onError(error, clientOptions);
}
if (mutationId === ref.current.mutationId &&
!clientOptions.ignoreResults) {
var result_1 = {
called: true,
loading: false,
data: data,
error: error,
client: client,
};
if (ref.current.isMounted && !equal(ref.current.result, result_1)) {
setResult((ref.current.result = result_1));
}
}
var onCompleted = executeOptions.onCompleted || ((_b = ref.current.options) === null || _b === void 0 ? void 0 : _b.onCompleted);
if (!error) {
onCompleted === null || onCompleted === void 0 ? void 0 : onCompleted(response.data, clientOptions);
}
return response;
})
.catch(function (error) {
var _a;
if (mutationId === ref.current.mutationId && ref.current.isMounted) {
var result_2 = {
loading: false,
error: error,
data: void 0,
called: true,
client: client,
};
if (!equal(ref.current.result, result_2)) {
setResult((ref.current.result = result_2));
}
}
var onError = executeOptions.onError || ((_a = ref.current.options) === null || _a === void 0 ? void 0 : _a.onError);
if (onError) {
onError(error, clientOptions);
// TODO(brian): why are we returning this here???
return { data: void 0, errors: error };
}
throw error;
});
}, []);
var reset = React.useCallback(function () {
if (ref.current.isMounted) {
var result_3 = { called: false, loading: false, client: client };
Object.assign(ref.current, { mutationId: 0, result: result_3 });
setResult(result_3);
}
}, []);
React.useEffect(function () {
ref.current.isMounted = true;
return function () {
ref.current.isMounted = false;
};
}, []);
return [execute, __assign({ reset: reset }, result)];
}
//# sourceMappingURL=useMutation.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/react/hooks/useSubscription.js
import { invariant } from "../../utilities/globals/index.js";
import * as React from "rehackt";
import { equal } from "@wry/equality";
import { DocumentType, verifyDocumentType } from "../parser/index.js";
import { useApolloClient } from "./useApolloClient.js";
/**
* > Refer to the [Subscriptions](https://www.apollographql.com/docs/react/data/subscriptions/) section for a more in-depth overview of `useSubscription`.
*
* @example
* ```jsx
* const COMMENTS_SUBSCRIPTION = gql`
* subscription OnCommentAdded($repoFullName: String!) {
* commentAdded(repoFullName: $repoFullName) {
* id
* content
* }
* }
* `;
*
* function DontReadTheComments({ repoFullName }) {
* const {
* data: { commentAdded },
* loading,
* } = useSubscription(COMMENTS_SUBSCRIPTION, { variables: { repoFullName } });
* return <h4>New comment: {!loading && commentAdded.content}</h4>;
* }
* ```
* @remarks
* #### Subscriptions and React 18 Automatic Batching
*
* With React 18's [automatic batching](https://react.dev/blog/2022/03/29/react-v18#new-feature-automatic-batching), multiple state updates may be grouped into a single re-render for better performance.
*
* If your subscription API sends multiple messages at the same time or in very fast succession (within fractions of a millisecond), it is likely that only the last message received in that narrow time frame will result in a re-render.
*
* Consider the following component:
*
* ```jsx
* export function Subscriptions() {
* const { data, error, loading } = useSubscription(query);
* const [accumulatedData, setAccumulatedData] = useState([]);
*
* useEffect(() => {
* setAccumulatedData((prev) => [...prev, data]);
* }, [data]);
*
* return (
* <>
* {loading && <p>Loading...</p>}
* {JSON.stringify(accumulatedData, undefined, 2)}
* </>
* );
* }
* ```
*
* If your subscription back-end emits two messages with the same timestamp, only the last message received by Apollo Client will be rendered. This is because React 18 will batch these two state updates into a single re-render.
*
* Since the component above is using `useEffect` to push `data` into a piece of local state on each `Subscriptions` re-render, the first message will never be added to the `accumulatedData` array since its render was skipped.
*
* Instead of using `useEffect` here, we can re-write this component to use the `onData` callback function accepted in `useSubscription`'s `options` object:
*
* ```jsx
* export function Subscriptions() {
* const [accumulatedData, setAccumulatedData] = useState([]);
* const { data, error, loading } = useSubscription(
* query,
* {
* onData({ data }) {
* setAccumulatedData((prev) => [...prev, data])
* }
* }
* );
*
* return (
* <>
* {loading && <p>Loading...</p>}
* {JSON.stringify(accumulatedData, undefined, 2)}
* </>
* );
* }
* ```
*
* > ⚠️ **Note:** The `useSubscription` option `onData` is available in Apollo Client >= 3.7. In previous versions, the equivalent option is named `onSubscriptionData`.
*
* Now, the first message will be added to the `accumulatedData` array since `onData` is called _before_ the component re-renders. React 18 automatic batching is still in effect and results in a single re-render, but with `onData` we can guarantee each message received after the component mounts is added to `accumulatedData`.
*
* @since 3.0.0
* @param subscription - A GraphQL subscription document parsed into an AST by `gql`.
* @param options - Options to control how the subscription is executed.
* @returns Query result object
*/
export function useSubscription(subscription, options) {
var hasIssuedDeprecationWarningRef = React.useRef(false);
var client = useApolloClient(options === null || options === void 0 ? void 0 : options.client);
verifyDocumentType(subscription, DocumentType.Subscription);
var _a = React.useState({
loading: !(options === null || options === void 0 ? void 0 : options.skip),
error: void 0,
data: void 0,
variables: options === null || options === void 0 ? void 0 : options.variables,
}), result = _a[0], setResult = _a[1];
if (!hasIssuedDeprecationWarningRef.current) {
hasIssuedDeprecationWarningRef.current = true;
if (options === null || options === void 0 ? void 0 : options.onSubscriptionData) {
globalThis.__DEV__ !== false && invariant.warn(options.onData ? 52 : 53);
}
if (options === null || options === void 0 ? void 0 : options.onSubscriptionComplete) {
globalThis.__DEV__ !== false && invariant.warn(options.onComplete ? 54 : 55);
}
}
var _b = React.useState(function () {
if (options === null || options === void 0 ? void 0 : options.skip) {
return null;
}
return client.subscribe({
query: subscription,
variables: options === null || options === void 0 ? void 0 : options.variables,
fetchPolicy: options === null || options === void 0 ? void 0 : options.fetchPolicy,
context: options === null || options === void 0 ? void 0 : options.context,
});
}), observable = _b[0], setObservable = _b[1];
var canResetObservableRef = React.useRef(false);
React.useEffect(function () {
return function () {
canResetObservableRef.current = true;
};
}, []);
var ref = React.useRef({ client: client, subscription: subscription, options: options });
React.useEffect(function () {
var _a, _b, _c, _d;
var shouldResubscribe = options === null || options === void 0 ? void 0 : options.shouldResubscribe;
if (typeof shouldResubscribe === "function") {
shouldResubscribe = !!shouldResubscribe(options);
}
if (options === null || options === void 0 ? void 0 : options.skip) {
if (!(options === null || options === void 0 ? void 0 : options.skip) !== !((_a = ref.current.options) === null || _a === void 0 ? void 0 : _a.skip) ||
canResetObservableRef.current) {
setResult({
loading: false,
data: void 0,
error: void 0,
variables: options === null || options === void 0 ? void 0 : options.variables,
});
setObservable(null);
canResetObservableRef.current = false;
}
}
else if ((shouldResubscribe !== false &&
(client !== ref.current.client ||
subscription !== ref.current.subscription ||
(options === null || options === void 0 ? void 0 : options.fetchPolicy) !== ((_b = ref.current.options) === null || _b === void 0 ? void 0 : _b.fetchPolicy) ||
!(options === null || options === void 0 ? void 0 : options.skip) !== !((_c = ref.current.options) === null || _c === void 0 ? void 0 : _c.skip) ||
!equal(options === null || options === void 0 ? void 0 : options.variables, (_d = ref.current.options) === null || _d === void 0 ? void 0 : _d.variables))) ||
canResetObservableRef.current) {
setResult({
loading: true,
data: void 0,
error: void 0,
variables: options === null || options === void 0 ? void 0 : options.variables,
});
setObservable(client.subscribe({
query: subscription,
variables: options === null || options === void 0 ? void 0 : options.variables,
fetchPolicy: options === null || options === void 0 ? void 0 : options.fetchPolicy,
context: options === null || options === void 0 ? void 0 : options.context,
}));
canResetObservableRef.current = false;
}
Object.assign(ref.current, { client: client, subscription: subscription, options: options });
}, [client, subscription, options, canResetObservableRef.current]);
React.useEffect(function () {
if (!observable) {
return;
}
var subscriptionStopped = false;
var subscription = observable.subscribe({
next: function (fetchResult) {
var _a, _b;
if (subscriptionStopped) {
return;
}
var result = {
loading: false,
// TODO: fetchResult.data can be null but SubscriptionResult.data
// expects TData | undefined only
data: fetchResult.data,
error: void 0,
variables: options === null || options === void 0 ? void 0 : options.variables,
};
setResult(result);
if ((_a = ref.current.options) === null || _a === void 0 ? void 0 : _a.onData) {
ref.current.options.onData({
client: client,
data: result,
});
}
else if ((_b = ref.current.options) === null || _b === void 0 ? void 0 : _b.onSubscriptionData) {
ref.current.options.onSubscriptionData({
client: client,
subscriptionData: result,
});
}
},
error: function (error) {
var _a, _b;
if (!subscriptionStopped) {
setResult({
loading: false,
data: void 0,
error: error,
variables: options === null || options === void 0 ? void 0 : options.variables,
});
(_b = (_a = ref.current.options) === null || _a === void 0 ? void 0 : _a.onError) === null || _b === void 0 ? void 0 : _b.call(_a, error);
}
},
complete: function () {
var _a, _b;
if (!subscriptionStopped) {
if ((_a = ref.current.options) === null || _a === void 0 ? void 0 : _a.onComplete) {
ref.current.options.onComplete();
}
else if ((_b = ref.current.options) === null || _b === void 0 ? void 0 : _b.onSubscriptionComplete) {
ref.current.options.onSubscriptionComplete();
}
}
},
});
return function () {
// immediately stop receiving subscription values, but do not unsubscribe
// until after a short delay in case another useSubscription hook is
// reusing the same underlying observable and is about to subscribe
subscriptionStopped = true;
setTimeout(function () {
subscription.unsubscribe();
});
};
}, [observable]);
return result;
}
//# sourceMappingURL=useSubscription.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/react/components/Subscription.js
import * as PropTypes from "prop-types";
import { useSubscription } from "../hooks/index.js";
/**
* @deprecated
* Official support for React Apollo render prop components ended in March 2020.
* This library is still included in the `@apollo/client` package,
* but it no longer receives feature updates or bug fixes.
*/
export function Subscription(props) {
var result = useSubscription(props.subscription, props);
return props.children && result ? props.children(result) : null;
}
Subscription.propTypes = {
subscription: PropTypes.object.isRequired,
variables: PropTypes.object,
children: PropTypes.func,
onSubscriptionData: PropTypes.func,
onData: PropTypes.func,
onSubscriptionComplete: PropTypes.func,
onComplete: PropTypes.func,
shouldResubscribe: PropTypes.oneOfType([PropTypes.func, PropTypes.bool]),
};
//# sourceMappingURL=Subscription.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/react/hoc/graphql.js
import { parser, DocumentType } from "../parser/index.js";
import { withQuery } from "./query-hoc.js";
import { withMutation } from "./mutation-hoc.js";
import { withSubscription } from "./subscription-hoc.js";
/**
* @deprecated
* Official support for React Apollo higher order components ended in March 2020.
* This library is still included in the `@apollo/client` package, but it no longer receives feature updates or bug fixes.
*/
export function graphql(document, operationOptions) {
if (operationOptions === void 0) { operationOptions = {}; }
switch (parser(document).type) {
case DocumentType.Mutation:
return withMutation(document, operationOptions);
case DocumentType.Subscription:
return withSubscription(document, operationOptions);
case DocumentType.Query:
default:
return withQuery(document, operationOptions);
}
}
//# sourceMappingURL=graphql.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/react/hoc/mutation-hoc.js
import { __assign, __extends, __rest } from "tslib";
import * as React from "rehackt";
import hoistNonReactStatics from "hoist-non-react-statics";
import { parser } from "../parser/index.js";
import { Mutation } from "../components/index.js";
import { defaultMapPropsToOptions, getDisplayName, calculateVariablesFromProps, GraphQLBase, } from "./hoc-utils.js";
/**
* @deprecated
* Official support for React Apollo higher order components ended in March 2020.
* This library is still included in the `@apollo/client` package, but it no longer receives feature updates or bug fixes.
*/
export function withMutation(document, operationOptions) {
if (operationOptions === void 0) { operationOptions = {}; }
// this is memoized so if coming from `graphql` there is nearly no extra cost
var operation = parser(document);
// extract options
var _a = operationOptions.options, options = _a === void 0 ? defaultMapPropsToOptions : _a, _b = operationOptions.alias, alias = _b === void 0 ? "Apollo" : _b;
var mapPropsToOptions = options;
if (typeof mapPropsToOptions !== "function")
mapPropsToOptions = function () {
return options;
};
return function (WrappedComponent) {
var graphQLDisplayName = "".concat(alias, "(").concat(getDisplayName(WrappedComponent), ")");
var GraphQL = /** @class */ (function (_super) {
__extends(GraphQL, _super);
function GraphQL() {
return _super !== null && _super.apply(this, arguments) || this;
}
GraphQL.prototype.render = function () {
var props = this.props;
var opts = mapPropsToOptions(props);
if (operationOptions.withRef) {
this.withRef = true;
props = Object.assign({}, props, {
ref: this.setWrappedInstance,
});
}
if (!opts.variables && operation.variables.length > 0) {
opts.variables = calculateVariablesFromProps(operation, props);
}
return (React.createElement(Mutation, __assign({ ignoreResults: true }, opts, { mutation: document }), function (mutate, _a) {
var _b, _c;
var data = _a.data, r = __rest(_a, ["data"]);
// the HOC's historically hoisted the data from the execution result
// up onto the result since it was passed as a nested prop
// we massage the Mutation component's shape here to replicate that
// this matches the query HoC
var result = Object.assign(r, data || {});
var name = operationOptions.name || "mutate";
var resultName = operationOptions.name ? "".concat(name, "Result") : "result";
var childProps = (_b = {},
_b[name] = mutate,
_b[resultName] = result,
_b);
if (operationOptions.props) {
var newResult = (_c = {},
_c[name] = mutate,
_c[resultName] = result,
_c.ownProps = props,
_c);
childProps = operationOptions.props(newResult);
}
return React.createElement(WrappedComponent, __assign({}, props, childProps));
}));
};
GraphQL.displayName = graphQLDisplayName;
GraphQL.WrappedComponent = WrappedComponent;
return GraphQL;
}(GraphQLBase));
// Make sure we preserve any custom statics on the original component.
return hoistNonReactStatics(GraphQL, WrappedComponent, {});
};
}
//# sourceMappingURL=mutation-hoc.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/react/hoc/subscription-hoc.js
import { __assign, __extends, __rest } from "tslib";
import * as React from "rehackt";
import hoistNonReactStatics from "hoist-non-react-statics";
import { parser } from "../parser/index.js";
import { Subscription } from "../components/index.js";
import { getDisplayName, GraphQLBase, calculateVariablesFromProps, defaultMapPropsToOptions, defaultMapPropsToSkip, } from "./hoc-utils.js";
/**
* @deprecated
* Official support for React Apollo higher order components ended in March 2020.
* This library is still included in the `@apollo/client` package, but it no longer receives feature updates or bug fixes.
*/
export function withSubscription(document, operationOptions) {
if (operationOptions === void 0) { operationOptions = {}; }
// this is memoized so if coming from `graphql` there is nearly no extra cost
var operation = parser(document);
// extract options
var _a = operationOptions.options, options = _a === void 0 ? defaultMapPropsToOptions : _a, _b = operationOptions.skip, skip = _b === void 0 ? defaultMapPropsToSkip : _b, _c = operationOptions.alias, alias = _c === void 0 ? "Apollo" : _c, shouldResubscribe = operationOptions.shouldResubscribe;
var mapPropsToOptions = options;
if (typeof mapPropsToOptions !== "function")
mapPropsToOptions = function () { return options; };
var mapPropsToSkip = skip;
if (typeof mapPropsToSkip !== "function")
mapPropsToSkip = function () { return skip; };
// allow for advanced referential equality checks
var lastResultProps;
return function (WrappedComponent) {
var graphQLDisplayName = "".concat(alias, "(").concat(getDisplayName(WrappedComponent), ")");
var GraphQL = /** @class */ (function (_super) {
__extends(GraphQL, _super);
function GraphQL(props) {
var _this = _super.call(this, props) || this;
_this.state = { resubscribe: false };
return _this;
}
GraphQL.prototype.updateResubscribe = function (resubscribe) {
this.setState({ resubscribe: resubscribe });
};
GraphQL.prototype.componentDidUpdate = function (prevProps) {
var resubscribe = !!(shouldResubscribe && shouldResubscribe(prevProps, this.props));
if (this.state.resubscribe !== resubscribe) {
this.updateResubscribe(resubscribe);
}
};
GraphQL.prototype.render = function () {
var _this = this;
var props = this.props;
var shouldSkip = mapPropsToSkip(props);
var opts = shouldSkip ? Object.create(null) : mapPropsToOptions(props);
if (!shouldSkip && !opts.variables && operation.variables.length > 0) {
opts.variables = calculateVariablesFromProps(operation, props);
}
return (React.createElement(Subscription, __assign({}, opts, { displayName: graphQLDisplayName, skip: shouldSkip, subscription: document, shouldResubscribe: this.state.resubscribe }), function (_a) {
var _b, _c;
var data = _a.data, r = __rest(_a, ["data"]);
if (operationOptions.withRef) {
_this.withRef = true;
props = Object.assign({}, props, {
ref: _this.setWrappedInstance,
});
}
// if we have skipped, no reason to manage any reshaping
if (shouldSkip) {
return (React.createElement(WrappedComponent, __assign({}, props, {})));
}
// the HOC's historically hoisted the data from the execution result
// up onto the result since it was passed as a nested prop
// we massage the Query components shape here to replicate that
var result = Object.assign(r, data || {});
var name = operationOptions.name || "data";
var childProps = (_b = {}, _b[name] = result, _b);
if (operationOptions.props) {
var newResult = (_c = {},
_c[name] = result,
_c.ownProps = props,
_c);
lastResultProps = operationOptions.props(newResult, lastResultProps);
childProps = lastResultProps;
}
return (React.createElement(WrappedComponent, __assign({}, props, childProps)));
}));
};
GraphQL.displayName = graphQLDisplayName;
GraphQL.WrappedComponent = WrappedComponent;
return GraphQL;
}(GraphQLBase));
// Make sure we preserve any custom statics on the original component.
return hoistNonReactStatics(GraphQL, WrappedComponent, {});
};
}
//# sourceMappingURL=subscription-hoc.js.map
webpack://frontend-mybets/../../node_modules/@apollo/client/react/hoc/query-hoc.js
import { __assign, __extends, __rest } from "tslib";
import * as React from "rehackt";
import hoistNonReactStatics from "hoist-non-react-statics";
import { parser } from "../parser/index.js";
import { Query } from "../components/index.js";
import { getDisplayName, GraphQLBase, calculateVariablesFromProps, defaultMapPropsToOptions, defaultMapPropsToSkip, } from "./hoc-utils.js";
/**
* @deprecated
* Official support for React Apollo higher order components ended in March 2020.
* This library is still included in the `@apollo/client` package, but it no longer receives feature updates or bug fixes.
*/
export function withQuery(document, operationOptions) {
if (operationOptions === void 0) { operationOptions = {}; }
// this is memoized so if coming from `graphql` there is nearly no extra cost
var operation = parser(document);
// extract options
var _a = operationOptions.options, options = _a === void 0 ? defaultMapPropsToOptions : _a, _b = operationOptions.skip, skip = _b === void 0 ? defaultMapPropsToSkip : _b, _c = operationOptions.alias, alias = _c === void 0 ? "Apollo" : _c;
var mapPropsToOptions = options;
if (typeof mapPropsToOptions !== "function") {
mapPropsToOptions = function () { return options; };
}
var mapPropsToSkip = skip;
if (typeof mapPropsToSkip !== "function") {
mapPropsToSkip = function () { return skip; };
}
// allow for advanced referential equality checks
var lastResultProps;
return function (WrappedComponent) {
var graphQLDisplayName = "".concat(alias, "(").concat(getDisplayName(WrappedComponent), ")");
var GraphQL = /** @class */ (function (_super) {
__extends(GraphQL, _super);
function GraphQL() {
return _super !== null && _super.apply(this, arguments) || this;
}
GraphQL.prototype.render = function () {
var _this = this;
var props = this.props;
var shouldSkip = mapPropsToSkip(props);
var opts = shouldSkip ? Object.create(null) : __assign({}, mapPropsToOptions(props));
if (!shouldSkip && !opts.variables && operation.variables.length > 0) {
opts.variables = calculateVariablesFromProps(operation, props);
}
return (React.createElement(Query, __assign({}, opts, { displayName: graphQLDisplayName, skip: shouldSkip, query: document }), function (_a) {
var _b, _c;
var _ = _a.client, data = _a.data, r = __rest(_a, ["client", "data"]);
if (operationOptions.withRef) {
_this.withRef = true;
props = Object.assign({}, props, {
ref: _this.setWrappedInstance,
});
}
// if we have skipped, no reason to manage any reshaping
if (shouldSkip) {
return (React.createElement(WrappedComponent, __assign({}, props, {})));
}
// the HOC's historically hoisted the data from the execution result
// up onto the result since it was passed as a nested prop
// we massage the Query components shape here to replicate that
var result = Object.assign(r, data || {});
var name = operationOptions.name || "data";
var childProps = (_b = {}, _b[name] = result, _b);
if (operationOptions.props) {
var newResult = (_c = {},
_c[name] = result,
_c.ownProps = props,
_c);
lastResultProps = operationOptions.props(newResult, lastResultProps);
childProps = lastResultProps;
}
return (React.createElement(WrappedComponent, __assign({}, props, childProps)));
}));
};
GraphQL.displayName = graphQLDisplayName;
GraphQL.WrappedComponent = WrappedComponent;
return GraphQL;
}(GraphQLBase));
// Make sure we preserve any custom statics on the original component.
return hoistNonReactStatics(GraphQL, WrappedComponent, {});
};
}
//# sourceMappingURL=query-hoc.js.map
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteralLoose.js
export default function _taggedTemplateLiteralLoose(strings, raw) {
if (!raw) {
raw = strings.slice(0);
}
strings.raw = raw;
return strings;
}
webpack://frontend-mybets/../../node_modules/graphql/jsutils/isObjectLike.mjs
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); }
/**
* Return true if `value` is object-like. A value is object-like if it's not
* `null` and has a `typeof` result of "object".
*/
export default function isObjectLike(value) {
return _typeof(value) == 'object' && value !== null;
}
webpack://frontend-mybets/../../node_modules/graphql/polyfills/symbols.mjs
// In ES2015 (or a polyfilled) environment, this will be Symbol.iterator // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317') export var SYMBOL_ITERATOR = typeof Symbol === 'function' && Symbol.iterator != null ? Symbol.iterator : '@@iterator'; // In ES2017 (or a polyfilled) environment, this will be Symbol.asyncIterator // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317') export var SYMBOL_ASYNC_ITERATOR = typeof Symbol === 'function' && Symbol.asyncIterator != null ? Symbol.asyncIterator : '@@asyncIterator'; // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317') export var SYMBOL_TO_STRING_TAG = typeof Symbol === 'function' && Symbol.toStringTag != null ? Symbol.toStringTag : '@@toStringTag';
webpack://frontend-mybets/../../node_modules/graphql/language/location.mjs
/**
* Represents a location in a Source.
*/
/**
* Takes a Source and a UTF-8 character offset, and returns the corresponding
* line and column as a SourceLocation.
*/
export function getLocation(source, position) {
var lineRegexp = /\r\n|[\n\r]/g;
var line = 1;
var column = position + 1;
var match;
while ((match = lineRegexp.exec(source.body)) && match.index < position) {
line += 1;
column = position + 1 - (match.index + match[0].length);
}
return {
line: line,
column: column
};
}
webpack://frontend-mybets/../../node_modules/graphql/language/printLocation.mjs
import { getLocation } from "./location.mjs";
/**
* Render a helpful description of the location in the GraphQL Source document.
*/
export function printLocation(location) {
return printSourceLocation(location.source, getLocation(location.source, location.start));
}
/**
* Render a helpful description of the location in the GraphQL Source document.
*/
export function printSourceLocation(source, sourceLocation) {
var firstLineColumnOffset = source.locationOffset.column - 1;
var body = whitespace(firstLineColumnOffset) + source.body;
var lineIndex = sourceLocation.line - 1;
var lineOffset = source.locationOffset.line - 1;
var lineNum = sourceLocation.line + lineOffset;
var columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0;
var columnNum = sourceLocation.column + columnOffset;
var locationStr = "".concat(source.name, ":").concat(lineNum, ":").concat(columnNum, "\n");
var lines = body.split(/\r\n|[\n\r]/g);
var locationLine = lines[lineIndex]; // Special case for minified documents
if (locationLine.length > 120) {
var subLineIndex = Math.floor(columnNum / 80);
var subLineColumnNum = columnNum % 80;
var subLines = [];
for (var i = 0; i < locationLine.length; i += 80) {
subLines.push(locationLine.slice(i, i + 80));
}
return locationStr + printPrefixedLines([["".concat(lineNum), subLines[0]]].concat(subLines.slice(1, subLineIndex + 1).map(function (subLine) {
return ['', subLine];
}), [[' ', whitespace(subLineColumnNum - 1) + '^'], ['', subLines[subLineIndex + 1]]]));
}
return locationStr + printPrefixedLines([// Lines specified like this: ["prefix", "string"],
["".concat(lineNum - 1), lines[lineIndex - 1]], ["".concat(lineNum), locationLine], ['', whitespace(columnNum - 1) + '^'], ["".concat(lineNum + 1), lines[lineIndex + 1]]]);
}
function printPrefixedLines(lines) {
var existingLines = lines.filter(function (_ref) {
var _ = _ref[0],
line = _ref[1];
return line !== undefined;
});
var padLen = Math.max.apply(Math, existingLines.map(function (_ref2) {
var prefix = _ref2[0];
return prefix.length;
}));
return existingLines.map(function (_ref3) {
var prefix = _ref3[0],
line = _ref3[1];
return leftPad(padLen, prefix) + (line ? ' | ' + line : ' |');
}).join('\n');
}
function whitespace(len) {
return Array(len + 1).join(' ');
}
function leftPad(len, str) {
return whitespace(len - str.length) + str;
}
webpack://frontend-mybets/../../node_modules/graphql/error/GraphQLError.mjs
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 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 _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 _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 _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 _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
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 _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
import isObjectLike from "../jsutils/isObjectLike.mjs";
import { SYMBOL_TO_STRING_TAG } from "../polyfills/symbols.mjs";
import { getLocation } from "../language/location.mjs";
import { printLocation, printSourceLocation } from "../language/printLocation.mjs";
/**
* A GraphQLError describes an Error found during the parse, validate, or
* execute phases of performing a GraphQL operation. In addition to a message
* and stack trace, it also includes information about the locations in a
* GraphQL document and/or execution result that correspond to the Error.
*/
export var GraphQLError = /*#__PURE__*/function (_Error) {
_inherits(GraphQLError, _Error);
var _super = _createSuper(GraphQLError);
/**
* An array of { line, column } locations within the source GraphQL document
* which correspond to this error.
*
* Errors during validation often contain multiple locations, for example to
* point out two things with the same name. Errors during execution include a
* single location, the field which produced the error.
*
* Enumerable, and appears in the result of JSON.stringify().
*/
/**
* An array describing the JSON-path into the execution response which
* corresponds to this error. Only included for errors during execution.
*
* Enumerable, and appears in the result of JSON.stringify().
*/
/**
* An array of GraphQL AST Nodes corresponding to this error.
*/
/**
* The source GraphQL document for the first location of this error.
*
* Note that if this Error represents more than one node, the source may not
* represent nodes after the first node.
*/
/**
* An array of character offsets within the source GraphQL document
* which correspond to this error.
*/
/**
* The original error thrown from a field resolver during execution.
*/
/**
* Extension fields to add to the formatted error.
*/
function GraphQLError(message, nodes, source, positions, path, originalError, extensions) {
var _nodeLocations, _nodeLocations2, _nodeLocations3;
var _this;
_classCallCheck(this, GraphQLError);
_this = _super.call(this, message);
_this.name = 'GraphQLError';
_this.originalError = originalError !== null && originalError !== void 0 ? originalError : undefined; // Compute list of blame nodes.
_this.nodes = undefinedIfEmpty(Array.isArray(nodes) ? nodes : nodes ? [nodes] : undefined);
var nodeLocations = [];
for (var _i2 = 0, _ref3 = (_this$nodes = _this.nodes) !== null && _this$nodes !== void 0 ? _this$nodes : []; _i2 < _ref3.length; _i2++) {
var _this$nodes;
var _ref4 = _ref3[_i2];
var loc = _ref4.loc;
if (loc != null) {
nodeLocations.push(loc);
}
}
nodeLocations = undefinedIfEmpty(nodeLocations); // Compute locations in the source for the given nodes/positions.
_this.source = source !== null && source !== void 0 ? source : (_nodeLocations = nodeLocations) === null || _nodeLocations === void 0 ? void 0 : _nodeLocations[0].source;
_this.positions = positions !== null && positions !== void 0 ? positions : (_nodeLocations2 = nodeLocations) === null || _nodeLocations2 === void 0 ? void 0 : _nodeLocations2.map(function (loc) {
return loc.start;
});
_this.locations = positions && source ? positions.map(function (pos) {
return getLocation(source, pos);
}) : (_nodeLocations3 = nodeLocations) === null || _nodeLocations3 === void 0 ? void 0 : _nodeLocations3.map(function (loc) {
return getLocation(loc.source, loc.start);
});
_this.path = path !== null && path !== void 0 ? path : undefined;
var originalExtensions = originalError === null || originalError === void 0 ? void 0 : originalError.extensions;
if (extensions == null && isObjectLike(originalExtensions)) {
_this.extensions = _objectSpread({}, originalExtensions);
} else {
_this.extensions = extensions !== null && extensions !== void 0 ? extensions : {};
} // By being enumerable, JSON.stringify will include bellow properties in the resulting output.
// This ensures that the simplest possible GraphQL service adheres to the spec.
Object.defineProperties(_assertThisInitialized(_this), {
message: {
enumerable: true
},
locations: {
enumerable: _this.locations != null
},
path: {
enumerable: _this.path != null
},
extensions: {
enumerable: _this.extensions != null && Object.keys(_this.extensions).length > 0
},
name: {
enumerable: false
},
nodes: {
enumerable: false
},
source: {
enumerable: false
},
positions: {
enumerable: false
},
originalError: {
enumerable: false
}
}); // Include (non-enumerable) stack trace.
if (originalError !== null && originalError !== void 0 && originalError.stack) {
Object.defineProperty(_assertThisInitialized(_this), 'stack', {
value: originalError.stack,
writable: true,
configurable: true
});
return _possibleConstructorReturn(_this);
} // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')
if (Error.captureStackTrace) {
Error.captureStackTrace(_assertThisInitialized(_this), GraphQLError);
} else {
Object.defineProperty(_assertThisInitialized(_this), 'stack', {
value: Error().stack,
writable: true,
configurable: true
});
}
return _this;
}
_createClass(GraphQLError, [{
key: "toString",
value: function toString() {
return printError(this);
} // FIXME: workaround to not break chai comparisons, should be remove in v16
// $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet
}, {
key: SYMBOL_TO_STRING_TAG,
get: function get() {
return 'Object';
}
}]);
return GraphQLError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
function undefinedIfEmpty(array) {
return array === undefined || array.length === 0 ? undefined : array;
}
/**
* Prints a GraphQLError to a string, representing useful location information
* about the error's position in the source.
*/
export function printError(error) {
var output = error.message;
if (error.nodes) {
for (var _i4 = 0, _error$nodes2 = error.nodes; _i4 < _error$nodes2.length; _i4++) {
var node = _error$nodes2[_i4];
if (node.loc) {
output += '\n\n' + printLocation(node.loc);
}
}
} else if (error.source && error.locations) {
for (var _i6 = 0, _error$locations2 = error.locations; _i6 < _error$locations2.length; _i6++) {
var location = _error$locations2[_i6];
output += '\n\n' + printSourceLocation(error.source, location);
}
}
return output;
}
webpack://frontend-mybets/../../node_modules/graphql/error/syntaxError.mjs
import { GraphQLError } from "./GraphQLError.mjs";
/**
* Produces a GraphQLError representing a syntax error, containing useful
* descriptive information about the syntax error's position in the source.
*/
export function syntaxError(source, position, description) {
return new GraphQLError("Syntax Error: ".concat(description), undefined, source, [position]);
}
webpack://frontend-mybets/../../node_modules/graphql/language/tokenKind.mjs
/**
* An exported enum describing the different kinds of tokens that the
* lexer emits.
*/
export var TokenKind = Object.freeze({
SOF: '<SOF>',
EOF: '<EOF>',
BANG: '!',
DOLLAR: '$',
AMP: '&',
PAREN_L: '(',
PAREN_R: ')',
SPREAD: '...',
COLON: ':',
EQUALS: '=',
AT: '@',
BRACKET_L: '[',
BRACKET_R: ']',
BRACE_L: '{',
PIPE: '|',
BRACE_R: '}',
NAME: 'Name',
INT: 'Int',
FLOAT: 'Float',
STRING: 'String',
BLOCK_STRING: 'BlockString',
COMMENT: 'Comment'
});
/**
* The enum type representing the token kinds values.
*/
webpack://frontend-mybets/../../node_modules/graphql/jsutils/devAssert.mjs
export default function devAssert(condition, message) {
var booleanCondition = Boolean(condition); // istanbul ignore else (See transformation done in './resources/inlineInvariant.js')
if (!booleanCondition) {
throw new Error(message);
}
}
webpack://frontend-mybets/../../node_modules/graphql/language/source.mjs
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; }
import { SYMBOL_TO_STRING_TAG } from "../polyfills/symbols.mjs";
import inspect from "../jsutils/inspect.mjs";
import devAssert from "../jsutils/devAssert.mjs";
import instanceOf from "../jsutils/instanceOf.mjs";
/**
* A representation of source input to GraphQL. The `name` and `locationOffset` parameters are
* optional, but they are useful for clients who store GraphQL documents in source files.
* For example, if the GraphQL input starts at line 40 in a file named `Foo.graphql`, it might
* be useful for `name` to be `"Foo.graphql"` and location to be `{ line: 40, column: 1 }`.
* The `line` and `column` properties in `locationOffset` are 1-indexed.
*/
export var Source = /*#__PURE__*/function () {
function Source(body) {
var name = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'GraphQL request';
var locationOffset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
line: 1,
column: 1
};
typeof body === 'string' || devAssert(0, "Body must be a string. Received: ".concat(inspect(body), "."));
this.body = body;
this.name = name;
this.locationOffset = locationOffset;
this.locationOffset.line > 0 || devAssert(0, 'line in locationOffset is 1-indexed and must be positive.');
this.locationOffset.column > 0 || devAssert(0, 'column in locationOffset is 1-indexed and must be positive.');
} // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet
_createClass(Source, [{
key: SYMBOL_TO_STRING_TAG,
get: function get() {
return 'Source';
}
}]);
return Source;
}();
/**
* Test if the given value is a Source object.
*
* @internal
*/
// eslint-disable-next-line no-redeclare
export function isSource(source) {
return instanceOf(source, Source);
}
webpack://frontend-mybets/../../node_modules/graphql/language/directiveLocation.mjs
/**
* The set of allowed directive location values.
*/
export var DirectiveLocation = Object.freeze({
// Request Definitions
QUERY: 'QUERY',
MUTATION: 'MUTATION',
SUBSCRIPTION: 'SUBSCRIPTION',
FIELD: 'FIELD',
FRAGMENT_DEFINITION: 'FRAGMENT_DEFINITION',
FRAGMENT_SPREAD: 'FRAGMENT_SPREAD',
INLINE_FRAGMENT: 'INLINE_FRAGMENT',
VARIABLE_DEFINITION: 'VARIABLE_DEFINITION',
// Type System Definitions
SCHEMA: 'SCHEMA',
SCALAR: 'SCALAR',
OBJECT: 'OBJECT',
FIELD_DEFINITION: 'FIELD_DEFINITION',
ARGUMENT_DEFINITION: 'ARGUMENT_DEFINITION',
INTERFACE: 'INTERFACE',
UNION: 'UNION',
ENUM: 'ENUM',
ENUM_VALUE: 'ENUM_VALUE',
INPUT_OBJECT: 'INPUT_OBJECT',
INPUT_FIELD_DEFINITION: 'INPUT_FIELD_DEFINITION'
});
/**
* The enum type representing the directive location values.
*/
webpack://frontend-mybets/../../node_modules/graphql/language/lexer.mjs
import { syntaxError } from "../error/syntaxError.mjs";
import { Token } from "./ast.mjs";
import { TokenKind } from "./tokenKind.mjs";
import { dedentBlockStringValue } from "./blockString.mjs";
/**
* Given a Source object, creates a Lexer for that source.
* A Lexer is a stateful stream generator in that every time
* it is advanced, it returns the next token in the Source. Assuming the
* source lexes, the final Token emitted by the lexer will be of kind
* EOF, after which the lexer will repeatedly return the same EOF token
* whenever called.
*/
export var Lexer = /*#__PURE__*/function () {
/**
* The previously focused non-ignored token.
*/
/**
* The currently focused non-ignored token.
*/
/**
* The (1-indexed) line containing the current token.
*/
/**
* The character offset at which the current line begins.
*/
function Lexer(source) {
var startOfFileToken = new Token(TokenKind.SOF, 0, 0, 0, 0, null);
this.source = source;
this.lastToken = startOfFileToken;
this.token = startOfFileToken;
this.line = 1;
this.lineStart = 0;
}
/**
* Advances the token stream to the next non-ignored token.
*/
var _proto = Lexer.prototype;
_proto.advance = function advance() {
this.lastToken = this.token;
var token = this.token = this.lookahead();
return token;
}
/**
* Looks ahead and returns the next non-ignored token, but does not change
* the state of Lexer.
*/
;
_proto.lookahead = function lookahead() {
var token = this.token;
if (token.kind !== TokenKind.EOF) {
do {
var _token$next;
// Note: next is only mutable during parsing, so we cast to allow this.
token = (_token$next = token.next) !== null && _token$next !== void 0 ? _token$next : token.next = readToken(this, token);
} while (token.kind === TokenKind.COMMENT);
}
return token;
};
return Lexer;
}();
/**
* @internal
*/
export function isPunctuatorTokenKind(kind) {
return kind === TokenKind.BANG || kind === TokenKind.DOLLAR || kind === TokenKind.AMP || kind === TokenKind.PAREN_L || kind === TokenKind.PAREN_R || kind === TokenKind.SPREAD || kind === TokenKind.COLON || kind === TokenKind.EQUALS || kind === TokenKind.AT || kind === TokenKind.BRACKET_L || kind === TokenKind.BRACKET_R || kind === TokenKind.BRACE_L || kind === TokenKind.PIPE || kind === TokenKind.BRACE_R;
}
function printCharCode(code) {
return (// NaN/undefined represents access beyond the end of the file.
isNaN(code) ? TokenKind.EOF : // Trust JSON for ASCII.
code < 0x007f ? JSON.stringify(String.fromCharCode(code)) : // Otherwise print the escaped form.
"\"\\u".concat(('00' + code.toString(16).toUpperCase()).slice(-4), "\"")
);
}
/**
* Gets the next token from the source starting at the given position.
*
* This skips over whitespace until it finds the next lexable token, then lexes
* punctuators immediately or calls the appropriate helper function for more
* complicated tokens.
*/
function readToken(lexer, prev) {
var source = lexer.source;
var body = source.body;
var bodyLength = body.length;
var pos = prev.end;
while (pos < bodyLength) {
var code = body.charCodeAt(pos);
var _line = lexer.line;
var _col = 1 + pos - lexer.lineStart; // SourceCharacter
switch (code) {
case 0xfeff: // <BOM>
case 9: // \t
case 32: // <space>
case 44:
// ,
++pos;
continue;
case 10:
// \n
++pos;
++lexer.line;
lexer.lineStart = pos;
continue;
case 13:
// \r
if (body.charCodeAt(pos + 1) === 10) {
pos += 2;
} else {
++pos;
}
++lexer.line;
lexer.lineStart = pos;
continue;
case 33:
// !
return new Token(TokenKind.BANG, pos, pos + 1, _line, _col, prev);
case 35:
// #
return readComment(source, pos, _line, _col, prev);
case 36:
// $
return new Token(TokenKind.DOLLAR, pos, pos + 1, _line, _col, prev);
case 38:
// &
return new Token(TokenKind.AMP, pos, pos + 1, _line, _col, prev);
case 40:
// (
return new Token(TokenKind.PAREN_L, pos, pos + 1, _line, _col, prev);
case 41:
// )
return new Token(TokenKind.PAREN_R, pos, pos + 1, _line, _col, prev);
case 46:
// .
if (body.charCodeAt(pos + 1) === 46 && body.charCodeAt(pos + 2) === 46) {
return new Token(TokenKind.SPREAD, pos, pos + 3, _line, _col, prev);
}
break;
case 58:
// :
return new Token(TokenKind.COLON, pos, pos + 1, _line, _col, prev);
case 61:
// =
return new Token(TokenKind.EQUALS, pos, pos + 1, _line, _col, prev);
case 64:
// @
return new Token(TokenKind.AT, pos, pos + 1, _line, _col, prev);
case 91:
// [
return new Token(TokenKind.BRACKET_L, pos, pos + 1, _line, _col, prev);
case 93:
// ]
return new Token(TokenKind.BRACKET_R, pos, pos + 1, _line, _col, prev);
case 123:
// {
return new Token(TokenKind.BRACE_L, pos, pos + 1, _line, _col, prev);
case 124:
// |
return new Token(TokenKind.PIPE, pos, pos + 1, _line, _col, prev);
case 125:
// }
return new Token(TokenKind.BRACE_R, pos, pos + 1, _line, _col, prev);
case 34:
// "
if (body.charCodeAt(pos + 1) === 34 && body.charCodeAt(pos + 2) === 34) {
return readBlockString(source, pos, _line, _col, prev, lexer);
}
return readString(source, pos, _line, _col, prev);
case 45: // -
case 48: // 0
case 49: // 1
case 50: // 2
case 51: // 3
case 52: // 4
case 53: // 5
case 54: // 6
case 55: // 7
case 56: // 8
case 57:
// 9
return readNumber(source, pos, code, _line, _col, prev);
case 65: // A
case 66: // B
case 67: // C
case 68: // D
case 69: // E
case 70: // F
case 71: // G
case 72: // H
case 73: // I
case 74: // J
case 75: // K
case 76: // L
case 77: // M
case 78: // N
case 79: // O
case 80: // P
case 81: // Q
case 82: // R
case 83: // S
case 84: // T
case 85: // U
case 86: // V
case 87: // W
case 88: // X
case 89: // Y
case 90: // Z
case 95: // _
case 97: // a
case 98: // b
case 99: // c
case 100: // d
case 101: // e
case 102: // f
case 103: // g
case 104: // h
case 105: // i
case 106: // j
case 107: // k
case 108: // l
case 109: // m
case 110: // n
case 111: // o
case 112: // p
case 113: // q
case 114: // r
case 115: // s
case 116: // t
case 117: // u
case 118: // v
case 119: // w
case 120: // x
case 121: // y
case 122:
// z
return readName(source, pos, _line, _col, prev);
}
throw syntaxError(source, pos, unexpectedCharacterMessage(code));
}
var line = lexer.line;
var col = 1 + pos - lexer.lineStart;
return new Token(TokenKind.EOF, bodyLength, bodyLength, line, col, prev);
}
/**
* Report a message that an unexpected character was encountered.
*/
function unexpectedCharacterMessage(code) {
if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) {
return "Cannot contain the invalid character ".concat(printCharCode(code), ".");
}
if (code === 39) {
// '
return 'Unexpected single quote character (\'), did you mean to use a double quote (")?';
}
return "Cannot parse the unexpected character ".concat(printCharCode(code), ".");
}
/**
* Reads a comment token from the source file.
*
* #[\u0009\u0020-\uFFFF]*
*/
function readComment(source, start, line, col, prev) {
var body = source.body;
var code;
var position = start;
do {
code = body.charCodeAt(++position);
} while (!isNaN(code) && ( // SourceCharacter but not LineTerminator
code > 0x001f || code === 0x0009));
return new Token(TokenKind.COMMENT, start, position, line, col, prev, body.slice(start + 1, position));
}
/**
* Reads a number token from the source file, either a float
* or an int depending on whether a decimal point appears.
*
* Int: -?(0|[1-9][0-9]*)
* Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)?
*/
function readNumber(source, start, firstCode, line, col, prev) {
var body = source.body;
var code = firstCode;
var position = start;
var isFloat = false;
if (code === 45) {
// -
code = body.charCodeAt(++position);
}
if (code === 48) {
// 0
code = body.charCodeAt(++position);
if (code >= 48 && code <= 57) {
throw syntaxError(source, position, "Invalid number, unexpected digit after 0: ".concat(printCharCode(code), "."));
}
} else {
position = readDigits(source, position, code);
code = body.charCodeAt(position);
}
if (code === 46) {
// .
isFloat = true;
code = body.charCodeAt(++position);
position = readDigits(source, position, code);
code = body.charCodeAt(position);
}
if (code === 69 || code === 101) {
// E e
isFloat = true;
code = body.charCodeAt(++position);
if (code === 43 || code === 45) {
// + -
code = body.charCodeAt(++position);
}
position = readDigits(source, position, code);
code = body.charCodeAt(position);
} // Numbers cannot be followed by . or NameStart
if (code === 46 || isNameStart(code)) {
throw syntaxError(source, position, "Invalid number, expected digit but got: ".concat(printCharCode(code), "."));
}
return new Token(isFloat ? TokenKind.FLOAT : TokenKind.INT, start, position, line, col, prev, body.slice(start, position));
}
/**
* Returns the new position in the source after reading digits.
*/
function readDigits(source, start, firstCode) {
var body = source.body;
var position = start;
var code = firstCode;
if (code >= 48 && code <= 57) {
// 0 - 9
do {
code = body.charCodeAt(++position);
} while (code >= 48 && code <= 57); // 0 - 9
return position;
}
throw syntaxError(source, position, "Invalid number, expected digit but got: ".concat(printCharCode(code), "."));
}
/**
* Reads a string token from the source file.
*
* "([^"\\\u000A\u000D]|(\\(u[0-9a-fA-F]{4}|["\\/bfnrt])))*"
*/
function readString(source, start, line, col, prev) {
var body = source.body;
var position = start + 1;
var chunkStart = position;
var code = 0;
var value = '';
while (position < body.length && !isNaN(code = body.charCodeAt(position)) && // not LineTerminator
code !== 0x000a && code !== 0x000d) {
// Closing Quote (")
if (code === 34) {
value += body.slice(chunkStart, position);
return new Token(TokenKind.STRING, start, position + 1, line, col, prev, value);
} // SourceCharacter
if (code < 0x0020 && code !== 0x0009) {
throw syntaxError(source, position, "Invalid character within String: ".concat(printCharCode(code), "."));
}
++position;
if (code === 92) {
// \
value += body.slice(chunkStart, position - 1);
code = body.charCodeAt(position);
switch (code) {
case 34:
value += '"';
break;
case 47:
value += '/';
break;
case 92:
value += '\\';
break;
case 98:
value += '\b';
break;
case 102:
value += '\f';
break;
case 110:
value += '\n';
break;
case 114:
value += '\r';
break;
case 116:
value += '\t';
break;
case 117:
{
// uXXXX
var charCode = uniCharCode(body.charCodeAt(position + 1), body.charCodeAt(position + 2), body.charCodeAt(position + 3), body.charCodeAt(position + 4));
if (charCode < 0) {
var invalidSequence = body.slice(position + 1, position + 5);
throw syntaxError(source, position, "Invalid character escape sequence: \\u".concat(invalidSequence, "."));
}
value += String.fromCharCode(charCode);
position += 4;
break;
}
default:
throw syntaxError(source, position, "Invalid character escape sequence: \\".concat(String.fromCharCode(code), "."));
}
++position;
chunkStart = position;
}
}
throw syntaxError(source, position, 'Unterminated string.');
}
/**
* Reads a block string token from the source file.
*
* """("?"?(\\"""|\\(?!=""")|[^"\\]))*"""
*/
function readBlockString(source, start, line, col, prev, lexer) {
var body = source.body;
var position = start + 3;
var chunkStart = position;
var code = 0;
var rawValue = '';
while (position < body.length && !isNaN(code = body.charCodeAt(position))) {
// Closing Triple-Quote (""")
if (code === 34 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34) {
rawValue += body.slice(chunkStart, position);
return new Token(TokenKind.BLOCK_STRING, start, position + 3, line, col, prev, dedentBlockStringValue(rawValue));
} // SourceCharacter
if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) {
throw syntaxError(source, position, "Invalid character within String: ".concat(printCharCode(code), "."));
}
if (code === 10) {
// new line
++position;
++lexer.line;
lexer.lineStart = position;
} else if (code === 13) {
// carriage return
if (body.charCodeAt(position + 1) === 10) {
position += 2;
} else {
++position;
}
++lexer.line;
lexer.lineStart = position;
} else if ( // Escape Triple-Quote (\""")
code === 92 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34 && body.charCodeAt(position + 3) === 34) {
rawValue += body.slice(chunkStart, position) + '"""';
position += 4;
chunkStart = position;
} else {
++position;
}
}
throw syntaxError(source, position, 'Unterminated string.');
}
/**
* Converts four hexadecimal chars to the integer that the
* string represents. For example, uniCharCode('0','0','0','f')
* will return 15, and uniCharCode('0','0','f','f') returns 255.
*
* Returns a negative number on error, if a char was invalid.
*
* This is implemented by noting that char2hex() returns -1 on error,
* which means the result of ORing the char2hex() will also be negative.
*/
function uniCharCode(a, b, c, d) {
return char2hex(a) << 12 | char2hex(b) << 8 | char2hex(c) << 4 | char2hex(d);
}
/**
* Converts a hex character to its integer value.
* '0' becomes 0, '9' becomes 9
* 'A' becomes 10, 'F' becomes 15
* 'a' becomes 10, 'f' becomes 15
*
* Returns -1 on error.
*/
function char2hex(a) {
return a >= 48 && a <= 57 ? a - 48 // 0-9
: a >= 65 && a <= 70 ? a - 55 // A-F
: a >= 97 && a <= 102 ? a - 87 // a-f
: -1;
}
/**
* Reads an alphanumeric + underscore name from the source.
*
* [_A-Za-z][_0-9A-Za-z]*
*/
function readName(source, start, line, col, prev) {
var body = source.body;
var bodyLength = body.length;
var position = start + 1;
var code = 0;
while (position !== bodyLength && !isNaN(code = body.charCodeAt(position)) && (code === 95 || // _
code >= 48 && code <= 57 || // 0-9
code >= 65 && code <= 90 || // A-Z
code >= 97 && code <= 122) // a-z
) {
++position;
}
return new Token(TokenKind.NAME, start, position, line, col, prev, body.slice(start, position));
} // _ A-Z a-z
function isNameStart(code) {
return code === 95 || code >= 65 && code <= 90 || code >= 97 && code <= 122;
}
webpack://frontend-mybets/../../node_modules/graphql/language/parser.mjs
import { syntaxError } from "../error/syntaxError.mjs";
import { Kind } from "./kinds.mjs";
import { Location } from "./ast.mjs";
import { TokenKind } from "./tokenKind.mjs";
import { Source, isSource } from "./source.mjs";
import { DirectiveLocation } from "./directiveLocation.mjs";
import { Lexer, isPunctuatorTokenKind } from "./lexer.mjs";
/**
* Configuration options to control parser behavior
*/
/**
* Given a GraphQL source, parses it into a Document.
* Throws GraphQLError if a syntax error is encountered.
*/
export function parse(source, options) {
var parser = new Parser(source, options);
return parser.parseDocument();
}
/**
* Given a string containing a GraphQL value (ex. `[42]`), parse the AST for
* that value.
* Throws GraphQLError if a syntax error is encountered.
*
* This is useful within tools that operate upon GraphQL Values directly and
* in isolation of complete GraphQL documents.
*
* Consider providing the results to the utility function: valueFromAST().
*/
export function parseValue(source, options) {
var parser = new Parser(source, options);
parser.expectToken(TokenKind.SOF);
var value = parser.parseValueLiteral(false);
parser.expectToken(TokenKind.EOF);
return value;
}
/**
* Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for
* that type.
* Throws GraphQLError if a syntax error is encountered.
*
* This is useful within tools that operate upon GraphQL Types directly and
* in isolation of complete GraphQL documents.
*
* Consider providing the results to the utility function: typeFromAST().
*/
export function parseType(source, options) {
var parser = new Parser(source, options);
parser.expectToken(TokenKind.SOF);
var type = parser.parseTypeReference();
parser.expectToken(TokenKind.EOF);
return type;
}
/**
* This class is exported only to assist people in implementing their own parsers
* without duplicating too much code and should be used only as last resort for cases
* such as experimental syntax or if certain features could not be contributed upstream.
*
* It is still part of the internal API and is versioned, so any changes to it are never
* considered breaking changes. If you still need to support multiple versions of the
* library, please use the `versionInfo` variable for version detection.
*
* @internal
*/
export var Parser = /*#__PURE__*/function () {
function Parser(source, options) {
var sourceObj = isSource(source) ? source : new Source(source);
this._lexer = new Lexer(sourceObj);
this._options = options;
}
/**
* Converts a name lex token into a name parse node.
*/
var _proto = Parser.prototype;
_proto.parseName = function parseName() {
var token = this.expectToken(TokenKind.NAME);
return {
kind: Kind.NAME,
value: token.value,
loc: this.loc(token)
};
} // Implements the parsing rules in the Document section.
/**
* Document : Definition+
*/
;
_proto.parseDocument = function parseDocument() {
var start = this._lexer.token;
return {
kind: Kind.DOCUMENT,
definitions: this.many(TokenKind.SOF, this.parseDefinition, TokenKind.EOF),
loc: this.loc(start)
};
}
/**
* Definition :
* - ExecutableDefinition
* - TypeSystemDefinition
* - TypeSystemExtension
*
* ExecutableDefinition :
* - OperationDefinition
* - FragmentDefinition
*/
;
_proto.parseDefinition = function parseDefinition() {
if (this.peek(TokenKind.NAME)) {
switch (this._lexer.token.value) {
case 'query':
case 'mutation':
case 'subscription':
return this.parseOperationDefinition();
case 'fragment':
return this.parseFragmentDefinition();
case 'schema':
case 'scalar':
case 'type':
case 'interface':
case 'union':
case 'enum':
case 'input':
case 'directive':
return this.parseTypeSystemDefinition();
case 'extend':
return this.parseTypeSystemExtension();
}
} else if (this.peek(TokenKind.BRACE_L)) {
return this.parseOperationDefinition();
} else if (this.peekDescription()) {
return this.parseTypeSystemDefinition();
}
throw this.unexpected();
} // Implements the parsing rules in the Operations section.
/**
* OperationDefinition :
* - SelectionSet
* - OperationType Name? VariableDefinitions? Directives? SelectionSet
*/
;
_proto.parseOperationDefinition = function parseOperationDefinition() {
var start = this._lexer.token;
if (this.peek(TokenKind.BRACE_L)) {
return {
kind: Kind.OPERATION_DEFINITION,
operation: 'query',
name: undefined,
variableDefinitions: [],
directives: [],
selectionSet: this.parseSelectionSet(),
loc: this.loc(start)
};
}
var operation = this.parseOperationType();
var name;
if (this.peek(TokenKind.NAME)) {
name = this.parseName();
}
return {
kind: Kind.OPERATION_DEFINITION,
operation: operation,
name: name,
variableDefinitions: this.parseVariableDefinitions(),
directives: this.parseDirectives(false),
selectionSet: this.parseSelectionSet(),
loc: this.loc(start)
};
}
/**
* OperationType : one of query mutation subscription
*/
;
_proto.parseOperationType = function parseOperationType() {
var operationToken = this.expectToken(TokenKind.NAME);
switch (operationToken.value) {
case 'query':
return 'query';
case 'mutation':
return 'mutation';
case 'subscription':
return 'subscription';
}
throw this.unexpected(operationToken);
}
/**
* VariableDefinitions : ( VariableDefinition+ )
*/
;
_proto.parseVariableDefinitions = function parseVariableDefinitions() {
return this.optionalMany(TokenKind.PAREN_L, this.parseVariableDefinition, TokenKind.PAREN_R);
}
/**
* VariableDefinition : Variable : Type DefaultValue? Directives[Const]?
*/
;
_proto.parseVariableDefinition = function parseVariableDefinition() {
var start = this._lexer.token;
return {
kind: Kind.VARIABLE_DEFINITION,
variable: this.parseVariable(),
type: (this.expectToken(TokenKind.COLON), this.parseTypeReference()),
defaultValue: this.expectOptionalToken(TokenKind.EQUALS) ? this.parseValueLiteral(true) : undefined,
directives: this.parseDirectives(true),
loc: this.loc(start)
};
}
/**
* Variable : $ Name
*/
;
_proto.parseVariable = function parseVariable() {
var start = this._lexer.token;
this.expectToken(TokenKind.DOLLAR);
return {
kind: Kind.VARIABLE,
name: this.parseName(),
loc: this.loc(start)
};
}
/**
* SelectionSet : { Selection+ }
*/
;
_proto.parseSelectionSet = function parseSelectionSet() {
var start = this._lexer.token;
return {
kind: Kind.SELECTION_SET,
selections: this.many(TokenKind.BRACE_L, this.parseSelection, TokenKind.BRACE_R),
loc: this.loc(start)
};
}
/**
* Selection :
* - Field
* - FragmentSpread
* - InlineFragment
*/
;
_proto.parseSelection = function parseSelection() {
return this.peek(TokenKind.SPREAD) ? this.parseFragment() : this.parseField();
}
/**
* Field : Alias? Name Arguments? Directives? SelectionSet?
*
* Alias : Name :
*/
;
_proto.parseField = function parseField() {
var start = this._lexer.token;
var nameOrAlias = this.parseName();
var alias;
var name;
if (this.expectOptionalToken(TokenKind.COLON)) {
alias = nameOrAlias;
name = this.parseName();
} else {
name = nameOrAlias;
}
return {
kind: Kind.FIELD,
alias: alias,
name: name,
arguments: this.parseArguments(false),
directives: this.parseDirectives(false),
selectionSet: this.peek(TokenKind.BRACE_L) ? this.parseSelectionSet() : undefined,
loc: this.loc(start)
};
}
/**
* Arguments[Const] : ( Argument[?Const]+ )
*/
;
_proto.parseArguments = function parseArguments(isConst) {
var item = isConst ? this.parseConstArgument : this.parseArgument;
return this.optionalMany(TokenKind.PAREN_L, item, TokenKind.PAREN_R);
}
/**
* Argument[Const] : Name : Value[?Const]
*/
;
_proto.parseArgument = function parseArgument() {
var start = this._lexer.token;
var name = this.parseName();
this.expectToken(TokenKind.COLON);
return {
kind: Kind.ARGUMENT,
name: name,
value: this.parseValueLiteral(false),
loc: this.loc(start)
};
};
_proto.parseConstArgument = function parseConstArgument() {
var start = this._lexer.token;
return {
kind: Kind.ARGUMENT,
name: this.parseName(),
value: (this.expectToken(TokenKind.COLON), this.parseValueLiteral(true)),
loc: this.loc(start)
};
} // Implements the parsing rules in the Fragments section.
/**
* Corresponds to both FragmentSpread and InlineFragment in the spec.
*
* FragmentSpread : ... FragmentName Directives?
*
* InlineFragment : ... TypeCondition? Directives? SelectionSet
*/
;
_proto.parseFragment = function parseFragment() {
var start = this._lexer.token;
this.expectToken(TokenKind.SPREAD);
var hasTypeCondition = this.expectOptionalKeyword('on');
if (!hasTypeCondition && this.peek(TokenKind.NAME)) {
return {
kind: Kind.FRAGMENT_SPREAD,
name: this.parseFragmentName(),
directives: this.parseDirectives(false),
loc: this.loc(start)
};
}
return {
kind: Kind.INLINE_FRAGMENT,
typeCondition: hasTypeCondition ? this.parseNamedType() : undefined,
directives: this.parseDirectives(false),
selectionSet: this.parseSelectionSet(),
loc: this.loc(start)
};
}
/**
* FragmentDefinition :
* - fragment FragmentName on TypeCondition Directives? SelectionSet
*
* TypeCondition : NamedType
*/
;
_proto.parseFragmentDefinition = function parseFragmentDefinition() {
var _this$_options;
var start = this._lexer.token;
this.expectKeyword('fragment'); // Experimental support for defining variables within fragments changes
// the grammar of FragmentDefinition:
// - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet
if (((_this$_options = this._options) === null || _this$_options === void 0 ? void 0 : _this$_options.experimentalFragmentVariables) === true) {
return {
kind: Kind.FRAGMENT_DEFINITION,
name: this.parseFragmentName(),
variableDefinitions: this.parseVariableDefinitions(),
typeCondition: (this.expectKeyword('on'), this.parseNamedType()),
directives: this.parseDirectives(false),
selectionSet: this.parseSelectionSet(),
loc: this.loc(start)
};
}
return {
kind: Kind.FRAGMENT_DEFINITION,
name: this.parseFragmentName(),
typeCondition: (this.expectKeyword('on'), this.parseNamedType()),
directives: this.parseDirectives(false),
selectionSet: this.parseSelectionSet(),
loc: this.loc(start)
};
}
/**
* FragmentName : Name but not `on`
*/
;
_proto.parseFragmentName = function parseFragmentName() {
if (this._lexer.token.value === 'on') {
throw this.unexpected();
}
return this.parseName();
} // Implements the parsing rules in the Values section.
/**
* Value[Const] :
* - [~Const] Variable
* - IntValue
* - FloatValue
* - StringValue
* - BooleanValue
* - NullValue
* - EnumValue
* - ListValue[?Const]
* - ObjectValue[?Const]
*
* BooleanValue : one of `true` `false`
*
* NullValue : `null`
*
* EnumValue : Name but not `true`, `false` or `null`
*/
;
_proto.parseValueLiteral = function parseValueLiteral(isConst) {
var token = this._lexer.token;
switch (token.kind) {
case TokenKind.BRACKET_L:
return this.parseList(isConst);
case TokenKind.BRACE_L:
return this.parseObject(isConst);
case TokenKind.INT:
this._lexer.advance();
return {
kind: Kind.INT,
value: token.value,
loc: this.loc(token)
};
case TokenKind.FLOAT:
this._lexer.advance();
return {
kind: Kind.FLOAT,
value: token.value,
loc: this.loc(token)
};
case TokenKind.STRING:
case TokenKind.BLOCK_STRING:
return this.parseStringLiteral();
case TokenKind.NAME:
this._lexer.advance();
switch (token.value) {
case 'true':
return {
kind: Kind.BOOLEAN,
value: true,
loc: this.loc(token)
};
case 'false':
return {
kind: Kind.BOOLEAN,
value: false,
loc: this.loc(token)
};
case 'null':
return {
kind: Kind.NULL,
loc: this.loc(token)
};
default:
return {
kind: Kind.ENUM,
value: token.value,
loc: this.loc(token)
};
}
case TokenKind.DOLLAR:
if (!isConst) {
return this.parseVariable();
}
break;
}
throw this.unexpected();
};
_proto.parseStringLiteral = function parseStringLiteral() {
var token = this._lexer.token;
this._lexer.advance();
return {
kind: Kind.STRING,
value: token.value,
block: token.kind === TokenKind.BLOCK_STRING,
loc: this.loc(token)
};
}
/**
* ListValue[Const] :
* - [ ]
* - [ Value[?Const]+ ]
*/
;
_proto.parseList = function parseList(isConst) {
var _this = this;
var start = this._lexer.token;
var item = function item() {
return _this.parseValueLiteral(isConst);
};
return {
kind: Kind.LIST,
values: this.any(TokenKind.BRACKET_L, item, TokenKind.BRACKET_R),
loc: this.loc(start)
};
}
/**
* ObjectValue[Const] :
* - { }
* - { ObjectField[?Const]+ }
*/
;
_proto.parseObject = function parseObject(isConst) {
var _this2 = this;
var start = this._lexer.token;
var item = function item() {
return _this2.parseObjectField(isConst);
};
return {
kind: Kind.OBJECT,
fields: this.any(TokenKind.BRACE_L, item, TokenKind.BRACE_R),
loc: this.loc(start)
};
}
/**
* ObjectField[Const] : Name : Value[?Const]
*/
;
_proto.parseObjectField = function parseObjectField(isConst) {
var start = this._lexer.token;
var name = this.parseName();
this.expectToken(TokenKind.COLON);
return {
kind: Kind.OBJECT_FIELD,
name: name,
value: this.parseValueLiteral(isConst),
loc: this.loc(start)
};
} // Implements the parsing rules in the Directives section.
/**
* Directives[Const] : Directive[?Const]+
*/
;
_proto.parseDirectives = function parseDirectives(isConst) {
var directives = [];
while (this.peek(TokenKind.AT)) {
directives.push(this.parseDirective(isConst));
}
return directives;
}
/**
* Directive[Const] : @ Name Arguments[?Const]?
*/
;
_proto.parseDirective = function parseDirective(isConst) {
var start = this._lexer.token;
this.expectToken(TokenKind.AT);
return {
kind: Kind.DIRECTIVE,
name: this.parseName(),
arguments: this.parseArguments(isConst),
loc: this.loc(start)
};
} // Implements the parsing rules in the Types section.
/**
* Type :
* - NamedType
* - ListType
* - NonNullType
*/
;
_proto.parseTypeReference = function parseTypeReference() {
var start = this._lexer.token;
var type;
if (this.expectOptionalToken(TokenKind.BRACKET_L)) {
type = this.parseTypeReference();
this.expectToken(TokenKind.BRACKET_R);
type = {
kind: Kind.LIST_TYPE,
type: type,
loc: this.loc(start)
};
} else {
type = this.parseNamedType();
}
if (this.expectOptionalToken(TokenKind.BANG)) {
return {
kind: Kind.NON_NULL_TYPE,
type: type,
loc: this.loc(start)
};
}
return type;
}
/**
* NamedType : Name
*/
;
_proto.parseNamedType = function parseNamedType() {
var start = this._lexer.token;
return {
kind: Kind.NAMED_TYPE,
name: this.parseName(),
loc: this.loc(start)
};
} // Implements the parsing rules in the Type Definition section.
/**
* TypeSystemDefinition :
* - SchemaDefinition
* - TypeDefinition
* - DirectiveDefinition
*
* TypeDefinition :
* - ScalarTypeDefinition
* - ObjectTypeDefinition
* - InterfaceTypeDefinition
* - UnionTypeDefinition
* - EnumTypeDefinition
* - InputObjectTypeDefinition
*/
;
_proto.parseTypeSystemDefinition = function parseTypeSystemDefinition() {
// Many definitions begin with a description and require a lookahead.
var keywordToken = this.peekDescription() ? this._lexer.lookahead() : this._lexer.token;
if (keywordToken.kind === TokenKind.NAME) {
switch (keywordToken.value) {
case 'schema':
return this.parseSchemaDefinition();
case 'scalar':
return this.parseScalarTypeDefinition();
case 'type':
return this.parseObjectTypeDefinition();
case 'interface':
return this.parseInterfaceTypeDefinition();
case 'union':
return this.parseUnionTypeDefinition();
case 'enum':
return this.parseEnumTypeDefinition();
case 'input':
return this.parseInputObjectTypeDefinition();
case 'directive':
return this.parseDirectiveDefinition();
}
}
throw this.unexpected(keywordToken);
};
_proto.peekDescription = function peekDescription() {
return this.peek(TokenKind.STRING) || this.peek(TokenKind.BLOCK_STRING);
}
/**
* Description : StringValue
*/
;
_proto.parseDescription = function parseDescription() {
if (this.peekDescription()) {
return this.parseStringLiteral();
}
}
/**
* SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ }
*/
;
_proto.parseSchemaDefinition = function parseSchemaDefinition() {
var start = this._lexer.token;
var description = this.parseDescription();
this.expectKeyword('schema');
var directives = this.parseDirectives(true);
var operationTypes = this.many(TokenKind.BRACE_L, this.parseOperationTypeDefinition, TokenKind.BRACE_R);
return {
kind: Kind.SCHEMA_DEFINITION,
description: description,
directives: directives,
operationTypes: operationTypes,
loc: this.loc(start)
};
}
/**
* OperationTypeDefinition : OperationType : NamedType
*/
;
_proto.parseOperationTypeDefinition = function parseOperationTypeDefinition() {
var start = this._lexer.token;
var operation = this.parseOperationType();
this.expectToken(TokenKind.COLON);
var type = this.parseNamedType();
return {
kind: Kind.OPERATION_TYPE_DEFINITION,
operation: operation,
type: type,
loc: this.loc(start)
};
}
/**
* ScalarTypeDefinition : Description? scalar Name Directives[Const]?
*/
;
_proto.parseScalarTypeDefinition = function parseScalarTypeDefinition() {
var start = this._lexer.token;
var description = this.parseDescription();
this.expectKeyword('scalar');
var name = this.parseName();
var directives = this.parseDirectives(true);
return {
kind: Kind.SCALAR_TYPE_DEFINITION,
description: description,
name: name,
directives: directives,
loc: this.loc(start)
};
}
/**
* ObjectTypeDefinition :
* Description?
* type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition?
*/
;
_proto.parseObjectTypeDefinition = function parseObjectTypeDefinition() {
var start = this._lexer.token;
var description = this.parseDescription();
this.expectKeyword('type');
var name = this.parseName();
var interfaces = this.parseImplementsInterfaces();
var directives = this.parseDirectives(true);
var fields = this.parseFieldsDefinition();
return {
kind: Kind.OBJECT_TYPE_DEFINITION,
description: description,
name: name,
interfaces: interfaces,
directives: directives,
fields: fields,
loc: this.loc(start)
};
}
/**
* ImplementsInterfaces :
* - implements `&`? NamedType
* - ImplementsInterfaces & NamedType
*/
;
_proto.parseImplementsInterfaces = function parseImplementsInterfaces() {
var _this$_options2;
if (!this.expectOptionalKeyword('implements')) {
return [];
}
if (((_this$_options2 = this._options) === null || _this$_options2 === void 0 ? void 0 : _this$_options2.allowLegacySDLImplementsInterfaces) === true) {
var types = []; // Optional leading ampersand
this.expectOptionalToken(TokenKind.AMP);
do {
types.push(this.parseNamedType());
} while (this.expectOptionalToken(TokenKind.AMP) || this.peek(TokenKind.NAME));
return types;
}
return this.delimitedMany(TokenKind.AMP, this.parseNamedType);
}
/**
* FieldsDefinition : { FieldDefinition+ }
*/
;
_proto.parseFieldsDefinition = function parseFieldsDefinition() {
var _this$_options3;
// Legacy support for the SDL?
if (((_this$_options3 = this._options) === null || _this$_options3 === void 0 ? void 0 : _this$_options3.allowLegacySDLEmptyFields) === true && this.peek(TokenKind.BRACE_L) && this._lexer.lookahead().kind === TokenKind.BRACE_R) {
this._lexer.advance();
this._lexer.advance();
return [];
}
return this.optionalMany(TokenKind.BRACE_L, this.parseFieldDefinition, TokenKind.BRACE_R);
}
/**
* FieldDefinition :
* - Description? Name ArgumentsDefinition? : Type Directives[Const]?
*/
;
_proto.parseFieldDefinition = function parseFieldDefinition() {
var start = this._lexer.token;
var description = this.parseDescription();
var name = this.parseName();
var args = this.parseArgumentDefs();
this.expectToken(TokenKind.COLON);
var type = this.parseTypeReference();
var directives = this.parseDirectives(true);
return {
kind: Kind.FIELD_DEFINITION,
description: description,
name: name,
arguments: args,
type: type,
directives: directives,
loc: this.loc(start)
};
}
/**
* ArgumentsDefinition : ( InputValueDefinition+ )
*/
;
_proto.parseArgumentDefs = function parseArgumentDefs() {
return this.optionalMany(TokenKind.PAREN_L, this.parseInputValueDef, TokenKind.PAREN_R);
}
/**
* InputValueDefinition :
* - Description? Name : Type DefaultValue? Directives[Const]?
*/
;
_proto.parseInputValueDef = function parseInputValueDef() {
var start = this._lexer.token;
var description = this.parseDescription();
var name = this.parseName();
this.expectToken(TokenKind.COLON);
var type = this.parseTypeReference();
var defaultValue;
if (this.expectOptionalToken(TokenKind.EQUALS)) {
defaultValue = this.parseValueLiteral(true);
}
var directives = this.parseDirectives(true);
return {
kind: Kind.INPUT_VALUE_DEFINITION,
description: description,
name: name,
type: type,
defaultValue: defaultValue,
directives: directives,
loc: this.loc(start)
};
}
/**
* InterfaceTypeDefinition :
* - Description? interface Name Directives[Const]? FieldsDefinition?
*/
;
_proto.parseInterfaceTypeDefinition = function parseInterfaceTypeDefinition() {
var start = this._lexer.token;
var description = this.parseDescription();
this.expectKeyword('interface');
var name = this.parseName();
var interfaces = this.parseImplementsInterfaces();
var directives = this.parseDirectives(true);
var fields = this.parseFieldsDefinition();
return {
kind: Kind.INTERFACE_TYPE_DEFINITION,
description: description,
name: name,
interfaces: interfaces,
directives: directives,
fields: fields,
loc: this.loc(start)
};
}
/**
* UnionTypeDefinition :
* - Description? union Name Directives[Const]? UnionMemberTypes?
*/
;
_proto.parseUnionTypeDefinition = function parseUnionTypeDefinition() {
var start = this._lexer.token;
var description = this.parseDescription();
this.expectKeyword('union');
var name = this.parseName();
var directives = this.parseDirectives(true);
var types = this.parseUnionMemberTypes();
return {
kind: Kind.UNION_TYPE_DEFINITION,
description: description,
name: name,
directives: directives,
types: types,
loc: this.loc(start)
};
}
/**
* UnionMemberTypes :
* - = `|`? NamedType
* - UnionMemberTypes | NamedType
*/
;
_proto.parseUnionMemberTypes = function parseUnionMemberTypes() {
return this.expectOptionalToken(TokenKind.EQUALS) ? this.delimitedMany(TokenKind.PIPE, this.parseNamedType) : [];
}
/**
* EnumTypeDefinition :
* - Description? enum Name Directives[Const]? EnumValuesDefinition?
*/
;
_proto.parseEnumTypeDefinition = function parseEnumTypeDefinition() {
var start = this._lexer.token;
var description = this.parseDescription();
this.expectKeyword('enum');
var name = this.parseName();
var directives = this.parseDirectives(true);
var values = this.parseEnumValuesDefinition();
return {
kind: Kind.ENUM_TYPE_DEFINITION,
description: description,
name: name,
directives: directives,
values: values,
loc: this.loc(start)
};
}
/**
* EnumValuesDefinition : { EnumValueDefinition+ }
*/
;
_proto.parseEnumValuesDefinition = function parseEnumValuesDefinition() {
return this.optionalMany(TokenKind.BRACE_L, this.parseEnumValueDefinition, TokenKind.BRACE_R);
}
/**
* EnumValueDefinition : Description? EnumValue Directives[Const]?
*
* EnumValue : Name
*/
;
_proto.parseEnumValueDefinition = function parseEnumValueDefinition() {
var start = this._lexer.token;
var description = this.parseDescription();
var name = this.parseName();
var directives = this.parseDirectives(true);
return {
kind: Kind.ENUM_VALUE_DEFINITION,
description: description,
name: name,
directives: directives,
loc: this.loc(start)
};
}
/**
* InputObjectTypeDefinition :
* - Description? input Name Directives[Const]? InputFieldsDefinition?
*/
;
_proto.parseInputObjectTypeDefinition = function parseInputObjectTypeDefinition() {
var start = this._lexer.token;
var description = this.parseDescription();
this.expectKeyword('input');
var name = this.parseName();
var directives = this.parseDirectives(true);
var fields = this.parseInputFieldsDefinition();
return {
kind: Kind.INPUT_OBJECT_TYPE_DEFINITION,
description: description,
name: name,
directives: directives,
fields: fields,
loc: this.loc(start)
};
}
/**
* InputFieldsDefinition : { InputValueDefinition+ }
*/
;
_proto.parseInputFieldsDefinition = function parseInputFieldsDefinition() {
return this.optionalMany(TokenKind.BRACE_L, this.parseInputValueDef, TokenKind.BRACE_R);
}
/**
* TypeSystemExtension :
* - SchemaExtension
* - TypeExtension
*
* TypeExtension :
* - ScalarTypeExtension
* - ObjectTypeExtension
* - InterfaceTypeExtension
* - UnionTypeExtension
* - EnumTypeExtension
* - InputObjectTypeDefinition
*/
;
_proto.parseTypeSystemExtension = function parseTypeSystemExtension() {
var keywordToken = this._lexer.lookahead();
if (keywordToken.kind === TokenKind.NAME) {
switch (keywordToken.value) {
case 'schema':
return this.parseSchemaExtension();
case 'scalar':
return this.parseScalarTypeExtension();
case 'type':
return this.parseObjectTypeExtension();
case 'interface':
return this.parseInterfaceTypeExtension();
case 'union':
return this.parseUnionTypeExtension();
case 'enum':
return this.parseEnumTypeExtension();
case 'input':
return this.parseInputObjectTypeExtension();
}
}
throw this.unexpected(keywordToken);
}
/**
* SchemaExtension :
* - extend schema Directives[Const]? { OperationTypeDefinition+ }
* - extend schema Directives[Const]
*/
;
_proto.parseSchemaExtension = function parseSchemaExtension() {
var start = this._lexer.token;
this.expectKeyword('extend');
this.expectKeyword('schema');
var directives = this.parseDirectives(true);
var operationTypes = this.optionalMany(TokenKind.BRACE_L, this.parseOperationTypeDefinition, TokenKind.BRACE_R);
if (directives.length === 0 && operationTypes.length === 0) {
throw this.unexpected();
}
return {
kind: Kind.SCHEMA_EXTENSION,
directives: directives,
operationTypes: operationTypes,
loc: this.loc(start)
};
}
/**
* ScalarTypeExtension :
* - extend scalar Name Directives[Const]
*/
;
_proto.parseScalarTypeExtension = function parseScalarTypeExtension() {
var start = this._lexer.token;
this.expectKeyword('extend');
this.expectKeyword('scalar');
var name = this.parseName();
var directives = this.parseDirectives(true);
if (directives.length === 0) {
throw this.unexpected();
}
return {
kind: Kind.SCALAR_TYPE_EXTENSION,
name: name,
directives: directives,
loc: this.loc(start)
};
}
/**
* ObjectTypeExtension :
* - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition
* - extend type Name ImplementsInterfaces? Directives[Const]
* - extend type Name ImplementsInterfaces
*/
;
_proto.parseObjectTypeExtension = function parseObjectTypeExtension() {
var start = this._lexer.token;
this.expectKeyword('extend');
this.expectKeyword('type');
var name = this.parseName();
var interfaces = this.parseImplementsInterfaces();
var directives = this.parseDirectives(true);
var fields = this.parseFieldsDefinition();
if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) {
throw this.unexpected();
}
return {
kind: Kind.OBJECT_TYPE_EXTENSION,
name: name,
interfaces: interfaces,
directives: directives,
fields: fields,
loc: this.loc(start)
};
}
/**
* InterfaceTypeExtension :
* - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition
* - extend interface Name ImplementsInterfaces? Directives[Const]
* - extend interface Name ImplementsInterfaces
*/
;
_proto.parseInterfaceTypeExtension = function parseInterfaceTypeExtension() {
var start = this._lexer.token;
this.expectKeyword('extend');
this.expectKeyword('interface');
var name = this.parseName();
var interfaces = this.parseImplementsInterfaces();
var directives = this.parseDirectives(true);
var fields = this.parseFieldsDefinition();
if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) {
throw this.unexpected();
}
return {
kind: Kind.INTERFACE_TYPE_EXTENSION,
name: name,
interfaces: interfaces,
directives: directives,
fields: fields,
loc: this.loc(start)
};
}
/**
* UnionTypeExtension :
* - extend union Name Directives[Const]? UnionMemberTypes
* - extend union Name Directives[Const]
*/
;
_proto.parseUnionTypeExtension = function parseUnionTypeExtension() {
var start = this._lexer.token;
this.expectKeyword('extend');
this.expectKeyword('union');
var name = this.parseName();
var directives = this.parseDirectives(true);
var types = this.parseUnionMemberTypes();
if (directives.length === 0 && types.length === 0) {
throw this.unexpected();
}
return {
kind: Kind.UNION_TYPE_EXTENSION,
name: name,
directives: directives,
types: types,
loc: this.loc(start)
};
}
/**
* EnumTypeExtension :
* - extend enum Name Directives[Const]? EnumValuesDefinition
* - extend enum Name Directives[Const]
*/
;
_proto.parseEnumTypeExtension = function parseEnumTypeExtension() {
var start = this._lexer.token;
this.expectKeyword('extend');
this.expectKeyword('enum');
var name = this.parseName();
var directives = this.parseDirectives(true);
var values = this.parseEnumValuesDefinition();
if (directives.length === 0 && values.length === 0) {
throw this.unexpected();
}
return {
kind: Kind.ENUM_TYPE_EXTENSION,
name: name,
directives: directives,
values: values,
loc: this.loc(start)
};
}
/**
* InputObjectTypeExtension :
* - extend input Name Directives[Const]? InputFieldsDefinition
* - extend input Name Directives[Const]
*/
;
_proto.parseInputObjectTypeExtension = function parseInputObjectTypeExtension() {
var start = this._lexer.token;
this.expectKeyword('extend');
this.expectKeyword('input');
var name = this.parseName();
var directives = this.parseDirectives(true);
var fields = this.parseInputFieldsDefinition();
if (directives.length === 0 && fields.length === 0) {
throw this.unexpected();
}
return {
kind: Kind.INPUT_OBJECT_TYPE_EXTENSION,
name: name,
directives: directives,
fields: fields,
loc: this.loc(start)
};
}
/**
* DirectiveDefinition :
* - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations
*/
;
_proto.parseDirectiveDefinition = function parseDirectiveDefinition() {
var start = this._lexer.token;
var description = this.parseDescription();
this.expectKeyword('directive');
this.expectToken(TokenKind.AT);
var name = this.parseName();
var args = this.parseArgumentDefs();
var repeatable = this.expectOptionalKeyword('repeatable');
this.expectKeyword('on');
var locations = this.parseDirectiveLocations();
return {
kind: Kind.DIRECTIVE_DEFINITION,
description: description,
name: name,
arguments: args,
repeatable: repeatable,
locations: locations,
loc: this.loc(start)
};
}
/**
* DirectiveLocations :
* - `|`? DirectiveLocation
* - DirectiveLocations | DirectiveLocation
*/
;
_proto.parseDirectiveLocations = function parseDirectiveLocations() {
return this.delimitedMany(TokenKind.PIPE, this.parseDirectiveLocation);
}
/*
* DirectiveLocation :
* - ExecutableDirectiveLocation
* - TypeSystemDirectiveLocation
*
* ExecutableDirectiveLocation : one of
* `QUERY`
* `MUTATION`
* `SUBSCRIPTION`
* `FIELD`
* `FRAGMENT_DEFINITION`
* `FRAGMENT_SPREAD`
* `INLINE_FRAGMENT`
*
* TypeSystemDirectiveLocation : one of
* `SCHEMA`
* `SCALAR`
* `OBJECT`
* `FIELD_DEFINITION`
* `ARGUMENT_DEFINITION`
* `INTERFACE`
* `UNION`
* `ENUM`
* `ENUM_VALUE`
* `INPUT_OBJECT`
* `INPUT_FIELD_DEFINITION`
*/
;
_proto.parseDirectiveLocation = function parseDirectiveLocation() {
var start = this._lexer.token;
var name = this.parseName();
if (DirectiveLocation[name.value] !== undefined) {
return name;
}
throw this.unexpected(start);
} // Core parsing utility functions
/**
* Returns a location object, used to identify the place in the source that created a given parsed object.
*/
;
_proto.loc = function loc(startToken) {
var _this$_options4;
if (((_this$_options4 = this._options) === null || _this$_options4 === void 0 ? void 0 : _this$_options4.noLocation) !== true) {
return new Location(startToken, this._lexer.lastToken, this._lexer.source);
}
}
/**
* Determines if the next token is of a given kind
*/
;
_proto.peek = function peek(kind) {
return this._lexer.token.kind === kind;
}
/**
* If the next token is of the given kind, return that token after advancing the lexer.
* Otherwise, do not change the parser state and throw an error.
*/
;
_proto.expectToken = function expectToken(kind) {
var token = this._lexer.token;
if (token.kind === kind) {
this._lexer.advance();
return token;
}
throw syntaxError(this._lexer.source, token.start, "Expected ".concat(getTokenKindDesc(kind), ", found ").concat(getTokenDesc(token), "."));
}
/**
* If the next token is of the given kind, return that token after advancing the lexer.
* Otherwise, do not change the parser state and return undefined.
*/
;
_proto.expectOptionalToken = function expectOptionalToken(kind) {
var token = this._lexer.token;
if (token.kind === kind) {
this._lexer.advance();
return token;
}
return undefined;
}
/**
* If the next token is a given keyword, advance the lexer.
* Otherwise, do not change the parser state and throw an error.
*/
;
_proto.expectKeyword = function expectKeyword(value) {
var token = this._lexer.token;
if (token.kind === TokenKind.NAME && token.value === value) {
this._lexer.advance();
} else {
throw syntaxError(this._lexer.source, token.start, "Expected \"".concat(value, "\", found ").concat(getTokenDesc(token), "."));
}
}
/**
* If the next token is a given keyword, return "true" after advancing the lexer.
* Otherwise, do not change the parser state and return "false".
*/
;
_proto.expectOptionalKeyword = function expectOptionalKeyword(value) {
var token = this._lexer.token;
if (token.kind === TokenKind.NAME && token.value === value) {
this._lexer.advance();
return true;
}
return false;
}
/**
* Helper function for creating an error when an unexpected lexed token is encountered.
*/
;
_proto.unexpected = function unexpected(atToken) {
var token = atToken !== null && atToken !== void 0 ? atToken : this._lexer.token;
return syntaxError(this._lexer.source, token.start, "Unexpected ".concat(getTokenDesc(token), "."));
}
/**
* Returns a possibly empty list of parse nodes, determined by the parseFn.
* This list begins with a lex token of openKind and ends with a lex token of closeKind.
* Advances the parser to the next lex token after the closing token.
*/
;
_proto.any = function any(openKind, parseFn, closeKind) {
this.expectToken(openKind);
var nodes = [];
while (!this.expectOptionalToken(closeKind)) {
nodes.push(parseFn.call(this));
}
return nodes;
}
/**
* Returns a list of parse nodes, determined by the parseFn.
* It can be empty only if open token is missing otherwise it will always return non-empty list
* that begins with a lex token of openKind and ends with a lex token of closeKind.
* Advances the parser to the next lex token after the closing token.
*/
;
_proto.optionalMany = function optionalMany(openKind, parseFn, closeKind) {
if (this.expectOptionalToken(openKind)) {
var nodes = [];
do {
nodes.push(parseFn.call(this));
} while (!this.expectOptionalToken(closeKind));
return nodes;
}
return [];
}
/**
* Returns a non-empty list of parse nodes, determined by the parseFn.
* This list begins with a lex token of openKind and ends with a lex token of closeKind.
* Advances the parser to the next lex token after the closing token.
*/
;
_proto.many = function many(openKind, parseFn, closeKind) {
this.expectToken(openKind);
var nodes = [];
do {
nodes.push(parseFn.call(this));
} while (!this.expectOptionalToken(closeKind));
return nodes;
}
/**
* Returns a non-empty list of parse nodes, determined by the parseFn.
* This list may begin with a lex token of delimiterKind followed by items separated by lex tokens of tokenKind.
* Advances the parser to the next lex token after last item in the list.
*/
;
_proto.delimitedMany = function delimitedMany(delimiterKind, parseFn) {
this.expectOptionalToken(delimiterKind);
var nodes = [];
do {
nodes.push(parseFn.call(this));
} while (this.expectOptionalToken(delimiterKind));
return nodes;
};
return Parser;
}();
/**
* A helper function to describe a token as a string for debugging.
*/
function getTokenDesc(token) {
var value = token.value;
return getTokenKindDesc(token.kind) + (value != null ? " \"".concat(value, "\"") : '');
}
/**
* A helper function to describe a token kind as a string for debugging.
*/
function getTokenKindDesc(kind) {
return isPunctuatorTokenKind(kind) ? "\"".concat(kind, "\"") : kind;
}
webpack://frontend-mybets/../../node_modules/@apollo/client/node_modules/graphql-tag/lib/index.js
import { __assign } from "tslib";
import { parse } from 'graphql';
var docCache = new Map();
var fragmentSourceMap = new Map();
var printFragmentWarnings = true;
var experimentalFragmentVariables = false;
function normalize(string) {
return string.replace(/[\s,]+/g, ' ').trim();
}
function cacheKeyFromLoc(loc) {
return normalize(loc.source.body.substring(loc.start, loc.end));
}
function processFragments(ast) {
var seenKeys = new Set();
var definitions = [];
ast.definitions.forEach(function (fragmentDefinition) {
if (fragmentDefinition.kind === 'FragmentDefinition') {
var fragmentName = fragmentDefinition.name.value;
var sourceKey = cacheKeyFromLoc(fragmentDefinition.loc);
var sourceKeySet = fragmentSourceMap.get(fragmentName);
if (sourceKeySet && !sourceKeySet.has(sourceKey)) {
if (printFragmentWarnings) {
console.warn("Warning: fragment with name " + fragmentName + " already exists.\n"
+ "graphql-tag enforces all fragment names across your application to be unique; read more about\n"
+ "this in the docs: http://dev.apollodata.com/core/fragments.html#unique-names");
}
}
else if (!sourceKeySet) {
fragmentSourceMap.set(fragmentName, sourceKeySet = new Set);
}
sourceKeySet.add(sourceKey);
if (!seenKeys.has(sourceKey)) {
seenKeys.add(sourceKey);
definitions.push(fragmentDefinition);
}
}
else {
definitions.push(fragmentDefinition);
}
});
return __assign(__assign({}, ast), { definitions: definitions });
}
function stripLoc(doc) {
var workSet = new Set(doc.definitions);
workSet.forEach(function (node) {
if (node.loc)
delete node.loc;
Object.keys(node).forEach(function (key) {
var value = node[key];
if (value && typeof value === 'object') {
workSet.add(value);
}
});
});
var loc = doc.loc;
if (loc) {
delete loc.startToken;
delete loc.endToken;
}
return doc;
}
function parseDocument(source) {
var cacheKey = normalize(source);
if (!docCache.has(cacheKey)) {
var parsed = parse(source, {
experimentalFragmentVariables: experimentalFragmentVariables,
allowLegacyFragmentVariables: experimentalFragmentVariables
});
if (!parsed || parsed.kind !== 'Document') {
throw new Error('Not a valid GraphQL document.');
}
docCache.set(cacheKey, stripLoc(processFragments(parsed)));
}
return docCache.get(cacheKey);
}
export function gql(literals) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
if (typeof literals === 'string') {
literals = [literals];
}
var result = literals[0];
args.forEach(function (arg, i) {
if (arg && arg.kind === 'Document') {
result += arg.loc.source.body;
}
else {
result += arg;
}
result += literals[i + 1];
});
return parseDocument(result);
}
export function resetCaches() {
docCache.clear();
fragmentSourceMap.clear();
}
export function disableFragmentWarnings() {
printFragmentWarnings = false;
}
export function enableExperimentalFragmentVariables() {
experimentalFragmentVariables = true;
}
export function disableExperimentalFragmentVariables() {
experimentalFragmentVariables = false;
}
var extras = {
gql: gql,
resetCaches: resetCaches,
disableFragmentWarnings: disableFragmentWarnings,
enableExperimentalFragmentVariables: enableExperimentalFragmentVariables,
disableExperimentalFragmentVariables: disableExperimentalFragmentVariables
};
(function (gql_1) {
gql_1.gql = extras.gql, gql_1.resetCaches = extras.resetCaches, gql_1.disableFragmentWarnings = extras.disableFragmentWarnings, gql_1.enableExperimentalFragmentVariables = extras.enableExperimentalFragmentVariables, gql_1.disableExperimentalFragmentVariables = extras.disableExperimentalFragmentVariables;
})(gql || (gql = {}));
gql["default"] = gql;
export default gql;
//# sourceMappingURL=index.js.map
webpack://frontend-mybets/../../packages/tvg-lib-custom-hooks/hooks/usePrevious.ts
import { useEffect, useRef } from "react";
// custom hook for getting previous value
export const usePrevious = <T = string>(value: T) => {
const ref = useRef<T>();
useEffect(() => {
ref.current = value;
});
return ref.current;
};
export default usePrevious;
webpack://frontend-mybets/../../packages/tvg-lib-custom-hooks/hooks/useIsomorphicLayoutEffect.ts
import { useLayoutEffect, useEffect } from "react";
const useIsomorphicLayoutEffect =
typeof window !== "undefined" ? useLayoutEffect : useEffect;
export default useIsomorphicLayoutEffect;
webpack://frontend-mybets/../../packages/tvg-lib-utils/modalV2.js
import { noop } from "lodash";
import useFakeInput from "./useFakeInput";
export const toggleBodyClass = (
show,
bodyPositionY,
setBodyPositionY,
device
) => {
const isNotDesktop = /mobile|tablet/.test(device);
if (typeof window !== "undefined" && document.body) {
if (show) {
setBodyPositionY(window.pageYOffset);
document.body.style.top = `-${window.pageYOffset}px`;
} else {
window.scrollTo(0, bodyPositionY);
document.body.style.top = "";
}
return isNotDesktop && document.body.classList.toggle("modal", show);
}
return undefined;
};
export const closeModalWrapper = (
callback = noop,
{
useFakeInput: propsUseFakeInput,
device,
isLastModal,
setIsOpen,
bodyPositionY,
setBodyPositionY
}
) => {
if (propsUseFakeInput) {
useFakeInput();
}
window.focus();
setIsOpen(false);
callback();
if (isLastModal) {
toggleBodyClass(false, bodyPositionY, setBodyPositionY, device);
}
};
webpack://frontend-mybets/../../packages/tvg-lib-utils/useFakeInput.js
const useFakeInput = () => {
setTimeout(() => {
const fakeInput = document.createElement("input");
fakeInput.type = "text";
document.body.insertBefore(fakeInput, document.body.firstChild);
fakeInput.focus();
setTimeout(() => {
document.body.removeChild(fakeInput);
window.focus();
}, 10);
});
};
export default useFakeInput;
webpack://frontend-mybets/../../packages/tvg-lib-custom-hooks/hooks/useModalV2Core.ts
import { useEffect, useState } from "react";
import type { NullaryFn } from "@tvg/ts-types/Functional";
import type { Device } from "@tvg/ts-types/Device";
import { closeModalWrapper, toggleBodyClass } from "@tvg/utils/modalV2";
import usePrevious from "./usePrevious";
// Custom hook for core logic of ModalV2 in MEP and FDR
export const useModalV2Core = (
isOpenProp: boolean,
useFakeInput: boolean,
isLastModal: boolean,
device: Device,
onOpen: NullaryFn<unknown>,
forceModalTop: boolean = false,
modalWrapperElementId: string = "modals"
) => {
const previousPropsIsOpen = usePrevious(isOpenProp);
const [isOpenState, setIsOpen] = useState(isOpenProp);
const [bodyPositionY, setBodyPositionY] = useState(0);
const [element, setElement] = useState<HTMLDivElement | null>(null);
const [root, setRoot] = useState<HTMLElement | null>(null);
const [readyToRender, setReadyToRender] = useState(false);
const openModal = () => {
setIsOpen(true);
onOpen();
if (isLastModal) {
toggleBodyClass(true, bodyPositionY, setBodyPositionY, device);
}
};
useEffect(() => {
if (isOpenProp) {
toggleBodyClass(true, bodyPositionY, setBodyPositionY, device);
}
if (
previousPropsIsOpen !== undefined &&
isOpenProp !== previousPropsIsOpen
) {
if (!isOpenProp) {
closeModalWrapper(() => {}, {
useFakeInput,
device,
isLastModal,
setIsOpen,
bodyPositionY,
setBodyPositionY
});
}
if (isOpenProp) {
openModal();
}
}
}, [isOpenProp, previousPropsIsOpen]);
useEffect(() => {
if (typeof window !== "undefined") {
const div = document.createElement("div");
if (forceModalTop) {
div.classList.add("forceModalTop");
}
setElement(div);
const modalWrapper =
document.getElementById(modalWrapperElementId) || document.body;
setRoot(modalWrapper);
}
}, []);
useEffect(() => {
if (element && root) {
root.appendChild(element);
setReadyToRender(true);
}
return () => {
if (root && element) {
root.removeChild(element);
}
};
}, [root, element]);
return {
isOpen: isOpenState,
setIsOpen,
bodyPositionY,
setBodyPositionY,
readyToRender,
element
};
};
export default useModalV2Core;
webpack://frontend-mybets/../../packages/tvg-lib-custom-hooks/hooks/useModalV2Resize.ts
import { useEffect } from "react";
import usePrevious from "./usePrevious";
import useForceUpdate from "./useForceUpdate";
// Custom hook to handle Modal js file on each ModalV2 from MEP and FDR
export const useModalV2Resize = (isOpen: boolean) => {
const forceUpdate = useForceUpdate();
const previousIsOpen = usePrevious(isOpen);
const onResize = () => {
setTimeout(() => {
forceUpdate();
}, 100);
};
useEffect(() => {
if (!previousIsOpen && isOpen && typeof window !== "undefined") {
window.addEventListener("resize", onResize);
// major hack for for resize on ios
setTimeout(() => {
forceUpdate();
}, 200);
} else if (previousIsOpen && !isOpen && typeof window !== "undefined") {
window.removeEventListener("resize", onResize);
}
return () => {
if (typeof window !== "undefined") {
window.removeEventListener("resize", onResize);
}
};
}, [isOpen]);
};
export default useModalV2Resize;
webpack://frontend-mybets/../../packages/tvg-lib-custom-hooks/hooks/useForceUpdate.ts
import { useState } from "react";
const useForceUpdate = () => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [value, setValue] = useState(0);
return () => setValue((val) => val + 1);
};
export default useForceUpdate;
webpack://frontend-mybets/../../packages/tvg-lib-custom-hooks/hooks/useNavigate.ts
import {
useNavigate as useRouterNavigate,
useLocation
} from "react-router-dom";
const useNavigate = () => ({
push: useRouterNavigate(),
location: useLocation()
});
export default useNavigate;
webpack://frontend-mybets/../../packages/tvg-lib-ts-types/Race.ts
import { NullaryFn } from "./Functional";
import { WagerType, WagerTypeCodesEnum } from "./Wager";
import { Talent } from "./Talent";
import { TalentPickData } from "./TalentPicks";
import { TopPool } from "./Pool";
import { SpecialCardSourceRace } from "./SpecialWager";
export type RaceStatusTypeCode = "SK" | "RO" | "O" | "IC";
export interface RaceStatusType {
code: RaceStatusTypeCode;
}
export enum RaceStatusEnum {
OPEN = "O",
UP_NEXT = "IC",
RACE_OFFICIAL = "RO",
RACE_OFF = "SK",
MANUALLY_OPENED = "MO",
MANUALLY_CLOSED = "MC"
}
export type RaceLegStatus =
| "open"
| "raceOff"
| "win"
| "lost"
| "pending"
| "attention"
| "unknown";
export type RaceSurfaceEnum = "Dirt";
export type RaceTypeEnum = "Thoroughbred" | "Harness";
export enum RaceTypeCodeEnum {
ALL = "ALL",
THOROUGHBRED = "T",
HARNESS = "H",
GREYHOUNDS = "G",
TB_LARC = "L",
QTR_HORSE = "Q"
}
export enum HighlightedStyle {
Highlighted = "Highlighted",
Normal = "Normal"
}
export enum RaceDistanceCodeEnum {
FURLONG = "F",
METERS = "Mtr",
MILE = "M",
YARD = "Y"
}
export type RaceClassEnum = "Maiden";
export interface RaceOdds {
denominator?: number | null;
numerator?: number;
}
export interface RaceStatus {
code: RaceStatusEnum;
}
export interface TalentPickDataRunners {
order: number;
}
export interface RaceSurface {
name: RaceSurfaceEnum;
shortName?: string;
defaultCondition?: string;
}
export interface RaceType {
name: RaceTypeEnum;
code: RaceTypeCodeEnum;
shortName?: string;
}
export interface RaceTypeCode {
code: RaceTypeCodeEnum;
}
export interface RaceClass {
name: RaceClassEnum;
shortName?: string;
}
export interface RacePool {
amount: number;
wagerType: WagerType;
}
export interface PoolRunnerData {
amount: number;
}
export interface BettingInterestPool {
wagerType: WagerType;
poolRunnersData: Array<PoolRunnerData>;
}
export interface BettingInterestPoolsRunners {
runnerId: string;
scratched: boolean;
}
export interface BettingInterestsPools {
biNumber: number;
runners: Array<BettingInterestPoolsRunners>;
biPools: Array<BettingInterestPool> | null;
}
export interface WillpayLegResult {
legNumber: number;
winningBi: number;
}
export interface WillpayPayout {
bettingInterestNumber: number;
payoutAmount: number;
}
export interface Willpay {
type: WagerType;
wagerAmount: number;
legResults: Array<WillpayLegResult>;
payouts: Array<WillpayPayout>;
}
export interface ProbableBetCombo {
runner1: string;
runner2: string | null;
payout: number;
}
export interface Probable {
amount: number;
minWagerAmount: number;
wagerType: WagerType;
betCombos: Array<ProbableBetCombo>;
}
export interface DistanceValues {
value: string;
code: string;
name: string;
shortName: string;
}
export interface Distance {
date: string;
newValue: DistanceValues;
oldValue: DistanceValues;
}
export interface Change {
date: string;
newValue: string;
oldValue: string;
}
export interface HorseChange {
runnerId: string;
horseName: string;
date: string;
scratched: boolean;
reason: string;
}
export interface JockeyChange {
runnerId: string;
horseName: string;
date: string;
oldValue: string;
newValue: string;
}
export interface SurfaceChanges {
course?: Array<Change>;
tempRailDistance?: Array<Change>;
condition?: Array<Change>;
distance?: Array<Distance>;
}
export interface HorseChanges {
scratched: Array<HorseChange>;
jockey: Array<JockeyChange>;
}
export interface Changes {
surface: SurfaceChanges;
horse: HorseChanges | null;
}
export interface HandicappingSpeedAndClass {
avgClassRating: number;
highSpeed: number;
avgSpeed: number;
lastClassRating: number;
avgDistance: number;
}
export interface HandicappingAveragePace {
finish: number;
numRaces: number;
middle: number;
early: number;
}
export interface HandicappingJockeyTrainer {
places: number;
jockeyName: string;
trainerName: string;
shows: number;
wins: number;
starts: number;
}
export interface HandicappingSnapshot {
powerRating?: number;
daysOff?: number;
horseWins?: number;
horseStarts?: number;
}
export interface HandicappingFreePick {
number?: number;
info?: string;
}
export interface TimeFormFreePick {
number?: number;
info?: string;
}
export interface HandicappingPastResults {
numberOfFirstPlace: number;
numberOfSecondPlace: number;
numberOfThirdPlace: number;
totalNumberOfStarts: number;
top3Percentage: number;
winPercentage: number;
}
export interface Handicapping {
speedAndClass: HandicappingSpeedAndClass;
averagePace: HandicappingAveragePace;
jockeyTrainer: HandicappingJockeyTrainer;
snapshot: HandicappingSnapshot;
freePick: HandicappingFreePick;
pastResults: HandicappingPastResults;
}
export interface HandicapOptions {
key?: string;
value: string | number;
sorting?: string;
}
export interface RaceTimeform {
analystVerdict?: string;
}
export interface Timeform {
silkUrl?: string;
silkUrlSvg?: string;
freePick?: TimeFormFreePick;
analystsComments?: string;
postRaceReport?: string | null;
accBeatenDistance?: string | null;
accBeatenDistanceStatus?: string | null;
winningDistance?: string | null;
winningDistanceStatus?: string | null;
flags?: RunnerFlags;
}
export interface Runner {
age?: number;
horseName: string;
jockey: string;
med?: string;
runnerId: string;
scratched: boolean;
sex?: string;
trainer: string;
weight?: number;
ownerName?: string;
sire?: string;
damSire?: string;
dam?: string;
handicapping?: Handicapping;
dob?: number;
hasJockeyChanges?: boolean;
timeform?: Timeform;
finishPosition?: number;
finishStatus?: string;
runnerName?: string;
runnerNumber?: number;
biNumber?: number;
entityRunnerId?: string;
}
export interface ResultRunner {
betAmount: number;
biNumber: number;
finishPosition: number;
finishStatus?: string;
placePayoff: number;
runnerNumber: string;
runnerName: string;
showPayoff: number;
winPayoff: number;
timeform?: Timeform | null;
favorite?: boolean;
}
export interface RunnerFlags {
horseInFocus: boolean;
warningHorse: boolean;
jockeyUplift: boolean;
trainerUplift: boolean;
horsesForCoursePos: boolean;
horsesForCourseNeg: boolean;
hotTrainer: boolean;
coldTrainer: boolean;
highestLastSpeedRating: boolean;
sectionalFlag: boolean;
significantImprover: boolean;
jockeyInForm: boolean;
clearTopRated: boolean;
interestingJockeyBooking: boolean;
firstTimeBlinkers: boolean;
}
export interface FullResultRunner {
runnerId: string;
runnerName: string;
trainer: string;
jockey: string;
scratched: boolean;
finishPosition: number;
accBeatenDistance?: string;
accBeatenDistanceStatus?: string;
postRaceReport?: string;
odds?: RaceOdds;
}
export interface PayoffsSelection {
payoutAmount: number;
selection: string;
}
export interface PayoffsWagerType {
code: string;
name: string;
}
export interface Payoffs {
selections: Array<PayoffsSelection>;
wagerAmount: number;
wagerType: PayoffsWagerType;
}
export interface Results {
payoffs: Array<Payoffs>;
runners: Array<ResultRunner> | undefined | null;
allRunners?: Array<ResultRunner> | undefined | null;
winningTime?: number | string;
}
export interface RaceProgramRaceVideo {
liveStreaming: boolean;
onTvg: boolean;
onTvg2: boolean;
streams: string[];
hasReplay: boolean;
replayFileName: string;
mobileAvailable: boolean;
isStreamHighDefinition?: boolean;
}
export interface RecentOdds {
odd: string;
trending?: boolean;
}
export interface BettingInterest {
biNumber: number;
currentOdds: RaceOdds;
morningLineOdds: RaceOdds;
recentOdds?: RecentOdds[];
numberColor: string;
runners: Runner[];
saddleColor: string;
isFavorite: boolean;
favorite?: boolean;
biPools?: Array<BettingInterestPool> | null;
}
export interface PickBetFavorite {
runnerNumber: string;
runnerName: string;
isWinner: boolean;
isFavorite: boolean;
}
export interface FavoriteRunners {
[key: number]: PickBetFavorite;
}
export interface RaceCardRunner {
age?: number;
horseName: string;
jockey?: string;
med?: string;
runnerId: string;
scratched: boolean;
sex?: string;
trainer?: string;
weight?: number;
ownerName?: string;
sire?: string;
damSire?: string;
dam?: string;
handicapping?: Array<HandicapOptions | string>;
masterPickNumber?: number;
masterPickInfo?: string;
dob?: number;
hasJockeyChanges?: boolean;
timeform?: Timeform;
}
export interface RaceCardBettingInterest {
biNumber: number;
currentOdds: RaceOdds;
recentOdds?: RecentOdds[];
morningLineOdds: RaceOdds;
isFavorite: boolean;
runners: RaceCardRunner[];
numberColor?: string;
saddleColor?: string;
}
export type RunnerTagsModalProps = {
isOpen: boolean;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
runnerTags?: { [key: string]: any }[];
linkedRunner: {
raceTypeCode?: string;
runnerId?: string;
horseName?: string;
};
currentRunnerTags?: string[];
trackName?: string;
raceNumber?: string;
concatRunnerTags?: string;
raceMtp: string;
raceStatus: string;
fdtvType: string;
};
export enum HandicapOptionsType {
BASIC = "basic",
ADVANCED = "advanced",
SNAPSHOT = "snapshot",
SPEED = "speed",
PACE = "pace",
STATUS = "stats"
}
export enum HandicapSortOptionsType {
SADDLECLOTH = "saddlecloth",
ODDS = "odds",
AGE = "age",
MED = "med",
WEIGHT = "weight",
POWER = "power",
WIN_STARTS = "winStarts",
DAYS_OFF = "daysOff",
AVG_SPEED = "avgSpeed",
AVG_DISTANCE = "avgDistance",
HIGH_SPEED = "highSpeed",
AVG_CLASS_RATING = "avgClassRating",
LAST_CLASS_RATING = "lastClassRating",
NUM_RACES = "numRaces",
EARLY = "early",
MIDDLE = "middle",
FINISH = "finish",
STARTS = "starts",
WINS = "wins",
PLACES = "places",
SHOWS = "shows"
}
export interface Stat {
value: string | number;
isPercent?: boolean;
everBold?: boolean;
description: string;
}
export interface HandicappingSortModesInfo {
basic: HandicapSortOptionsType;
advanced: HandicapSortOptionsType;
snapshot: HandicapSortOptionsType;
speed: HandicapSortOptionsType;
pace: HandicapSortOptionsType;
stats: HandicapSortOptionsType;
}
export interface RaceWagerTypeGroup {
id: number;
name: string;
code: WagerTypeCodesEnum;
description?: string;
descriptionInternational?: string;
}
export interface RaceWagerType {
columnCount: number;
isBox: boolean;
isKey: boolean;
isWheel: boolean;
allowAlternateSelection?: boolean;
legCount: number;
minWagerAmount: number;
positionCount: number;
group: RaceWagerTypeGroup;
type: WagerType;
specialGroup?: boolean;
types?: RaceWagerType[];
wagerAmounts: number[];
unitedWagerTypeCode: string;
}
export interface TrackLocation {
country: string;
state?: string;
}
export interface RaceProgramRaceTrack {
featured: boolean;
numberOfRaces: number;
trackCode: string;
code?: string;
shortName?: string;
trackLocation: TrackLocation;
trackName: string;
trackDataSource?: string;
perfAbbr?: string;
specialCardTypes?: SpecialCardTypes[];
}
export interface SpecialCardTypes {
specialCardTypeAbbreviation: string;
specialCardTypeName: string;
}
export interface RaceHighlighted {
description: string;
style: string;
}
export interface Promo {
rootParentPromoID: number;
isAboveTheLine: boolean;
promoPath: string;
isOptedIn?: boolean;
isPromoTagShown?: boolean;
}
export interface RaceListItem {
value: string | number;
changed: boolean;
changes: Change[];
changeKeyword: string;
}
export interface RaceProgram {
id?: string;
tvgRaceId?: number;
bettingInterests?: BettingInterest[];
mtp?: number;
postTime?: string;
status?: RaceStatus;
racePools?: RacePool[];
track?: RaceProgramRaceTrack;
raceNumber?: string;
highlighted?: RaceHighlighted;
description?: string;
distance?: string;
purse?: number;
numRunners?: string;
numWagerableRunners?: string;
surface?: RaceSurface;
type?: RaceType;
raceClass?: RaceClass;
wagerTypes?: RaceWagerType[];
video?: RaceProgramRaceVideo;
isLoading?: boolean;
results?: Results;
wagerable?: boolean;
promo?: Promo;
promos?: Promo[];
changes?: Changes;
raceDate?: string;
number?: string;
willPays?: Willpay[];
probables?: Probable[];
runnersPools?: BettingInterestsPools[];
claimingPrice?: number;
timeform?: RaceTimeform;
talentPicks?: TalentPickData[];
value?: string;
specialCardTypes?: SpecialCardTypes[];
specialCardSourceRace?: SpecialCardSourceRace;
}
export interface RaceInfo {
country: string;
isGreyhound: boolean;
mtp: number;
postTime: string;
raceId: string;
raceNumber: string;
raceStatus: RaceStatus;
trackAbbr: string;
trackName: string;
trackShortName: string;
typeCode: RaceTypeCode;
onTvg: boolean;
onTvg2: boolean;
promo: Promo;
}
export interface UserPromotions {
optedIn: boolean;
isAboveTheLine?: boolean;
}
export interface RaceTrack {
code: string;
name: string;
shortName?: string;
perfAbbr?: string;
location?: TrackLocation;
hasAboveTheLinePromo?: boolean;
}
export interface RaceVideo {
onTvg: boolean;
onTvg2: boolean;
hasReplay?: boolean;
liveStreaming?: boolean;
streams?: string[];
}
export interface RaceDistance {
code?: RaceDistanceCodeEnum;
name?: string;
shortName?: string;
value?: number;
}
export interface Race {
id: string;
raceNumber: string;
number: string;
track: RaceTrack;
mtp: number;
postTime: string;
isGreyhound: boolean;
status: RaceStatus;
type: RaceTypeCode;
video: RaceVideo;
highlighted?: RaceHighlighted;
bettingInterests?: BettingInterest[];
numRunners?: number;
promos?: Promo[];
tvgRaceId?: number;
raceDistance?: RaceDistance;
pools?: Pick<TopPool, "amount">[];
racePools?: RacePool[];
trackCode?: string;
trackName?: string;
probables?: Probable[];
wagerTypes?: RaceWagerType[];
specialCardSourceRace?: SpecialCardSourceRace;
}
export interface TalentPickGraphData {
id: string;
talent: Talent;
race: Race;
wagerType: WagerType;
track?: string;
amount: string;
price: string;
selections: TalentPickDataRunners[][];
favorites: TalentPickDataRunners[][];
}
export interface RacePanelLinkBets {
count: number;
}
export interface RacePanelLink {
country: string;
runnerNumber: string;
raceNumber?: string;
isGreyhound: boolean;
mtp: number;
raceId: string;
trackName: string;
trackCode: string;
postTime: string;
promos?: Promo[];
userPromotions?: UserPromotions[];
bets?: RacePanelLinkBets;
talentPicks: TalentPickGraphData[];
bettingInterests?: RaceCardBettingInterest[];
highlighted?: RaceHighlighted;
}
export interface UpcomingGraphRaceRaceStatus {
code: RaceStatusEnum;
}
export interface UpcomingGraphRaceLocation {
country: string;
}
export interface UpcomingGraphRaceHighlighted {
description: string;
style: string;
}
export interface UpcomingGraphRacePromo {
isAboveTheLine: boolean;
rootParentPromoID: number;
}
export interface UpcomingGraphRaceTalentPicks {
id: string;
}
export type UpcomingGraphRace = {
raceId: string;
mtp: number;
postTime: string;
raceNumber: string;
trackName: string;
trackCode: string;
raceStatus: UpcomingGraphRaceRaceStatus;
location: UpcomingGraphRaceLocation;
isGreyhound: boolean;
highlighted: UpcomingGraphRaceHighlighted;
promos: UpcomingGraphRacePromo;
talentPicks: UpcomingGraphRaceTalentPicks;
};
export type UpcomingGraphRaces =
| Array<UpcomingGraphRace>
| Array<{ currentRace: UpcomingGraphRace }>;
export interface UpcomingGraphRacesResponseData {
upcomingRaces: UpcomingGraphRaces;
extraRaces: UpcomingGraphRaces;
loading: boolean;
}
export interface UpcomingGraphRacesResponse {
data: UpcomingGraphRacesResponseData;
}
export enum ImportanceType {
NO_LEVEL = "",
LEVEL_0 = "0",
LEVEL_1 = "1",
LEVEL_2 = "2",
LEVEL_3 = "3"
}
export interface RaceInfoNav extends RaceInfo {
importanceLevel?: ImportanceType;
description?: string;
action?: string;
pinnedOrder?: string;
}
export interface RaceAbbr {
trackCode: string;
trackName: string;
raceStatus: RaceStatusEnum;
mtp: number;
postTime: string;
number: string;
hasBets: boolean;
isGreyhound: boolean;
hasResults?: boolean;
showTrackCode: boolean;
promo: Promo;
}
export interface RaceNavigationType {
mtp: number;
postTime: string;
status: RaceStatusEnum;
isGreyhound: boolean;
trackName: string;
trackAbbr: string;
raceNumber: string;
isSmall?: boolean;
onClickCallback: NullaryFn<void>;
}
export interface PastPerformanceRaceTrack {
name: string;
code: string;
}
export interface PastPerformanceRaceSurface {
shortName: string;
defaultCondition: string;
}
export interface PastPerformanceRaceClass {
shortName: string;
}
export interface PastPerformanceRace {
id: string;
raceDate: string;
date: string;
raceNumber: string;
number: string;
track: PastPerformanceRaceTrack;
raceTypeCode: RaceTypeCodeEnum;
hasReplays: boolean;
replayFileName?: string;
distance: string;
surface: PastPerformanceRaceSurface;
raceClass: PastPerformanceRaceClass;
purse: number;
numRunners: number;
handicappingData?: string[];
finishPosition?: number;
finishStatus?: string;
scratched?: boolean;
odds?: RaceOdds;
postRaceReport?: string;
accBeatenDistance?: string;
accBeatenDistanceStatus?: string;
favorite?: boolean;
}
export interface PastRaceBettingInterests {
biNumber: number;
favorite: boolean;
currentOdds?: RaceOdds;
morningLineOdds?: RaceOdds;
runners: Runner[];
numberColor?: string;
saddleColor?: string;
}
export interface PastRace {
id?: string;
raceId?: string;
bettingInterests: PastRaceBettingInterests[];
results?: Results;
}
export interface VideoSRC {
sd?: string;
hd?: string;
replay?: string;
}
export interface Video {
show: boolean;
error: boolean;
src: VideoSRC;
}
export enum RaceVideoFeedback {
NOT_AVAILABLE_REPLAY = "NOT_AVAILABLE_REPLAY",
STARTING_SOON_REPLAY = "STARTING_SOON_REPLAY",
FINISHED_REPLAY = "FINISHED_REPLAY",
AVAILABLE_REPLAY = "AVAILABLE_REPLAY",
NOT_AVAILABLE_NO_REPLAY = "NOT_AVAILABLE_NO_REPLAY",
STARTING_SOON_NO_REPLAY = "STARTING_SOON_NO_REPLAY",
FINISHED_NO_REPLAY = "FINISHED_NO_REPLAY",
AVAILABLE_NO_REPLAY = "AVAILABLE_NO_REPLAY",
SHOWN_ON_NBC = "SHOWN_ON_NBC"
}
export interface ExpandLineArgs {
runnerId: string;
selection: string;
column: number;
fromIcon: boolean;
direction: string;
isScratched: boolean;
}
export interface RaceTemplate {
trackName: string;
trackCode: string;
number: string;
raceStatus: RaceStatusEnum;
hasBets: boolean;
hasResults?: boolean;
postTime: string;
mtp: number;
showTrackCode: boolean;
isGreyhound: boolean;
promo: Promo;
}
export interface CustomRaceAbbr extends RaceAbbr {
id?: string;
idPrefix?: string;
}
export interface RaceInfoMyBetsRunner {
runnerNumber?: string;
biNumber: number;
finishPosition: number;
betAmount: number;
}
export interface RaceInfoMyBetsResults {
runners?: RaceInfoMyBetsRunner[];
payoffs?: Array<Payoffs>;
winningTime?: number | string;
}
export interface RaceInfoMyBetsStatus {
code: RaceStatusEnum;
}
export interface RaceInfoMyBetsVideo {
liveStreaming: boolean;
hasReplay: boolean;
}
export interface RaceInfoMyBets {
id: string;
raceId?: string;
tvgRaceId: number;
postTime: string;
raceDate: string;
probables?: Probable[];
bettingInterests: BettingInterest[];
trackName: string;
trackCode: string;
isGreyhound: boolean;
mtp: number;
number: number;
results?: RaceInfoMyBetsResults;
willPays?: Willpay[];
status: RaceInfoMyBetsStatus;
video: RaceInfoMyBetsVideo;
wagerTypes: RaceWagerType[];
type?: RaceType;
numRunners: string;
track?: {
specialCardTypes?: SpecialCardTypes[];
};
}
export interface MTPNotificationConfigType {
mtpBelowThresholdText: string;
raceOffText: string;
mtpThreshold: number;
hideNotificationDelay: number;
showNotificationDelay: number;
}
export interface RaceBet {
id: string; // this is a string because WRO uses a serial number string to identify bets
raceTypeCode: RaceTypeCodeEnum;
betTotal: number;
wagerAmount: number;
wagerType: WagerType;
isKey: boolean;
isLeg: boolean;
selections: Array<Array<string>>;
onDelete?: NullaryFn<unknown>;
isCancelable?: boolean;
isLost?: boolean;
isRepeatable?: boolean;
isPromoQualifying?: boolean;
hasRepeatButton?: boolean;
hasRepeaterEnabled?: boolean;
repetitionsNr?: number;
isCancelled?: boolean;
isRefunded?: boolean;
totalWinAmount?: number;
onRepeatClick?: NullaryFn<void>;
}
export interface RaceBetGroup {
postTime: string;
mtp: number;
raceNumber: string;
trackName: string;
status: RaceStatus;
isGreyhound: boolean;
showRaceDate?: boolean;
bets: RaceBet[];
raceDate: string;
trackCode: string;
}
export interface PastRaceResults {
id: string;
number: string;
description: string;
purse: number;
date: string;
postTime: string;
track: {
code: string;
name: string;
};
surface: {
code: string;
name: string;
};
distance: {
value: number;
code: string;
name: string;
};
type: {
id: number;
code: string;
name: string;
};
raceClass: {
code: string;
name: string;
};
video: {
replayFileName: string;
};
results: Results;
}
webpack://frontend-mybets/../../packages/tvg-lib-utils/handicapping-conf/handicappingOptions.ts
export default [
{
title: "Handicapping Info",
description: "Basic Summary",
handicapData: ["Jockey Name", "Trainer Name"],
key: "basic",
qaLabel: "basicSummary"
},
{
title: "ADVANCED SUMMARY",
description: "Advanced Summary",
handicapData: [
{ key: "age", value: "Age", sorting: "asc" },
{ key: "gender", value: "Gender" },
{ key: "jockey", value: "Jockey" },
{ key: "trainer", value: "Trainer" },
{ key: "med", value: "Med", sorting: "desc" },
{ key: "weight", value: "Wgt", sorting: "desc" },
{ key: "sire", value: "Sire" },
{ key: "dam", value: "Dam" },
{ key: "damsire", value: "DamSire" },
{ key: "owner", value: "Owner" }
],
key: "advanced",
qaLabel: "advancedSummary"
},
{
title: "SNAPSHOT",
description: "Snapshot",
handicapData: [
{ key: "power", value: "Power Rating", sorting: "desc" },
{ key: "winStarts", value: "Wins/Starts", sorting: "desc" },
{ key: "daysOff", value: "Days Rest", sorting: "asc" }
],
key: "snapshot",
qaLabel: "snapshot"
},
{
title: "SPEED & CLASS",
description: "Speed & Class",
handicapData: [
{
key: "avgSpeed",
value: "Avg. Speed",
sorting: "desc"
},
{
key: "avgDistance",
value: "Avg. Distance",
sorting: "desc"
},
{
key: "highSpeed",
value: "High Speed",
sorting: "desc"
},
{
key: "avgClassRating",
value: "Avg. Class",
sorting: "desc"
},
{
key: "lastClassRating",
value: "Last Class",
sorting: "desc"
}
],
key: "speed",
qaLabel: "speedClass"
},
{
title: "PACE",
description: "Pace",
handicapData: [
{
key: "numRaces",
value: "Number of Races",
sorting: "desc"
},
{
key: "early",
value: "Early",
sorting: "desc"
},
{
key: "middle",
value: "Middle",
sorting: "desc"
},
{
key: "finish",
value: "Finish",
sorting: "desc"
}
],
key: "pace",
qaLabel: "pace"
},
{
title: "JOCKEY/TRAINER STATS",
description: "Jockey/Trainer Stats",
handicapData: [
{ key: "jockey", value: "Jockey" },
{ key: "trainer", value: "Trainer" },
{
key: "starts",
value: "Runs",
sorting: "desc"
},
{
key: "wins",
value: "1st",
sorting: "desc"
},
{
key: "places",
value: "2nd",
sorting: "desc"
},
{
key: "shows",
value: "3rd",
sorting: "desc"
}
],
key: "stats",
qaLabel: "jockeyTrainerStats"
}
];
export const handicappingGreyhoundOptions = [
{
title: "Handicapping Info",
description: "basic summary",
handicapData: [
{ key: "kennel", value: "Kennel" },
{ key: "trainer", value: "Trainer" }
],
key: "basic",
qaLabel: "basicSummary"
},
{
title: "ADVANCED SUMMARY",
description: "advanced summary",
handicapData: [
"Kennel",
"Trainer",
"Weight",
"Whelped",
"Gender",
"Sire",
"Dam"
],
key: "advanced",
qaLabel: "advancedSummary"
}
];
export const handicappingHarnessOptions = [
{
title: "Handicapping Info",
description: "Basic Summary",
handicapData: ["Driver Name", "Trainer Name"],
key: "basic",
qaLabel: "basicSummary"
},
{
title: "ADVANCED SUMMARY",
description: "Advanced Summary",
handicapData: [
{ key: "age", value: "Age", sorting: "asc" },
{ key: "gender", value: "Gender" },
{ key: "jockey", value: "Driver" },
{ key: "trainer", value: "Trainer" },
{ key: "med", value: "Med", sorting: "desc" },
{ key: "weight", value: "Wgt", sorting: "desc" },
{ key: "sire", value: "Sire" },
{ key: "dam", value: "Dam" },
{ key: "damsire", value: "DamSire" },
{ key: "owner", value: "Owner" }
],
key: "advanced",
qaLabel: "advancedSummary"
},
{
title: "SNAPSHOT",
description: "Snapshot",
handicapData: [
{ key: "power", value: "Power Rating", sorting: "desc" },
{ key: "winStarts", value: "Wins/Starts", sorting: "desc" },
{ key: "daysOff", value: "Days Rest", sorting: "asc" }
],
key: "snapshot",
qaLabel: "snapshot"
},
{
title: "SPEED & CLASS",
description: "Speed & Class",
handicapData: [
{
key: "avgSpeed",
value: "Avg. Speed",
sorting: "desc"
},
{
key: "avgDistance",
value: "Avg. Distance",
sorting: "desc"
},
{
key: "highSpeed",
value: "High Speed",
sorting: "desc"
},
{
key: "avgClassRating",
value: "Avg. Class",
sorting: "desc"
},
{
key: "lastClassRating",
value: "Last Class",
sorting: "desc"
}
],
key: "speed",
qaLabel: "speedClass"
},
{
title: "PACE",
description: "Pace",
handicapData: [
{
key: "numRaces",
value: "Number of Races",
sorting: "desc"
},
{
key: "early",
value: "Early",
sorting: "desc"
},
{
key: "middle",
value: "Middle",
sorting: "desc"
},
{
key: "finish",
value: "Finish",
sorting: "desc"
}
],
key: "pace",
qaLabel: "pace"
},
{
title: "DRIVER/TRAINER STATS",
description: "Driver/Trainer Stats",
handicapData: [
{ key: "jockey", value: "Driver" },
{ key: "trainer", value: "Trainer" },
{
key: "starts",
value: "Runs",
sorting: "desc"
},
{
key: "wins",
value: "1st",
sorting: "desc"
},
{
key: "places",
value: "2nd",
sorting: "desc"
},
{
key: "shows",
value: "3rd",
sorting: "desc"
}
],
key: "stats",
qaLabel: "jockeyTrainerStats"
}
];
webpack://frontend-mybets/../../packages/urp-comp-derby-banner/src/types.ts
import { BinaryFn } from "@tvg/ts-types/Functional";
export interface BannerProps {
raceStartDate?: Date | null;
eventStatus: DerbyEventStatus;
bannerCfg?: HeaderBanner;
orientation?: "portrait" | "landscape";
onCtaClick: BinaryFn<string, string, void>;
qaLabel?: string;
}
export type Variables = Record<
string,
string | number | Date | undefined | null
>;
export interface RichTextParserProps {
content: Array<RichText> | undefined;
variables?: Variables;
}
export interface CountdownProps {
// End date in Date format
endDate?: Date | null;
// Event status
eventStatus: DerbyEventStatus;
// Full date
forceFullDate?: boolean;
}
export enum DerbyEventStatus {
PRE = "preEvent",
DERBY_DAY = "eventDay",
POST = "default"
}
export interface HomepageEventBannerText {
label: string;
size: number;
}
export interface ContentParagraph {
type: "paragraph";
content?: Array<ContentText>;
}
export interface ContentHeading {
type: "heading";
attrs: {
level: number;
};
content: Array<ContentText>;
}
export interface ContentText {
type: "text";
text: string;
marks?: Array<TextMarks>;
}
export interface TextMarks {
type: "textStyle";
attrs: {
color: string;
};
}
export type RichText = ContentParagraph | ContentHeading;
export enum BannerConfigType {
DEFAULT = "default",
EVENT_DAY = "eventDay",
PRE_EVENT = "preEvent",
FRIDAY_PRE_EVENT = "fridayPreEvent",
THURSDAY_PRE_EVENT = "thursdayPreEvent"
}
export enum BannerContext {
DESKTOP = "desk",
MOBILE_SA = "mobile",
X_SELL = "xSell",
HOME_PAGE = "homePage",
PROGRAM_PAGE = "programPage"
}
export interface CtaButton {
button_type: string;
label: string;
link_url: {
url: string;
};
}
export interface HeaderBanner {
context: Array<BannerContext>;
background_image: {
filename: string;
alt: string;
};
cta_buttons_bg_color?: string;
cta_buttons: Array<CtaButton>;
dynamic_text_bg_color?: string;
dynamic_text?: {
type: "doc";
content: Array<RichText>;
};
background_image_link?: {
url?: string;
};
}
export type HomepageHeaderBanner = Partial<
Record<BannerConfigType, Array<HeaderBanner>>
>;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/__mocks__/probablesMocks.ts
export const winProbable = {
wagerType: {
code: "WN",
id: 10
},
minWagerAmount: 1,
betCombos: [
{
runner1: "1",
runner2: null,
payout: "1.32"
},
{
runner1: "2",
runner2: null,
payout: "4.82"
},
{
runner1: "3",
runner2: null,
payout: "2.92"
},
{
runner1: "4",
runner2: null,
payout: "1.1"
},
{
runner1: "5",
runner2: null,
payout: "1.85"
},
{
runner1: "6",
runner2: null,
payout: "2.5"
},
{
runner1: "7",
runner2: null,
payout: "11.2"
},
{
runner1: "8",
runner2: null,
payout: "2.1"
},
{
runner1: "9",
runner2: null,
payout: "3.2"
}
]
};
export const placeProbable = {
wagerType: {
id: 20,
code: "PL"
},
minWagerAmount: 1,
betCombos: [
{
runner1: "1",
runner2: "1",
payout: "1.32"
},
{
runner1: "1",
runner2: "2",
payout: "2.5"
},
{
runner1: "1",
runner2: "3",
payout: "2.92"
},
{
runner1: "1",
runner2: "4",
payout: "1.1"
},
{
runner1: "2",
runner2: "1",
payout: "1.85"
},
{
runner1: "2",
runner2: "2",
payout: "4.82"
},
{
runner1: "2",
runner2: "3",
payout: "11.2"
},
{
runner1: "2",
runner2: "4",
payout: "2.1"
}
]
};
export const showProbable = {
...placeProbable,
wagerType: {
id: 30,
code: "SH"
}
};
export const quinellaProbable = {
wagerType: {
id: 80,
code: "QN"
},
minWagerAmount: 1,
betCombos: [
{
runner1: "1",
runner2: "1",
payout: "0.0"
},
{
runner1: "1",
runner2: "2",
payout: "4.82"
},
{
runner1: "1",
runner2: "3",
payout: "2.92"
},
{
runner1: "2",
runner2: "1",
payout: "4.82"
},
{
runner1: "2",
runner2: "2",
payout: "0.0"
},
{
runner1: "2",
runner2: "3",
payout: "2.1"
},
{
runner1: "3",
runner2: "1",
payout: "2.92"
},
{
runner1: "3",
runner2: "2",
payout: "2.1"
},
{
runner1: "3",
runner2: "3",
payout: "0.0"
}
]
};
export const dailyDoubleProbable = {
wagerType: {
id: 310,
code: "DB"
},
minWagerAmount: 1,
betCombos: [
{
runner1: "1",
runner2: "1",
payout: "0.0"
},
{
runner1: "1",
runner2: "2",
payout: "7.12"
},
{
runner1: "1",
runner2: "3",
payout: "1.62"
},
{
runner1: "2",
runner2: "1",
payout: "3.49"
},
{
runner1: "2",
runner2: "2",
payout: "0.0"
},
{
runner1: "2",
runner2: "3",
payout: "2.9"
},
{
runner1: "3",
runner2: "1",
payout: "9.9"
},
{
runner1: "3",
runner2: "2",
payout: "4.1"
},
{
runner1: "3",
runner2: "3",
payout: "0.0"
}
]
};
export const exactaProbable = {
minWagerAmount: 1,
wagerType: {
id: 110,
code: "EX"
},
betCombos: [
{ runner1: "1", runner2: "1", payout: "0.0" },
{ runner1: "1", runner2: "2", payout: "1.08" },
{ runner1: "1", runner2: "3", payout: "1.68" },
{ runner1: "1", runner2: "4", payout: "1.18" },
{ runner1: "1", runner2: "5", payout: "3.48" },
{ runner1: "1", runner2: "6", payout: "3.94" },
{ runner1: "1", runner2: "7", payout: "0.0" },
{ runner1: "1", runner2: "8", payout: "0.0" },
{ runner1: "2", runner2: "1", payout: "2.1" },
{ runner1: "2", runner2: "2", payout: "0.0" },
{ runner1: "2", runner2: "3", payout: "5.84" },
{ runner1: "2", runner2: "4", payout: "6.66" },
{ runner1: "2", runner2: "5", payout: "5.18" },
{ runner1: "2", runner2: "6", payout: "9.82" },
{ runner1: "2", runner2: "7", payout: "0.0" },
{ runner1: "2", runner2: "8", payout: "0.0" },
{ runner1: "3", runner2: "1", payout: "3.04" },
{ runner1: "3", runner2: "2", payout: "4.7" },
{ runner1: "3", runner2: "3", payout: "0.0" },
{ runner1: "3", runner2: "4", payout: "6.88" },
{ runner1: "3", runner2: "5", payout: "10.38" },
{ runner1: "3", runner2: "6", payout: "17.0" },
{ runner1: "3", runner2: "7", payout: "0.0" },
{ runner1: "3", runner2: "8", payout: "0.0" },
{ runner1: "4", runner2: "1", payout: "2.42" },
{ runner1: "4", runner2: "2", payout: "5.1" },
{ runner1: "4", runner2: "3", payout: "6.06" },
{ runner1: "4", runner2: "4", payout: "0.0" },
{ runner1: "4", runner2: "5", payout: "11.14" },
{ runner1: "4", runner2: "6", payout: "17.4" },
{ runner1: "4", runner2: "7", payout: "0.0" },
{ runner1: "4", runner2: "8", payout: "0.0" },
{ runner1: "5", runner2: "1", payout: "8.38" },
{ runner1: "5", runner2: "2", payout: "5.06" },
{ runner1: "5", runner2: "3", payout: "12.3" },
{ runner1: "5", runner2: "4", payout: "11.66" },
{ runner1: "5", runner2: "5", payout: "0.0" },
{ runner1: "5", runner2: "6", payout: "19.78" },
{ runner1: "5", runner2: "7", payout: "0.0" },
{ runner1: "5", runner2: "8", payout: "0.0" },
{ runner1: "6", runner2: "1", payout: "5.86" },
{ runner1: "6", runner2: "2", payout: "11.26" },
{ runner1: "6", runner2: "3", payout: "19.64" },
{ runner1: "6", runner2: "4", payout: "24.14" },
{ runner1: "6", runner2: "5", payout: "19.74" },
{ runner1: "6", runner2: "6", payout: "0.0" },
{ runner1: "6", runner2: "7", payout: "0.0" },
{ runner1: "6", runner2: "8", payout: "0.0" },
{ runner1: "7", runner2: "1", payout: "0.0" },
{ runner1: "7", runner2: "2", payout: "0.0" },
{ runner1: "7", runner2: "3", payout: "0.0" },
{ runner1: "7", runner2: "4", payout: "0.0" },
{ runner1: "7", runner2: "5", payout: "0.0" },
{ runner1: "7", runner2: "6", payout: "0.0" },
{ runner1: "7", runner2: "7", payout: "0.0" },
{ runner1: "7", runner2: "8", payout: "0.0" },
{ runner1: "8", runner2: "1", payout: "0.0" },
{ runner1: "8", runner2: "2", payout: "0.0" },
{ runner1: "8", runner2: "3", payout: "0.0" },
{ runner1: "8", runner2: "4", payout: "0.0" },
{ runner1: "8", runner2: "5", payout: "0.0" },
{ runner1: "8", runner2: "6", payout: "0.0" },
{ runner1: "8", runner2: "7", payout: "0.0" },
{ runner1: "8", runner2: "8", payout: "0.0" }
]
};
export const placeNaN = {
wagerType: {
id: 20,
code: "PL"
},
minWagerAmount: 1,
betCombos: [
{
runner1: "1",
runner2: null,
payout: "1.32"
},
{
runner1: "2",
runner2: null,
payout: "4.82"
},
{
runner1: "3",
runner2: null,
payout: "2.92"
},
{
runner1: "4",
runner2: null,
payout: "1.1"
},
{
runner1: "5",
runner2: null,
payout: "1.85"
},
{
runner1: "6",
runner2: null,
payout: "2.5"
},
{
runner1: "7",
runner2: null,
payout: "11.2"
},
{
runner1: "8",
runner2: null,
payout: "2.1"
},
{
runner1: "9",
runner2: null,
payout: "3.2"
}
]
};
export const emptyProbable = {
title: "No Probables available",
description:
"There are no available Probables at the moment. Check back later"
};
export const probablesMock = [
winProbable,
placeProbable,
showProbable,
quinellaProbable,
dailyDoubleProbable,
exactaProbable,
emptyProbable
];
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/store/defaultValues.ts
import { WagerTypeCodesEnum } from "@tvg/ts-types/Wager";
import {
HandicappingModuleMessage,
HandicappingTabsMap,
handicappingRunnerFlagsName,
BetslipAccountErrorDefault,
AlternateSelectionsMessages
} from "../types";
export const defaultTvg5BlacklistedBets = {
blacklistedBets: ["EXW", "TRW", "SUW", "H5W"] as WagerTypeCodesEnum[]
};
export const handicappingDefaultTitle = "1-2-3 Prediction";
export const forbiddenBettingStates = {
blockedStates: ["az"],
errorMessage:
"For legal reasons, we cannot accept wagers from your state on a computer. Try again on a mobile device using the app or mobile website"
};
export const handicappingDefaultTabs: HandicappingTabsMap = {
USGSA: [
{
icon: "numberFire",
name: "NumberFire Prediction",
value: "timeform"
},
{
icon: "trackMaster",
name: "Free Trackmaster Picks",
value: "handicapping"
}
],
GSA: [{ icon: "timeForm", name: "Timeform 1-2-3", value: "handicapping" }],
SRW: [{ icon: "badge", name: "Free 1-2-3", value: "handicapping" }],
RAS: [{ icon: "rs", name: "R&S Expert Tips", value: "handicapping" }],
EQB: [
{
icon: "trackMaster",
name: "Free Trackmaster Picks",
value: "handicapping"
}
]
};
export const handicappingMessageDefault: HandicappingModuleMessage = {
title: handicappingDefaultTitle,
tabs: handicappingDefaultTabs
};
export const handicappingRunnerFlags: handicappingRunnerFlagsName = {
flags: [
{
id: "clearTopRated",
name: "BEST IN CLASS"
},
{
id: "coldTrainer",
name: "COLD TRAINER"
},
{
id: "firstTimeBlinkers",
name: "FIRST TIME BLINKERS"
},
{
id: "highestLastSpeedRating",
name: "Highest Last Speed Rating"
},
{
id: "horsesForCoursePos",
name: "HORSES FOR COURSES"
},
{
id: "jockeyInForm",
name: "HOT JOCKEY"
},
{
id: "hotTrainer",
name: "HOT TRAINER"
},
{
id: "significantImprover",
name: "IMPROVER"
},
{
id: "interestingJockeyBooking",
name: "JOCKEY UPLIFT"
},
{
id: "jockeyUplift",
name: "JOCKEY UPLIFT"
},
{
id: "horseInFocus",
name: "ONE TO WATCH"
},
{
id: "sectionalFlag",
name: "SECTIONAL FLAG"
},
{
id: "trainerUplift",
name: "TRAINER UPLIFT"
},
{
id: "warningHorse",
name: "WARNING HORSE"
}
]
};
export const customAmountMessages = {
title: "Custom bet amount",
buttons: [
{ text: "Confirm", variant: "betting", action: "submit" },
{ text: "Cancel", variant: "secondary", action: "cancel" }
]
};
export const betslipAccountErrorDefault: BetslipAccountErrorDefault = {
geolocationError: {
title: "Verify your location so you can bet",
message: "We need to make sure you're in a state that allows wagering.",
button: "Verify location"
},
accountComplianceError: {
title: "Verify your account so you can bet",
message: "We need to first confirm your identity.",
button: "Verify Account"
},
termsAndConditionsError: {
button: "Accept terms and conditions"
}
};
export const customTrackListMessages = {
title: "Betslip Selections",
description:
"There is one or more selection in the betslip. By leaving this page you will lose the selection. Do you want to proceed?"
};
export const alternateSelectionsMessagesDefault: AlternateSelectionsMessages = {
infoModal: {
title: "Alternate Selections",
subtitle:
"You can optionally select up to one alternate per leg. If your main selection scratches, the alternate will replace it.",
description:
"Choosing an alternate selection incurs no additional cost and is only available on certain tracks and bet types. If no alternate is selected, scratches will be replaced with the post-time favorite."
},
betslipButton: "Alternate Selections",
alternatesModal: {
title: "Alternate Selections",
alert: {
title: "Alternate Selections",
description:
"You can optionally select up to one alternate per leg.<br/>If your main selection scratches, the alternate will replace it.<br/><br/>Choosing an alternate selection incurs no additional cost and is only available on certain tracks and bet types. If no alternate is selected, scratches will be replaced with the post-time favorite."
},
buttons: {
cancel: "Cancel",
apply: "Apply"
}
}
};
export const defaultFollowHorseMessages = {
label: "Add to Stable",
followingLabel: "Manage Stable",
success: "Success All of your entries have been added to your stable.",
error:
"There was an issue saving your entries to your stable. please check again later and retry."
};
webpack://frontend-mybets/../../packages/tvg-comp-program-page/__mocks__/willPaysMocks.ts
import { BettingInterest, Willpay } from "@tvg/ts-types/Race";
import { WagerTypeCodesEnum } from "@tvg/ts-types/Wager";
export const emptyWillPays = {
title: "No will pays available",
description:
"There are no available will pays at the moment. Check back later"
};
export const willPays: Willpay[] = [
{
wagerAmount: 2,
type: {
id: 310,
code: WagerTypeCodesEnum.DAILY_DOUBLE,
name: "Daily Double"
},
payouts: [
{
bettingInterestNumber: 1,
payoutAmount: 37.6
},
{
bettingInterestNumber: 2,
payoutAmount: 84.4
},
{
bettingInterestNumber: 3,
payoutAmount: 95
}
],
legResults: [
{
legNumber: 1,
winningBi: 6
}
]
},
{
wagerAmount: 0.5,
type: {
id: 330,
code: WagerTypeCodesEnum.PICK_3,
name: "Pick 3"
},
payouts: [
{
bettingInterestNumber: 4,
payoutAmount: 10
},
{
bettingInterestNumber: 3,
payoutAmount: 84.4
},
{
bettingInterestNumber: 2,
payoutAmount: 50
},
{
bettingInterestNumber: 1,
payoutAmount: 25
}
],
legResults: [
{
legNumber: 1,
winningBi: 4
},
{
legNumber: 2,
winningBi: 5
}
]
}
];
export const bettingInterests: BettingInterest[] = [
{
biNumber: 1,
isFavorite: true,
currentOdds: {},
morningLineOdds: {},
runners: [
{
runnerId: "1",
scratched: true,
horseName: "Asdrubal",
jockey: "Mickey",
trainer: "Trainer"
},
{
runnerId: "1A",
scratched: false,
horseName: "Asdrubal",
jockey: "Mickey",
trainer: "Trainer"
}
],
numberColor: "#FFFFFF",
saddleColor: "#BC0000"
},
{
biNumber: 2,
isFavorite: false,
currentOdds: {},
morningLineOdds: {},
runners: [
{
runnerId: "2",
scratched: true,
horseName: "Asdrubal2",
jockey: "Mickey2",
trainer: "Trainer2"
}
],
numberColor: "#FFFFFF",
saddleColor: "#253B84"
},
{
biNumber: 3,
isFavorite: false,
currentOdds: {},
morningLineOdds: {},
runners: [
{
runnerId: "3",
scratched: false,
horseName: "Asdrubal3",
jockey: "Mickey3",
trainer: "Trainer3"
}
],
numberColor: "#050303",
saddleColor: "#7e2584"
}
];
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/store/selectors.ts
import { get } from "lodash";
import { Race } from "@tvg/ts-types/Race";
import parseCAPIMessage from "@tvg/utils/capiUtils";
import { RunnerBI } from "@tvg/pp/src/hooks/useGetRunnerFromBI";
import {
DerbyEventStatus,
HomepageHeaderBanner,
HomepageEventBannerText
} from "@urp/derby-banner/src/types";
import { ChannelUFC } from "@tvg/ts-types/Alerts";
import { Store } from "@reduxjs/toolkit";
import {
TalentPickBet,
EmptyMessage,
HandicappingModuleMessage,
InlinePPMessage,
RepeatBetConfig,
WillPay,
ForbiddentBettingStates,
TrackListMessage,
AlternateSelectionsMessages,
PreferenceRunnerModifier,
BetPromoBannerContent,
MyStableMessages
} from "../types";
import { emptyProbable } from "../../__mocks__/probablesMocks";
import { emptyWillPays } from "../../__mocks__/willPaysMocks";
import { inlinePPContent } from "../../__mocks__/inlinePastPerformanceMocks";
import {
handicappingMessageDefault,
handicappingRunnerFlags,
customAmountMessages,
forbiddenBettingStates,
betslipAccountErrorDefault,
defaultTvg5BlacklistedBets,
customTrackListMessages,
alternateSelectionsMessagesDefault,
defaultFollowHorseMessages
} from "./defaultValues";
type UTCDate = [number, number, number, number];
const MONTH_INDEX = 1;
export const getBlacklistedWagerTypes = (store: unknown) =>
parseCAPIMessage(
store,
"capi.messages.Tvg5BlacklistedBets",
defaultTvg5BlacklistedBets
);
export const getBonus = (store: Store): number =>
get(store, "userData.bonus", 0);
export const getBonusFundsWagerMessages = (store: Store) =>
parseCAPIMessage(store, "capi.messages.bonusFundsWagerMessages", {});
export const getHasRequestedLogin = (store: Store) =>
get(store, "userData.hasRequested", false);
export const getOptedInPromosStore = (store: unknown) =>
get(store, "userData.optedInPromos", {});
export const getProgramPageMessages = (store: unknown) =>
parseCAPIMessage(store, "capi.messages.TVG5ProgramPage", "");
export const getBetSlipDisabledSelectionsLabel = (store: unknown) =>
parseCAPIMessage(
store,
"capi.messages.BetSlipDisabledSelectionsLabel",
"Select Runners"
);
export const getPickSelectorLabels = (store: unknown) =>
parseCAPIMessage(store, "capi.messages.pickSelectorLabels", undefined);
export const getOldPromosURLs = (store: unknown): string[] =>
parseCAPIMessage(store, "capi.messages.oldPromosURLs", []);
export const getWtxErrorMessagesWithBehaviour = (store: unknown) =>
parseCAPIMessage(store, "capi.messages.wtxErrorMessagesWithBehaviour", {});
export const getBetConfirmationMessages = (store: unknown) =>
parseCAPIMessage(store, "capi.messages.betConfirmation", {});
export const getShowHandicappingOptionPicksToggle = (store: unknown) =>
get(store, "capi.featureToggles.ShowHandicappingOptionPicks", false);
export const getShowBetConfirmPref = (store: unknown) =>
get(store, "userData.preferences.show_bet_confirm");
export const getGeoLocation = (store: unknown) => get(store, "geolocation");
export const getMyBetsEmptyStateMessage = (store: unknown) =>
parseCAPIMessage(store, "capi.messages.mybetsEmptyStateMessage", {});
export const getPoolsEmptyStateMessage = (store: unknown) =>
parseCAPIMessage(store, "capi.messages.poolsEmptyStateMessage", {});
export const getUserBalanceIsShown = (store: unknown) =>
get(store, "userData.preferences.balance_is_shown");
export const getHandicappingTagsDescription = (store: unknown) =>
parseCAPIMessage(
store,
"capi.messages.handicappingRunnerFlags",
handicappingRunnerFlags
);
export const getProgramPageModuleConfigs = (store: unknown) =>
parseCAPIMessage(store, "capi.messages.tvg5ProgramPageModulesConfig", {
activeBetsModule: false,
changesModule: false,
probablesModule: false,
poolsModule: false,
willPaysModule: false,
handicappingModule: false
});
export const getChangesEmptyStateMessage = (store: unknown) =>
parseCAPIMessage(store, "capi.messages.changesEmptyStateMessage", {});
export const getProbablesEmptyMessage = (store: Store): EmptyMessage =>
parseCAPIMessage(
store,
"capi.messages.probablesEmptyStateMessage",
emptyProbable
);
export const getWillPaysEmptyMessage = (store: Store): WillPay =>
parseCAPIMessage(
store,
"capi.messages.willPaysEmptyStateMessage",
emptyWillPays
);
export const getInlinePPContent = (store: Store): InlinePPMessage =>
parseCAPIMessage(
store,
"capi.messages.inlinePastPerformances",
inlinePPContent
);
export const getIsLoginModalOpen = (store: unknown): boolean =>
get(store, "loginModal.loginOpen", false);
export const getIsBetSlipExpanded = (store: unknown) =>
get(store, "app.isBetSlipExpanded", false);
export const getIsRunnerModifierExpanded = (store: unknown) =>
get(store, "programPage.isRunnerModifierExpanded", false);
export const getIsPoolsNInfoModalOpen = (store: unknown) => ({
isPoolsNInfoModalOpen: get(store, "programPage.isPoolsNInfoModalOpen", false),
PIRace: get(store, "programPage.PIRace", undefined)
});
export const getBetslipAccountError = (store: Store) =>
parseCAPIMessage(
store,
"capi.messages.BetslipAccountError",
betslipAccountErrorDefault
);
export const getHandicappingModule = (
store: Store
): HandicappingModuleMessage =>
parseCAPIMessage(
store,
"capi.messages.handicappingModule",
handicappingMessageDefault
);
export const getIsHamburgerMenuOpen = (store: unknown): boolean =>
get(store, "hdr.isHamburgerMenuOpen", false);
export const getBetSelections = (store: unknown) =>
get(store, "BetTicket.betSelections", [[]]);
export const getScratchedSelections = (store: unknown) =>
get(store, "BetTicket.scratchedSelections", [[]]);
export const getBetConfirmModalTexts = (store: unknown) =>
parseCAPIMessage(store, "capi.messages.betConfirmModalText", {});
export const getRepeatBetConfig = (store: Store): RepeatBetConfig =>
parseCAPIMessage(store, "capi.messages.repeatBet", {});
export const getTalentPickBet = (store: Store): TalentPickBet =>
parseCAPIMessage(store, "capi.messages.talentPickBet", {});
export const getTrackListMessages = (store: Store): TrackListMessage =>
parseCAPIMessage(
store,
"capi.messages.trackListMessage",
customTrackListMessages
);
export const getCustomAmountMessages = (store: Store) =>
parseCAPIMessage(
store,
"capi.messages.CustomAmountModalMessages",
customAmountMessages
);
export const getForbiddenBettingStates = (
store: Store
): ForbiddentBettingStates =>
parseCAPIMessage(
store,
"capi.messages.forbiddenBettingStates",
forbiddenBettingStates
);
export const getFeatureBettingBlockedByUserState = (store: unknown) =>
get(store, "capi.featureToggles.bettingBlockedByUserState", false);
export const getFeatureTracksList = (store: unknown) =>
get(store, "capi.featureToggles.showTracksListDropdown", true);
export const getUserMyStableEntities = (store: unknown): ChannelUFC[] =>
get(store, "programPage.userMyStableEntities", []);
export const getCancelLimitBetSlipEnabled = (store: unknown) =>
get(store, "capi.featureToggles.cancelLimitBetSlipEnabled", false);
export const getCancelLimitsBetSlipConf = (store: unknown) =>
parseCAPIMessage(store, "capi.messages.cancelLimitsBetSlipConf", null);
export const getStoredFreePastPerformace = (
store: Store
): Record<string, string>[] =>
get(store, "programPage.freePastPerformances", []);
export const getFppSectionContent = (store: Store): Record<string, string> =>
parseCAPIMessage(store, "capi.messages.fppSectionContent");
export const getEnableFppSection = (store: Store): Record<string, string> =>
get(store, "capi.featureToggles.enableFpp", false);
export const getEnableUrpConfirmModalRepeatBet = (store: unknown) =>
get(store, "capi.featureToggles.enableUrpConfirmModalRepeatBet", false);
export const getRunnerModifierPreferences = (
store: Store
): PreferenceRunnerModifier | undefined =>
get(store, "userData.preferences.runnerModifier");
export const getEventDate = (store: unknown): Date | null =>
new Date(get(store, "home.eventInfo.eventDate", null));
export const getDerbyRace = (store: unknown): Race | undefined =>
get(store, "home.derbyRace");
export const getHomepageEventTrackAbbr = (store: unknown): string =>
get(store, "home.eventInfo.trackAbbr", "");
export const getHomepageCurrentConfig = (store: unknown): DerbyEventStatus =>
get(store, "home.currentConfig", DerbyEventStatus.POST);
export const getHomepageDerbyBanner = (store: unknown): HomepageHeaderBanner =>
get(store, "home.derbyBanner", undefined);
export const getDerbyBannerImageToggle = (store: unknown) =>
get(store, "capi.featureToggles.useDerbyBannerImage", false);
export const getHomepageEventName = (store: unknown): HomepageEventBannerText =>
get(store, "home.eventInfo.eventName", {
label: "",
size: 0
});
export const getshowStoryblokHomeToggle = (store: Store): boolean =>
get(store, "capi.featureToggles.showStoryblokHome", false);
export const getBonusFundsFeedbackEnabled = (store: Store): boolean =>
get(store, "capi.featureToggles.enableBonusFundsFeedback", false);
export const getAddToBetSlipOriginMobile = (store: unknown) =>
get(store, "programPage.addToBetSlipOriginMobile", "");
export const getBetSourceModule = (store: Store): string | undefined =>
get(store, "BetSource.module");
export const getTodayDate = (store: unknown): Date => {
const currentLocalDate = new Date();
const raceDate: UTCDate = get(store, "mtpStatus.raceDate", "")
.split("-")
.map((date: string, i: number) => {
const parsedDate = +date;
return MONTH_INDEX === i ? parsedDate - 1 : parsedDate;
});
const todayDate: UTCDate =
raceDate.length === 4
? raceDate
: [
currentLocalDate.getUTCFullYear(),
currentLocalDate.getUTCMonth(),
currentLocalDate.getUTCDate(),
currentLocalDate.getUTCHours()
];
return new Date(Date.UTC(...todayDate));
};
export const getEnableURPAlternates = (store: Store): boolean =>
get(store, "capi.featureToggles.enableURPAlternates", false);
export const getAlternateSelectionsMessages = (
store: Store
): AlternateSelectionsMessages =>
parseCAPIMessage(
store,
"capi.messages.alternateSelectionsMessages",
alternateSelectionsMessagesDefault
);
export const getIsAlternateSelectionModalOpen = (store: unknown) =>
get(store, "programPage.isAlternateSelectionModalOpen", false);
export const getShowAddToMyStableEnabled = (store: Store): boolean =>
get(store, "capi.featureToggles.showAddToMyStable", false);
export const getDisableSpecialWagers = (store: Store): boolean =>
get(store, "capi.featureToggles.disableSpecialWagers", false);
export const getBetPromoBannerContent = (
store: Store
): BetPromoBannerContent | undefined =>
get(store, "programPage.betPromoBannerContent", undefined);
export const getURPRaceAlertsEnabled = (
store: Store
): BetPromoBannerContent | undefined =>
get(store, "capi.featureToggles.enableURPRaceAlerts", false);
export const getTriggerConfirmationModalFromUrl = (store: Store) =>
get(store, "programPage.triggerConfirmationModalFromUrl", false);
export const getRunnerBI = (store: Store): RunnerBI | undefined =>
get(store, "programPage.selectedRunnerBI", undefined);
export const getFollowHorseMessages = (store: Store): MyStableMessages =>
parseCAPIMessage(
store,
"capi.messages.followHorseMessages",
defaultFollowHorseMessages
);
export const getTalentPicksSelectedTalent = (store: Store) =>
get(store, "talentPicks.talent.selectedTalent", null);
webpack://frontend-mybets/../../packages/tvg-comp-mtp-update/src/actions.ts
import type { RaceStatusEnum } from "@tvg/ts-types/Race";
export type MtpStatus = {
id: string;
mtp: number;
tvgRaceId: number;
postTime: string;
trackCode: string;
trackName: string;
number: string;
status: {
code: RaceStatusEnum;
};
};
type MtpUpdateAction = {
type: "MTP_STATUS_UPDATE";
payload: { mtpStatus: MtpStatus[]; raceDate: string };
};
type MtpRacesUpdateAction = {
type: "UPDATE_MTP_RACES";
payload: { races: MtpStatus[] };
};
type MtpRaceDateAction = {
type: "UPDATE_MTP_RACEDATE";
payload: { raceDate: string };
};
export type Actions =
| MtpUpdateAction
| MtpRacesUpdateAction
| MtpRaceDateAction;
export const MtpUpdate = (
mtpUpdate: MtpStatus[],
raceDate: string
): MtpUpdateAction => ({
type: "MTP_STATUS_UPDATE",
payload: { mtpStatus: mtpUpdate, raceDate }
});
export const MtpRacesUpdate = (races: MtpStatus[]): MtpRacesUpdateAction => ({
type: "UPDATE_MTP_RACES",
payload: { races }
});
export const MtpRaceDate = (raceDate: string): MtpRaceDateAction => ({
type: "UPDATE_MTP_RACEDATE",
payload: { raceDate }
});
export default MtpUpdate;
webpack://frontend-mybets/../../packages/tvg-comp-mtp-update/src/hooks/useMtpUpdate.ts
import { useEffect, useState } from "react";
import { gql, useQuery, useSubscription } from "@apollo/client";
import tvgConf from "@tvg/conf";
import { Race } from "@tvg/ts-types/Race";
import { useWagerProfile } from "@tvg/custom-hooks";
import { useDispatch, useSelector } from "react-redux";
import mediator from "@tvg/mediator";
import { getHasRequestedLogin } from "@tvg/pp/src/store/selectors";
import { ApplicationState } from "@tvg/tracks/src/v2/redux/types";
import { get, isArray } from "lodash";
import { MtpRacesUpdate, MtpRaceDate } from "../actions";
export const getDateRace = (store: ApplicationState) =>
get(store, "mtpStatus.raceDate");
export const MTP_GLOBAL_UPDATE = gql`
subscription raceMtpUpdate(
$wagerProfile: String!
$product: String
$device: String
$brand: String
) {
featuredTrackAndRaceMtpOrStatusUpdate(profile: $wagerProfile) {
id
tvgRaceId
mtp
postTime
track {
id
code
featured
name
}
trackCode
trackName
highlighted(product: $product, device: $device, brand: $brand) {
description
pinnedOrder
action
style
}
promos(product: $product, brand: $brand) {
rootParentPromoID
isAboveTheLine
promoPath
isPromoTagShown
}
type {
code
}
status {
code
}
video {
liveStreaming
streams
onTvg
onTvg2
hasReplay
}
}
}
`;
const useMtpUpdate = (shouldRunSubscription: boolean) => {
const wagerProfile: string = useWagerProfile();
const hasRequestedLogin = useSelector(getHasRequestedLogin);
const [shouldSkip, setShouldSkip] = useState(true);
const raceDate = useSelector(getDateRace);
const dispatch = useDispatch();
const { data } = useQuery(
gql`
query getRaceDate {
raceDate
}
`,
{
pollInterval: 300000,
fetchPolicy: "network-only",
ssr: false
}
);
useEffect(() => {
if (wagerProfile && hasRequestedLogin && shouldRunSubscription) {
setShouldSkip(false);
}
}, [wagerProfile, hasRequestedLogin]);
useEffect(() => {
if (data?.raceDate && raceDate !== data.raceDate) {
dispatch(MtpRaceDate(data.raceDate));
}
}, [data?.raceDate]);
useSubscription(MTP_GLOBAL_UPDATE, {
variables: {
wagerProfile,
...tvgConf().graphContext()
},
skip: shouldSkip,
onData: (result) => {
const updatedData =
result?.data?.data?.featuredTrackAndRaceMtpOrStatusUpdate;
if (updatedData) {
dispatch(MtpRacesUpdate(updatedData || []));
}
mediator.base.dispatch({
type: "URP:MTP_UPDATE",
payload: {
data: updatedData
}
});
if (
((isArray(updatedData) && updatedData) || []).some(
(raceData: Race) => raceData.status.code === "RO"
)
) {
mediator.base.dispatch({
type: "URP:MTP_UPDATE_CLOSED_RACES",
payload: {}
});
}
}
});
};
export default useMtpUpdate;
webpack://frontend-mybets/../../packages/tvg-lib-custom-hooks/hooks/useWagerProfile.ts
import { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import { getPortByBrand } from "@tvg/utils/generalUtils";
import { getWagerProfile } from "@urp/store-selectors";
const useWagerProfile = () => {
const userProfile: string = useSelector(getWagerProfile);
const [wagerProfile, setWagerProfile] = useState("");
useEffect(() => {
if (userProfile) {
setWagerProfile(userProfile);
} else {
// TODO IMPLEMENT BRAND BASE PORT
setWagerProfile(getPortByBrand());
}
}, [userProfile]);
return wagerProfile;
};
export default useWagerProfile;
webpack://frontend-mybets/../../packages/tvg-comp-mtp-update/src/graphql/queries/MTPStatusUpdate.ts
import { gql } from "@apollo/client";
export const GET_RACES_MTP_STATUS = gql`
query getRacesMtpStatus(
$wagerProfile: String
$sortBy: RaceListSort
$filterBy: RaceListFilter
$filterByRO: RaceListFilter
$pageRO: Pagination
$sortByRO: RaceListSort
) {
raceDate
mtpRaces: races(filter: $filterBy, profile: $wagerProfile, sort: $sortBy) {
id
tvgRaceId
track {
id
code
featured
name
}
trackCode
trackName
number
mtp
postTime
status {
code
}
video {
liveStreaming
streams
onTvg
onTvg2
hasReplay
}
}
resultsRaces: races(
filter: $filterByRO
sort: $sortByRO
page: $pageRO
profile: $wagerProfile
) {
id
tvgRaceId
mtp
status {
code
}
}
}
`;
export default GET_RACES_MTP_STATUS;
webpack://frontend-mybets/../../packages/tvg-comp-mtp-update/src/graphql/options.graph.ts
import type { RaceStatusEnum } from "@tvg/ts-types/Race";
import { get } from "lodash";
import { getPortByBrand } from "@tvg/utils/generalUtils";
import Props, { QueryProps } from "../types";
const INCLUDE_GREYHOUNDS = true;
const QUERY_VARIABLES: QueryProps = {
filterBy: {
status: ["O", "SK", "IC"],
allRaceClasses: INCLUDE_GREYHOUNDS
},
sortBy: { byPostTime: "ASC" },
filterByRO: {
allRaceClasses: INCLUDE_GREYHOUNDS,
status: ["RO"]
},
sortByRO: { byPostTime: "DESC" },
pageRO: { results: 30, current: 0 }
};
const POLL_INTERVAL = 20000;
const POLL_INTERVAL_SUBSCRIPTION = 0;
type GraphMtpStatusResult = {
id: string;
mtp: number;
status: {
code: RaceStatusEnum;
};
};
type GraphMTPStatusResults = {
mtpRaces: GraphMtpStatusResult[];
resultsRaces: GraphMtpStatusResult[];
raceDate: string;
};
export default {
options: (props: Props) => {
if (!props.removeStartIn) {
QUERY_VARIABLES.filterBy = {
...QUERY_VARIABLES.filterBy,
startIn: 60
};
}
const variables = {
...QUERY_VARIABLES,
wagerProfile: props.wagerProfile || getPortByBrand()
};
return {
pollInterval: props.shouldRunSubscription
? POLL_INTERVAL_SUBSCRIPTION
: POLL_INTERVAL,
fetchPolicy: "cache-and-network",
ssr: false,
variables
};
},
props: (result: GraphMTPStatusResults) => ({
mtpRaces: [
...get(result, "data.mtpRaces", []),
...get(result, "data.resultsRaces", [])
],
raceDate: get(result, "data.raceDate", "")
})
};
webpack://frontend-mybets/../../packages/tvg-comp-mtp-update/src/index.tsx
import { useEffect } from "react";
import { connect, useDispatch, useSelector } from "react-redux";
import { graphql } from "@apollo/client/react/hoc";
import { get } from "lodash";
import useMtpUpdate, { getDateRace } from "./hooks/useMtpUpdate";
// @ts-ignore
import MTPStatusQuery from "./graphql/queries/MTPStatusUpdate";
import ApolloOptions from "./graphql/options.graph";
import { MtpRaceDate, MtpRacesUpdate } from "./actions";
import Props from "./types";
export const MtpStatusComponent = ({
mtpRaces,
raceDate,
children,
shouldRunSubscription
}: Props) => {
const dispatch = useDispatch();
const storedRaceDate = useSelector(getDateRace);
useMtpUpdate(shouldRunSubscription);
useEffect(() => {
if (raceDate && raceDate !== storedRaceDate) {
dispatch(MtpRaceDate(raceDate));
}
}, [raceDate]);
useEffect(() => {
dispatch(MtpRacesUpdate(mtpRaces || []));
}, [mtpRaces]);
return children;
};
export default connect(
(store) => ({
wagerProfile: get(store, "userData.user.profile", "PORT-Generic"),
shouldRunSubscription: get(
store,
"capi.featureToggles.mtpUpdateSubscriptionMblEnabled",
false
)
}),
(dispatch) => ({ dispatch })
// @ts-ignore
)(graphql(MTPStatusQuery, ApolloOptions)(MtpStatusComponent));
webpack://frontend-mybets/../../node_modules/date-fns/esm/isBefore/index.js
import toDate from '../toDate/index.js';
import requiredArgs from '../_lib/requiredArgs/index.js';
/**
* @name isBefore
* @category Common Helpers
* @summary Is the first date before the second one?
*
* @description
* Is the first date before the second one?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date that should be before the other one to return true
* @param {Date|Number} dateToCompare - the date to compare with
* @returns {Boolean} the first date is before the second date
* @throws {TypeError} 2 arguments required
*
* @example
* // Is 10 July 1989 before 11 February 1987?
* var result = isBefore(new Date(1989, 6, 10), new Date(1987, 1, 11))
* //=> false
*/
export default function isBefore(dirtyDate, dirtyDateToCompare) {
requiredArgs(2, arguments);
var date = toDate(dirtyDate);
var dateToCompare = toDate(dirtyDateToCompare);
return date.getTime() < dateToCompare.getTime();
}
webpack://frontend-mybets/../../packages/sh-lib-my-bets/utils/raceDetails.ts
import {
RaceInfoMyBetsResults,
RaceInfoMyBets,
RaceVideoFeedback,
RaceStatusEnum,
RaceInfoMyBetsRunner,
RaceLegStatus,
RaceTypeCodeEnum
} from "@tvg/ts-types/Race";
import { useSelector } from "react-redux";
import { get, first, find, every } from "lodash";
import { isBefore } from "date-fns";
import { CheckRaceStatus } from "@tvg/sh-lib-my-bets/utils/types";
import { WagerTypeCodesEnum } from "@tvg/ts-types/Wager";
import { WroWagerGroup } from "@tvg/ts-types/WroWager";
import { Selections, SelectionRunner } from "@tvg/ts-types/Selections";
import { getXsellBlacklistedMyBets } from "../redux/selectors";
type Props = {
isMultiRace: boolean;
isSettledBet: boolean;
isCancelled: boolean;
legRaces: Array<RaceInfoMyBets>;
currentRace?: RaceInfoMyBets;
currentLeg?: RaceInfoMyBets;
bet: WroWagerGroup;
currentRaceDate: string;
betDate: string;
videoFeedback: RaceVideoFeedback;
raceNumber: number;
};
const betTypesCodes = {
exotic: [
"EX",
"EKB",
"EXB",
"EXW",
"EXK",
"TR",
"TRB",
"TRW",
"TRK",
"TKB",
"SU",
"SUB",
"SUK",
"SUW",
"SKB",
"SH5",
"H5B",
"H5W",
"S5K",
"5KB",
"QN",
"QNB",
"OM",
"OMB",
"TI",
"TIB"
],
multiRace: [
"DB",
"P3",
"P4",
"P5",
"P6",
"P7",
"P8",
"P9",
"P10",
"P11",
"P12",
"A3",
"A4",
"A5",
"A6",
"A7",
"A8",
"A9",
"A10",
"A11",
"A12",
"L3",
"L4",
"L5",
"L6",
"L7",
"L8",
"L9",
"L10",
"GS"
],
pickBet: [
"DB",
"P3",
"P4",
"P5",
"P6",
"P7",
"P8",
"P9",
"P10",
"P11",
"P12"
],
pickBetScratchRules: [
"DB",
"P3",
"P4",
"P5",
"P6",
"A3",
"A4",
"A5",
"A6",
"GS"
],
pickBetSub: ["P4", "P5", "P6", "A4", "A5", "A6", "GS"],
keyBoxWheel: [
"EXB",
"EXK",
"EXW",
"EKB",
"TRB",
"TRK",
"TRW",
"TKB",
"SUB",
"SUK",
"SUW",
"SKB",
"H5B",
"S5K",
"H5W",
"5KB",
"QNB",
"QNW",
"OMB",
"OMW",
"TIB",
"TIW"
]
};
export const getPickAll = (
pickType: string,
startNumber: number,
endNumber: number
): Array<string> =>
new Array(endNumber - startNumber + 1)
.fill(pickType)
.map((value: string, index) => `${value}${index + startNumber}`);
export const isPickBetWithInvalidResults = (wagerType: string) =>
["GS", ...getPickAll("L", 3, 20)].includes(wagerType);
export const isPicketBetScratchRules = (betTypesCode: WagerTypeCodesEnum) =>
betTypesCodes.pickBetScratchRules.includes(betTypesCode);
export const isPickBetSub = (betTypesCode: WagerTypeCodesEnum) =>
betTypesCodes.pickBetSub.includes(betTypesCode);
export const isPickBetWager = (betTypeCode: WagerTypeCodesEnum) =>
betTypesCodes.pickBet.includes(betTypeCode);
export const isMultiRaceBet = (betTypeCode: WagerTypeCodesEnum) =>
betTypesCodes.multiRace.includes(betTypeCode);
export const isExoticBet = (betTypeCode: WagerTypeCodesEnum) =>
betTypesCodes.exotic.includes(betTypeCode);
export const useIsXsellBlacklistedBet = (
betTypeCode: WagerTypeCodesEnum,
isURPPpOnXSellEnabled: boolean
) => {
const blacklistedBets = useSelector(getXsellBlacklistedMyBets);
return (
!isURPPpOnXSellEnabled &&
blacklistedBets.blacklistedBets.includes(betTypeCode)
);
};
export const getWinnerBI = (
results: RaceInfoMyBetsResults,
finishPosition: number = 1
) => {
const runners = get(results, "runners") || [];
return runners.reduce((acc: RaceInfoMyBetsRunner[], runner) => {
if (runner.finishPosition === finishPosition) {
const currentRunner = { ...runner };
return [...acc, currentRunner];
}
return acc;
}, []);
};
export const shouldShowWillPays = (
races: RaceInfoMyBets[],
selection: Selections[],
results: RaceInfoMyBetsResults[],
finalBettedLeg: number
) => {
let showWillPays = false;
const lastFinishedRace = first(
races
.filter((race) => race.status.code === "RO")
.sort((a, b) => +b.number - +a.number)
);
const lastFinishedLeg = lastFinishedRace ? lastFinishedRace.number : 0;
const currentLeg = +lastFinishedLeg + 1;
const isTrackOver = races.findIndex((race) => +race.number === 1) === -1;
if (!isTrackOver && finalBettedLeg - currentLeg === 0 && results) {
const finishedResults = results
? results.filter((result) => result !== null)
: [];
if (finishedResults.length === selection.length - 1) {
const isWinningSoFar = Array(selection.length - 1);
// eslint-disable-next-line
finishedResults.forEach((result, index) => {
if (result.runners) {
const winnerBI = getWinnerBI(result);
isWinningSoFar[index as number] = !!selection[
index as number
].runners.find(
(runner: SelectionRunner) =>
!!winnerBI &&
(+runner.number === +get(winnerBI, "[0].biNumber", -1) ||
+runner.number === +get(winnerBI, "[1].biNumber", -1))
);
}
});
if (isWinningSoFar.every((w) => w)) {
showWillPays = true;
}
}
}
return showWillPays;
};
export const getActiveLegs = (
races: RaceInfoMyBets[],
raceNumber: number,
length: number
) =>
races
.filter(
(race) =>
race.number >= +raceNumber && race.number <= +raceNumber + length - 1
)
.filter((race) => race.status.code !== RaceStatusEnum.RACE_OFFICIAL);
export const getRacesInPickBets = (
races: RaceInfoMyBets[],
raceNumber: number,
length: number
) =>
races.filter(
(race) =>
race.number >= +raceNumber && race.number <= +raceNumber + length - 1
);
export const getRaceProps = ({
isMultiRace,
isSettledBet,
legRaces,
currentRace,
currentLeg,
bet,
currentRaceDate,
betDate,
videoFeedback,
raceNumber,
isCancelled
}: Props) => {
let statusCode: RaceStatusEnum = get(currentRace, "status.code");
const raceType: RaceTypeCodeEnum = get(bet, "wagers[0].raceTypeAbbreviation");
if (currentRace && !statusCode) {
statusCode = RaceStatusEnum.OPEN;
}
if (
(!currentRace && !statusCode) ||
isBefore(new Date(betDate), new Date(currentRaceDate))
) {
statusCode = RaceStatusEnum.RACE_OFFICIAL;
}
const hasLiveVideo =
currentRaceDate === betDate &&
(isMultiRace && currentLeg && !isSettledBet
? videoFeedback.indexOf("AVAILABLE") === 0 &&
currentLeg.status.code !== RaceStatusEnum.RACE_OFFICIAL &&
currentLeg.status.code !== RaceStatusEnum.MANUALLY_CLOSED
: videoFeedback.indexOf("AVAILABLE") === 0 &&
statusCode !== RaceStatusEnum.RACE_OFFICIAL &&
statusCode !== RaceStatusEnum.MANUALLY_CLOSED);
if (isMultiRace && currentLeg && (!isSettledBet || isCancelled)) {
const currentLegNumber =
legRaces &&
currentLeg &&
legRaces.findIndex((race) => race.number === currentLeg.number) + 1;
const mtp = isCancelled
? get(currentRace, "mtp", 0)
: get(currentLeg, "mtp", 0);
const legStatusCode = isCancelled
? get(currentRace, "status.code")
: get(currentLeg, "status.code");
const currentRaceNumber = currentLegNumber + raceNumber - 1;
return {
mtp,
postTime: currentLeg.postTime,
statusCode,
legStatusCode,
legNumber: currentLegNumber,
currentRaceNumber,
hasLiveVideo: hasLiveVideo && mtp <= 60,
raceType
};
}
const mtp = get(currentLeg, "mtp", null) || get(currentRace, "mtp", 0);
return {
mtp,
postTime: get(bet, "wagers[0].racePostTime"),
statusCode,
legStatusCode: null,
legNumber: 0,
currentRaceNumber: raceNumber,
hasLiveVideo: hasLiveVideo && mtp <= 60,
raceType
};
};
export const getRaceStatus = ({
isAllRunnersScratched,
legContainsScratch,
isMultiRace,
selectionIndex,
selection,
races,
raceNumber,
selectionLength,
isCanceled,
betStatusName,
wagerType,
favoriteRunner,
shouldShowReplacement
}: CheckRaceStatus) => {
const winnerBI = !!find(selection, { isWinner: true });
const isRaceActive = betStatusName?.toLowerCase() === "active";
const isInvalidWagerType = isPickBetWithInvalidResults(wagerType);
let raceStatus: RaceLegStatus = "open";
if (isMultiRace) {
if (isRaceActive) {
if (get(races, "length", 0) > 0) {
const legRaces = getRacesInPickBets(races, raceNumber, selectionLength);
const legStatus = get(legRaces, `${selectionIndex}.status.code`);
const legResults = get(legRaces, `${selectionIndex}.results`);
const activeLegs = getActiveLegs(races, raceNumber, selectionLength);
const currentActiveLeg = first(activeLegs);
if (winnerBI) {
raceStatus = "win";
} else if (!legResults && legStatus === RaceStatusEnum.RACE_OFFICIAL) {
raceStatus = "raceOff";
} else if (
(!legStatus || legStatus === RaceStatusEnum.RACE_OFFICIAL) &&
!winnerBI
) {
raceStatus = "lost";
} else if (
activeLegs.length > 0 &&
currentActiveLeg?.number &&
+currentActiveLeg?.number === +raceNumber + selectionIndex &&
currentActiveLeg.status.code !== RaceStatusEnum.MANUALLY_CLOSED
) {
raceStatus = "raceOff";
} else if (isAllRunnersScratched || legContainsScratch) {
raceStatus = "attention";
}
} else if (selectionIndex === 0) {
raceStatus = "raceOff";
}
} else if (!isCanceled) {
const isUnknownStatus = get(selection, "0.isWinner") === null;
const alternateBI = get(
find(
selection,
(item) =>
every(get(item, "runners", []), { isScratched: true }) &&
get(item, "alternate")
),
"alternate"
);
const isAlternateWinnerBI = get(alternateBI, "isWinner", false);
if (isUnknownStatus) {
raceStatus = "unknown";
} else if (winnerBI || isAlternateWinnerBI) {
raceStatus = "win";
} else {
raceStatus = "lost";
const isAlternateScratched = every(get(alternateBI, "runners", []), {
isScratched: true
});
const showFavoriteRunnerStatus = !alternateBI || isAlternateScratched;
if (
favoriteRunner &&
favoriteRunner.isWinner &&
isAllRunnersScratched &&
shouldShowReplacement &&
showFavoriteRunnerStatus
) {
raceStatus = "win";
}
}
}
}
if (
!["open", "raceOff", "attention"].includes(raceStatus) &&
isInvalidWagerType
) {
raceStatus = "unknown";
}
return raceStatus;
};
export const getRacesIds = (bets: WroWagerGroup[] = []): Array<string> =>
bets.map((bet) => {
const [, trackCode] = bet.value.split("|");
return trackCode;
});
export const isRaceOff = (status: RaceStatusEnum): boolean =>
status === RaceStatusEnum.RACE_OFF || status === RaceStatusEnum.RACE_OFFICIAL;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/utils/general.ts
import { get } from "lodash";
import { useEffect, useLayoutEffect } from "react";
import { Location } from "react-router-dom";
import { Dispatch } from "redux";
import { History } from "@tvg/ts-types/History";
import mediator from "@tvg/mediator";
import {
BetCancelResult,
CheckSelectionLabel
} from "@tvg/sh-lib-my-bets/utils/types";
import formatSequencial from "@tvg/formatter/numeric";
import { BetSelection, BetStatus } from "@tvg/ts-types/Bet";
import {
BettingInterest,
RaceInfoMyBets,
RaceStatusEnum,
RaceWagerType
} from "@tvg/ts-types/Race";
import { isEqual } from "date-fns";
import { Selections } from "@tvg/ts-types/Selections";
import { WroWager } from "@tvg/ts-types/WroWager";
import { TabKey } from "@tvg/ts-types/Generic";
import { NullaryFn, UnaryFn } from "@tvg/ts-types/Functional";
import { ActiveTabEnum, SettledTabEnum } from "./types";
import { closeMyBetsStandalone } from "../redux/actions";
import { onToggleShowDetails } from "./gtm";
import {
isExoticBet,
isMultiRaceBet,
isPickBetWager,
useIsXsellBlacklistedBet
} from "./raceDetails";
export const calculateProbableValue = (
comboAmount: number,
minWagerAmount: number,
userAmount: number
): number => (comboAmount * userAmount) / minWagerAmount;
export const SELECTIONS_MODIFIERS = {
KEY: "KY",
KEY_BOX: "KYBX",
BOX: "BX"
};
export const isSuccessBetCancel = (betCancelNotification: BetCancelResult) =>
get(betCancelNotification, "status", "") === "success";
export const closeModal = (
dispatch: Dispatch,
location?: Location,
history?: History
) => {
if (location !== undefined && history !== undefined) {
const currentPath = `${location.pathname}${location.search}`;
history.push(currentPath);
}
dispatch(closeMyBetsStandalone());
mediator.base.dispatch({ type: "MYBETS_MODAL_CLOSE" });
};
export const scrollToView = (element: Element | HTMLElement | null) => {
if (
element &&
typeof window !== "undefined" &&
window.navigator &&
window.navigator.userAgent &&
typeof get(element, "scrollIntoView") === "function"
) {
const ua = window.navigator.userAgent;
if (
(!!ua.match(/Safari/i) || !!ua.match(/AppleWebKit/i)) &&
!ua.match(/Chrome/i)
) {
setTimeout(() => {
element.scrollIntoView();
}, 0);
} else {
element.scrollIntoView();
}
}
};
export const scrollActivePillIntoView = () => {
const elements = document.getElementsByClassName("active");
if (elements) {
Array.from(elements).forEach((el) => {
if (el.className.includes("PillAtom")) {
scrollToView(el);
}
});
}
};
export const scrollActiveBetIntoView = (indexBuffer: number) => {
if (indexBuffer !== 0) {
const elmnt = document.getElementById(`activebet-${indexBuffer}`);
scrollToView(elmnt);
}
};
export const useIsomorphicLayoutEffect =
typeof window !== "undefined" ? useLayoutEffect : useEffect;
export const changeTab = (
selectedTab: TabKey,
setSelectedTab: UnaryFn<TabKey, void>
) => {
setSelectedTab(selectedTab);
return true;
};
export const getWinType = (winningsAmount: number, betAmount: number) => {
let winType;
if (winningsAmount < betAmount * 5) {
winType = "SmallWin";
} else if (
winningsAmount >= betAmount * 5 &&
winningsAmount < betAmount * 10
) {
winType = "Win";
} else if (winningsAmount >= betAmount * 10) {
winType = "BigWin";
}
return winType;
};
export const getSelectionLabel = ({
raceNumber,
selectionLength,
selectionIndex,
selectionsModifier,
isMultiRace,
isKey,
isBox,
isDesktop,
isSpecialWager = false
}: CheckSelectionLabel) => {
const isKeyRace = isKey || selectionsModifier === SELECTIONS_MODIFIERS.KEY;
const isKeyBox = isBox || selectionsModifier === SELECTIONS_MODIFIERS.KEY_BOX;
const isBoxRace = isBox || selectionsModifier === SELECTIONS_MODIFIERS.BOX;
let pickBetsLabelLength = 10;
let key = false;
let label = "";
// check multiple selections
if (selectionLength > 1) {
key =
(selectionIndex === 0 && isKeyRace) || (selectionIndex === 0 && isKeyBox);
if (isKeyBox && selectionIndex !== 0) {
label = "Box";
} else if (isKeyRace && selectionIndex !== 0) {
label = "W/";
} else {
const legNumber = selectionIndex + 1;
if (!isMultiRace) {
label = formatSequencial(legNumber);
} else {
label = isDesktop
? `${isSpecialWager ? "L" : "R"}${raceNumber + selectionIndex}`
: `LEG ${legNumber} - R${raceNumber + selectionIndex}`;
}
}
} else if (isBoxRace) {
label = "Box";
}
if (selectionLength >= 10 && raceNumber + selectionLength > 10) {
pickBetsLabelLength = 12;
} else if (selectionLength >= 10 || raceNumber + selectionLength > 10) {
pickBetsLabelLength = 11;
}
return {
label,
key,
pickBetsLabelLength
};
};
export const checkAllDetailedViewIsOpen = (showBetsDetailedView: boolean[]) =>
showBetsDetailedView &&
!!showBetsDetailedView.length &&
typeof showBetsDetailedView.find((isOpen) => !isOpen) === "undefined";
export const toggleAllDetailViews = (
showBetsDetailedView: boolean[],
setShowBetsDetailedView: UnaryFn<Array<boolean>, void>,
selections: BetSelection[][] | Selections[][] = []
) => {
const closeAll = checkAllDetailedViewIsOpen(showBetsDetailedView);
const showBetsDetailedViewState = new Array(selections.length).fill(
!closeAll
);
setShowBetsDetailedView(showBetsDetailedViewState);
};
export const setShowContent = (
value: boolean,
id: string,
showContentObj: Record<string, boolean>,
setShowContentObj: UnaryFn<Record<string, boolean>, void>
) => {
const auxObj = { ...showContentObj };
auxObj[id] = value;
setShowContentObj(auxObj);
};
export const handleDetailsButton = (
selectedTab: ActiveTabEnum,
selectedSettledTab: SettledTabEnum,
isDetailsOpened: boolean,
showBetsDetailedView: boolean[],
setShowBetsDetailedView: UnaryFn<boolean[], void>,
// eslint-disable-next-line @typescript-eslint/default-param-last
selections: BetSelection[][] | Selections[][] = [],
handleScrollPosition: NullaryFn<void>,
totalActiveBets?: number,
totalSettledBets?: number
) => {
onToggleShowDetails({
selectedTab,
selectedSettledTab,
show: !isDetailsOpened,
activeBetsCount: totalActiveBets,
settledBetsCount: totalSettledBets
});
toggleAllDetailViews(
showBetsDetailedView,
setShowBetsDetailedView,
selections
);
handleScrollPosition();
};
export const getWagerToRender = (
wagers: WroWager[],
selectedWager?: WroWager
) => {
if (selectedWager) {
return [selectedWager];
}
return wagers;
};
// Rule to protect wagers being shown from previous day when BE doesnt have new info from TOTE
export const shouldRenderWager = (
selectedTab: ActiveTabEnum,
currentRaceDate: string,
wagerRaceDate: string,
trackNameFilters?: string[],
trackName?: string
) => {
if (trackNameFilters && trackNameFilters.length && trackName) {
return trackNameFilters.includes(trackName);
}
return selectedTab !== "ACTIVE" || currentRaceDate === wagerRaceDate;
};
export const checkWagerIsCancelable = (
wager: WroWager,
statusCode: RaceStatusEnum
) => {
const cancelableStatus: RaceStatusEnum[] = [
RaceStatusEnum.OPEN,
RaceStatusEnum.UP_NEXT
];
return (
get(wager, "cancelable", false) && cancelableStatus.includes(statusCode)
);
};
export const getWagerBetStatus = (wagerBetStatus: BetStatus) => ({
isCanceled: wagerBetStatus.name === "canceled",
isActive: wagerBetStatus.code === "A"
});
export const checkWagerIsBetWinner = (wager: WroWager) =>
get(wager, "winningsAmount", 0) > get(wager, "betTotal", 0);
export const getWagerProps = (
wager: WroWager,
statusCode: RaceStatusEnum,
currentRaceDate: string,
mainWagerDetails: string,
isURPPpOnXSellEnabled: boolean,
currentRace?: RaceInfoMyBets
) => {
const wagerBetStatus = get(wager, "betStatus", {} as BetStatus);
const currentWagerTypeCode = get(wager, "wagerType.code", "");
const currentWagerTypeId = get(wager, "wagerType.id", 10);
const raceWagerTypes = get(currentRace, "wagerTypes", []);
const currentWagerTypeByRace = raceWagerTypes.find(
(wagerType: RaceWagerType) =>
get(wagerType, "type.id") === currentWagerTypeId
);
const isOptedIn = get(wager, "promoQualifying", false);
const isCurrentRaceDate = isEqual(
new Date(mainWagerDetails),
new Date(currentRaceDate)
);
const { isCanceled, isActive } = getWagerBetStatus(wagerBetStatus);
const isWagerCancelable = checkWagerIsCancelable(wager, statusCode);
const isMultiRace = isMultiRaceBet(currentWagerTypeCode);
const isPickBet = isPickBetWager(currentWagerTypeCode);
const isExotic = isExoticBet(currentWagerTypeCode);
const isXsellBlacklisted = useIsXsellBlacklistedBet(
currentWagerTypeCode,
isURPPpOnXSellEnabled
);
const isBetWinner = checkWagerIsBetWinner(wager);
const isWheel = get(currentWagerTypeByRace, "isWheel", false);
const isKey = get(currentWagerTypeByRace, "isKey", false);
const isBox = get(currentWagerTypeByRace, "isBox", false);
return {
wagerBetStatus,
isCurrentRaceDate,
isCanceled,
isActive,
currentWagerTypeCode,
currentWagerTypeId,
isWagerCancelable,
isMultiRace,
isPickBet,
isExotic,
isBetWinner,
isOptedIn,
isWheel,
isKey,
isBox,
isXsellBlacklisted
};
};
export const isFavoriteRunner = (
raceDate: string,
currentBiNumber: number,
race?: RaceInfoMyBets
): boolean => {
const bettingInterestsRaceDate = get(race, `raceDate`, "");
if (bettingInterestsRaceDate === raceDate) {
const bettingInterests = get(
race,
`bettingInterests`,
[] as Array<BettingInterest>
);
return bettingInterests.reduce(
(isFavorite: boolean, betInterests: BettingInterest) => {
const betInterestsFavorite =
get(betInterests, "favorite", false) ||
get(betInterests, "isFavorite", false);
const biNumber = get(betInterests, "biNumber");
return (
isFavorite ||
(bettingInterestsRaceDate === raceDate &&
betInterestsFavorite &&
biNumber === currentBiNumber)
);
},
false
);
}
return false;
};
webpack://frontend-mybets/../../node_modules/date-fns/esm/isEqual/index.js
import toDate from '../toDate/index.js';
import requiredArgs from '../_lib/requiredArgs/index.js';
/**
* @name isEqual
* @category Common Helpers
* @summary Are the given dates equal?
*
* @description
* Are the given dates equal?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the first date to compare
* @param {Date|Number} dateRight - the second date to compare
* @returns {Boolean} the dates are equal
* @throws {TypeError} 2 arguments required
*
* @example
* // Are 2 July 2014 06:30:45.000 and 2 July 2014 06:30:45.500 equal?
* var result = isEqual(
* new Date(2014, 6, 2, 6, 30, 45, 0),
* new Date(2014, 6, 2, 6, 30, 45, 500)
* )
* //=> false
*/
export default function isEqual(dirtyLeftDate, dirtyRightDate) {
requiredArgs(2, arguments);
var dateLeft = toDate(dirtyLeftDate);
var dateRight = toDate(dirtyRightDate);
return dateLeft.getTime() === dateRight.getTime();
}
webpack://frontend-mybets/../../packages/tvg-comp-desktop-bet-ticket/src/utils/groupByWagerType.ts
import { cloneDeep, isEmpty, get } from "lodash";
import { WagerTypes, WagerTypesGroup } from "@tvg/ts-types/Wager";
import { RaceWagerType } from "@tvg/ts-types/Race";
const groupedPlace = [
WagerTypes.WIN_PLACE,
WagerTypes.PLACE_SHOW,
WagerTypes.WIN_PLACE_SHOW
];
const groupedShow = [
WagerTypes.WIN_SHOW,
WagerTypes.PLACE_SHOW,
WagerTypes.WIN_PLACE_SHOW
];
export const getLegGroup = (wagerType: WagerTypes) => {
switch (wagerType) {
case WagerTypes.WIN_PLACE:
case WagerTypes.PLACE_SHOW:
case WagerTypes.WIN_SHOW:
return 2;
case WagerTypes.WIN_PLACE_SHOW:
return 3;
default:
return 1;
}
};
const setGroupWagerTypes = (
wagerTypesList: RaceWagerType[],
wagerGroupList: RaceWagerType[]
) =>
wagerTypesList.map((wagerType) => {
const wagerTypeGroupped = { ...wagerType };
const specialGroup =
(wagerType.group.id === WagerTypes.WIN &&
wagerType.type.id !== WagerTypes.WIN) ||
(wagerType.group.id === WagerTypes.PLACE &&
wagerType.type.id !== WagerTypes.PLACE);
if (!wagerTypeGroupped.types) {
wagerTypeGroupped.specialGroup = specialGroup;
wagerTypeGroupped.types = specialGroup ? wagerGroupList : [];
}
return wagerTypeGroupped;
});
const groupWinPlaceShow = (
newWagerType: RaceWagerType,
wagerTypeList: RaceWagerType[]
) => {
let foundGroupIndex = -1;
const filteredList = wagerTypeList;
const filteredWagerType = cloneDeep(newWagerType);
if (
filteredWagerType.type.id === WagerTypes.PLACE ||
filteredWagerType.type.id === WagerTypes.SHOW
) {
return wagerTypeList;
}
if (filteredWagerType.type.id === WagerTypes.WIN) {
return [...wagerTypeList, filteredWagerType];
}
filteredWagerType.columnCount = getLegGroup(filteredWagerType.type.id);
foundGroupIndex = filteredList.findIndex(
(wagerTypeFiltered) =>
wagerTypeFiltered.type.id === WagerTypes.WIN_PLACE ||
wagerTypeFiltered.type.id === WagerTypes.WIN_SHOW ||
wagerTypeFiltered.type.id === WagerTypes.PLACE_SHOW ||
wagerTypeFiltered.type.id === WagerTypes.WIN_PLACE_SHOW
);
if (foundGroupIndex >= 0) {
// eslint-disable-next-line security/detect-object-injection
filteredList[foundGroupIndex] = filteredWagerType;
} else {
return [...filteredList, filteredWagerType];
}
return filteredList;
};
const groupByWagerType = (wagerTypes: RaceWagerType[]) => {
let groupedWagerTypes: RaceWagerType[] = [];
const winGroup: RaceWagerType[] = [];
if (wagerTypes && wagerTypes.length > 0) {
groupedWagerTypes = wagerTypes.reduce<RaceWagerType[]>(
(arrayFiltered, wagerType) => {
const foundEqual = arrayFiltered.find(
(item) => item.group.id === wagerType.group.id
);
if (WagerTypesGroup.WIN_PLACE_SHOW.includes(wagerType.group.id)) {
winGroup.push(cloneDeep(wagerType));
return groupWinPlaceShow(wagerType, arrayFiltered);
}
if (
foundEqual &&
!WagerTypesGroup.WIN_PLACE_SHOW.includes(wagerType.group.id)
) {
return [...arrayFiltered, wagerType];
}
if (!foundEqual) {
return [...arrayFiltered, wagerType];
}
return arrayFiltered;
},
[]
);
if (
isEmpty(groupedWagerTypes) ||
!groupedWagerTypes.find((wagerTypeItem) =>
groupedShow.includes(wagerTypeItem.type.id)
)
) {
const showWagerType = wagerTypes.find(
(wager) => get(wager, "type.id") === WagerTypes.SHOW
);
groupedWagerTypes = showWagerType
? [showWagerType, ...groupedWagerTypes]
: groupedWagerTypes;
}
if (
isEmpty(groupedWagerTypes) ||
!groupedWagerTypes.some((wagerTypeItem) =>
groupedPlace.includes(wagerTypeItem.type.id)
)
) {
const placeWagerType = wagerTypes.find(
(wager) => get(wager, "type.id") === WagerTypes.PLACE
);
groupedWagerTypes = placeWagerType
? [placeWagerType, ...groupedWagerTypes]
: groupedWagerTypes;
}
}
return setGroupWagerTypes(groupedWagerTypes, winGroup);
};
export default groupByWagerType;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/utils/potentialReturn.ts
import { isEmpty, flatten, get, size } from "lodash";
import { Probable, RaceWagerType, ProbableBetCombo } from "@tvg/ts-types/Race";
import formatCurrency, {
formatPurseWithoutCurrency
} from "@tvg/formatter/currency";
import { WagerTypes, WagerTypesPos, WagerType } from "@tvg/ts-types/Wager";
import { exactaAndDailyDouble } from "./potentialReturn/exactaAndDailyDouble";
import { quinella } from "./potentialReturn/quinella";
import { placeAndShow } from "./potentialReturn/placeAndShow";
import { win } from "./potentialReturn/win";
import { BetComboHash } from "./types";
export const doesRaceWagerTypeHasProbables = (
probables: Probable[],
currentWagerTypeId: number
): boolean => {
if (!isEmpty(probables) && currentWagerTypeId) {
let probableIndex = -1;
// Checking if has index there for it means we have a probable for current wager type
if (
currentWagerTypeId === WagerTypes.WIN_PLACE ||
currentWagerTypeId === WagerTypes.WIN_SHOW ||
currentWagerTypeId === WagerTypes.PLACE_SHOW ||
currentWagerTypeId === WagerTypes.WIN_PLACE_SHOW
) {
[WagerTypes.WIN, WagerTypes.PLACE, WagerTypes.SHOW].forEach((type) => {
const possibleIndex = probables.findIndex(
(probable: Probable) => probable.wagerType.id === type
);
if (possibleIndex > -1) {
probableIndex = possibleIndex;
}
});
} else {
probableIndex = probables.findIndex(
(probable: Probable) => probable.wagerType.id === currentWagerTypeId
);
}
if (probableIndex > -1) {
return true;
}
}
return false;
};
export const formatProbableAmountList = (
probableAmountList: number[],
betAmount: number,
betsNumber: number = 1
): string => {
const probableAmountLength = probableAmountList.length;
// To ensure that minimum probable value is always more than my initial bet amount
const probableAmountDefault = betAmount * 1.05;
const minValue =
Math.max(Math.min(...probableAmountList), probableAmountDefault) *
betsNumber;
const maxValue =
Math.max(...probableAmountList, probableAmountDefault) * betsNumber;
if (!probableAmountLength) {
return "0";
}
if (probableAmountLength === 1) {
return probableAmountList[0] > 999
? formatPurseWithoutCurrency(probableAmountList[0] * betsNumber)
: formatCurrency(probableAmountList[0] * betsNumber);
}
const minValueFormated =
minValue > 999
? formatPurseWithoutCurrency(minValue)
: formatCurrency(minValue);
const maxValueFormated =
maxValue > 999
? formatPurseWithoutCurrency(maxValue)
: formatCurrency(maxValue);
if (minValueFormated === maxValueFormated) {
return minValueFormated;
}
if (minValueFormated === "$0.00" && maxValueFormated !== "$0.00") {
return maxValueFormated;
}
return `${minValueFormated} - ${maxValueFormated}`;
};
export const getBetCombosHash = (betCombos: ProbableBetCombo[]): BetComboHash =>
betCombos.reduce(
(accumulator: BetComboHash, currentValue: ProbableBetCombo) => {
const newValue: BetComboHash = {};
if (currentValue.runner2 === null) {
newValue[currentValue.runner1] = currentValue.payout;
} else {
newValue[`${currentValue.runner1}-${currentValue.runner2}`] =
currentValue.payout;
}
return {
...accumulator,
...newValue
};
},
{}
);
export const getKindOfSpecialGroupType = (
betSelections: string[][],
wagerType: RaceWagerType | WagerType | null
): number[] => {
const type = get(wagerType, "id") || get(wagerType, "type.id");
const isSpecialGroup = !![
WagerTypes.WIN_PLACE,
WagerTypes.WIN_SHOW,
WagerTypes.PLACE_SHOW,
WagerTypes.WIN_PLACE_SHOW
].find((id) => id === type);
// Check if is multiple wager types and max runners is 3
if (isSpecialGroup) {
const MAX_RUNNERS = 3;
if (betSelections[0].length <= MAX_RUNNERS) {
let specialGroup: number[];
switch (type) {
case WagerTypes.WIN_PLACE:
specialGroup = [WagerTypes.WIN, WagerTypes.PLACE];
break;
case WagerTypes.WIN_SHOW:
specialGroup = [WagerTypes.WIN, WagerTypes.SHOW];
break;
case WagerTypes.PLACE_SHOW:
specialGroup = [WagerTypes.PLACE, WagerTypes.SHOW];
break;
case WagerTypes.WIN_PLACE_SHOW:
specialGroup = [WagerTypes.WIN, WagerTypes.PLACE, WagerTypes.SHOW];
break;
default:
specialGroup = [];
}
return specialGroup;
}
}
return [];
};
export const getProbableValues = (
probableIndex: number,
probables: Probable[],
betSelections: string[][],
betAmount: number
): number[] => {
if (probableIndex !== -1) {
// Search and calculate probable
const { wagerType, minWagerAmount, betCombos } = probables[probableIndex];
// Turn betCombo into an hashTable
const betCombosHash = getBetCombosHash(betCombos);
// Find which payout we want to multiply
const typesProps = {
betSelections,
betCombosHash,
minWagerAmount,
betAmount
};
switch (wagerType.id) {
// Exacta
case WagerTypes.EXACTA:
return exactaAndDailyDouble(typesProps);
// Daily Double
case WagerTypes.DAILY_DOUBLE:
return exactaAndDailyDouble(typesProps);
// Quinella
case WagerTypes.QUINELLA:
return quinella(typesProps);
// Show
case WagerTypes.SHOW:
return placeAndShow({
...typesProps,
wagerTypeId: wagerType.id
});
// Place
case WagerTypes.PLACE:
return placeAndShow({
...typesProps,
wagerTypeId: wagerType.id
});
// Win
case WagerTypes.WIN:
return win(typesProps);
default:
return [];
}
}
return [];
};
export const hasCalculatedProbable = (currentProbable: string = "0"): boolean =>
currentProbable !== "0";
export const getCurrentProbableValue = (
probables: Probable[],
currentWagerType: RaceWagerType | WagerType | null,
betAmount: number,
betSelections: string[][],
betsNumber: number = 1
): string => {
let probableValueList: number[] = [];
if (
isEmpty(probables) ||
isEmpty(currentWagerType) ||
!betAmount ||
isEmpty(flatten(betSelections))
) {
return "0";
}
let probableIndex = -1;
const specialGroupWagerTypes = getKindOfSpecialGroupType(
betSelections,
currentWagerType
);
if (specialGroupWagerTypes.length) {
const allProbables = specialGroupWagerTypes.map((wagerTypeId) => {
const probIndex = probables.findIndex(
(probable: Probable) => probable.wagerType.id === wagerTypeId
);
return getProbableValues(probIndex, probables, betSelections, betAmount);
});
// Check if it has invalid probable
if (allProbables.find((probable) => !size(probable))) {
return "0";
}
let minOfMin = 999999;
let maxOfWin = 0;
let maxOfPlace = 0;
let maxOfShow = 0;
allProbables.forEach((probable, index) => {
// Get the biggest numbers for each wager
if (index === WagerTypesPos.Win) {
maxOfWin = Math.max(...probable);
} else if (index === WagerTypesPos.Place) {
maxOfPlace = Math.max(...probable);
} else if (index === WagerTypesPos.Show) {
maxOfShow = Math.max(...probable);
}
// Get the lowest number but checking on each wager
const currentMinNumber = Math.min(...probable);
if (currentMinNumber < minOfMin) {
minOfMin = currentMinNumber;
}
});
const sumOfWagerTypes = maxOfWin + maxOfPlace + maxOfShow;
probableValueList = [minOfMin, sumOfWagerTypes];
} else {
probableIndex = probables.findIndex(
(probable: Probable) =>
probable.wagerType.id === get(currentWagerType, "type.id") ||
probable.wagerType.id === get(currentWagerType, "id")
);
probableValueList = getProbableValues(
probableIndex,
probables,
betSelections,
betAmount
);
}
return formatProbableAmountList(probableValueList, betAmount, betsNumber);
};
webpack://frontend-mybets/../../packages/sh-lib-my-bets/utils/potentialReturn/exactaAndDailyDouble.ts
import { get, isNaN } from "lodash";
import { PotentialReturn, ProbableValueList } from "../types";
import { calculateProbableValue } from "../general";
export const exactaAndDailyDouble = ({
betSelections,
betCombosHash,
minWagerAmount,
betAmount
}: PotentialReturn): ProbableValueList => {
const probableValueList: ProbableValueList = [];
const firstPlaceSelectionsLength = get(betSelections, "[0].length", 0);
const secondPlaceSelectionsLength = get(betSelections, "[1].length", 0);
if (firstPlaceSelectionsLength > 0 && secondPlaceSelectionsLength > 0) {
try {
// There are selections, now find combinations and add payouts to probableValueList
get(betSelections, "[0]", []).forEach((firstPlaceSelection: string) => {
get(betSelections, "[1]", []).forEach(
(secondPlaceSelection: string) => {
const payout =
+betCombosHash[`${firstPlaceSelection}-${secondPlaceSelection}`];
if (!isNaN(payout)) {
if (payout) {
probableValueList.push(
calculateProbableValue(payout, minWagerAmount, betAmount)
);
}
} else {
throw new Error("NaN");
}
}
);
});
} catch (e) {
return [];
}
}
return probableValueList;
};
export default exactaAndDailyDouble;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/utils/potentialReturn/quinella.ts
import { get, isNaN } from "lodash";
import { PotentialReturn, ProbableValueList } from "../types";
import { calculateProbableValue } from "../general";
export const quinella = ({
betSelections,
betCombosHash,
minWagerAmount,
betAmount
}: PotentialReturn): ProbableValueList => {
const probableValueList: ProbableValueList = [];
const first = get(betSelections, "[0][0]", "");
const second = get(betSelections, "[0][1]", "");
if (first && second) {
const payout = +betCombosHash[`${first}-${second}`];
try {
if (!isNaN(payout)) {
if (payout) {
probableValueList.push(
calculateProbableValue(payout, minWagerAmount, betAmount)
);
}
} else {
throw new Error("NaN");
}
} catch (e) {
return [];
}
}
return probableValueList;
};
export default quinella;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/utils/potentialReturn/placeAndShow.ts
import { isNaN } from "lodash";
import { PotentialReturn, ProbableValueList } from "../types";
import { calculateProbableValue } from "../general";
export const placeAndShow = ({
betSelections,
betCombosHash,
minWagerAmount,
betAmount,
wagerTypeId
}: PotentialReturn): ProbableValueList => {
const probableValueList: ProbableValueList = [];
const comboHashKeys = Object.keys(betCombosHash);
const hashLength = Number(
comboHashKeys[comboHashKeys.length - 1].split("-")[0]
);
const payoutsMaximum: number[] = [];
try {
betSelections[0].forEach((betSelection) => {
const runnerPayoutList: number[] = [];
// P.S: I KNOW, it can be `i++` but just complain eslint... (we can change this rule later :) )
for (let i = 1; i <= hashLength; i += 1) {
const payout = +betCombosHash[`${i}-${betSelection}`];
if (!isNaN(payout)) {
if (payout) {
probableValueList.push(
calculateProbableValue(payout, minWagerAmount, betAmount)
);
}
} else {
throw new Error("NaN");
}
runnerPayoutList.push(payout);
}
// Check biggest runner payout and add to payouts maximum
payoutsMaximum.push(Math.max(...runnerPayoutList));
});
} catch (e) {
return [];
}
// Check the biggest 2 (Place) | 3 (Show) runners payouts and add to probable value list
if (payoutsMaximum.length > 2) {
const sortedPayoutsMaximum = payoutsMaximum.sort();
const sortedPayoutsMaximumLength = sortedPayoutsMaximum.length;
let payoutsSum =
sortedPayoutsMaximum[sortedPayoutsMaximumLength - 1] +
sortedPayoutsMaximum[sortedPayoutsMaximumLength - 2];
if (wagerTypeId === 30) {
// Show requires to sum the third biggest payout
payoutsSum += sortedPayoutsMaximum[sortedPayoutsMaximumLength - 3];
}
probableValueList.push(
calculateProbableValue(payoutsSum, minWagerAmount, betAmount)
);
} else {
// Sum payouts available (1 OR 2 can be sum here)
probableValueList.push(
calculateProbableValue(
payoutsMaximum.reduce((acc, value) => acc + value, 0),
minWagerAmount,
betAmount
)
);
}
return probableValueList;
};
export default placeAndShow;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/utils/potentialReturn/win.ts
import { isNaN } from "lodash";
import { PotentialReturn, ProbableValueList } from "../types";
import { calculateProbableValue } from "../general";
export const win = ({
betSelections,
betCombosHash,
minWagerAmount,
betAmount
}: PotentialReturn): ProbableValueList => {
const probableValueList: ProbableValueList = [];
try {
betSelections[0].forEach((betSelection) => {
const payout = +betCombosHash[betSelection];
if (!isNaN(payout)) {
if (payout) {
probableValueList.push(
calculateProbableValue(payout, minWagerAmount, betAmount)
);
}
} else {
throw new Error("NaN");
}
});
} catch (e) {
return [];
}
return probableValueList;
};
export default win;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/hooks/useMyBetsSubscription.ts
import { useEffect } from "react";
import { get } from "lodash";
import { UnaryFn } from "@tvg/ts-types/Functional";
import { SettledTabEnum, ActiveTabEnum, SelectedFilters } from "../utils/types";
import { getQueryFilters } from "../utils/filters";
export const updateQueryFunction = (
prev: unknown,
{
subscriptionData
}: {
subscriptionData: {
data: {
wagerHistoryUpdate: {
totals?: Object;
groupWagers: Object[];
trackFilter?: string;
wagerTypeFilter?: string;
} | null;
};
};
}
) => {
if (
!subscriptionData ||
!subscriptionData.data ||
!subscriptionData.data.wagerHistoryUpdate
) {
return prev;
}
// Updates Apollo cache to latest subscription update / component props
return {
wagerHistory: {
id: get(subscriptionData, "data.wagerHistoryUpdate.id"),
futureWagersList: {
wagers: null,
totals: null,
...get(prev, "wagerHistory.futureWagersList"),
...get(subscriptionData, "data.wagerHistoryUpdate.futureWagersList")
},
totals: {
...get(prev, "wagerHistory.totals", {}),
...subscriptionData.data.wagerHistoryUpdate.totals
},
groupWagersList: {
...get(prev, "wagerHistory.groupWagersList", {}),
wagerGroups: [...subscriptionData.data.wagerHistoryUpdate.groupWagers]
},
trackFilter: subscriptionData.data.wagerHistoryUpdate.trackFilter,
wagerTypeFilter: subscriptionData.data.wagerHistoryUpdate.wagerTypeFilter
}
};
};
function useMyBetsSubscription(
WagersSubscription: unknown,
isLogged: boolean,
subscribeToMore: UnaryFn<unknown, void>,
selectedTab: ActiveTabEnum,
selectedSettledTab: SettledTabEnum,
filters: SelectedFilters | null,
isCustomTimeFrame: boolean | null,
accountNumber?: string
) {
useEffect(() => {
const isSettledTodayBetsTab = selectedSettledTab === "TODAY";
let unsubscribe: Function | void | null;
if (
isLogged &&
accountNumber !== undefined &&
accountNumber !== "" &&
typeof subscribeToMore === "function" &&
isSettledTodayBetsTab &&
!isCustomTimeFrame
) {
const queryFilters = getQueryFilters(selectedTab, filters) || {};
unsubscribe = subscribeToMore({
document: WagersSubscription,
variables: {
accountId: parseInt(accountNumber, 10),
...queryFilters
},
updateQuery: updateQueryFunction
});
}
// On component will unmount, unsubscribes to websocket
return () => {
if (typeof unsubscribe === "function") {
unsubscribe();
unsubscribe = null;
}
};
}, [
subscribeToMore,
isLogged,
accountNumber,
selectedTab,
selectedSettledTab,
filters,
isCustomTimeFrame
]);
return null;
}
export default useMyBetsSubscription;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/hooks/useGraphRacesSubscription.ts
import { useEffect } from "react";
import { get } from "lodash";
import { UnaryFn } from "@tvg/ts-types/Functional";
import { RaceInfoMyBets, RaceProgram } from "@tvg/ts-types/Race";
import { WroWagerGroup } from "@tvg/ts-types/WroWager";
import { getRacesIds } from "../utils/raceDetails";
import { SettledTabEnum } from "../utils/types";
let unsubscribe: Function | void | null;
interface prevInterface {
raceDate: string;
races: Array<RaceInfoMyBets | RaceProgram>;
}
interface subscriptionInterface {
subscriptionData: {
data: {
racesByTrackCodes: Array<RaceInfoMyBets | RaceProgram>;
};
};
}
export const updateRacesQueryFunction = (
prev: prevInterface,
{ subscriptionData }: subscriptionInterface
) => {
if (!get(subscriptionData, "data.racesByTrackCodes.length")) {
return prev;
}
const races = [...get(prev, "races", [])];
const updatedRaces = get(subscriptionData, "data.racesByTrackCodes", []);
const newRaces = races.map((race) => {
const { id: currentRaceId } = race;
const updatedRaceIndex = updatedRaces.findIndex(
(updatedRace: RaceInfoMyBets | RaceProgram) =>
updatedRace.id === currentRaceId
);
const newRace =
updatedRaceIndex !== -1
? { ...race, ...updatedRaces[updatedRaceIndex] }
: race;
if (updatedRaceIndex !== -1) {
updatedRaces.splice(updatedRaceIndex, 1);
}
return newRace;
});
return {
raceDate: prev.raceDate,
races: newRaces
};
};
function useGraphRacesSubscription(
RacesSubscription: unknown,
isLogged: boolean,
subscribeToMore: UnaryFn<unknown, void>,
selectedSettledTab: SettledTabEnum,
wagerProfile: string,
bets: WroWagerGroup[]
) {
useEffect(() => {
const races = getRacesIds(bets);
const isSettledTodayBetsTab = selectedSettledTab === SettledTabEnum.TODAY;
if (
isLogged &&
bets.length &&
typeof subscribeToMore === "function" &&
isSettledTodayBetsTab
) {
unsubscribe = subscribeToMore({
document: RacesSubscription,
variables: { wagerProfile, races },
updateQuery: updateRacesQueryFunction
});
} else if (typeof unsubscribe === "function") {
unsubscribe();
unsubscribe = null;
}
// On component will unmount, unsubscribes to websocket
return () => {
if (typeof unsubscribe === "function") {
unsubscribe();
unsubscribe = null;
}
};
}, [subscribeToMore, isLogged, selectedSettledTab, JSON.stringify(bets)]);
return null;
}
export default useGraphRacesSubscription;
webpack://frontend-mybets/../../node_modules/date-fns/esm/addDays/index.js
import toInteger from '../_lib/toInteger/index.js';
import toDate from '../toDate/index.js';
import requiredArgs from '../_lib/requiredArgs/index.js';
/**
* @name addDays
* @category Day Helpers
* @summary Add the specified number of days to the given date.
*
* @description
* Add the specified number of days to the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of days to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} the new date with the days added
* @throws {TypeError} 2 arguments required
*
* @example
* // Add 10 days to 1 September 2014:
* var result = addDays(new Date(2014, 8, 1), 10)
* //=> Thu Sep 11 2014 00:00:00
*/
export default function addDays(dirtyDate, dirtyAmount) {
requiredArgs(2, arguments);
var date = toDate(dirtyDate);
var amount = toInteger(dirtyAmount);
if (isNaN(amount)) {
return new Date(NaN);
}
if (!amount) {
// If 0 days, no-op to avoid changing times in the hour before end of DST
return date;
}
date.setDate(date.getDate() + amount);
return date;
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/subDays/index.js
import toInteger from '../_lib/toInteger/index.js';
import addDays from '../addDays/index.js';
import requiredArgs from '../_lib/requiredArgs/index.js';
/**
* @name subDays
* @category Day Helpers
* @summary Subtract the specified number of days from the given date.
*
* @description
* Subtract the specified number of days from the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of days to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} the new date with the days subtracted
* @throws {TypeError} 2 arguments required
*
* @example
* // Subtract 10 days from 1 September 2014:
* var result = subDays(new Date(2014, 8, 1), 10)
* //=> Fri Aug 22 2014 00:00:00
*/
export default function subDays(dirtyDate, dirtyAmount) {
requiredArgs(2, arguments);
var amount = toInteger(dirtyAmount);
return addDays(dirtyDate, -amount);
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/subWeeks/index.js
import toInteger from '../_lib/toInteger/index.js';
import addWeeks from '../addWeeks/index.js';
import requiredArgs from '../_lib/requiredArgs/index.js';
/**
* @name subWeeks
* @category Week Helpers
* @summary Subtract the specified number of weeks from the given date.
*
* @description
* Subtract the specified number of weeks from the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of weeks to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} the new date with the weeks subtracted
* @throws {TypeError} 2 arguments required
*
* @example
* // Subtract 4 weeks from 1 September 2014:
* var result = subWeeks(new Date(2014, 8, 1), 4)
* //=> Mon Aug 04 2014 00:00:00
*/
export default function subWeeks(dirtyDate, dirtyAmount) {
requiredArgs(2, arguments);
var amount = toInteger(dirtyAmount);
return addWeeks(dirtyDate, -amount);
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/addWeeks/index.js
import toInteger from '../_lib/toInteger/index.js';
import addDays from '../addDays/index.js';
import requiredArgs from '../_lib/requiredArgs/index.js';
/**
* @name addWeeks
* @category Week Helpers
* @summary Add the specified number of weeks to the given date.
*
* @description
* Add the specified number of week to the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of weeks to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} the new date with the weeks added
* @throws {TypeError} 2 arguments required
*
* @example
* // Add 4 weeks to 1 September 2014:
* var result = addWeeks(new Date(2014, 8, 1), 4)
* //=> Mon Sep 29 2014 00:00:00
*/
export default function addWeeks(dirtyDate, dirtyAmount) {
requiredArgs(2, arguments);
var amount = toInteger(dirtyAmount);
var days = amount * 7;
return addDays(dirtyDate, days);
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/subMonths/index.js
import toInteger from '../_lib/toInteger/index.js';
import addMonths from '../addMonths/index.js';
import requiredArgs from '../_lib/requiredArgs/index.js';
/**
* @name subMonths
* @category Month Helpers
* @summary Subtract the specified number of months from the given date.
*
* @description
* Subtract the specified number of months from the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of months to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} the new date with the months subtracted
* @throws {TypeError} 2 arguments required
*
* @example
* // Subtract 5 months from 1 February 2015:
* var result = subMonths(new Date(2015, 1, 1), 5)
* //=> Mon Sep 01 2014 00:00:00
*/
export default function subMonths(dirtyDate, dirtyAmount) {
requiredArgs(2, arguments);
var amount = toInteger(dirtyAmount);
return addMonths(dirtyDate, -amount);
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/addMonths/index.js
import toInteger from '../_lib/toInteger/index.js';
import toDate from '../toDate/index.js';
import requiredArgs from '../_lib/requiredArgs/index.js';
/**
* @name addMonths
* @category Month Helpers
* @summary Add the specified number of months to the given date.
*
* @description
* Add the specified number of months to the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of months to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} the new date with the months added
* @throws {TypeError} 2 arguments required
*
* @example
* // Add 5 months to 1 September 2014:
* var result = addMonths(new Date(2014, 8, 1), 5)
* //=> Sun Feb 01 2015 00:00:00
*/
export default function addMonths(dirtyDate, dirtyAmount) {
requiredArgs(2, arguments);
var date = toDate(dirtyDate);
var amount = toInteger(dirtyAmount);
if (isNaN(amount)) {
return new Date(NaN);
}
if (!amount) {
// If 0 months, no-op to avoid changing times in the hour before end of DST
return date;
}
var dayOfMonth = date.getDate(); // The JS Date object supports date math by accepting out-of-bounds values for
// month, day, etc. For example, new Date(2020, 1, 0) returns 31 Dec 2019 and
// new Date(2020, 13, 1) returns 1 Feb 2021. This is *almost* the behavior we
// want except that dates will wrap around the end of a month, meaning that
// new Date(2020, 13, 31) will return 3 Mar 2021 not 28 Feb 2021 as desired. So
// we'll default to the end of the desired month by adding 1 to the desired
// month and using a date of 0 to back up one day to the end of the desired
// month.
var endOfDesiredMonth = new Date(date.getTime());
endOfDesiredMonth.setMonth(date.getMonth() + amount + 1, 0);
var daysInMonth = endOfDesiredMonth.getDate();
if (dayOfMonth >= daysInMonth) {
// If we're already at the end of the month, then this is the correct date
// and we're done.
return endOfDesiredMonth;
} else {
// Otherwise, we now know that setting the original day-of-month value won't
// cause an overflow, so set the desired day-of-month. Note that we can't
// just set the date of `endOfDesiredMonth` because that object may have had
// its time changed in the unusual case where where a DST transition was on
// the last day of the month and its local time was in the hour skipped or
// repeated next to a DST transition. So we use `date` instead which is
// guaranteed to still have the original time.
date.setFullYear(endOfDesiredMonth.getFullYear(), endOfDesiredMonth.getMonth(), dayOfMonth);
return date;
}
}
webpack://frontend-mybets/../../packages/sh-lib-my-bets/graphql/behgOptions.graph.ts
import { graphql } from "@apollo/client/react/hoc";
import { BinaryFn, UnaryFn } from "@tvg/ts-types/Functional";
import { get, set } from "lodash";
import { format, subDays, subWeeks, subMonths } from "date-fns";
import { WroWager, WroWagerGroup } from "@tvg/ts-types/WroWager";
import { WatchQueryFetchPolicy } from "@apollo/client";
import { getQueryFilters } from "../utils/filters";
import { GraphResponse, Props } from "../utils/types";
export const getVariables = (props: Props) => {
const hasCustomDate = props.customStartDate && props.customStartDate !== "";
const hasPagination = props.selectedSettledTab !== "TODAY" || hasCustomDate;
const settledTab = props.selectedTab.toLowerCase() === "settled";
let startDate = props.customStartDate
? new Date(props.customStartDate)
: new Date();
const endDate = props.customEndDate
? new Date(props.customEndDate)
: new Date();
if (settledTab && !hasCustomDate) {
const settledStartTimes = {
TODAY: startDate,
YESTERDAY: subDays(startDate, 1),
LAST_WEEK: subWeeks(startDate, 1),
LAST_MONTH: subMonths(startDate, 1)
};
startDate = settledStartTimes[props.selectedSettledTab];
}
const { statusFilters, trackFilters, betTypeFilters } = props;
const queryFilters = getQueryFilters(props.selectedTab, {
statusFilters,
trackFilters,
betTypeFilters
});
// Conditional for IOS because the web format fails in native
return {
startDate: format(startDate, "yyyy-MM-dd"),
endDate: format(endDate, "yyyy-MM-dd"),
accountId: parseInt(props.accountNumber, 10),
pagination: hasPagination
? {
current: 0,
results: get(props, "myBetsPaginationConf.wagersPerPage", 20)
}
: null,
...(queryFilters || {})
};
};
type WagerHistory = { wagerHistory: { groupWagersList: { wagerGroups: [] } } };
type FetchMore = UnaryFn<
{
variables: {
pagination: {
current: number;
results: number;
};
};
updateQuery: BinaryFn<
WagerHistory,
{ fetchMoreResult: WagerHistory },
void
>;
},
Promise<{ data: WagerHistory }>
>;
export const onFetchMore = (
fetchMore: FetchMore,
page: number,
callback: UnaryFn<boolean, void>,
wagersPerPage: number
) =>
fetchMore({
variables: {
pagination: {
current: page,
results: wagersPerPage
}
},
updateQuery: (prev, { fetchMoreResult }) => {
if (!fetchMoreResult) {
return prev;
}
const nextWagerGroups =
fetchMoreResult.wagerHistory.groupWagersList.wagerGroups;
return {
wagerHistory: {
...fetchMoreResult.wagerHistory,
groupWagersList: {
...fetchMoreResult.wagerHistory.groupWagersList,
wagerGroups: [
...prev.wagerHistory.groupWagersList.wagerGroups,
...nextWagerGroups
]
}
}
};
}
}).then(({ data }) => {
const nextWagerGroups = data.wagerHistory.groupWagersList.wagerGroups;
const isDoneLoadingMore = nextWagerGroups.length < wagersPerPage;
callback(isDoneLoadingMore);
});
// @ts-ignore
const getProps = (result: graphql<GraphResponse>) => {
const isActiveBetsTab =
get(result, "ownProps.selectedTab", "").toLowerCase() === "active";
const isFutureBetsTab =
get(result, "ownProps.selectedTab", "").toLowerCase() === "futures";
const groupWagers = get(
result,
"data.wagerHistory.groupWagersList.wagerGroups",
[]
);
let totalBets = 0;
let totalAmount = 0;
const betsToReturn: {
value: string;
wagers: WroWager[];
}[] = [];
const raceBets = {};
groupWagers.forEach((eachGroup: WroWagerGroup) => {
const tempActiveBets: WroWager[] = [];
eachGroup.wagers.forEach((wager: WroWager) => {
const shouldPushWager = isActiveBetsTab
? wager.betStatus.code === "A"
: wager.betStatus.code !== "A";
const currentRaceBet: [] = get(raceBets, wager.tvgRaceId, []);
set(raceBets, wager.tvgRaceId, [...currentRaceBet, wager]);
if (shouldPushWager) {
totalAmount += wager.betTotal;
if (
!result.ownProps.deletedBets.includes(wager.serialNumber) ||
!isActiveBetsTab
) {
tempActiveBets.push(wager);
}
}
});
if (tempActiveBets.length > 0) {
totalBets += tempActiveBets.length;
tempActiveBets.sort(
(betA, betB) =>
+new Date(betB.transactionDate) - +new Date(betA.transactionDate)
);
betsToReturn.push({
value: eachGroup.value.replace(/#/gi, "|"),
wagers: tempActiveBets
});
}
});
betsToReturn.sort((wagerGroupA, wagerGroupB) =>
isActiveBetsTab
? +new Date(wagerGroupA.wagers[0].racePostTime) -
+new Date(wagerGroupB.wagers[0].racePostTime)
: +new Date(wagerGroupB.wagers[0].racePostTime) -
+new Date(wagerGroupA.wagers[0].racePostTime)
);
const futureWagerList = get(
result,
"data.wagerHistory.futureWagersList.wagers",
[]
);
const groups = ["raceDate", "trackCode", "raceNumber"];
// @TODO: refactor this old logic since we are pushing in the object grouped and grouped is not array type...
const grouped = {};
if (futureWagerList.length) {
futureWagerList.forEach((wager: WroWager) => {
groups
.reduce((acc, group) => {
// @ts-ignore
const g = wager[group].toString();
// @ts-ignore
acc[g] = acc[g] || [];
// @ts-ignore
return acc[g];
}, grouped)
// @ts-ignore
.push(wager);
});
}
// @ts-ignore
const futureWagers = [];
Object.keys(grouped).forEach((raceDate) => {
// @ts-ignore
Object.keys(grouped[raceDate]).forEach((trackCode) => {
// @ts-ignore
Object.keys(grouped[raceDate][trackCode]).forEach((raceNumber) => {
futureWagers.push({
value: `${raceDate}|${trackCode}|${raceNumber}`,
// @ts-ignore
wagers: grouped[raceDate][trackCode][raceNumber]
});
});
});
});
// @ts-ignore
const betsBuffer = isFutureBetsTab ? futureWagers : betsToReturn;
return {
queryBets: {
bets: betsBuffer,
totalBets,
totalAmount
},
subscribeToMore: result.data.loading ? null : result.data.subscribeToMore,
fetchMore: (callback: UnaryFn<boolean, void>, page: number) =>
onFetchMore(
result.data.fetchMore,
page,
callback,
get(result, "ownProps.myBetsPaginationConf.wagersPerPage", 20)
),
raceBets,
isLoadingBehg: result.data.loading,
queryTrackList: result.data?.wagerHistory?.trackFilter,
wagerTypeFilter: result.data?.wagerHistory?.wagerTypeFilter,
refetchBehg: result?.data?.refetch
};
};
export default {
skip: (props: Props) => !props.accountNumber,
options: (props: Props) => ({
fetchPolicy: "cache-and-network" as WatchQueryFetchPolicy,
nextFetchPolicy: "cache-first" as WatchQueryFetchPolicy,
client: props.behgClient,
ssr: false,
variables: getVariables(props)
}),
// @ts-ignore
props: (result: graphql<GraphResponse>) => ({
...getProps(result)
})
};
webpack://frontend-mybets/../../packages/sh-lib-my-bets/graphql/options.graph.ts
import { graphql } from "@apollo/client/react/hoc";
import { attempt, get } from "lodash";
import { WroWagerGroup } from "@tvg/ts-types/WroWager";
import { WatchQueryFetchPolicy } from "@apollo/client";
import { GraphResponse, Props } from "../utils/types";
const getRaces = (bets: WroWagerGroup[] = []): Array<{ trackCode: string }> =>
bets.map((bet) => {
const [, trackCode] = bet.value.split("|");
return { trackCode };
});
const getProps = (result: GraphResponse) => {
const props = {};
attempt(() => {
Object.assign(props, {
raceDate: result.loading
? get(result, "previousData.raceDate", "")
: result.raceDate,
races: result.loading
? get(result, "previousData.races", [])
: result.races,
isLoadingGraph: result.loading && result.networkStatus === 1,
subscribeToMoreGraph: result.loading ? null : result.subscribeToMore
});
});
return props;
};
export default {
skip: (props: Props) => get(props, "queryBets.bets.length", 0) === 0,
options: (props: Props) => ({
fetchPolicy: "cache-and-network" as WatchQueryFetchPolicy,
nextFetchPolicy: "cache-first" as WatchQueryFetchPolicy,
ssr: false,
variables: {
wagerProfile: get(props, "wagerProfile", ""),
races: getRaces(get(props, "queryBets.bets", []))
}
}),
// @ts-ignore
props: (result: graphql<GraphResponse>) => ({
...getProps(result.data)
})
};
webpack://frontend-mybets/../../packages/sh-lib-my-bets/graphql/queries/GroupWagers.ts
import { gql } from "@apollo/client";
export const GET_GROUP_WAGERS_MY_BETS = gql`
query GetGroupWagersMyBets(
$accountId: Int!
$startDate: String
$endDate: String
$statusList: [Status!]
$pagination: Pagination
$trackCodes: [String!]
$wagerTypes: [String!]
) {
wagerHistory(
beginDate: $startDate
accountId: $accountId
endDate: $endDate
statusList: $statusList
trackCodes: $trackCodes
wagerTypes: $wagerTypes
) {
id
wagerTypeFilter {
id
code
name
}
trackFilter {
code
name
}
totals {
totalCount
profit
winnings
refunded
totalAmount
}
groupWagersList(
group: { group: RACE, order: DESC }
pagination: $pagination
) {
wagerGroups {
value: key
wagers: value {
id
serialNumber
wagerAmount
betTotal: cost
betRefund
winningsAmount: winnings
betStatus {
code
name
}
transactionDate
wageringPlatform
wagerType {
id
code
name
}
promoQualifying
cancelableStatus {
code
name
}
cancelable
selections {
selectionString
modifier
selection {
bettingInterests {
currentOdds {
numerator
denominator
}
biNumber
isWinner
runners {
runnerId
scratched
horseName
}
payouts {
amount
wagerType {
code
}
}
}
alternateBettingInterest {
currentOdds {
numerator
denominator
}
biNumber
isWinner
runners {
runnerId
scratched
horseName
}
payouts {
amount
wagerType {
code
}
}
}
selectionType {
code
name
}
runners {
number
}
}
}
raceDate
racePostTime: postTime
raceTypeAbbreviation: raceType
tvgRaceId
trackName
wagerReference
}
}
}
futureWagersList {
totals {
totalCount
totalAmount
}
wagers {
id
serialNumber
wagerAmount
betTotal: cost
betRefund
winningsAmount: winnings
betStatus {
code
name
}
transactionDate
wageringPlatform
wagerType {
id
code
name
}
promoQualifying
cancelableStatus {
code
name
}
cancelable
selections {
selectionString
modifier
selection {
bettingInterests {
currentOdds {
numerator
denominator
}
biNumber
isWinner
runners {
runnerId
scratched
horseName
}
payouts {
amount
wagerType {
code
}
}
}
alternateBettingInterest {
currentOdds {
numerator
denominator
}
biNumber
isWinner
runners {
runnerId
scratched
horseName
}
payouts {
amount
wagerType {
code
}
}
}
selectionType {
code
name
}
runners {
number
}
}
}
raceDate
racePostTime: postTime
raceTypeAbbreviation: raceType
tvgRaceId
trackName
wagerReference
trackCode
raceNumber
}
}
}
}
`;
export default GET_GROUP_WAGERS_MY_BETS;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/graphql/queries/GroupWagersBehg.ts
import { gql } from "@apollo/client";
export const GET_GROUP_WAGERS_MY_BETS = gql`
query GetGroupWagersMyBets(
$accountId: Int!
$startDate: String
$endDate: String
$statusList: [Status!]
$pagination: Pagination
$trackCodes: [String!]
$wagerTypes: [String!]
) {
wagerHistory(
beginDate: $startDate
accountId: $accountId
endDate: $endDate
statusList: $statusList
trackCodes: $trackCodes
wagerTypes: $wagerTypes
) {
id
wagerTypeFilter {
id
code
name
}
trackFilter {
code
name
}
totals {
totalCount
profit
winnings
refunded
totalAmount
}
groupWagersList(
group: { group: RACE, order: DESC }
pagination: $pagination
) {
wagerGroups {
value: key
wagers: value {
id
serialNumber
wagerAmount
betTotal: cost
betRefund
winningsAmount: winnings
betStatus {
code
name
}
transactionDate
wageringPlatform
wagerType {
id
code
name
}
promoQualifying
cancelableStatus {
code
name
}
cancelable
selections {
selectionString
modifier
selection {
bettingInterests {
currentOdds {
numerator
denominator
}
biNumber
isWinner
runners {
runnerId
scratched
horseName
}
payouts {
amount
wagerType {
code
}
}
}
selectionType {
code
name
}
runners {
number
}
}
}
raceDate
racePostTime: postTime
raceTypeAbbreviation: raceType
tvgRaceId
trackName
wagerReference
}
}
}
futureWagersList {
totals {
totalCount
totalAmount
}
wagers {
id
serialNumber
wagerAmount
betTotal: cost
betRefund
winningsAmount: winnings
betStatus {
code
name
}
transactionDate
wageringPlatform
wagerType {
id
code
name
}
promoQualifying
cancelableStatus {
code
name
}
cancelable
selections {
selectionString
modifier
selection {
bettingInterests {
currentOdds {
numerator
denominator
}
biNumber
isWinner
runners {
runnerId
scratched
horseName
}
payouts {
amount
wagerType {
code
}
}
}
selectionType {
code
name
}
runners {
number
}
}
}
raceDate
racePostTime: postTime
raceTypeAbbreviation: raceType
tvgRaceId
trackName
wagerReference
trackCode
raceNumber
}
}
}
}
`;
export default GET_GROUP_WAGERS_MY_BETS;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/graphql/fragments/Probables.ts
import { gql } from "@apollo/client";
export const PROBABLES = gql`
fragment Probables on Race {
probables {
wagerType {
id
name
}
betCombos {
runner1
runner2
payout
}
minWagerAmount
}
}
`;
export default PROBABLES;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/graphql/fragments/BettingInterests.ts
import { gql } from "@apollo/client";
export const BETTING_INTERESTS = gql`
fragment BettingInterests on Race {
bettingInterests {
biNumber
numberColor
saddleColor
favorite
currentOdds {
numerator
denominator
}
morningLineOdds {
numerator
denominator
}
runners {
runnerId
scratched
horseName
trainer
jockey
scratched
}
}
}
`;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/graphql/fragments/Results.ts
import { gql } from "@apollo/client";
export const RESULTS = gql`
fragment Results on Race {
results {
runners {
betAmount
biNumber
finishPosition
placePayoff
runnerName
showPayoff
winPayoff
runnerNumber
timeform {
postRaceReport
accBeatenDistance
accBeatenDistanceStatus
}
}
payoffs {
selections {
payoutAmount
selection
}
wagerAmount
wagerType {
code
name
}
}
winningTime
}
}
`;
export default RESULTS;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/graphql/fragments/WillPays.ts
import { gql } from "@apollo/client";
export const WILL_PAYS = gql`
fragment WillPays on Race {
willPays {
wagerAmount
payOffType
type {
id
code
name
}
payouts {
bettingInterestNumber
payoutAmount
}
legResults {
legNumber
winningBi
}
}
}
`;
export default WILL_PAYS;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/graphql/fragments/WagerTypes.ts
import { gql } from "@apollo/client";
export const WAGER_TYPES = gql`
fragment WagerTypes on Race {
wagerTypes {
positionCount
minWagerAmount
wagerAmounts
columnCount
legCount
isBox
isKey
isWheel
type {
id
code
name
}
group {
id
code
name
}
}
}
`;
export default WAGER_TYPES;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/graphql/queries/AllWagerTypes.ts
import { gql } from "@apollo/client";
import { PROBABLES } from "../fragments/Probables";
import { BETTING_INTERESTS } from "../fragments/BettingInterests";
import { RESULTS } from "../fragments/Results";
import { WILL_PAYS } from "../fragments/WillPays";
import { WAGER_TYPES } from "../fragments/WagerTypes";
export const GET_ALL_WAGER_TYPES = gql`
query GetAllWagerTypes($wagerProfile: String, $races: [MatchRacesFilter]) {
raceDate
races(profile: $wagerProfile, filter: { matchRaces: $races }) {
id
tvgRaceId
raceDate
postTime
trackName
trackCode
number
mtp
isGreyhound
numRunners
distance
specialCardSourceRace {
raceDate
trackCode
trackName
raceNumber
}
surface {
shortName
defaultCondition
}
raceClass {
shortName
name
}
type {
code
name
shortName
}
purse
status {
code
}
video {
hasReplay
liveStreaming
mobileAvailable
replays
replayFileName
streams
}
track {
specialCardTypes: specialCardTypes {
specialCardTypeAbbreviation
specialCardTypeName
}
}
...Probables
...BettingInterests
...Results
...WillPays
...WagerTypes
}
}
${PROBABLES}
${BETTING_INTERESTS}
${RESULTS}
${WILL_PAYS}
${WAGER_TYPES}
`;
export default GET_ALL_WAGER_TYPES;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/graphql/queries/AllWagerTypesMep.ts
import { gql } from "@apollo/client";
import { PROBABLES } from "../fragments/Probables";
import { BETTING_INTERESTS } from "../fragments/BettingInterests";
import { RESULTS } from "../fragments/Results";
import { WILL_PAYS } from "../fragments/WillPays";
import { WAGER_TYPES } from "../fragments/WagerTypes";
export const GET_ALL_WAGER_TYPES = gql`
query GetAllWagerTypes($wagerProfile: String, $races: [MatchRacesFilter]) {
raceDate
races(profile: $wagerProfile, filter: { matchRaces: $races }) {
id
tvgRaceId
raceDate
postTime
trackName
trackCode
number
mtp
isGreyhound
numRunners
distance
surface {
shortName
defaultCondition
}
raceClass {
shortName
name
}
type {
code
name
shortName
}
purse
status {
code
}
video {
hasReplay
liveStreaming
mobileAvailable
replays
replayFileName
streams
}
...Probables
...BettingInterests
...Results
...WillPays
...WagerTypes
}
}
${PROBABLES}
${BETTING_INTERESTS}
${RESULTS}
${WILL_PAYS}
${WAGER_TYPES}
`;
export default GET_ALL_WAGER_TYPES;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/graphql/subscriptions/WagersSubscription.ts
import { gql } from "@apollo/client";
export const GET_GROUP_WAGERS_SUBSCRIPTION_MY_BETS = gql`
subscription GetGroupWagersSubscriptionMyBets(
$accountId: Int!
$statusList: [Status!]
$trackCodes: [String!]
$wagerTypes: [String!]
) {
wagerHistoryUpdate(
accountId: $accountId
statusList: $statusList
trackCodes: $trackCodes
wagerTypes: $wagerTypes
) {
id
wagerTypeFilter {
id
code
name
}
trackFilter {
code
name
}
totals(page: { current: 0, results: 99 }) {
totalCount
profit
winnings
refunded
totalAmount
}
groupWagers(group: { group: RACE, order: DESC }) {
id: key
value: key
wagers: value {
id
serialNumber
wagerAmount
betTotal: cost
betRefund
winningsAmount: winnings
betStatus {
code
name
}
transactionDate
wageringPlatform
wagerType {
id
code
name
}
promoQualifying
cancelableStatus {
code
name
}
cancelable
selections {
selectionString
modifier
selection {
bettingInterests {
currentOdds {
numerator
denominator
}
biNumber
isWinner
runners {
runnerId
scratched
horseName
}
payouts {
amount
wagerType {
code
}
}
}
alternateBettingInterest {
currentOdds {
numerator
denominator
}
biNumber
isWinner
runners {
runnerId
scratched
horseName
}
payouts {
amount
wagerType {
code
}
}
}
selectionType {
code
name
}
runners {
number
}
}
}
raceDate
racePostTime: postTime
raceTypeAbbreviation: raceType
tvgRaceId
trackName
wagerReference
}
}
futureWagersList {
wagers {
id
serialNumber
wagerAmount
betTotal: cost
betRefund
winningsAmount: winnings
betStatus {
code
name
}
transactionDate
wageringPlatform
wagerType {
id
code
name
}
promoQualifying
cancelableStatus {
code
name
}
cancelable
selections {
selectionString
modifier
selection {
bettingInterests {
currentOdds {
numerator
denominator
}
biNumber
isWinner
runners {
runnerId
scratched
horseName
}
payouts {
amount
wagerType {
code
}
}
}
alternateBettingInterest {
currentOdds {
numerator
denominator
}
biNumber
isWinner
runners {
runnerId
scratched
horseName
}
payouts {
amount
wagerType {
code
}
}
}
selectionType {
code
name
}
runners {
number
}
}
}
raceDate
racePostTime: postTime
raceTypeAbbreviation: raceType
tvgRaceId
trackName
wagerReference
trackCode
raceNumber
}
}
}
}
`;
export default GET_GROUP_WAGERS_SUBSCRIPTION_MY_BETS;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/graphql/subscriptions/WagersSubscriptionBehg.ts
import { gql } from "@apollo/client";
export const GET_GROUP_WAGERS_SUBSCRIPTION_MY_BETS = gql`
subscription GetGroupWagersSubscriptionMyBets(
$accountId: Int!
$statusList: [Status!]
$trackCodes: [String!]
$wagerTypes: [String!]
) {
wagerHistoryUpdate(
accountId: $accountId
statusList: $statusList
trackCodes: $trackCodes
wagerTypes: $wagerTypes
) {
id
wagerTypeFilter {
id
code
name
}
trackFilter {
code
name
}
totals(page: { current: 0, results: 99 }) {
totalCount
profit
winnings
refunded
totalAmount
}
groupWagers(group: { group: RACE, order: DESC }) {
id: key
value: key
wagers: value {
id
serialNumber
wagerAmount
betTotal: cost
betRefund
winningsAmount: winnings
betStatus {
code
name
}
transactionDate
wageringPlatform
wagerType {
id
code
name
}
promoQualifying
cancelableStatus {
code
name
}
cancelable
selections {
selectionString
modifier
selection {
bettingInterests {
currentOdds {
numerator
denominator
}
biNumber
isWinner
runners {
runnerId
scratched
horseName
}
payouts {
amount
wagerType {
code
}
}
}
selectionType {
code
name
}
runners {
number
}
}
}
raceDate
racePostTime: postTime
raceTypeAbbreviation: raceType
tvgRaceId
trackName
wagerReference
}
}
futureWagersList {
wagers {
id
serialNumber
wagerAmount
betTotal: cost
betRefund
winningsAmount: winnings
betStatus {
code
name
}
transactionDate
wageringPlatform
wagerType {
id
code
name
}
promoQualifying
cancelableStatus {
code
name
}
cancelable
selections {
selectionString
modifier
selection {
bettingInterests {
currentOdds {
numerator
denominator
}
biNumber
isWinner
runners {
runnerId
scratched
horseName
}
payouts {
amount
wagerType {
code
}
}
}
selectionType {
code
name
}
runners {
number
}
}
}
raceDate
racePostTime: postTime
raceTypeAbbreviation: raceType
tvgRaceId
trackName
wagerReference
trackCode
raceNumber
}
}
}
}
`;
export default GET_GROUP_WAGERS_SUBSCRIPTION_MY_BETS;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/graphql/subscriptions/RacesSubscription.ts
import { gql } from "@apollo/client";
import { RESULTS } from "../fragments/Results";
import { WILL_PAYS } from "../fragments/WillPays";
export const GET_RACES_SUBSCRIPTION_MY_BETS = gql`
subscription GetRacesSubscriptionMyBets(
$wagerProfile: String
$races: [String!]!
) {
racesByTrackCodes(profile: $wagerProfile, trackCodes: $races) {
id
status {
code
}
...Results
...WillPays
}
}
${RESULTS}
${WILL_PAYS}
`;
export default GET_RACES_SUBSCRIPTION_MY_BETS;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/graphql/optionsSettled.graph.ts
import { graphql } from "@apollo/client/react/hoc";
import { Dispatch } from "redux";
import { get } from "lodash";
import { batch } from "react-redux";
import { format, subDays, subMonths, subWeeks } from "date-fns";
import {
setSettledCounterMyBetsStandalone,
setSettledWagerAmountMyBetsStandalone
} from "@tvg/sh-lib-my-bets/redux/actions";
import { FooterProps } from "../utils/types";
type WagerHistory = {
totals: { totalBets: number; totalAmount: number };
};
const formatBets = (
wagerHistory: WagerHistory,
dispatch: Dispatch,
error: unknown
) => {
if (!error) {
let totalSettledBets = 0;
let settledWageredAmount = 0;
if (wagerHistory?.totals) {
totalSettledBets = wagerHistory.totals.totalBets;
settledWageredAmount = wagerHistory.totals.totalAmount;
batch(() => {
// Entry point for our counters and saving them in redux store
dispatch(
setSettledCounterMyBetsStandalone(wagerHistory.totals.totalBets)
);
dispatch(
setSettledWagerAmountMyBetsStandalone(wagerHistory.totals.totalAmount)
);
});
}
return {
totalSettledBets,
settledWageredAmount
};
}
return {};
};
export default {
skip: (props: FooterProps) => !props.accountNumber,
options: (props: FooterProps) => {
const settledTab = props.selectedTab.toLowerCase() === "settled";
let startDate = new Date();
let endDate = new Date();
if (settledTab) {
const settledStartTimes = {
TODAY: startDate,
YESTERDAY: subDays(startDate, 1),
LAST_WEEK: subWeeks(startDate, 1),
LAST_MONTH: subMonths(startDate, 1)
};
startDate =
props.isCustomTimeFrame && props.customStartDate
? props.customStartDate
: settledStartTimes[props.selectedSettledTab];
endDate =
props.isCustomTimeFrame && props.customEndDate
? props.customEndDate
: new Date();
}
const variables = {
startDate: format(startDate, "yyyy-MM-dd"),
endDate: format(endDate, "yyyy-MM-dd"),
accountId: parseInt(props.accountNumber, 10),
status: ["SETTLED"]
};
return {
fetchPolicy: "cache-and-network",
nextFetchPolicy: "cache-first",
client: props.behgClient,
ssr: false,
variables
};
},
// @ts-ignore
props: (result: graphql<Response>) => ({
...formatBets(
get(result, "data.wagerHistory"),
get(result, "ownProps.dispatch"),
get(result, "data.error")
),
isLoadingSettledTotals: get(result, "data.loading", false),
subscribeToMoreSettled: result?.data?.subscribeToMore,
refetchSettled: result?.data?.refetch
})
};
webpack://frontend-mybets/../../packages/sh-lib-my-bets/graphql/fragments/betsTotals.ts
import { gql } from "@apollo/client";
export const TOTALS = gql`
fragment totals on WagerHistoryResponse {
totals {
totalBets: totalCount
totalAmount
totalGambledCount
totalGambledAmount
}
}
`;
export default TOTALS;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/graphql/queries/activeBetsQuery.ts
import { gql } from "@apollo/client";
import BETS_TOTALS from "../fragments/betsTotals";
export const GET_ACTIVE_BETS = gql`
query GetActiveBets(
$accountId: Int!
$startDate: String
$endDate: String
$status: [Status!]
) {
wagerHistory(
beginDate: $startDate
accountId: $accountId
endDate: $endDate
statusList: $status
) {
id
...totals
futureWagersList {
totals {
totalCount
totalAmount
}
}
groupWagers(group: { group: RACE, order: DESC }) {
wagers: value {
betStatus {
code
name
}
tvgRaceId
trackCode
}
}
}
}
${BETS_TOTALS}
`;
export default GET_ACTIVE_BETS;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/graphql/queries/settledBetsQuery.ts
import { gql } from "@apollo/client";
import { TOTALS } from "../fragments/betsTotals";
export const GET_SETTLED_BETS = gql`
query GetSettledBets(
$accountId: Int!
$startDate: String
$endDate: String
$status: [Status!]
) {
wagerHistory(
beginDate: $startDate
accountId: $accountId
endDate: $endDate
statusList: $status
) {
id
...totals
}
}
${TOTALS}
`;
export default GET_SETTLED_BETS;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/graphql/optionsActive.graph.ts
import { get } from "lodash";
import { batch } from "react-redux";
import { format } from "date-fns";
import {
setActiveWagerAmountMyBetsStandalone,
setCounterMyBetsStandalone,
setFutureCounterMyBetsStandalone,
setFutureWageredAmountMyBetsStandalone,
Actions
} from "@tvg/sh-lib-my-bets/redux/actions";
import { ApolloError } from "@apollo/client/errors";
import type { Dispatch } from "redux";
import { FooterProps, WagerHistoryProps, WagerHistory } from "../utils/types";
export const getRacesActiveBets = (wagerHistory: WagerHistory) => {
const activeBetsTrackCode: string[] = [];
if (wagerHistory && wagerHistory.groupWagers) {
const activeBetsArray: number[] = [];
wagerHistory.groupWagers.forEach((eachGroup) => {
eachGroup.wagers.forEach((wager) => {
if (wager.betStatus.code === "A") {
activeBetsArray.push(wager.tvgRaceId);
if (wager.trackCode && !activeBetsTrackCode.includes(wager.trackCode))
activeBetsTrackCode.push(wager.trackCode);
}
});
});
const racesActiveBets = activeBetsArray.reduce<Record<number, number>>(
(acc, currentValue) => {
const value = get(acc, currentValue, 0);
if (value > 0) {
return {
...acc,
[currentValue]: value + 1
};
}
return {
...acc,
[currentValue]: 1
};
},
{}
);
return { racesActiveBets, activeBetsTrackCode };
}
return { racesActiveBets: {}, activeBetsTrackCode: [] };
};
export const formatBets = (
wagerHistory: WagerHistoryProps,
dispatch: Dispatch<Actions>,
error: ApolloError | undefined
) => {
if (!error && get(wagerHistory, "totals.totalGambledCount") !== undefined) {
const totalActiveBets = get(wagerHistory, "totals.totalGambledCount", 0);
const activeWageredAmount = get(
wagerHistory,
"totals.totalGambledAmount",
50
);
const totalFutureBets = get(
wagerHistory,
"futureWagersList.totals.totalCount",
0
);
const futureWageredAmount = get(
wagerHistory,
"futureWagersList.totals.totalAmount",
0
);
batch(() => {
// Entry point for our counters and saving them in redux store
dispatch(setCounterMyBetsStandalone(totalActiveBets));
dispatch(setActiveWagerAmountMyBetsStandalone(activeWageredAmount));
dispatch(setFutureCounterMyBetsStandalone(totalFutureBets));
dispatch(setFutureWageredAmountMyBetsStandalone(futureWageredAmount));
});
return {
totalActiveBets,
totalFutureBets,
activeWageredAmount,
futureWageredAmount
};
}
return {};
};
export default {
skip: (props: FooterProps) => !props.accountNumber,
options: (props: FooterProps) => {
const date = format(new Date(), "yyyy-MM-dd");
const variables = {
startDate: date,
endDate: date,
accountId: parseInt(props.accountNumber, 10) || 0,
status: ["PENDING"]
};
return {
fetchPolicy: "cache-and-network",
nextFetchPolicy: "cache-first",
client: props.behgClient,
ssr: false,
variables
};
},
// @ts-ignore
props: (result: graphql<Response>) => ({
...formatBets(
get(result, "data.wagerHistory"),
get(result, "ownProps.dispatch"),
get(result, "data.error")
),
isLoadingActiveTotals: get(result, "data.loading", false),
subscribeToMore: result.data.loading ? null : result.data.subscribeToMore
})
};
webpack://frontend-mybets/../../packages/sh-lib-my-bets/graphql/subscriptions/activeBetsSubscription.ts
import { gql } from "@apollo/client";
import BETS_TOTALS from "../fragments/betsTotals";
export const GET_ACTIVE_BETS_SUBSCRIPTION = gql`
subscription getActiveBetsSubscription($accountId: Int!, $status: [Status!]) {
wagerHistory: wagerHistoryUpdate(
accountId: $accountId
statusList: $status
) {
id
...totals
groupWagers(group: { group: RACE, order: DESC }) {
wagers: value {
betStatus {
code
name
}
tvgRaceId
trackCode
}
}
futureWagersList {
totals {
totalCount
totalAmount
}
}
}
}
${BETS_TOTALS}
`;
export default GET_ACTIVE_BETS_SUBSCRIPTION;
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/inheritsLoose.js
import setPrototypeOf from "./setPrototypeOf.js";
export default function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
setPrototypeOf(subClass, superClass);
}
webpack://frontend-mybets/../../node_modules/dom-helpers/esm/removeClass.js
function replaceClassName(origClass, classToRemove) {
return origClass.replace(new RegExp("(^|\\s)" + classToRemove + "(?:\\s|$)", 'g'), '$1').replace(/\s+/g, ' ').replace(/^\s*|\s*$/g, '');
}
/**
* Removes a CSS class from a given element.
*
* @param element the element
* @param className the CSS class name
*/
export default function removeClass(element, className) {
if (element.classList) {
element.classList.remove(className);
} else if (typeof element.className === 'string') {
element.className = replaceClassName(element.className, className);
} else {
element.setAttribute('class', replaceClassName(element.className && element.className.baseVal || '', className));
}
}
webpack://frontend-mybets/../../node_modules/react-transition-group/esm/config.js
export default {
disabled: false
};
webpack://frontend-mybets/../../node_modules/react-transition-group/esm/TransitionGroupContext.js
import React from 'react'; export default React.createContext(null);
webpack://frontend-mybets/../../node_modules/react-transition-group/esm/Transition.js
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose";
import PropTypes from 'prop-types';
import React from 'react';
import ReactDOM from 'react-dom';
import config from './config';
import { timeoutsShape } from './utils/PropTypes';
import TransitionGroupContext from './TransitionGroupContext';
export var UNMOUNTED = 'unmounted';
export var EXITED = 'exited';
export var ENTERING = 'entering';
export var ENTERED = 'entered';
export var EXITING = 'exiting';
/**
* The Transition component lets you describe a transition from one component
* state to another _over time_ with a simple declarative API. Most commonly
* it's used to animate the mounting and unmounting of a component, but can also
* be used to describe in-place transition states as well.
*
* ---
*
* **Note**: `Transition` is a platform-agnostic base component. If you're using
* transitions in CSS, you'll probably want to use
* [`CSSTransition`](https://reactcommunity.org/react-transition-group/css-transition)
* instead. It inherits all the features of `Transition`, but contains
* additional features necessary to play nice with CSS transitions (hence the
* name of the component).
*
* ---
*
* By default the `Transition` component does not alter the behavior of the
* component it renders, it only tracks "enter" and "exit" states for the
* components. It's up to you to give meaning and effect to those states. For
* example we can add styles to a component when it enters or exits:
*
* ```jsx
* import { Transition } from 'react-transition-group';
*
* const duration = 300;
*
* const defaultStyle = {
* transition: `opacity ${duration}ms ease-in-out`,
* opacity: 0,
* }
*
* const transitionStyles = {
* entering: { opacity: 1 },
* entered: { opacity: 1 },
* exiting: { opacity: 0 },
* exited: { opacity: 0 },
* };
*
* const Fade = ({ in: inProp }) => (
* <Transition in={inProp} timeout={duration}>
* {state => (
* <div style={{
* ...defaultStyle,
* ...transitionStyles[state]
* }}>
* I'm a fade Transition!
* </div>
* )}
* </Transition>
* );
* ```
*
* There are 4 main states a Transition can be in:
* - `'entering'`
* - `'entered'`
* - `'exiting'`
* - `'exited'`
*
* Transition state is toggled via the `in` prop. When `true` the component
* begins the "Enter" stage. During this stage, the component will shift from
* its current transition state, to `'entering'` for the duration of the
* transition and then to the `'entered'` stage once it's complete. Let's take
* the following example (we'll use the
* [useState](https://reactjs.org/docs/hooks-reference.html#usestate) hook):
*
* ```jsx
* function App() {
* const [inProp, setInProp] = useState(false);
* return (
* <div>
* <Transition in={inProp} timeout={500}>
* {state => (
* // ...
* )}
* </Transition>
* <button onClick={() => setInProp(true)}>
* Click to Enter
* </button>
* </div>
* );
* }
* ```
*
* When the button is clicked the component will shift to the `'entering'` state
* and stay there for 500ms (the value of `timeout`) before it finally switches
* to `'entered'`.
*
* When `in` is `false` the same thing happens except the state moves from
* `'exiting'` to `'exited'`.
*/
var Transition = /*#__PURE__*/function (_React$Component) {
_inheritsLoose(Transition, _React$Component);
function Transition(props, context) {
var _this;
_this = _React$Component.call(this, props, context) || this;
var parentGroup = context; // In the context of a TransitionGroup all enters are really appears
var appear = parentGroup && !parentGroup.isMounting ? props.enter : props.appear;
var initialStatus;
_this.appearStatus = null;
if (props.in) {
if (appear) {
initialStatus = EXITED;
_this.appearStatus = ENTERING;
} else {
initialStatus = ENTERED;
}
} else {
if (props.unmountOnExit || props.mountOnEnter) {
initialStatus = UNMOUNTED;
} else {
initialStatus = EXITED;
}
}
_this.state = {
status: initialStatus
};
_this.nextCallback = null;
return _this;
}
Transition.getDerivedStateFromProps = function getDerivedStateFromProps(_ref, prevState) {
var nextIn = _ref.in;
if (nextIn && prevState.status === UNMOUNTED) {
return {
status: EXITED
};
}
return null;
} // getSnapshotBeforeUpdate(prevProps) {
// let nextStatus = null
// if (prevProps !== this.props) {
// const { status } = this.state
// if (this.props.in) {
// if (status !== ENTERING && status !== ENTERED) {
// nextStatus = ENTERING
// }
// } else {
// if (status === ENTERING || status === ENTERED) {
// nextStatus = EXITING
// }
// }
// }
// return { nextStatus }
// }
;
var _proto = Transition.prototype;
_proto.componentDidMount = function componentDidMount() {
this.updateStatus(true, this.appearStatus);
};
_proto.componentDidUpdate = function componentDidUpdate(prevProps) {
var nextStatus = null;
if (prevProps !== this.props) {
var status = this.state.status;
if (this.props.in) {
if (status !== ENTERING && status !== ENTERED) {
nextStatus = ENTERING;
}
} else {
if (status === ENTERING || status === ENTERED) {
nextStatus = EXITING;
}
}
}
this.updateStatus(false, nextStatus);
};
_proto.componentWillUnmount = function componentWillUnmount() {
this.cancelNextCallback();
};
_proto.getTimeouts = function getTimeouts() {
var timeout = this.props.timeout;
var exit, enter, appear;
exit = enter = appear = timeout;
if (timeout != null && typeof timeout !== 'number') {
exit = timeout.exit;
enter = timeout.enter; // TODO: remove fallback for next major
appear = timeout.appear !== undefined ? timeout.appear : enter;
}
return {
exit: exit,
enter: enter,
appear: appear
};
};
_proto.updateStatus = function updateStatus(mounting, nextStatus) {
if (mounting === void 0) {
mounting = false;
}
if (nextStatus !== null) {
// nextStatus will always be ENTERING or EXITING.
this.cancelNextCallback();
if (nextStatus === ENTERING) {
this.performEnter(mounting);
} else {
this.performExit();
}
} else if (this.props.unmountOnExit && this.state.status === EXITED) {
this.setState({
status: UNMOUNTED
});
}
};
_proto.performEnter = function performEnter(mounting) {
var _this2 = this;
var enter = this.props.enter;
var appearing = this.context ? this.context.isMounting : mounting;
var _ref2 = this.props.nodeRef ? [appearing] : [ReactDOM.findDOMNode(this), appearing],
maybeNode = _ref2[0],
maybeAppearing = _ref2[1];
var timeouts = this.getTimeouts();
var enterTimeout = appearing ? timeouts.appear : timeouts.enter; // no enter animation skip right to ENTERED
// if we are mounting and running this it means appear _must_ be set
if (!mounting && !enter || config.disabled) {
this.safeSetState({
status: ENTERED
}, function () {
_this2.props.onEntered(maybeNode);
});
return;
}
this.props.onEnter(maybeNode, maybeAppearing);
this.safeSetState({
status: ENTERING
}, function () {
_this2.props.onEntering(maybeNode, maybeAppearing);
_this2.onTransitionEnd(enterTimeout, function () {
_this2.safeSetState({
status: ENTERED
}, function () {
_this2.props.onEntered(maybeNode, maybeAppearing);
});
});
});
};
_proto.performExit = function performExit() {
var _this3 = this;
var exit = this.props.exit;
var timeouts = this.getTimeouts();
var maybeNode = this.props.nodeRef ? undefined : ReactDOM.findDOMNode(this); // no exit animation skip right to EXITED
if (!exit || config.disabled) {
this.safeSetState({
status: EXITED
}, function () {
_this3.props.onExited(maybeNode);
});
return;
}
this.props.onExit(maybeNode);
this.safeSetState({
status: EXITING
}, function () {
_this3.props.onExiting(maybeNode);
_this3.onTransitionEnd(timeouts.exit, function () {
_this3.safeSetState({
status: EXITED
}, function () {
_this3.props.onExited(maybeNode);
});
});
});
};
_proto.cancelNextCallback = function cancelNextCallback() {
if (this.nextCallback !== null) {
this.nextCallback.cancel();
this.nextCallback = null;
}
};
_proto.safeSetState = function safeSetState(nextState, callback) {
// This shouldn't be necessary, but there are weird race conditions with
// setState callbacks and unmounting in testing, so always make sure that
// we can cancel any pending setState callbacks after we unmount.
callback = this.setNextCallback(callback);
this.setState(nextState, callback);
};
_proto.setNextCallback = function setNextCallback(callback) {
var _this4 = this;
var active = true;
this.nextCallback = function (event) {
if (active) {
active = false;
_this4.nextCallback = null;
callback(event);
}
};
this.nextCallback.cancel = function () {
active = false;
};
return this.nextCallback;
};
_proto.onTransitionEnd = function onTransitionEnd(timeout, handler) {
this.setNextCallback(handler);
var node = this.props.nodeRef ? this.props.nodeRef.current : ReactDOM.findDOMNode(this);
var doesNotHaveTimeoutOrListener = timeout == null && !this.props.addEndListener;
if (!node || doesNotHaveTimeoutOrListener) {
setTimeout(this.nextCallback, 0);
return;
}
if (this.props.addEndListener) {
var _ref3 = this.props.nodeRef ? [this.nextCallback] : [node, this.nextCallback],
maybeNode = _ref3[0],
maybeNextCallback = _ref3[1];
this.props.addEndListener(maybeNode, maybeNextCallback);
}
if (timeout != null) {
setTimeout(this.nextCallback, timeout);
}
};
_proto.render = function render() {
var status = this.state.status;
if (status === UNMOUNTED) {
return null;
}
var _this$props = this.props,
children = _this$props.children,
_in = _this$props.in,
_mountOnEnter = _this$props.mountOnEnter,
_unmountOnExit = _this$props.unmountOnExit,
_appear = _this$props.appear,
_enter = _this$props.enter,
_exit = _this$props.exit,
_timeout = _this$props.timeout,
_addEndListener = _this$props.addEndListener,
_onEnter = _this$props.onEnter,
_onEntering = _this$props.onEntering,
_onEntered = _this$props.onEntered,
_onExit = _this$props.onExit,
_onExiting = _this$props.onExiting,
_onExited = _this$props.onExited,
_nodeRef = _this$props.nodeRef,
childProps = _objectWithoutPropertiesLoose(_this$props, ["children", "in", "mountOnEnter", "unmountOnExit", "appear", "enter", "exit", "timeout", "addEndListener", "onEnter", "onEntering", "onEntered", "onExit", "onExiting", "onExited", "nodeRef"]);
return (
/*#__PURE__*/
// allows for nested Transitions
React.createElement(TransitionGroupContext.Provider, {
value: null
}, typeof children === 'function' ? children(status, childProps) : React.cloneElement(React.Children.only(children), childProps))
);
};
return Transition;
}(React.Component);
Transition.contextType = TransitionGroupContext;
Transition.propTypes = process.env.NODE_ENV !== "production" ? {
/**
* A React reference to DOM element that need to transition:
* https://stackoverflow.com/a/51127130/4671932
*
* - When `nodeRef` prop is used, `node` is not passed to callback functions
* (e.g. `onEnter`) because user already has direct access to the node.
* - When changing `key` prop of `Transition` in a `TransitionGroup` a new
* `nodeRef` need to be provided to `Transition` with changed `key` prop
* (see
* [test/CSSTransition-test.js](https://github.com/reactjs/react-transition-group/blob/13435f897b3ab71f6e19d724f145596f5910581c/test/CSSTransition-test.js#L362-L437)).
*/
nodeRef: PropTypes.shape({
current: typeof Element === 'undefined' ? PropTypes.any : function (propValue, key, componentName, location, propFullName, secret) {
var value = propValue[key];
return PropTypes.instanceOf(value && 'ownerDocument' in value ? value.ownerDocument.defaultView.Element : Element)(propValue, key, componentName, location, propFullName, secret);
}
}),
/**
* A `function` child can be used instead of a React element. This function is
* called with the current transition status (`'entering'`, `'entered'`,
* `'exiting'`, `'exited'`), which can be used to apply context
* specific props to a component.
*
* ```jsx
* <Transition in={this.state.in} timeout={150}>
* {state => (
* <MyComponent className={`fade fade-${state}`} />
* )}
* </Transition>
* ```
*/
children: PropTypes.oneOfType([PropTypes.func.isRequired, PropTypes.element.isRequired]).isRequired,
/**
* Show the component; triggers the enter or exit states
*/
in: PropTypes.bool,
/**
* By default the child component is mounted immediately along with
* the parent `Transition` component. If you want to "lazy mount" the component on the
* first `in={true}` you can set `mountOnEnter`. After the first enter transition the component will stay
* mounted, even on "exited", unless you also specify `unmountOnExit`.
*/
mountOnEnter: PropTypes.bool,
/**
* By default the child component stays mounted after it reaches the `'exited'` state.
* Set `unmountOnExit` if you'd prefer to unmount the component after it finishes exiting.
*/
unmountOnExit: PropTypes.bool,
/**
* By default the child component does not perform the enter transition when
* it first mounts, regardless of the value of `in`. If you want this
* behavior, set both `appear` and `in` to `true`.
*
* > **Note**: there are no special appear states like `appearing`/`appeared`, this prop
* > only adds an additional enter transition. However, in the
* > `<CSSTransition>` component that first enter transition does result in
* > additional `.appear-*` classes, that way you can choose to style it
* > differently.
*/
appear: PropTypes.bool,
/**
* Enable or disable enter transitions.
*/
enter: PropTypes.bool,
/**
* Enable or disable exit transitions.
*/
exit: PropTypes.bool,
/**
* The duration of the transition, in milliseconds.
* Required unless `addEndListener` is provided.
*
* You may specify a single timeout for all transitions:
*
* ```jsx
* timeout={500}
* ```
*
* or individually:
*
* ```jsx
* timeout={{
* appear: 500,
* enter: 300,
* exit: 500,
* }}
* ```
*
* - `appear` defaults to the value of `enter`
* - `enter` defaults to `0`
* - `exit` defaults to `0`
*
* @type {number | { enter?: number, exit?: number, appear?: number }}
*/
timeout: function timeout(props) {
var pt = timeoutsShape;
if (!props.addEndListener) pt = pt.isRequired;
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return pt.apply(void 0, [props].concat(args));
},
/**
* Add a custom transition end trigger. Called with the transitioning
* DOM node and a `done` callback. Allows for more fine grained transition end
* logic. Timeouts are still used as a fallback if provided.
*
* **Note**: when `nodeRef` prop is passed, `node` is not passed.
*
* ```jsx
* addEndListener={(node, done) => {
* // use the css transitionend event to mark the finish of a transition
* node.addEventListener('transitionend', done, false);
* }}
* ```
*/
addEndListener: PropTypes.func,
/**
* Callback fired before the "entering" status is applied. An extra parameter
* `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount
*
* **Note**: when `nodeRef` prop is passed, `node` is not passed.
*
* @type Function(node: HtmlElement, isAppearing: bool) -> void
*/
onEnter: PropTypes.func,
/**
* Callback fired after the "entering" status is applied. An extra parameter
* `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount
*
* **Note**: when `nodeRef` prop is passed, `node` is not passed.
*
* @type Function(node: HtmlElement, isAppearing: bool)
*/
onEntering: PropTypes.func,
/**
* Callback fired after the "entered" status is applied. An extra parameter
* `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount
*
* **Note**: when `nodeRef` prop is passed, `node` is not passed.
*
* @type Function(node: HtmlElement, isAppearing: bool) -> void
*/
onEntered: PropTypes.func,
/**
* Callback fired before the "exiting" status is applied.
*
* **Note**: when `nodeRef` prop is passed, `node` is not passed.
*
* @type Function(node: HtmlElement) -> void
*/
onExit: PropTypes.func,
/**
* Callback fired after the "exiting" status is applied.
*
* **Note**: when `nodeRef` prop is passed, `node` is not passed.
*
* @type Function(node: HtmlElement) -> void
*/
onExiting: PropTypes.func,
/**
* Callback fired after the "exited" status is applied.
*
* **Note**: when `nodeRef` prop is passed, `node` is not passed
*
* @type Function(node: HtmlElement) -> void
*/
onExited: PropTypes.func
} : {}; // Name the function so it is clearer in the documentation
function noop() {}
Transition.defaultProps = {
in: false,
mountOnEnter: false,
unmountOnExit: false,
appear: false,
enter: true,
exit: true,
onEnter: noop,
onEntering: noop,
onEntered: noop,
onExit: noop,
onExiting: noop,
onExited: noop
};
Transition.UNMOUNTED = UNMOUNTED;
Transition.EXITED = EXITED;
Transition.ENTERING = ENTERING;
Transition.ENTERED = ENTERED;
Transition.EXITING = EXITING;
export default Transition;
webpack://frontend-mybets/../../node_modules/react-transition-group/esm/CSSTransition.js
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose";
import PropTypes from 'prop-types';
import addOneClass from 'dom-helpers/addClass';
import removeOneClass from 'dom-helpers/removeClass';
import React from 'react';
import Transition from './Transition';
import { classNamesShape } from './utils/PropTypes';
var _addClass = function addClass(node, classes) {
return node && classes && classes.split(' ').forEach(function (c) {
return addOneClass(node, c);
});
};
var removeClass = function removeClass(node, classes) {
return node && classes && classes.split(' ').forEach(function (c) {
return removeOneClass(node, c);
});
};
/**
* A transition component inspired by the excellent
* [ng-animate](https://docs.angularjs.org/api/ngAnimate) library, you should
* use it if you're using CSS transitions or animations. It's built upon the
* [`Transition`](https://reactcommunity.org/react-transition-group/transition)
* component, so it inherits all of its props.
*
* `CSSTransition` applies a pair of class names during the `appear`, `enter`,
* and `exit` states of the transition. The first class is applied and then a
* second `*-active` class in order to activate the CSS transition. After the
* transition, matching `*-done` class names are applied to persist the
* transition state.
*
* ```jsx
* function App() {
* const [inProp, setInProp] = useState(false);
* return (
* <div>
* <CSSTransition in={inProp} timeout={200} classNames="my-node">
* <div>
* {"I'll receive my-node-* classes"}
* </div>
* </CSSTransition>
* <button type="button" onClick={() => setInProp(true)}>
* Click to Enter
* </button>
* </div>
* );
* }
* ```
*
* When the `in` prop is set to `true`, the child component will first receive
* the class `example-enter`, then the `example-enter-active` will be added in
* the next tick. `CSSTransition` [forces a
* reflow](https://github.com/reactjs/react-transition-group/blob/5007303e729a74be66a21c3e2205e4916821524b/src/CSSTransition.js#L208-L215)
* between before adding the `example-enter-active`. This is an important trick
* because it allows us to transition between `example-enter` and
* `example-enter-active` even though they were added immediately one after
* another. Most notably, this is what makes it possible for us to animate
* _appearance_.
*
* ```css
* .my-node-enter {
* opacity: 0;
* }
* .my-node-enter-active {
* opacity: 1;
* transition: opacity 200ms;
* }
* .my-node-exit {
* opacity: 1;
* }
* .my-node-exit-active {
* opacity: 0;
* transition: opacity 200ms;
* }
* ```
*
* `*-active` classes represent which styles you want to animate **to**, so it's
* important to add `transition` declaration only to them, otherwise transitions
* might not behave as intended! This might not be obvious when the transitions
* are symmetrical, i.e. when `*-enter-active` is the same as `*-exit`, like in
* the example above (minus `transition`), but it becomes apparent in more
* complex transitions.
*
* **Note**: If you're using the
* [`appear`](http://reactcommunity.org/react-transition-group/transition#Transition-prop-appear)
* prop, make sure to define styles for `.appear-*` classes as well.
*/
var CSSTransition = /*#__PURE__*/function (_React$Component) {
_inheritsLoose(CSSTransition, _React$Component);
function CSSTransition() {
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.appliedClasses = {
appear: {},
enter: {},
exit: {}
};
_this.onEnter = function (maybeNode, maybeAppearing) {
var _this$resolveArgument = _this.resolveArguments(maybeNode, maybeAppearing),
node = _this$resolveArgument[0],
appearing = _this$resolveArgument[1];
_this.removeClasses(node, 'exit');
_this.addClass(node, appearing ? 'appear' : 'enter', 'base');
if (_this.props.onEnter) {
_this.props.onEnter(maybeNode, maybeAppearing);
}
};
_this.onEntering = function (maybeNode, maybeAppearing) {
var _this$resolveArgument2 = _this.resolveArguments(maybeNode, maybeAppearing),
node = _this$resolveArgument2[0],
appearing = _this$resolveArgument2[1];
var type = appearing ? 'appear' : 'enter';
_this.addClass(node, type, 'active');
if (_this.props.onEntering) {
_this.props.onEntering(maybeNode, maybeAppearing);
}
};
_this.onEntered = function (maybeNode, maybeAppearing) {
var _this$resolveArgument3 = _this.resolveArguments(maybeNode, maybeAppearing),
node = _this$resolveArgument3[0],
appearing = _this$resolveArgument3[1];
var type = appearing ? 'appear' : 'enter';
_this.removeClasses(node, type);
_this.addClass(node, type, 'done');
if (_this.props.onEntered) {
_this.props.onEntered(maybeNode, maybeAppearing);
}
};
_this.onExit = function (maybeNode) {
var _this$resolveArgument4 = _this.resolveArguments(maybeNode),
node = _this$resolveArgument4[0];
_this.removeClasses(node, 'appear');
_this.removeClasses(node, 'enter');
_this.addClass(node, 'exit', 'base');
if (_this.props.onExit) {
_this.props.onExit(maybeNode);
}
};
_this.onExiting = function (maybeNode) {
var _this$resolveArgument5 = _this.resolveArguments(maybeNode),
node = _this$resolveArgument5[0];
_this.addClass(node, 'exit', 'active');
if (_this.props.onExiting) {
_this.props.onExiting(maybeNode);
}
};
_this.onExited = function (maybeNode) {
var _this$resolveArgument6 = _this.resolveArguments(maybeNode),
node = _this$resolveArgument6[0];
_this.removeClasses(node, 'exit');
_this.addClass(node, 'exit', 'done');
if (_this.props.onExited) {
_this.props.onExited(maybeNode);
}
};
_this.resolveArguments = function (maybeNode, maybeAppearing) {
return _this.props.nodeRef ? [_this.props.nodeRef.current, maybeNode] // here `maybeNode` is actually `appearing`
: [maybeNode, maybeAppearing];
};
_this.getClassNames = function (type) {
var classNames = _this.props.classNames;
var isStringClassNames = typeof classNames === 'string';
var prefix = isStringClassNames && classNames ? classNames + "-" : '';
var baseClassName = isStringClassNames ? "" + prefix + type : classNames[type];
var activeClassName = isStringClassNames ? baseClassName + "-active" : classNames[type + "Active"];
var doneClassName = isStringClassNames ? baseClassName + "-done" : classNames[type + "Done"];
return {
baseClassName: baseClassName,
activeClassName: activeClassName,
doneClassName: doneClassName
};
};
return _this;
}
var _proto = CSSTransition.prototype;
_proto.addClass = function addClass(node, type, phase) {
var className = this.getClassNames(type)[phase + "ClassName"];
var _this$getClassNames = this.getClassNames('enter'),
doneClassName = _this$getClassNames.doneClassName;
if (type === 'appear' && phase === 'done' && doneClassName) {
className += " " + doneClassName;
} // This is to force a repaint,
// which is necessary in order to transition styles when adding a class name.
if (phase === 'active') {
/* eslint-disable no-unused-expressions */
node && node.scrollTop;
}
if (className) {
this.appliedClasses[type][phase] = className;
_addClass(node, className);
}
};
_proto.removeClasses = function removeClasses(node, type) {
var _this$appliedClasses$ = this.appliedClasses[type],
baseClassName = _this$appliedClasses$.base,
activeClassName = _this$appliedClasses$.active,
doneClassName = _this$appliedClasses$.done;
this.appliedClasses[type] = {};
if (baseClassName) {
removeClass(node, baseClassName);
}
if (activeClassName) {
removeClass(node, activeClassName);
}
if (doneClassName) {
removeClass(node, doneClassName);
}
};
_proto.render = function render() {
var _this$props = this.props,
_ = _this$props.classNames,
props = _objectWithoutPropertiesLoose(_this$props, ["classNames"]);
return /*#__PURE__*/React.createElement(Transition, _extends({}, props, {
onEnter: this.onEnter,
onEntered: this.onEntered,
onEntering: this.onEntering,
onExit: this.onExit,
onExiting: this.onExiting,
onExited: this.onExited
}));
};
return CSSTransition;
}(React.Component);
CSSTransition.defaultProps = {
classNames: ''
};
CSSTransition.propTypes = process.env.NODE_ENV !== "production" ? _extends({}, Transition.propTypes, {
/**
* The animation classNames applied to the component as it appears, enters,
* exits or has finished the transition. A single name can be provided, which
* will be suffixed for each stage, e.g. `classNames="fade"` applies:
*
* - `fade-appear`, `fade-appear-active`, `fade-appear-done`
* - `fade-enter`, `fade-enter-active`, `fade-enter-done`
* - `fade-exit`, `fade-exit-active`, `fade-exit-done`
*
* A few details to note about how these classes are applied:
*
* 1. They are _joined_ with the ones that are already defined on the child
* component, so if you want to add some base styles, you can use
* `className` without worrying that it will be overridden.
*
* 2. If the transition component mounts with `in={false}`, no classes are
* applied yet. You might be expecting `*-exit-done`, but if you think
* about it, a component cannot finish exiting if it hasn't entered yet.
*
* 2. `fade-appear-done` and `fade-enter-done` will _both_ be applied. This
* allows you to define different behavior for when appearing is done and
* when regular entering is done, using selectors like
* `.fade-enter-done:not(.fade-appear-done)`. For example, you could apply
* an epic entrance animation when element first appears in the DOM using
* [Animate.css](https://daneden.github.io/animate.css/). Otherwise you can
* simply use `fade-enter-done` for defining both cases.
*
* Each individual classNames can also be specified independently like:
*
* ```js
* classNames={{
* appear: 'my-appear',
* appearActive: 'my-active-appear',
* appearDone: 'my-done-appear',
* enter: 'my-enter',
* enterActive: 'my-active-enter',
* enterDone: 'my-done-enter',
* exit: 'my-exit',
* exitActive: 'my-active-exit',
* exitDone: 'my-done-exit',
* }}
* ```
*
* If you want to set these classes using CSS Modules:
*
* ```js
* import styles from './styles.css';
* ```
*
* you might want to use camelCase in your CSS file, that way could simply
* spread them instead of listing them one by one:
*
* ```js
* classNames={{ ...styles }}
* ```
*
* @type {string | {
* appear?: string,
* appearActive?: string,
* appearDone?: string,
* enter?: string,
* enterActive?: string,
* enterDone?: string,
* exit?: string,
* exitActive?: string,
* exitDone?: string,
* }}
*/
classNames: classNamesShape,
/**
* A `<Transition>` callback fired immediately after the 'enter' or 'appear' class is
* applied.
*
* **Note**: when `nodeRef` prop is passed, `node` is not passed.
*
* @type Function(node: HtmlElement, isAppearing: bool)
*/
onEnter: PropTypes.func,
/**
* A `<Transition>` callback fired immediately after the 'enter-active' or
* 'appear-active' class is applied.
*
* **Note**: when `nodeRef` prop is passed, `node` is not passed.
*
* @type Function(node: HtmlElement, isAppearing: bool)
*/
onEntering: PropTypes.func,
/**
* A `<Transition>` callback fired immediately after the 'enter' or
* 'appear' classes are **removed** and the `done` class is added to the DOM node.
*
* **Note**: when `nodeRef` prop is passed, `node` is not passed.
*
* @type Function(node: HtmlElement, isAppearing: bool)
*/
onEntered: PropTypes.func,
/**
* A `<Transition>` callback fired immediately after the 'exit' class is
* applied.
*
* **Note**: when `nodeRef` prop is passed, `node` is not passed
*
* @type Function(node: HtmlElement)
*/
onExit: PropTypes.func,
/**
* A `<Transition>` callback fired immediately after the 'exit-active' is applied.
*
* **Note**: when `nodeRef` prop is passed, `node` is not passed
*
* @type Function(node: HtmlElement)
*/
onExiting: PropTypes.func,
/**
* A `<Transition>` callback fired immediately after the 'exit' classes
* are **removed** and the `exit-done` class is added to the DOM node.
*
* **Note**: when `nodeRef` prop is passed, `node` is not passed
*
* @type Function(node: HtmlElement)
*/
onExited: PropTypes.func
}) : {};
export default CSSTransition;
webpack://frontend-mybets/../../node_modules/dom-helpers/esm/addClass.js
import hasClass from './hasClass';
/**
* Adds a CSS class to a given element.
*
* @param element the element
* @param className the CSS class name
*/
export default function addClass(element, className) {
if (element.classList) element.classList.add(className);else if (!hasClass(element, className)) if (typeof element.className === 'string') element.className = element.className + " " + className;else element.setAttribute('class', (element.className && element.className.baseVal || '') + " " + className);
}
webpack://frontend-mybets/../../node_modules/dom-helpers/esm/hasClass.js
/**
* Checks if a given element has a CSS class.
*
* @param element the element
* @param className the CSS class name
*/
export default function hasClass(element, className) {
if (element.classList) return !!className && element.classList.contains(className);
return (" " + (element.className.baseVal || element.className) + " ").indexOf(" " + className + " ") !== -1;
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Typography/index.js
export const defaultSize = "14px"; export const titleFont = "'Roboto Condensed', sans-serif"; export const titleFontSecondary = "'Roboto', sans-serif"; export const titleMedium = "'Roboto-Medium', sans-serif"; export const defaultTextFont = "'Roboto', Arial, sans-serif"; // New fonts export const fontCondensedNormal = "'RobotoCondensed-Regular', sans-serif"; export const fontNormal = "'Roboto-Regular', sans-serif"; export const fontMono = "'Roboto Mono', monospace"; export const fontMedium = "'Roboto-Medium', sans-serif"; export const fontBold = "'Roboto-Bold', sans-serif"; export const fontBlack = "'Roboto-Black', sans-serif"; export const fontSansSerif = "sans-serif";
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/Title/styled-components.js
/* eslint-disable import/prefer-default-export */
import styled from "styled-components";
import { titleFont, titleFontSecondary } from "../../_static/Typography";
export const buildTitle = (titleDataInit) => {
const defaultProp = {
tag: "h1",
fontSize: -1,
color: "inherit",
uppercase: false,
ellipsis: false
};
const titleData = { ...defaultProp, ...titleDataInit };
const TitleAtom = styled[titleData.tag].attrs({
"data-qa-label": titleData.qaLabel
})`
font-family: ${titleData.fontFamilySecondary
? titleFontSecondary
: titleFont};
${titleData.fontSize >= 0 && `font-size: ${titleData.fontSize}px;`};
text-transform: ${titleData.uppercase && "uppercase"};
color: ${titleData.color !== "inherit" && titleData.color};
margin: 0;
`;
return !titleData.ellipsis
? TitleAtom
: styled(TitleAtom)`
display: block;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
`;
};
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/Title/index.jsx
import React, { PureComponent } from "react";
import { buildTitle } from "./styled-components";
export default class Title extends PureComponent {
static defaultProps = {
children: null,
tag: "h1",
ellipsis: false,
uppercase: true,
fontSize: -1,
color: "inherit",
fontFamilySecondary: false,
className: "",
qaLabel: ""
};
render() {
let Tlt = buildTitle({
tag: this.props.tag,
fontSize: this.props.fontSize,
color: this.props.color,
uppercase: this.props.uppercase,
ellipsis: this.props.ellipsis,
fontFamilySecondary: this.props.fontFamilySecondary,
qaLabel: this.props.qaLabel
});
if (this.props.tag !== "h1") {
Tlt = Tlt.withComponent(this.props.tag);
}
return <Tlt className={this.props.className}>{this.props.children}</Tlt>;
}
}
export { buildTitle };
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/Buttons/default-styled.js
// Default Button
import styled from "styled-components";
export default styled.button`
outline: none;
opacity: ${(props) => (props.isDisabled ? 0.3 : 1)};
cursor: ${(props) => (props.isDisabled ? "default" : "pointer")};
background-color: transparent;
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/Buttons/default.jsx
import React, { PureComponent } from "react";
import { noop } from "lodash";
import DefaultButton from "./default-styled";
export default class ButtonDefault extends PureComponent {
static defaultProps = {
children: null,
onClick: noop,
className: "",
isDisabled: false,
qaLabel: "",
optionalData: null
};
render() {
const componentProps = {
...(this.props.qaLabel !== ""
? {
"data-qa-label": this.props.qaLabel
}
: {}),
...(this.props.optionalData
? {
"data-optional": this.props.optionalData
}
: {}),
onClick: !this.props.isDisabled ? this.props.onClick : noop,
className: this.props.className,
isDisabled: this.props.isDisabled
};
return (
<DefaultButton {...componentProps} disabled={this.props.isDisabled}>
{this.props.children}
</DefaultButton>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Transitions/index.js
import { keyframes, css } from "styled-components";
export const delayTime = "150ms";
export const easeInOut = {
function: "ease-in-out",
value: 200,
time: "ms"
};
export const delayAction = {
function: "linear",
value: 0,
time: "s"
};
export const linear = {
function: "linear",
value: 300,
time: "ms"
};
export const cubic = {
function: "cubic-bezier(0.03, 0.59, 0.1, 0.97)",
value: 250,
time: "ms"
};
export const spring = {
function: "cubic-bezier(.19,1.32,.48,1)",
value: 450,
time: "ms"
};
export const pageSwitch = {
function: "cubic-bezier(0,1.02,.58,1)",
value: 400,
time: "ms"
};
export const generateTransition = (transition, cssProp = "all", delay) =>
`${cssProp} ${transition.value}${transition.time} ${transition.function}${
delay ? ` ${delay}` : ""
}`;
export const opacityIn = () => keyframes`
from {
opacity: 0;
}
to {
opacity: 1;
}
`;
export const opacityOut = () => keyframes`
from {
opacity: 1;
}
to {
opacity: 0;
}
`;
const TransitionBaseFloating = `
backface-visibility: hidden;
transform: translateZ(0);
will-change: transform;
transform: translate3d(0, -50%, 0);
transition: ${generateTransition(cubic, "transform")};
`;
const TransitionBase = `
backface-visibility: hidden;
transform: translateZ(0);
will-change: transform;
transform: translate3d(0, 0, 0);
transition: ${generateTransition(cubic, "transform")};
`;
export const SlideFloatingBottomTransition = css`
${TransitionBaseFloating}
&.bottomFloating-appear {
transition-delay: ${delayTime};
transform: translate3d(0, 50%, 0);
}
&.bottomFloating-appear-active {
transform: translate3d(0, -50%, 0);
}
&.bottomFloating-enter {
transition-delay: ${delayTime};
transform: translate3d(0, 50vh, 0);
}
&.bottomFloating-enter-active {
transform: translate3d(0, -50%, 0);
}
&.bottomFloating-exit {
transform: translate3d(0, 50vh, 0);
}
`;
export const SlideBottomTransition = css`
${TransitionBase}
&.bottom-appear {
transition-delay: ${delayTime};
transform: translate3d(0, 100%, 0);
}
&.bottom-appear-active {
transform: translate3d(0, 0, 0);
}
&.bottom-enter {
transition-delay: ${delayTime};
transform: translate3d(0, 100%, 0);
}
&.bottom-enter-active {
transform: translate3d(0, 0, 0);
}
&.bottom-exit {
transform: translate3d(0, 100%, 0);
}
`;
export const SlideTopTransition = css`
${TransitionBase}
&.top-appear {
transition-delay: ${delayTime};
transform: translate3d(0, -100%, 0);
}
&.top-appear-active {
transform: translate3d(0, 0, 0);
}
&.top-enter {
transition-delay: ${delayTime};
transform: translate3d(0, -100%, 0);
}
&.top-enter-active {
transform: translate3d(0, 0, 0);
}
&.top-exit {
transform: translate3d(0, -100%, 0);
}
`;
export const SlideRightTransition = css`
${TransitionBase}
&.right-appear {
transform: translate3d(99.9%, 0, 0);
}
&.right-appear-active {
transform: translate3d(0, 0, 0);
}
&.right-enter {
transform: translate3d(99.9%, 0, 0);
}
&.right-enter-active {
transform: translate3d(0, 0, 0);
}
&.right-exit {
transform: translate3d(99.9%, 0, 0);
}
`;
export const SlideLeftTransition = css`
${TransitionBase}
&.left-appear {
transform: translate3d(-99.9%, 0, 0);
}
&.left-appear-active {
transform: translate3d(0, 0, 0);
}
&.left-enter {
transform: translate3d(-99.9%, 0, 0);
}
&.left-enter-active {
transform: translate3d(0, 0, 0);
}
&.left-exit {
transform: translate3d(-99.9%, 0, 0);
}
`;
export const FadeTransition = css`
backface-visibility: hidden;
will-change: opacity;
transition: ${generateTransition(easeInOut, "opacity")};
&.fade-appear {
opacity: 0;
}
&.fade-appear-active {
opacity: 1;
}
&.fade-enter {
opacity: 0;
}
&.fade-enter-active {
opacity: 1;
}
&.fade-exit {
opacity: 0;
}
`;
export const grow = () => keyframes`
0% {
transform: scale(0);
}
50% {
transform: scale(1.5);
}
100%{
transform: scale(1);
}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/ColorPalette/index.jsx
import ColorPalette from "./palette.json"; export default (color, variation) => ColorPalette[color][variation].value;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/ModalHeaderV3/styled-components.js
import styled, { css } from "styled-components";
import { transparentize } from "polished";
import { buildTitle } from "../../_atom/Title";
import Button from "../../_atom/Buttons/default";
import { fontBold } from "../../_static/Typography";
import { easeInOut, generateTransition } from "../../_static/Transitions";
import buildColor from "../../_static/ColorPalette";
export const TitleContainer = styled.div`
position: relative;
display: flex;
align-items: flex-start;
padding: 8px;
transition: ${generateTransition(easeInOut, "box-shadow")};
background-color: ${buildColor("white", "100")};
${({ showBottomShadow }) =>
showBottomShadow &&
css`
box-shadow: inset 0 -1px 0 ${buildColor("blue", "100")};
`};
color: ${buildColor("grey", "900")};
flex: 0 0 auto;
z-index: 2;
${(props) =>
props.roundedCorners &&
css`
border-radius: 4px 4px 0 0;
`};
${(props) =>
props.showShadow &&
css`
box-shadow:
0 2px 4px ${transparentize(0.94, buildColor("blue", "900"))},
0 1px 2px ${transparentize(0.92, buildColor("blue", "900"))};
`};
${(props) =>
props.device === "tablet" &&
css`
padding: 16px;
`};
`;
export const TitleHolder = styled.div`
display: inline-flex;
flex: 1 0 auto;
flex-direction: column;
${({ isTitleCenter }) =>
isTitleCenter &&
css`
text-align: center;
`}
`;
export const Title = styled(
buildTitle({
color: buildColor("grey", "900"),
fontSize: 16,
ellipsis: true,
uppercase: false,
qaLabel: "modal-title"
})
)`
flex: 1 1 auto;
margin: 4px 0 0 4px;
line-height: 24px;
font-family: ${fontBold};
${({ isTitleCapitalized }) =>
isTitleCapitalized &&
css`
text-transform: capitalize;
`}
`;
export const Subtitle = styled.p`
${({ isTitleCenter }) =>
!isTitleCenter &&
css`
margin: 0 0 4px 4px;
`};
line-height: 18px;
font-family: ${({ subtitleFontFamily }) => subtitleFontFamily};
font-size: 14px;
font-style: normal;
text-transform: capitalize;
color: ${({ subtitleColor }) => subtitleColor};
`;
const buttonStyle = css`
display: flex;
justify-content: center;
align-items: center;
width: 32px;
height: 32px;
border: 0;
background: none;
border-radius: 50%;
&:hover {
background-color: ${buildColor("grey", "100")};
}
&:active {
background-color: ${buildColor("grey", "200")};
}
@media (pointer: fine) {
&:hover {
background-color: ${buildColor("grey", "100")};
}
}
@media (pointer: coarse) {
&:active {
background-color: ${buildColor("grey", "200")};
}
}
`;
export const BackButton = styled(Button)`
${({ isAbsolute }) =>
isAbsolute &&
css`
position: absolute;
left: 6px;
top: 8px;
`};
${buttonStyle}
`;
export const CloseButton = styled(Button)`
position: absolute;
right: 6px;
top: 8px;
${buttonStyle}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Icons/icons.js
import color from "../ColorPalette";
export const account = {
id: "account",
shapes: [
{
path: "M506.24 416c70.692 0 128-57.308 128-128s-57.308-128-128-128v0c-70.692 0-128 57.308-128 128s57.308 128 128 128v0zM506.24 512c-123.712 0-224-100.288-224-224s100.288-224 224-224v0c123.712 0 224 100.288 224 224s-100.288 224-224 224v0zM840.96 864l-13.44-80.192c-10.911-63.833-65.826-111.808-131.946-111.808-0.008 0-0.015 0-0.023 0l-378.687-0c-0.006-0-0.014-0-0.022-0-66.12 0-121.035 47.975-131.834 111.015l-0.112 0.793-13.376 80.192h669.44zM316.8 576h378.688c0.015-0 0.034-0 0.052-0 113.556 0 207.871 82.38 226.443 190.638l0.193 1.362 25.792 154.752c0.276 1.578 0.433 3.394 0.433 5.248 0 17.668-14.318 31.992-31.984 32l-820.417 0c-17.667-0.008-31.985-14.332-31.985-32 0-1.854 0.158-3.67 0.46-5.438l-0.027 0.19 25.792-154.752c18.76-109.594 113.035-191.961 226.556-192l0.004-0z",
fill: null
}
]
};
export const accountTransactions = {
id: "accountTransactions",
shapes: [
{
path: "M143.768 64C64.242 64-.195 128.488-.195 208v608c0 79.512 64.437 144 143.963 144h267.019v-96H143.768c-26.472 0-47.963-21.473-47.963-48V208c0-26.527 21.491-48 47.963-48h473.144c30.561 0 54.395 25.386 54.395 48v66.501h96V208c0-83.425-74.957-144-150.395-144H143.768zM512.02 656c0-114.892 93.098-208 207.902-208 114.804 0 207.902 93.108 207.902 208s-93.098 208-207.902 208c-114.804 0-207.902-93.108-207.902-208zm207.902-304C552.064 352 416.02 488.123 416.02 656s136.044 304 303.902 304c167.858 0 303.898-136.123 303.898-304S887.78 352 719.922 352zm39.12 224c0-26.51-21.49-48-48-48-26.509 0-48 21.49-48 48v117.383a48.002 48.002 0 0028.519 43.869l95.963 42.617c24.228 10.759 52.591-.159 63.351-24.387 10.759-24.228-.159-52.591-24.387-63.351l-67.446-29.952V576zm-439.351 31.826h-128v-96h128v96zm-128-191.797h255.903v-96H191.691v96z",
fill: null,
fillRule: "evenodd",
clipRule: "evenodd"
}
]
};
export const chat = {
id: "chat",
shapes: [
{
path: "M873.412 120.471h-722.824c-49.815 0-90.353 40.538-90.353 90.353v481.882c0 49.815 40.538 90.353 90.353 90.353h164.563l111.556 167.273c5.602 8.373 14.999 13.432 25.058 13.432s19.456-5 25.058-13.432l111.556-167.273h285.033c49.815 0 90.353-40.538 90.353-90.353v-481.882c0-49.815-40.538-90.353-90.353-90.353zM903.529 692.706c0 16.625-13.553 30.118-30.118 30.118h-301.176c-10.059 0-19.456 5-25.058 13.432l-95.413 143.119-95.413-143.119c-5.602-8.433-14.999-13.432-25.058-13.432h-180.706c-16.565 0-30.118-13.493-30.118-30.118v-481.882c0-16.625 13.553-30.118 30.118-30.118h722.824c16.565 0 30.118 13.493 30.118 30.118v481.882z",
fill: null
}
]
};
export const account20 = {
id: "account20",
shapes: [
{
path: "M151.706 883.2h720.589l-15.923-119.296c-8.635-63.047-62.142-111.101-126.873-111.104l-434.995-0c-64.732 0.003-118.239 48.057-126.799 110.438l-0.075 0.666-15.872 119.296zM294.554 576h434.944c0.002-0 0.004-0 0.007-0 103.557 0 189.162 76.861 202.881 176.648l0.12 1.067 23.654 177.306c0.143 1.015 0.224 2.188 0.224 3.379 0 14.138-11.462 25.6-25.6 25.6-0.007 0-0.014-0-0.020-0l-837.58 0c-0.006 0-0.012 0-0.019 0-14.138 0-25.6-11.462-25.6-25.6 0-1.192 0.081-2.364 0.239-3.512l-0.015 0.133 23.654-177.306c13.839-100.854 99.444-177.715 203.001-177.715 0.002 0 0.005 0 0.007 0l-0-0zM512 512c-123.712 0-224-100.288-224-224s100.288-224 224-224v0c123.712 0 224 100.288 224 224s-100.288 224-224 224v0zM512 435.2c81.296 0 147.2-65.904 147.2-147.2s-65.904-147.2-147.2-147.2v0c-81.296 0-147.2 65.904-147.2 147.2s65.904 147.2 147.2 147.2v0z",
fill: null
}
]
};
export const calendar = {
id: "calendar",
shapes: [
{
path: "M672 67.2a48 48 0 0148 48V128h128a112 112 0 01112 112v608a112 112 0 01-112 112H176A112 112 0 0164 848V240a112 112 0 01112-112h128v-12.8a48 48 0 1196 0V128h224v-12.8a48 48 0 0148-48zM624 224H400v44.8a48 48 0 11-96 0V224H176a16 16 0 00-16 16v608a16 16 0 0016 16h672a16 16 0 0016-16V240a16 16 0 00-16-16H720v44.8a48 48 0 11-96 0V224zM352 704v64h-96v-64h96zm192 0v64h-96v-64h96zM352 576v64h-96v-64h96zm192 0v64h-96v-64h96zm192 0v64h-96v-64h96zm-576-96v-96h704v96H160z",
fill: null
}
]
};
export const add = {
id: "add",
shapes: [
{
path: "M576 448h224c17.673 0 32 14.327 32 32v0 64c0 17.673-14.327 32-32 32v0h-224v224c0 17.673-14.327 32-32 32v0h-64c-17.673 0-32-14.327-32-32v0-224h-224c-17.673 0-32-14.327-32-32v0-64c0-17.673 14.327-32 32-32v0h224v-224c0-17.673 14.327-32 32-32v0h64c17.673 0 32 14.327 32 32v0 224z",
fill: null
}
]
};
export const minus = {
id: "minus",
shapes: [
{
path: "M224 448h576c17.673 0 32 14.327 32 32v64c0 17.673-14.327 32-32 32h-576c-17.673 0-32-14.327-32-32v-64c0-17.673 14.327-32 32-32z",
fill: null
}
]
};
export const plus = {
id: "plus",
shapes: [
{
path: "M560 560h176c17.673 0 32-14.327 32-32v0-32c0-17.673-14.327-32-32-32v0h-176v-176c0-17.673-14.327-32-32-32v0h-32c-17.673 0-32 14.327-32 32v0 176h-176c-17.673 0-32 14.327-32 32v0 32c0 17.673 14.327 32 32 32v0h176v176c0 17.673 14.327 32 32 32v0h32c17.673 0 32-14.327 32-32v0-176zM512 0c-282.77 0-512 229.23-512 512s229.23 512 512 512v0c282.77 0 512-229.23 512-512s-229.23-512-512-512v0zM512 96c229.75 0 416 186.25 416 416s-186.25 416-416 416v0c-229.75 0-416-186.25-416-416s186.25-416 416-416v0z",
fill: null
}
]
};
export const tick = {
id: "tick",
shapes: [
{
path: "M373.312 651.648l429.888-429.888c5.791-5.789 13.789-9.369 22.624-9.369s16.833 3.58 22.624 9.369l45.248 45.248c5.789 5.791 9.369 13.789 9.369 22.624s-3.58 16.833-9.369 22.624l-497.792 497.792c-5.791 5.789-13.789 9.369-22.624 9.369s-16.833-3.58-22.624-9.369l-226.24-226.24c-5.789-5.791-9.369-13.789-9.369-22.624s3.58-16.833 9.369-22.624l45.248-45.248c5.791-5.789 13.789-9.369 22.624-9.369s16.833 3.58 22.624 9.369l158.4 158.336z",
fill: null
}
]
};
export const doubleArrowRight = {
id: "doubleArrowRight",
shapes: [
{
path: "M728.034 511.984l-248.902-248.902c-12.497-12.497-12.497-32.758 0-45.255l45.255-45.255c12.497-12.497 32.758-12.497 45.255 0l316.784 316.784c12.497 12.497 12.497 32.758 0 45.255l-316.784 316.784c-12.497 12.497-32.758 12.497-45.255 0l-45.255-45.255c-12.497-12.497-12.497-32.758 0-45.255l248.902-248.902zM386.274 512l-248.902-248.902c-12.497-12.497-12.497-32.758 0-45.255l45.255-45.255c12.497-12.497 32.758-12.497 45.255 0l316.784 316.784c12.497 12.497 12.497 32.758 0 45.255l-316.784 316.784c-12.497 12.497-32.758 12.497-45.255 0l-45.255-45.255c-12.497-12.497-12.497-32.758 0-45.255l248.902-248.902z",
fill: null
}
]
};
export const doubleArrowLeft = {
id: "doubleArrowLeft",
shapes: [
{
path: "M295.765 512l248.902 248.902c12.497 12.497 12.497 32.758 0 45.255l-45.255 45.255c-12.497 12.497-32.758 12.497-45.255 0l-316.784-316.784c-12.497-12.497-12.497-32.758 0-45.255l316.784-316.784c12.497-12.497 32.758-12.497 45.255 0l45.255 45.255c12.497 12.497 12.497 32.758 0 45.255l-248.902 248.902zM637.525 511.984l248.902 248.902c12.497 12.497 12.497 32.758 0 45.255l-45.255 45.255c-12.497 12.497-32.758 12.497-45.255 0l-316.784-316.784c-12.497-12.497-12.497-32.758 0-45.255l316.784-316.784c12.497-12.497 32.758-12.497 45.255 0l45.255 45.255c12.497 12.497 12.497 32.758 0 45.255l-248.902 248.902z",
fill: null
}
]
};
export const alert = {
id: "alert",
shapes: [
{
path: "M502.656 160c-123.712 0-224 100.288-224 224v0 128c-0.001 15.629-3.737 30.386-10.364 43.426l0.252-0.546-42.176 84.352c-1.502 2.947-2.382 6.427-2.382 10.112 0 12.513 10.143 22.656 22.656 22.656 0.005 0 0.010-0 0.015-0l511.999 0c0.004 0 0.009 0 0.014 0 12.513 0 22.656-10.143 22.656-22.656 0-3.685-0.88-7.165-2.441-10.241l0.059 0.129-42.176-84.288c-6.376-12.496-10.112-27.255-10.112-42.887 0-0.020 0-0.040 0-0.061l-0 0.003v-128c0-123.712-100.288-224-224-224v0zM502.656 64c176.731 0 320 143.269 320 320v0 128l42.112 84.288c7.896 15.458 12.523 33.717 12.523 53.056 0 65.524-53.112 118.644-118.634 118.656l-512.001 0c-65.523-0.012-118.635-53.132-118.635-118.656 0-19.34 4.627-37.598 12.834-53.73l-0.311 0.674 42.112-84.288v-128c0-176.731 143.269-320 320-320v0zM502.656 864c53.019 0 96-42.981 96-96v0h-192c0 53.019 42.981 96 96 96v0zM310.656 672h384v96c0 106.039-85.961 192-192 192s-192-85.961-192-192v0-96z",
fill: null
}
]
};
export const alertSuspended = {
id: "alert-suspended",
shapes: [
{
path: "M182.7 386.3l96 96V512a96 96 0 01-10.2 43l-42.1 84.2a22.7 22.7 0 0020.3 32.8h221.7l96 96H406.7A96 96 0 00594 797.6l71.7 71.8a191.9 191.9 0 01-355-101.4h-64a118.7 118.7 0 01-106.2-171.7l42.2-84.3V386.3zM109.3 86.6a32 32 0 0145.2 0L923.8 856a32 32 0 010 45.2l-22.6 22.6a32 32 0 01-45.2 0L86.6 154.5a32 32 0 010-45.2zM502.7 64a320 320 0 01320 320v128l42.1 84.3a118.1 118.1 0 0110.4 75.3L727.4 523.7a96 96 0 01-.7-11.7V384a224 224 0 00-334.2-195.1L323 119.2A318.5 318.5 0 01502.7 64z",
fill: null
}
]
};
export const trash = {
id: "trash",
shapes: [
{
path: "M320 256v-64c0-70.692 57.308-128 128-128v0h128c70.692 0 128 57.308 128 128v0 64h160c17.673 0 32 14.327 32 32v0 32c0 17.673-14.327 32-32 32v0h-704c-17.673 0-32-14.327-32-32v0-32c0-17.673 14.327-32 32-32v0h160zM832 448v480c0 17.673-14.327 32-32 32v0h-576c-17.673 0-32-14.327-32-32v0-480c0-17.673 14.327-32 32-32v0h32c17.673 0 32 14.327 32 32v0 416h448v-416c0-17.673 14.327-32 32-32v0h32c17.673 0 32 14.327 32 32v0zM416 416h32c17.673 0 32 14.327 32 32v0 288c0 17.673-14.327 32-32 32v0h-32c-17.673 0-32-14.327-32-32v0-288c0-17.673 14.327-32 32-32v0zM576 416h32c17.673 0 32 14.327 32 32v0 288c0 17.673-14.327 32-32 32v0h-32c-17.673 0-32-14.327-32-32v0-288c0-17.673 14.327-32 32-32v0zM416 256h192v-64c0-17.673-14.327-32-32-32v0h-128c-17.673 0-32 14.327-32 32v0 64z",
fill: null
}
]
};
export const trash20 = {
id: "trash20",
shapes: [
{
path: "M281.6 883.2h460.8v-448c0-14.138 11.462-25.6 25.6-25.6h25.6c14.138 0 25.6 11.462 25.6 25.6v499.2c0 14.138-11.462 25.6-25.6 25.6h-563.2c-14.138 0-25.6-11.462-25.6-25.6v-499.2c0-14.138 11.462-25.6 25.6-25.6h25.6c14.138 0 25.6 11.462 25.6 25.6v448zM307.2 256v-89.6c0-56.554 45.846-102.4 102.4-102.4h204.8c56.554 0 102.4 45.846 102.4 102.4v89.6h128c14.138 0 25.6 11.462 25.6 25.6v25.6c0 14.138-11.462 25.6-25.6 25.6h-665.6c-14.138 0-25.6-11.462-25.6-25.6v-25.6c0-14.138 11.462-25.6 25.6-25.6h128zM435.2 140.8c-28.277 0-51.2 22.923-51.2 51.2v64h256v-64c0-28.277-22.923-51.2-51.2-51.2h-153.6zM422.153 409.6h25.6c14.138 0 25.6 11.462 25.6 25.6v345.6c0 14.138-11.462 25.6-25.6 25.6h-25.6c-14.138 0-25.6-11.462-25.6-25.6v-345.6c0-14.138 11.462-25.6 25.6-25.6zM575.753 409.6h25.6c14.138 0 25.6 11.462 25.6 25.6v345.6c0 14.138-11.462 25.6-25.6 25.6h-25.6c-14.138 0-25.6-11.462-25.6-25.6v-345.6c0-14.138 11.462-25.6 25.6-25.6z",
fill: null
}
]
};
export const lock = {
id: "lock",
shapes: [
{
path: "M224 448v416h576v-416h-576zM256 352v-96c0-106.039 85.961-192 192-192v0h128c106.039 0 192 85.961 192 192v0 96h96c17.673 0 32 14.327 32 32v0 544c0 17.673-14.327 32-32 32v0h-704c-17.673 0-32-14.327-32-32v0-544c0-17.673 14.327-32 32-32v0h96zM352 352h320v-96c0-53.019-42.981-96-96-96v0h-128c-53.019 0-96 42.981-96 96v0 96zM480 560h64c17.673 0 32 14.327 32 32v0 96c0 17.673-14.327 32-32 32v0h-64c-17.673 0-32-14.327-32-32v0-96c0-17.673 14.327-32 32-32v0z",
fill: null
}
]
};
export const warningOutline = {
id: "warningOutline",
shapes: [
{
path: "M612.16 70.592c-41.216-82.56-159.040-82.56-200.32 0l-392.448 784.896c-7.463 14.599-11.836 31.845-11.836 50.112 0 61.855 50.142 111.998 111.996 112l784.896 0c61.854-0.002 111.996-50.145 111.996-112 0-18.267-4.373-35.513-12.13-50.748l0.294 0.636-392.448-784.896zM497.728 113.536c2.688-5.278 8.081-8.831 14.304-8.831s11.616 3.553 14.262 8.74l0.042 0.091 392.448 784.896c1.069 2.088 1.695 4.555 1.695 7.168 0 8.837-7.163 16-16 16-0.011 0-0.022-0-0.033-0l0.002 0h-784.896c-8.823-0.019-15.967-7.175-15.967-16 0-2.613 0.626-5.080 1.737-7.259l-0.042 0.091 392.448-784.896zM464 384c0-17.673 14.327-32 32-32v0h32c17.673 0 32 14.327 32 32v0 224c0 17.673-14.327 32-32 32v0h-32c-17.673 0-32-14.327-32-32v0-224zM464 768c0-17.673 14.327-32 32-32v0h32c17.673 0 32 14.327 32 32v0 32c0 17.673-14.327 32-32 32v0h-32c-17.673 0-32-14.327-32-32v0-32z",
fill: null
}
]
};
export const warning = {
id: "warning",
shapes: [
{
path: "M612.16 70.592c-41.216-82.56-159.040-82.56-200.32 0l-392.448 784.896c-7.463 14.599-11.836 31.845-11.836 50.112 0 61.855 50.142 111.998 111.996 112l784.896 0c61.854-0.002 111.996-50.145 111.996-112 0-18.267-4.373-35.513-12.13-50.748l0.294 0.636-392.448-784.896zM464 384c0-17.673 14.327-32 32-32v0h32c17.673 0 32 14.327 32 32v0 224c0 17.673-14.327 32-32 32v0h-32c-17.673 0-32-14.327-32-32v0-224zM464 768c0-17.673 14.327-32 32-32v0h32c17.673 0 32 14.327 32 32v0 32c0 17.673-14.327 32-32 32v0h-32c-17.673 0-32-14.327-32-32v0-32z",
fill: null
}
]
};
export const close = {
id: "close",
shapes: [
{
path: "M602.496 512l226.304 226.304c5.789 5.791 9.369 13.789 9.369 22.624s-3.58 16.833-9.369 22.624l-45.248 45.248c-5.791 5.789-13.789 9.369-22.624 9.369s-16.833-3.58-22.624-9.369l-226.304-226.304-226.304 226.304c-5.791 5.789-13.789 9.369-22.624 9.369s-16.833-3.58-22.624-9.369l-45.248-45.248c-5.789-5.791-9.369-13.789-9.369-22.624s3.58-16.833 9.369-22.624l226.304-226.304-226.304-226.304c-5.789-5.791-9.369-13.789-9.369-22.624s3.58-16.833 9.369-22.624l45.248-45.248c5.791-5.789 13.789-9.369 22.624-9.369s16.833 3.58 22.624 9.369l226.304 226.304 226.304-226.304c5.791-5.789 13.789-9.369 22.624-9.369s16.833 3.58 22.624 9.369l45.248 45.248c5.789 5.791 9.369 13.789 9.369 22.624s-3.58 16.833-9.369 22.624l-226.304 226.304z",
fill: null
}
]
};
export const arrowBack = {
id: "arrowBack",
shapes: [
{
path: "M321.28 575.744l184.96 185.024c5.789 5.791 9.369 13.789 9.369 22.624s-3.58 16.833-9.369 22.624l-45.248 45.248c-5.791 5.789-13.789 9.369-22.624 9.369s-16.833-3.58-22.624-9.369l-316.8-316.8c-5.77-5.787-9.337-13.773-9.337-22.592s3.567-16.805 9.338-22.593l-0.001 0.001 316.8-316.8c5.791-5.789 13.789-9.369 22.624-9.369s16.833 3.58 22.624 9.369l45.248 45.248c5.789 5.791 9.369 13.789 9.369 22.624s-3.58 16.833-9.369 22.624l-184.768 184.768h590.464c17.673 0 32 14.327 32 32v0 64c0 17.673-14.327 32-32 32v0h-590.656z",
fill: null
}
]
};
export const arrowForward = {
id: "arrowForward",
shapes: [
{
path: "M712.32 448l-185.024-184.96c-5.808-5.794-9.401-13.805-9.401-22.656s3.593-16.862 9.401-22.655l0.001-0.001 45.248-45.248c5.791-5.789 13.789-9.369 22.624-9.369s16.833 3.58 22.624 9.369l316.8 316.8c5.789 5.791 9.369 13.789 9.369 22.624s-3.58 16.833-9.369 22.624l-316.8 316.8c-5.791 5.789-13.789 9.369-22.624 9.369s-16.833-3.58-22.624-9.369l0 0-45.248-45.312c-5.789-5.791-9.369-13.789-9.369-22.624s3.58-16.833 9.369-22.624l184.768-184.768h-590.464c-17.673 0-32-14.327-32-32v0-64c0-17.673 14.327-32 32-32v0h590.72z",
fill: null
}
]
};
export const arrowUpward = {
id: "arrowUpward",
shapes: [
{
path: "M452.864 316.352l-184.96 185.024c-5.794 5.808-13.805 9.401-22.656 9.401s-16.862-3.593-22.655-9.401l-0.001-0.001-45.248-45.248c-5.789-5.791-9.369-13.789-9.369-22.624s3.58-16.833 9.369-22.624l316.8-316.8c5.791-5.789 13.789-9.369 22.624-9.369s16.833 3.58 22.624 9.369l316.8 316.8c5.789 5.791 9.369 13.789 9.369 22.624s-3.58 16.833-9.369 22.624l-45.248 45.248c-5.791 5.789-13.789 9.369-22.624 9.369s-16.833-3.58-22.624-9.369l-184.832-184.768v590.464c0 17.673-14.327 32-32 32v0h-64c-17.673 0-32-14.327-32-32v0-590.72z",
fill: null
}
]
};
export const arrowDownward = {
id: "arrowDownward",
shapes: [
{
path: "M580.672 707.392l184.96-184.96c5.794-5.808 13.805-9.401 22.656-9.401s16.862 3.593 22.655 9.401l0.001 0.001 45.248 45.184c5.808 5.794 9.401 13.805 9.401 22.656s-3.593 16.862-9.401 22.655l-0.001 0.001-316.8 316.8c-5.791 5.789-13.789 9.369-22.624 9.369s-16.833-3.58-22.624-9.369l-316.8-316.8c-5.808-5.794-9.401-13.805-9.401-22.656s3.593-16.862 9.401-22.655l0.001-0.001 45.248-45.248c5.794-5.808 13.805-9.401 22.656-9.401s16.862 3.593 22.655 9.401l0.001 0.001 184.768 184.832v-590.464c0-17.673 14.327-32 32-32v0h64c17.673 0 32 14.327 32 32v0 590.72z",
fill: null
}
]
};
export const arrowLeft = {
id: "arrowLeft",
shapes: [
{
path: "M427.008 512l248.896 248.96c5.77 5.787 9.337 13.773 9.337 22.592s-3.567 16.805-9.338 22.593l0.001-0.001-45.248 45.248c-5.794 5.808-13.805 9.401-22.656 9.401s-16.862-3.593-22.655-9.401l-0.001-0.001-316.8-316.8c-5.789-5.791-9.369-13.789-9.369-22.624s3.58-16.833 9.369-22.624l316.8-316.8c5.794-5.808 13.805-9.401 22.656-9.401s16.862 3.593 22.655 9.401l0.001 0.001 45.248 45.312c5.789 5.791 9.369 13.789 9.369 22.624s-3.58 16.833-9.369 22.624l-249.024 248.896z",
fill: null
}
]
};
export const arrowRight = {
id: "arrowRight",
shapes: [
{
path: "M596.992 512l-248.832-248.96c-5.77-5.787-9.337-13.773-9.337-22.592s3.567-16.805 9.338-22.593l-0.001 0.001 45.248-45.248c5.794-5.808 13.805-9.401 22.656-9.401s16.862 3.593 22.655 9.401l0.001 0.001 316.8 316.8c5.789 5.791 9.369 13.789 9.369 22.624s-3.58 16.833-9.369 22.624l-316.8 316.8c-5.794 5.808-13.805 9.401-22.656 9.401s-16.862-3.593-22.655-9.401l-0.001-0.001-45.248-45.312c-5.789-5.791-9.369-13.789-9.369-22.624s3.58-16.833 9.369-22.624l248.96-248.896z",
fill: null
}
]
};
export const arrowUp = {
id: "arrowUp",
shapes: [
{
path: "M512 427.008l-248.96 248.832c-5.787 5.77-13.773 9.337-22.592 9.337s-16.805-3.567-22.593-9.338l0.001 0.001-45.248-45.248c-5.808-5.794-9.401-13.805-9.401-22.656s3.593-16.862 9.401-22.655l0.001-0.001 316.8-316.8c5.791-5.789 13.789-9.369 22.624-9.369s16.833 3.58 22.624 9.369l316.8 316.8c5.808 5.794 9.401 13.805 9.401 22.656s-3.593 16.862-9.401 22.655l-0.001 0.001-45.312 45.248c-5.791 5.789-13.789 9.369-22.624 9.369s-16.833-3.58-22.624-9.369l-248.896-248.96z",
fill: null
}
]
};
export const arrowDown = {
id: "arrowDown",
shapes: [
{
path: "M512 596.992l248.96-248.896c5.787-5.77 13.773-9.337 22.592-9.337s16.805 3.567 22.593 9.338l-0.001-0.001 45.248 45.248c5.808 5.794 9.401 13.805 9.401 22.656s-3.593 16.862-9.401 22.655l-0.001 0.001-316.8 316.8c-5.791 5.789-13.789 9.369-22.624 9.369s-16.833-3.58-22.624-9.369l-316.8-316.8c-5.808-5.794-9.401-13.805-9.401-22.656s3.593-16.862 9.401-22.655l0.001-0.001 45.312-45.248c5.791-5.789 13.789-9.369 22.624-9.369s16.833 3.58 22.624 9.369l248.896 249.024z",
fill: null
}
]
};
export const home = {
id: "home",
shapes: [
{
path: "M160 404.416v459.584h192v-192c0-70.692 57.308-128 128-128v0h64c70.692 0 128 57.308 128 128v0 192h192v-459.584l-352-226.304-352 226.368zM78.72 342.528l416-267.392c4.885-3.177 10.862-5.067 17.28-5.067s12.395 1.889 17.404 5.142l-0.124-0.076 416 267.392c8.909 5.78 14.72 15.678 14.72 26.933 0 0.004-0 0.008-0 0.011l0-0.001v558.528c0 17.673-14.327 32-32 32v0h-320c-17.673 0-32-14.327-32-32v0-256c0-17.673-14.327-32-32-32v0h-64c-17.673 0-32 14.327-32 32v0 256c0 17.673-14.327 32-32 32v0h-320c-17.673 0-32-14.327-32-32v0-558.528c0.019-11.235 5.825-21.109 14.596-26.804l0.124-0.076z",
fill: null
}
]
};
export const home20 = {
id: "home20",
shapes: [
{
path: "M512 158.362l-371.2 265.165v459.674h217.6v-243.2c0-56.554 45.846-102.4 102.4-102.4v0h102.4c56.554 0 102.4 45.846 102.4 102.4v0 243.2h217.6v-459.674l-371.2-265.165zM526.848 74.65l422.4 301.67c6.537 4.696 10.747 12.275 10.752 20.838l0 0.001v537.242c0 14.138-11.462 25.6-25.6 25.6v0h-320c-14.138 0-25.6-11.462-25.6-25.6v0-294.4c0-14.138-11.462-25.6-25.6-25.6v0h-102.4c-14.138 0-25.6 11.462-25.6 25.6v0 294.4c0 14.138-11.462 25.6-25.6 25.6v0h-320c-14.138 0-25.6-11.462-25.6-25.6v0-537.242c0.005-8.563 4.215-16.143 10.676-20.786l0.076-0.052 422.4-301.67c4.125-2.968 9.279-4.746 14.848-4.746s10.723 1.778 14.924 4.798l-0.076-0.052z",
fill: null
}
]
};
export const tracks = {
id: "tracks",
shapes: [
{
path: "M448 128c-0.016-0-0.035-0-0.054-0-212.077 0-384 171.923-384 384 0 70.692 19.103 136.923 52.427 193.812l-0.981-1.812h117.952c-45.51-50.716-73.337-118.108-73.337-192 0-159.056 128.938-287.996 287.993-288l480-0c17.673 0 32-14.327 32-32v0-32c0-17.673-14.327-32-32-32v0h-480zM790.656 320c45.51 50.716 73.337 118.108 73.337 192 0 159.056-128.938 287.996-287.993 288l-480 0c-17.673 0-32 14.327-32 32v0 32c0 17.673 14.327 32 32 32v0h480c0.016 0 0.035 0 0.054 0 212.077 0 384-171.923 384-384 0-70.692-19.103-136.923-52.427-193.812l0.981 1.812h-117.952zM576 320c106.039 0 192 85.961 192 192s-85.961 192-192 192v0h-128c-106.039 0-192-85.961-192-192s85.961-192 192-192v0h128zM448 416c-53.019 0-96 42.981-96 96s42.981 96 96 96v0h128c53.019 0 96-42.981 96-96s-42.981-96-96-96v0h-128z",
fill: null
}
]
};
export const results = {
id: "results",
shapes: [
{
path: "M512 64c159.058 0 288 128.942 288 288 0 142.684-103.761 261.134-239.944 284.009l-0.056 291.991c0 17.673-14.327 32-32 32h-32c-17.673 0-32-14.327-32-32l0.008-291.981c-136.214-22.848-240.008-141.313-240.008-284.019 0-159.058 128.942-288 288-288zM512 172c-99.411 0-180 80.589-180 180s80.589 180 180 180c99.411 0 180-80.589 180-180s-80.589-180-180-180z",
fill: null
}
]
};
export const tracks20 = {
id: "tracks20",
shapes: [
{
path: "M64 512c0-226.216 183.384-409.6 409.6-409.6v0h460.8c14.138 0 25.6 11.462 25.6 25.6v0 25.6c0 14.138-11.462 25.6-25.6 25.6v0h-460.8c-0.010-0-0.023-0-0.035-0-183.8 0-332.8 149-332.8 332.8 0 102.693 46.513 194.522 119.621 255.57l0.53 0.43h-107.059c-55.974-69.243-89.856-158.359-89.856-255.389 0-0.215 0-0.43 0-0.645l-0 0.034zM537.6 256h-64c-141.385 0-256 114.615-256 256s114.615 256 256 256v0h76.8c141.385 0 256-114.615 256-256s-114.615-256-256-256v0h-12.8zM763.085 256c73.637 61.477 120.15 153.307 120.15 256 0 183.8-149 332.8-332.8 332.8-0.012 0-0.025-0-0.037-0l-460.798 0c-14.138 0-25.6 11.462-25.6 25.6v0 25.6c0 14.138 11.462 25.6 25.6 25.6v0h460.8c226.216 0 409.6-183.384 409.6-409.6 0-97.228-33.877-186.544-90.47-256.788l0.614 0.788h-107.059zM294.4 512c0-98.969 80.231-179.2 179.2-179.2v0h76.8c98.969 0 179.2 80.231 179.2 179.2s-80.231 179.2-179.2 179.2v0h-76.8c-98.969 0-179.2-80.231-179.2-179.2v0z",
fill: null
}
]
};
export const cup = {
id: "cup",
shapes: [
{
path: "M232.064 576h-40.064c-70.692 0-128-57.308-128-128v0-224c0-17.673 14.327-32 32-32v0h128v-96c0-17.673 14.327-32 32-32v0h512c17.673 0 32 14.327 32 32v0 96h128c17.673 0 32 14.327 32 32v0 224c0 70.692-57.308 128-128 128v0h-40.064c-28.108 106.091-119.976 184.254-231.18 191.449l-0.756 0.039v96.512h112c17.673 0 32 14.327 32 32v0 32c0 17.673-14.327 32-32 32v0h-320c-17.673 0-32-14.327-32-32v0-32c0-17.673 14.327-32 32-32v0h112v-96.512c-111.96-7.234-203.829-85.398-231.532-189.7l-0.404-1.788zM800 288v192h32c17.673 0 32-14.327 32-32v0-160h-64zM160 288v160c0 17.673 14.327 32 32 32v0h32v-192h-64zM320 160v352c0 88.366 71.634 160 160 160v0h64c88.366 0 160-71.634 160-160v0-352h-384z",
fill: null
}
]
};
export const more = {
id: "more",
shapes: [
{
path: "M96 256h832c17.673 0 32 14.327 32 32v0 32c0 17.673-14.327 32-32 32v0h-832c-17.673 0-32-14.327-32-32v0-32c0-17.673 14.327-32 32-32v0zM96 496h832c17.673 0 32 14.327 32 32v0 32c0 17.673-14.327 32-32 32v0h-832c-17.673 0-32-14.327-32-32v0-32c0-17.673 14.327-32 32-32v0zM96 736h832c17.673 0 32 14.327 32 32v0 32c0 17.673-14.327 32-32 32v0h-832c-17.673 0-32-14.327-32-32v0-32c0-17.673 14.327-32 32-32v0z",
fill: null
}
]
};
export const more20 = {
id: "more20",
shapes: [
{
path: "M85.35 192h853.299c11.776 0 21.35 9.574 21.35 21.35v34.099c0 11.776-9.574 21.35-21.35 21.35h-853.299c-11.792 0-21.35-9.559-21.35-21.35h0v-34.099c0-11.776 9.574-21.35 21.35-21.35zM85.35 473.6h853.299c11.776 0 21.35 9.574 21.35 21.35v34.099c0 11.776-9.574 21.35-21.35 21.35h-853.299c-11.792 0-21.35-9.559-21.35-21.35l0 0v-34.099c0-11.776 9.574-21.35 21.35-21.35zM85.35 755.2h853.299c11.776 0 21.35 9.574 21.35 21.35v34.099c0 11.776-9.574 21.35-21.35 21.35h-853.299c-11.792 0-21.35-9.559-21.35-21.35l0 0v-34.099c0-11.776 9.574-21.35 21.35-21.35z",
fill: null
}
]
};
export const exclamationOutline = {
id: "exclamationOutline",
shapes: [
{
path: "M512 1024c-282.77 0-512-229.23-512-512s229.23-512 512-512v0c282.77 0 512 229.23 512 512s-229.23 512-512 512v0zM512 928c229.75 0 416-186.25 416-416s-186.25-416-416-416v0c-229.75 0-416 186.25-416 416s186.25 416 416 416v0zM496 256h32c17.673 0 32 14.327 32 32v0 272c0 17.673-14.327 32-32 32v0h-32c-17.673 0-32-14.327-32-32v0-272c0-17.673 14.327-32 32-32v0zM496 672h32c17.673 0 32 14.327 32 32v0 32c0 17.673-14.327 32-32 32v0h-32c-17.673 0-32-14.327-32-32v0-32c0-17.673 14.327-32 32-32v0z",
fill: null
}
]
};
export const exclamation = {
id: "exclamation",
shapes: [
{
path: "M512 1024c-282.77 0-512-229.23-512-512s229.23-512 512-512v0c282.77 0 512 229.23 512 512s-229.23 512-512 512v0zM496 256c-17.673 0-32 14.327-32 32v0 272c0 17.673 14.327 32 32 32v0h32c17.673 0 32-14.327 32-32v0-272c0-17.673-14.327-32-32-32v0h-32zM496 672c-17.673 0-32 14.327-32 32v0 32c0 17.673 14.327 32 32 32v0h32c17.673 0 32-14.327 32-32v0-32c0-17.673-14.327-32-32-32v0h-32z",
fill: null
}
]
};
export const changes = {
id: "changes",
shapes: [
{
path: "M432.804 43.536c43.739-43.739 114.653-43.739 158.392 0l389.27 389.27c43.734 43.738 43.734 114.653 0 158.392l-389.27 389.27c-43.739 43.742-114.653 43.742-158.392 0l-389.27-389.27c-43.739-43.739-43.739-114.654 0-158.392l389.27-389.27zm90.51 67.882c-6.249-6.248-16.379-6.248-22.628 0l-389.27 389.27c-6.248 6.248-6.248 16.379 0 22.627l389.27 389.27c6.249 6.249 16.379 6.249 22.628 0l389.27-389.27c6.248-6.248 6.248-16.379 0-22.627l-389.27-389.27zM560 288.001v288h-96v-288h96zm0 352v96h-96v-96h96z",
fill: null
}
]
};
export const infoOutline = {
id: "infoOutline",
shapes: [
{
path: "M512 0c282.77 0 512 229.23 512 512s-229.23 512-512 512v0c-282.77 0-512-229.23-512-512s229.23-512 512-512v0zM512 96c-229.75 0-416 186.25-416 416s186.25 416 416 416v0c229.75 0 416-186.25 416-416s-186.25-416-416-416v0zM528 768h-32c-17.673 0-32-14.327-32-32v0-272c0-17.673 14.327-32 32-32v0h32c17.673 0 32 14.327 32 32v0 272c0 17.673-14.327 32-32 32v0zM528 352h-32c-17.673 0-32-14.327-32-32v0-32c0-17.673 14.327-32 32-32v0h32c17.673 0 32 14.327 32 32v0 32c0 17.673-14.327 32-32 32v0z",
fill: null
}
]
};
export const info = {
id: "info",
shapes: [
{
path: "M512 0c282.77 0 512 229.23 512 512s-229.23 512-512 512v0c-282.77 0-512-229.23-512-512s229.23-512 512-512v0zM528 768c17.673 0 32-14.327 32-32v0-272c0-17.673-14.327-32-32-32v0h-32c-17.673 0-32 14.327-32 32v0 272c0 17.673 14.327 32 32 32v0h32zM528 352c17.673 0 32-14.327 32-32v0-32c0-17.673-14.327-32-32-32v0h-32c-17.673 0-32 14.327-32 32v0 32c0 17.673 14.327 32 32 32v0h32z",
fill: null
}
]
};
export const bets = {
id: "bets",
shapes: [
{
path: "M224 160v684.622l24.998-16.665c42.996-28.664 99.008-28.664 142.004 0L416 844.622l24.998-16.665c42.996-28.664 99.009-28.664 142.004 0L608 844.622l24.998-16.665c42.995-28.664 99.009-28.664 142.004 0L800 844.622V160H224zm288-96h352c17.673 0 32 14.327 32 32v782.874a32 32 0 01-14.25 26.626l-64 42.666a31.998 31.998 0 01-35.5 0l-60.5-40.332a31.998 31.998 0 00-35.5 0l-60.5 40.332a31.998 31.998 0 01-35.5 0l-60.5-40.332a31.998 31.998 0 00-35.5 0l-60.5 40.332a31.998 31.998 0 01-35.5 0l-60.5-40.332a31.998 31.998 0 00-35.5 0l-60.5 40.332a31.998 31.998 0 01-35.5 0l-64-42.666A32 32 0 01128 878.874V96c0-17.673 14.327-32 32-32h352zM352 480h320c17.673 0 32 14.327 32 32v32c0 17.673-14.327 32-32 32H352c-17.673 0-32-14.327-32-32v-32c0-17.673 14.327-32 32-32zm0-192h128c17.673 0 32 14.327 32 32v32c0 17.673-14.327 32-32 32H352c-17.673 0-32-14.327-32-32v-32c0-17.673 14.327-32 32-32z",
fill: null
}
]
};
export const betsSuccess = {
id: "betsSuccess",
shapes: [
{
path: "M128 176c0-61.856 50.144-112 112-112h544c61.856 0 112 50.144 112 112v336h-96V176c0-8.837-7.163-16-16-16H240c-8.837 0-16 7.163-16 16v678.139l76.505-34.002a48.001 48.001 0 0146.121 3.925L416 870.311l69.374-46.249 53.252 79.876-96 64a48 48 0 01-53.252 0l-74.019-49.346-119.86 53.271A48.001 48.001 0 01128 928V176zm384 240H320v-96h192v96zm64 192H320v-96h256v96zm449.94 65.941l-255.999 256c-18.745 18.745-49.137 18.745-67.882 0l-128-128 67.882-67.882L736 828.118l222.059-222.059 67.881 67.882z",
fill: null
}
]
};
export const betsRefund = {
id: "betsRefund",
shapes: [
{
path: "M128 176c0-61.856 50.144-112 112-112h544c61.856 0 112 50.144 112 112v334.23h-96V176c0-8.837-7.163-16-16-16H240c-8.837 0-16 7.163-16 16v678.139l76.505-34.002a48.001 48.001 0 0146.121 3.925L416 870.311l69.374-46.249 53.252 79.876-96 64a48 48 0 01-53.252 0l-74.019-49.346-119.86 53.271A48.001 48.001 0 01128 928V176zm384 240H320v-96h192v96zm64 192H320v-96h256v96zm163.882 208l78.059 78.059-67.882 67.882-160-160c-18.745-18.745-18.745-49.137 0-67.882l160-160 67.882 67.882L739.882 720H976v96H739.882z",
fill: null
}
]
};
export const betsCancel = {
id: "betsCancel",
shapes: [
{
path: "M128 176c0-61.856 50.144-112 112-112h544c61.856 0 112 50.144 112 112v336h-96V176c0-8.837-7.163-16-16-16H240c-8.837 0-16 7.163-16 16v678.139l76.505-34.002a48.001 48.001 0 0146.121 3.925L416 870.311l69.374-46.249 53.252 79.876-96 64a48 48 0 01-53.252 0l-74.019-49.346-119.86 53.271A48.001 48.001 0 01128 928V176zm384 240H320v-96h192v96zm64 192H320v-96h256v96zm188.118 160L638.059 641.941l67.882-67.882L832 700.118l126.059-126.059 67.881 67.882L899.882 768l126.058 126.059-67.881 67.882L832 835.882 705.941 961.941l-67.882-67.882L764.118 768z",
fill: null
}
]
};
export const bets20 = {
id: "bets20",
shapes: [
{
path: "M204.8 140.8v714.086l19.2 12.8 39.219-26.112c15.957-10.765 35.619-17.184 56.781-17.184s40.824 6.419 57.146 17.416l-0.365-0.232 39.219 26.112 39.219-26.112c15.957-10.765 35.619-17.184 56.781-17.184s40.824 6.419 57.146 17.416l-0.365-0.232 39.219 26.112 39.219-26.112c15.957-10.765 35.619-17.184 56.781-17.184s40.824 6.419 57.146 17.416l-0.365-0.232 39.219 26.112 19.2-12.8v-714.086h-614.4zM204.8 881.766v0zM819.2 881.766v0zM512 64h358.4c14.138 0 25.6 11.462 25.6 25.6v0 792.678c-0.005 8.849-4.498 16.647-11.326 21.241l-0.092 0.058-70.4 46.95c-3.987 2.686-8.897 4.288-14.182 4.288s-10.196-1.601-14.274-4.346l0.091 0.058-67.584-45.056c-3.992-2.697-8.912-4.305-14.208-4.305s-10.216 1.608-14.299 4.362l0.091-0.058-67.584 45.056c-3.992 2.697-8.912 4.305-14.208 4.305s-10.216-1.608-14.299-4.362l0.091 0.058-67.584-45.056c-3.992-2.697-8.912-4.305-14.208-4.305s-10.216 1.608-14.299 4.362l0.091-0.058-67.584 45.056c-3.992 2.697-8.912 4.305-14.208 4.305s-10.216-1.608-14.299-4.362l0.091 0.058-67.584-45.056c-3.992-2.697-8.912-4.305-14.208-4.305s-10.216 1.608-14.299 4.362l0.091-0.058-67.584 45.056c-3.992 2.697-8.912 4.305-14.208 4.305s-10.216-1.608-14.299-4.362l0.091 0.058-70.4-46.95c-6.92-4.653-11.413-12.451-11.418-21.298l-0-0.001v-792.678c0-14.138 11.462-25.6 25.6-25.6v0h358.4zM345.6 489.626c-14.138 0-25.6 11.462-25.6 25.6v0 25.6c0 14.138 11.462 25.6 25.6 25.6v0h332.8c14.138 0 25.6-11.462 25.6-25.6v0-25.6c0-14.138-11.462-25.6-25.6-25.6v0h-332.8zM345.6 297.626c-14.138 0-25.6 11.462-25.6 25.6v0 25.6c0 14.138 11.462 25.6 25.6 25.6v0h140.8c14.138 0 25.6-11.462 25.6-25.6v0-25.6c0-14.138-11.462-25.6-25.6-25.6v0h-140.8z",
fill: null
}
]
};
export const starOutline = {
id: " ",
shapes: [
{
path: "M335.62 812.62L512 715.53l176.37 97.09-33.82-206.45 147.99-151.03-204.05-31.05-86.5-183.49-86.48 183.5-204.05 31.04 147.98 151.03-33.82 206.45zM512 825.12L266.62 960.18a32 32 0 0 1-43.47-12.6 32 32 0 0 1-3.54-20.6l47.23-288.35L65.42 433.06a32 32 0 0 1 .46-45.25 32 32 0 0 1 17.59-8.78l277.01-42.15L483.05 76.85a32 32 0 0 1 42.6-15.3 32 32 0 0 1 15.3 15.3L663.5 336.88l277.02 42.15a32 32 0 0 1 26.82 36.45 32 32 0 0 1-8.78 17.58L757.15 638.63l47.24 288.35a32 32 0 0 1-26.41 36.75 32 32 0 0 1-20.6-3.54L512 825.12z",
fill: null
}
]
};
export const starOutlineFill = {
id: "starOutlineFill",
shapes: [
{
path: "M511.994 853.936l-189.611 104.372c-41.055 22.598-92.657 7.637-115.255-33.418-9.163-16.646-12.474-35.885-9.402-54.636l37.12-226.602-157.985-161.239c-32.799-33.473-32.251-87.198 1.223-119.995 12.715-12.458 29.025-20.603 46.624-23.28l215.049-32.718 95.483-202.567c19.982-42.39 70.545-60.557 112.935-40.575 17.826 8.403 32.172 22.749 40.575 40.575l95.483 202.567 215.051 32.718c46.33 7.049 78.175 50.321 71.126 96.651-2.678 17.599-10.822 33.909-23.281 46.624l-157.985 161.239 37.12 226.602c7.576 46.247-23.774 89.879-70.021 97.456-18.751 3.071-37.99-0.24-54.636-9.402l-189.611-104.372z",
fill: null,
strokeWidth: 102,
strokeColor: "#333333"
}
]
};
export const star = {
id: "star",
shapes: [
{
path: "M512 825.12L266.62 960.18a32 32 0 0 1-43.47-12.6 32 32 0 0 1-3.54-20.6l47.23-288.35L65.42 433.06a32 32 0 0 1 .46-45.25 32 32 0 0 1 17.59-8.78l277.01-42.15L483.05 76.85a32 32 0 0 1 42.6-15.3 32 32 0 0 1 15.3 15.3L663.5 336.88l277.02 42.15a32 32 0 0 1 26.82 36.45 32 32 0 0 1-8.78 17.58L757.15 638.63l47.24 288.35a32 32 0 0 1-26.41 36.75 32 32 0 0 1-20.6-3.54L512 825.12z",
fill: null
}
]
};
export const key = {
id: "key",
shapes: [
{
path: "M461.76 471.424l300.736-300.672c5.791-5.789 13.789-9.369 22.624-9.369s16.833 3.58 22.624 9.369l45.248 45.248c5.789 5.791 9.369 13.789 9.369 22.624s-3.58 16.833-9.369 22.624l-36.224 36.224 68.736 68.672c5.789 5.791 9.369 13.789 9.369 22.624s-3.58 16.833-9.369 22.624l-45.312 45.312c-5.791 5.789-13.789 9.369-22.624 9.369s-16.833-3.58-22.624-9.369l0 0-68.672-68.736-174.016 174.016c16.763 30.651 26.622 67.148 26.622 105.947 0 123.782-100.346 224.128-224.128 224.128-61.627 0-117.444-24.873-157.962-65.127l0.012 0.012c-40.669-40.558-65.831-96.648-65.831-158.615 0-123.712 100.288-224 224-224 39.139 0 75.933 10.038 107.948 27.679l-1.157-0.584zM423.040 736.384c18.822-17.574 30.555-42.534 30.555-70.235 0-53.019-42.981-96-96-96-27.701 0-52.661 11.732-70.183 30.499l-0.052 0.056c-15.964 17.097-25.765 40.127-25.765 65.445 0 53.019 42.981 96 96 96 25.319 0 48.348-9.801 65.501-25.817l-0.056 0.052z",
fill: null
}
]
};
export const successOutline = {
id: "successOutline",
shapes: [
{
path: "M512 1024c-282.77 0-512-229.23-512-512s229.23-512 512-512v0c282.77 0 512 229.23 512 512s-229.23 512-512 512v0zM512 928c229.75 0 416-186.25 416-416s-186.25-416-416-416v0c-229.75 0-416 186.25-416 416s186.25 416 416 416v0zM417.152 599.296l271.552-271.552c5.791-5.789 13.789-9.369 22.624-9.369s16.833 3.58 22.624 9.369l22.656 22.656c5.789 5.791 9.369 13.789 9.369 22.624s-3.58 16.833-9.369 22.624l-316.8 316.8c-5.791 5.789-13.789 9.369-22.624 9.369s-16.833-3.58-22.624-9.369l-135.744-135.808c-5.789-5.791-9.369-13.789-9.369-22.624s3.58-16.833 9.369-22.624l22.592-22.592c5.791-5.789 13.789-9.369 22.624-9.369s16.833 3.58 22.624 9.369l90.496 90.496z",
fill: null
}
]
};
export const success = {
id: "success",
shapes: [
{
path: "M512 1024c-282.77 0-512-229.23-512-512s229.23-512 512-512v0c282.77 0 512 229.23 512 512s-229.23 512-512 512v0zM417.152 599.296l-90.496-90.496c-5.791-5.789-13.789-9.369-22.624-9.369s-16.833 3.58-22.624 9.369l-22.592 22.592c-5.789 5.791-9.369 13.789-9.369 22.624s3.58 16.833 9.369 22.624l135.68 135.808c5.794 5.808 13.805 9.401 22.656 9.401s16.862-3.593 22.655-9.401l0.001-0.001 316.8-316.8c5.789-5.791 9.369-13.789 9.369-22.624s-3.58-16.833-9.369-22.624l-22.656-22.656c-5.791-5.789-13.789-9.369-22.624-9.369s-16.833 3.58-22.624 9.369l-271.552 271.552z",
fill: null
}
]
};
export const errorOutline = {
id: "errorOutline",
shapes: [
{
path: "M512 1024c-282.77 0-512-229.23-512-512s229.23-512 512-512v0c282.77 0 512 229.23 512 512s-229.23 512-512 512v0zM512 928c229.75 0 416-186.25 416-416s-186.25-416-416-416v0c-229.75 0-416 186.25-416 416s186.25 416 416 416v0zM579.84 512l147.136 147.072c5.789 5.791 9.369 13.789 9.369 22.624s-3.58 16.833-9.369 22.624l-22.656 22.656c-5.791 5.789-13.789 9.369-22.624 9.369s-16.833-3.58-22.624-9.369l-147.072-147.136-147.072 147.072c-5.791 5.789-13.789 9.369-22.624 9.369s-16.833-3.58-22.624-9.369l-22.656-22.656c-5.789-5.791-9.369-13.789-9.369-22.624s3.58-16.833 9.369-22.624l-0 0 147.136-147.008-147.136-147.072c-5.789-5.791-9.369-13.789-9.369-22.624s3.58-16.833 9.369-22.624l22.656-22.656c5.791-5.789 13.789-9.369 22.624-9.369s16.833 3.58 22.624 9.369l147.072 147.136 147.072-147.072c5.791-5.789 13.789-9.369 22.624-9.369s16.833 3.58 22.624 9.369l22.656 22.656c5.789 5.791 9.369 13.789 9.369 22.624s-3.58 16.833-9.369 22.624l0-0-147.136 147.008z",
fill: null
}
]
};
export const error = {
id: "error",
shapes: [
{
path: "M512 1024c-282.77 0-512-229.23-512-512s229.23-512 512-512v0c282.77 0 512 229.23 512 512s-229.23 512-512 512v0zM579.84 512l147.136-147.072c5.789-5.791 9.369-13.789 9.369-22.624s-3.58-16.833-9.369-22.624l-22.656-22.656c-5.791-5.789-13.789-9.369-22.624-9.369s-16.833 3.58-22.624 9.369l-147.072 147.136-147.072-147.136c-5.791-5.789-13.789-9.369-22.624-9.369s-16.833 3.58-22.624 9.369l-22.656 22.656c-5.789 5.791-9.369 13.789-9.369 22.624s3.58 16.833 9.369 22.624l147.136 147.072-147.072 147.072c-5.789 5.791-9.369 13.789-9.369 22.624s3.58 16.833 9.369 22.624l22.656 22.656c5.791 5.789 13.789 9.369 22.624 9.369s16.833-3.58 22.624-9.369l-0 0 147.008-147.136 147.072 147.072c5.791 5.789 13.789 9.369 22.624 9.369s16.833-3.58 22.624-9.369l22.656-22.656c5.789-5.791 9.369-13.789 9.369-22.624s-3.58-16.833-9.369-22.624l0 0-147.136-147.008z",
fill: null
}
]
};
export const selectFavorite = {
id: "selectFavorite",
shapes: [
{
path: "M435.2 422.4l-135.424 71.194 25.856-150.784-109.568-106.803 151.424-22.016L435.2 76.8l67.712 137.19 151.424 22.016-109.568 106.803 25.856 150.784z",
fill: "#CFDAE2",
fillRule: "evenodd"
},
{
path: "M600.269 460.8a44.8 44.8 0 0 0-45.005 44.8v268.8l-30.003-59.725c-24.576-45.414-48.768-40.704-67.533-29.875-21.709 14.413-29.798 29.286-15.002 67.2 34.048 83.226 86.349 182.4 142.541 246.4h202.573c71.168-52.48 128.461-302.131 30.003-313.6-9.037 0-23.501 1.434-30.003 7.475 0-29.875-26.189-37.53-37.53-37.35-12.979.23-22.502 7.475-30.003 22.4 0-29.85-24.474-37.325-37.504-37.325-14.336 0-30.976 8.909-37.53 22.4V505.6c0-24.832-20.07-44.8-45.005-44.8z",
fill: "#93AFCD",
fillRule: "nonzero"
}
]
};
export const locationPin = {
id: "locationPin",
shapes: [
{
path: "M788.058 262.144l-436.525 180.706 139.324 46.441c36.058 12.271 63.926 40.139 75.946 75.349l0.252 0.848 45.116 135.349 175.887-438.694zM578.379 885.218l-97.039-291.177c-3.069-9.005-10.029-15.966-18.822-18.971l-0.212-0.063-292.503-97.461c-12.094-4.096-20.644-15.344-20.644-28.589 0-12.5 7.615-23.221 18.458-27.778l0.198-0.074 717.884-297.201c3.417-1.46 7.392-2.31 11.566-2.31 16.634 0 30.118 13.484 30.118 30.118 0 4.044-0.797 7.902-2.243 11.425l0.073-0.201-290.334 723.968c-4.578 11.158-15.358 18.873-27.94 18.873-13.214 0-24.44-8.51-28.498-20.348l-0.063-0.212z",
fill: null
}
]
};
export const wifi = {
id: "wifi",
shapes: [
{
path: "M391.872 188.16l-78.976-78.848c63.68-19.264 130.624-29.312 199.104-29.312 170.624 0 331.712 62.4 456.704 173.44 9.92 8.835 16.138 21.644 16.138 35.904 0 26.515-21.495 48.010-48.010 48.010-12.254 0-23.437-4.591-31.92-12.148l0.048 0.042c-103.665-92.632-241.225-149.249-392.009-149.249-0.335 0-0.669 0-1.004 0.001l0.053-0c-40.896 0-81.088 4.16-120.128 12.16zM120.32 324.096c-8.694 8.678-20.696 14.045-33.952 14.045-26.543 0-48.061-21.517-48.061-48.061 0-13.288 5.392-25.316 14.108-34.015l0.001-0.001 67.904 67.968zM672.192 468.672l-131.648-131.776c120.567 7.52 227.56 60.148 305.394 141.036l0.142 0.148c8.909 8.722 14.433 20.871 14.433 34.311 0 26.51-21.49 48-48 48-14.076 0-26.738-6.059-35.518-15.712l-0.035-0.039c-29.534-30.644-64.181-56.108-102.61-75.070l-2.158-0.962zM297.28 501.056c-17.997 13.056-33.846 26.773-48.441 41.719l-0.071 0.073c-8.726 8.92-20.885 14.45-34.336 14.45-26.52 0-48.018-21.499-48.018-48.018 0-13.069 5.221-24.919 13.691-33.577l-0.009 0.009c15.296-15.616 31.552-30.080 48.64-43.2l68.544 68.544zM486.144 689.92c-43.776 6.4-83.2 29.12-111.168 63.552-8.863 11.411-22.586 18.684-38.008 18.684-26.51 0-48-21.49-48-48 0-11.866 4.306-22.726 11.44-31.104l-0.056 0.068c28.474-35.043 64.853-62.567 106.494-80.036l1.794-0.668 77.504 77.504zM512 944c-26.51 0-48-21.49-48-48s21.49-48 48-48v0c26.51 0 48 21.49 48 48s-21.49 48-48 48v0zM855.936 923.84l-769.28-769.28c-5.808-5.794-9.401-13.805-9.401-22.656s3.593-16.862 9.401-22.655l0.001-0.001 22.592-22.592c5.791-5.789 13.789-9.369 22.624-9.369s16.833 3.58 22.624 9.369l769.344 769.28c5.789 5.791 9.369 13.789 9.369 22.624s-3.58 16.833-9.369 22.624l-22.656 22.656c-5.791 5.789-13.789 9.369-22.624 9.369s-16.833-3.58-22.624-9.369l0 0z",
fill: null
}
]
};
export const quickDeposit = {
id: "deposit",
shapes: [
{
path: "M816 0c-17.673 0-32 14.327-32 32v0 112h-112c-17.673 0-32 14.327-32 32v0 32c0 17.673 14.327 32 32 32v0h112v112c0 17.673 14.327 32 32 32v0h32c17.673 0 32-14.327 32-32v0-112h112c17.673 0 32-14.327 32-32v0-32c0-17.673-14.327-32-32-32v0h-112v-112c0-17.673-14.327-32-32-32v0h-32zM512 64c-0.415 17.756-14.361 32.125-31.903 33.211l-0.097 0.005c-215.554 17.141-383.982 196.284-383.982 414.766 0 229.75 186.25 416 416 416 218.482 0 397.626-168.428 414.673-382.525l0.093-1.457c1.091-17.639 15.46-31.585 33.176-31.999l0.040-0.001h32c17.664 0 32.128 14.336 31.040 32-17.36 268.64-239.5 479.956-510.996 479.956-282.77 0-512-229.23-512-512 0-271.496 211.316-493.637 478.445-510.918l1.511-0.078c17.664-1.088 32 13.376 32 31.040v32zM496 224c-17.673 0-32 14.327-32 32v0 19.328c-64.64 13.76-114.304 57.088-120.192 124.16-3.2 35.968 4.352 75.776 34.944 107.52 29.44 30.656 73.472 46.592 127.68 51.392 41.92 3.712 59.712 14.784 66.944 22.272 6.144 6.4 9.984 15.808 8.512 32.64-1.472 16.448-19.52 46.4-83.904 40.704-26.88-2.368-47.424-12.608-60.16-24.192-6.592-5.952-16.448-8.448-24-3.84l-54.592 33.344c-7.552 4.608-9.984 14.528-4.608 21.568 25.6 32.96 65.216 55.68 109.376 64.96v22.144c0 17.673 14.327 32 32 32v0h32c17.673 0 32-14.327 32-32v0-22.72c63.36-14.464 111.68-57.472 117.504-123.52 3.2-36.096-4.416-75.84-34.944-107.584-29.44-30.72-73.472-46.592-127.68-51.392-41.92-3.712-59.776-14.848-66.944-22.336-6.144-6.4-9.984-15.744-8.512-32.576 1.472-16.448 19.52-46.464 83.904-40.704 26.88 2.368 47.424 12.608 60.16 24.192 6.592 5.952 16.448 8.448 24 3.84l54.592-33.408c7.552-4.608 9.984-14.528 4.544-21.504-24.96-32.32-63.552-54.784-106.624-64.384v-19.904c0-17.673-14.327-32-32-32v0h-32z",
fill: null
}
]
};
export const deposit = {
id: "deposit",
shapes: [
{
path: "M720 464V320h96v144h144v96H816v144h-96V560H576v-96h144z",
fill: null
},
{
path: "M272.002 159.91c-82.273 11.174-132.442 51.032-160.704 96.251-15.75 25.201-23.46 50.077-27.287 68.45-1.93 9.264-2.926 17.129-3.444 22.921-.259 2.904-.4 5.313-.476 7.145-.038.917-.06 1.692-.073 2.315l-.013.821-.002.323V358.34c0 .03 0 .06 47.999.06h-48v1.854c-.023 26.076-.059 68.265 36.982 107.775 33.78 36.031 93.22 64.369 190.65 90.35 94.57 25.219 131.13 48.081 145.35 63.25 10.014 10.681 11.008 18.583 11.018 43.565l-.005.132a57.112 57.112 0 01-.18 2.605c-.233 2.608-.736 6.743-1.806 11.879-2.172 10.427-6.464 23.951-14.713 37.149-14.611 23.379-46.647 54.24-127.296 54.24-80.648 0-112.684-30.861-127.296-54.24-8.249-13.198-12.54-26.722-14.713-37.149-1.07-5.136-1.573-9.271-1.806-11.879a57.112 57.112 0 01-.18-2.605l-.009-.253.003.162.001.156v.152c0 .028 0 .057-48 .057s-48 .03-48 .06V665.864l.003.323.013.821c.012.623.034 1.398.073 2.315.076 1.832.217 4.241.476 7.145.518 5.792 1.514 13.657 3.444 22.921 3.828 18.373 11.536 43.249 27.287 68.45 28.262 45.219 78.431 85.077 160.704 96.25V960h96v-95.911c82.273-11.173 132.442-51.031 160.704-96.25 15.751-25.201 23.46-50.077 27.287-68.45 1.93-9.264 2.927-17.129 3.444-22.921.259-2.904.4-5.313.477-7.145.038-.917.06-1.692.073-2.315l.012-.821.002-.323.001-.14v-.064c0-.03 0-.06-48-.06h48l.001-1.854c.022-26.076.058-68.265-36.983-107.775-33.779-36.031-93.22-64.369-190.65-90.35-94.57-25.219-131.129-48.081-145.35-63.25-10.014-10.681-11.007-18.583-11.018-43.565l.005-.132c.018-.418.064-1.309.18-2.605.233-2.608.736-6.743 1.806-11.879 2.173-10.427 6.464-23.951 14.713-37.149 14.612-23.379 46.648-54.24 127.296-54.24 80.649 0 112.685 30.861 127.296 54.24 8.249 13.198 12.541 26.722 14.713 37.149 1.07 5.136 1.573 9.271 1.806 11.879.116 1.296.162 2.187.18 2.605.007.174.009.264.009.264v-.011l-.002-.162-.001-.156-.001-.098v-.054c0-.028 0-.057 48-.057s48-.03 48-.06v-.064l-.001-.14-.002-.323-.012-.821a112.71 112.71 0 00-.073-2.315 153.154 153.154 0 00-.477-7.145c-.517-5.792-1.514-13.657-3.444-22.921-3.827-18.373-11.536-43.249-27.287-68.45-28.262-45.219-78.431-85.077-160.704-96.251V64h-96v95.91zm192.004 505.163l-.001.042zM720.002 464V320h96v144h144v96h-144v144h-96V560h-144v-96h144z",
fill: null
}
]
};
export const depositCancel = {
id: "depositCancel",
shapes: [
{
path: "M272.002 159.91c-82.273 11.174-132.442 51.032-160.704 96.251-15.75 25.201-23.46 50.077-27.287 68.45-1.93 9.264-2.926 17.129-3.444 22.921-.259 2.904-.4 5.313-.476 7.145-.038.917-.06 1.692-.073 2.315l-.013.821-.002.323V358.34c0 .03 0 .06 47.999.06h-48v1.854c-.023 26.076-.059 68.265 36.982 107.775 33.78 36.031 93.22 64.369 190.65 90.35 94.57 25.219 131.13 48.081 145.35 63.25 10.014 10.681 11.008 18.583 11.018 43.565l-.005.132a57.112 57.112 0 01-.18 2.605c-.233 2.608-.736 6.743-1.806 11.879-2.172 10.427-6.464 23.951-14.713 37.149-14.611 23.379-46.647 54.24-127.296 54.24-80.648 0-112.684-30.861-127.296-54.24-8.249-13.198-12.54-26.722-14.713-37.149-1.07-5.136-1.573-9.271-1.806-11.879a57.112 57.112 0 01-.18-2.605l-.009-.253.003.162.001.156v.152c0 .028 0 .057-48 .057s-48 .03-48 .06V665.864l.003.323.013.821c.012.623.034 1.398.073 2.315.076 1.832.217 4.241.476 7.145.518 5.792 1.514 13.657 3.444 22.921 3.828 18.373 11.536 43.249 27.287 68.45 28.262 45.219 78.431 85.077 160.704 96.25V960h96v-95.911c82.273-11.173 132.442-51.031 160.704-96.25 15.751-25.201 23.46-50.077 27.287-68.45 1.93-9.264 2.927-17.129 3.444-22.921.259-2.904.4-5.313.477-7.145.038-.917.06-1.692.072-2.315l.013-.821.002-.323.001-.14v-.064c0-.03 0-.06-48-.06h48l.001-1.854c.022-26.076.058-68.265-36.983-107.775-33.779-36.031-93.22-64.369-190.65-90.35-94.57-25.219-131.129-48.081-145.35-63.25-10.014-10.681-11.007-18.583-11.018-43.565l.005-.132c.018-.418.064-1.309.18-2.605.233-2.608.736-6.743 1.806-11.879 2.173-10.427 6.464-23.951 14.713-37.149 14.612-23.379 46.648-54.24 127.296-54.24 80.649 0 112.685 30.861 127.296 54.24 8.249 13.198 12.541 26.722 14.713 37.149 1.07 5.136 1.573 9.271 1.806 11.879.116 1.296.162 2.187.18 2.605.007.174.009.264.009.264v-.011l-.002-.162-.001-.156-.001-.098v-.054c0-.028 0-.057 48-.057s48-.03 48-.06v-.064l-.001-.14-.002-.323-.013-.821a105.17 105.17 0 00-.072-2.315 153.154 153.154 0 00-.477-7.145c-.517-5.792-1.514-13.657-3.444-22.921-3.827-18.373-11.536-43.249-27.287-68.45-28.262-45.219-78.431-85.077-160.704-96.251V64h-96v95.91zm192.004 505.163l-.001.042zM732.121 544L606.062 417.941l67.883-67.882 126.059 126.058 126.058-126.058 67.883 67.882L867.886 544l126.059 126.059-67.883 67.882-126.058-126.059-126.059 126.059-67.883-67.882L732.121 544z",
fill: null
}
]
};
export const settings = {
id: "settings",
shapes: [
{
path: "M473.408 177.92c-11.213 50.947-55.974 88.506-109.508 88.506-22.622 0-43.677-6.707-61.286-18.241l0.427 0.262-29.12-18.816-44.288 44.288 18.816 29.12c11.271 17.182 17.978 38.238 17.978 60.86 0 53.534-37.559 98.295-87.763 109.371l-0.743 0.138-33.92 7.296v62.592l33.92 7.296c50.947 11.213 88.506 55.974 88.506 109.508 0 22.622-6.707 43.677-18.241 61.286l0.262-0.427-18.816 29.12 44.288 44.288 29.12-18.816c17.182-11.271 38.238-17.978 60.86-17.978 53.534 0 98.295 37.559 109.371 87.763l0.138 0.743 7.296 33.92h62.592l7.296-33.92c11.213-50.947 55.974-88.506 109.508-88.506 22.622 0 43.677 6.707 61.286 18.241l-0.427-0.262 29.12 18.816 44.288-44.288-18.816-29.12c-11.271-17.182-17.978-38.238-17.978-60.86 0-53.534 37.559-98.295 87.763-109.371l0.743-0.138 33.92-7.296v-62.592l-33.92-7.296c-50.947-11.213-88.506-55.974-88.506-109.508 0-22.622 6.707-43.677 18.241-61.286l-0.262 0.427 18.816-29.12-44.288-44.288-29.12 18.816c-17.182 11.271-38.238 17.978-60.86 17.978-53.534 0-98.295-37.559-109.371-87.763l-0.138-0.743-7.296-33.92h-62.592l-7.296 33.92zM405.184 114.56c6.41-29.090 31.961-50.538 62.526-50.56l88.578-0c30.567 0.022 56.118 21.47 62.449 50.135l0.079 0.425 9.984 46.592c3.209 14.55 15.995 25.275 31.285 25.275 6.449 0 12.453-1.908 17.477-5.19l-0.123 0.075 40-25.856c9.817-6.439 21.847-10.27 34.772-10.27 17.66 0 33.649 7.153 45.228 18.719l62.655 62.591c11.566 11.579 18.718 27.568 18.718 45.228 0 12.925-3.831 24.955-10.42 35.016l0.15-0.244-25.856 40c-3.207 4.902-5.115 10.905-5.115 17.355 0 15.291 10.725 28.077 25.062 31.246l0.212 0.039 46.592 10.048c29.090 6.41 50.538 31.961 50.56 62.526l0 0.002v88.576c-0.022 30.567-21.47 56.118-50.135 62.449l-0.425 0.079-46.592 9.984c-14.55 3.209-25.275 15.995-25.275 31.285 0 6.449 1.908 12.453 5.19 17.477l-0.075-0.123 25.856 40c6.439 9.817 10.27 21.847 10.27 34.772 0 17.66-7.153 33.649-18.719 45.228l-62.591 62.655c-11.579 11.566-27.568 18.718-45.228 18.718-12.925 0-24.955-3.831-35.016-10.42l0.244 0.15-40-25.856c-4.902-3.207-10.905-5.115-17.355-5.115-15.291 0-28.077 10.725-31.246 25.062l-0.039 0.212-10.048 46.592c-6.41 29.090-31.961 50.538-62.526 50.56l-88.578 0c-30.567-0.022-56.118-21.47-62.449-50.135l-0.079-0.425-9.984-46.592c-3.209-14.55-15.995-25.275-31.285-25.275-6.449 0-12.453 1.908-17.477 5.19l0.123-0.075-40 25.856c-9.817 6.439-21.847 10.27-34.772 10.27-17.66 0-33.649-7.153-45.228-18.719l-62.655-62.591c-11.566-11.579-18.718-27.568-18.718-45.228 0-12.925 3.831-24.955 10.42-35.016l-0.15 0.244 25.856-40c3.207-4.902 5.115-10.905 5.115-17.355 0-15.291-10.725-28.077-25.062-31.246l-0.212-0.039-46.592-10.048c-29.090-6.41-50.538-31.961-50.56-62.526l-0-0.002v-88.576c0.022-30.567 21.47-56.118 50.135-62.449l0.425-0.079 46.592-9.984c14.55-3.209 25.275-15.995 25.275-31.285 0-6.449-1.908-12.453-5.19-17.477l0.075 0.123-25.856-40c-6.439-9.817-10.27-21.847-10.27-34.772 0-17.66 7.153-33.649 18.719-45.228l62.591-62.655c11.579-11.566 27.568-18.718 45.228-18.718 12.925 0 24.955 3.831 35.016 10.42l-0.244-0.15 40 25.856c4.902 3.207 10.905 5.115 17.355 5.115 15.291 0 28.077-10.725 31.246-25.062l0.039-0.212 10.048-46.592zM512 624c-61.856 0-112-50.144-112-112s50.144-112 112-112v0c61.856 0 112 50.144 112 112s-50.144 112-112 112v0zM512 704c106.039 0 192-85.961 192-192s-85.961-192-192-192v0c-106.039 0-192 85.961-192 192s85.961 192 192 192v0z",
fill: null
}
]
};
export const refresh = {
id: "refresh",
shapes: [
{
path: "M96 96c0-17.673 14.327-32 32-32v0h256c17.673 0 32 14.327 32 32v0 256c0 17.673-14.327 32-32 32v0h-32c-17.673 0-32-14.327-32-32v0-135.040c-96.959 63.749-160.086 172.043-160.086 295.082 0 183.168 139.905 333.66 318.684 350.444l1.403 0.106c17.6 1.536 32 15.744 32 33.408v32c0.003 0.166 0.005 0.362 0.005 0.558 0 16.754-13.582 30.336-30.336 30.336-0.587 0-1.17-0.017-1.749-0.050l0.080 0.004c-233.258-17.218-415.984-210.697-415.984-446.855 0-142.366 66.406-269.222 169.934-351.282l0.93-0.711h-106.88c-17.673 0-32-14.327-32-32v0-32zM864 512c0-0.015 0-0.032 0-0.050 0-183.138-139.858-333.61-318.595-350.436l-1.405-0.107c-17.636-1.249-31.531-15.633-31.999-33.363l-0.001-0.045v-32c0-17.664 14.4-32.128 32-30.848 233.258 17.218 415.984 210.697 415.984 446.855 0 142.366-66.406 269.222-169.934 351.282l-0.93 0.711h106.88c17.673 0 32 14.327 32 32v0 32c0 17.673-14.327 32-32 32v0h-256c-17.673 0-32-14.327-32-32v0-256c0-17.673 14.327-32 32-32v0h32c17.673 0 32 14.327 32 32v0 135.040c96.907-63.714 160-171.95 160-294.921 0-0.042-0-0.084-0-0.126l0 0.007z",
fill: null
}
]
};
export const timer = {
id: "timer",
shapes: [
{
path: "M160 576c0 194.404 157.596 352 352 352s352-157.596 352-352v0c0-194.404-157.596-352-352-352s-352 157.596-352 352v0zM417.6 137.984c-1.014-2.98-1.599-6.414-1.6-9.984l-0-0v-32c0-17.673 14.327-32 32-32v0h128c17.673 0 32 14.327 32 32v0 32c-0.001 3.57-0.586 7.004-1.666 10.21l0.066-0.226c203.751 44.882 353.948 223.909 353.948 438.016 0 247.424-200.576 448-448 448-0.122 0-0.245-0-0.367-0l0.019 0c-0.103 0-0.225 0-0.348 0-247.424 0-448-200.576-448-448 0-214.107 150.197-393.134 350.975-437.465l2.972-0.551zM736.576 38.4l110.848 64c9.632 5.636 15.999 15.931 15.999 27.712 0 5.891-1.592 11.41-4.369 16.151l0.082-0.151-16 27.776c-5.636 9.632-15.931 15.999-27.712 15.999-5.891 0-11.41-1.592-16.151-4.369l0.151 0.082-110.848-64c-9.632-5.636-15.999-15.931-15.999-27.712 0-5.891 1.592-11.41 4.369-16.151l-0.082 0.151 16-27.776c5.636-9.632 15.931-15.999 27.712-15.999 5.891 0 11.41 1.592 16.151 4.369l-0.151-0.082zM176.576 102.4l110.848-64c4.59-2.695 10.109-4.287 16-4.287 11.782 0 22.076 6.367 27.631 15.848l0.082 0.151 16 27.776c2.695 4.59 4.287 10.109 4.287 16 0 11.782-6.367 22.076-15.848 27.631l-0.151 0.082-110.848 64c-4.59 2.695-10.109 4.287-16 4.287-11.782 0-22.076-6.367-27.631-15.848l-0.082-0.151-16-27.776c-2.695-4.59-4.287-10.109-4.287-16 0-11.782 6.367-22.076 15.848-27.631l0.151-0.082zM496 320h32c17.673 0 32 14.327 32 32v0 256c0 17.673-14.327 32-32 32v0h-32c-17.673 0-32-14.327-32-32v0-256c0-17.673 14.327-32 32-32v0z",
fill: null
}
]
};
export const overload = {
id: "overload",
shapes: [
{
path: "M496 704h32c17.673 0 32 14.327 32 32v0 192c0 17.673-14.327 32-32 32v0h-32c-17.673 0-32-14.327-32-32v0-192c0-17.673 14.327-32 32-32v0zM496 64h32c17.673 0 32 14.327 32 32v0 192c0 17.673-14.327 32-32 32v0h-32c-17.673 0-32-14.327-32-32v0-192c0-17.673 14.327-32 32-32v0zM364.928 636.48l22.592 22.592c5.789 5.791 9.369 13.789 9.369 22.624s-3.58 16.833-9.369 22.624l-135.68 135.808c-5.794 5.808-13.805 9.401-22.656 9.401s-16.862-3.593-22.655-9.401l-0.001-0.001-22.656-22.656c-5.789-5.791-9.369-13.789-9.369-22.624s3.58-16.833 9.369-22.624l135.808-135.744c5.791-5.789 13.789-9.369 22.624-9.369s16.833 3.58 22.624 9.369l-0-0zM817.472 183.872l22.656 22.656c5.789 5.791 9.369 13.789 9.369 22.624s-3.58 16.833-9.369 22.624l-135.808 135.744c-5.791 5.789-13.789 9.369-22.624 9.369s-16.833-3.58-22.624-9.369l-22.592-22.592c-5.789-5.791-9.369-13.789-9.369-22.624s3.58-16.833 9.369-22.624l135.68-135.808c5.794-5.808 13.805-9.401 22.656-9.401s16.862 3.593 22.655 9.401l0.001 0.001zM320 496v32c0 17.673-14.327 32-32 32v0h-192c-17.673 0-32-14.327-32-32v0-32c0-17.673 14.327-32 32-32v0h192c17.673 0 32 14.327 32 32v0zM960 496v32c0 17.673-14.327 32-32 32v0h-192c-17.673 0-32-14.327-32-32v0-32c0-17.673 14.327-32 32-32v0h192c17.673 0 32 14.327 32 32v0zM387.52 364.928l-22.592 22.592c-5.791 5.789-13.789 9.369-22.624 9.369s-16.833-3.58-22.624-9.369l-135.808-135.68c-5.808-5.794-9.401-13.805-9.401-22.656s3.593-16.862 9.401-22.655l0.001-0.001 22.656-22.656c5.791-5.789 13.789-9.369 22.624-9.369s16.833 3.58 22.624 9.369l135.744 135.808c5.789 5.791 9.369 13.789 9.369 22.624s-3.58 16.833-9.369 22.624l0-0zM840.128 817.472l-22.656 22.656c-5.791 5.789-13.789 9.369-22.624 9.369s-16.833-3.58-22.624-9.369l-135.744-135.808c-5.789-5.791-9.369-13.789-9.369-22.624s3.58-16.833 9.369-22.624l22.592-22.592c5.791-5.789 13.789-9.369 22.624-9.369s16.833 3.58 22.624 9.369l135.808 135.68c5.808 5.794 9.401 13.805 9.401 22.656s-3.593 16.862-9.401 22.655l-0.001 0.001z",
fill: null
}
]
};
export const filters = {
id: "filters",
shapes: [
{
path: "M336 848c70.692 0 128-57.308 128-128 0-70.692-57.308-128-128-128-70.692 0-127.952 57.308-127.952 128 0 70.692 57.26 128 127.952 128zM624 432c70.692 0 128-57.308 128-128 0-70.692-57.308-128-128-128-70.692 0-128 57.308-128 128 0 70.692 57.308 128 128 128z",
fill: null,
fillOpacity: 0.1
},
{
path: "M624 224c-44.183 0-80 35.817-80 80s35.817 80 80 80 80-35.817 80-80-35.817-80-80-80zm-169.375 32C475.519 182.128 543.438 128 624 128s148.481 54.128 169.375 128H960v96H793.375C772.481 425.872 704.562 480 624 480s-148.481-54.128-169.375-128H64v-96h390.625zM336 640c-44.159 0-79.952 35.794-79.952 80s35.793 80 79.952 80c44.183 0 80-35.817 80-80s-35.817-80-80-80zm-169.33 32c20.88-73.86 88.752-128 169.33-128 80.562 0 148.481 54.128 169.375 128H960v96H505.375C484.481 841.872 416.562 896 336 896c-80.578 0-148.45-54.14-169.33-128H64v-96h102.67z",
fill: null,
fillRule: "evenodd"
}
]
};
export const funnel = {
id: "funnel",
shapes: [
{
path: "M864 800v128c0 17.673-14.327 32-32 32v0h-32c-17.673 0-32-14.327-32-32v0-128h-64c-17.673 0-32-14.327-32-32v0-32c0-17.673 14.327-32 32-32v0h224c17.673 0 32 14.327 32 32v0 32c0 17.673-14.327 32-32 32v0h-64zM560 288h64c17.673 0 32 14.327 32 32v0 32c0 17.673-14.327 32-32 32v0h-224c-17.673 0-32-14.327-32-32v0-32c0-17.673 14.327-32 32-32v0h64v-192c0-17.673 14.327-32 32-32v0h32c17.673 0 32 14.327 32 32v0 192zM256 608v320c0 17.673-14.327 32-32 32v0h-32c-17.673 0-32-14.327-32-32v0-320h-64c-17.673 0-32-14.327-32-32v0-32c0-17.673 14.327-32 32-32v0h224c17.673 0 32 14.327 32 32v0 32c0 17.673-14.327 32-32 32v0h-64zM192 64h32c17.673 0 32 14.327 32 32v0 288c0 17.673-14.327 32-32 32v0h-32c-17.673 0-32-14.327-32-32v0-288c0-17.673 14.327-32 32-32v0zM496 480h32c17.673 0 32 14.327 32 32v0 416c0 17.673-14.327 32-32 32v0h-32c-17.673 0-32-14.327-32-32v0-416c0-17.673 14.327-32 32-32v0zM800 64h32c17.673 0 32 14.327 32 32v0 480c0 17.673-14.327 32-32 32v0h-32c-17.673 0-32-14.327-32-32v0-480c0-17.673 14.327-32 32-32v0z",
fill: null
}
]
};
export const edit = {
id: "edit",
shapes: [
{
path: "M868.864 312.704l-135.68-135.808-90.368 90.624 136.064 135.68 89.984-90.496zM574.912 335.552l-314.24 314.048-11.328 147.072 147.008-11.328 314.496-314.048-135.936-135.68zM439.104 878.336l-256.832 19.84c-0.739 0.061-1.599 0.095-2.468 0.095-17.673 0-32-14.327-32-32 0-0.89 0.036-1.771 0.107-2.642l-0.008 0.114 19.84-256.896 542.72-543.104c5.791-5.789 13.789-9.369 22.624-9.369s16.833 3.58 22.624 9.369l226.24 226.304c5.789 5.791 9.369 13.789 9.369 22.624s-3.58 16.833-9.369 22.624l-542.912 543.040z",
fill: null
}
]
};
export const liveVideo = {
id: "liveVideo",
shapes: [
{
path: "M160 224v576h704v-576h-704zM96 128h832c17.673 0 32 14.327 32 32v0 704c0 17.673-14.327 32-32 32v0h-832c-17.673 0-32-14.327-32-32v0-704c0-17.673 14.327-32 32-32v0zM426.88 680.768c-2.37 1.465-5.244 2.333-8.32 2.333-8.837 0-16-7.163-16-16 0-0.010 0-0.021 0-0.031l-0 0.002v-309.76c-0-0.009-0-0.019-0-0.029 0-8.837 7.163-16 16-16 3.076 0 5.95 0.868 8.389 2.373l-0.069-0.040 256.448 154.88c4.663 2.852 7.728 7.916 7.728 13.696s-3.065 10.844-7.658 13.656l-0.070 0.040-256.512 154.88z",
fill: null
}
]
};
export const liveVideo20 = {
id: "liveVideo20",
shapes: [
{
path: "M550.4 806.4v76.8h320c14.138 0 25.6 11.462 25.6 25.6v0 25.6c0 14.138-11.462 25.6-25.6 25.6v0h-716.8c-14.138 0-25.6-11.462-25.6-25.6v0-25.6c0-14.138 11.462-25.6 25.6-25.6v0h320v-76.8h-384c-14.138 0-25.6-11.462-25.6-25.6v0-691.2c0-14.138 11.462-25.6 25.6-25.6v0h844.8c14.138 0 25.6 11.462 25.6 25.6v0 691.2c0 14.138-11.462 25.6-25.6 25.6v0h-384zM140.8 140.8v588.8h742.4v-588.8h-742.4zM667.392 457.165l-244.634 146.79c-3.757 2.287-8.299 3.641-13.158 3.641-14.138 0-25.6-11.462-25.6-25.6 0-0.020 0-0.040 0-0.060l-0 0.003v-293.478c-0-0.002-0-0.003-0-0.005 0-14.138 11.462-25.6 25.6-25.6 4.859 0 9.402 1.354 13.272 3.705l-0.114-0.064 244.634 146.79c7.509 4.553 12.451 12.682 12.451 21.965s-4.941 17.412-12.337 21.901l-0.114 0.064z",
fill: null
}
]
};
export const withdraw = {
id: "withdraw",
shapes: [
{
path: "M272.002 159.91c-82.273 11.174-132.442 51.032-160.704 96.251-15.75 25.201-23.46 50.077-27.287 68.45-1.93 9.264-2.926 17.129-3.444 22.921-.259 2.904-.4 5.313-.476 7.145-.038.917-.06 1.692-.073 2.315l-.013.821-.002.323V358.34c0 .03 0 .06 47.999.06h-48v1.854c-.023 26.076-.059 68.265 36.982 107.775 33.78 36.031 93.22 64.369 190.65 90.35 94.57 25.219 131.13 48.081 145.35 63.25 10.014 10.681 11.008 18.583 11.018 43.565l-.005.132a57.112 57.112 0 01-.18 2.605c-.232 2.608-.736 6.743-1.806 11.879-2.172 10.427-6.464 23.951-14.713 37.149-14.611 23.379-46.647 54.24-127.296 54.24-80.648 0-112.684-30.861-127.296-54.24-8.249-13.198-12.54-26.722-14.713-37.149-1.07-5.136-1.573-9.271-1.806-11.879a57.112 57.112 0 01-.18-2.605l-.009-.253.003.162.001.156v.152c0 .028 0 .057-48 .057s-48 .03-48 .06V665.864l.003.323.013.821c.012.623.034 1.398.073 2.315.076 1.832.217 4.241.476 7.145.518 5.792 1.514 13.657 3.444 22.921 3.828 18.373 11.536 43.249 27.287 68.45 28.262 45.219 78.431 85.077 160.704 96.25V960h96v-95.911c82.273-11.173 132.442-51.031 160.704-96.25 15.751-25.201 23.46-50.077 27.287-68.45 1.93-9.264 2.927-17.129 3.444-22.921.259-2.904.4-5.313.477-7.145.038-.917.06-1.692.073-2.315l.012-.821.002-.323.001-.14v-.064c0-.03 0-.06-48-.06h48l.001-1.854c.022-26.076.058-68.265-36.983-107.775-33.779-36.031-93.22-64.369-190.65-90.35-94.57-25.219-131.129-48.081-145.35-63.25-10.014-10.681-11.007-18.583-11.018-43.565l.005-.132c.018-.418.064-1.309.18-2.605.233-2.608.736-6.743 1.806-11.879 2.173-10.427 6.464-23.951 14.713-37.149 14.612-23.379 46.648-54.24 127.296-54.24 80.649 0 112.685 30.861 127.296 54.24 8.249 13.198 12.541 26.722 14.713 37.149 1.07 5.136 1.574 9.271 1.806 11.879.116 1.296.162 2.187.18 2.605.007.174.009.264.009.264v-.011l-.002-.162-.001-.156-.001-.098v-.054c0-.028 0-.057 48-.057s48-.03 48-.06v-.064l-.001-.14-.002-.323-.012-.821a112.71 112.71 0 00-.073-2.315 153.154 153.154 0 00-.477-7.145c-.517-5.792-1.514-13.657-3.444-22.921-3.827-18.373-11.536-43.249-27.287-68.45-28.262-45.219-78.431-85.077-160.704-96.251V64h-96v95.91zm192.004 505.163l-.001.042zm255.996-124.955V320h96v220.118l78.059-78.059 67.882 67.882-160 160c-18.745 18.745-49.137 18.745-67.882 0l-160-160 67.882-67.882 78.059 78.059z",
fill: null
}
]
};
export const circleWithdraw = {
id: "circleWithdraw",
shapes: [
{
path: "M462.985 592.481L352.593 482.089C340.096 469.592 319.835 469.592 307.338 482.089L284.711 504.716C272.214 517.213 272.214 537.474 284.711 549.971L488.357 753.618C494.606 759.866 502.795 762.991 510.985 762.991C519.174 762.991 527.364 759.866 533.612 753.618L737.259 549.971C749.756 537.474 749.756 517.213 737.259 504.716L714.631 482.089C702.135 469.592 681.873 469.592 669.377 482.089L558.985 592.481V288C558.985 270.327 544.658 256 526.985 256H494.985C477.312 256 462.985 270.327 462.985 288L462.985 592.481ZM512 1024C794.77 1024 1024 794.77 1024 512C1024 229.23 794.77 0 512 0C229.23 0 0 229.23 0 512C0 794.77 229.23 1024 512 1024ZM512 928C282.25 928 96 741.75 96 512C96 282.25 282.25 96 512 96C741.75 96 928 282.25 928 512C928 741.75 741.75 928 512 928Z",
fill: null
}
]
};
export const phone = {
id: "phone",
shapes: [
{
path: "M835.52 721.216l-136.64-45.568-32.32 32.32c-14.475 14.464-34.466 23.409-56.546 23.409-17.444 0-33.584-5.583-46.73-15.060l0.237 0.162-62.464-44.608c-60.692-43.708-112.281-95.318-154.607-154.048l-1.361-1.984-44.608-62.4c-9.314-12.91-14.897-29.050-14.897-46.494 0-22.080 8.945-42.072 23.41-56.547l32.319-32.319-45.568-136.64-116.544 58.24c6.144 167.424 65.472 306.496 178.56 419.52 113.024 113.088 252.096 172.416 419.456 178.56l58.24-116.544zM637.952 600.768c14.479-14.486 34.485-23.446 56.583-23.446 9.064 0 17.777 1.508 25.9 4.285l-0.563-0.167 163.456 54.528c32.064 10.914 54.719 40.761 54.719 75.9 0 13.042-3.121 25.356-8.657 36.234l0.21-0.454-71.040 142.208c-13.434 26.408-40.409 44.185-71.535 44.185-0.704 0-1.405-0.009-2.104-0.027l0.103 0.002c-196.224-4.672-362.176-73.856-495.104-206.912-133.056-132.992-202.24-298.88-206.976-495.168-0.014-0.567-0.023-1.236-0.023-1.906 0-31.151 17.804-58.143 43.792-71.356l0.455-0.21 142.208-71.104c10.429-5.332 22.748-8.456 35.798-8.456 35.119 0 64.952 22.629 75.715 54.101l0.167 0.563 54.528 163.52c9.6 28.8 2.048 60.48-19.328 81.92l-29.696 29.632 36.672 51.456c37.47 52.002 81.712 96.204 132.056 132.465l1.704 1.167 51.392 36.736 29.632-29.696z",
fill: null
}
]
};
export const phone24 = {
id: "phone24",
shapes: [
{
path: "M857.844 711.859l-163.508-54.503-39.272 39.272c-22.122 22.122-56.996 25.009-82.454 6.824l-62.437-44.598c-58.818-42.013-110.276-93.471-152.289-152.289l-44.598-62.437c-18.184-25.458-15.298-60.332 6.824-82.454l39.272-39.272-54.503-163.508-142.208 71.104c4.209 175.967 65.229 322.246 183.525 440.543s264.575 179.316 440.542 183.526l71.104-142.208zM300.943 715.796c-130.081-130.081-197.655-292.072-202.253-484.269-0.592-24.786 13.185-47.684 35.36-58.772l142.208-71.104c31.615-15.807 70.058-2.993 85.865 28.622 1.354 2.709 2.515 5.51 3.472 8.383l54.503 163.508c7.666 22.997 1.68 48.352-15.461 65.493l-39.272 39.272 44.598 62.437c37.908 53.071 84.338 99.501 137.409 137.409l62.437 44.598 39.272-39.272c17.141-17.141 42.496-23.127 65.493-15.461l163.508 54.503c33.532 11.177 51.655 47.422 40.477 80.954-0.958 2.873-2.118 5.674-3.472 8.383l-71.104 142.208c-11.088 22.176-33.987 35.953-58.774 35.36-192.195-4.598-354.186-72.172-484.267-202.253z",
fill: null
}
]
};
export const email = {
id: "email",
shapes: [
{
path: "M96 192h832c17.673 0 32 14.327 32 32v0 576c0 17.673-14.327 32-32 32v0h-832c-17.673 0-32-14.327-32-32v0-576c0-17.673 14.327-32 32-32v0zM864 477.44l-320.448 137.28c-9.285 4.082-20.109 6.457-31.488 6.457s-22.203-2.376-32.003-6.658l0.515 0.201-320.768-137.28v258.56h704.192v-258.56zM159.872 288v84.864l352.128 150.912 352-150.848v-84.928h-704.128z",
fill: null
}
]
};
export const emptyFile = {
id: "emptyFile",
shapes: [
{
path: "M620.337 251.89l-226.331-226.331c-16.365-16.365-38.165-25.386-61.353-25.386h-236.277c-47.822 0-86.739 38.917-86.739 86.739v809.562c0 47.822 38.917 86.739 86.739 86.739h462.607c47.822 0 86.739-38.917 86.739-86.739v-583.232c0-23.188-9.021-44.989-25.386-61.353zM575.927 289.303h-190.421c-15.96 0-28.913-12.953-28.913-28.913v-190.421l219.334 219.334zM558.984 925.388h-462.607c-15.96 0-28.913-12.953-28.913-28.913v-809.562c0-15.96 12.953-28.913 28.913-28.913h202.391v202.391c0 47.822 38.917 86.739 86.739 86.739h202.391v549.346c0 15.96-12.953 28.913-28.913 28.913z",
fill: null
}
]
};
export const crossedFile = {
id: "crossedFile",
shapes: [
{
path: "M3.5 2H10.5V5H13.5V13H3.5V2Z",
fill: "#ffffff",
fillOpacity: 0.1
},
{
path: "M0.969727 1.53033L14.9697 15.5303L16.0304 14.4697L14.5 12.9393V5.5C14.5 5.30109 14.421 5.11032 14.2803 4.96967L10.7803 1.46967C10.6397 1.32902 10.4489 1.25 10.25 1.25H2.81072L2.03039 0.469666L0.969727 1.53033ZM4.31072 2.75H9.5V5.5C9.5 5.91421 9.83579 6.25 10.25 6.25H13V11.4393L4.31072 2.75ZM11 4.75V3.81066L11.9393 4.75H11ZM4 12.5V5.25H2.5V12.5C2.5 13.4665 3.2835 14.25 4.25 14.25H11.5V12.75H4.25C4.11193 12.75 4 12.6381 4 12.5Z",
fill: null
}
]
};
export const email24 = {
id: "email24",
shapes: [
{
path: "M896 400.424v-144.424h-768v144.424l384 141.474 384-141.474zM896 468.629l-361.875 133.322c-14.281 5.261-29.969 5.261-44.25 0l-361.875-133.322v299.371h768v-299.371zM96 192h832c17.673 0 32 14.327 32 32v576c0 17.673-14.327 32-32 32h-832c-17.673 0-32-14.327-32-32v-576c0-17.673 14.327-32 32-32z",
fill: null
}
]
};
export const facebook = {
id: "facebook",
shapes: [
{
path: "M383.030 411.733v-70.4c0-112.905 102.002-202.667 225.939-202.667h116.364c17.673 0 32 14.327 32 32v136.533c0 17.673-14.327 32-32 32h-116.364c-4.595 0-6.788 1.93-6.788 2.133v70.4h123.152c21.24 0 36.586 20.313 30.782 40.745l-38.788 136.533c-3.909 13.761-16.477 23.255-30.782 23.255h-84.364v241.067c0 17.673-14.327 32-32 32h-155.152c-17.673 0-32-14.327-32-32v-241.067h-84.364c-17.673 0-32-14.327-32-32v-136.533c0-17.673 14.327-32 32-32h84.364zM693.333 202.667h-84.364c-90.282 0-161.939 63.058-161.939 138.667v102.4c0 17.673-14.327 32-32 32h-84.364v72.533h84.364c17.673 0 32 14.327 32 32v241.067h91.152v-241.067c0-17.673 14.327-32 32-32h92.188l20.606-72.533h-112.794c-17.673 0-32-14.327-32-32v-102.4c0-37.499 32.538-66.133 70.788-66.133h84.364v-72.533z",
fill: null
}
]
};
export const twitter = {
id: "twitter",
shapes: [
{
path: "M878.14 187.123c24.389-16.405 56.138 5.991 48.865 34.47-11.97 46.87-35.958 90-69.635 125.55 0.522 5.409 0.793 10.855 0.812 16.332 0 394.048-396.999 595.547-745.162 411.1-30.060-15.925-17.8-61.543 16.193-60.254 60.255 2.285 119.876-9.295 173.925-33.377-77.324-45.053-126.807-104.937-151.062-176.017-24.959-73.144-21.314-150.050-0.492-223.051 6.295-22.070 12.69-38.691 17.23-48.43 10.264-22.023 40.363-25.022 54.771-5.458 59.391 80.645 153.949 130.805 256.418 137.199-1.074-76.647 47.731-145.204 121.663-172.113 66.69-24.273 141.355-10.14 193.352 35.279 29.516-10.118 57.479-23.983 83.121-41.23zM795.217 295.364c-11.693 3.357-24.278-0.205-32.475-9.194-34.266-37.571-89.983-50.865-139.187-32.956-48.689 17.721-80.244 62.047-79.555 111.26v33.289c0 17.365-13.849 31.561-31.209 31.99-114.783 2.838-224.461-41.146-302.608-119.433-14.889 58.208-16.475 118.441 2.463 173.939 23.726 69.53 78.227 126.169 172.204 165.999 23.632 10.016 26.448 42.38 4.902 56.326-40.036 25.915-84.002 45.143-130.036 57.182 271.699 70.821 534.466-100.186 534.466-400.179-0.025-7.197-0.751-14.377-2.169-21.451-2.172-10.837 1.402-22.029 9.454-29.601 9.062-8.522 17.345-17.685 24.791-27.388-10.189 3.794-20.544 7.204-31.040 10.218z",
fill: null
}
]
};
export const pause = {
id: "pause",
shapes: [
{
path: "M304 192h128c17.673 0 32 14.327 32 32v0 576c0 17.673-14.327 32-32 32v0h-128c-17.673 0-32-14.327-32-32v0-576c0-17.673 14.327-32 32-32v0zM592 192h128c17.673 0 32 14.327 32 32v0 576c0 17.673-14.327 32-32 32v0h-128c-17.673 0-32-14.327-32-32v0-576c0-17.673 14.327-32 32-32v0z",
fill: null
}
]
};
export const play = {
id: "play",
shapes: [
{
path: "M315.84 849.152c-4.711 2.882-10.412 4.589-16.512 4.589-17.666 0-31.989-14.316-32-31.98l-0-0.001v-619.52c0.011-17.665 14.334-31.981 32-31.981 6.1 0 11.801 1.707 16.653 4.669l-0.141-0.080 512.96 309.76c9.297 5.709 15.404 15.821 15.404 27.36s-6.107 21.651-15.265 27.281l-0.139 0.079-512.96 309.824z",
fill: null
}
]
};
export const fullscreenExit = {
id: "fullscreenExit",
shapes: [
{
path: "M659.392 271.552l198.208-198.208c5.794-5.808 13.805-9.401 22.656-9.401s16.862 3.593 22.655 9.401l22.593 22.657c5.789 5.791 9.369 13.789 9.369 22.624s-3.58 16.833-9.369 22.624l-197.504 197.504h123.52c17.673 0 32 14.327 32 32v0 32c0 17.673-14.327 32-32 32v0h-256c-17.673 0-32-14.327-32-32v0-256c0-17.673 14.327-32 32-32v0h32c17.673 0 32 14.327 32 32v0 124.8zM339.392 725.952l-198.144 198.208c-5.791 5.789-13.789 9.369-22.624 9.369s-16.833-3.58-22.624-9.369l0 0-22.656-22.592c-5.789-5.791-9.369-13.789-9.369-22.624s3.58-16.833 9.369-22.624l197.504-197.504h-123.456c-17.673 0-32-14.327-32-32v0-32c0-17.673 14.327-32 32-32v0h256c17.673 0 32 14.327 32 32v0 256c0 17.673-14.327 32-32 32v0h-32c-17.673 0-32-14.327-32-32v0-124.8z",
fill: null
}
]
};
export const fullscreen = {
id: "fullscreen",
shapes: [
{
path: "M64 928v-256c0-17.673 14.327-32 32-32v0h32c17.673 0 32 14.327 32 32v0 123.456l167.040-167.104c5.794-5.808 13.805-9.401 22.656-9.401s16.862 3.593 22.655 9.401l0.001 0.001 22.656 22.656c5.789 5.791 9.369 13.789 9.369 22.624s-3.58 16.833-9.369 22.624l-167.808 167.744h124.8c17.673 0 32 14.327 32 32v0 32c0 17.673-14.327 32-32 32v0h-256c-17.673 0-32-14.327-32-32v0zM960 96v256c0 17.673-14.327 32-32 32v0h-32c-17.673 0-32-14.327-32-32v0-123.456l-167.040 167.104c-5.794 5.808-13.805 9.401-22.656 9.401s-16.862-3.593-22.655-9.401l-0.001-0.001-22.656-22.656c-5.789-5.791-9.369-13.789-9.369-22.624s3.58-16.833 9.369-22.624l167.808-167.744h-124.8c-17.673 0-32-14.327-32-32v0-32c0-17.673 14.327-32 32-32v0h256c17.673 0 32 14.327 32 32v0z",
fill: null
}
]
};
export const replay = {
id: "replay",
shapes: [
{
path: "M512 928c229.75 0 416-186.25 416-416v0c0-17.28 13.504-32 30.848-32h34.112c16.896 0 30.976 13.184 31.040 30.080 0 284.672-229.248 513.92-512 513.92-282.744-0.034-511.94-229.251-511.94-512 0-282.77 229.23-512 512-512 170.696 0 321.883 83.532 414.912 211.95l1.028 1.49v-117.44c0-17.673 14.327-32 32-32v0h32c17.673 0 32 14.327 32 32v0 256c0 17.673-14.327 32-32 32v0h-256c-17.673 0-32-14.327-32-32v0-32c0-17.673 14.327-32 32-32v0h126.592c-75.083-116.186-203.959-192-350.542-192-229.75 0-416 186.25-416 416 0 229.733 186.221 415.972 415.948 416l0.003 0zM426.88 680.768c-2.37 1.465-5.244 2.333-8.32 2.333-8.837 0-16-7.163-16-16 0-0.010 0-0.021 0-0.031l-0 0.002v-309.76c-0-0.009-0-0.019-0-0.029 0-8.837 7.163-16 16-16 3.076 0 5.95 0.868 8.389 2.373l-0.069-0.040 256.448 154.88c4.663 2.852 7.728 7.916 7.728 13.696s-3.065 10.844-7.658 13.656l-0.070 0.040-256.512 154.88z",
fill: null
}
]
};
export const soundMute = {
id: "soundMute",
shapes: [
{
path: "M330.88 380.928c-17.567 17.57-40.217 30.057-65.555 35.066l-0.813 0.134-104.512 20.096v157.312l98.816 13.888c28.614 4.152 53.613 17.236 72.639 36.287l0.001 0.001 84.544 84.48v-432.384l-85.12 85.12zM851.392 527.488l79.232 79.232c5.789 5.791 9.369 13.789 9.369 22.624s-3.58 16.833-9.369 22.624l-22.656 22.656c-5.791 5.789-13.789 9.369-22.624 9.369s-16.833-3.58-22.624-9.369l0 0-79.168-79.232-79.232 79.232c-5.791 5.789-13.789 9.369-22.624 9.369s-16.833-3.58-22.624-9.369l0 0-22.592-22.656c-5.789-5.791-9.369-13.789-9.369-22.624s3.58-16.833 9.369-22.624l79.168-79.168-79.168-79.232c-5.789-5.791-9.369-13.789-9.369-22.624s3.58-16.833 9.369-22.624l22.592-22.592c5.791-5.789 13.789-9.369 22.624-9.369s16.833 3.58 22.624 9.369l79.232 79.168 79.168-79.168c5.791-5.789 13.789-9.369 22.624-9.369s16.833 3.58 22.624 9.369l-0-0 22.656 22.592c5.789 5.791 9.369 13.789 9.369 22.624s-3.58 16.833-9.369 22.624l-79.232 79.232zM89.984 352l156.352-30.080c6.553-1.267 12.233-4.38 16.641-8.769l-0.001 0.001 194.368-194.432c5.794-5.808 13.805-9.401 22.656-9.401 17.648 0 31.96 14.287 32 31.925l0 0.004v741.504c-0.004 17.67-14.329 31.993-32 31.993-8.851 0-16.862-3.593-22.655-9.401l-0.001-0.001-193.792-193.792c-4.766-4.748-11.021-8.003-18.005-9.004l-0.171-0.020-153.856-21.76c-15.618-2.27-27.484-15.552-27.52-31.612l-0-0.004v-265.792c0.035-15.517 11.108-28.437 25.781-31.327l0.203-0.033z",
fill: null
}
]
};
export const soundPlay = {
id: "soundPlay",
shapes: [
{
path: "M416 295.744l-85.12 85.184c-17.567 17.57-40.217 30.057-65.555 35.066l-0.813 0.134-104.512 20.096v157.312l98.816 13.888c28.614 4.152 53.613 17.236 72.639 36.287l0.001 0.001 84.544 84.48v-432.384zM89.984 352l156.352-30.080c6.553-1.267 12.233-4.38 16.641-8.769l-0.001 0.001 194.368-194.432c5.794-5.808 13.805-9.401 22.656-9.401 17.648 0 31.96 14.287 32 31.925l0 0.004v741.504c-0.004 17.67-14.329 31.993-32 31.993-8.851 0-16.862-3.593-22.655-9.401l-0.001-0.001-193.792-193.792c-4.766-4.748-11.021-8.003-18.005-9.004l-0.171-0.020-153.856-21.76c-15.618-2.27-27.484-15.552-27.52-31.612l-0-0.004v-265.792c0.035-15.517 11.108-28.437 25.781-31.327l0.203-0.033zM702.4 696.704c-8.561 13.959-23.737 23.13-41.055 23.13-26.51 0-48-21.49-48-48 0-8.563 2.242-16.602 6.171-23.562l-0.124 0.24c23.012-38.952 36.609-85.835 36.609-135.894 0-0.217-0-0.435-0.001-0.652l0 0.034c0-49.152-12.992-96.256-37.376-137.6-4.169-6.969-6.634-15.372-6.634-24.352 0-26.515 21.495-48.010 48.010-48.010 17.536 0 32.876 9.401 41.255 23.439l0.121 0.22c32.96 56 50.624 119.936 50.624 186.304 0 65.728-17.28 129.024-49.6 184.64zM854.208 816.32c-8.689 13.261-23.48 21.898-40.288 21.898-26.515 0-48.010-21.495-48.010-48.010 0-9.707 2.881-18.741 7.834-26.294l-0.112 0.182c46.622-70.905 74.369-157.833 74.369-251.241 0-0.301-0-0.602-0.001-0.902l0 0.047c0-91.008-26.24-177.984-74.688-252.544-5.183-7.551-8.278-16.888-8.278-26.947 0-26.51 21.49-48 48-48 17.097 0 32.106 8.939 40.609 22.398l0.116 0.197c56.568 85.783 90.241 191.008 90.241 304.098 0 0.281-0 0.561-0.001 0.841l0-0.043c0 109.44-31.488 214.4-89.792 304.256z",
fill: null
}
]
};
export const video = {
id: "video",
shapes: [
{
path: "M96 512c0 229.75 186.25 416 416 416v0c229.75 0 416-186.25 416-416s-186.25-416-416-416v0c-229.75 0-416 186.25-416 416v0zM0 512c0-282.77 229.23-512 512-512s512 229.23 512 512v0c0 282.77-229.23 512-512 512s-512-229.23-512-512v0zM426.88 680.768c-2.37 1.465-5.244 2.333-8.32 2.333-8.837 0-16-7.163-16-16 0-0.010 0-0.021 0-0.031l-0 0.002v-309.76c-0-0.009-0-0.019-0-0.029 0-8.837 7.163-16 16-16 3.076 0 5.95 0.868 8.389 2.373l-0.069-0.040 256.448 154.88c4.663 2.852 7.728 7.916 7.728 13.696s-3.065 10.844-7.658 13.656l-0.070 0.040-256.512 154.88z",
fill: null
}
]
};
export const noVideo = {
id: "noVideo",
shapes: [
{
path: "M612.736 680.64l84.672-51.136 140.8 140.8c56.008-70.237 89.869-160.291 89.869-258.253 0-229.75-186.25-416-416-416-97.962 0-188.015 33.861-259.095 90.517l0.841-0.648 88.96 88.96c-22.291 20.529-36.211 49.854-36.224 82.43l-0 0.002v17.152l-120.704-120.704c-56.008 70.237-89.869 160.291-89.869 258.253 0 229.75 186.25 416 416 416 97.962 0 188.015-33.861 259.095-90.517l-0.841 0.648-157.44-157.504zM117.632 185.472l-30.976-30.976c-5.789-5.791-9.369-13.789-9.369-22.624s3.58-16.833 9.369-22.624l22.592-22.592c5.791-5.789 13.789-9.369 22.624-9.369s16.833 3.58 22.624 9.369l30.976 30.976c87.919-73.212 202.044-117.652 326.548-117.652 282.77 0 512 229.23 512 512 0 124.504-44.44 238.628-118.322 327.376l0.671-0.829 17.472 17.408c5.789 5.791 9.369 13.789 9.369 22.624s-3.58 16.833-9.369 22.624l-22.656 22.656c-5.791 5.789-13.789 9.369-22.624 9.369s-16.833-3.58-22.624-9.369l-17.408-17.408c-87.919 73.212-202.044 117.652-326.548 117.652-282.77 0-512-229.23-512-512 0-124.504 44.44-238.628 118.322-327.376l-0.671 0.829zM426.816 680.832c-2.355 1.441-5.206 2.295-8.256 2.295-8.837 0-16-7.163-16-16 0-0.019 0-0.038 0-0.058l-0 0.003v-309.76c-0-0.009-0-0.019-0-0.029 0-8.837 7.163-16 16-16 3.076 0 5.95 0.868 8.389 2.373l-0.069-0.040 256.448 154.88c4.663 2.852 7.728 7.916 7.728 13.696s-3.065 10.844-7.658 13.656l-0.070 0.040-256.512 154.88z",
fill: null
}
]
};
export const promo = {
id: "promo",
shapes: [
{
path: "M848.477 80c61.856 0 112 50.144 112 112v264.321a176.004 176.004 0 01-56.007 128.755L526.649 937.183c-44.129 41.125-112.901 39.914-155.555-2.739L106.429 669.779c-42.623-42.624-43.867-111.337-2.813-155.475l351.743-378.17A175.996 175.996 0 01584.231 80h264.246zm0 96H584.231a79.998 79.998 0 00-58.578 25.515L173.909 579.686c-5.864 6.305-5.687 16.121.402 22.21l264.666 264.666c6.093 6.093 15.918 6.266 22.222.391l377.82-352.107a80 80 0 0025.458-58.525V192c0-8.837-7.163-16-16-16zm-134.852 80c44.183 0 80 35.817 80 80s-35.817 80-80 80-80-35.817-80-80 35.817-80 80-80z",
fill: null
}
]
};
export const promosolid = {
id: "promosolid",
shapes: [
{
path: "M864.45 192a16 16 0 0 0-16-16H584.21a80 80 0 0 0-58.58 25.52L173.88 579.67a16 16 0 0 0 .4 22.22l264.67 264.66a16 16 0 0 0 22.22.4L839 514.84a80 80 0 0 0 25.46-58.53V192z",
fill: color("yellow", "500")
},
{
path: "M864.45 192a16 16 0 0 0-16-16H584.21a80 80 0 0 0-58.58 25.52L173.88 579.67a16 16 0 0 0 .4 22.22l264.67 264.66a16 16 0 0 0 22.22.4L839 514.84a80 80 0 0 0 25.46-58.53V192zm96 0v264.32a176 176 0 0 1-56 128.76l-377.83 352.1c-44.12 41.13-112.9 39.92-155.55-2.74L106.4 669.78c-42.62-42.62-43.86-111.34-2.81-155.47l351.74-378.18A176 176 0 0 1 584.21 80h264.24c61.86 0 112 50.14 112 112zM713.6 416a80 80 0 1 1 0-160 80 80 0 0 1 0 160z",
fill: "#333333"
}
]
};
export const tvgChannel1 = {
id: "tvgChannel1",
shapes: [
{
path: "M205.89 538.614c208.401-281.889 514.177-332.53 517.236-333.001l5.14-0.813 6.861 31.387-5.288 1.136c-314.754 67.555-494.055 318.753-495.83 321.285l-3.23 4.592-28.005-20.367 3.117-4.22zM650.663 356.751l-0.685 5.427c-0.045 0.373-4.559 38.417 16.388 60.759 10.703 11.411 26.419 16.829 46.956 16.412l5.496-0.13 0.617 28.645-4.996 0.507c-0.378 0.045-2.707 0.256-6.424 0.256-12.352 0-39.902-2.46-61.033-22.306-20.059-18.836-28.735-48.046-25.798-86.818l0.405-5.382 29.073 2.631zM818.133 510.882l-23.712-18.544 36.64-50.134-151.143-161.839 21.19-21.624 169.292 181.011-52.267 71.129zM451.417 266.996v29.812h-263.861l8.324-29.812h255.537zM275.817 402.479v30.274h-126.156l8.428-30.274h117.728zM354.076 334.92v29.861h-185.472l8.324-29.861h177.148zM762.375 672.779c-36.468 0-63.425 14.602-73.157 51.828-8.876 34.029 8.629 51.976 53.032 51.976 29.217 0 46.244-9.234 56.219-23.087h-36.873l10.915-41.783h127.471l-27.47 105.2h-38.471l-5.716-17.055c-27.596 16.822-58.537 23.28-109.971 23.28-62.813 0-145.129-12.669-122.912-97.751 3.727-14.27 9.488-26.576 16.762-37.204l-104.592 128.73h-94.069l-40.024-137.883h-78.139l-35.991 137.883h-89.626l36.004-137.883h-87.614l12.153-46.568 328.225-0.018 18.999 118.335h0.626l80.799-118.335 146.678-0.009c21.277-4.525 43.265-6.22 63.826-6.22 99.749 0 141.312 22.253 135.925 69.641h-101.086c-0.050-9.539-5.167-15.472-12.59-18.719-7.71-3.332-17.608-4.359-29.334-4.359z",
fill: null
}
]
};
export const tvgChannel2 = {
id: "tvgChannel2",
shapes: [
{
path: "M205.89 538.614c208.401-281.889 514.177-332.53 517.236-333.001l5.14-0.813 6.861 31.387-5.288 1.136c-314.754 67.555-494.055 318.753-495.83 321.285l-3.23 4.592-28.005-20.367 3.117-4.22zM650.663 356.751l-0.685 5.427c-0.045 0.373-4.559 38.417 16.388 60.759 10.703 11.411 26.419 16.829 46.956 16.412l5.496-0.13 0.617 28.645-4.996 0.507c-0.378 0.045-2.707 0.256-6.424 0.256-12.352 0-39.902-2.46-61.033-22.306-20.059-18.836-28.735-48.046-25.798-86.818l0.405-5.382 29.073 2.631zM818.133 510.882l-23.712-18.544 36.64-50.134-151.143-161.839 21.19-21.624 169.292 181.011-52.267 71.129zM451.417 266.996v29.812h-263.861l8.324-29.812h255.537zM275.817 402.479v30.274h-126.156l8.428-30.274h117.728zM354.076 334.92v29.861h-185.472l8.324-29.861h177.148zM682.746 676.672c-7.719-3.332-17.631-4.358-29.382-4.358-36.544 0-63.556 14.598-73.308 51.835-8.886 34.028 8.647 51.975 53.14 51.975 29.267 0 46.341-9.232 56.332-23.086h-36.95l10.937-41.787h127.713l-27.516 105.204h-38.542l-5.73-17.053c-27.649 16.817-58.649 23.278-110.188 23.278-62.937 0-145.414-12.669-123.15-97.752 3.731-14.274 9.505-26.584 16.791-37.21l-104.786 128.737h-94.264l-40.089-137.891h-78.295l-36.066 137.891h-89.799l36.066-137.891h-87.783l12.184-46.566 328.858-0.018 19.673 118.33 80.957-118.33 146.962-0.018c21.318-4.515 43.352-6.216 63.945-6.216 99.949 0 141.586 22.253 136.192 69.651h-101.284c-0.044-9.548-5.181-15.475-12.617-18.728zM983.054 817.668h-210.363l0.899-5.543c3.288-20.227 16.361-36.922 42.401-54.095 18.566-12.253 40.052-21.73 59.014-30.096 29.521-13.019 55.030-24.276 58.859-40.291 0.551-2.317 0.155-4.212-1.247-5.954-3.017-3.781-10.25-6.213-18.43-6.213-25.924 0-34.946 16.609-37.944 30.546l-0.822 3.791h-73.431l1.489-5.945c12.928-51.53 54.392-77.653 123.24-77.653 38.098 0 66.44 9.171 79.794 25.827 8.297 10.348 10.724 23.147 7.223 38.042-7.591 32.135-41.434 46.236-74.176 59.886l-5.869 2.451c-8.355 3.523-16.767 6.806-24.783 9.936-2.156 0.842-4.284 1.666-6.382 2.489h92.935l-12.406 52.822z",
fill: null
}
]
};
export const security = {
id: "security",
shapes: [
{
path: "M860.16 643.072c0 112.64-207.258 237.568-348.16 295.526-255.181-103.424-348.16-232.858-348.16-295.526v-442.982c199.68-6.554 299.008-55.91 347.75-96.256 47.514 39.936 147.046 89.702 348.57 96.256v442.368zM905.216 139.264c-323.174 0-377.856-109.158-378.266-110.182-2.458-5.325-8.192-8.806-14.95-9.011-6.554 0-12.288 3.686-15.155 8.806-0.41 1.229-56.32 110.592-378.266 110.592-9.216 0-16.384 6.144-16.384 14.336v488.653c0 200.090 386.662 352.87 403.046 359.219 2.048 1.024 4.096 1.229 6.554 1.229 2.048 0 4.506 0 6.554-1.229 16.384-6.144 403.046-159.13 403.046-359.424v-488.653c0-7.782-7.168-14.336-16.384-14.336z",
fill: null
},
{
path: "M690.995 445.235c6.758-6.758 10.24-15.77 10.24-25.395s-3.482-18.432-10.24-25.395c-13.926-13.926-36.454-13.926-50.381 0l-154.010 163.84-72.704-77.005c-6.144-6.758-15.36-10.24-24.986-10.24-9.421 0-18.432 3.482-25.19 10.24s-10.24 15.77-10.24 25.395 3.482 18.432 10.24 25.395l97.69 107.725c6.758 6.758 15.77 10.24 25.19 10.24 9.626 0 18.432-3.482 25.19-10.24l179.405-194.56z",
fill: "#38ab50"
}
]
};
export const devices = {
id: "devices",
shapes: [
{
path: "M441.049 711.86h-357.359c-8.317 0-15.071-6.496-15.071-15.071v-586.591c0-8.317 6.762-15.588 15.071-15.588h856.626c8.317 0 15.071 7.279 15.071 15.588v128.394c25.211 2.599 48.596 11.175 68.613 24.69v-153.344c0-46.782-37.687-84.47-83.687-84.47h-856.626c-46.262 0.26-83.687 38.206-83.687 84.728v586.591c0 46.782 37.421 84.47 83.687 84.47h287.187v113.316h-45.228c-28.595 0-51.462 23.395-51.462 51.98s22.87 51.98 51.462 51.98h144.243c-18.188-25.995-28.595-57.179-28.595-90.964v-195.445z",
fill: null
},
{
path: "M729.006 945.77v-74.591h-150.744v-477.693c0-10.397 7.797-18.188 18.188-18.188h340.467c10.397 0 18.188 7.797 18.188 18.188v148.144h25.995c15.588 0 30.148 4.413 42.879 11.694v-159.838c0-48.079-38.985-87.328-86.811-87.328h-340.992c-47.82 0-86.545 38.985-86.545 87.062v514.598c0 48.079 38.985 87.328 86.811 87.328h148.144c-9.362-13.515-15.588-32.488-15.588-49.381z",
fill: "#38ab50"
},
{
path: "M897.938 968.381c-4.679 0-9.095-2.080-12.22-5.198-3.637-3.119-5.977-7.797-5.977-12.996 0-10.397 7.797-18.188 18.188-18.188 9.879 0 18.188 7.797 18.188 18.188 0 5.198-2.599 9.879-5.977 12.996s-7.797 5.198-12.22 5.198zM823.347 911.467v-274.969h149.181v274.718h-149.181zM981.112 584.77h-166.335c-23.395 0-42.879 19.492-42.879 43.405v317.596c0 24.171 19.232 43.663 42.879 43.663h166.335c23.395 0 42.879-19.492 42.879-43.405v-317.855c0-23.912-19.232-43.145-42.879-43.145z",
fill: null
}
]
};
export const tickets = {
id: "tickets",
shapes: [
{
path: "M237.158 241.664h57.344v29.082c0 13.926 0 28.262 28.672 28.262 28.262 0 28.262-14.336 28.262-28.262v-28.672h114.278v28.672c0 13.926 0 28.262 28.672 28.262s28.672-14.336 28.672-28.262v-28.672h114.278v28.672c0 13.926 0 28.262 28.672 28.262s28.672-14.336 28.672-28.262v-28.672h114.074v28.672c0 13.926 0 28.262 28.262 28.262 28.672 0 28.672-14.336 28.672-28.262v-28.672h57.344v685.67h-57.344v-28.672s0-28.672-28.672-28.672-27.853 28.672-27.853 28.672l-0.614 28.672h-114.688v-28.672s0-28.672-28.672-28.672c-28.262 0-27.648 28.672-27.648 28.672v28.672h-115.098l-0.614-28.672s0.614-28.672-28.262-28.672c-28.672 0-28.262 28.672-28.262 28.672v28.672h-114.278v-28.672s0-28.672-28.672-28.672-28.672 28.672-28.672 28.672v28.672h-56.115v-686.080zM494.387 356.352c-27.853 0-57.344 0-86.016-28.672-28.262 28.672-56.934 28.672-85.402 28.672h-28.672v457.114h28.672c28.672 0 57.344 0 85.606 28.672 28.672-28.672 57.344-28.672 85.402-28.672 28.262 0 57.344 0 86.016 28.672 28.672-28.672 57.958-28.672 86.016-28.672 27.648 0 56.934 0 85.606 28.672 28.672-28.672 57.754-28.672 85.606-28.672h28.672v-457.114h-28.672c-28.672 0-57.344 0-85.606-28.672-28.672 28.672-57.344 28.672-85.402 28.672-28.262 0-57.344 0-86.016-28.672-28.672 28.672-57.958 28.672-86.016 28.672z",
fill: null
},
{
path: "M493.978 756.326l314.778 0.819v-57.958l-315.187-0.819zM351.437 584.909h457.523v-57.344h-457.728zM351.437 470.63h457.523v-57.344h-457.728z",
fill: "#38ab50"
},
{
path: "M788.48 222.003v-140.083h-57.344v28.672c0 14.336 0 28.672-28.672 28.672s-28.672-14.336-28.672-28.672v-28.672h-114.074v28.672c0 14.336 0 28.672-28.672 28.672s-28.672-14.336-28.672-28.672v-28.672h-114.278v28.672c0 14.336 0 28.672-28.672 28.672s-28.672-14.336-28.672-28.672v-28.672h-113.664v28.672c0 14.336 0 28.672-28.672 28.672s-28.672-14.336-28.672-28.672v-28.672h-57.344v686.080h57.344v-28.672s0-28.672 28.672-28.672c2.867 0 5.734 0.41 8.192 1.024v-58.368h-36.864v-456.704h28.672c28.262 0 56.934 0 85.402-28.672 28.672 28.672 57.958 28.672 86.016 28.672 27.648 0 56.934 0 85.402-28.672 28.672 28.672 57.958 28.672 86.016 28.672 28.672 0 56.934 0 85.606-28.672 28.672 28.672 57.344 28.672 85.606 28.672h28.672v25.805h57.344z",
fill: null
}
]
};
export const replays = {
id: "replays",
shapes: [
{
path: "M512 869.581c197.427 0 357.581-160.154 357.581-357.581s-160.154-357.581-357.581-357.581-357.581 160.154-357.581 357.581 160.154 357.581 357.581 357.581zM512 921.6c-226.304 0-409.6-183.296-409.6-409.6s183.296-409.6 409.6-409.6 409.6 183.296 409.6 409.6-183.296 409.6-409.6 409.6z",
fill: null
},
{
path: "M414.106 658.637l242.688-146.637-242.688-146.637z",
fill: "#38ab50"
}
]
};
export const talentShape = {
id: "talentShape",
shapes: [
{
path: "M850.455 758.809c4.907-1.397 9.988-2.811 15.242-4.243 5.6-1.526 11.050-2.977 16.348-4.354l0 0c16.916-4.394 34.229 5.598 38.887 22.444l38.216 138.268c4.708 17.028-5.274 34.651-22.3 39.367-5.568 1.558-11.139 3.101-16.71 4.644-5.163 1.43-9.883 2.734-14.161 3.912l-0.001-0.002c-17.025 4.687-34.627-5.304-39.333-22.323l-38.27-138.408c-4.685-16.942 5.174-34.492 22.081-39.304zM512.147 479.825c-114.875 0-208-93.086-208-207.913s93.125-207.913 208-207.913c114.875 0 208 93.086 208 207.913s-93.125 207.913-208 207.913zM512.147 383.866c61.856 0 112-50.123 112-111.953s-50.144-111.953-112-111.953c-61.856 0-112 50.123-112 111.953s50 .144 111.953 112 111.953zM268.739 623.648c0.306-0.105 0.611-0.22 0.914-0.344-0.099 0.041-0.197 0.081-0.295 0.122l-0.618 0.222zM233.038 679.146c-2.891 10.4-27.655 96.308-74.293 257.725-4.535 15.697-20.168 25.456-36.262 22.638-7.854-1.375-15.4-2.878-22.64-4.508-3.452-0.777-6.842-1.502-10.172-2.175-17.323-3.501-28.528-20.382-25.027-37.705 0.081-0.399 0.169-0.797 0.265-1.193 37.957-156.723 59.287-243.547 63.991-260.471 15.75-56.661 32.557-97.728 85.478-119.51 9.645-3.955 38.753-5.993 49.182-5.993h316.781c17.673 0 32 14.327 32 32 0 5.327 0 10.653 0 15.98s0 10.653 0 15.98c0 17.673-14.327 32-32 32l-298.971-0.006c-9.727 0-18.927 4.424-25 12.022-11.569 14.472-19.346 28.878-23.332 43.218zM497.629 834.366l322.069-321.933c9.362-9.358 24.54-9.358 33.902 0l33.902 33.888c9.362 9.358 9.362 24.53 0 33.888l-372.921 372.765c-9.362 9.358-24.54 9.358-33.902 0l-169.51-169.439c-9.362-9.358-9.362-24.53 0-33.888l33.902-33.888c9.362-9.358 24.54-9.358 33.902 0l118.657 118.607z",
fill: null
}
]
};
export const talent = {
id: "talent",
shapes: [
{
path: "M850.455 758.809c4.907-1.397 9.988-2.811 15.242-4.243 5.6-1.526 11.050-2.977 16.348-4.354l0 0c16.916-4.394 34.229 5.598 38.887 22.444l38.216 138.268c4.708 17.028-5.274 34.651-22.3 39.367-5.568 1.558-11.139 3.101-16.71 4.644-5.163 1.43-9.883 2.734-14.161 3.912l-0.001-0.002c-17.025 4.687-34.627-5.304-39.333-22.323l-38.27-138.408c-4.685-16.942 5.174-34.492 22.081-39.304zM512.147 479.825c-114.875 0-208-93.086-208-207.913s93.125-207.913 208-207.913c114.875 0 208 93.086 208 207.913s-93.125 207.913-208 207.913zM512.147 383.866c61.856 0 112-50.123 112-111.953s-50.144-111.953-112-111.953c-61.856 0-112 50.123-112 111.953s50.144 111.953 112 111.953zM268.739 623.648c0.306-0.105 0.611-0.22 0.914-0.344-0.099 0.041-0.197 0.081-0.295 0.122l-0.618 0.222zM233.038 679.146c-2.891 10.4-27.655 96.308-74.293 257.725-4.535 15.697-20.168 25.456-36.262 22.638-7.854-1.375-15.4-2.878-22.64-4.508-3.452-0.777-6.842-1.502-10.172-2.175-17.323-3.501-28.528-20.382-25.027-37.705 0.081-0.399 0.169-0.797 0.265-1.193 37.957-156.723 59.287-243.547 63.991-260.471 15.75-56.661 32.557-97.728 85.478-119.51 9.645-3.955 38.753-5.993 49.182-5.993h316.781c17.673 0 32 14.327 32 32 0 5.327 0 10.653 0 15.98s0 10.653 0 15.98c0 17.673-14.327 32-32 32l-298.971-0.006c-9.727 0-18.927 4.424-25 12.022-11.569 14.472-19.346 28.878-23.332 43.218zM497.629 834.366l322.069-321.933c9.362-9.358 24.54-9.358 33.902 0l33.902 33.888c9.362 9.358 9.362 24.53 0 33.888l-372.921 372.765c-9.362 9.358-24.54 9.358-33.902 0l-169.51-169.439c-9.362-9.358-9.362-24.53 0-33.888l33.902-33.888c9.362-9.358 24.54-9.358 33.902 0l118.657 118.607z",
fill: null
}
]
};
export const talent20 = {
id: "talent20",
shapes: [
{
path: "M852.567 724.24l9.44-2.388 14.055-3.652c13.457-3.497 27.245 4.387 31.057 17.758l51.687 181.296c3.864 13.553-3.953 27.68-17.489 31.606l-15.558 4.512-11.665 2.629c-13.36 3.011-26.724-5.026-30.327-18.239l-49.62-181.969c-3.72-13.64 4.323-27.714 17.963-31.433 0.152-0.041 0.304-0.081 0.456-0.12zM512 479.825c-114.875 0-208-93.086-208-207.913s93.125-207.913 208-207.913c114.875 0 208 93.086 208 207.913s-93.125 207.913-208 207.913zM512 403.178c72.526 0 131.32-58.769 131.32-131.265s-58.794-131.265-131.32-131.265c-72.526 0-131.32 58.769-131.32 131.265s58.794 131.265 131.32 131.265zM268.592 623.648c0.306-0.105 0.611-0.22 0.914-0.344-0.099 0.041-0.197 0.081-0.295 0.122l-0.618 0.222zM205.249 676.322c-2.915 10.488-25.779 98.040-68.59 262.657l-0.005-0.001c-3.427 13.178-16.573 21.366-29.912 18.631-4.271-0.876-8.838-1.861-13.702-2.956-3.177-0.715-6.184-1.39-9.020-2.023l0.001-0.003c-13.797-3.083-22.482-16.766-19.399-30.563 0.033-0.147 0.067-0.295 0.103-0.441 39.211-161.949 61.21-251.534 65.997-268.754 15.75-56.661 21.606-97.728 74.527-119.51 9.645-3.955 49.704-5.993 60.133-5.993h384.644c14.138 0 25.6 11.462 25.6 25.6 0 3.293 0 6.586 0 9.879 0 5.168 0 10.335 0 15.503 0 14.125-11.441 25.581-25.566 25.6l-399.515 0.526c-9.985 0.013-19.052 5.83-23.225 14.901-10.508 22.837-17.864 41.82-22.070 56.95zM497.994 859.491l340.634-340.956c7.489-7.486 19.632-7.486 27.122 0l27.122 27.11c7.489 7.486 7.489 19.624 0 27.11l-381.317 381.621c-7.489 7.486-19.632 7.486-27.122 0l-176.393-176.517c-7.489-7.486-7.489-19.624 0-27.11l27.122-27.11c7.489-7.486 19.632-7.486 27.122 0l135.711 135.852z",
fill: null
}
]
};
export const videoReplay = {
id: "talentShape",
shapes: [
{
path: "M160 160v704h704v-704h-704zM96 64h832c17.673 0 32 14.327 32 32v832c0 17.673-14.327 32-32 32h-832c-17.673 0-32-14.327-32-32v-832c0-17.673 14.327-32 32-32zM64 560v-96h896v96h-896zM254.773 70.639h96v882.723h-96v-882.723zM673.605 70.639h96v882.723h-96v-882.723zM79.693 359.926v-96h240.307v96h-240.307zM79.693 760.22v-96h240.307v96h-240.307zM704 359.926v-96h240.307v96h-240.307zM704 760.22v-96h240.307v96h-240.307z",
fill: null
}
]
};
export const noVideoReplay = {
id: "talent",
shapes: [
{
path: "M259.545 758.278h-99.585v105.768h99.585v-105.768zM259.545 662.278v-103.941h-99.585v103.941h99.585zM260.231 463.040l93.16 95.439v305.568h309.531l96.882 96-663.843-0.232c-17.673 0-32-14.327-32-32l-0-658.968 96 95.823v97.668l100.27-0v0.702zM767.077 262.938h96.883v-102.892h-95.669l-1.214 102.892zM765.944 358.938l-1.22 103.399 99.237-0v-103.399h-98.016zM763.598 557.699l-0.008 0.639-90.166-89.43v-308.861h-311.686l-96.882-96 663.104-0c17.673 0 32 14.327 32 32l0 660.892-96-97.012v-101.589h-100.362v-0.639zM987.064 963.195l-23.903 23.891c-12.496 12.494-32.755 12.494-45.251 0l-871.544-871.38c-12.498-12.496-12.5-32.757-0.004-45.255 0.001-0.001 0.003-0.003 0.004-0.004l23.907-23.888c12.496-12.494 32.755-12.494 45.251 0l871.544 871.38c12.498 12.496 12.5 32.757 0.004 45.255-0.001 0.001-0.003 0.003-0.004 0.004l-0.004-0.004z",
fill: null
}
]
};
export const trackMasterPick = {
id: "talent",
shapes: [
{
path: "M461.972 391.25h-87.25l-52.5 302.75h-72l52.5-302.75h-86l10.75-61.25h245.25l-10.75 61.25zM579.778 330l21.25 261.75 111.75-261.75h94.5l-63.25 364h-72l17.5-100.75 31.5-143.75-111.5 244.5h-48.75l-27.5-252.75-20.75 156.75-16.5 96h-71.75l63-364h92.5zM544.366 893.805c250.524 0 448.341-175.105 448.341-383.414s-197.816-383.414-448.341-383.414c-250.524 0-448.341 175.105-448.341 383.414s197.816 383.414 448.341 383.414zM512.137 958.543c-282.845 0-512.137-199.924-512.137-446.543s229.291-446.543 512.137-446.543c282.845 0 512.137 199.924 512.137 446.543s-229.291 446.543-512.137 446.543z",
fill: null
}
]
};
export const medal = {
id: "medal",
shapes: [
{
path: "M512 864.226c106.039 0 192-85.961 192-192s-85.961-192-192-192c-106.039 0-192 85.961-192 192s85.961 192 192 192zM593.321 329.666c-26.104-6.173-53.331-9.44-81.321-9.44-8.141 0-16.218 0.276-24.222 0.82l137.024-240.864c8.739-15.361 28.276-20.73 43.637-11.991l27.814 15.823c15.361 8.739 20.73 28.276 11.991 43.637l-114.923 202.015zM369.185 350.403c-29.585 13.148-57.020 30.256-81.633 50.651l-155.534-273.403c-8.739-15.361-3.37-34.898 11.991-43.637l27.814-15.823c15.361-8.739 34.898-3.37 43.637 11.991l153.724 270.221zM736.325 400.953c-24.621-20.383-52.064-37.479-81.654-50.613l153.688-270.157c8.739-15.361 28.276-20.73 43.637-11.991l27.814 15.823c15.361 8.739 20.73 28.276 11.991 43.637l-155.477 273.301zM512 960.226c-159.058 0-288-128.942-288-288s128.942-288 288-288c159.058 0 288 128.942 288 288s-128.942 288-288 288zM496 544.226c-17.673 0-32 14.327-32 32v192c0 17.673 14.327 32 32 32h32c17.673 0 32-14.327 32-32v-192c0-17.673-14.327-32-32-32h-32zM355.845 68.684c0.031-0.017 0.061-0.035 0.092-0.052 15.39-8.688 34.909-3.255 43.597 12.135l76.096 134.797-55.17 94.214-104.176-181.645c-0.019-0.032-0.037-0.065-0.055-0.097-8.739-15.361-3.37-34.898 11.991-43.637l27.625-15.715z",
fill: null
}
]
};
export const fileDownload = {
id: "fileDownload",
shapes: [
{
path: "M800 590a32 32 0 0132 32v188.2l55.4-55.5a32 32 0 0145.3 0l22.6 22.7a32 32 0 010 45.2L818 960a48 48 0 01-67.8 0L612.7 822.6a32 32 0 010-45.2l22.6-22.7a32 32 0 0145.3 0l55.4 55.5V622a32 32 0 0132-32zM560 64c12.7 0 25 5 34 14l224 224c9 9 14 21.3 14 34v144a32 32 0 01-32 32h-32a32 32 0 01-32-32v-96H560a48 48 0 01-48-48V160H176a16 16 0 00-16 16v672a16 16 0 0016 16h240a32 32 0 0132 32v32a32 32 0 01-32 32H176A112 112 0 0164 848V176A112 112 0 01176 64zm48 163.9V288h60.1L608 227.9z",
fill: null
}
]
};
export const pdf = {
id: "pdf",
shapes: [
{
path: "M176 112v799.897l671.839-1.437v-632.293l-153.294-166.167h-518.544zM128 80c0-8.837 7.163-16 16-16h564.561c4.467 0 8.731 1.868 11.76 5.151l171.278 185.661c2.726 2.955 4.24 6.828 4.24 10.849v676.731c0 8.823-7.143 15.981-15.966 16l-735.839 1.573c-8.871 0-16.034-7.163-16.034-16v-863.966zM77.962 439.79h672c8.837 0 16 7.163 16 16v288c0 8.837-7.163 16-16 16h-672c-8.837 0-16-7.163-16-16v-288c0-8.837 7.163-16 16-16zM176.587 695.79h37v-69.125h24.125c16.75 0 29.542-0.875 38.375-2.625 6.5-1.417 12.896-4.312 19.188-8.687s11.479-10.396 15.562-18.063c4.083-7.667 6.125-17.125 6.125-28.375 0-14.583-3.542-26.479-10.625-35.688s-15.875-15.187-26.375-17.938c-6.833-1.833-21.5-2.75-44-2.75h-59.375v183.25zM213.587 543.54h17.875c13.333 0 22.208 0.417 26.625 1.25 6 1.083 10.958 3.792 14.875 8.125s5.875 9.833 5.875 16.5c0 5.417-1.396 10.167-4.188 14.25s-6.646 7.083-11.562 9c-4.917 1.917-14.667 2.875-29.25 2.875h-20.25v-52zM347.212 512.54v183.25h69.625c13.667 0 24.583-1.292 32.75-3.875 10.917-3.5 19.583-8.375 26-14.625 8.5-8.25 15.042-19.042 19.625-32.375 3.75-10.917 5.625-23.917 5.625-39 0-17.167-2-31.604-6-43.312s-9.833-21.604-17.5-29.688c-7.667-8.083-16.875-13.708-27.625-16.875-8-2.333-19.625-3.5-34.875-3.5h-67.625zM384.212 543.54h16.625c15.083 0 25.208 0.583 30.375 1.75 6.917 1.5 12.625 4.375 17.125 8.625s8 10.167 10.5 17.75c2.5 7.583 3.75 18.458 3.75 32.625s-1.25 25.354-3.75 33.563c-2.5 8.208-5.729 14.104-9.688 17.688s-8.937 6.125-14.937 7.625c-4.583 1.167-12.042 1.75-22.375 1.75h-27.625v-121.375zM532.462 695.79h37v-77.875h76.5v-31h-76.5v-43.375h88.625v-31h-125.625v183.25z",
fill: null
}
]
};
export const curvedArrow = {
id: "curvedArrow",
shapes: [
{
path: "M736.339 999.331c-81.488-65.987-214.7-181.888-401.414-347.536l-187.34-170.972c-25.261-23.667-45.344-41.536-59.674-56.351-6.956-5.633-12.134-11.431-17.311-17.229l-7.95-6.438c-1.988-1.609-3.19-4.189-6.38-8.377-6.428-16.444-8.465-26.121-6.943-36.128 0.736-9.037 4.037-19.209 10.319-26.966 2.356-2.909 4.711-5.818 7.276-6.953s4.92-4.044 7.276-6.953c5.914-3.239 11.827-6.478 21.299-10.047l63.897-30.14 200.425-84.952c237.318-100.032 369.086-157.093 399.648-172.483 13.606-6.643 28.832-7.158 42.904-2.184 15.066 5.778 25.997 14.63 34.781 28.165s11.238 26.761 6.575 40.646c-3.877 12.916-10.736 23.417-22.563 29.895-52.855 24.632-187.972 83.797-408.126 176.856l-119.941 50.583c272.709 93.997 556.987 171.675 849.069 231.589 293.861 59.749 590.188 102.229 890.761 127.274s596.030 21.866 889.353-7.125c292.329-29.796 557.987-87.612 795.98-174.253 12.821-5.673 26.476-4.249 41.751 3.304 14.281 6.748 25.421 17.374 33.211 30.105 7.005 13.7 7.68 27.091 2.023 40.171-4.662 13.885-14.294 23.747-27.323 27.646-245.685 90.045-520.029 150.461-822.247 180.276s-607.564 33.016-917.24 7.020c-309.676-25.995-614.322-70.394-913.937-133.197s-589.439-141.76-866.908-238.007c45.344 41.536 97.645 88.705 154.129 140.867 183.942 165.009 315.952 278.33 396.446 343.513 12.919 10.461 19.715 22.387 22.377 37.387s-1.215 27.916-9.853 38.582c-8.637 10.666-20.465 17.144-35.69 17.659-11.668 0.185-25.74-4.788-38.659-15.25z",
fill: null
}
]
};
export const handicapping = {
id: "handicapping",
shapes: [
{
path: "M160.192 864.384h767.808c17.673 0 32 14.327 32 32v0 32c0 17.673-14.327 32-32 32v0h-832c-17.673 0-32-14.327-32-32v0-32c-0.003-0.176-0.005-0.383-0.005-0.59 0-1.258 0.072-2.499 0.211-3.719l-0.014 0.149v-795.392c0-17.673 14.327-32 32-32v0h32c17.673 0 32 14.327 32 32v0 767.552zM256.32 738.816v-245.312c0-8.448 3.904-16.384 10.624-21.504l2.112-1.6c5.297-4.035 12.008-6.464 19.285-6.464 0.015 0 0.030 0 0.045 0l-0.002-0h31.808c0.013-0 0.028-0 0.043-0 7.277 0 13.988 2.429 19.364 6.521l-0.078-0.057 2.112 1.6c6.72 5.12 10.688 13.056 10.688 21.504v245.312c0 0.005 0 0.011 0 0.016 0 8.745-4.166 16.517-10.622 21.44l-0.066 0.048-2.112 1.6c-5.297 4.035-12.008 6.464-19.285 6.464-0.015 0-0.030-0-0.045-0l0.002 0h-31.808c-0.013 0-0.028 0-0.043 0-7.277 0-13.988-2.429-19.364-6.521l0.078 0.057-2.112-1.6c-6.485-4.972-10.624-12.722-10.624-21.439 0-0.023 0-0.046 0-0.068l-0 0.004zM448.32 738.816v-388.736c0-8.384 3.904-16.384 10.624-21.44l2.112-1.6c5.302-4.065 12.028-6.518 19.326-6.528l0.002-0h31.808c7.3 0.010 14.026 2.463 19.405 6.584l-0.077-0.056 2.112 1.6c6.72 5.12 10.688 13.056 10.688 21.44v388.8c0 0.005 0 0.011 0 0.016 0 8.745-4.166 16.517-10.622 21.44l-0.066 0.048-2.112 1.6c-5.297 4.035-12.008 6.464-19.285 6.464-0.015 0-0.030-0-0.045-0l0.002 0h-31.808c-0.013 0-0.028 0-0.043 0-7.277 0-13.988-2.429-19.364-6.521l0.078 0.057-2.112-1.6c-6.485-4.972-10.624-12.722-10.624-21.439 0-0.023 0-0.046 0-0.068l-0 0.004zM640.32 738.816v-291.904c0-8.448 3.904-16.384 10.624-21.504l2.112-1.6c5.302-4.065 12.028-6.518 19.326-6.528l0.002-0h31.808c7.3 0.010 14.026 2.463 19.405 6.584l-0.077-0.056 2.112 1.6c6.72 5.12 10.688 13.056 10.688 21.504v291.904c0 0.005 0 0.011 0 0.016 0 8.745-4.166 16.517-10.622 21.44l-0.066 0.048-2.112 1.6c-5.297 4.035-12.008 6.464-19.285 6.464-0.015 0-0.030-0-0.045-0l0.002 0h-31.808c-0.013 0-0.028 0-0.043 0-7.277 0-13.988-2.429-19.364-6.521l0.078 0.057-2.112-1.6c-6.485-4.972-10.624-12.722-10.624-21.439 0-0.023 0-0.046 0-0.068l-0 0.004zM832.512 732.416v-440.768c0.022-8.27 3.178-15.799 8.343-21.465l-0.023 0.025 3.52-3.968c5.877-6.493 14.336-10.556 23.743-10.56l24.897-0c9.408 0.004 17.867 4.067 23.72 10.533l0.024 0.027 3.584 3.968c5.083 5.642 8.192 13.149 8.192 21.382 0 0.020-0 0.041-0 0.061l0-0.003v440.896c0 0.017 0 0.038 0 0.058 0 8.233-3.109 15.74-8.218 21.411l0.025-0.029-3.584 3.904c-5.877 6.493-14.336 10.556-23.743 10.56l-24.897 0c-9.408-0.004-17.867-4.067-23.72-10.533l-0.024-0.027-3.584-3.904c-5.119-5.648-8.253-13.178-8.256-21.439l-0-0.001z",
fill: null,
grid: 0
}
]
};
export const sorting = {
id: "sorting",
shapes: [
{
path: "M85.312 192h853.376c11.776 0 21.312 9.6 21.312 21.312v53.376c0 11.776-9.6 21.312-21.312 21.312h-853.376c-11.77 0-21.312-9.542-21.312-21.312v0-53.376c0-11.712 9.6-21.312 21.312-21.312zM85.312 464h597.376c11.776 0 21.312 9.6 21.312 21.312v53.376c0 11.776-9.6 21.312-21.312 21.312h-597.376c-11.77 0-21.312-9.542-21.312-21.312v0-53.376c0-11.712 9.6-21.312 21.312-21.312zM85.312 736h469.376c11.776 0 21.312 9.6 21.312 21.312v53.376c0 11.776-9.6 21.312-21.312 21.312h-469.376c-11.77 0-21.312-9.542-21.312-21.312v-53.376c0-11.712 9.6-21.312 21.312-21.312z",
fill: null,
grid: 0
}
]
};
export const contests = {
id: "contests",
shapes: [
{
path: "M512 1024C229.23 1024 0 794.77 0 512S229.23 0 512 0s512 229.23 512 512-229.23 512-512 512zm0-96c229.75 0 416-186.25 416-416S741.75 96 512 96 96 282.25 96 512s186.25 416 416 416zm-16-704h32a32 32 0 0 1 32 32v19.88c43.07 9.6 81.64 32.1 106.64 64.4 5.4 7 2.97 16.9-4.57 21.52l-54.6 33.38c-7.54 4.6-17.42 2.13-23.96-3.82-12.75-11.6-33.33-21.85-60.17-24.22-64.43-5.7-82.46 24.26-83.92 40.76-1.49 16.8 2.38 26.2 8.5 32.57 7.2 7.48 25.03 18.58 66.96 22.3 54.2 4.79 98.23 20.73 127.7 51.38 30.52 31.75 38.11 71.54 34.92 107.56-5.85 66.1-54.18 109.13-117.5 123.54V768a32 32 0 0 1-32 32h-32a32 32 0 0 1-32-32v-22.14c-44.16-9.26-83.83-32.01-109.35-65-5.4-6.98-2.97-16.9 4.57-21.5l54.6-33.39c7.54-4.6 17.42-2.12 23.96 3.82 12.75 11.61 33.34 21.85 60.18 24.23 64.42 5.7 82.46-24.27 83.92-40.77 1.48-16.79-2.38-26.2-8.51-32.57-7.2-7.48-25.03-18.58-66.95-22.29-54.21-4.8-98.24-20.74-127.7-51.38-30.53-31.76-38.12-71.55-34.93-107.57C349.72 332.4 399.36 289.09 464 275.3V256a32 32 0 0 1 32-32z",
fill: null,
grid: 0
}
]
};
export const store = {
id: "store",
shapes: [
{
path: "M189.135 620.549c17.673 0 32 14.327 32 32l-.015 211.771h580.864l.002-211.771c0-17.673 14.327-32 32-32h31.885c17.673 0 32 14.327 32 32V928c0 17.673-14.327 32-32 32h-63.885l-.002-.256H221.12l.015.256H157.25c-17.673 0-32-14.327-32-32V652.549c0-17.673 14.327-32 32-32h31.885zM859.294 64c14.52 0 27.219 9.775 30.935 23.81l5.707 21.694 58.769 214.592c21.439 101.238-22.869 180.801-121.21 199.486l-11.586 1.884c-74.231 10.1-143.177-6.348-175.826-42.193l.509.503-1.069.057c-33.832 33.667-79.313 40.602-121.921 43.57l-11.602.732c-45.798-2.656-96.599-7.557-133.523-44.302l-1.133-.057-6.431 6.405c-34.861 31.012-99.54 44.712-168.822 35.285-106.421-14.481-155.06-96.238-132.796-201.37l44.932-164.163 19.823-72.385C137.858 73.642 150.496 64 164.914 64h694.38zm-48.99 95.872H213.632l-51.069 186.354c-10.704 50.684-1.118 76.793 60.53 85.636 61.649 8.843 106.041 0 106.041-64.174v-4.6c0-17.674 14.327-32 32-32h31.885c17.673 0 32 14.326 32 32v4.6c0 60.796 57.355 63.996 83.013 64.164h7.931c25.609-.168 82.494-3.368 82.494-64.164l-.377 6.008.009-10.608c0-17.674 14.327-32 32-32h31.885a31.878 31.878 0 0121.159 7.993c3.97 2.609 6.833 6.691 8.602 12.243 1.531 4.074 2.239 7.836 2.239 11.764l-.042 8.221c1.691 60.884 46.505 69.227 106.975 60.553 61.648-8.843 71.234-34.952 60.53-85.636l-51.133-186.354z",
fill: null,
grid: 0
}
]
};
export const question = {
id: "question",
shapes: [
{
path: "M512 1024C229.23 1024 0 794.77 0 512S229.23 0 512 0s512 229.23 512 512-229.23 512-512 512zm0-96c229.75 0 416-186.25 416-416S741.75 96 512 96 96 282.25 96 512s186.25 416 416 416zm-56.85-316.75c0-34.07 3.85-60.96 11.55-80.67s20.18-36.81 37.45-51.28 30.4-27.7 39.38-39.72S557 414.32 557 399.85c0-35.23-15.17-52.85-45.5-52.85-14 0-25.32 5.13-33.95 15.4s-13.18 24.15-13.65 41.65H345.6c.47-46.67 15.17-83 44.1-109.03S459.23 256 511.5 256c52.03 0 92.34 12.02 120.93 36.05s42.87 58.22 42.87 102.55c0 19.37-3.85 36.98-11.55 52.85s-20.07 32.08-37.1 48.65l-40.25 37.45c-11.43 10.97-19.37 22.23-23.8 33.77s-6.88 26.2-7.35 43.93zm-14.35 106.4c0-17.27 6.24-31.44 18.72-42.52s28.06-16.63 46.73-16.63 34.24 5.54 46.73 16.63 18.72 25.25 18.72 42.52-6.24 31.44-18.73 42.52-28.05 16.63-46.72 16.63-34.24-5.54-46.73-16.63-18.72-25.25-18.72-42.52z",
fill: null,
grid: 0
}
]
};
export const greyhounds = {
id: "greyhounds",
shapes: [
{
path: "M313.86 760.6a16 16 0 0 0 6.72 21.26l52.14 28.07a16.02 16.02 0 0 0 12.41 1.16 15.99 15.99 0 0 0 9.48-8.1c30.75-61.5 77-111.72 131.34-150.53 23.67-16.91 50.7-20.57 78.8-13.6 55.72 15.92 111.93 31.97 164.25 44.08 28.84 9.31 65.64 4.36 93.39-14.15 5.47-3.64 8.13-4.79 9.21-5.15.42-.14.6-.15.6-.15s.17-.02.45-.03c34.64 4 65.53-8.1 88.3-32.08h7.47l4.68-4.69c6.58-6.58 10.6-15.35 13-23.15a84.73 84.73 0 0 0 3.72-24.26c0-22.13-11.35-38.76-26.95-49.25l-28.9-20.64-1.12-.56c-7.22-3.61-14.59-8.2-22.74-13.3l-.31-.2c-7.75-4.83-16.24-10.14-24.88-14.47-58.87-31.42-111.73-69.63-145.61-129.66-19.19-38-57.2-56.6-94.33-56.6-35.8 0-67.32-14.28-88.11-38.53l-.4-.47-.44-.43c-25.64-25.64-59.47-46.8-93.34-59.6-32.8-15.17-60.06-15.98-81.7-8.34-20.77 7.33-34.25 21.7-41.81 33.83-14.82 17.95-27.82 38.35-39.57 56.8-4.44 6.98-8.71 13.67-12.83 19.85l-15.3 22.96c-6.26 6.97-11.45 18.27-11.45 30.03v.9c-2.34 6.88-1.9 13.48-.52 19.02.55 2.22 1.3 4.38 2.1 6.4-39.38 22.7-75.73 48.57-111.87 77.48-20.1 16.08-39.64 31.7-63.05 47.3L58.2 522.15a16 16 0 0 0-5.77 18.4l20.05 56.15a16 16 0 0 0 22.23 8.93c2.3-1.16 3.86-1.75 5.79-2.5.76-.28 1.58-.6 2.52-.97a34.54 34.54 0 0 0 10.05-5.85l26.54-15.16.54-.32.66-.45c23.86-15.9 48.48-32.32 73.16-52.87 39.96-31.96 75-59.16 117.6-82.43 13.31-6.68 26.86-16.05 37.34-23.3 2.9-2 5.56-3.85 7.92-5.43l19.73-11.81.64-.43c17.87-11.92 23.8-34.25 19.08-51.95-.62-11.36-5.44-21.18-13.95-28a41.8 41.8 0 0 0-14.46-7.38l3.37-5.58 4.73-7.82c6.8-11.16 13.22-21.23 20.35-30.23l.91-.93c.29.05.63.11 1.03.2 2.2.51 5.73 1.72 11.02 4.37l.25.12c24.29 12.14 45.9 23.12 63.77 40.99 42.98 42.98 94.76 64.52 150.45 68.8l.61.05h.62c9.33 0 14 2.3 15.88 3.62l.2.14v1l2.57 3.97c45.53 70.37 107.77 128.55 182.72 166.03a213.84 213.84 0 0 1 22.74 13.1c-20.55 1.6-41.18 9.44-55.91 22.55-3.27.9-5.67 1.21-7.8 1.21-2.74 0-5.98-.52-10.97-2.19l-.36-.1c-30.08-9.26-60.88-17.38-92.1-25.61-22.64-5.97-45.5-12-68.47-18.56-57.25-17.56-114.28-4.27-157.85 26.13-70.6 45.74-124.52 108.07-161.77 182.57z",
fill: null,
grid: 0
}
]
};
export const horse = {
id: "horse",
shapes: [
{
path: "M544 256c-160 32-384 192-384 480l384 192-32-384c25.6 128 170.667 138.667 224 128l96 64c51.2-25.6 42.667-96 32-128-32-10.667-64-96-96-192-20.239-60.716-85.333-138.667-128-192v-96l-96 128z",
fill: null
},
{
path: "M655.179 82.466C674.779 89 688 107.342 688 128.003v79.117c19.201 23.881 42.372 52.72 63.451 82.189 24.652 34.464 49.575 73.983 62.086 111.515 16.014 48.041 31.283 91.079 46.045 123.064 7.408 16.05 13.884 27.522 19.237 34.883 1.998 2.746 3.422 4.343 4.229 5.173a48.001 48.001 0 0126.489 28.88c6.956 20.869 13.293 53.715 9.331 87.217-4.05 34.24-20.263 76.325-65.402 98.895a48.003 48.003 0 01-48.092-2.994l-80.861-53.908c-34.829 3.199-82.507-.082-127.795-17.098a242.269 242.269 0 01-24.017-10.522l19.133 229.603a47.998 47.998 0 01-20.924 43.733 47.999 47.999 0 01-48.376 3.186l-384-192A48 48 0 01112 736.003c0-305.787 229.723-479.631 404.209-522.945L601.6 99.203c12.396-16.528 33.979-23.27 53.579-16.737zM604.063 255.92l-32.666 43.555-17.983 3.597c-138.258 27.652-330.086 162.684-344.545 403.701l280.204 140.102-24.907-298.885c-2.113-25.357 15.928-47.957 41.123-51.514 25.195-3.558 48.789 13.164 53.779 38.115 8.743 43.713 36.523 67.371 71.414 80.48 37.047 13.919 77.475 13.591 96.104 9.865a48.003 48.003 0 0136.04 7.13l60.398 40.266c.191-1.129.36-2.316.508-3.566 1.188-10.039.366-20.955-1.321-30.45-8.842-7.414-15.777-15.856-21.03-23.08-10.647-14.639-20.171-32.5-28.763-51.117-17.238-37.348-33.969-84.977-49.955-132.936-7.728-23.183-25.471-52.998-49.093-86.022-19.492-27.25-40.853-53.827-60.163-77.852-3.106-3.865-6.16-7.664-9.144-11.389z",
fill: null
}
]
};
export const referFriend = {
id: "referFriend",
shapes: [
{
path: "M511.993 159.703c-61.905 0-112.089 50.184-112.089 112.089 0 61.906 50.184 112.09 112.089 112.09s112.089-50.184 112.089-112.09c0-61.905-50.184-112.089-112.089-112.089zM303.904 271.792c0-114.924 93.165-208.089 208.089-208.089 114.925 0 208.089 93.165 208.089 208.089 0 114.925-93.164 208.09-208.089 208.09-114.924 0-208.089-93.165-208.089-208.09zm6.29 352.09c-21.647 0-40.615 14.489-46.309 35.374l-50.383 184.801c-2.775 10.178 4.887 20.208 15.436 20.208H543.99v96H228.938c-73.845 0-127.48-70.214-108.056-141.459l50.383-184.801c17.082-62.655 73.988-106.123 138.929-106.123H543.99v96H310.194zm539.735-49.826l160.001 160c18.74 18.746 18.74 49.138 0 67.883l-160.001 160-67.882-67.883 78.059-78.058H623.988v-96h236.118l-78.059-78.059 67.882-67.883z",
fill: null,
grid: 0
},
{
path: "M7.49991 14.2542H2.57723C1.91789 14.2542 1.43901 13.6273 1.61244 12.9912L2.39967 10.1037C2.57761 9.45101 3.17038 8.99821 3.84685 8.99821H7.49991M8.74988 12H14.203M11.7499 9.50002L14.2499 12L11.7499 14.5M9.50135 4.24682C9.50135 5.6283 8.38144 6.74821 6.99996 6.74821C5.61847 6.74821 4.49856 5.6283 4.49856 4.24682C4.49856 2.86533 5.61847 1.74542 6.99996 1.74542C8.38144 1.74542 9.50135 2.86533 9.50135 4.24682Z",
fill: null
}
]
};
export const rewards = {
id: "rewards",
shapes: [
{
path: "M511.985 864.226c106.039 0 192-85.961 192-192s-85.961-192-192-192c-106.038 0-192 85.961-192 192s85.962 192 192 192zm0-480c159.058 0 288 128.942 288 288 0 154.514-121.679 280.607-274.442 287.687l-13.558.313c-159.058 0-288-128.942-288-288s128.942-288 288-288zm16 160h-32c-17.673 0-32 14.327-32 32v192c0 17.673 14.327 32 32 32h32c17.674 0 32-14.327 32-32v-192c0-17.673-14.326-32-32-32zM171.809 68.191c15.362-8.739 34.899-3.37 43.637 11.992l153.71 270.227c-29.591 13.152-57.031 30.267-81.648 50.669L132.004 127.652c-8.739-15.362-3.37-34.899 11.991-43.638l27.814-15.823zm680.172 0l27.815 15.823c15.361 8.74 20.73 28.276 11.991 43.638L736.275 400.923a352.107 352.107 0 00-81.606-50.578L808.344 80.182c8.739-15.36 28.276-20.73 43.637-11.99zm-183.557 0l27.815 15.823c15.361 8.74 20.73 28.276 11.991 43.638L593.258 329.655c-26.089-6.166-53.3-9.429-81.273-9.429-8.14 0-16.217.276-24.219.82L624.787 80.183c8.739-15.362 28.276-20.73 43.637-11.992zm-312.502.441c15.39-8.688 34.91-3.255 43.598 12.136l76.095 134.797-55.17 94.214L316.27 128.134l-.056-.097c-8.739-15.361-3.37-34.898 11.991-43.637l27.625-15.716.092-.052z",
fill: null
}
]
};
export const optedin = {
id: "optedin",
shapes: [
{
path: "M169.6 192v264.321c0 22.195 9.221 43.393 25.458 58.525l377.82 352.107c6.304 5.875 16.129 5.702 22.222-0.391l264.665-264.665c6.089-6.089 6.267-15.905 0.402-22.211l-351.743-378.17c-15.135-16.272-36.356-25.515-58.578-25.515h-264.246c-8.837 0-16 7.163-16 16zM73.6 192c0-61.856 50.144-112 112-112h264.246c48.889 0 95.576 20.335 128.872 56.134l351.743 378.17c41.053 44.138 39.81 112.851-2.814 155.475l-264.665 264.665c-42.654 42.654-111.426 43.865-155.555 2.739l-377.82-352.107c-35.722-33.291-56.008-79.926-56.008-128.755v-264.321zM320.452 416c-44.183 0-80-35.817-80-80s35.817-80 80-80c44.183 0 80 35.817 80 80s-35.817 80-80 80z",
fill: null
},
{
path: "M1024 256c0 141.385-114.615 256-256 256s-256-114.615-256-256c0-141.385 114.615-256 256-256s256 114.615 256 256z",
fill: color("green", "500")
},
{
path: "M720.59 299.647l135.764-135.765c6.248-6.248 16.379-6.248 22.627 0l11.314 11.314c6.248 6.248 6.248 16.379 0 22.627l-158.392 158.392c-6.248 6.248-16.379 6.248-22.627 0l-67.882-67.882c-6.248-6.248-6.248-16.379 0-22.627l11.314-11.314c6.248-6.248 16.379-6.248 22.627 0l45.255 45.255z",
fill: color("white", "100")
}
]
};
export const timeformPick = {
id: "talent",
shapes: [
{
path: "M858.913 64h-693.826c-55.904 0-101.087 52.864-101.087 118.272v659.456c0 65.408 45.183 118.272 101.087 118.272h693.826c55.904 0 101.087-52.864 101.087-118.272v-659.456c0-65.408-45.183-118.272-101.087-118.272zM523.648 290.688c0 10.752-8.96 19.712-19.712 19.712h-77.952c-10.752 0-19.712 8.96-19.712 19.712v405.888c0 39.424-31.36 70.784-70.784 70.784h-26.88c-10.752 0-19.712-8.96-19.712-19.712v-456.96c0-10.752-8.96-19.712-19.712-19.712h-77.952c-10.752 0-19.712-8.96-19.712-19.712v-54.656c0-10.752 8.96-19.712 19.712-19.712h314.496c10.752 0 19.712 8.96 19.712 19.712v54.656h-1.792zM855.168 290.688c0 10.752-8.96 19.712-19.712 19.712h-137.984c-10.752 0-19.712 8.96-19.712 19.712v113.792c0 10.752 8.96 19.712 19.712 19.712h78.848c10.752 0 19.712 8.96 19.712 19.712v55.552c0 10.752-8.96 19.712-19.712 19.712h-77.952c-10.752 0-19.712 8.96-19.712 19.712v157.696c0 39.424-31.36 70.784-70.784 70.784h-26.88c-10.752 0-19.712-8.96-19.712-19.712v-551.040c0-10.752 8.96-19.712 19.712-19.712h255.36c10.752 0 19.712 8.96 19.712 19.712v54.656h-0.896z",
fill: null,
grid: 0
}
]
};
export const srwPick = {
id: "talent",
shapes: [
{
path: "M512 864.23c106.04 0 192-85.97 192-192 0-106.04-85.96-192-192-192s-192 85.96-192 192c0 106.03 85.96 192 192 192zm0-480c159.06 0 288 128.94 288 288 0 157.46-126.38 285.41-283.24 287.96l-4.76.04c-159.06 0-288-128.95-288-288 0-159.06 128.94-288 288-288zm16 160h-32a32 32 0 00-32 32v192a32 32 0 0032 32h32a32 32 0 0032-32v-192a32 32 0 00-32-32zM171.82 68.19a32 32 0 0143.64 12L369.2 350.4a352.09 352.09 0 00-81.64 50.65l-155.53-273.4A32 32 0 01144 84.01zm680.18 0l27.81 15.82a32 32 0 0112 43.64l-155.48 273.3a352.08 352.08 0 00-81.66-50.61L808.36 80.18A32 32 0 01852 68.2zm-183.56 0l27.81 15.82a32 32 0 0112 43.64L593.31 329.67a352.99 352.99 0 00-81.32-9.44c-8.14 0-16.22.27-24.23.82L624.8 80.18a32 32 0 0143.64-11.99zm-312.5.44a32 32 0 0143.6 12.14l76.09 134.8-55.17 94.2-104.18-181.64a32 32 0 0111.94-43.73l27.62-15.72z",
fill: null,
grid: 0
}
]
};
export const numberFirePick = {
id: "numberFirePick",
shapes: [
{
path: "M326.367 371.2c97.644 0 154.533 64.141 154.533 167.947V832H351.839V579.657c0-60.765-28.869-91.991-78.115-91.991-49.247 0-80.663 31.226-80.663 91.991V832H64V379.64h129.061v64.14c29.718-37.978 67.926-72.58 133.306-72.58zM960 192v126.877H733.046v140.309h200.48v119.183h-200.48V832H574.575V192H960z",
fill: null
}
]
};
export const transactionAdjust = {
id: "transactionAdjust",
shapes: [
{
path: "M791.928 490.692c11.746-11.746 30.84-11.746 42.586 0v0l180.646 180.646c2.831 2.771 5.060 6.084 6.566 9.818 3.072 7.349 3.072 15.661 0 23.010-1.566 3.674-3.795 7.048-6.566 9.879v0l-180.646 180.646c-5.903 5.843-13.613 8.794-21.323 8.794s-15.42-2.952-21.263-8.855c-11.746-11.746-11.746-30.84 0-42.586v0l129.265-129.265h-650.12c-16.625 0-30.118-13.493-30.118-30.118s13.493-30.118 30.118-30.118v0h650.12l-129.265-129.265c-11.746-11.746-11.746-30.84 0-42.586zM189.515 129.28c11.746-11.746 30.84-11.746 42.586 0s11.746 30.84 0 42.586v0l-129.265 129.265h650.12c16.625 0 30.118 13.493 30.118 30.118s-13.493 30.118-30.118 30.118v0h-650.12l129.325 129.265c11.746 11.806 11.746 30.84 0 42.647-5.903 5.843-13.613 8.794-21.323 8.794s-15.42-2.952-21.323-8.855v0l-180.646-180.646c-2.831-2.771-5.060-6.084-6.566-9.818-3.072-7.349-3.072-15.661 0-23.010 1.566-3.674 3.795-7.048 6.566-9.818v0z",
fill: null
}
]
};
export const transactionDeposit = {
id: "transactionDeposit",
shapes: [
{
path: "M993.882 963.765h-187.934c24.395-46.743 37.346-97.882 37.346-150.588 0-182.694-148.6-331.294-331.294-331.294s-331.294 148.6-331.294 331.294c0 52.706 12.89 103.846 37.346 150.588h-187.934c-16.625 0-30.118 13.493-30.118 30.118s13.493 30.118 30.118 30.118h963.765c16.625 0 30.118-13.493 30.118-30.118s-13.493-30.118-30.118-30.118zM240.941 813.176c0-149.444 121.615-271.059 271.059-271.059s271.059 121.615 271.059 271.059c0 53.67-16.926 105.231-47.827 150.588h-446.464c-30.901-45.357-47.827-96.919-47.827-150.588zM512 662.588c16.634 0 30.118-13.484 30.118-30.118s-13.484-30.118-30.118-30.118c-16.634 0-30.118 13.484-30.118 30.118s13.484 30.118 30.118 30.118zM632.471 722.824c16.634 0 30.118-13.484 30.118-30.118s-13.484-30.118-30.118-30.118c-16.634 0-30.118 13.484-30.118 30.118s13.484 30.118 30.118 30.118zM692.706 843.294c16.634 0 30.118-13.484 30.118-30.118s-13.484-30.118-30.118-30.118c-16.634 0-30.118 13.484-30.118 30.118s13.484 30.118 30.118 30.118zM391.529 722.824c16.634 0 30.118-13.484 30.118-30.118s-13.484-30.118-30.118-30.118c-16.634 0-30.118 13.484-30.118 30.118s13.484 30.118 30.118 30.118zM331.294 843.294c16.634 0 30.118-13.484 30.118-30.118s-13.484-30.118-30.118-30.118c-16.634 0-30.118 13.484-30.118 30.118s13.484 30.118 30.118 30.118zM632.471 963.765c16.634 0 30.118-13.484 30.118-30.118s-13.484-30.118-30.118-30.118c-16.634 0-30.118 13.484-30.118 30.118s13.484 30.118 30.118 30.118zM391.529 963.765c16.634 0 30.118-13.484 30.118-30.118s-13.484-30.118-30.118-30.118c-16.634 0-30.118 13.484-30.118 30.118s13.484 30.118 30.118 30.118zM490.677 412.792c2.771 2.771 6.144 5 9.818 6.566 3.674 1.506 7.59 2.289 11.505 2.289s7.831-0.783 11.505-2.289c3.735-1.506 7.048-3.735 9.818-6.566l180.646-180.646c11.746-11.746 11.746-30.84 0-42.586s-30.84-11.746-42.586 0l-129.265 129.265v-288.708c0-16.625-13.493-30.118-30.118-30.118s-30.118 13.493-30.118 30.118v288.708l-129.265-129.265c-11.746-11.746-30.84-11.746-42.586 0s-11.746 30.84 0 42.586l180.646 180.646z",
fill: null
}
]
};
export const transactionBets = {
id: "transactionBets",
shapes: [
{
path: "M512.018 722.83c16.625 0 30.118 13.493 30.118 30.118s-13.493 30.118-30.118 30.118h-240.941c-16.625 0-30.118-13.493-30.118-30.118s13.493-30.118 30.118-30.118h240.941zM752.959 722.83c16.625 0 30.118 13.493 30.118 30.118s-13.493 30.118-30.118 30.118h-60.235c-16.625 0-30.118-13.493-30.118-30.118s13.493-30.118 30.118-30.118h60.235zM512.018 542.124c16.625 0 30.118 13.493 30.118 30.118s-13.493 30.118-30.118 30.118h-240.941c-16.625 0-30.118-13.493-30.118-30.118s13.493-30.118 30.118-30.118h240.941zM752.959 542.124c16.625 0 30.118 13.493 30.118 30.118s-13.493 30.118-30.118 30.118h-60.235c-16.625 0-30.118-13.493-30.118-30.118s13.493-30.118 30.118-30.118h60.235zM752.959 301.182c16.625 0 30.118 13.493 30.118 30.118s-13.493 30.118-30.118 30.118h-481.882c-16.625 0-30.118-13.493-30.118-30.118s13.493-30.118 30.118-30.118h481.882zM146.372 60.536c-14.637 1.988-25.901 14.276-25.901 29.033v844.92c0 16.143 13.493 29.274 30.118 29.274h722.824c16.625 0 30.118-13.131 30.118-29.274v-844.92c0-14.878-11.384-27.166-26.082-29.094l-175.285 57.645c-6.144 1.988-12.83 1.988-18.974 0l-168.659-56.26-174.743 59.211c-6.325 2.168-13.192 2.108-19.516-0.060l-173.899-60.476zM873.412 1024h-722.824c-49.815 0-90.353-40.177-90.353-89.51v-844.92c0-49.393 40.538-89.57 90.353-89.57 3.373 0 6.746 0.602 9.879 1.626l169.803 59.091 174.502-59.151c6.204-2.108 12.951-2.048 19.215 0l168.779 56.26 171.249-56.26c3.012-1.024 6.204-1.566 9.397-1.566 49.815 0 90.353 40.177 90.353 89.57v844.92c0 49.333-40.538 89.51-90.353 89.51v0z",
fill: null
}
]
};
export const transactionWithdraw = {
id: "transactionWithdraw",
shapes: [
{
path: "M993.882 0.181h-963.765c-16.625 0-30.118 13.493-30.118 30.118s13.493 30.118 30.118 30.118h210.824v391.529c0 49.815 40.538 90.353 90.353 90.353h361.412c49.815 0 90.353-40.538 90.353-90.353v-391.529h210.824c16.625 0 30.118-13.493 30.118-30.118s-13.493-30.118-30.118-30.118zM596.811 60.416c-12.469 34.997-45.598 60.235-84.811 60.235s-72.343-25.239-84.811-60.235h169.623zM512 602.534c16.625 0 30.118 13.493 30.118 30.118v0 288.708l129.265-129.325c11.806-11.746 30.84-11.686 42.586 0.060s11.746 30.84 0 42.586v0l-180.646 180.646c-2.771 2.831-6.084 5.060-9.818 6.566-3.674 1.506-7.59 2.289-11.505 2.289s-7.831-0.783-11.505-2.289c-3.674-1.566-7.048-3.795-9.818-6.566v0l-180.646-180.646c-11.746-11.746-11.746-30.84 0-42.586s30.84-11.746 42.586 0v0l129.265 129.265v-288.708c0-16.625 13.493-30.118 30.118-30.118zM364.484 60.416c13.975 68.668 74.812 120.471 147.516 120.471s133.542-51.802 147.516-120.471h63.307v391.529c0 16.625-13.493 30.118-30.118 30.118h-361.412c-16.625 0-30.118-13.493-30.118-30.118v-391.529h63.307z",
fill: null
}
]
};
export const transactionPromo = {
id: "transactionPromo",
shapes: [
{
path: "M582.415 60.296l-513.385 510.554c-5.662 5.602-8.794 13.131-8.794 21.143 0 7.951 3.132 15.48 8.855 21.203l342.377 341.775c5.722 5.662 13.252 8.794 21.263 8.794s15.541-3.132 21.263-8.794l509.771-510.916v-382.072l-381.35-1.687zM432.73 1024h-0.060c-24.154 0-46.803-9.397-63.789-26.443l-342.377-341.775c-17.107-16.986-26.504-39.695-26.504-63.789s9.397-46.803 26.504-63.789l522.3-519.409c5.662-5.602 13.312-8.794 21.263-8.794h0.12l423.816 1.867c16.565 0.060 29.997 13.553 29.997 30.118v424.538c0 8.011-3.192 15.661-8.794 21.323l-518.626 519.71c-17.047 17.047-39.755 26.443-63.849 26.443v0zM843.3 240.941c0 33.31-26.925 60.235-60.235 60.235s-60.235-26.925-60.235-60.235c0-33.31 26.925-60.235 60.235-60.235s60.235 26.925 60.235 60.235z",
fill: null
}
]
};
export const checkPromo = {
id: "checkPromo",
shapes: [
{
path: "M8.43423 1.75195H13.2482C13.8005 1.75195 14.2482 2.19967 14.2482 2.75195V7.56592C14.2482 7.84424 14.1322 8.10997 13.9281 8.29921L7.79672 13.9844C7.4025 14.3499 6.78983 14.3384 6.40969 13.9582L2.04192 9.59046C1.66178 9.21032 1.65021 8.59765 2.01574 8.20343L7.70095 2.07203C7.89018 1.86794 8.15591 1.75195 8.43423 1.75195Z",
fill: null
},
{
path: "M5.99968 7L7.99968 9L11.9997 5M13.2482 1.75195H8.43423C8.15591 1.75195 7.89018 1.86794 7.70095 2.07203L2.01574 8.20343C1.65021 8.59765 1.66178 9.21032 2.04192 9.59046L6.40969 13.9582C6.78983 14.3384 7.4025 14.3499 7.79672 13.9844L13.9281 8.29921C14.1322 8.10997 14.2482 7.84424 14.2482 7.56592V2.75195C14.2482 2.19967 13.8005 1.75195 13.2482 1.75195Z",
fill: null,
strokeColor: "#329A47",
strokeWidth: 1.5,
strokeLinejoin: "round"
}
]
};
export const caretUp = {
id: "caretUp",
shapes: [{ path: "M768 640h-512l256-320z", fill: null }]
};
export const caretDown = {
id: "caretDown",
shapes: [{ path: "M256 320h512l-256 320z", fill: null }]
};
export const hasReplay = {
id: "hasReplay",
shapes: [
{
path: "M219.152 218.266c-.008.008.008-.008 0 0l-54.746 54.746H257v96H48.75c-26.51 0-48-21.491-48-48v-208.25h96v92.141l54.622-54.622C243.966 57.967 371.854.812 513 .812c282.879 0 512.2 229.32 512.2 512.199 0 282.88-229.321 512.199-512.2 512.199C230.12 1025.21.8 795.891.8 513.011h96C96.8 742.872 283.14 929.21 513 929.21c229.86 0 416.199-186.338 416.199-416.199 0-229.86-186.339-416.198-416.199-416.198-114.704 0-218.517 46.362-293.848 121.453zm142.228 60.975a48 48 0 0148.347.613l319.936 192a48.001 48.001 0 01.008 82.311l-319.937 192.08a47.998 47.998 0 01-48.35.619 47.999 47.999 0 01-24.357-41.772v-384.08a48 48 0 0124.353-41.771zm71.647 126.557v214.49l178.67-107.268-178.67-107.222z",
fill: null
}
]
};
export const noReplay = {
id: "noReplay",
shapes: [
{
path: "M186.71 254.592c-56.294 70.986-89.913 160.769-89.913 258.404 0 229.86 186.339 416.199 416.199 416.199 97.635 0 187.418-33.619 258.404-89.913L647.055 714.937l67.882-67.882L839.282 771.4c56.294-70.986 89.913-160.769 89.913-258.404 0-229.86-186.339-416.2-416.199-416.2-97.635 0-187.418 33.62-258.404 89.914l68.345 68.345-67.882 67.882-68.345-68.345zm-68.25-68.25C44.971 275.003.797 388.841.797 512.996c0 282.88 229.319 512.204 512.199 512.204 124.155 0 237.993-44.179 326.654-117.668l87.405 87.405 67.882-67.882-87.405-87.405c73.489-88.661 117.668-202.499 117.668-326.654 0-282.88-229.324-512.2-512.204-512.2-124.155 0-237.993 44.175-326.654 117.664L98.937 31.055 31.055 98.937l87.405 87.405zm242.916 92.883a48 48 0 0148.347.614l319.937 192a47.999 47.999 0 01.008 82.31L409.73 746.227a48 48 0 01-72.707-41.153V320.996a48 48 0 0124.353-41.771zm71.647 126.557v214.489l178.67-107.267-178.67-107.222z",
fill: null,
fillRule: "evenodd"
}
]
};
export const ippChanges = {
id: "ippChanges",
shapes: [
{
path: "M466.745 77.477c24.994-24.993 65.516-24.993 90.51 0l389.27 389.27c24.993 24.994 24.993 65.517 0 90.51l-389.27 389.27c-24.994 24.994-65.516 24.994-90.51 0l-389.27-389.27c-24.993-24.994-24.993-65.516 0-90.51l389.27-389.27z",
fill: color("orange", "400")
},
{
path: "M432.804 43.536c43.739-43.739 114.653-43.739 158.392 0l389.27 389.27c43.734 43.738 43.734 114.653 0 158.392l-389.27 389.27c-43.739 43.742-114.653 43.742-158.392 0l-389.27-389.27c-43.739-43.739-43.739-114.654 0-158.392l389.27-389.27zm90.51 67.882c-6.249-6.248-16.379-6.248-22.628 0l-389.27 389.27c-6.248 6.248-6.248 16.379 0 22.627l389.27 389.27c6.249 6.249 16.379 6.249 22.628 0l389.27-389.27c6.248-6.248 6.248-16.379 0-22.627l-389.27-389.27zM560 288.001v288h-96v-288h96zm0 352v96h-96v-96h96z",
fill: color("grey", "900"),
fillRule: "evenodd"
}
]
};
export const spinningWheel = {
id: "spinningWheel",
shapes: [
{
path: "M512 1024C229.23 1024 0 794.77 0 512S229.23 0 512 0v118.154c-217.515 0-393.846 176.331-393.846 393.846 0 217.515 176.331 393.846 393.846 393.846V1024z",
fill: null
}
]
};
export const eyeShow = {
id: "eyeShow",
shapes: [
{
path: "M512 176C213.333 176 48 512 48 512C48 512 213.333 848 512 848C810.667 848 976 512 976 512C976 512 810.667 176 512 176ZM512 656.242C591.662 656.242 656.238 591.662 656.238 512C656.238 432.338 591.662 367.76 512 367.76C432.338 367.76 367.758 432.338 367.758 512C367.758 591.662 432.338 656.242 512 656.242Z",
fill: null,
fillRule: "evenodd",
clipRule: "evenodd",
strokeWidth: 85.3333
}
]
};
export const eyeLineShow = {
id: "eyeLineShow",
shapes: [
{
path: "M1.52341 7.99984C1.59239 8.11771 1.68012 8.26215 1.78612 8.42628C2.09152 8.89915 2.54367 9.52778 3.13032 10.1535C4.31731 11.4197 5.96613 12.5832 7.99984 12.5832C10.0335 12.5832 11.6824 11.4197 12.8694 10.1535C13.456 9.52778 13.9082 8.89915 14.2136 8.42628C14.3196 8.26215 14.4073 8.11771 14.4763 7.99983C14.4073 7.88196 14.3196 7.73752 14.2136 7.5734C13.9082 7.10052 13.456 6.47189 12.8694 5.84613C11.6824 4.58001 10.0335 3.4165 7.99984 3.4165C5.96613 3.4165 4.31731 4.58001 3.13032 5.84613C2.54367 6.47189 2.09152 7.10052 1.78612 7.5734C1.68012 7.73752 1.59239 7.88196 1.52341 7.99984ZM15.3332 7.99984C16.004 7.66443 16.0037 7.66391 16.0037 7.66391L16.0026 7.66161L16.0002 7.65685L15.9924 7.64162C15.9859 7.62897 15.9767 7.61137 15.965 7.58915C15.9415 7.54473 15.9075 7.48179 15.8632 7.40297C15.7745 7.24544 15.6443 7.02389 15.4736 6.75961C15.1332 6.23249 14.627 5.52778 13.9637 4.82021C12.6506 3.41967 10.6328 1.9165 7.99984 1.9165C5.36687 1.9165 3.34903 3.41967 2.03602 4.82021C1.37267 5.52778 0.86649 6.23249 0.526058 6.75961C0.355376 7.02389 0.225132 7.24544 0.13652 7.40297C0.0921861 7.48179 0.0581893 7.54473 0.034683 7.58915C0.0229274 7.61137 0.0137877 7.62897 0.00728332 7.64162L-0.000497416 7.65685L-0.00290294 7.66161L-0.00373377 7.66326C-0.00373377 7.66326 -0.00431651 7.66443 0.666504 7.99984L-0.00431652 7.66443C-0.109889 7.87557 -0.109889 8.1241 -0.00431652 8.33525L0.666504 7.99984C-0.00431651 8.33525 -0.00431652 8.33525 -0.00431652 8.33525L-0.00373377 8.33641L-0.00290294 8.33806L-0.000497416 8.34282L0.00728332 8.35806C0.0137877 8.37071 0.0229274 8.38831 0.034683 8.41052C0.0581893 8.45494 0.0921861 8.51788 0.13652 8.5967C0.225132 8.75423 0.355376 8.97578 0.526058 9.24006C0.86649 9.76719 1.37267 10.4719 2.03602 11.1795C3.34903 12.58 5.36687 14.0832 7.99984 14.0832C10.6328 14.0832 12.6506 12.58 13.9637 11.1795C14.627 10.4719 15.1332 9.76719 15.4736 9.24006C15.6443 8.97578 15.7745 8.75423 15.8632 8.5967C15.9075 8.51788 15.9415 8.45494 15.965 8.41052C15.9767 8.38831 15.9859 8.37071 15.9924 8.35806L16.0002 8.34282L16.0026 8.33806L16.0034 8.33641C16.0034 8.33641 16.004 8.33525 15.3332 7.99984ZM15.3332 7.99984L16.004 8.33525C16.1096 8.1241 16.1093 7.87505 16.0037 7.66391L15.3332 7.99984Z",
fill: null,
fillRule: "evenodd",
clipRule: "evenodd"
},
{
path: "M8 6.75C7.30964 6.75 6.75 7.30964 6.75 8C6.75 8.69036 7.30964 9.25 8 9.25C8.69036 9.25 9.25 8.69036 9.25 8C9.25 7.30964 8.69036 6.75 8 6.75ZM5.25 8C5.25 6.48122 6.48122 5.25 8 5.25C9.51878 5.25 10.75 6.48122 10.75 8C10.75 9.51878 9.51878 10.75 8 10.75C6.48122 10.75 5.25 9.51878 5.25 8Z",
fill: null,
fillRule: "evenodd",
clipRule: "evenodd"
}
]
};
export const eyeHide = {
id: "eyeHide",
shapes: [
{
path: "M164.699 666.96C97.5661 587.524 48 511.999 48 511.999C48 511.999 213.332 176 511.999 176C556.475 176 597.64 183.451 635.493 196.134M262.842 760.688C329.257 810.566 412.309 848 511.999 848C810.665 848 976 511.999 976 511.999C976 511.999 893.48 362.33 760.44 262.775M960 64L613.993 410.007M64 960L613.993 410.007M367.758 512.001C367.758 432.338 432.337 367.76 511.999 367.76M409.917 613.906C436.027 640.06 472.123 656.241 511.999 656.241C591.661 656.241 656.239 591.663 656.239 512.001C656.239 472.17 640.095 436.11 613.993 410.007",
fill: null,
fillRule: "evenodd",
clipRule: "evenodd",
strokeWidth: 85.3333
}
]
};
export const eyeLineHide = {
id: "eyeLineHide",
shapes: [
{
path: "M2.91416 3.97482C3.28381 3.65539 3.69042 3.34784 4.13289 3.07223L5.228 4.16734C4.77834 4.41713 4.36108 4.71499 3.97783 5.03849L2.91416 3.97482ZM1.84576 5.02774C1.27517 5.66404 0.833169 6.28408 0.526058 6.75961C0.355376 7.02389 0.225132 7.24544 0.13652 7.40297C0.0921861 7.48179 0.0581893 7.54473 0.034683 7.58915C0.0229274 7.61137 0.0137877 7.62897 0.00728332 7.64162L-0.000497416 7.65685L-0.00290294 7.66161L-0.00373377 7.66326C-0.00373377 7.66326 -0.00431651 7.66443 0.666504 7.99984L-0.00431652 7.66443C-0.109889 7.87557 -0.109889 8.1241 -0.00431652 8.33525L-0.00373377 8.33641L-0.00290294 8.33806L-0.000497416 8.34282L0.00728332 8.35806C0.0137877 8.37071 0.0229274 8.38831 0.034683 8.41052C0.0581893 8.45494 0.0921861 8.51788 0.13652 8.5967C0.225132 8.75423 0.355376 8.97578 0.526058 9.24006C0.86649 9.76719 1.37267 10.4719 2.03602 11.1795C3.34903 12.58 5.36687 14.0832 7.99984 14.0832C8.88765 14.0832 9.70553 13.9123 10.45 13.632L9.25175 12.4337C8.85257 12.5299 8.43502 12.5832 7.99984 12.5832C5.96613 12.5832 4.31731 11.4197 3.13032 10.1535C2.54367 9.52778 2.09152 8.89915 1.78612 8.42628C1.68012 8.26215 1.59239 8.11771 1.52341 7.99984C1.59239 7.88196 1.68012 7.73752 1.78612 7.5734C2.05178 7.16205 2.42849 6.63284 2.90819 6.09018L1.84576 5.02774ZM10.7717 11.8323L11.8668 12.9274C12.3092 12.6518 12.7159 12.3443 13.0855 12.0249L12.0218 10.9612C11.6386 11.2847 11.2213 11.5826 10.7717 11.8323ZM13.0915 9.9095L14.1539 10.9719C14.7245 10.3356 15.1665 9.71559 15.4736 9.24006C15.6443 8.97578 15.7745 8.75423 15.8632 8.5967C15.9075 8.51788 15.9415 8.45494 15.965 8.41052C15.9767 8.38831 15.9859 8.37071 15.9924 8.35806L16.0002 8.34282L16.0026 8.33806L16.0034 8.33641C16.0034 8.33641 16.004 8.33525 15.3332 7.99984L16.004 8.33525C16.1096 8.1241 16.1093 7.87505 16.0037 7.66391L16.0026 7.66161L16.0002 7.65685L15.9924 7.64162C15.9859 7.62897 15.9767 7.61137 15.965 7.58915C15.9415 7.54473 15.9075 7.48179 15.8632 7.40297C15.7745 7.24544 15.6443 7.02389 15.4736 6.75961C15.1332 6.23249 14.627 5.52778 13.9637 4.82021C12.6506 3.41967 10.6328 1.9165 7.99984 1.9165C7.11202 1.9165 6.29414 2.08741 5.54964 2.36767L6.74791 3.56594C7.1471 3.46978 7.56465 3.4165 7.99984 3.4165C10.0335 3.4165 11.6824 4.58001 12.8694 5.84613C13.456 6.47189 13.9082 7.10052 14.2136 7.5734C14.3196 7.73752 14.4073 7.88196 14.4763 7.99983C14.4073 8.11771 14.3196 8.26215 14.2136 8.42628C13.9479 8.83763 13.5712 9.36684 13.0915 9.9095ZM15.3332 7.99984C16.004 7.66443 16.0037 7.66391 16.0037 7.66391L15.3332 7.99984Z",
fill: null,
fillRule: "evenodd",
clipRule: "evenodd"
},
{
path: "M5.05197 6.11263C5.32486 5.68728 5.68728 5.32486 6.11263 5.05197L7.21893 6.15827C6.74244 6.3606 6.3606 6.74244 6.15827 7.21893L5.05197 6.11263ZM4.5131 7.69508C4.50443 7.79557 4.5 7.89727 4.5 8C4.5 9.933 6.067 11.5 8 11.5C8.10273 11.5 8.20443 11.4956 8.30492 11.4869L4.5131 7.69508ZM10.948 9.88737C10.6751 10.3127 10.3127 10.6751 9.88737 10.948L8.78107 9.84173C9.25756 9.6394 9.6394 9.25756 9.84173 8.78108L10.948 9.88737ZM11.4869 8.30492L7.69508 4.5131C7.79557 4.50443 7.89727 4.5 8 4.5C9.933 4.5 11.5 6.067 11.5 8C11.5 8.10273 11.4956 8.20443 11.4869 8.30492Z",
fill: null,
fillRule: "evenodd",
clipRule: "evenodd"
},
{
path: "M2.41414 1.35348C2.21888 1.15822 1.90229 1.15822 1.70703 1.35348L1.35348 1.70703C1.15822 1.90229 1.15822 2.21888 1.35348 2.41414L13.3743 14.435C13.5696 14.6302 13.8861 14.6302 14.0814 14.435L14.435 14.0814C14.6302 13.8861 14.6302 13.5696 14.435 13.3743L2.41414 1.35348Z",
fill: null
}
]
};
export const glassyError = {
id: "glassyError",
shapes: [
{
path: "M321.008 320.029L513.008 512.029M513.008 512.029L705.008 704.029M513.008 512.029L321.008 704.029M513.008 512.029L705.008 320.029M977.025 512.208C977.025 768.479 769.276 976.228 513.005 976.228C256.733 976.228 48.9844 768.479 48.9844 512.208C48.9844 255.936 256.733 48.1875 513.005 48.1875C769.276 48.1875 977.025 255.936 977.025 512.208Z",
fill: "transparent",
strokeColor: "#C92C2C",
strokeWidth: 96
}
]
};
export const questionMark = {
id: "questionMark",
shapes: [
{
path: "M 512.0001,896.00019 V 764.34318 M 336.45743,369.37215 c 0,0 0,-175.54265 175.54267,-175.54265 175.54269,0 175.54269,175.54265 175.54269,175.54265 0,175.54269 -175.54269,131.65702 -175.54269,307.19968",
fill: "transparent",
strokeWidth: 131
}
]
};
export const exclamationMark = {
id: "exclamationMark",
shapes: [
{
path: "m 519.02327,84.666671 v 522.657139 0 0 0 0 m -0.012,115.97226 v 174.17064",
fill: "transparent",
strokeWidth: 175
}
]
};
export const exclamationMarkYellow = {
id: "exclamationMarkYellow",
shapes: [
{
path: "M976.022 512.179c0 256.271-207.749 464.02-464.02 464.02-256.271 0-464.02-207.749-464.02-464.02 0-256.271 207.749-464.02 464.02-464.02 256.271 0 464.02 207.749 464.02 464.02z",
fill: "#FFE099"
},
{
path: "M512.002 85.622c-235.581 0-426.557 190.976-426.557 426.557 0 235.581 190.976 426.557 426.557 426.557 235.581 0 426.557-190.976 426.557-426.557 0-235.581-190.976-426.557-426.557-426.557zM10.518 512.179c0-276.962 224.522-501.484 501.484-501.484S1013.49 235.217 1013.49 512.18 788.964 1013.66 512.002 1013.66 10.518 789.141 10.518 512.179zM549.464 256v320h-74.926V256h74.926zm0 416v96h-74.926v-96h74.926z",
fill: "#CA9008",
fillRule: "evenodd"
}
]
};
export const personRightArrow = {
id: "personRightArrow",
shapes: [
{
path: "M4.84636 8.99805H11.1525C11.829 8.99805 12.4218 9.45084 12.5997 10.1035L13.3869 12.991C13.5604 13.6271 13.0815 14.254 12.4222 14.254H3.57674C2.9174 14.254 2.43852 13.6271 2.61195 12.991L3.39918 10.1035C3.57712 9.45084 4.16989 8.99805 4.84636 8.99805Z",
fill: "white",
fillOpacity: 0.1
},
{
path: "M10.5018 4.247C10.5018 5.62848 9.38193 6.74839 8.00044 6.74839C6.61896 6.74839 5.49905 5.62848 5.49905 4.247C5.49905 2.86552 6.61896 1.74561 8.00044 1.74561C9.38193 1.74561 10.5018 2.86552 10.5018 4.247Z",
fill: "white",
fillOpacity: 0.1
},
{
path: "M8.50039 14.2544H3.57771C2.91838 14.2544 2.4395 13.6275 2.61293 12.9914L3.40016 10.1038C3.5781 9.45119 4.17087 8.9984 4.84734 8.9984H8.50039M9.75037 12.0002H15.2035M12.7504 9.50021L15.2504 12.0002L12.7504 14.5002M10.5018 4.247C10.5018 5.62848 9.38193 6.74839 8.00044 6.74839C6.61896 6.74839 5.49905 5.62848 5.49905 4.247C5.49905 2.86552 6.61896 1.74561 8.00044 1.74561C9.38193 1.74561 10.5018 2.86552 10.5018 4.247Z",
fill: null,
strokeColor: "",
strokeWidth: 1.5
}
]
};
export const deleteIcon = {
id: "deleteIcon",
shapes: [
{
path: "M6.4269 1.70483C6.33003 1.79937 6.22599 1.90299 6.08705 2.04278C6.08705 2.04278 3.7982 4.33387 3.79055 4.34049C3.71954 4.40787 3.66045 4.46549 3.59919 4.5264C3.57104 4.55455 3.546 4.57931 3.49261 4.63185C3.4467 4.67702 3.42545 4.698 3.39899 4.72432L1.32949 6.79678C1.28508 6.84287 1.24697 6.88168 1.19796 6.93092L1.14217 6.98703C1.07898 7.05035 1.02899 7.10188 0.95834 7.17559C0.796275 7.33556 0.631939 7.51646 0.477196 7.70618C0.333415 7.85954 0.217338 8.03681 0.134231 8.2301L0.112272 8.28858C-0.0374241 8.75215 -0.0374241 9.25109 0.112272 9.71466L0.135197 9.77538C0.218934 9.96819 0.335628 10.1448 0.479954 10.2974C0.634044 10.4868 0.79826 10.6677 0.971886 10.8394C1.00841 10.8788 1.06223 10.9338 1.13412 11.0057C1.18377 11.0554 1.20513 11.0768 1.23175 11.1036C1.26613 11.1383 1.29585 11.1687 1.32344 11.1973L3.39839 13.2767C3.5012 13.3795 3.54722 13.4252 3.62955 13.5055C3.69723 13.5725 3.73729 13.6114 3.81146 13.6799L6.0891 15.9615C6.25981 16.1323 6.3364 16.2085 6.43293 16.3034C6.55841 16.429 6.64112 16.5101 6.77032 16.6364C6.819 16.6878 6.83724 16.7066 6.86219 16.7299C7.15378 17.023 7.50944 17.282 7.89889 17.4808C8.28873 17.6772 8.70205 17.8137 9.12862 17.8874C9.52828 17.9532 9.9271 17.9884 10.3269 17.9934C10.4964 17.9972 10.6665 17.9995 10.8346 18.0001L11.2348 18.0001H18.6805C18.835 18.0001 18.9882 17.9979 19.2006 17.9933C19.598 17.9884 20.0008 17.9531 20.3992 17.8876C20.8343 17.8125 21.2505 17.6747 21.6397 17.4781C22.0341 17.2785 22.394 17.0176 22.706 16.7049C23.0167 16.3929 23.2765 16.035 23.4767 15.6436C23.6748 15.2491 23.812 14.832 23.8858 14.4016C23.9518 13.9981 23.9869 13.5955 23.9917 13.1919C23.9947 13.0928 23.9961 13.0055 23.9984 12.8111L24 12.6867L24.0001 12.0735V5.284L23.9989 5.1766C23.9976 5.05681 23.997 5.0045 23.9958 4.93737C23.9947 4.87442 23.9934 4.81668 23.9918 4.76104C23.9873 4.37304 23.9525 3.97396 23.888 3.57918C23.8138 3.14702 23.6778 2.73345 23.4836 2.34646C23.2825 1.95326 23.0244 1.59806 22.7163 1.28897C22.4081 0.978475 22.051 0.718677 21.6595 0.520425C21.2732 0.324986 20.8603 0.188142 20.434 0.114261C20.0325 0.0489346 19.6336 0.0140846 19.2338 0.00884734C19.0528 0.00446197 18.8857 0.0021224 18.7251 0.0021224C18.563 0.000459011 18.4289 0.00012207 18.1279 0.00012207H11.4324C11.1336 0.00012207 10.9986 0.000461062 10.8292 0.00215574C10.6756 0.0021224 10.5091 0.00444704 10.3181 0.00897761C9.92594 0.0141291 9.5277 0.0489854 9.13367 0.113131C8.7003 0.188264 8.28703 0.32496 7.90046 0.519926C7.5081 0.719875 7.15225 0.979229 6.84371 1.28956C6.82941 1.30363 6.81895 1.31464 6.73159 1.40792C6.62322 1.51071 6.52357 1.60779 6.4269 1.70483ZM3.83526 4.3024L3.83773 4.30047C3.83474 4.30272 3.83266 4.30429 3.83008 4.30643L3.83526 4.3024ZM7.03198 15.0185L4.72997 12.7124C4.72997 12.7124 4.68405 12.6706 4.67927 12.6666C4.64375 12.6326 4.6132 12.6028 4.53688 12.5273C4.48179 12.4738 4.43893 12.4313 4.34135 12.3337L2.27471 10.2628C2.25047 10.2375 2.21671 10.203 2.17842 10.1644C2.14997 10.1357 2.12699 10.1127 2.07666 10.0623C2.01337 9.999 1.96793 9.95259 1.92557 9.9076C1.76375 9.74699 1.62675 9.59538 1.4986 9.43642L1.45468 9.38716C1.42077 9.35271 1.39238 9.31332 1.37044 9.27037C1.3204 9.09396 1.32053 8.90704 1.37083 8.73068C1.39279 8.68696 1.42134 8.64681 1.45552 8.61166L1.4959 8.56616C1.62476 8.40688 1.76234 8.25485 1.90801 8.11078C1.98605 8.0297 2.03116 7.9832 2.06527 7.94861L2.11069 7.90335L2.1426 7.87136C2.19682 7.81688 2.24019 7.77271 2.28181 7.72934L4.34061 5.66778C4.36321 5.6453 4.38235 5.62641 4.43646 5.57317C4.48323 5.52714 4.51031 5.50037 4.54032 5.47035C4.58676 5.42418 4.63243 5.37952 4.67729 5.3365C4.68714 5.32827 4.69862 5.31762 4.73129 5.28732L7.03128 2.98362C7.16705 2.84701 7.2669 2.74758 7.36464 2.65211C7.45862 2.55785 7.54933 2.46948 7.64526 2.37847C7.66653 2.35862 7.67923 2.34533 7.73795 2.28301L7.78437 2.23396C7.99784 2.01928 8.2389 1.84359 8.50301 1.709C8.76969 1.5745 9.05746 1.47932 9.35449 1.4278C9.67671 1.37538 10.0093 1.34627 10.3426 1.34186C10.5308 1.33744 10.6871 1.33525 10.8357 1.33525C11.0059 1.33358 11.1379 1.33325 11.4323 1.33325H18.1277C18.4243 1.33325 18.5554 1.33358 18.7183 1.33522C18.8739 1.33525 19.0306 1.33745 19.2089 1.34173C19.5502 1.34624 19.8834 1.37535 20.2131 1.42897C20.5024 1.47914 20.7892 1.5742 21.0574 1.70988C21.3214 1.84358 21.5625 2.01894 21.7712 2.22916C21.9824 2.44113 22.1586 2.68364 22.2944 2.94891C22.4273 3.21385 22.522 3.50197 22.5731 3.79928C22.6259 4.12274 22.6549 4.45517 22.6588 4.78838C22.6605 4.84998 22.6617 4.90222 22.6627 4.95987C22.6638 5.02318 22.6644 5.07361 22.6657 5.19052L22.6668 5.29158L22.6668 5.88134V12.6716L22.6652 12.7949C22.663 12.9814 22.6617 13.0635 22.6587 13.1638C22.6545 13.5124 22.6252 13.8484 22.5708 14.1808C22.5201 14.4763 22.4243 14.7677 22.2874 15.0403C22.1525 15.3042 21.9744 15.5494 21.7619 15.7628C21.5504 15.9747 21.3059 16.152 21.0381 16.2875C20.7671 16.4245 20.477 16.5204 20.1776 16.5722C19.8506 16.6259 19.5146 16.6554 19.1777 16.6595C18.9679 16.6641 18.8233 16.6661 18.6803 16.6661H10.8371C10.6799 16.6655 10.5178 16.6633 10.3498 16.6596C10.0107 16.6553 9.67865 16.6261 9.35022 16.572C9.05844 16.5215 8.7707 16.4266 8.50154 16.291C8.24018 16.1575 7.99858 15.9816 7.78884 15.7712C7.77629 15.7589 7.75888 15.7409 7.73686 15.7177L7.73412 15.7148C7.68164 15.6594 7.6698 15.6469 7.65739 15.635L7.64241 15.621C7.5662 15.5494 7.49173 15.4764 7.37126 15.3559C7.27429 15.2605 7.19956 15.1861 7.03198 15.0185ZM11.8121 12.5287C11.7581 12.5822 11.6934 12.6259 11.6204 12.6561C11.3969 12.7487 11.1397 12.6975 10.9687 12.5265C10.8562 12.4143 10.793 12.2619 10.793 12.1029C10.793 11.944 10.8562 11.7916 10.9687 11.6793V11.6807C11.0014 11.648 11.0372 11.6197 11.0753 11.5959L13.6685 8.99876L10.9688 6.30118L10.9778 6.29212C10.9242 6.23802 10.8805 6.17322 10.8502 6.10009C10.7577 5.87659 10.8088 5.61933 10.9798 5.44828C11.0921 5.33531 11.2447 5.27178 11.404 5.27178C11.5632 5.27178 11.7158 5.33531 11.8281 5.44828H11.8254C11.8551 5.47799 11.8812 5.5103 11.9035 5.54457L14.5129 8.15308L17.1326 5.52935C17.1527 5.50039 17.1757 5.4728 17.2015 5.44699C17.3725 5.27593 17.6297 5.22475 17.8531 5.31732C18.0765 5.40989 18.2222 5.62798 18.2222 5.8699C18.2222 6.03077 18.1578 6.1811 18.0489 6.291L18.0556 6.29765L15.3587 8.99862L17.9672 11.6062C18 11.628 18.0309 11.6532 18.0592 11.6815L18.0578 11.6828C18.2288 11.8539 18.28 12.1111 18.1875 12.3346C18.0949 12.5581 17.8769 12.7038 17.635 12.7038C17.474 12.7038 17.3236 12.6392 17.2137 12.5301L17.2082 12.5356L14.5146 9.84409L11.8231 12.5397L11.8121 12.5287Z",
fillRule: "evenodd",
clipRule: "evenodd",
fill: null
}
]
};
// icons being used in PAWS
export const userOutline = {
id: "userNew",
shapes: [
{
path: "M11.1269 4.30838C11.1269 6.03524 9.72702 7.43513 8.00017 7.43513C6.27331 7.43513 4.87342 6.03524 4.87342 4.30838C4.87342 2.58153 6.27331 1.18164 8.00017 1.18164C9.72702 1.18164 11.1269 2.58153 11.1269 4.30838Z",
fill: "transparent",
fillOpacity: 0.1,
strokeWidth: 2
},
{
path: "M13.7499 11.6319C13.5274 10.8162 12.7865 10.2502 11.941 10.2502H4.05856C3.21303 10.2502 2.4721 10.8162 2.24963 11.6319L1.26594 15.2387C1.04908 16.0339 1.64768 16.8176 2.4719 16.8176H13.5276C14.3518 16.8176 14.9504 16.0339 14.7336 15.2387L13.7499 11.6319",
fill: "transparent",
fillOpacity: 0.1,
strokeWidth: 2
},
{
path: "M11.1269 4.30838C11.1269 6.03524 9.72702 7.43513 8.00017 7.43513C6.27331 7.43513 4.87342 6.03524 4.87342 4.30838C4.87342 2.58153 6.27331 1.18164 8.00017 1.18164C9.72702 1.18164 11.1269 2.58153 11.1269 4.30838Z",
strokeColor: color("blue", "000"),
strokeWidth: 2,
strokeLinejoin: "round",
fill: null
},
{
path: "M13.7499 11.6319C13.5274 10.8162 12.7865 10.2502 11.941 10.2502H4.05856C3.21303 10.2502 2.4721 10.8162 2.24963 11.6319L1.26594 15.2387C1.04908 16.0339 1.64768 16.8176 2.4719 16.8176H13.5276C14.3518 16.8176 14.9504 16.0339 14.7336 15.2387L13.7499 11.6319",
strokeColor: color("blue", "000"),
strokeWidth: 2,
strokeLinejoin: "round",
fill: null
}
]
};
export const depositNewExp = {
id: "depositNewExp",
shapes: [
{
path: "M12 5V8M12 8V11M12 8H15M12 8H9",
strokeColor: "#fff",
strokeWidth: 1.5,
fill: null
},
{
path: "M8 5.60001C8 5.60001 8 3.20001 5 3.20001M5 3.20001C2 3.20001 2 5.60001 2 5.60001C2 6.40001 2 7.2 5 8C8 8.8 8 9.59999 8 10.4C8 10.4 8 12.8 5 12.8M5 3.20001V1M5 12.8C2 12.8 2 10.4 2 10.4M5 12.8V15M12 5V8M12 8V11M12 8H15M12 8H9",
strokeColor: "#fff",
strokeWidth: 1.5,
fill: null
}
]
};
export const envelope = {
id: "envelope",
shapes: [
{
path: "M1.24998 1.74998L9 8.25L16.75 1.74998M1.1875 1.6875H16.8125V12.3125H1.1875V1.6875Z",
strokeColor: color("blue", "100"),
fill: null,
strokeWidth: 2,
strokeLinejoin: "round"
}
]
};
export const betTicket = {
id: "betTicket",
shapes: [
{
path: "M10.25 0.75H1.75C1.19772 0.75 0.75 1.19772 0.75 1.75V13.5L3 12.5L4.5 13.5L6 12.5L7.5 13.5L9 12.5L11.25 13.5V1.75C11.25 1.19772 10.8023 0.75 10.25 0.75Z",
fillOpacity: 0.1,
fill: "white"
},
{
path: "M3 4.75H6M3 7.75H9M1.75 0.75H10.25C10.8023 0.75 11.25 1.19772 11.25 1.75V13.5L9 12.5L7.5 13.5L6 12.5L4.5 13.5L3 12.5L0.75 13.5V1.75C0.75 1.19772 1.19772 0.75 1.75 0.75Z",
strokeColor: color("grey", "900"),
strokeWidth: 1.5,
strokeLinejoin: "round",
fill: null
}
]
};
export const watchLive = {
id: "watchLive",
shapes: [
{
path: "M10 14.5625H5.46875H2.8125C1.77697 14.5625 0.9375 13.723 0.9375 12.6875V3.3125C0.9375 2.27697 1.77697 1.4375 2.8125 1.4375H17.1875C18.223 1.4375 19.0625 2.27697 19.0625 3.3125V12.6875C19.0625 13.723 18.223 14.5625 17.1875 14.5625H14.5312H10ZM7.5 11.75V4.25L13.75 8L7.5 11.75Z",
fillRule: "evenodd",
clipRule: "evenodd",
fill: "white",
fillOpacity: 0.1
},
{
path: "M5.46875 14.5625H10H14.5312M5.46875 14.5625L2.5 17.375M5.46875 14.5625H2.8125C1.77697 14.5625 0.9375 13.723 0.9375 12.6875V3.3125C0.9375 2.27697 1.77697 1.4375 2.8125 1.4375H17.1875C18.223 1.4375 19.0625 2.27697 19.0625 3.3125V12.6875C19.0625 13.723 18.223 14.5625 17.1875 14.5625H14.5312M14.5312 14.5625L17.5 17.375M7.5 4.25V11.75L13.75 8L7.5 4.25Z",
strokeColor: color("blue", "000"),
strokeWidth: 1.5,
fill: null
}
]
};
export const stable = {
id: "stable",
shapes: [
{
path: "M14.25 14.25V7.98791L12.94 4.18214L8 2L3.0444 4.18214L1.75 7.98791V14.25H4.25V9H11.75V14.25H14.25Z",
fill: "white",
fillOpacity: 0.1
},
{
path: "M4.25 14.25H1.75V7.98791L3.0444 4.18214L8 2L12.94 4.18214L14.25 7.98791V14.25H11.75M4.25 14.25V9H11.75V14.25M4.25 14.25H11.75M11.75 14.25L4.26953 9.01953",
strokeWidth: 1.5,
strokeLinejoin: "round",
strokeColor: color("blue_accent", "500"),
fill: null
}
]
};
export const customerSupport = {
id: "customerSupport",
shapes: [
{
path: "M2 7.5513L2.5 12L5.5 11.5V8L2 7.5513Z",
fill: "none",
fillOpacity: 0.1
},
{
path: "M13.5027 11.9764L13.9977 7.57138L10.5 8V11.5L13.5027 11.9764Z",
fill: "white",
fillOpacity: 0.1
},
{
path: "M2 7.5513C2 4.34733 4.68629 1.75 8 1.75C11.3137 1.75 14 4.34733 14 7.5513L13.5 12L12.5 14L7.75 14.25M2 7.5513L2.5 12L5.5 11.5V8L2 7.5513ZM10.5 11.5V8L13.9977 7.57138L13.5027 11.9764L10.5 11.5Z",
strokeWidth: 1.5,
strokeColor: color("blue_accent", "500"),
strokeLinejoin: "round",
fill: null
}
]
};
export const wallet = {
id: "wallet",
shapes: [
{
path: "M3.8156 3C2.81287 3 2 3.82974 2 4.85328V16.0734C2 16.5851 2.40644 17 2.9078 17H17.0922C17.5936 17 18 16.5851 18 16.0734V7.2278C18 6.71603 17.5936 6.30116 17.0922 6.30116H3.8156V4.85328H17.0922V3H3.8156ZM3.8156 15.1467V8.15444H16.1844V15.1467H3.8156ZM13.6312 13.0772C14.1326 13.0772 14.539 12.6624 14.539 12.1506C14.539 11.6388 14.1326 11.2239 13.6312 11.2239C13.1298 11.2239 12.7234 11.6388 12.7234 12.1506C12.7234 12.6624 13.1298 13.0772 13.6312 13.0772Z",
fillRule: "evenodd",
clipRule: "evenodd",
fill: null
}
]
};
export const questionNewExp = {
id: "questionNewExp",
shapes: [
{
path: "M10.9999 16.0001V14.1251M8.49989 8.50008C8.49989 8.50008 8.49989 6.00008 10.9999 6.00008C13.4999 6.00008 13.4999 8.50008 13.4999 8.50008C13.4999 11.0001 10.9999 10.3751 10.9999 12.8751M20.0628 11.0036C20.0628 16.0089 16.0052 20.0665 10.9999 20.0665C5.99461 20.0665 1.93701 16.0089 1.93701 11.0036C1.93701 5.99827 5.99461 1.94067 10.9999 1.94067C16.0052 1.94067 20.0628 5.99827 20.0628 11.0036Z",
fill: "none",
strokeWidth: 2,
strokeColor: "#fff"
}
]
};
export const closeThin = {
id: "closeThin",
shapes: [
{
path: "M4.375 4.375L15.625 15.625M15.625 4.375L4.375 15.625",
strokeWidth: 1.5,
strokeLinejoin: "round",
fill: null
}
]
};
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Icons/index.jsx
import React from "react";
import styled from "styled-components";
export const generatePaths = (icon, qaLabel) =>
icon.map((shape, index) => {
if (shape.path) {
return (
<path
key={`path-${index.toString()}`}
fill={shape.fill}
fillRule={shape.fillRule}
clipRule={shape.clipRule}
stroke={shape.strokeColor}
strokeWidth={shape.strokeWidth}
fillOpacity={shape.fillOpacity}
d={shape.path}
{...(qaLabel ? { "data-qa-label": `${qaLabel}-path` } : {})}
/>
);
}
return (
<rect
key={`rect-${index.toString()}`}
x={shape.xRect}
y={shape.yRect}
width={shape.widthRect}
height={shape.heightRect}
rx={shape.rxRect}
fill={shape.fill}
stroke={shape.strokeColor}
strokeWidth={shape.strokeWidth}
{...(qaLabel ? { "data-qa-label": `${qaLabel}-rect` } : {})}
/>
);
});
const colorize = (
colorList = [],
strokeColorList = [],
strokeWidthList = [],
icon
) => {
const localIcon = icon.map((shape) => ({ ...shape }));
if (colorList.length) {
colorList.forEach((color, index) => {
if (color && localIcon[index]) {
localIcon[index].fill = color;
}
});
}
if (strokeColorList.length) {
strokeColorList.forEach((color, index) => {
if (color && localIcon[index]) {
localIcon[index].strokeColor = color;
}
});
}
if (strokeWidthList.length) {
strokeWidthList.forEach((width, index) => {
if (width && localIcon[index]) {
localIcon[index].strokeWidth = width;
}
});
}
return localIcon;
};
const IconSVG = styled.svg.attrs(({ size, qaLabel, viewBoxSize, filter }) => ({
width: size,
height: size,
viewBox: `0 0 ${viewBoxSize} ${viewBoxSize}`,
"data-qa-label": qaLabel,
filter
}))`
display: inline-block;
width: ${({ size }) => size}px;
height: ${({ size }) => size}px;
fill: ${({ color, colorList }) =>
color !== "inherit" && colorList.length === 0 && color};
stroke: ${({ stroke }) => stroke !== "inherit" && stroke};
${({ filter }) => (filter ? `filter: ${filter};` : "")};
`;
const Icon = ({
icon,
size,
qaLabel,
className,
colorList,
stroke,
strokeColorList,
strokeWidthList,
filter,
color,
viewBoxSize
}) => (
<IconSVG
size={size}
qaLabel={qaLabel}
className={className}
colorList={colorList}
filter={filter}
color={color}
stroke={stroke}
viewBoxSize={viewBoxSize}
>
{generatePaths(
colorList.length || strokeColorList.length || strokeWidthList.length
? colorize(colorList, strokeColorList, strokeWidthList, icon.shapes)
: icon?.shapes || [],
qaLabel
)}
</IconSVG>
);
Icon.defaultProps = {
size: 16,
icon: null,
color: "inherit",
stroke: "inherit",
className: "",
qaLabel: null,
filter: "",
colorList: [],
strokeColorList: [],
strokeWidthList: [],
viewBoxSize: 1024
};
export default Icon;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/ModalHeaderV3/index.jsx
import React, { PureComponent } from "react";
import { noop, isFunction, get } from "lodash";
import {
BackButton,
CloseButton,
Subtitle,
Title,
TitleContainer,
TitleHolder
} from "./styled-components";
import { arrowBack, close } from "../../_static/Icons/icons";
import { fontNormal } from "../../_static/Typography";
import buildColor from "../../_static/ColorPalette";
import Icon from "../../_static/Icons";
export default class ModalHeader extends PureComponent {
static defaultProps = {
title: null,
subtitle: null,
onClose: noop,
onBack: null,
hasRoundedCorners: true,
hasCloseButton: true,
scrollableRef: {
current: null
},
className: "",
device: "mobile",
isTitleCenter: false,
subtitleColor: buildColor("grey", "800"),
subtitleFontFamily: fontNormal,
isTitleCapitalized: true,
showBottomShadow: true
};
constructor(props) {
super(props);
this.state = {
isAtTop: true
};
}
componentDidMount() {
this.addEventListener(this.props.scrollableRef.current);
}
componentDidUpdate(prevProps) {
this.removeEventListener(prevProps.scrollableRef.current);
this.addEventListener(this.props.scrollableRef.current);
}
componentWillUnmount() {
this.removeEventListener(this.props.scrollableRef.current);
}
setIsAtTop = () => {
if (get(this.props, "scrollableRef.current.scrollTop") === 0) {
this.setState({
isAtTop: true
});
} else {
this.setState({
isAtTop: false
});
}
};
addEventListener = (element) => {
if (element) {
element.addEventListener("scroll", this.setIsAtTop, {
capture: true
});
}
};
removeEventListener = (element) => {
if (element) {
element.removeEventListener("scroll", this.setIsAtTop);
}
};
render() {
const hasBack = this.props.onBack && isFunction(this.props.onBack);
const hasClose = this.props.hasCloseButton;
return (
<TitleContainer
className={this.props.className}
data-qa-label="modal-header"
roundedCorners={this.props.hasRoundedCorners}
showShadow={!this.state.isAtTop && this.props.showBottomShadow}
hasBack={hasBack}
device={this.props.device}
showBottomShadow={this.props.showBottomShadow}
>
{hasBack && (
<BackButton
qaLabel="modal-backBtn"
onClick={this.props.onBack}
isAbsolute={this.props.isTitleCenter}
>
<Icon
icon={arrowBack}
color={buildColor("grey", "900")}
size={16}
/>
</BackButton>
)}
{this.props.subtitle ? (
<TitleHolder isTitleCenter={this.props.isTitleCenter}>
<Title isTitleCapitalized={this.props.isTitleCapitalized}>
{this.props.title}
</Title>
<Subtitle
isUsingMargin={!this.props.isTitleCenter}
subtitleColor={this.props.subtitleColor}
subtitleFontFamily={this.props.subtitleFontFamily}
data-qa-label="modal-subtitle"
>
{this.props.subtitle}
</Subtitle>
</TitleHolder>
) : (
<TitleHolder isTitleCenter={this.props.isTitleCenter}>
<Title isTitleCapitalized={this.props.isTitleCapitalized}>
{this.props.title}
</Title>
</TitleHolder>
)}
{hasClose && (
<CloseButton qaLabel="modal-closeBtn" onClick={this.props.onClose}>
<Icon icon={close} color={buildColor("grey", "900")} size={16} />
</CloseButton>
)}
</TitleContainer>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/ModalHeader/styled-components.js
import styled, { css } from "styled-components";
import { transparentize } from "polished";
import { buildTitle } from "../../_atom/Title";
import Button from "../../_atom/Buttons/default";
import Icon from "../../_static/Icons";
import { fontMedium, fontBold, fontNormal } from "../../_static/Typography";
import { easeInOut, generateTransition } from "../../_static/Transitions";
import buildColor from "../../_static/ColorPalette";
export const TitleContainer = styled.div`
display: flex;
align-items: stretch;
padding: 8px;
transition: ${generateTransition(easeInOut, "box-shadow")};
${({ isTitleCenter }) => isTitleCenter && `position: relative`};
${(props) =>
props.isNavigation
? css`
justify-content: flex-start;
background-color: ${buildColor("blue", "700")};
`
: css`
justify-content: ${({ isTitleCenter }) =>
isTitleCenter ? `center` : `space-between`};
background-color: ${props.titleType === "defaultBold"
? buildColor("blue", "700")
: buildColor("white", "100")};
${props.titleType !== "defaultBold" &&
props.hasHeaderBorder &&
css`
border-bottom: 1px solid ${buildColor("blue", "100")};
`};
`};
color: ${(props) =>
props.titleType === "defaultBold"
? buildColor("white", "100")
: buildColor("grey", "900")};
${(props) =>
props.roundedCorners &&
css`
border-radius: 4px 4px 0 0;
`};
flex: 0 0 auto;
${(props) =>
props.isSticky &&
css`
position: sticky;
top: 0;
z-index: 20;
`};
${(props) =>
props.myBetsStandaloneToggle &&
css`
color: ${buildColor("blue", "900")};
`};
${({ titleType, myBetsStandaloneToggle }) =>
titleType === "ipp" &&
!myBetsStandaloneToggle &&
css`
border-bottom: 1px solid ${buildColor("blue", "100")};
z-index: 20;
`}
${(props) =>
props.showShadow &&
css`
box-shadow:
0 2px 4px ${transparentize(0.94, buildColor("blue", "900"))},
0 1px 2px ${transparentize(0.92, buildColor("blue", "900"))};
`};
`;
export const NavigationTitleContainer = styled.div`
display: flex;
`;
export const HeaderButton = styled(Button)`
display: flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
border: 0;
background: none;
flex: 0 0 32px;
border-radius: 50%;
${({ isTitleCenter }) =>
isTitleCenter &&
css`
position: absolute;
top: 0;
right: 8px;
transform: translate(0, 25%);
`}
${({ hasBiggerHeader }) =>
hasBiggerHeader &&
css`
align-self: start;
`}
${({ hasMarginRight }) =>
hasMarginRight &&
css`
margin-right: 10px;
`}
${({ shouldRenderWhiteTitle }) =>
!shouldRenderWhiteTitle &&
`
&:hover {
background-color: ${buildColor("grey", "100")};
}
&:active {
background-color: ${buildColor("grey", "200")};
}
@media (pointer: fine) {
&:hover {
background-color: ${buildColor("grey", "100")};
}
}
@media (pointer: coarse) {
&:active {
background-color: ${buildColor("grey", "200")};
}
}
`}
`;
export const CloseButton = styled(Button)`
margin: 0 12px 0 auto;
color: ${buildColor("white", "100")};
font-weight: 500;
font-size: 14px;
font-family: ${fontMedium};
background: none;
display: flex;
${({ translateHeader }) =>
translateHeader &&
css`
transform: translateX(-338px);
`}
& > svg {
margin-left: 4px;
}
`;
export const StatusIcon = styled(Icon)`
margin-right: 8px;
`;
export const Title = styled(
buildTitle({
color: buildColor("grey", "900"),
fontSize: 16,
ellipsis: true,
uppercase: false,
qaLabel: "modal-title"
})
)`
display: flex;
align-items: center;
${({ isTitleCenter }) => !isTitleCenter && `flex: 1 1 auto`};
margin: 4px 0 0 4px;
line-height: 24px;
font-family: ${fontBold};
text-transform: capitalize;
${(props) =>
!props.hasSubtitle &&
css`
margin-bottom: 4px;
`};
${(props) =>
props.success &&
css`
color: ${buildColor("green", "600")};
`};
${(props) =>
props.error &&
css`
color: ${buildColor("red", "500")};
`};
${(props) =>
props.warning &&
css`
color: ${buildColor("orange", "500")};
`};
${(props) =>
props.isNavigation &&
css`
color: ${buildColor("white", "100")};
`};
${(props) =>
props.subtitle &&
css`
color: ${buildColor("grey", "800")};
`};
${(props) =>
props.myBetsStandaloneToggle &&
css`
display: inline-block;
font-family: ${fontBold};
text-transform: capitalize;
font-size: 18px;
`};
${({ info }) =>
info &&
css`
font-size: 18px;
font-weight: 700;
text-transform: none;
`}
${({ shouldRenderWhiteTitle }) =>
shouldRenderWhiteTitle && `color: ${buildColor("white", "100")};`}
`;
export const TitleHolder = styled.div`
flex: 1 0 auto;
display: inline-flex;
flex-direction: column;
`;
export const WidgetContainer = styled.div`
display: flex;
justify-content: space-between;
width: 100%;
align-items: center;
padding-right: 8px;
`;
export const Subtitle = styled.p`
margin: 0 0 4px 4px;
font-family: ${fontNormal};
font-size: 14px;
font-style: normal;
text-transform: capitalize;
line-height: 18px;
color: ${buildColor("grey", "800")};
`;
export const HeaderChildrenContainer = styled.div`
display: block;
width: 100%;
`;
export const HeaderContainer = styled.div`
display: block;
${(props) =>
props.showShadow &&
css`
z-index: 20;
box-shadow:
0 2px 4px ${transparentize(0.94, buildColor("blue", "900"))},
0 1px 2px ${transparentize(0.92, buildColor("blue", "900"))};
`};
`;
export const CounterContainer = styled.div`
margin: auto;
display: flex;
align-items: center;
padding-right: 12px;
`;
export const NormalCounter = styled.span`
padding-right: 4px;
font-weight: 700;
`;
export const DollarCounter = styled.span`
padding-right: 4px;
padding-left: 16px;
font-weight: 700;
`;
export const CounterDescription = styled.span`
font-size: 11px;
font-family: ${fontNormal};
color: ${buildColor("grey", "700")};
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/ModalHeader/index.jsx
import React, { PureComponent } from "react";
import { noop, isFunction, get } from "lodash";
import { formatCurrency } from "@tvg/formatter";
import {
HeaderButton,
NavigationTitleContainer,
StatusIcon,
Subtitle,
Title,
TitleContainer,
TitleHolder,
WidgetContainer,
HeaderContainer,
HeaderChildrenContainer,
CounterContainer,
NormalCounter,
DollarCounter,
CounterDescription
} from "./styled-components";
import { arrowBack, close, success } from "../../_static/Icons/icons";
import buildColor from "../../_static/ColorPalette";
import Icon from "../../_static/Icons";
export default class ModalHeader extends PureComponent {
static defaultProps = {
title: null,
subtitle: null,
titleType: "default",
onClose: noop,
onBack: null,
hasRoundedCorners: true,
widget: null,
isSticky: false,
hasCloseWithoutHeader: false,
hasIcon: true,
hasCloseButton: true,
hasHeaderBorder: true,
myBetsStandaloneToggle: false,
scrollableRef: {
current: null
},
hasBiggerHeader: false,
device: "mobile",
shouldRenderWhiteTitle: false,
headerTitleChildren: null,
isTitleCenter: false
};
constructor(props) {
super(props);
this.state = {
isAtTop: true
};
}
// ipp modal header needs to have a drop shadow when scrolled down
componentDidMount() {
this.addEventListener(
this.props.titleType,
this.props.scrollableRef.current
);
}
componentDidUpdate(prevProps) {
this.removeEventListener(
prevProps.titleType,
prevProps.scrollableRef.current
);
this.addEventListener(
this.props.titleType,
this.props.scrollableRef.current
);
}
componentWillUnmount() {
this.removeEventListener(
this.props.titleType,
this.props.scrollableRef.current
);
}
getArrowColor = (titleType) => {
if (titleType === "ipp") {
return buildColor("grey", "900");
}
return titleType === "defaultBold"
? buildColor("white", "100")
: buildColor("blue", "500");
};
setIsAtTop = () => {
if (get(this.props, "scrollableRef.current.scrollTop") === 0) {
this.setState({
isAtTop: true
});
} else {
this.setState({
isAtTop: false
});
}
};
addEventListener = (titleType, element) => {
if (titleType === "ipp" && element) {
element.addEventListener("scroll", this.setIsAtTop, {
capture: true
});
}
};
removeEventListener = (titleType, element) => {
if (titleType === "ipp" && element) {
element.removeEventListener("scroll", this.setIsAtTop);
}
};
render() {
let ModalTitle;
switch (this.props.titleType) {
case "success":
ModalTitle = (
<Title
success
myBetsStandaloneToggle={this.props.myBetsStandaloneToggle}
hasSubtitle={!!this.props.subtitle}
>
{this.props.hasIcon && (
<StatusIcon
icon={success}
color={buildColor("green", "600")}
size={16}
/>
)}
{this.props.title}
</Title>
);
break;
case "error":
ModalTitle = (
<Title
error
myBetsStandaloneToggle={this.props.myBetsStandaloneToggle}
hasSubtitle={!!this.props.subtitle}
>
{this.props.title}
</Title>
);
break;
case "warning":
ModalTitle = (
<Title
warning
myBetsStandaloneToggle={this.props.myBetsStandaloneToggle}
hasSubtitle={!!this.props.subtitle}
>
{this.props.title}
</Title>
);
break;
case "navigation":
ModalTitle = (
<Title
isNavigation
myBetsStandaloneToggle={this.props.myBetsStandaloneToggle}
hasSubtitle={!!this.props.subtitle}
>
{this.props.title}
</Title>
);
break;
case "subtitle":
ModalTitle = (
<Title
subtitle
myBetsStandaloneToggle={this.props.myBetsStandaloneToggle}
hasSubtitle={!!this.props.subtitle}
>
{this.props.title}
</Title>
);
break;
case "ipp":
ModalTitle = (
<Title
ipp
myBetsStandaloneToggle={this.props.myBetsStandaloneToggle}
hasBiggerHeader={this.props.hasBiggerHeader}
hasSubtitle={!!this.props.subtitle}
isTitleCenter={this.props.isTitleCenter}
>
{this.props.title}
</Title>
);
break;
case "info":
ModalTitle = (
<Title
info
hasSubtitle={!!this.props.subtitle}
isTitleCenter={this.props.isTitleCenter}
>
{this.props.title}
</Title>
);
break;
default:
ModalTitle = (
<Title
myBetsStandaloneToggle={this.props.myBetsStandaloneToggle}
hasSubtitle={!!this.props.subtitle}
shouldRenderWhiteTitle={this.props.shouldRenderWhiteTitle}
>
{typeof this.props.title === "string" &&
this.props.title.includes("RACE SCHEDULE")
? this.props.title.replace("RACE SCHEDULE", "Race Schedule")
: this.props.title}
</Title>
);
}
if (this.props.subtitle) {
ModalTitle = (
<TitleHolder>
{ModalTitle}
<Subtitle>{this.props.subtitle}</Subtitle>
</TitleHolder>
);
}
const hasBack =
/default|defaultBold|ipp/.test(this.props.titleType) &&
isFunction(this.props.onBack);
return this.props.titleType === "navigation" ? (
<TitleContainer
data-qa-label="modal-header"
titleType={this.props.titleType}
isNavigation={this.props.titleType === "navigation"}
roundedCorners={this.props.hasRoundedCorners}
isSticky={this.props.isSticky}
hasHeaderBorder={this.props.hasHeaderBorder}
myBetsStandaloneToggle={this.props.myBetsStandaloneToggle}
hasBiggerHeader={this.props.hasBiggerHeader}
device={this.props.device}
isTitleCenter={this.props.isTitleCenter}
>
<NavigationTitleContainer>
<HeaderButton qaLabel="modal-closeBtn" onClick={this.props.onClose}>
<Icon
icon={arrowBack}
color={buildColor("white", "100")}
size={16}
/>
</HeaderButton>
</NavigationTitleContainer>
<WidgetContainer>
{ModalTitle}
{this.props.widget}
</WidgetContainer>
</TitleContainer>
) : (
<HeaderContainer
showShadow={this.props.titleType === "ipp" && !this.state.isAtTop}
>
<TitleContainer
data-qa-label="modal-header"
titleType={this.props.titleType}
roundedCorners={this.props.hasRoundedCorners}
hasBack={hasBack}
hasHeaderBorder={this.props.hasHeaderBorder}
myBetsStandaloneToggle={this.props.myBetsStandaloneToggle}
hasBiggerHeader={this.props.hasBiggerHeader}
device={this.props.device}
isTitleCenter={this.props.isTitleCenter}
>
{hasBack && (
<HeaderButton qaLabel="modal-backBtn" onClick={this.props.onBack}>
<Icon
icon={arrowBack}
color={this.getArrowColor(this.props.titleType)}
size={16}
/>
</HeaderButton>
)}
{ModalTitle}
{this.props.headerTitleChildren && this.props.headerTitleChildren}
{this.props.hasCloseButton && (
<HeaderButton
qaLabel="modal-closeBtn"
onClick={this.props.onClose}
hasBiggerHeader={this.props.hasBiggerHeader}
hasMarginRight={this.props.device !== "mobile"}
shouldRenderWhiteTitle={this.props.shouldRenderWhiteTitle}
isTitleCenter={this.props.isTitleCenter}
>
<Icon
icon={close}
color={
this.props.titleType === "defaultBold"
? buildColor("white", "100")
: buildColor("grey", "900")
}
size={18}
qaLabel="modal-closeBtn-Icon"
/>
</HeaderButton>
)}
</TitleContainer>
{this.props.headerChildren && (
<HeaderChildrenContainer>
{this.props.headerChildren}
</HeaderChildrenContainer>
)}
</HeaderContainer>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/Buttons/styles.js
import buildColor from "../../_static/ColorPalette";
const SIZES = {
default: { height: "32px", fontSize: "11px", padding: "0 8px" },
small: { height: "24px", fontSize: "10px", padding: "0 8px" },
micro: { height: "16px", fontSize: "10px", padding: "2px" },
big: { height: "40px", fontSize: "12px", padding: "0 16px" },
bigger: { height: "44px", fontSize: "14px", padding: "0 16px" },
huge: { height: "48px", fontSize: "14px", padding: "0 24px" },
autoSized: { height: "auto", fontSize: "auto", padding: "0" }
};
const TYPES = {
primary: {
background: buildColor("blue_accent", "500"),
hover: buildColor("blue_accent", "600"),
active: buildColor("blue_accent", "700"),
selected: buildColor("blue_accent", "600"),
text: buildColor("white", "100"),
loadingBackground: buildColor("blue_accent", "200"),
border: "none"
},
secondary: {
background: buildColor("white", "100"),
hover: buildColor("blue", "000"),
active: buildColor("blue", "100"),
selected: buildColor("blue", "100"),
text: buildColor("grey", "900"),
border: `1px solid ${buildColor("blue", "100")}`
},
secondary_alt: {
background: buildColor("white", "20"),
hover: buildColor("white", "50"),
active: buildColor("white", "10"),
selected: buildColor("black", "50"),
text: buildColor("white", "100"),
border: "none"
},
tertiary: {
background: "transparent",
hover: buildColor("blue_accent", "100"),
active: buildColor("blue", "200"),
selected: buildColor("blue", "100"),
text: buildColor("blue_accent", "500"),
loadingBackground: buildColor("blue", "100"),
border: "none"
},
tertiary_alt: {
background: "transparent",
hover: buildColor("white", "10"),
active: buildColor("white", "20"),
selected: buildColor("white", "20"),
text: buildColor("white", "100"),
border: "none"
},
bet: {
background: buildColor("green", "500"),
hover: buildColor("green", "600"),
active: buildColor("green", "700"),
selected: buildColor("green", "600"),
text: buildColor("white", "100"),
loadingBackground: buildColor("green", "100"),
border: "none"
},
marketing: {
background: buildColor("yellow", "500"),
hover: buildColor("yellow", "600"),
active: buildColor("yellow", "700"),
selected: buildColor("yellow", "600"),
text: buildColor("grey", "900"),
loadingBackground: buildColor("yellow", "100"),
border: "none"
},
delete: {
background: buildColor("red", "500"),
hover: buildColor("red", "400"),
active: buildColor("red", "600"),
selected: buildColor("red", "600"),
text: buildColor("white", "100"),
loadingBackground: buildColor("red", "100"),
border: "none"
},
shadow: {
background: buildColor("black", "50"),
hover: buildColor("grey", "900"),
active: buildColor("black", "70"),
selected: buildColor("black", "70"),
text: buildColor("white", "100"),
border: "none"
},
non_styled: {}
};
export const getType = (type) => TYPES[type];
export const getSize = (size) => SIZES[size];
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/Buttons/styled-components.js
import { Link } from "react-router-dom";
import styled, { css } from "styled-components";
import ButtonDefault from "./default";
import { getSize, getType } from "./styles";
import buildColor from "../../_static/ColorPalette";
// Button
export const ButtonComp = styled(ButtonDefault)`
height: ${(props) => props.$sizeSpecs.height};
width: ${(props) => props.$isStretched && "100%"};
padding: ${(props) => props.$sizeSpecs.padding};
font-size: ${(props) => props.$sizeSpecs.fontSize};
font-family: ${(props) => (props.fontFamily ? props.fontFamily : "inherit")};
&& {
background-color: ${(props) =>
props.isSelected && !props.$isDisabled
? props.$typeSpecs.selected
: props.$typeSpecs.background};
background-color: ${(props) =>
props.isLoading && props.$typeSpecs.loadingBackground};
}
color: ${(props) => props.$typeSpecs.text};
border: ${(props) => props.$typeSpecs.border};
font-weight: ${(props) => (props.isBold ? "bold" : "normal")};
text-transform: ${(props) =>
props.isUppercase ? "uppercase" : props.textTransform};
border-radius: ${(props) => (props.$hasRoundedCorners ? "2px" : 0)};
${(props) =>
props.$hasShadow && `box-shadow: 0px 2px 2px rgba(17, 43, 68, 0.15);`}
${({ customMarginBottom }) =>
customMarginBottom > 0 ? `margin-bottom: ${customMarginBottom}px;` : ""}
/* only add hover state for fine pointers, meaning that only on desktops using a mouse the hover state will work */
@media (pointer: fine) {
&:hover {
background-color: ${(props) =>
!props.$isDisabled && props.$typeSpecs.hover};
}
}
&:active {
background-color: ${(props) =>
!props.$isDisabled && props.$typeSpecs.active};
/* on touch devices (coarse), the active color should be the hover spec according to the style guide on zeplin */
@media (pointer: coarse) {
background-color: ${(props) =>
!props.$isDisabled && props.$typeSpecs.hover};
}
}
& > span {
display: flex;
width: 100%;
height: 100%;
align-items: center;
justify-content: center;
line-height: 1;
}
`;
export const StyledLink = styled(Link)`
display: inline-flex;
align-items: center;
justify-content: center;
width: ${(props) => props.$isStretched && "100%"};
height: ${(props) => props.$sizeSpecs.height};
padding: ${(props) => props.$sizeSpecs.padding};
font-size: ${(props) => props.$sizeSpecs.fontSize};
background-color: ${(props) => props.$typeSpecs.background};
color: ${(props) => props.$typeSpecs.text};
opacity: ${(props) => (props.$isDisabled ? 0.3 : 1)};
border: ${(props) => props.$typeSpecs.border};
font-weight: ${(props) => (props.isBold ? "bold" : "normal")};
text-decoration: none;
text-transform: ${(props) => (props.isUppercase ? "uppercase" : "normal")};
border-radius: ${(props) => (props.$hasRoundedCorners ? "2px" : 0)};
line-height: 1;
${(props) =>
props.$hasShadow && `box-shadow: 0px 2px 2px rgba(17, 43, 68, 0.15);`}
/* only add hover state for fine pointers, meaning that only on desktops using a mouse the hover state will work */
@media (pointer: fine) {
&:hover {
background-color: ${(props) =>
!props.$isDisabled && props.$typeSpecs.hover};
}
}
&:active {
background-color: ${(props) =>
!props.$isDisabled && props.$typeSpecs.active};
/* on touch devices (coarse), the active color should be the hover spec according to the style guide on zeplin */
@media (pointer: coarse) {
background-color: ${(props) =>
!props.$isDisabled && props.$typeSpecs.hover};
}
}
`;
export const StyledRef = styled.a`
display: inline-flex;
align-items: center;
justify-content: center;
width: ${(props) => props.$isStretched && "100%"};
height: ${(props) => props.$sizeSpecs.height};
padding: ${(props) => props.$sizeSpecs.padding};
font-size: ${(props) => props.$sizeSpecs.fontSize};
background-color: ${(props) => props.$typeSpecs.background};
color: ${(props) => props.$typeSpecs.text};
opacity: ${(props) => (props.$isDisabled ? 0.3 : 1)};
border: ${(props) => props.$typeSpecs.border};
font-weight: ${(props) => (props.isBold ? "bold" : "normal")};
text-decoration: none;
text-transform: ${(props) => (props.isUppercase ? "uppercase" : "normal")};
border-radius: ${(props) => (props.$hasRoundedCorners ? "2px" : 0)};
line-height: 1;
${(props) =>
props.$hasShadow && `box-shadow: 0px 2px 2px rgba(17, 43, 68, 0.15);`}
/* only add hover state for fine pointers, meaning that only on desktops using a mouse the hover state will work */
@media (pointer: fine) {
&:hover {
background-color: ${(props) =>
!props.$isDisabled && props.$typeSpecs.hover};
}
}
&:active {
background-color: ${(props) =>
!props.$isDisabled && props.$typeSpecs.active};
/* on touch devices (coarse), the active color should be the hover spec according to the style guide on zeplin */
@media (pointer: coarse) {
background-color: ${(props) =>
!props.$isDisabled && props.$typeSpecs.hover};
}
}
`;
const appendHref = ({ component, isExternal }) =>
isExternal ? styled.a.attrs((props) => ({ href: props.to })) : component;
// Link
export const buildLink = (
tag,
type,
size,
isStretched,
isDisabled,
hasRoundedCorners,
isExternal
) => {
const sizeSpecs = getSize(size);
const typeSpecs = getType(type);
const StyledComp = appendHref({ component: styled(Link), isExternal })`
display: inline-flex;
align-items: center;
justify-content: center;
width: ${isStretched && "100%"};
height: ${sizeSpecs.height};
padding: ${sizeSpecs.padding};
font-size: ${sizeSpecs.fontSize};
background-color: ${typeSpecs.background};
color: ${typeSpecs.text};
opacity: ${isDisabled ? 0.3 : 1};
border: ${typeSpecs.border};
font-weight: ${(props) => (props.isBold ? "bold" : "normal")};
text-decoration: none;
text-transform: ${(props) => (props.isUppercase ? "uppercase" : "normal")};
border-radius: ${hasRoundedCorners ? "2px" : 0};
line-height: 1;
/* only add hover state for fine pointers, meaning that only on desktops using a mouse the hover state will work */
@media (pointer: fine) {
&:hover {
background-color: ${!isDisabled && typeSpecs.hover};
}
}
&:active {
background-color: ${!isDisabled && typeSpecs.active};
/* on touch devices (coarse), the active color should be the hover spec according to the style guide on zeplin */
@media (pointer: coarse) {
background-color: ${!isDisabled && typeSpecs.hover};
}
}
`;
return tag === "link" ? StyledComp : StyledComp.withComponent(tag);
};
// Promos
const OverwriteStyles = css`
width: 56px;
padding: 0;
font-size: 10px;
display: flex;
flex-direction: column;
`;
export const Promos = styled(
buildLink("link", "marketing", "big", false, false, true)
)`
${OverwriteStyles};
`;
export const PromosExternal = styled(
buildLink("a", "marketing", "big", false, false, true, true)
)`
${OverwriteStyles};
`;
export const OptedInAlt = styled(
buildLink("link", "secondary_alt", "big", false, false, true)
)`
${OverwriteStyles};
`;
export const OptedIn = styled(
buildLink("link", "secondary", "big", false, false, true)
)`
${OverwriteStyles};
`;
// MyBets
export const RoundBtnComp = styled.button`
display: inline-flex;
justify-content: center;
align-items: center;
outline: none;
height: 44px;
width: 44px;
background-color: ${buildColor("white", "100")};
border-radius: 50%;
border: 1px solid ${buildColor("blue", "100")};
z-index: 20;
text-align: center;
pointer-events: all;
&:active {
background-color: ${buildColor("blue_accent", "100")};
}
`;
webpack://frontend-mybets/../../node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteral.js
export default function _taggedTemplateLiteral(strings, raw) {
if (!raw) {
raw = strings.slice(0);
}
return Object.freeze(Object.defineProperties(strings, {
raw: {
value: Object.freeze(raw)
}
}));
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/CircularLoader/styled-components.js
import styled from "styled-components";
import buildColor from "../ColorPalette";
export const CircularBackground = styled.div`
position: absolute;
display: block;
height: ${({ size }) => (size === "small" ? `24px` : "38px")};
width: ${({ size }) => (size === "small" ? `24px` : "38px")};
`;
export const Bar = styled.span`
display: block;
position: absolute;
inset: 0;
margin: auto;
&::before,
&::after {
content: "";
display: block;
position: absolute;
inset: 0;
margin: auto;
height: ${({ size }) => (size === "small" ? `18px` : "32px")};
width: ${({ size }) => (size === "small" ? `18px` : "32px")};
border-radius: 50%;
}
&::before {
border: 3px solid
${({ backgroundColor }) => backgroundColor || buildColor("green", "800")};
border-top: 3px solid
${({ borderColor }) => borderColor || buildColor("white", "100")};
-webkit-animation: loader-2-3 1.5s cubic-bezier(0.77, 0, 0.175, 1) infinite;
animation: loader-2-3 1.5s cubic-bezier(0.77, 0, 0.175, 1) infinite;
}
@keyframes loader-2-3 {
0% {
-webkit-transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(360deg);
}
}
@keyframes loader-2-3 {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/CircularLoader/index.jsx
import React from "react";
import { CircularBackground, Bar } from "./styled-components";
const CircularLoader = ({ size, borderColor, backgroundColor }) => (
<CircularBackground size={size}>
<Bar
size={size}
borderColor={borderColor}
backgroundColor={backgroundColor}
/>
</CircularBackground>
);
export default CircularLoader;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/Buttons/button.jsx
import React, { PureComponent } from "react";
import { noop } from "lodash";
import { ButtonComp } from "./styled-components";
import { getSize, getType } from "./styles";
import CircularLoader from "../../_static/CircularLoader";
export default class Button extends PureComponent {
static defaultProps = {
children: null,
className: "",
onClick: noop,
size: "default",
type: "primary",
isDisabled: false,
isSelected: false,
hasRoundedCorners: true,
isStretched: false,
isUppercase: true,
textTransform: "normal",
isBold: true,
hasShadow: false,
qaLabel: "",
fontFamily: "inherit",
isLoading: false,
loadingBorderColor: "",
loadingBackgroundColor: "",
optionalData: null,
customMarginBottom: 0
};
render() {
const sizeSpecs = getSize(this.props.size);
const typeSpecs = getType(this.props.type);
const compProps = {
$sizeSpecs: sizeSpecs,
$typeSpecs: typeSpecs,
isSelected: this.props.isSelected,
$isStretched: this.props.isStretched,
isUppercase: this.props.isUppercase,
textTransform: this.props.textTransform,
isBold: this.props.isBold,
$hasShadow: this.props.hasShadow,
$isDisabled: this.props.isDisabled,
$hasRoundedCorners: this.props.hasRoundedCorners,
...(this.props.qaLabel !== ""
? {
qaLabel: this.props.qaLabel
}
: {}),
fontFamily: this.props.fontFamily,
isLoading: this.props.isLoading,
optionalData: this.props.optionalData
};
return (
<ButtonComp
{...compProps}
className={this.props.className}
isDisabled={this.props.isDisabled}
customMarginBottom={this.props.customMarginBottom}
onClick={this.props.onClick}
>
{this.props.isLoading ? (
<span>
<CircularLoader
borderColor={this.props.loadingBorderColor}
backgroundColor={this.props.loadingBackgroundColor}
/>
</span>
) : (
<span
{...(compProps.optionalData
? { "data-optional": compProps.optionalData }
: {})}
>
{this.props.children}
</span>
)}
</ButtonComp>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/Video/OverlayControls/styled-components.js
import styled from "styled-components";
import Button from "../../../_atom/Buttons/button";
import buildColor from "../../../_static/ColorPalette";
export const Container = styled.div`
position: absolute;
top: 0;
left: 0;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
height: 100%;
width: 100%;
padding: 8px;
z-index: 2000;
background-color: ${(props) => props.isVisible && buildColor("black", "30")};
`;
export const ExpandButton = styled(Button)`
justify-self: stretch;
`;
export const VolumeButton = styled(Button)`
justify-self: stretch;
margin-right: 8px;
`;
export const PlayButton = styled.button`
display: flex;
height: 40px;
padding: 0 8px;
background-color: ${buildColor("black", "30")};
border-radius: 2px;
outline: none;
cursor: pointer;
/* only add hover state for fine pointers, meaning that only on desktops using a mouse the hover state will work */
@media (pointer: fine) {
&:hover {
background-color: ${buildColor("black", "30")};
}
}
&:active {
background-color: ${buildColor("black", "50")};
/* on touch devices (coarse), the active color should be the hover spec according to the style guide on zeplin */
@media (pointer: coarse) {
background-color: ${buildColor("black", "30")};
}
}
& > span {
display: flex;
width: 100%;
height: 100%;
align-items: center;
justify-content: center;
}
`;
export const LeftCornerOverlay = styled.div`
position: absolute;
top: 0;
right: 0;
display: flex;
padding: 8px;
`;
// TODO: TO BE REMOVED ON THE FUTURE
export const FeedBackContainer = styled.div`
position: relative;
place-self: stretch stretch;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
& span {
padding-top: 4px;
}
`;
export const SkipButton = styled.button`
background-color: ${buildColor("black", "60")};
color: ${buildColor("white", "100")};
width: 57px;
height: 24px;
top: calc(50% - 12px);
border-radius: 2px;
padding: 0 8px;
font-weight: bold;
font-size: 12px;
display: flex;
align-items: center;
justify-content: space-between;
cursor: pointer;
&.rewButton {
position: absolute;
left: 8px;
}
&.fwdButton {
position: absolute;
right: 8px;
}
`;
export const PlayButtonLabel = styled.span`
text-transform: uppercase;
color: ${buildColor("white", "100")};
font-size: 12px;
user-select: none;
`;
export const InnerPlayButtonWrapper = styled.div`
display: flex;
flex-direction: column;
align-items: center;
`;
export const WatchButton = styled.button`
color: ${buildColor("white", "100")};
font-size: 12px;
text-transform: uppercase;
padding: 7px 8px;
background-color: ${buildColor("black", "30")};
position: absolute;
top: 8px;
left: calc(50% - 52px);
cursor: pointer;
border-radius: 2px;
&.replay {
left: calc(50% - 45px);
}
/* only add hover state for fine pointers, meaning that only on desktops using a mouse the hover state will work */
@media (pointer: fine) {
&:hover {
background-color: ${buildColor("black", "30")};
}
}
&:active {
background-color: ${buildColor("black", "50")};
/* on touch devices (coarse), the active color should be the hover spec according to the style guide on zeplin */
@media (pointer: coarse) {
background-color: ${buildColor("black", "30")};
}
}
`;
export const FullUnmuteButton = styled(Button)`
margin-right: 8px;
& svg {
margin-right: 6px;
}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/Text/index.jsx
import React, { PureComponent } from "react";
import { buildTextFn } from "./styled-components";
export const buildText = (textDataInit) => buildTextFn(textDataInit);
export default class Text extends PureComponent {
static defaultProps = {
tag: "span",
children: null,
fontSize: -1,
bold: false,
color: "inherit",
align: "inherit",
uppercase: false,
capitalize: false,
ellipsis: false,
className: "",
qaLabel: "",
lineHeight: ""
};
render() {
const Txt = buildText({
tag: this.props.tag,
fontSize: this.props.fontSize,
color: this.props.color,
bold: this.props.bold,
align: this.props.align,
uppercase: this.props.uppercase,
capitalize: this.props.capitalize,
ellipsis: this.props.ellipsis,
qaLabel: this.props.qaLabel,
lineHeight: this.props.lineHeight
});
return <Txt className={this.props.className}>{this.props.children}</Txt>;
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/Text/styled-components.js
import styled from "styled-components";
import { fontNormal } from "../../_static/Typography";
// eslint-disable-next-line import/prefer-default-export
export const buildTextFn = (props) => {
const defaultProp = {
tag: "span",
fontSize: -1,
color: "inherit",
bold: false,
align: "inherit",
uppercase: false,
capitalize: false,
ellipsis: false,
qaLabel: "",
lineHeight: ""
};
const textData = { ...defaultProp, ...props };
const TextAtom = styled[textData.tag].attrs({
...(textData.qaLabel !== ""
? {
"data-qa-label": textData.qaLabel
}
: {})
})`
font-family: ${fontNormal};
font-size: ${textData.fontSize >= 0 && `${textData.fontSize}px`};
font-weight: ${textData.bold && "bold"};
color: ${textData.color !== "inherit" && textData.color};
text-transform: ${(textData.uppercase && "uppercase") ||
(textData.capitalize && "capitalize")};
text-align: ${textData.align !== "inherit" && textData.align};
line-height: ${textData.lineHeight || "normal"};
`;
return !textData.ellipsis
? TextAtom
: styled(TextAtom)`
display: block;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
`;
};
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Spinners/index.jsx
import React, { PureComponent } from "react";
import styled, { keyframes } from "styled-components";
import buildColor from "../ColorPalette";
const spinerwingfade = keyframes`
0% {
opacity: 0.85;
}
50% {
opacity: 0.25;
}
100% {
opacity: 0.25;
}
`;
const Spinnerwing = styled.div`
position: absolute;
left: 44.5%;
top: 37%;
width: 10%;
height: 25%;
border-radius: 50%/20%;
background-color: ${(props) => props.color};
animation: ${spinerwingfade} 1s linear infinite;
animation-play-state: running;
&:nth-child(1) {
animation-delay: -1.6666666667s;
transform: rotate(30deg) translate(0, -150%);
}
&:nth-child(2) {
animation-delay: -1.5833333333s;
transform: rotate(60deg) translate(0, -150%);
}
&:nth-child(3) {
animation-delay: -1.5s;
transform: rotate(90deg) translate(0, -150%);
}
&:nth-child(4) {
animation-delay: -1.4166666667s;
transform: rotate(120deg) translate(0, -150%);
}
&:nth-child(5) {
animation-delay: -1.3333333333s;
transform: rotate(150deg) translate(0, -150%);
}
&:nth-child(6) {
animation-delay: -1.25s;
transform: rotate(180deg) translate(0, -150%);
}
&:nth-child(7) {
animation-delay: -1.1666666667s;
transform: rotate(210deg) translate(0, -150%);
}
&:nth-child(8) {
animation-delay: -1.0833333333s;
transform: rotate(240deg) translate(0, -150%);
}
&:nth-child(9) {
animation-delay: -1s;
transform: rotate(270deg) translate(0, -150%);
}
&:nth-child(10) {
animation-delay: -0.9166666667s;
transform: rotate(300deg) translate(0, -150%);
}
&:nth-child(11) {
animation-delay: -0.8333333333s;
transform: rotate(330deg) translate(0, -150%);
}
&:nth-child(12) {
animation-delay: -0.75s;
transform: rotate(360deg) translate(0, -150%);
}
`;
const SpinnerElement = styled.div`
position: relative;
width: ${(props) => `${props.width}px`};
height: ${(props) => `${props.height}px`};
`;
export default class Spinner extends PureComponent {
static defaultProps = {
width: 24,
height: 24,
color: buildColor("black", "100")
};
render() {
return (
<SpinnerElement
width={this.props.width}
height={this.props.height}
data-qa-label={this.props.qaLabel}
>
<Spinnerwing color={this.props.color} />
<Spinnerwing color={this.props.color} />
<Spinnerwing color={this.props.color} />
<Spinnerwing color={this.props.color} />
<Spinnerwing color={this.props.color} />
<Spinnerwing color={this.props.color} />
<Spinnerwing color={this.props.color} />
<Spinnerwing color={this.props.color} />
<Spinnerwing color={this.props.color} />
<Spinnerwing color={this.props.color} />
<Spinnerwing color={this.props.color} />
<Spinnerwing color={this.props.color} />
</SpinnerElement>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/FeedbackOverlay/styled-components.js
import styled, { keyframes } from "styled-components";
import buildColor from "../../_static/ColorPalette";
const ScaleAnimation = keyframes`
0% {
transform: scale(0);
opacity: 0;
}
100% {
transform: scale(1);
opacity: 1;
}
`;
const FadeAnimation = keyframes`
0% {
opacity: 0;
}
100% {
opacity: 1;
}
`;
export const Overlay = styled.div`
position: absolute;
inset: 0;
background-color: ${(props) => props.overlayBgColor};
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-transform: uppercase;
color: ${buildColor("white", "100")};
font-weight: bold;
font-size: 16px;
animation: ${FadeAnimation} 0.5s ease-in-out;
z-index: 9999;
`;
export const Circle = styled.div`
display: flex;
align-items: center;
justify-content: center;
width: 80px;
height: 80px;
border-radius: 100%;
margin-bottom: 16px;
`;
export const Success = styled(Circle)`
background-color: ${buildColor("green", "500")};
animation: ${ScaleAnimation} 0.5s;
`;
export const Error = styled(Circle)`
background-color: ${buildColor("red", "500")};
animation: ${ScaleAnimation} 0.5s;
`;
export const Warning = styled(Circle)`
background-color: ${buildColor("yellow", "500")};
animation: ${ScaleAnimation} 0.5s;
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/FeedbackOverlay/index.jsx
import React, { PureComponent } from "react";
import buildColor from "../../_static/ColorPalette";
import Icon from "../../_static/Icons";
import { tick, warning, close } from "../../_static/Icons/icons";
import Spinner from "../../_static/Spinners";
import { Overlay, Success, Error, Warning } from "./styled-components";
export default class FeedbackOverlay extends PureComponent {
static defaultProps = {
type: "loading",
message: "",
loadingIconColor: buildColor("white", "100"),
overlayBgColor: buildColor("black", "70")
};
renderIcon() {
switch (this.props.type) {
case "success":
return (
<Success data-qa-label="feedback-successIcon">
<Icon icon={tick} color={buildColor("white", "100")} size={50} />
</Success>
);
case "error":
return (
<Error data-qa-label="feedback-errorIcon">
<Icon icon={close} color={buildColor("white", "100")} size={50} />
</Error>
);
case "warning":
return (
<Warning data-qa-label="feedback-warningIcon">
<Icon icon={warning} color={buildColor("white", "100")} size={50} />
</Warning>
);
case "loading":
default:
return (
<Spinner
width={32}
height={32}
color={this.props.loadingIconColor}
data-qa-label="feedback-loadingIcon"
/>
);
}
}
render() {
return (
<Overlay
overlayBgColor={this.props.overlayBgColor}
data-qa-label="feedback"
>
{this.renderIcon()}
<span data-qa-label={`feedback-${this.props.type}`}>
{this.props.message}
</span>
</Overlay>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/Video/OverlayControls/index.jsx
import React, { Fragment } from "react";
import { noop } from "lodash";
import {
Container,
ExpandButton,
VolumeButton,
FullUnmuteButton,
PlayButton,
FeedBackContainer,
LeftCornerOverlay,
PlayButtonLabel,
InnerPlayButtonWrapper,
SkipButton,
WatchButton
} from "./styled-components";
import Icon from "../../../_static/Icons";
import buildColor from "../../../_static/ColorPalette";
import {
fullscreen,
fullscreenExit,
soundMute,
soundPlay,
info,
play,
videoReplay,
refresh,
pause,
doubleArrowLeft,
doubleArrowRight
} from "../../../_static/Icons/icons";
import Text from "../../../_atom/Text";
import FeedbackOverlay from "../../../_atom/FeedbackOverlay";
class OverlayControls extends React.Component {
static defaultProps = {
renderOnOverlay: noop,
skipToggleHandler: noop,
liveButtonCallback: noop,
showControls: true,
loading: false,
isReplay: false,
hasLiveStream: false,
hasReplayStream: false,
isFullUnmute: false,
fwdButtonIsVisible: false,
rewButtonIsVisible: false,
hasNewStreamVideo: false,
disableFullscreen: false
};
playIcon = () => {
let returnIcon = play;
if (!this.props.playing && this.props.isReplay && this.props.ended) {
returnIcon = refresh;
} else if (!this.props.playing && this.props.isReplay) {
returnIcon = videoReplay;
} else if (this.props.playing) {
returnIcon = pause;
}
return returnIcon;
};
playButtonLabel = () => (this.props.ended ? "RESTART" : "REPLAY");
renderPlayButton = () => {
const isEndOfReplay = this.props.ended && this.props.isReplay;
const hasntEnded = !this.props.ended;
const hasNoErrorsLoading = !this.props.loading && !this.props.error;
const showPlayButton =
(isEndOfReplay || hasntEnded) &&
(hasNoErrorsLoading ||
(!this.props.isReplay && this.props.hasNewStreamVideo));
return (
showPlayButton && (
<PlayButton type="shadow" onClick={this.props.playHandler}>
<InnerPlayButtonWrapper>
<Icon
size={this.props.isReplay && !this.props.playing ? 16 : 24}
icon={this.playIcon()}
color={buildColor("white", "100")}
/>
{this.props.isReplay && !this.props.playing && (
<PlayButtonLabel>{this.playButtonLabel()}</PlayButtonLabel>
)}
</InnerPlayButtonWrapper>
</PlayButton>
)
);
};
renderWatchButton = () => {
const buttonLabel = this.props.isReplay ? "WATCH LIVE" : "WATCH REPLAY";
return (
<WatchButton
className={this.props.isReplay ? "replay" : ""}
onClick={this.props.liveButtonCallback}
>
{buttonLabel}
</WatchButton>
);
};
renderSkipButtonLabel = (actionType) =>
actionType === "fwd" ? (
<Fragment>
<span>15s</span>
<Icon
size={16}
icon={doubleArrowRight}
color={buildColor("white", "100")}
/>
</Fragment>
) : (
<Fragment>
<Icon
size={16}
icon={doubleArrowLeft}
color={buildColor("white", "100")}
/>
<span>15s</span>
</Fragment>
);
renderVideoOptions = () => (
<Fragment>
<LeftCornerOverlay>
{this.props.isFullUnmute &&
!this.props.loading &&
this.props.playing ? (
<FullUnmuteButton
type="secondary"
qaLabel="full-unMute-btn"
onClick={this.props.muteHandler}
>
<Icon size={16} icon={soundMute} />
<span>tap to unmute</span>
</FullUnmuteButton>
) : (
<VolumeButton type="shadow" onClick={this.props.muteHandler}>
<Icon
size={16}
icon={this.props.muted ? soundMute : soundPlay}
color={buildColor("white", "100")}
/>
</VolumeButton>
)}
{!this.props.disableFullscreen && (
<ExpandButton type="shadow" onClick={this.props.fullscreenHandler}>
<Icon
size={16}
icon={this.props.fullscreen ? fullscreenExit : fullscreen}
color={buildColor("white", "100")}
/>
</ExpandButton>
)}
</LeftCornerOverlay>
{/* this need to be replaced by feedback component */}
{((!this.props.isReplay && this.props.ended) ||
(this.props.error &&
(this.props.isReplay || !this.props.hasNewStreamVideo))) && (
<FeedBackContainer>
<Icon icon={info} color={buildColor("white", "100")} size={16} />
<Text fontSize={12} color={buildColor("white", "100")}>
The streaming is not available
</Text>
</FeedBackContainer>
)}
{this.props.hasLiveStream &&
this.props.hasReplayStream &&
this.renderWatchButton()}
{this.renderPlayButton()}
{this.props.isReplay && (
<Fragment>
{this.props.rewButtonIsVisible && (
<SkipButton
className="rewButton"
qaLabel="videoRewButton"
onClick={this.props.skipToggleHandler("rew")}
>
{this.renderSkipButtonLabel("rew")}
</SkipButton>
)}
{this.props.fwdButtonIsVisible && (
<SkipButton
className="fwdButton"
qaLabel="videoFwdButton"
onClick={this.props.skipToggleHandler("fwd")}
>
{this.renderSkipButtonLabel("fwd")}
</SkipButton>
)}
</Fragment>
)}
</Fragment>
);
render() {
const showOverLay =
(this.props.buffering && !this.props.error) || this.props.loading;
return (
<Container
onClick={() => this.props.clickHandler(true)}
isVisible={this.props.showControls}
>
{this.props.showControls && this.renderVideoOptions()}
{showOverLay &&
(this.props.isReplay || !this.props.hasNewStreamVideo) && (
<FeedbackOverlay />
)}
{this.props.renderOnOverlay(this.props.showControls)}
</Container>
);
}
}
export default OverlayControls;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/Video/styled-components.js
import styled, { css } from "styled-components";
import buildColor from "../../_static/ColorPalette";
export const Container = styled.div`
position: relative;
display: flex;
${(props) =>
props.containerHeight
? css`
height: ${props.containerHeight}px;
max-height: ${props.containerHeight}px;
`
: css`
width: 100%;
height: 100%;
`};
flex-shrink: 0;
align-items: center;
justify-content: center;
${(props) =>
props.background
? css`
background-image: url("${props.background}");
background-size: 100% 100%;
`
: css`
background-color: ${buildColor("black", "100")};
`};
& canvas {
${(props) => props.hideCanvas && "display: none;"}
}
`;
export const StyledVideo = styled.video`
height: 100%;
width: 100%;
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/Video/Stream/styled-components.js
import styled from "styled-components"; const StyledStream = styled.ins` height: 100%; width: 100%; `; export default StyledStream;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/Video/Stream/index.jsx
import React, { useEffect, useCallback } from "react";
import { noop, get } from "lodash";
import StyledStream from "./styled-components";
const StreamVideo = (props) => {
const bindVideoRef = () => {
const videoElem = document.querySelector("video");
if (videoElem) {
props.setVideoElement(videoElem);
const playerId = videoElem.id
.replace("h5live-player_", "")
.replace("_html5_api", "")
.replace("player_", "");
const player = window.RCN.players[playerId];
if (player) {
props.setupPlayer(player);
}
}
};
useEffect(() => {
if (window.RCN) {
window.RCN.addRCNEventHandler("h2livePlay", props.onPlay);
window.RCN.addRCNEventHandler("h2liveReady", bindVideoRef);
}
return () => {
if (window.RCN) {
window.RCN.removeRCNEventHandler("h2livePlay", props.onPlay);
window.RCN.removeRCNEventHandler("h2liveReady", bindVideoRef);
}
};
}, []);
const refCallback = useCallback((node) => {
if (node) {
bindVideoRef();
}
});
const isIosTablet =
get(window, "__TVG_GLOBALS__.PRODUCT") === "ios2" &&
get(window, "__TVG_GLOBALS__.DEVICE") === "tablet";
return (
<StyledStream
data-referer="TVG"
data-hash={props.dataHash}
data-timestamp={props.dataTimestamp}
data-stream={props.dataStream}
data-autoplay="1"
data-muted="1"
data-hd={props.dataQuality}
data-speed={props.dataQuality === "1" ? "771" : "400"}
data-hidecontrols="1"
data-poster="none"
data-forcetech={isIosTablet ? "iosh2live" : undefined}
ref={refCallback}
/>
);
};
StreamVideo.defaultProps = {
dataHash: "",
dataTimestamp: "",
dataStream: "",
dataQuality: "",
onPlay: noop,
setVideoElement: noop,
setupPlayer: noop
};
export default StreamVideo;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/Video/index.jsx
import React from "react";
import {
debounce,
get,
isNumber,
noop,
isFunction,
isEqual,
isUndefined,
attempt,
isError,
negate
} from "lodash";
import OverlayControls from "./OverlayControls";
import { Container, StyledVideo } from "./styled-components";
import StreamVideo from "./Stream";
export const calcVideoContainerHeight = () => {
const width = get(window, "innerWidth");
return isNumber(width) ? Math.min(Math.round((width / 16) * 9), 284) : 180;
};
class Video extends React.Component {
static defaultProps = {
src: {
sd: null,
hd: null,
replay: null
},
mtp: 0,
feedSwitchLoading: false,
raceStatus: "IC",
error: false,
isReplay: false,
backGroundImage: null,
inlineVideo: false,
onVideoMute: noop,
onVideoFullScreen: noop,
onVideoPlay: noop,
onVideoPause: noop,
onVideoSuccess: noop,
onVideoError: noop,
renderOnOverlay: noop,
startCallback: noop,
errorCallback: noop,
videoFullscreenTilt: false,
deviceLockRotationToggle: noop,
reloadStreams: () => new Promise(noop),
onSwitchVideoType: noop,
onNavigateVideo: noop,
isAutoPlay: false,
hasNewStreamVideo: false,
disableFullscreen: false
};
constructor(props) {
super(props);
this.state = {
controlsVisible: true,
quality: "hd",
playing: this.props.isAutoPlay,
fullscreen: false,
muted: this.props.isAutoPlay,
isFullUnmute: true,
ended: false,
buffering: false,
loading: true,
loadingTimeout: setTimeout(() => {
this.setState({
loading: false,
feedSwitchLoading: false,
error: true
});
}, 10000),
error: false,
skipping: false,
live: !props.isReplay,
raceId: props.raceId,
feedSwitchLoading: false,
videoSRC: !this.props.isReplay
? this.props.src.hd
: this.props.src.replay,
src: {
sd: get(this.props, "sd", null),
hd: get(this.props, "hd", null),
replay: get(this.props, "replay", null)
},
retry: 0,
updateIndex: 0,
autoPlay: this.props.isAutoPlay
};
// big hack to play videos on chrome
if (typeof window !== "undefined" && !!window.chrome) {
attempt(() => {
const element = document.getElementById("videoHack");
element.classList.add("videoHack");
});
}
}
componentDidMount() {
this.props.reloadStreams();
document.addEventListener(
"webkitfullscreenchange",
this.exitFullScreenMobile,
true
);
document.addEventListener(
"mozfullscreenchange",
this.exitFullScreenMobile,
true
);
window.addEventListener("resize", this.updateVideoSize);
window.addEventListener("online", this.restartVideo, false);
if (this.props.videoFullscreenTilt) {
window.addEventListener("orientationchange", this.orientationChange);
this.addBackgroundRunDetect();
}
let hidden;
let visibilityChange;
if (typeof document.hidden !== "undefined") {
visibilityChange = "visibilitychange";
} else if (typeof document.msHidden !== "undefined") {
visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
visibilityChange = "webkitvisibilitychange";
}
if (
typeof document.addEventListener !== "undefined" &&
hidden !== undefined
) {
document.addEventListener(
visibilityChange,
this.handleVisibilityChange,
false
);
}
}
shouldComponentUpdate(nextProps, nextState) {
return (
!isEqual(nextProps.src, this.props.src) ||
!isEqual(nextState, this.state) ||
!isEqual(nextProps, this.props)
);
}
getSnapshotBeforeUpdate(prevProps, prevState) {
if (prevState.videoSRC !== this.state.videoSRC) {
attempt(() => {
const { id } = this.player;
this.player.cleanupConvivaSession();
this.streamPlayer.destroy();
setTimeout(() => {
delete window.RCN.players[id];
}, 1000);
});
}
return null;
}
componentDidUpdate(nextProps) {
if (!isEqual(this.props.raceId, nextProps.raceId)) {
this.closeControlsDebounce.cancel();
}
}
static getDerivedStateFromProps(props, state) {
// When an error occurs
if (props.error) {
props.onVideoError("The streaming is not available");
return {
...state,
playing: false,
controlsVisible: true,
error: true,
loading: false,
feedSwitchLoading: false,
skipping: false
};
}
const srcAndRaceHasChanged = !isEqual(state.src, props.src);
if (srcAndRaceHasChanged) {
if (state.feedSwitchLoading && state.loadingTimeout) {
clearTimeout(state.loadingTimeout);
}
if (state.raceId !== props.raceId) {
const shouldGoToLive =
(!state.live && state.src.replay && !props.src.replay) ||
(state.live && !props.src.replay);
const hasReplay = !!props.src.replay;
const live = state.playing ? shouldGoToLive : !hasReplay;
const newSrc = live ? props.src[state.quality] : props.src.replay;
return {
...state,
raceId: props.raceId,
controlsVisible: true,
live,
ended: false,
feedSwitchLoading:
newSrc !== state.videoSRC ? true : state.feedSwitchLoading,
src: props.src,
retry: 0,
error: false,
videoSRC: newSrc
};
}
const newSrc = state.live ? props.src[state.quality] : props.src.replay;
return {
...state,
src: props.src,
ended: false,
feedSwitchLoading:
newSrc !== state.videoSRC ? true : state.feedSwitchLoading,
videoSRC: newSrc,
retry: 0,
error: false
};
}
return null;
}
componentDidCatch() {
this.setState(
{
controlsVisible: true,
playing: false,
fullscreen: false,
skipping: false
},
() => {
this.fullscreenOff();
}
);
}
componentWillUnmount() {
// This is an hack. browser continue to download data if we don't change the src and load.
if (this.video || (this.streamPlayer && this.props.hasNewStreamVideo)) {
if (this.streamPlayer && this.props.hasNewStreamVideo) {
attempt(() => {
this.player.destroy();
this.player = null;
this.streamPlayer = null;
this.closeControlsDebounce.cancel();
});
} else {
this.video.pause();
this.video.src = "";
this.video.load();
this.closeControlsDebounce.cancel();
}
this.clearLoadingTimeout();
document.removeEventListener(
"webkitfullscreenchange",
this.exitFullScreenMobile,
true
);
document.removeEventListener(
"mozfullscreenchange",
this.exitFullScreenMobile,
true
);
window.removeEventListener("resize", this.updateVideoSize);
window.removeEventListener("online", this.restartVideo, false);
if (this.props.videoFullscreenTilt) {
window.removeEventListener("orientationchange", this.orientationChange);
this.props.deviceLockRotationToggle(true);
}
let hidden;
let visibilityChange;
if (typeof document.hidden !== "undefined") {
visibilityChange = "visibilitychange";
} else if (typeof document.msHidden !== "undefined") {
visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
visibilityChange = "webkitvisibilitychange";
}
if (
typeof document.addEventListener !== "undefined" &&
hidden !== undefined
) {
document.removeEventListener(
visibilityChange,
this.handleVisibilityChange,
false
);
}
}
attempt(() => {
const element = document.getElementById("videoHack");
element.classList.remove("videoHack");
});
}
onPlay = () => {
const muted = get(this.video, "muted");
this.setState(
{
playing: true,
autoPlay: true,
controlsVisible: true,
ended: false,
skipping: false,
muted
},
this.restartControlsDebounce
);
};
onBufferOn = () => {
this.clearLoadingTimeout();
this.setState({
controlsVisible: true,
buffering: true,
loading: false
});
};
onBufferStop = () => {
this.clearLoadingTimeout();
if (this.state.skipping || this.state.playing) {
this.setState(
{
controlsVisible: true,
buffering: false,
loading: false,
autoPlay: true,
feedSwitchLoading: false
},
this.restartControlsDebounce
);
} else {
this.setState({
controlsVisible: get(this, "video.paused", true),
buffering: false,
loading: false,
playing: !get(this, "video.paused", true),
feedSwitchLoading: false
});
}
this.props.startCallback();
};
onVideoEnded = () => {
this.setState({
playing: false,
controlsVisible: this.props.isReplay,
ended: true,
loading: false,
skipping: false
});
};
onError = () => {
this.props.onVideoError("The streaming is not available");
this.setState(
{
playing: false,
feedSwitchLoading: false,
controlsVisible: true,
error: !(this.state.retry < 2),
loading: false,
skipping: false
},
() => {
if (this.state.retry < 2) {
this.clearLoadingTimeout();
this.props.reloadStreams();
this.setState({
retry: this.state.retry + 1,
feedSwitchLoading: true,
loadingTimeout: setTimeout(() => {
this.setState({ feedSwitchLoading: false, error: true });
}, 10000)
});
}
}
);
const error = {
message: get(this.video, "error.message", ""),
code: get(this.video, "error.code", -1)
};
this.props.errorCallback(error);
};
onLoadedMeta = () => {
if (!this.state.autoPlay) {
this.clearLoadingTimeout();
}
this.setState({
controlsVisible: true,
loading: this.state.autoPlay ? this.state.loading : false,
feedSwitchLoading: this.state.autoPlay
? this.state.feedSwitchLoading
: false
});
};
onPause = () => {
// setTimeout need for exiting fullScreen playing work
setTimeout(() => {
this.setState({
playing: false,
autoPlay: false
});
}, 0);
};
onMute = () => {
const muted = !!(this.video && this.video.muted);
if (this.state.muted !== muted)
this.setState({
muted
});
};
setVideoElement = (video) => {
this.video = video;
};
setupPlayer = (player) => {
this.player = player;
this.streamPlayer = player.playerObj;
};
playToggle = (e) => {
if (e && e.stopPropagation) {
e.stopPropagation();
}
// big hack for rcn v2, only allow start video if its ready
const bigButton = document.getElementsByClassName("vjs-big-play-button");
if (
this.props.hasNewStreamVideo &&
!this.props.isReplay &&
!this.streamPlayer &&
!bigButton.length
) {
return;
}
this.setState(
(prevState) => ({
playing: !prevState.playing,
autoPlay: !prevState.playing,
controlsVisible: true,
ended: false,
skipping: false
}),
() => {
this.props.deviceLockRotationToggle(!this.state.playing);
if (this.state.playing) {
this.closeControlsDebounce.flush();
if (e) {
this.props.onVideoPlay();
}
return this.playVideo();
}
this.closeControlsDebounce.cancel();
if (e) {
this.props.onVideoPause();
}
return this.pauseVideo();
}
);
};
playVideo = () => {
if (this.state.live && this.streamPlayer && this.props.hasNewStreamVideo) {
this.streamPlayer.play();
} else if (this.video) {
this.video.play().catch(() => {
this.setState({
playing: false,
controlsVisible: true,
buffering: false,
skipping: false
});
});
}
};
pauseVideo = () => {
if (this.state.live && this.streamPlayer && this.props.hasNewStreamVideo) {
this.streamPlayer.pause();
} else if (this.video) {
this.video.pause();
}
};
addBackgroundRunDetect = () => {
let hidden;
let visibilityChange;
if (!isUndefined(document.hidden)) {
hidden = "hidden";
visibilityChange = "visibilitychange";
} else if (!isUndefined(document.msHidden)) {
hidden = "msHidden";
visibilityChange = "msvisibilitychange";
} else if (!isUndefined(document.webkitHidden)) {
hidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
}
if (!isUndefined(document.addEventListener) && !isUndefined(hidden)) {
document.addEventListener(
visibilityChange,
this.handleVisibilityChange,
false
);
}
};
handleVisibilityChange = (hiddenKey) => {
if (document[hiddenKey]) {
if (this.video && !this.state.fullscreen) {
this.setState({
playing: false,
fullscreen: false
});
this.video.pause();
this.exitFullScreenCrossDevice();
}
}
if (this.streamPlayer && this.props.hasNewStreamVideo) {
if (document.visibilityState === "visible") {
window.hl2functions.reloadPlayer(this.player.id);
} else {
this.streamPlayer.pause();
}
}
};
orientationChange = () => {
if (
(window.orientation === 90 || window.orientation === -90) &&
this.state.playing
) {
this.fullscreenOn(true);
} else if (this.state.playing) {
this.exitFullScreenCrossDevice(true);
}
};
exitFullScreenCrossDevice = (tilt = false) => {
const webkitExitFullscreen = get(this.video, "webkitExitFullscreen", null);
if (isFunction(webkitExitFullscreen)) {
this.video.webkitExitFullscreen();
this.exitFullScreenSafariMobile(tilt);
// hack to prevent video resizing in safari when coming out of full screen
this.hackToTriggerCssRepaint(
this.video,
"vjs-tech",
"object-fit: cover",
100
);
} else {
this.fullscreenOff();
this.exitFullScreenMobile(tilt);
}
};
updateVideoSize = () => {
setTimeout(() => {
window.scroll();
this.setState(
{
updateIndex: this.state.updateIndex + 1
},
() => {
window.scroll();
}
);
}, 300);
};
hackToTriggerCssRepaint(element, className, style, timeoutDelay) {
const { classList } = element;
if (classList.contains(className)) {
this.video.style = style;
setTimeout(() => {
this.video.style = "";
}, timeoutDelay);
}
}
exitFullScreenSafariMobile = (tilt = false) => {
// hack to prevent video resizing in safari when coming out of full screen
this.hackToTriggerCssRepaint(
this.video,
"vjs-tech",
"object-fit: cover",
500
);
this.setState(
{
fullscreen: false,
buffering: false
},
() => {
if (this.state.playing && get(this, "video.play")) {
setTimeout(() => {
if (this.streamPlayer) {
this.streamPlayer.play();
} else {
this.video.play().catch(console.log);
}
this.setState({
playing: true,
autoPlay: true
});
}, 1000);
}
}
);
this.video.removeEventListener(
"webkitendfullscreen",
this.exitFullScreenSafariMobile,
true
);
this.props.onVideoFullScreen(false, tilt);
};
muteVideo = () => {
this.props.onVideoMute(true);
this.video.muted = true;
};
unmuteVideo = () => {
this.props.onVideoMute(false);
this.video.muted = false;
};
skipToggleHandler = (skipType) => (e) => {
this.props.onNavigateVideo(skipType === "fwd");
const videoDuration = this.video.duration;
const bufferedVideo = this.video.buffered.length;
const incrementValue =
this.state.buffering && bufferedVideo < videoDuration
? bufferedVideo
: 15;
const increment = skipType === "fwd" ? incrementValue : -15;
const timeIsOverDuration =
skipType === "fwd" && this.video.currentTime + increment >= videoDuration;
const timeIsBellowZero =
skipType === "rew" && this.video.currentTime + increment <= 0;
if (e && e.stopPropagation) {
e.stopPropagation();
}
this.setState({ controlsVisible: true, skipping: true }, () => {
if (isFunction(this.closeControlsDebounce.cancel)) {
this.closeControlsDebounce.cancel();
}
this.closeControlsDebounce = debounce(() => this.closeControls(), 3000);
});
if (timeIsOverDuration) {
this.video.currentTime = videoDuration - 0.01;
} else if (timeIsBellowZero) {
this.video.currentTime = 0;
} else {
this.video.currentTime += increment;
}
};
exitFullScreenMobile = (tilt = false) => {
const isInFullScreen =
document.fullscreenElement ||
document.webkitFullscreenElement ||
document.mozFullScreenElement ||
document.msFullscreenElement;
if (!isInFullScreen) {
this.setState(
{
fullscreen: false
},
() => {
if (this.state.playing && get(this, "video.play")) {
setTimeout(() => {
if (this.streamPlayer) {
this.streamPlayer.play();
} else {
this.video.play().catch(console.log);
}
this.setState({
playing: true,
autoPlay: true
});
}, 1000);
}
}
);
this.props.onVideoFullScreen(false, tilt);
}
};
fullscreenOn = (tilt = false) => {
let fullScreenState = this.state.fullscreen;
if (get(this.video, "webkitSupportsFullscreen")) {
this.video.webkitEnterFullscreen();
this.video.addEventListener(
"webkitendfullscreen",
this.exitFullScreenSafariMobile,
true
);
fullScreenState = true;
} else if (this.container.requestFullscreen) {
this.container.requestFullscreen();
fullScreenState = true;
} else if (this.container.webkitRequestFullscreen) {
this.container.webkitRequestFullscreen();
fullScreenState = true;
} else if (this.container.mozRequestFullScreen) {
this.container.mozRequestFullScreen();
fullScreenState = true;
} else if (this.container.msRequestFullscreen) {
this.container.msRequestFullscreen();
fullScreenState = true;
}
if (get(window, "screen.orientation.lock")) {
setTimeout(() => {
window.screen.orientation.lock("landscape-primary");
}, 100);
}
this.setState({
fullscreen: fullScreenState
});
this.props.onVideoFullScreen(true, tilt);
// This can be added on future to lock landscape on fullscreenMode. Remember safari do not have this
// screen.orientation.lock('landscape');
};
fullscreenOff = () => {
let fullScreenState = this.state.fullscreen;
attempt(() => {
if (document.exitFullscreen) {
document.exitFullscreen();
fullScreenState = false;
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
fullScreenState = false;
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
fullScreenState = false;
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
fullScreenState = false;
}
this.setState({
fullscreen: fullScreenState
});
});
};
muteToggle = (e) => {
if (e && e.stopPropagation) {
e.stopPropagation();
}
if (this.video) {
this.setState(
(prevState) => ({
muted: !prevState.muted,
isFullUnmute: false
}),
() => {
if (this.state.muted) {
return this.muteVideo();
}
return this.unmuteVideo();
}
);
}
};
fullscreenToggle = (e) => {
if (e && e.stopPropagation) {
e.stopPropagation();
}
return this.fullscreenOn();
};
closeControls = () => {
this.setState({
controlsVisible: false,
skipping: false,
isFullUnmute: false
});
};
closeControlsDebounce = debounce(() => this.closeControls(), 3000);
restartControlsDebounce = () => {
if (isFunction(this.closeControlsDebounce.cancel)) {
this.closeControlsDebounce.cancel();
}
this.closeControlsDebounce();
};
showControls = (overrideSkipping = false) => {
// Controls are visible and skipping is not active, get controls to hide
if (
this.state.controlsVisible &&
(!this.state.skipping || overrideSkipping)
) {
this.setState(
{
controlsVisible: false
},
() => {
this.closeControlsDebounce.flush();
}
);
return;
}
// Otherwise, controls are not visible, get them to show
this.setState(
{
controlsVisible: true
},
() => {
if (!this.state.playing) {
this.closeControlsDebounce.cancel();
return;
}
this.closeControlsDebounce();
}
);
};
liveButtonCallback = (e) => {
if (e && e.stopPropagation) {
e.stopPropagation();
}
const live = !this.state.live;
this.props.onSwitchVideoType(live);
this.props.reloadStreams().then(() => {
this.setState({
playing: false,
autoPlay: this.state.playing,
retry: 0,
controlsVisible: true,
ended: false,
error: false,
feedSwitchLoading: true,
loadingTimeout: setTimeout(() => {
this.setState({ feedSwitchLoading: false, error: true });
}, 10000),
live,
videoSRC: live
? this.props.src[this.state.quality]
: this.props.src.replay
});
});
this.clearLoadingTimeout();
};
rewButtonIsVisible = () =>
this.video && this.state.playing ? this.video.currentTime >= 0 : false;
fwdButtonIsVisible = () =>
this.video && this.state.playing
? this.video.currentTime <= this.video.duration
: false;
restartVideo = () => {
if (
(this.state.playing && this.state.buffering) ||
this.state.error ||
this.state.feedSwitchLoading
) {
this.props.reloadStreams();
this.clearLoadingTimeout();
this.setState({
loading: false,
error: false,
buffering: false,
feedSwitchLoading: true,
loadingTimeout: setTimeout(() => {
this.setState({ feedSwitchLoading: false });
}, 10000),
controlsVisible: true,
playing: false,
autoPlay: false
});
}
};
clearLoadingTimeout = () => {
if (this.state.loadingTimeout) {
clearTimeout(this.state.loadingTimeout);
}
};
player;
streamPlayer;
video;
container;
isVideoReplay = (hasReplaySrc) => !this.state.live && hasReplaySrc;
hasVideoReplaySrc = () => !!this.props.src.replay;
renderLiveVideo = () => {
let streamHash = "";
let streamTimestamp = "";
let dataStream = "";
let hd = "";
const url = get(this, `props.src[${get(this, "state.quality", "")}]`, "");
if (url) {
const streamUrl = attempt((urlArg) => new URL(urlArg), url);
if (negate(isError)(streamUrl)) {
streamHash = streamUrl.searchParams.get("h");
streamTimestamp = streamUrl.searchParams.get("t");
dataStream = streamUrl.searchParams.get("stream");
hd = streamUrl.searchParams.get("hd");
} else {
console.log("ERROR IN URL:", streamUrl);
}
}
return (
<StreamVideo
dataHash={streamHash}
dataTimestamp={streamTimestamp}
dataStream={dataStream}
dataQuality={hd}
onPlay={this.onPlay}
setVideoElement={this.setVideoElement}
setupPlayer={this.setupPlayer}
/>
);
};
render() {
const hasLiveSrc = !!this.props.src[this.state.quality];
const hasReplaySrc = this.hasVideoReplaySrc();
const isReplay = this.isVideoReplay(hasReplaySrc);
return (
<Container
background={this.state.error && this.props.backGroundImage}
fullscreen={this.state.fullscreen}
hideCanvas={this.state.controlsVisible && !this.state.playing}
containerHeight={!this.props.inlineVideo && calcVideoContainerHeight()}
ref={(c) => {
if (c) {
this.container = c;
}
}}
>
{!!this.state.videoSRC &&
(!this.props.hasNewStreamVideo || isReplay ? (
<StyledVideo
fullscreen={this.state.fullscreen}
ref={(c) => {
if (c) {
this.video = c;
}
}}
src={this.state.videoSRC}
onEnded={this.onVideoEnded}
onWaiting={this.onBufferOn}
onError={this.onError}
onPause={this.onPause}
onLoadedData={this.props.onVideoSuccess}
onLoadedMetadata={this.onLoadedMeta}
onVolumeChange={this.onMute}
onPlaying={this.onBufferStop}
onCanPlay={this.onBufferStop}
playsInline
autoPlay={this.state.autoPlay}
muted={this.state.muted}
preload="metadata"
/>
) : (
this.renderLiveVideo()
))}
<OverlayControls
showControls={this.state.controlsVisible}
loading={this.state.feedSwitchLoading || this.state.loading}
clickHandler={this.showControls}
playing={this.state.playing}
playHandler={this.playToggle}
muted={this.state.muted}
isFullUnmute={this.props.isAutoPlay && this.state.isFullUnmute}
muteHandler={this.muteToggle}
fullscreen={this.state.fullscreen}
fullscreenHandler={this.fullscreenToggle}
skipToggleHandler={this.skipToggleHandler}
ended={this.state.ended}
buffering={this.state.buffering}
renderOnOverlay={this.props.renderOnOverlay}
error={
this.state.error || (!this.state.videoSRC && !this.state.loading)
}
isReplay={isReplay}
hasReplayStream={hasReplaySrc}
hasLiveStream={hasLiveSrc}
liveButtonCallback={this.liveButtonCallback}
rewButtonIsVisible={this.rewButtonIsVisible()}
fwdButtonIsVisible={this.fwdButtonIsVisible()}
hasNewStreamVideo={this.props.hasNewStreamVideo}
disableFullscreen={this.props.disableFullscreen}
/>
</Container>
);
}
}
export default Video;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_templates/ModalV2/transitions.styled-components.js
import styled, { css } from "styled-components";
import {
SlideFloatingBottomTransition,
SlideBottomTransition,
SlideTopTransition,
SlideLeftTransition,
SlideRightTransition,
FadeTransition
} from "../../_static/Transitions";
const modalWidthByDevice = (device) =>
device === "desktop"
? css`
width: 1000px;
`
: css`
@media (max-width: 320px) {
width: 100%;
}
@media (min-width: 320px) {
width: 345px;
}
@media (min-width: 1200px) {
width: 378px;
}
@media (min-width: 1365px) {
width: 414px;
}
`;
const BaseTransition = css`
position: fixed;
z-index: 1051;
display: flex;
flex-direction: column;
`;
const FullWidthMedia = css`
${(props) =>
props.isFullWidth
? css`
width: 100%;
`
: modalWidthByDevice(props.device)};
`;
const BottomFloating = css`
right: ${(props) => `${props.offset.right}px`};
left: ${(props) => `${props.offset.left}px`};
top: ${(props) => (props.fixIosKeyboard ? "70%" : "50%")};
width: auto;
${({ hasContentMaxHeight }) =>
hasContentMaxHeight &&
css`
max-height: 80vh;
`};
${({ hasContentMaxHeight, contentMaxHeight }) =>
hasContentMaxHeight &&
contentMaxHeight &&
css`
max-height: ${contentMaxHeight};
`};
${({ hasContentMaxHeight, contentMaxHeight, paddings }) =>
hasContentMaxHeight &&
contentMaxHeight &&
paddings &&
css`
padding-top: ${paddings};
padding-bottom: ${paddings};
`};
`;
const BottomPositioning = css`
right: ${(props) => `${props.offset.right}px`};
bottom: ${(props) => `${props.offset.bottom}px`};
${(props) =>
!props.isFullHeight &&
css`
max-height: calc(100% - ${`${props.offset.top + props.offset.bottom}px`});
`};
${(props) =>
props.isFullHeight &&
css`
top: ${`${props.offset.top}px`};
`};
`;
const LeftPositioning = css`
${(props) =>
props.isFullHeight &&
css`
top: ${`${props.offset.top}px`};
`};
left: ${(props) => `${props.offset.left}px`};
bottom: ${(props) => `${props.offset.bottom}px`};
`;
const RightPositioning = css`
right: ${(props) => `${props.offset.right}px`};
bottom: ${(props) => `${props.offset.bottom}px`};
${(props) =>
props.isFullHeight &&
css`
top: ${`${props.offset.top}px`};
`};
`;
const TopPositioning = css`
right: ${(props) => `${props.offset.right}px`};
top: ${(props) => `${props.offset.top}px`};
${(props) =>
props.isFullHeight &&
css`
bottom: ${`${props.offset.bottom}px`};
`};
`;
const FadePositioning = css`
${(props) =>
!props.isFullWidth &&
!props.isFluidWidth &&
!props.hasContainerFixedWidth &&
modalWidthByDevice(props.device)};
${(props) =>
!props.isFullHeight &&
!props.isFullWidth &&
css`
top: ${({ fixIosKeyboard }) => (fixIosKeyboard ? "70%" : "50%")};
left: 50%;
transform: translate3d(-50%, -50%, 0);
max-height: calc(
100vh - ${`${props.offset.top + props.offset.bottom}px`}
);
`};
${(props) =>
props.isFullHeight &&
props.isFullWidth &&
css`
top: ${`${props.offset.top}px`};
left: ${`${props.offset.left}px`};
right: ${`${props.offset.right}px`};
bottom: ${`${props.offset.bottom}px`};
transform: translate3d(0, 0, 0);
`};
${(props) =>
props.isFullWidth &&
!props.isFullHeight &&
css`
top: 50%;
left: ${`${props.offset.left}px`};
right: ${`${props.offset.right}px`};
transform: translate3d(0, -50%, 0);
`};
${(props) =>
!props.isFullWidth &&
props.isFullHeight &&
css`
top: ${`${props.offset.top}px`};
bottom: ${`${props.offset.bottom}px`};
left: 50%;
transform: translate3d(-50%, 0, 0);
`};
`;
export const FromBottomFloating = styled.div`
${BaseTransition};
${BottomFloating};
${SlideFloatingBottomTransition};
`;
export const FromBottom = styled.div`
${BaseTransition};
${BottomPositioning};
${FullWidthMedia};
${SlideBottomTransition};
`;
export const FromLeft = styled.div`
${BaseTransition};
${LeftPositioning};
${FullWidthMedia};
${SlideLeftTransition};
`;
export const FromRight = styled.div`
${BaseTransition};
${RightPositioning};
${FullWidthMedia};
${SlideRightTransition};
`;
export const FromTop = styled.div`
${BaseTransition};
${TopPositioning};
${FullWidthMedia};
${SlideTopTransition};
`;
export const FromFade = styled.div`
${BaseTransition};
${FadePositioning};
${FadeTransition};
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_templates/ModalV2/styled-components.js
import styled, { css } from "styled-components";
import { opacityIn, opacityOut } from "../../_static/Transitions";
import buildColor from "../../_static/ColorPalette";
import {
FromBottomFloating,
FromBottom,
FromLeft,
FromRight,
FromTop,
FromFade
} from "./transitions.styled-components";
// Old value: 1050
// Reason to change this is to amtch teh z-index of design system modal to garantee the modals hierarchy
const defaultLayerOffset = 9999;
export const Overlay = styled.div.attrs((props) =>
props.qaLabel
? {
"data-qa-label": props.qaLabel
}
: {}
)`
position: fixed;
top: 0;
bottom: 0;
left: 0;
/* stylelint-disable-next-line */
right: 0;
width: 100%;
height: 100%;
z-index: ${({ layerOffset }) =>
layerOffset ? defaultLayerOffset + layerOffset : defaultLayerOffset};
overflow: hidden;
perspective: 1000px;
transform-style: preserve-3d;
background-color: ${(props) =>
props.isTransparent ? "transparent" : buildColor("black", "70")};
transition: opacity 0.3s ease-out;
opacity: ${(props) => +props.opening};
& ~ div {
z-index: ${({ layerOffset }) =>
layerOffset ? defaultLayerOffset + layerOffset : defaultLayerOffset};
}
`;
export const Transitions = {
bottomFloating: FromBottomFloating,
bottom: FromBottom,
left: FromLeft,
right: FromRight,
top: FromTop,
fade: FromFade
};
export const Container = styled.div.attrs((props) => ({
"data-qa-label": props.qaLabel
}))`
position: relative;
display: flex;
flex-direction: column;
flex: 1 1 auto;
width: ${({ fixedWidth }) => fixedWidth};
margin: auto;
min-height: 0;
${({ minWidth }) =>
minWidth &&
css`
min-width: ${minWidth};
`}
/* stylelint-disable-next-line */
& .iframeOnModal {
top: 48px;
position: fixed;
height: auto;
}
`;
export const Content = styled.div`
display: flex;
flex-direction: column;
flex: 1 1 auto;
overflow-y: auto;
overflow-scrolling: touch; /* stylelint-disable-line */
-webkit-overflow-scrolling: touch; /* stylelint-disable-line */
background-color: ${(props) =>
props.isContentTransparent
? buildColor("white", "0")
: buildColor("blue", "100")};
${(props) =>
props.roundedCorners &&
css`
border-radius: 0 0 4px 4px;
`};
${(props) =>
props.contentRoundedCorners &&
css`
border-radius: 4px 4px ${props.roundedCorners ? "4px 4px" : "0 0"};
`};
& > :first-child {
flex: 1 0 auto;
display: flex;
flex-direction: column;
}
`;
export const ContentScroll = styled.div`
display: flex;
flex: 1 1 auto;
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_templates/ModalV2/defaultProps.js
import { noop } from "lodash";
export const ModalV2DefaultProps = {
title: null,
subtitle: null,
titleType: "default",
isOpen: false,
onOpen: noop,
onOpenAnimationEnd: noop,
onClose: noop,
onCloseAnimationEnd: noop,
shouldRenderWhite: false,
onBack: null,
onOverlayClick: null,
hasOverlay: true,
isFullWidth: true,
isFullHeight: true,
isFluidWidth: false,
hasRoundedCorners: true,
animation: "right",
offsetTop: 16,
offsetBottom: 0,
offsetLeft: 0,
offsetRight: 0,
hasVideoOffset: false,
children: noop,
qaLabel: null,
modalTopChildren: noop,
isLastModal: true,
fixIosKeyboard: false,
useFakeInput: false,
hasHeader: true,
device: "mobile",
hasHeaderIcon: true,
hasCloseButton: true,
fixedWidth: "100%",
myBetsStandaloneToggle: false,
layerOffset: 0,
hasContentMaxHeight: false,
hasBiggerHeader: false,
scrollableRef: { current: null },
setScrollableRef: null,
headerChildren: null,
headerTitleChildren: null,
onScrollFn: noop,
isTitleCenter: false,
isTitleCapitalized: true,
useModalHeaderV3: false,
showBottomShadow: true
};
export const ModalDefaultProps = {
title: null,
subtitle: null,
titleType: "default",
isOpen: false,
onOpen: noop,
onOpenAnimationEnd: noop,
onClose: noop,
onCloseAnimationEnd: noop,
onBack: null,
onOverlayClick: null,
hasOverlay: true,
isFullWidth: true,
isFullHeight: true,
isFluidWidth: false,
hasRoundedCorners: true,
animation: "right",
offsetTop: 16,
offsetBottom: 0,
offsetLeft: 0,
offsetRight: 0,
hasVideoOffset: false,
children: noop,
modalTopChildren: noop,
qaLabel: null,
fixIosKeyboard: false,
hasHeader: true,
device: "mobile",
isContentTransparent: false,
hasCloseWithoutHeader: false,
hasHeaderIcon: true,
hasHeaderBorder: true,
hasCloseButton: true,
fixedWidth: "100%",
myBetsStandaloneToggle: false,
layerOffset: 0,
hasContentMaxHeight: false,
contentMaxHeight: 0,
hasBiggerHeader: false,
scrollableRef: { current: null },
setScrollableRef: null,
useModalHeaderV3: false,
className: "",
shouldRenderWhiteTitle: false,
headerTitleChildren: null,
onScrollFn: noop,
isTitleCenter: false,
isTitleCapitalized: true
};
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_templates/ModalV2/utils.js
export const stopTouchEvent = (e) => e && e.stopPropagation();
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_templates/ModalV2/Modal.jsx
import React, { useRef, useState, Fragment } from "react";
import { CSSTransition } from "react-transition-group";
import { useModalV2Resize } from "@tvg/custom-hooks";
import { noop } from "lodash";
import ModalHeaderV3 from "../../_organism/ModalHeaderV3";
import ModalHeader from "../../_organism/ModalHeader";
import { calcVideoContainerHeight } from "../../_organism/Video";
import {
Container,
Content,
ContentScroll,
Overlay,
Transitions
} from "./styled-components";
import { ModalDefaultProps } from "./defaultProps";
import { stopTouchEvent } from "./utils";
const Modal = (props) => {
const [transition, setTransition] = useState("exited");
const contentRef = useRef(null);
useModalV2Resize(props.isOpen);
const renderOverlay = () =>
transition !== "exited" ? (
<Overlay
qaLabel={props.qaLabel && `${props.qaLabel}-overlay`}
onTouchStart={stopTouchEvent}
onTouchCancel={stopTouchEvent}
onTouchEnd={stopTouchEvent}
onTouchMove={stopTouchEvent}
layerOffset={props.layerOffset}
{...(typeof props.onOverlayClick === "function"
? {
onClick: props.onOverlayClick
}
: {
onClick: props.onClose
})}
opening={transition === "enter"}
exiting={transition === "exiting"}
exited={transition === "exited"}
/>
) : null;
const renderTransparentOverlay = () =>
transition !== "exited" ? (
<Overlay
qaLabel={props.qaLabel && `${props.qaLabel}-overlay`}
onTouchStart={stopTouchEvent}
onTouchCancel={stopTouchEvent}
onTouchEnd={stopTouchEvent}
onTouchMove={stopTouchEvent}
{...(typeof props.onOverlayClick === "function"
? {
onClick: props.onOverlayClick
}
: {
onClick: props.onClose
})}
opening={transition === "enter"}
exiting={transition === "exiting"}
exited={transition === "exited"}
isTransparent
/>
) : null;
const renderTopChildren = () => {
if (props.modalTopChildren !== noop) {
return props.modalTopChildren();
}
return null;
};
const renderTitle = () => {
if (props.useModalHeaderV3 && props.hasHeader) {
return (
<ModalHeaderV3
title={props.title}
isTitleCapitalized={props.isTitleCapitalized}
subtitle={props.subtitle}
isTitleCenter={props.isTitleCenter}
subtitleColor={props.subtitleColor}
subtitleFontFamily={props.subtitleFontFamily}
onClose={props.onClose}
onBack={props.onBack}
hasRoundedCorners={!(props.isFullHeight && props.offsetTop === 0)}
hasCloseButton={props.hasCloseButton}
scrollableRef={contentRef}
device={props.device}
className={props.className ? `${props.className}-modal-header` : ""}
/>
);
}
if (props.hasCloseWithoutHeader || (props.hasHeader && props.title)) {
return (
<ModalHeader
title={props.title}
subtitle={props.subtitle}
titleType={props.titleType}
onClose={props.onClose}
onBack={props.onBack}
hasRoundedCorners={props.hasRoundedCorners}
hasCloseWithoutHeader={props.hasCloseWithoutHeader}
hasIcon={props.hasHeaderIcon}
hasCloseButton={props.hasCloseButton}
hasHeaderBorder={props.hasHeaderBorder}
myBetsStandaloneToggle={props.myBetsStandaloneToggle}
scrollableRef={props.scrollableRef || contentRef}
hasBiggerHeader={props.hasBiggerHeader}
device={props.device}
shouldRenderWhiteTitle={props.shouldRenderWhiteTitle}
headerChildren={props.headerChildren}
headerTitleChildren={props.headerTitleChildren}
isTitleCenter={props.isTitleCenter}
/>
);
}
return null;
};
const renderContainer = (transitionState) => {
const modalProps = props.useModalHeaderV3
? {
ref: contentRef,
roundedCorners: props.hasRoundedCorners,
contentRoundedCorners: props.offsetTop > 0 && !props.hasHeader
}
: {
ref: props.setScrollableRef || contentRef,
onScroll: props.onScrollFn,
isContentTransparent: props.isContentTransparent,
isNavigation: props.titleType === "navigation",
roundedCorners:
(props.animation === "fade" ||
props.animation === "bottomFloating") &&
props.hasRoundedCorners
};
const renderChildren =
typeof props.children === "function" && props.children(transitionState);
return (
<Container
onTouchStart={stopTouchEvent}
onTouchCancel={stopTouchEvent}
onTouchEnd={stopTouchEvent}
onTouchMove={stopTouchEvent}
role="presentation"
isFullWidth={props.isFullWidth}
fixedWidth={props.fixedWidth}
minWidth={props.minWidth}
offset={{ top: props.offsetTop, bottom: props.offsetBottom }}
{...(props.allowClickPropagation
? {}
: {
onClick: (e) => {
e.stopPropagation();
}
})}
{...(props.qaLabel ? { qaLabel: props.qaLabel } : {})}
>
{renderTopChildren()}
{renderTitle()}
<Content {...modalProps} data-qa-label="modal-content">
{props.useModalHeaderV3 ? (
<ContentScroll data-qa-label="modal-content-v3">
{renderChildren}
</ContentScroll>
) : (
renderChildren
)}
</Content>
</Container>
);
};
const transitionProps = {
appear: true,
mountOnEnter: true,
unmountOnExit: true,
timeout: 300,
in: props.isOpen
};
const transitionStates = {
onEnter: () => setTransition("enter"),
onEntered: () => props.onOpenAnimationEnd(),
onExiting: () => setTransition("exiting"),
onExited: () => {
setTransition("exited");
props.onCloseAnimationEnd();
}
};
const Transition = Transitions[props.animation];
return (
<Fragment>
{props.hasOverlay && renderOverlay()}
{!props.hasOverlay && renderTransparentOverlay()}
<CSSTransition
{...transitionProps}
{...transitionStates}
classNames={props.animation}
>
{(state) => (
<Transition
type={props.animation}
isFullWidth={props.isFullWidth && !props.isFluidWidth}
isFluidWidth={props.isFluidWidth && !props.isFullWidth}
isFullHeight={props.isFullHeight}
offset={{
top: props.hasVideoOffset
? calcVideoContainerHeight()
: props.offsetTop,
bottom: props.offsetBottom,
left: props.offsetLeft,
right: props.offsetRight
}}
fixIosKeyboard={props.fixIosKeyboard}
device={props.device}
hasContentMaxHeight={props.hasContentMaxHeight}
contentMaxHeight={props.contentMaxHeight}
paddings={props.marginsForMaxHeight}
hasContainerFixedWidth={props.fixedWidth !== "100%"}
>
{renderContainer(state)}
</Transition>
)}
</CSSTransition>
</Fragment>
);
};
Modal.defaultProps = ModalDefaultProps;
export default Modal;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_templates/ModalV2/index.jsx
import React from "react";
import { createPortal } from "react-dom";
import { useModalV2Core } from "@tvg/custom-hooks";
import { closeModalWrapper } from "@tvg/utils/modalV2";
import Modal from "./Modal";
import { ModalV2DefaultProps } from "./defaultProps";
const ModalV2 = (props) => {
const {
isOpen,
setIsOpen,
bodyPositionY,
setBodyPositionY,
readyToRender,
element
} = useModalV2Core(
props.isOpen,
props.useFakeInput,
props.isLastModal,
props.device,
props.onOpen
);
if (typeof window === "undefined" || !readyToRender) {
return null;
}
const mixedProps = {
...props,
onClose: () => {
closeModalWrapper(props.onClose, {
useFakeInput: props.useFakeInput,
device: props.device,
isLastModal: props.isLastModal,
setIsOpen,
bodyPositionY,
setBodyPositionY
});
},
isOpen,
bodyPositionY
};
const component = <Modal {...mixedProps} />;
return createPortal(component, element);
};
ModalV2.defaultProps = ModalV2DefaultProps;
export default ModalV2;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_templates/WagerCancellationRulesModal/styled-components.js
import styled, { css } from "styled-components";
import buildColor from "../../_static/ColorPalette";
import { fontMedium, fontNormal } from "../../_static/Typography";
export const Container = styled.div`
background-color: ${buildColor("white", "100")};
padding: 16px 12px;
`;
export const ContentContainer = styled.div`
&:not(:last-child) {
margin-bottom: 18px;
}
`;
const textSharedStyles = css`
font-size: 14px;
line-height: 18px;
`;
export const Title = styled.p`
${textSharedStyles};
color: ${buildColor("grey", "900")};
font-family: ${fontMedium};
`;
export const Text = styled.p`
${textSharedStyles};
color: ${buildColor("grey", "800")};
font-family: ${fontNormal};
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_templates/WagerCancellationRulesModal/index.jsx
import React from "react";
import ModalV2 from "@tvg/atomic-ui/_templates/ModalV2";
import tvgConf from "@tvg/conf";
import { get } from "lodash";
import { Container, ContentContainer, Title, Text } from "./styled-components";
const WagerCancellationRulesModal = ({
isOpen = false,
onClose,
messages,
userLocation,
onBack,
hasBack = false
}) => {
const content = get(messages, userLocation, messages.DEFAULT);
const { device } = tvgConf();
const baseModalProps = {
title: "Wager cancellations",
titleType: "ipp",
isOpen,
onClose,
onBack: hasBack ? onBack : null,
qaLabel: "bet-cancel-rules",
hasShadow: true,
hasOverlay: true,
isFullWidth: false,
isContentTransparent: false,
isFullHeight: false,
layerOffset: 1
};
const modalProps =
device === "mobile"
? {
...baseModalProps,
animation: "bottomFloating",
offsetTop: 200,
offsetBottom: 200,
offsetLeft: 8,
offsetRight: 8
}
: {
...baseModalProps,
animation: "fade",
offsetTop: 40,
offsetBottom: 0,
offsetLeft: 40,
offsetRight: 40
};
return (
<ModalV2 {...modalProps}>
{() => (
<Container>
{content &&
content.map(({ title, text }, index) => (
<ContentContainer key={index.toString()}>
{title && <Title>{title}</Title>}
{text && <Text>{text}</Text>}
</ContentContainer>
))}
</Container>
)}
</ModalV2>
);
};
export default WagerCancellationRulesModal;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/SegmentedControl/styled-components.js
import styled, { css } from "styled-components";
import buildColor from "../../_static/ColorPalette";
import { fontMedium, fontCondensedNormal } from "../../_static/Typography";
export const Container = styled.ul`
position: relative;
display: flex;
width: 100%;
height: 40px;
padding: 4px;
background-color: ${buildColor("blue", "000")};
border-radius: 68px;
`;
const ActiveStyles = css`
background-color: ${buildColor("white", "100")};
color: ${buildColor("grey", "900")};
box-shadow:
0 2px 4px rgba(17, 43, 68, 0.06),
0 1px 2px rgba(17, 43, 68, 0.08);
`;
const NormalStyles = css`
color: ${buildColor("grey", "800")};
`;
export const Slider = styled.div`
position: absolute;
top: 4px;
${({ selectedIndex, tabsLength }) => css`
left: calc(
((100% / ${tabsLength || 1}) - 4px) * ${selectedIndex || 0} +
${selectedIndex >= 2 ? selectedIndex * 4 : 4}px
);
width: calc((100% / ${tabsLength || 1}) - 4px);
`}
height: 32px;
border-radius: 68px;
background-color: ${buildColor("white", "100")};
color: ${buildColor("grey", "900")};
box-shadow:
0 2px 4px rgba(17, 43, 68, 0.06),
0 1px 2px rgba(17, 43, 68, 0.08);
transition: left 0.3s ease;
`;
export const Item = styled.li`
display: flex;
flex-grow: 1;
border-radius: 68px;
justify-content: center;
align-items: center;
cursor: pointer;
font-family: ${fontMedium};
z-index: 2;
width: ${({ tabsLength }) => `calc(100% / ${tabsLength})`};
${({ isActive, withAnimation }) => {
if (isActive) {
if (withAnimation) {
return css`
color: ${buildColor("grey", "900")};
`;
}
return ActiveStyles;
}
return NormalStyles;
}}
&::after {
${({ counter, displayZero }) =>
(displayZero || (counter && counter > 0)) &&
css`
z-index: 2;
content: "${counter.toString()}";
${displayZero && counter === 0
? css`
background-color: ${buildColor("blue", "100")};
color: ${buildColor("grey", "900")};
opacity: 0.5;
`
: css`
background-color: ${buildColor("red", "500")};
color: ${buildColor("white", "100")};
`};
`};
border-radius: 12px;
display: inline-flex;
margin-left: 4px;
height: 16px;
padding: 0 5px;
text-align: center;
font-size: 12px;
font-family: ${fontCondensedNormal};
line-height: 11px;
justify-content: center;
align-items: center;
}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/SegmentedControl/index.jsx
import React from "react";
import { Container, Item, Slider } from "./styled-components";
const SegmentedControl = ({ tabs, qaLabel, className, withAnimation }) => {
const selectedIndex = tabs.findIndex((tab) => tab.isActive);
return (
<Container className={className} data-qa-label={qaLabel}>
{withAnimation && (
<Slider tabsLength={tabs.length} selectedIndex={selectedIndex} />
)}
{tabs.map((tab, index) => (
<Item
key={`${tab.title}_${index.toString()}`}
withAnimation={withAnimation}
tabsLength={tabs.length}
isActive={tab.isActive}
counter={tab.counter}
displayZero={tab.displayZero}
onClick={tab.onClick}
data-qa-label={tab.qaLabel}
>
{tab.title}
</Item>
))}
</Container>
);
};
export default SegmentedControl;
webpack://frontend-mybets/../../node_modules/react-helmet/es/Helmet.js
import PropTypes from 'prop-types';
import withSideEffect from 'react-side-effect';
import isEqual from 'react-fast-compare';
import React from 'react';
import objectAssign from 'object-assign';
var ATTRIBUTE_NAMES = {
BODY: "bodyAttributes",
HTML: "htmlAttributes",
TITLE: "titleAttributes"
};
var TAG_NAMES = {
BASE: "base",
BODY: "body",
HEAD: "head",
HTML: "html",
LINK: "link",
META: "meta",
NOSCRIPT: "noscript",
SCRIPT: "script",
STYLE: "style",
TITLE: "title"
};
var VALID_TAG_NAMES = Object.keys(TAG_NAMES).map(function (name) {
return TAG_NAMES[name];
});
var TAG_PROPERTIES = {
CHARSET: "charset",
CSS_TEXT: "cssText",
HREF: "href",
HTTPEQUIV: "http-equiv",
INNER_HTML: "innerHTML",
ITEM_PROP: "itemprop",
NAME: "name",
PROPERTY: "property",
REL: "rel",
SRC: "src",
TARGET: "target"
};
var REACT_TAG_MAP = {
accesskey: "accessKey",
charset: "charSet",
class: "className",
contenteditable: "contentEditable",
contextmenu: "contextMenu",
"http-equiv": "httpEquiv",
itemprop: "itemProp",
tabindex: "tabIndex"
};
var HELMET_PROPS = {
DEFAULT_TITLE: "defaultTitle",
DEFER: "defer",
ENCODE_SPECIAL_CHARACTERS: "encodeSpecialCharacters",
ON_CHANGE_CLIENT_STATE: "onChangeClientState",
TITLE_TEMPLATE: "titleTemplate"
};
var HTML_TAG_MAP = Object.keys(REACT_TAG_MAP).reduce(function (obj, key) {
obj[REACT_TAG_MAP[key]] = key;
return obj;
}, {});
var SELF_CLOSING_TAGS = [TAG_NAMES.NOSCRIPT, TAG_NAMES.SCRIPT, TAG_NAMES.STYLE];
var HELMET_ATTRIBUTE = "data-react-helmet";
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
var 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 _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 encodeSpecialCharacters = function encodeSpecialCharacters(str) {
var encode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
if (encode === false) {
return String(str);
}
return String(str).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
};
var getTitleFromPropsList = function getTitleFromPropsList(propsList) {
var innermostTitle = getInnermostProperty(propsList, TAG_NAMES.TITLE);
var innermostTemplate = getInnermostProperty(propsList, HELMET_PROPS.TITLE_TEMPLATE);
if (innermostTemplate && innermostTitle) {
// use function arg to avoid need to escape $ characters
return innermostTemplate.replace(/%s/g, function () {
return Array.isArray(innermostTitle) ? innermostTitle.join("") : innermostTitle;
});
}
var innermostDefaultTitle = getInnermostProperty(propsList, HELMET_PROPS.DEFAULT_TITLE);
return innermostTitle || innermostDefaultTitle || undefined;
};
var getOnChangeClientState = function getOnChangeClientState(propsList) {
return getInnermostProperty(propsList, HELMET_PROPS.ON_CHANGE_CLIENT_STATE) || function () {};
};
var getAttributesFromPropsList = function getAttributesFromPropsList(tagType, propsList) {
return propsList.filter(function (props) {
return typeof props[tagType] !== "undefined";
}).map(function (props) {
return props[tagType];
}).reduce(function (tagAttrs, current) {
return _extends({}, tagAttrs, current);
}, {});
};
var getBaseTagFromPropsList = function getBaseTagFromPropsList(primaryAttributes, propsList) {
return propsList.filter(function (props) {
return typeof props[TAG_NAMES.BASE] !== "undefined";
}).map(function (props) {
return props[TAG_NAMES.BASE];
}).reverse().reduce(function (innermostBaseTag, tag) {
if (!innermostBaseTag.length) {
var keys = Object.keys(tag);
for (var i = 0; i < keys.length; i++) {
var attributeKey = keys[i];
var lowerCaseAttributeKey = attributeKey.toLowerCase();
if (primaryAttributes.indexOf(lowerCaseAttributeKey) !== -1 && tag[lowerCaseAttributeKey]) {
return innermostBaseTag.concat(tag);
}
}
}
return innermostBaseTag;
}, []);
};
var getTagsFromPropsList = function getTagsFromPropsList(tagName, primaryAttributes, propsList) {
// Calculate list of tags, giving priority innermost component (end of the propslist)
var approvedSeenTags = {};
return propsList.filter(function (props) {
if (Array.isArray(props[tagName])) {
return true;
}
if (typeof props[tagName] !== "undefined") {
warn("Helmet: " + tagName + " should be of type \"Array\". Instead found type \"" + _typeof(props[tagName]) + "\"");
}
return false;
}).map(function (props) {
return props[tagName];
}).reverse().reduce(function (approvedTags, instanceTags) {
var instanceSeenTags = {};
instanceTags.filter(function (tag) {
var primaryAttributeKey = void 0;
var keys = Object.keys(tag);
for (var i = 0; i < keys.length; i++) {
var attributeKey = keys[i];
var lowerCaseAttributeKey = attributeKey.toLowerCase();
// Special rule with link tags, since rel and href are both primary tags, rel takes priority
if (primaryAttributes.indexOf(lowerCaseAttributeKey) !== -1 && !(primaryAttributeKey === TAG_PROPERTIES.REL && tag[primaryAttributeKey].toLowerCase() === "canonical") && !(lowerCaseAttributeKey === TAG_PROPERTIES.REL && tag[lowerCaseAttributeKey].toLowerCase() === "stylesheet")) {
primaryAttributeKey = lowerCaseAttributeKey;
}
// Special case for innerHTML which doesn't work lowercased
if (primaryAttributes.indexOf(attributeKey) !== -1 && (attributeKey === TAG_PROPERTIES.INNER_HTML || attributeKey === TAG_PROPERTIES.CSS_TEXT || attributeKey === TAG_PROPERTIES.ITEM_PROP)) {
primaryAttributeKey = attributeKey;
}
}
if (!primaryAttributeKey || !tag[primaryAttributeKey]) {
return false;
}
var value = tag[primaryAttributeKey].toLowerCase();
if (!approvedSeenTags[primaryAttributeKey]) {
approvedSeenTags[primaryAttributeKey] = {};
}
if (!instanceSeenTags[primaryAttributeKey]) {
instanceSeenTags[primaryAttributeKey] = {};
}
if (!approvedSeenTags[primaryAttributeKey][value]) {
instanceSeenTags[primaryAttributeKey][value] = true;
return true;
}
return false;
}).reverse().forEach(function (tag) {
return approvedTags.push(tag);
});
// Update seen tags with tags from this instance
var keys = Object.keys(instanceSeenTags);
for (var i = 0; i < keys.length; i++) {
var attributeKey = keys[i];
var tagUnion = objectAssign({}, approvedSeenTags[attributeKey], instanceSeenTags[attributeKey]);
approvedSeenTags[attributeKey] = tagUnion;
}
return approvedTags;
}, []).reverse();
};
var getInnermostProperty = function getInnermostProperty(propsList, property) {
for (var i = propsList.length - 1; i >= 0; i--) {
var props = propsList[i];
if (props.hasOwnProperty(property)) {
return props[property];
}
}
return null;
};
var reducePropsToState = function reducePropsToState(propsList) {
return {
baseTag: getBaseTagFromPropsList([TAG_PROPERTIES.HREF, TAG_PROPERTIES.TARGET], propsList),
bodyAttributes: getAttributesFromPropsList(ATTRIBUTE_NAMES.BODY, propsList),
defer: getInnermostProperty(propsList, HELMET_PROPS.DEFER),
encode: getInnermostProperty(propsList, HELMET_PROPS.ENCODE_SPECIAL_CHARACTERS),
htmlAttributes: getAttributesFromPropsList(ATTRIBUTE_NAMES.HTML, propsList),
linkTags: getTagsFromPropsList(TAG_NAMES.LINK, [TAG_PROPERTIES.REL, TAG_PROPERTIES.HREF], propsList),
metaTags: getTagsFromPropsList(TAG_NAMES.META, [TAG_PROPERTIES.NAME, TAG_PROPERTIES.CHARSET, TAG_PROPERTIES.HTTPEQUIV, TAG_PROPERTIES.PROPERTY, TAG_PROPERTIES.ITEM_PROP], propsList),
noscriptTags: getTagsFromPropsList(TAG_NAMES.NOSCRIPT, [TAG_PROPERTIES.INNER_HTML], propsList),
onChangeClientState: getOnChangeClientState(propsList),
scriptTags: getTagsFromPropsList(TAG_NAMES.SCRIPT, [TAG_PROPERTIES.SRC, TAG_PROPERTIES.INNER_HTML], propsList),
styleTags: getTagsFromPropsList(TAG_NAMES.STYLE, [TAG_PROPERTIES.CSS_TEXT], propsList),
title: getTitleFromPropsList(propsList),
titleAttributes: getAttributesFromPropsList(ATTRIBUTE_NAMES.TITLE, propsList)
};
};
var rafPolyfill = function () {
var clock = Date.now();
return function (callback) {
var currentTime = Date.now();
if (currentTime - clock > 16) {
clock = currentTime;
callback(currentTime);
} else {
setTimeout(function () {
rafPolyfill(callback);
}, 0);
}
};
}();
var cafPolyfill = function cafPolyfill(id) {
return clearTimeout(id);
};
var requestAnimationFrame = typeof window !== "undefined" ? window.requestAnimationFrame && window.requestAnimationFrame.bind(window) || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || rafPolyfill : global.requestAnimationFrame || rafPolyfill;
var cancelAnimationFrame = typeof window !== "undefined" ? window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || cafPolyfill : global.cancelAnimationFrame || cafPolyfill;
var warn = function warn(msg) {
return console && typeof console.warn === "function" && console.warn(msg);
};
var _helmetCallback = null;
var handleClientStateChange = function handleClientStateChange(newState) {
if (_helmetCallback) {
cancelAnimationFrame(_helmetCallback);
}
if (newState.defer) {
_helmetCallback = requestAnimationFrame(function () {
commitTagChanges(newState, function () {
_helmetCallback = null;
});
});
} else {
commitTagChanges(newState);
_helmetCallback = null;
}
};
var commitTagChanges = function commitTagChanges(newState, cb) {
var baseTag = newState.baseTag,
bodyAttributes = newState.bodyAttributes,
htmlAttributes = newState.htmlAttributes,
linkTags = newState.linkTags,
metaTags = newState.metaTags,
noscriptTags = newState.noscriptTags,
onChangeClientState = newState.onChangeClientState,
scriptTags = newState.scriptTags,
styleTags = newState.styleTags,
title = newState.title,
titleAttributes = newState.titleAttributes;
updateAttributes(TAG_NAMES.BODY, bodyAttributes);
updateAttributes(TAG_NAMES.HTML, htmlAttributes);
updateTitle(title, titleAttributes);
var tagUpdates = {
baseTag: updateTags(TAG_NAMES.BASE, baseTag),
linkTags: updateTags(TAG_NAMES.LINK, linkTags),
metaTags: updateTags(TAG_NAMES.META, metaTags),
noscriptTags: updateTags(TAG_NAMES.NOSCRIPT, noscriptTags),
scriptTags: updateTags(TAG_NAMES.SCRIPT, scriptTags),
styleTags: updateTags(TAG_NAMES.STYLE, styleTags)
};
var addedTags = {};
var removedTags = {};
Object.keys(tagUpdates).forEach(function (tagType) {
var _tagUpdates$tagType = tagUpdates[tagType],
newTags = _tagUpdates$tagType.newTags,
oldTags = _tagUpdates$tagType.oldTags;
if (newTags.length) {
addedTags[tagType] = newTags;
}
if (oldTags.length) {
removedTags[tagType] = tagUpdates[tagType].oldTags;
}
});
cb && cb();
onChangeClientState(newState, addedTags, removedTags);
};
var flattenArray = function flattenArray(possibleArray) {
return Array.isArray(possibleArray) ? possibleArray.join("") : possibleArray;
};
var updateTitle = function updateTitle(title, attributes) {
if (typeof title !== "undefined" && document.title !== title) {
document.title = flattenArray(title);
}
updateAttributes(TAG_NAMES.TITLE, attributes);
};
var updateAttributes = function updateAttributes(tagName, attributes) {
var elementTag = document.getElementsByTagName(tagName)[0];
if (!elementTag) {
return;
}
var helmetAttributeString = elementTag.getAttribute(HELMET_ATTRIBUTE);
var helmetAttributes = helmetAttributeString ? helmetAttributeString.split(",") : [];
var attributesToRemove = [].concat(helmetAttributes);
var attributeKeys = Object.keys(attributes);
for (var i = 0; i < attributeKeys.length; i++) {
var attribute = attributeKeys[i];
var value = attributes[attribute] || "";
if (elementTag.getAttribute(attribute) !== value) {
elementTag.setAttribute(attribute, value);
}
if (helmetAttributes.indexOf(attribute) === -1) {
helmetAttributes.push(attribute);
}
var indexToSave = attributesToRemove.indexOf(attribute);
if (indexToSave !== -1) {
attributesToRemove.splice(indexToSave, 1);
}
}
for (var _i = attributesToRemove.length - 1; _i >= 0; _i--) {
elementTag.removeAttribute(attributesToRemove[_i]);
}
if (helmetAttributes.length === attributesToRemove.length) {
elementTag.removeAttribute(HELMET_ATTRIBUTE);
} else if (elementTag.getAttribute(HELMET_ATTRIBUTE) !== attributeKeys.join(",")) {
elementTag.setAttribute(HELMET_ATTRIBUTE, attributeKeys.join(","));
}
};
var updateTags = function updateTags(type, tags) {
var headElement = document.head || document.querySelector(TAG_NAMES.HEAD);
var tagNodes = headElement.querySelectorAll(type + "[" + HELMET_ATTRIBUTE + "]");
var oldTags = Array.prototype.slice.call(tagNodes);
var newTags = [];
var indexToDelete = void 0;
if (tags && tags.length) {
tags.forEach(function (tag) {
var newElement = document.createElement(type);
for (var attribute in tag) {
if (tag.hasOwnProperty(attribute)) {
if (attribute === TAG_PROPERTIES.INNER_HTML) {
newElement.innerHTML = tag.innerHTML;
} else if (attribute === TAG_PROPERTIES.CSS_TEXT) {
if (newElement.styleSheet) {
newElement.styleSheet.cssText = tag.cssText;
} else {
newElement.appendChild(document.createTextNode(tag.cssText));
}
} else {
var value = typeof tag[attribute] === "undefined" ? "" : tag[attribute];
newElement.setAttribute(attribute, value);
}
}
}
newElement.setAttribute(HELMET_ATTRIBUTE, "true");
// Remove a duplicate tag from domTagstoRemove, so it isn't cleared.
if (oldTags.some(function (existingTag, index) {
indexToDelete = index;
return newElement.isEqualNode(existingTag);
})) {
oldTags.splice(indexToDelete, 1);
} else {
newTags.push(newElement);
}
});
}
oldTags.forEach(function (tag) {
return tag.parentNode.removeChild(tag);
});
newTags.forEach(function (tag) {
return headElement.appendChild(tag);
});
return {
oldTags: oldTags,
newTags: newTags
};
};
var generateElementAttributesAsString = function generateElementAttributesAsString(attributes) {
return Object.keys(attributes).reduce(function (str, key) {
var attr = typeof attributes[key] !== "undefined" ? key + "=\"" + attributes[key] + "\"" : "" + key;
return str ? str + " " + attr : attr;
}, "");
};
var generateTitleAsString = function generateTitleAsString(type, title, attributes, encode) {
var attributeString = generateElementAttributesAsString(attributes);
var flattenedTitle = flattenArray(title);
return attributeString ? "<" + type + " " + HELMET_ATTRIBUTE + "=\"true\" " + attributeString + ">" + encodeSpecialCharacters(flattenedTitle, encode) + "</" + type + ">" : "<" + type + " " + HELMET_ATTRIBUTE + "=\"true\">" + encodeSpecialCharacters(flattenedTitle, encode) + "</" + type + ">";
};
var generateTagsAsString = function generateTagsAsString(type, tags, encode) {
return tags.reduce(function (str, tag) {
var attributeHtml = Object.keys(tag).filter(function (attribute) {
return !(attribute === TAG_PROPERTIES.INNER_HTML || attribute === TAG_PROPERTIES.CSS_TEXT);
}).reduce(function (string, attribute) {
var attr = typeof tag[attribute] === "undefined" ? attribute : attribute + "=\"" + encodeSpecialCharacters(tag[attribute], encode) + "\"";
return string ? string + " " + attr : attr;
}, "");
var tagContent = tag.innerHTML || tag.cssText || "";
var isSelfClosing = SELF_CLOSING_TAGS.indexOf(type) === -1;
return str + "<" + type + " " + HELMET_ATTRIBUTE + "=\"true\" " + attributeHtml + (isSelfClosing ? "/>" : ">" + tagContent + "</" + type + ">");
}, "");
};
var convertElementAttributestoReactProps = function convertElementAttributestoReactProps(attributes) {
var initProps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return Object.keys(attributes).reduce(function (obj, key) {
obj[REACT_TAG_MAP[key] || key] = attributes[key];
return obj;
}, initProps);
};
var convertReactPropstoHtmlAttributes = function convertReactPropstoHtmlAttributes(props) {
var initAttributes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return Object.keys(props).reduce(function (obj, key) {
obj[HTML_TAG_MAP[key] || key] = props[key];
return obj;
}, initAttributes);
};
var generateTitleAsReactComponent = function generateTitleAsReactComponent(type, title, attributes) {
var _initProps;
// assigning into an array to define toString function on it
var initProps = (_initProps = {
key: title
}, _initProps[HELMET_ATTRIBUTE] = true, _initProps);
var props = convertElementAttributestoReactProps(attributes, initProps);
return [React.createElement(TAG_NAMES.TITLE, props, title)];
};
var generateTagsAsReactComponent = function generateTagsAsReactComponent(type, tags) {
return tags.map(function (tag, i) {
var _mappedTag;
var mappedTag = (_mappedTag = {
key: i
}, _mappedTag[HELMET_ATTRIBUTE] = true, _mappedTag);
Object.keys(tag).forEach(function (attribute) {
var mappedAttribute = REACT_TAG_MAP[attribute] || attribute;
if (mappedAttribute === TAG_PROPERTIES.INNER_HTML || mappedAttribute === TAG_PROPERTIES.CSS_TEXT) {
var content = tag.innerHTML || tag.cssText;
mappedTag.dangerouslySetInnerHTML = { __html: content };
} else {
mappedTag[mappedAttribute] = tag[attribute];
}
});
return React.createElement(type, mappedTag);
});
};
var getMethodsForTag = function getMethodsForTag(type, tags, encode) {
switch (type) {
case TAG_NAMES.TITLE:
return {
toComponent: function toComponent() {
return generateTitleAsReactComponent(type, tags.title, tags.titleAttributes, encode);
},
toString: function toString() {
return generateTitleAsString(type, tags.title, tags.titleAttributes, encode);
}
};
case ATTRIBUTE_NAMES.BODY:
case ATTRIBUTE_NAMES.HTML:
return {
toComponent: function toComponent() {
return convertElementAttributestoReactProps(tags);
},
toString: function toString() {
return generateElementAttributesAsString(tags);
}
};
default:
return {
toComponent: function toComponent() {
return generateTagsAsReactComponent(type, tags);
},
toString: function toString() {
return generateTagsAsString(type, tags, encode);
}
};
}
};
var mapStateOnServer = function mapStateOnServer(_ref) {
var baseTag = _ref.baseTag,
bodyAttributes = _ref.bodyAttributes,
encode = _ref.encode,
htmlAttributes = _ref.htmlAttributes,
linkTags = _ref.linkTags,
metaTags = _ref.metaTags,
noscriptTags = _ref.noscriptTags,
scriptTags = _ref.scriptTags,
styleTags = _ref.styleTags,
_ref$title = _ref.title,
title = _ref$title === undefined ? "" : _ref$title,
titleAttributes = _ref.titleAttributes;
return {
base: getMethodsForTag(TAG_NAMES.BASE, baseTag, encode),
bodyAttributes: getMethodsForTag(ATTRIBUTE_NAMES.BODY, bodyAttributes, encode),
htmlAttributes: getMethodsForTag(ATTRIBUTE_NAMES.HTML, htmlAttributes, encode),
link: getMethodsForTag(TAG_NAMES.LINK, linkTags, encode),
meta: getMethodsForTag(TAG_NAMES.META, metaTags, encode),
noscript: getMethodsForTag(TAG_NAMES.NOSCRIPT, noscriptTags, encode),
script: getMethodsForTag(TAG_NAMES.SCRIPT, scriptTags, encode),
style: getMethodsForTag(TAG_NAMES.STYLE, styleTags, encode),
title: getMethodsForTag(TAG_NAMES.TITLE, { title: title, titleAttributes: titleAttributes }, encode)
};
};
var Helmet = function Helmet(Component) {
var _class, _temp;
return _temp = _class = function (_React$Component) {
inherits(HelmetWrapper, _React$Component);
function HelmetWrapper() {
classCallCheck(this, HelmetWrapper);
return possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
HelmetWrapper.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
return !isEqual(this.props, nextProps);
};
HelmetWrapper.prototype.mapNestedChildrenToProps = function mapNestedChildrenToProps(child, nestedChildren) {
if (!nestedChildren) {
return null;
}
switch (child.type) {
case TAG_NAMES.SCRIPT:
case TAG_NAMES.NOSCRIPT:
return {
innerHTML: nestedChildren
};
case TAG_NAMES.STYLE:
return {
cssText: nestedChildren
};
}
throw new Error("<" + child.type + " /> elements are self-closing and can not contain children. Refer to our API for more information.");
};
HelmetWrapper.prototype.flattenArrayTypeChildren = function flattenArrayTypeChildren(_ref) {
var _babelHelpers$extends;
var child = _ref.child,
arrayTypeChildren = _ref.arrayTypeChildren,
newChildProps = _ref.newChildProps,
nestedChildren = _ref.nestedChildren;
return _extends({}, arrayTypeChildren, (_babelHelpers$extends = {}, _babelHelpers$extends[child.type] = [].concat(arrayTypeChildren[child.type] || [], [_extends({}, newChildProps, this.mapNestedChildrenToProps(child, nestedChildren))]), _babelHelpers$extends));
};
HelmetWrapper.prototype.mapObjectTypeChildren = function mapObjectTypeChildren(_ref2) {
var _babelHelpers$extends2, _babelHelpers$extends3;
var child = _ref2.child,
newProps = _ref2.newProps,
newChildProps = _ref2.newChildProps,
nestedChildren = _ref2.nestedChildren;
switch (child.type) {
case TAG_NAMES.TITLE:
return _extends({}, newProps, (_babelHelpers$extends2 = {}, _babelHelpers$extends2[child.type] = nestedChildren, _babelHelpers$extends2.titleAttributes = _extends({}, newChildProps), _babelHelpers$extends2));
case TAG_NAMES.BODY:
return _extends({}, newProps, {
bodyAttributes: _extends({}, newChildProps)
});
case TAG_NAMES.HTML:
return _extends({}, newProps, {
htmlAttributes: _extends({}, newChildProps)
});
}
return _extends({}, newProps, (_babelHelpers$extends3 = {}, _babelHelpers$extends3[child.type] = _extends({}, newChildProps), _babelHelpers$extends3));
};
HelmetWrapper.prototype.mapArrayTypeChildrenToProps = function mapArrayTypeChildrenToProps(arrayTypeChildren, newProps) {
var newFlattenedProps = _extends({}, newProps);
Object.keys(arrayTypeChildren).forEach(function (arrayChildName) {
var _babelHelpers$extends4;
newFlattenedProps = _extends({}, newFlattenedProps, (_babelHelpers$extends4 = {}, _babelHelpers$extends4[arrayChildName] = arrayTypeChildren[arrayChildName], _babelHelpers$extends4));
});
return newFlattenedProps;
};
HelmetWrapper.prototype.warnOnInvalidChildren = function warnOnInvalidChildren(child, nestedChildren) {
if (process.env.NODE_ENV !== "production") {
if (!VALID_TAG_NAMES.some(function (name) {
return child.type === name;
})) {
if (typeof child.type === "function") {
return warn("You may be attempting to nest <Helmet> components within each other, which is not allowed. Refer to our API for more information.");
}
return warn("Only elements types " + VALID_TAG_NAMES.join(", ") + " are allowed. Helmet does not support rendering <" + child.type + "> elements. Refer to our API for more information.");
}
if (nestedChildren && typeof nestedChildren !== "string" && (!Array.isArray(nestedChildren) || nestedChildren.some(function (nestedChild) {
return typeof nestedChild !== "string";
}))) {
throw new Error("Helmet expects a string as a child of <" + child.type + ">. Did you forget to wrap your children in braces? ( <" + child.type + ">{``}</" + child.type + "> ) Refer to our API for more information.");
}
}
return true;
};
HelmetWrapper.prototype.mapChildrenToProps = function mapChildrenToProps(children, newProps) {
var _this2 = this;
var arrayTypeChildren = {};
React.Children.forEach(children, function (child) {
if (!child || !child.props) {
return;
}
var _child$props = child.props,
nestedChildren = _child$props.children,
childProps = objectWithoutProperties(_child$props, ["children"]);
var newChildProps = convertReactPropstoHtmlAttributes(childProps);
_this2.warnOnInvalidChildren(child, nestedChildren);
switch (child.type) {
case TAG_NAMES.LINK:
case TAG_NAMES.META:
case TAG_NAMES.NOSCRIPT:
case TAG_NAMES.SCRIPT:
case TAG_NAMES.STYLE:
arrayTypeChildren = _this2.flattenArrayTypeChildren({
child: child,
arrayTypeChildren: arrayTypeChildren,
newChildProps: newChildProps,
nestedChildren: nestedChildren
});
break;
default:
newProps = _this2.mapObjectTypeChildren({
child: child,
newProps: newProps,
newChildProps: newChildProps,
nestedChildren: nestedChildren
});
break;
}
});
newProps = this.mapArrayTypeChildrenToProps(arrayTypeChildren, newProps);
return newProps;
};
HelmetWrapper.prototype.render = function render() {
var _props = this.props,
children = _props.children,
props = objectWithoutProperties(_props, ["children"]);
var newProps = _extends({}, props);
if (children) {
newProps = this.mapChildrenToProps(children, newProps);
}
return React.createElement(Component, newProps);
};
createClass(HelmetWrapper, null, [{
key: "canUseDOM",
// Component.peek comes from react-side-effect:
// For testing, you may use a static peek() method available on the returned component.
// It lets you get the current state without resetting the mounted instance stack.
// Don’t use it for anything other than testing.
/**
* @param {Object} base: {"target": "_blank", "href": "http://mysite.com/"}
* @param {Object} bodyAttributes: {"className": "root"}
* @param {String} defaultTitle: "Default Title"
* @param {Boolean} defer: true
* @param {Boolean} encodeSpecialCharacters: true
* @param {Object} htmlAttributes: {"lang": "en", "amp": undefined}
* @param {Array} link: [{"rel": "canonical", "href": "http://mysite.com/example"}]
* @param {Array} meta: [{"name": "description", "content": "Test description"}]
* @param {Array} noscript: [{"innerHTML": "<img src='http://mysite.com/js/test.js'"}]
* @param {Function} onChangeClientState: "(newState) => console.log(newState)"
* @param {Array} script: [{"type": "text/javascript", "src": "http://mysite.com/js/test.js"}]
* @param {Array} style: [{"type": "text/css", "cssText": "div { display: block; color: blue; }"}]
* @param {String} title: "Title"
* @param {Object} titleAttributes: {"itemprop": "name"}
* @param {String} titleTemplate: "MySite.com - %s"
*/
set: function set$$1(canUseDOM) {
Component.canUseDOM = canUseDOM;
}
}]);
return HelmetWrapper;
}(React.Component), _class.propTypes = {
base: PropTypes.object,
bodyAttributes: PropTypes.object,
children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]),
defaultTitle: PropTypes.string,
defer: PropTypes.bool,
encodeSpecialCharacters: PropTypes.bool,
htmlAttributes: PropTypes.object,
link: PropTypes.arrayOf(PropTypes.object),
meta: PropTypes.arrayOf(PropTypes.object),
noscript: PropTypes.arrayOf(PropTypes.object),
onChangeClientState: PropTypes.func,
script: PropTypes.arrayOf(PropTypes.object),
style: PropTypes.arrayOf(PropTypes.object),
title: PropTypes.string,
titleAttributes: PropTypes.object,
titleTemplate: PropTypes.string
}, _class.defaultProps = {
defer: true,
encodeSpecialCharacters: true
}, _class.peek = Component.peek, _class.rewind = function () {
var mappedState = Component.rewind();
if (!mappedState) {
// provide fallback if mappedState is undefined
mappedState = mapStateOnServer({
baseTag: [],
bodyAttributes: {},
encodeSpecialCharacters: true,
htmlAttributes: {},
linkTags: [],
metaTags: [],
noscriptTags: [],
scriptTags: [],
styleTags: [],
title: "",
titleAttributes: {}
});
}
return mappedState;
}, _temp;
};
var NullComponent = function NullComponent() {
return null;
};
var HelmetSideEffects = withSideEffect(reducePropsToState, handleClientStateChange, mapStateOnServer)(NullComponent);
var HelmetExport = Helmet(HelmetSideEffects);
HelmetExport.renderStatic = HelmetExport.rewind;
export default HelmetExport;
export { HelmetExport as Helmet };
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/Pagination/styled-components.js
import styled, { css } from "styled-components";
import { buildText } from "../../_atom/Text";
import DefaultButton from "../../_atom/Buttons/default";
import buildColor from "../../_static/ColorPalette";
import { fontNormal } from "../../_static/Typography";
import Icon from "../../_static/Icons";
export const PaginationWrapper = styled.nav`
display: flex;
justify-content: space-between;
align-items: center;
${(props) => {
let returnCSS = "";
switch (props.theme) {
case "tutorials":
returnCSS = css`
margin-top: 22px;
& > button {
min-width: 60px;
text-transform: uppercase;
background-color: ${buildColor("white", "0")};
&:first-child {
text-align: left;
}
svg {
fill: ${buildColor("blue_accent", "500")};
}
}
`;
break;
case "topRaces":
returnCSS = css`
max-width: 64px;
border: 1px solid ${buildColor("blue", "100")};
background-color: ${buildColor("blue_accent", "000")};
border-radius: 4px;
&:hover {
cursor: pointer;
}
& > button {
background-color: ${buildColor("white", "0")};
width: 32px;
height: 32px;
padding: 8px;
svg {
fill: ${buildColor("blue_accent", "500")};
}
&:hover {
background-color: ${buildColor("blue_accent", "100")};
}
}
`;
break;
default:
returnCSS = css`
background-color: ${buildColor("white", "0")};
padding: 8px 12px;
padding-bottom: calc(constant(safe-area-inset-bottom) + 8px);
padding-bottom: calc(env(safe-area-inset-bottom) + 8px);
& > button {
background-color: ${buildColor("white", "0")};
min-width: 40px;
height: 40px;
&:first-child:active,
:last-child:active {
background-color: ${buildColor("blue", "100")};
}
}
`;
break;
}
return returnCSS;
}};
`;
export const PaginationBullet = styled.span`
background-color: ${(props) =>
props.active
? buildColor("blue_accent", "500")
: buildColor("blue_accent", "100")};
width: 8px;
height: 8px;
border-radius: 50%;
padding: 0;
margin-right: 8px;
`;
export const PagesWrapper = styled.div`
display: flex;
justify-content: center;
`;
export const TopRacesButtonDefault = styled(DefaultButton)`
border: none;
margin: 0;
`;
export const NextWrapper = styled.span`
display: flex;
justify-content: space-between;
align-items: center;
flex-direction: row;
color: ${buildColor("blue_accent", "500")};
font-weight: bold;
`;
export const NavigationWrapper = styled.span`
min-width: 80px;
display: flex;
justify-content: ${({ alignRight }) =>
alignRight ? "flex-end" : "flex-start"};
align-items: center;
font-size: 12px;
line-height: 17px;
${({ isHidden }) =>
isHidden &&
css`
visibility: hidden;
`}
`;
export const WordWrapper = styled.span`
font-family: ${fontNormal};
padding: 0 8px;
`;
export const SelectorContainer = styled.div`
width: 98px;
height: 32px;
overflow: hidden;
flex: 0 0 auto;
margin: 0 8px;
border: 1px solid ${buildColor("blue", "100")};
box-sizing: border-box;
box-shadow:
0 2px 4px rgb(17 43 68 / 6%),
0 1px 2px rgb(17 43 68 / 8%);
border-radius: 4px;
position: relative;
`;
export const LabelsWrapper = styled(
buildText({
tag: "span",
fontSize: 14,
color: buildColor("grey", "900"),
ellipsis: true
})
)`
padding: 6px 32px 6px 8px;
line-height: 18px;
width: 100%;
height: 32px;
display: flex;
align-items: center;
justify-content: flex-start;
`;
export const PageSelected = styled(
buildText({
tag: "span",
fontSize: 14,
color: buildColor("grey", "900")
})
)`
line-height: 19px;
font-weight: 500;
vertical-align: baseline;
`;
export const SelectIcon = styled(Icon)`
position: absolute;
right: 8px;
top: 50%;
transform: translate(0, -50%);
`;
export const SelectList = styled.select.attrs({
"data-qa-label": "pageSelector"
})`
opacity: 0;
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
z-index: 1;
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/Pagination/index.jsx
import React, { PureComponent, Fragment } from "react";
import { noop } from "lodash";
import Icon from "../../_static/Icons";
import buildColor from "../../_static/ColorPalette";
import { arrowBack, arrowForward, arrowDown } from "../../_static/Icons/icons";
import DefaultButton from "../../_atom/Buttons/default";
import {
PaginationWrapper,
TopRacesButtonDefault,
PagesWrapper,
NextWrapper,
WordWrapper,
NavigationWrapper,
PaginationBullet,
SelectList,
SelectorContainer,
LabelsWrapper,
PageSelected,
SelectIcon
} from "./styled-components";
export default class Pagination extends PureComponent {
static defaultProps = {
pageSelected: 1,
totalPages: 1,
onBackPage: noop,
onForwardPage: noop,
onSelectPage: undefined,
theme: "default",
className: "",
qaLabel: "pagination",
isBackDisabled: false,
isForwardDisabled: false,
isLabelsShown: false
};
defaultPaginationRender = () => {
const {
theme,
onBackPage,
pageSelected,
onSelectPage,
onForwardPage,
totalPages,
isLabelsShown
} = this.props;
return (
<PaginationWrapper
theme={theme}
className={this.props.className}
data-qa-label={this.props.qaLabel}
>
<DefaultButton
onClick={onBackPage}
isDisabled={pageSelected === 1}
qaLabel="previous-page-button"
>
{isLabelsShown ? (
<NavigationWrapper isHidden={pageSelected === 1}>
<Icon icon={arrowBack} />
<WordWrapper>Previous</WordWrapper>
</NavigationWrapper>
) : (
<Icon icon={arrowBack} />
)}
</DefaultButton>
<PagesWrapper>
{onSelectPage ? (
this.renderButtons()
) : (
<Fragment>
<strong>{pageSelected}</strong> of
<strong>{totalPages}</strong>
</Fragment>
)}
</PagesWrapper>
<DefaultButton
onClick={onForwardPage}
isDisabled={pageSelected === totalPages}
qaLabel="next-page-button"
>
{isLabelsShown ? (
<NavigationWrapper
isHidden={pageSelected === totalPages}
alignRight
>
<WordWrapper>Next</WordWrapper>
<Icon icon={arrowForward} />
</NavigationWrapper>
) : (
<Icon icon={arrowForward} />
)}
</DefaultButton>
</PaginationWrapper>
);
};
topRacesPaginationRender = () => (
<PaginationWrapper
theme={this.props.theme}
className={this.props.className}
data-qa-label={this.props.qaLabel}
>
<TopRacesButtonDefault
onClick={this.props.onBackPage}
isDisabled={this.props.isBackDisabled}
size={16}
qaLabel="pagination-previousButton"
>
<Icon icon={arrowBack} />
</TopRacesButtonDefault>
<TopRacesButtonDefault
onClick={this.props.onForwardPage}
isDisabled={this.props.isForwardDisabled}
size={16}
qaLabel="pagination-forwardButton"
>
<Icon icon={arrowForward} />
</TopRacesButtonDefault>
</PaginationWrapper>
);
tutorialsPaginationRender = () => {
const { theme, onBackPage, pageSelected, onForwardPage, totalPages } =
this.props;
return (
<PaginationWrapper
theme={theme}
className={this.props.className}
data-qa-label={this.props.qaLabel}
>
<DefaultButton
onClick={onBackPage}
isDisabled={pageSelected === 1}
qaLabel="pagination-previousButton"
>
<Icon icon={arrowBack} />
</DefaultButton>
{pageSelected !== totalPages && (
<Fragment>
<PagesWrapper>{this.renderButtons()}</PagesWrapper>
<DefaultButton
onClick={onForwardPage}
isDisabled={pageSelected === totalPages}
qaLabel="pagination-nextButton"
>
<NextWrapper>
<WordWrapper>NEXT</WordWrapper>
<Icon icon={arrowForward} />
</NextWrapper>
</DefaultButton>
</Fragment>
)}
</PaginationWrapper>
);
};
renderButtons = () => {
const { theme, totalPages, pageSelected, onSelectPage } = this.props;
if (theme === "tutorials") {
const buttonsArray = [];
for (let i = 1; i <= totalPages; i += 1) {
buttonsArray.push(
<PaginationBullet key={`wbp-${i}`} active={pageSelected === i} />
);
}
return <Fragment>{buttonsArray}</Fragment>;
}
return (
<SelectorContainer>
<LabelsWrapper>
<PageSelected data-qa-label="pageSelected">
{pageSelected}
</PageSelected>
{`of ${totalPages}`}
</LabelsWrapper>
<SelectList
onChange={(event) => {
if (onSelectPage) onSelectPage(+event.target.value);
}}
value={pageSelected}
>
<option value="select-page" disabled>
Select Page
</option>
{Array.from(Array(totalPages), (_, i) => i + 1).map((page) => (
<option key={`page-${page}`} value={page}>
{page}
</option>
))}
</SelectList>
<SelectIcon icon={arrowDown} color={buildColor("grey", "900")} />
</SelectorContainer>
);
};
render() {
const { theme } = this.props;
let returnRender;
switch (theme) {
case "tutorials":
returnRender = this.tutorialsPaginationRender();
break;
case "topRaces":
returnRender = this.topRacesPaginationRender();
break;
default:
returnRender = this.defaultPaginationRender();
break;
}
return returnRender;
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/DayPickerCustomNavBar/index.tsx
import React from "react";
import Pagination from "@tvg/atomic-ui/_molecule/Pagination";
import { CustomNavBarProps } from "./types";
const CustomNavBar = ({ onPreviousClick, onNextClick }: CustomNavBarProps) => (
<div className="DayPicker-NavBar">
<Pagination
theme="topRaces"
className="DayPicker-NavBarElement"
onBackPage={() => {
onPreviousClick();
}}
onForwardPage={() => {
onNextClick();
}}
/>
</div>
);
export default CustomNavBar;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/DayPickerCustomMonthSelector/styled-components.ts
import styled, { css } from "styled-components";
import buildColor from "@tvg/atomic-ui/_static/ColorPalette";
import { fontMedium, fontBold } from "@tvg/atomic-ui/_static/Typography";
import DefaultButton from "@tvg/atomic-ui/_atom/Buttons/default";
import Icon from "@tvg/atomic-ui/_static/Icons";
export const MonthButton = styled(DefaultButton)`
display: flex;
align-items: center;
height: 32px;
padding: 0 8px;
border: 1px solid ${buildColor("blue", "100")};
background-color: ${buildColor("blue_accent", "000")};
border-radius: 2px;
box-shadow: 0 2px 2px rgba(17, 43, 68, 0.15);
color: ${buildColor("grey", "900")};
&:active {
background-color: ${buildColor("blue_accent", "100")};
}
`;
export const MonthButtonIcon = styled(Icon)`
fill: ${buildColor("grey", "800")};
`;
export const MonthSelectorWrapper = styled.div`
display: flex;
flex-direction: column;
position: absolute;
top: 0;
left: 0;
width: 100%;
max-height: 318px;
overflow-y: auto;
background-color: white;
border-radius: 4px;
z-index: 1;
`;
export const MonthSelectorContainer = styled.div`
position: relative;
`;
export const MonthSelectorHeader = styled.div`
display: flex;
position: sticky;
top: 0;
left: 0;
width: 100%;
height: 54px;
border-bottom: 1px solid ${buildColor("blue", "100")};
background-color: white;
&::after {
content: "";
flex: 1;
}
`;
export const MonthSelectorCloseButton = styled(DefaultButton)`
display: flex;
align-items: center;
width: 18px;
margin-left: 18px;
flex: 1;
&:hover {
> svg {
background-color: ${buildColor("blue_accent", "100")};
}
}
&:active {
> svg {
background-color: ${buildColor("blue_accent", "200")};
}
}
`;
export const MonthSelectorCloseIcon = styled(Icon)`
border-radius: 50%;
background: transparent;
padding: 7px;
fill: ${buildColor("blue_accent", "500")};
`;
export const MonthSelectorTitle = styled.span`
align-self: center;
font-family: ${fontBold};
font-size: 14px;
color: ${buildColor("grey", "900")};
`;
export const MonthSelectorYearWrapper = styled.div`
display: flex;
flex-direction: column;
width: 100%;
`;
export const YearLabel = styled.div`
width: 100%;
padding: 8px 16px;
background-color: ${buildColor("grey", "000")};
color: ${buildColor("grey", "700")};
font-family: ${fontMedium};
font-size: 14px;
`;
export const MonthSelectorPickerWrapper = styled.div`
display: flex;
flex-flow: row wrap;
width: 100%;
padding: 8px 12px;
`;
export const MonthPickerButton = styled(DefaultButton)<{
isSelectedMonth: boolean;
}>`
width: 33.3%;
padding: 12px;
color: ${buildColor("blue_accent", "500")};
font-family: ${fontMedium};
font-size: 14px;
border-radius: 2px;
${({ isSelectedMonth }) =>
isSelectedMonth &&
css`
background-color: ${buildColor("blue_accent", "200")};
`}
&:hover {
background-color: ${buildColor("blue_accent", "100")};
}
&:active {
background-color: ${buildColor("blue_accent", "200")};
}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/DayPickerCustomMonthSelector/index.tsx
import React, { useMemo } from "react";
import { range, get } from "lodash";
import { isSameYear, isSameMonth } from "date-fns";
import { arrowRight, arrowLeft } from "@tvg/atomic-ui/_static/Icons/icons";
import {
MonthButton,
MonthButtonIcon,
MonthSelectorWrapper,
MonthSelectorContainer,
MonthSelectorHeader,
MonthSelectorCloseButton,
MonthSelectorCloseIcon,
MonthSelectorTitle,
MonthSelectorYearWrapper,
YearLabel,
MonthSelectorPickerWrapper,
MonthPickerButton
} from "./styled-components";
import { CustomMonthSelectorProps } from "./types";
const CustomMonthSelector = ({
date,
localeUtils,
initialYearRange,
isMonthSelector,
setIsMonthSelector,
selectedMonth,
setSelectedMonth
}: CustomMonthSelectorProps) => {
const currentYear = new Date().getFullYear();
const selectedYear = date.getFullYear();
const initialYear = currentYear - initialYearRange;
const months = localeUtils.getMonths();
const currentMonth = months[date.getMonth()];
const monthLabel = `${currentMonth} ${selectedYear}`;
const renderMonths = useMemo(() => {
const yearRange = range(currentYear, initialYear);
const monthRange = range(0, 12);
return yearRange.map((year) => (
<MonthSelectorYearWrapper>
<YearLabel>{year}</YearLabel>
<MonthSelectorPickerWrapper>
{monthRange.map((month) => {
const dateToRender = new Date(year, month);
const isSelectedMonth =
isSameMonth(selectedMonth as Date, dateToRender) &&
isSameYear(selectedMonth as Date, dateToRender);
return (
<MonthPickerButton
isSelectedMonth={isSelectedMonth}
onClick={() => {
setSelectedMonth(dateToRender);
setIsMonthSelector(false);
}}
>
{get(months, month, "")}
</MonthPickerButton>
);
})}
</MonthSelectorPickerWrapper>
</MonthSelectorYearWrapper>
));
}, []);
const renderMonthSelector = () => (
<MonthSelectorWrapper>
<MonthSelectorContainer>
<MonthSelectorHeader>
<MonthSelectorCloseButton
onClick={() => {
setIsMonthSelector(false);
}}
>
<MonthSelectorCloseIcon icon={arrowLeft} size="18" />
</MonthSelectorCloseButton>
<MonthSelectorTitle>Select Month</MonthSelectorTitle>
</MonthSelectorHeader>
{renderMonths}
</MonthSelectorContainer>
</MonthSelectorWrapper>
);
const renderMonthCaption = () => (
<div className="DayPicker-Caption">
<MonthButton
onClick={() => {
setIsMonthSelector(true);
}}
>
{monthLabel}
<MonthButtonIcon icon={arrowRight} />
</MonthButton>
</div>
);
return isMonthSelector ? renderMonthSelector() : renderMonthCaption();
};
export default CustomMonthSelector;
webpack://frontend-mybets/../../node_modules/date-fns/esm/isSameMonth/index.js
import toDate from '../toDate/index.js';
import requiredArgs from '../_lib/requiredArgs/index.js';
/**
* @name isSameMonth
* @category Month Helpers
* @summary Are the given dates in the same month?
*
* @description
* Are the given dates in the same month?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the first date to check
* @param {Date|Number} dateRight - the second date to check
* @returns {Boolean} the dates are in the same month
* @throws {TypeError} 2 arguments required
*
* @example
* // Are 2 September 2014 and 25 September 2014 in the same month?
* var result = isSameMonth(new Date(2014, 8, 2), new Date(2014, 8, 25))
* //=> true
*/
export default function isSameMonth(dirtyDateLeft, dirtyDateRight) {
requiredArgs(2, arguments);
var dateLeft = toDate(dirtyDateLeft);
var dateRight = toDate(dirtyDateRight);
return dateLeft.getFullYear() === dateRight.getFullYear() && dateLeft.getMonth() === dateRight.getMonth();
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/isSameYear/index.js
import toDate from '../toDate/index.js';
import requiredArgs from '../_lib/requiredArgs/index.js';
/**
* @name isSameYear
* @category Year Helpers
* @summary Are the given dates in the same year?
*
* @description
* Are the given dates in the same year?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the first date to check
* @param {Date|Number} dateRight - the second date to check
* @returns {Boolean} the dates are in the same year
* @throws {TypeError} 2 arguments required
*
* @example
* // Are 2 September 2014 and 25 September 2014 in the same year?
* var result = isSameYear(new Date(2014, 8, 2), new Date(2014, 8, 25))
* //=> true
*/
export default function isSameYear(dirtyDateLeft, dirtyDateRight) {
requiredArgs(2, arguments);
var dateLeft = toDate(dirtyDateLeft);
var dateRight = toDate(dirtyDateRight);
return dateLeft.getFullYear() === dateRight.getFullYear();
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MyBetsDesktopSettledFilters/styled-components.ts
import styled, { css } from "styled-components";
import buildColor from "@tvg/atomic-ui/_static/ColorPalette";
import {
fontNormal,
fontMedium,
defaultSize
} from "@tvg/atomic-ui/_static/Typography";
export const filterButtonSelected = (calendar: boolean) =>
calendar
? css`
background-color: ${buildColor("blue_accent", "100")};
border-color: ${buildColor("blue", "100")};
`
: css`
background-color: ${buildColor("blue_accent", "100")};
border-color: ${buildColor("blue_accent", "500")};
color: ${buildColor("blue_accent", "700")};
`;
export const FiltersContainer = styled.div<{
calendar?: boolean;
}>`
display: flex;
border: 1px solid ${buildColor("blue", "100")};
border-radius: 3px;
margin: 14px 8px 14px 0;
box-shadow: 0 2px 2px rgba(17, 43, 68, 0.15);
align-items: center;
${({ calendar }) =>
calendar &&
css`
z-index: 2;
`}
`;
export const FilterButton = styled.button<{
selected?: boolean;
calendar?: boolean;
}>`
box-sizing: content-box;
padding: 0 12px;
border: 1px solid transparent;
border-radius: 2px;
font-family: ${fontMedium};
background-color: transparent;
color: ${buildColor("black", "70")};
cursor: pointer;
height: 26px;
display: flex;
align-items: center;
gap: 9px;
${({ selected, calendar }) =>
selected
? filterButtonSelected(!!calendar)
: css`
& :hover {
background-color: ${buildColor("blue_accent", "000")};
border-color: ${buildColor("blue", "100")};
}
`}
`;
export const IconContainer = styled.div`
display: flex;
align-items: center;
padding: 0 10px;
`;
export const DateSpan = styled.span<{
value: Date;
}>`
padding-left: 8px;
color: ${buildColor("grey", "700")};
${({ value }) =>
value &&
css`
color: ${buildColor("grey", "900")};
`};
`;
export const Divider = styled.div`
height: 16px;
display: flex;
align-items: center;
border-left: 1px solid ${buildColor("blue_accent", "100")};
`;
export const DatePickerOverlay = styled.div`
position: fixed;
width: 100%;
height: 100%;
margin-top: -45px;
margin-left: -25px;
z-index: -1;
`;
export const DatePickerWrapper = styled.div`
position: absolute;
margin-top: 46px;
background: ${buildColor("white", "100")};
border: 1px solid ${buildColor("blue", "100")};
box-sizing: border-box;
box-shadow: 0 4px 4px rgba(0, 0, 0, 0.14);
border-radius: 4px;
min-height: 322px;
z-index: 1;
`;
// TODO: this is the default styles file minified, it's a workaround. We are currently exploring options with our css webpack plugin.
// Whenever you are changing or bumping react-day-picker, please make sure to update this string as well.
const MinifiedDayPickerDefaultStyles =
".DayPicker{display:inline-block;font-size:1rem}.DayPicker-wrapper{position:relative;flex-direction:row;padding-bottom:1em;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.DayPicker-Months{display:flex;flex-wrap:wrap;justify-content:center}.DayPicker-Month{display:table;margin:0 1em;margin-top:1em;border-spacing:0;border-collapse:collapse;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.DayPicker-NavButton{position:absolute;top:1em;right:1.5em;left:auto;display:inline-block;margin-top:2px;width:1.25em;height:1.25em;background-position:center;background-size:50%;background-repeat:no-repeat;color:#8b9898;cursor:pointer}.DayPicker-NavButton:hover{opacity:.8}.DayPicker-NavButton--prev{margin-right:1.5em;background-image:url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACQAAAAwCAYAAAB5R9gVAAAABGdBTUEAALGPC/xhBQAAAVVJREFUWAnN2G0KgjAYwPHpGfRkaZeqvgQaK+hY3SUHrk1YzNLay/OiEFp92I+/Mp2F2Mh2lLISWnflFjzH263RQjzMZ19wgs73ez0o1WmtW+dgA01VxrE3p6l2GLsnBy1VYQOtVSEH/atCCgqpQgKKqYIOiq2CBkqtggLKqQIKgqgCBjpJ2Y5CdJ+zrT9A7HHSTA1dxUdHgzCqJIEwq0SDsKsEg6iqBIEoq/wEcVRZBXFV+QJxV5mBtlDFB5VjYTaGZ2sf4R9PM7U9ZU+lLuaetPP/5Die3ToO1+u+MKtHs06qODB2zBnI/jBd4MPQm1VkY79Tb18gB+C62FdBFsZR6yeIo1YQiLJWMIiqVjQIu1YSCLNWFgijVjYIuhYYCKoWKAiiFgoopxYaKLUWOii2FgkophYp6F3r42W5A9s9OcgNvva8xQaysKXlFytoqdYmQH6tF3toSUo0INq9AAAAAElFTkSuQmCC')}.DayPicker-NavButton--next{background-image:url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACQAAAAwCAYAAAB5R9gVAAAABGdBTUEAALGPC/xhBQAAAXRJREFUWAnN119ugjAcwPHWzJ1gnmxzB/BBE0n24m4xfNkTaOL7wOtsl3AXMMb+Vjaa1BG00N8fSEibPpAP3xAKKs2yjzTPH9RAjhEo9WzPr/Vm8zgE0+gXATAxxuxtqeJ9t5tIwv5AtQAApsfT6TPdbp+kUBcgVwvO51KqVhMkXKsVJFXrOkigVhCIs1Y4iKlWZxB1rX4gwlpRIIpa8SDkWmggrFq4IIRaJKCYWnSgnrXIQV1r8YD+1Vrn+bReagysIFfLABRt31v8oBu1xEBttfRbltmfjgEcWh9snUS2kNdBK6WN1vrOWxObWsz+fjxevsxmB1GQDfINWiev83nhaoiB/CoOU438oPrhXS0WpQ9xc1ZQWxWHqUYe0I0qrKCQKjygDlXIQV2r0IF6ViEBxVTBBSFUQQNhVYkHIVeJAtkNsbQ7c1LtzP6FsObhb2rCKv7NBIGoq4SDmKoEgTirXAcJVGkFSVVpgoSrXICGUMUH/QBZNSUy5XWUhwAAAABJRU5ErkJggg==')}.DayPicker-NavButton--interactionDisabled{display:none}.DayPicker-Caption{display:table-caption;margin-bottom:.5em;padding:0 .5em;text-align:left}.DayPicker-Caption>div{font-weight:500;font-size:1.15em}.DayPicker-Weekdays{display:table-header-group;margin-top:1em}.DayPicker-WeekdaysRow{display:table-row}.DayPicker-Weekday{display:table-cell;padding:.5em;color:#8b9898;text-align:center;font-size:.875em}.DayPicker-Weekday abbr[title]{border-bottom:none;text-decoration:none}.DayPicker-Body{display:table-row-group}.DayPicker-Week{display:table-row}.DayPicker-Day{display:table-cell;padding:.5em;border-radius:50%;vertical-align:middle;text-align:center;cursor:pointer}.DayPicker-WeekNumber{display:table-cell;padding:.5em;min-width:1em;border-right:1px solid #eaecec;color:#8b9898;vertical-align:middle;text-align:right;font-size:.75em;cursor:pointer}.DayPicker--interactionDisabled .DayPicker-Day{cursor:default}.DayPicker-Footer{padding-top:.5em}.DayPicker-TodayButton{border:none;background-color:transparent;background-image:none;box-shadow:none;color:#4a90e2;font-size:.875em;cursor:pointer}.DayPicker-Day--today{color:#d0021b;font-weight:700}.DayPicker-Day--outside{color:#8b9898;cursor:default}.DayPicker-Day--disabled{color:#dce0e0;cursor:default}.DayPicker-Day--sunday{background-color:#f7f8f8}.DayPicker-Day--sunday:not(.DayPicker-Day--today){color:#dce0e0}.DayPicker-Day--selected:not(.DayPicker-Day--disabled):not(.DayPicker-Day--outside){position:relative;background-color:#4a90e2;color:#f0f8ff}.DayPicker-Day--selected:not(.DayPicker-Day--disabled):not(.DayPicker-Day--outside):hover{background-color:#51a0fa}.DayPicker:not(.DayPicker--interactionDisabled) .DayPicker-Day:not(.DayPicker-Day--disabled):not(.DayPicker-Day--selected):not(.DayPicker-Day--outside):hover{background-color:#f0f8ff}.DayPickerInput{display:inline-block}.DayPickerInput-OverlayWrapper{position:relative}.DayPickerInput-Overlay{position:absolute;left:0;z-index:1;background:#fff;box-shadow:0 2px 5px rgba(0,0,0,.15)}";
export const DayPickerCustomStyles = (
from: Date | undefined,
to: Date | undefined,
isSameDate: boolean
) => `
${MinifiedDayPickerDefaultStyles}
.DayPicker {
font-family: ${fontNormal};
font-size: ${defaultSize};
}
.DayPicker-Caption {
font-family: ${fontMedium};
font-size: ${defaultSize};
color: ${buildColor("grey", "900")};
}
.DayPicker-Month {
margin: 24px 24px 0;
border-collapse: separate;
border-spacing: 8px;
}
.DayPicker-NavBar {
position: absolute;
right: 24px;
top: 24px;
}
.DayPicker-NavBarElement {
border-radius: 2px;
box-shadow: 0px 2px 2px rgba(17, 43, 68, 0.15);
}
.DayPicker-NavBarElement > button:hover {
background: transparent;
}
.DayPicker-NavBarElement > button:active {
background: ${buildColor("blue_accent", "100")};
}
.DayPicker-Week {
height: 24px;
}
.DayPicker-Day {
padding: 0;
font-size: ${defaultSize};
width: 32px;
height: 32px;
}
.DayPicker-Day:not(.DayPicker-Day--disabled):not(.DayPicker-Day--selected):not(.DayPicker-Day--outside):hover {
border-radius: 50% !important;
background-color: ${buildColor("blue", "100")} !important;
color: ${buildColor("grey", "900")} !important;
}
.DayPicker-Day--secondaryDate:not(.DayPicker-Day--today):not(.DayPicker-Day--outside), .DayPicker-Day--secondaryDate:not(.DayPicker-Day--today):not(.DayPicker-Day--outside):hover {
background-color: ${buildColor("blue_accent", "500")} !important;
color: white;
}
.DayPicker-Day--today:not(.DayPicker-Day--outside) {
border-radius: 50% !important;
border: 1px solid ${buildColor("blue_accent", "500")};
background: transparent;
color: ${buildColor("grey", "900")};
font-weight: normal !important;
}
.DayPicker-Weekday {
font-family: ${fontMedium};
color: ${buildColor("grey", "700")};
}
.DayPicker-Day--disabled {
color: ${buildColor("grey", "600")};
}
.DayPicker-Day--selected:not(.DayPicker-Day--outside) {
background-color: ${buildColor("blue_accent", "500")} !important;
}
.DayPicker-Day--selected:not(.DayPicker-Day--start):not(.DayPicker-Day--end):not(.DayPicker-Day--outside) {
border-radius: 0 !important;
background-color: ${buildColor("blue_accent", "100")} !important;
color: ${buildColor("grey", "900")};
box-shadow: -4px 0 0 0 ${buildColor(
"blue_accent",
"100"
)}, 4px 0 0 0 ${buildColor("blue_accent", "100")};
}
.DayPicker-Day--selected:not(.DayPicker-Day--start):not(.DayPicker-Day--end):not(.DayPicker-Day--outside):hover {
background-color: ${buildColor("blue", "100")} !important;
box-shadow: -4px 0 0 0 ${buildColor("blue", "100")},
4px 0 0 0 ${buildColor("blue", "100")};
}
.DayPicker-Day.DayPicker-Day--end.DayPicker-Day--selected, .DayPicker-Day.DayPicker-Day--start.DayPicker-Day--selected {
border: none !important;
}
.DayPicker-Day--start {
border-radius: 50% !important;
}
.DayPicker-Day--end {
border-radius: 50% !important;
}
${
!!from &&
!!to &&
!isSameDate &&
`.DayPicker-Day--end.DayPicker-Day--selected:not(.DayPicker-Day--outside)::before {
content: " ";
position: absolute;
height: 100%;
width: 100%;
top: 0;
left: 0;
background-color: ${buildColor("blue_accent", "100")} !important;
border-top-right-radius: 50% !important;
border-bottom-right-radius: 50% !important;
box-shadow: -4px 0 0 0 ${buildColor("blue_accent", "100")};
z-index: -1;
}
.DayPicker-Day--start.DayPicker-Day--selected:not(.DayPicker-Day--outside)::before {
content: " ";
position: absolute;
height: 100%;
width: 100%;
top: 0;
left: 0;
background-color: ${buildColor("blue_accent", "100")} !important;
border-top-left-radius: 50% !important;
border-bottom-left-radius: 50% !important;
box-shadow: 4px 0 0 0 ${buildColor("blue_accent", "100")};
z-index: -1;
}`
}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MyBetsDesktopSettledFilters/types.ts
export enum SettledTab {
TODAY = "TODAY",
YESTERDAY = "YESTERDAY",
LAST_WEEK = "LAST_WEEK",
LAST_MONTH = "LAST_MONTH",
DATE_PICKER = "DATE_PICKER"
}
export enum DatePickerStatus {
NONE = "NONE",
START_DATE = "START",
END_DATE = "END"
}
export interface DateRange {
to: Date | undefined;
from?: Date | undefined;
}
export interface Props {
selectNewTimeFrame: Function;
setShowDatePicker: Function;
showDatePicker: DatePickerStatus;
onDateChange: Function;
dateRange: DateRange;
showPresetDate: boolean;
onPresetDateChange: Function;
toggleCustom: Function;
isMonthSelector: boolean;
setIsMonthSelector: Function;
selectedMonth: Date | undefined;
setSelectedMonth: Function;
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MyBetsDesktopSettledFilters/utils.ts
import { subDays, subMonths, subWeeks } from "date-fns";
export const getPreset = (days?: number, type: string = "day") => {
const today = new Date();
let presetDate = {
from: today,
to: today
};
if (days) {
let dateModifier = subDays;
if (type === "month") {
dateModifier = subMonths;
} else if (type === "week") {
dateModifier = subWeeks;
}
presetDate = {
from: dateModifier(today, days),
to: today
};
}
return presetDate;
};
export const datePreset = {
today: getPreset(),
yesterday: getPreset(1),
lastWeek: getPreset(1, "week"),
lastMonth: getPreset(1, "month")
};
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MyBetsDesktopSettledFilters/index.tsx
import React, { useCallback, useMemo } from "react";
import { batch } from "react-redux";
import { noop, get } from "lodash";
import buildColor from "@tvg/atomic-ui/_static/ColorPalette";
import Icon from "@tvg/atomic-ui/_static/Icons";
import { formatDateToMMDDYYYY } from "@tvg/formatter/dates";
import {
calendar,
close,
doubleArrowRight
} from "@tvg/atomic-ui/_static/Icons/icons";
import { Helmet } from "react-helmet";
import DayPicker, { Modifier } from "react-day-picker";
import CustomNavBar from "@tvg/atomic-ui/_molecule/DayPickerCustomNavBar";
import CustomMonthSelector from "@tvg/atomic-ui/_molecule/DayPickerCustomMonthSelector";
import {
DayPickerCustomStyles,
FilterButton,
FiltersContainer,
IconContainer,
DatePickerWrapper,
Divider,
DatePickerOverlay
} from "./styled-components";
import type { Props } from "./types";
import { datePreset } from "./utils";
import { DatePickerStatus, DateRange } from "./types";
const checkPresetSelected = (presetDay: Date, selectedDay?: Date) =>
selectedDay &&
formatDateToMMDDYYYY(presetDay) === formatDateToMMDDYYYY(selectedDay);
const getDisableRules = (
showDatePicker: DatePickerStatus,
dateRange: DateRange
): Modifier | Modifier[] => {
switch (showDatePicker) {
case DatePickerStatus.START_DATE:
return {
after: get(dateRange, "to") as Date
};
case DatePickerStatus.END_DATE:
return {
before: get(dateRange, "from"),
after: datePreset.today.from
};
default:
return undefined;
}
};
const MyBetsDesktopSettledFilters = (props: Props) => {
const {
selectNewTimeFrame,
setShowDatePicker,
showDatePicker,
onDateChange,
dateRange,
showPresetDate,
onPresetDateChange,
toggleCustom,
isMonthSelector,
setIsMonthSelector,
selectedMonth,
setSelectedMonth
} = props;
const { from, to } = dateRange;
const isSameDate = useCallback(() => {
if (from && to) {
return new Date(from || to).getTime() === new Date(to).getTime();
}
return false;
}, [from, to]);
const modifiers = useMemo(() => ({ start: from, end: to }), [from, to]);
const renderDayPicker = useMemo(
() => (
<DatePickerWrapper>
<DatePickerOverlay
onClick={() => {
batch(() => {
setIsMonthSelector(false);
setShowDatePicker(DatePickerStatus.NONE);
});
}}
/>
<DayPicker
month={selectedMonth}
selectedDays={[from, { from, to }]}
modifiers={modifiers}
onDayClick={(date, dayModifiers) => {
if (!dayModifiers.disabled) {
const dayToRange =
showDatePicker === DatePickerStatus.START_DATE
? {
to,
from: date
}
: {
from,
to: date
};
onDateChange(dayToRange);
}
}}
disabledDays={getDisableRules(showDatePicker, dateRange)}
captionElement={({ date, localeUtils }) => (
<CustomMonthSelector
date={date}
localeUtils={localeUtils}
initialYearRange={21}
isMonthSelector={isMonthSelector}
setIsMonthSelector={setIsMonthSelector}
selectedMonth={selectedMonth || new Date()}
setSelectedMonth={setSelectedMonth}
/>
)}
navbarElement={({ onPreviousClick, onNextClick }) => (
<CustomNavBar
onPreviousClick={onPreviousClick}
onNextClick={onNextClick}
/>
)}
/>
</DatePickerWrapper>
),
[
isMonthSelector,
selectedMonth,
showDatePicker,
modifiers,
from,
to,
isSameDate()
]
);
return !showPresetDate ? (
<>
<FiltersContainer calendar>
<FilterButton
data-qa-label="bets-settled-calendar-start-tab"
onClick={() => {
setShowDatePicker(DatePickerStatus.START_DATE);
setSelectedMonth(from);
}}
calendar
selected={showDatePicker === DatePickerStatus.START_DATE}
>
<Icon icon={calendar} color={buildColor("black", "70")} size={16} />{" "}
{(from && formatDateToMMDDYYYY(from)) || "MM/DD/YYYY"}
</FilterButton>
<IconContainer>
<Icon
icon={doubleArrowRight}
color={buildColor("grey", "800")}
size={14}
/>
</IconContainer>
<FilterButton
data-qa-label="bets-settled-calendar-end-tab"
onClick={() => {
setShowDatePicker(DatePickerStatus.END_DATE);
setSelectedMonth(to);
}}
calendar
selected={showDatePicker === DatePickerStatus.END_DATE}
>
<Icon icon={calendar} color={buildColor("black", "70")} size={16} />{" "}
{(to && formatDateToMMDDYYYY(to)) || "MM/DD/YYYY"}
</FilterButton>
<Divider />
<FilterButton
data-qa-label="bets-settled-calendar-close-tab"
onClick={() => {
onPresetDateChange(true);
selectNewTimeFrame?.("TODAY");
toggleCustom(false);
setSelectedMonth(new Date());
}}
>
<Icon icon={close} color={buildColor("grey", "800")} size={16} />
</FilterButton>
</FiltersContainer>
{showDatePicker !== DatePickerStatus.NONE && renderDayPicker}
<Helmet>
<style>{DayPickerCustomStyles(from, to, isSameDate())}</style>
</Helmet>
</>
) : (
<FiltersContainer>
<FilterButton
data-qa-label="bets-settled-today-tab"
selected={!from || checkPresetSelected(datePreset.today.from, from)}
onClick={() => {
toggleCustom(false);
selectNewTimeFrame?.("TODAY");
onDateChange(datePreset.today);
}}
>
Today
</FilterButton>
<FilterButton
data-qa-label="bets-settled-yesterday-tab"
selected={checkPresetSelected(datePreset.yesterday.from, from)}
onClick={() => {
toggleCustom(false);
selectNewTimeFrame?.("YESTERDAY");
onDateChange(datePreset.yesterday);
}}
>
Since Yesterday
</FilterButton>
<FilterButton
data-qa-label="bets-settled-last_week-tab"
selected={checkPresetSelected(datePreset.lastWeek.from, from)}
onClick={() => {
toggleCustom(false);
selectNewTimeFrame?.("LAST_WEEK");
onDateChange(datePreset.lastWeek);
}}
>
Last Week
</FilterButton>
<FilterButton
data-qa-label="bets-settled-last_month-tab"
selected={checkPresetSelected(datePreset.lastMonth.from, from)}
onClick={() => {
toggleCustom(false);
selectNewTimeFrame?.("LAST_MONTH");
onDateChange(datePreset.lastMonth);
}}
>
Last Month
</FilterButton>
<FilterButton
data-qa-label="bets-settled-calendar-open-tab"
onClick={() => {
toggleCustom(true);
onPresetDateChange(false);
}}
>
<Icon icon={calendar} color={buildColor("black", "70")} size={16} />
</FilterButton>
</FiltersContainer>
);
};
MyBetsDesktopSettledFilters.defaultProps = {
setShowDatePicker: noop,
showDatePicker: false,
onDateChange: noop,
dateRange: datePreset.today,
showPresetDate: true,
onPresetDateChange: noop,
isMonthSelector: false,
setIsMonthSelector: noop
};
export default MyBetsDesktopSettledFilters;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/Checkbox/styled-components.js
import styled, { css } from "styled-components";
import buildColor from "../../_static/ColorPalette";
export const Container = styled.label`
display: flex;
align-items: center;
${({ cursorPointer }) =>
cursorPointer &&
css`
cursor: pointer;
`}
`;
export const HiddenCheckbox = styled.input.attrs({ type: "checkbox" })`
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
white-space: nowrap;
width: 1px;
`;
export const CheckboxContainer = styled.div`
display: inline-block;
vertical-align: middle;
`;
export const StyledCheckbox = styled.div`
display: flex;
justify-content: center;
align-items: center;
height: 24px;
width: 24px;
margin: 0 8px 0 0;
border-radius: 3px;
${({ checked }) =>
checked
? css`
background: ${buildColor("blue_accent", "500")};
border: 1px solid ${buildColor("blue_accent", "500")};
`
: css`
background: ${buildColor("white", "100")};
border: 1px solid ${buildColor("blue", "200")};
box-shadow: 0 2px 2px rgb(17 43 68 / 15%);
`};
`;
export const Label = styled.div`
font-size: 14px;
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/Checkbox/index.jsx
import React from "react";
import { noop } from "lodash";
import buildColor from "../../_static/ColorPalette";
import Icon from "../../_static/Icons";
import { tick } from "../../_static/Icons/icons";
import {
Container,
CheckboxContainer,
HiddenCheckbox,
StyledCheckbox,
Label
} from "./styled-components";
const Checkbox = (props) => (
<Container
cursorPointer={props.cursorPointer}
data-qa-label={`${props.qaLabel}-wrapper-${props.value}`}
>
<CheckboxContainer className={props.className}>
<HiddenCheckbox
data-qa-label={`${props.qaLabel}-checkbox`}
checked={props.checked}
{...props}
/>
<StyledCheckbox checked={props.checked}>
{props.checked && (
<Icon icon={tick} color={buildColor("white", "100")} />
)}
</StyledCheckbox>
</CheckboxContainer>
<Label data-qa-label={`${props.qaLabel}-label`}>{props.label}</Label>
</Container>
);
Checkbox.defaultProps = {
className: "",
checked: false,
label: "",
name: "checkbox",
value: "",
onChange: noop,
qaLabel: "checkbox",
cursorPointer: false
};
export default Checkbox;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MultipleSelectionDropdown/styled-components.js
import styled, { css } from "styled-components";
import buildColor from "../../_static/ColorPalette";
import { fontBold, fontMedium, fontNormal } from "../../_static/Typography";
export const FilterContainer = styled.div`
margin: 14px 6px;
`;
export const SelectButton = styled.button`
border: 1px solid ${buildColor("blue", "100")};
box-shadow: 0 2px 2px rgba(17, 43, 68, 0.15);
padding-left: 8px;
display: flex;
height: 100%;
border-radius: 3px;
align-items: center;
font-family: ${fontMedium};
background-color: transparent;
color: ${buildColor("black", "70")};
cursor: pointer;
${(props) =>
props.isExpanded &&
css`
background-color: ${buildColor("blue_accent", "100")};
box-shadow: none;
`}
${(props) =>
props.isDisabled &&
css`
color: ${buildColor("grey", "500")};
`}
${(props) =>
!props.isDisabled &&
css`
& :hover {
background-color: ${buildColor("blue_accent", "000")};
}
`}
`;
export const Selections = styled.div`
position: absolute;
margin-top: 10px;
font-family: ${fontMedium};
overflow-y: auto;
max-height: ${(props) =>
`calc(100vh - ${props.offsetTop + props.offsetBottom}px)`};
min-width: 180px;
border: 1px solid ${buildColor("blue", "100")};
border-radius: 3px;
background-color: ${buildColor("white", "100")};
padding: 6px;
padding-bottom: 0;
z-index: 902;
box-shadow: 0 3px 3px rgba(17, 43, 68, 0.15);
${(props) =>
!props.isExpanded &&
css`
visibility: hidden;
`}
`;
export const IconContainer = styled.div`
display: flex;
align-items: center;
padding: 0 6px;
`;
export const ClearButton = styled.button`
background-color: ${buildColor("white", "100")};
font-family: ${fontMedium};
color: ${buildColor("blue_accent", "500")};
cursor: pointer;
${(props) =>
props.isDisabled &&
css`
color: ${buildColor("blue_accent", "300")};
`}
`;
export const SelectionsHeader = styled.div`
display: flex;
justify-content: space-between;
height: 20px;
align-items: center;
font-family: ${fontMedium};
font-size: 13.33px;
padding: 10px 10px 0 4px;
color: ${buildColor("black", "70")};
margin-bottom: 22px;
`;
export const Overlay = styled.div`
position: fixed;
background-color: transparent;
top: 68px;
left: 0;
right: 0;
bottom: 0;
z-index: 901;
`;
export const HeaderOverlay = styled.div`
position: fixed;
background-color: transparent;
top: 0;
left: 0;
right: 0;
height: 68px;
z-index: 1002;
`;
export const CheckboxName = styled.span`
margin-block: auto;
font-family: ${fontNormal};
cursor: pointer;
`;
export const CheckboxContainer = styled.div`
display: flex;
margin: 16px 4px;
&:last-child {
margin-bottom: 12px;
}
`;
export const SelectionsCounter = styled.div`
position: absolute;
display: flex;
align-items: center;
justify-content: center;
background-color: ${buildColor("blue_accent", "500")};
color: ${buildColor("white", "100")};
border-radius: 7px;
height: 14px;
width: 14px;
font-size: 11px;
font-family: ${fontBold};
z-index: 901;
margin-left: ${(props) => props.filterWidth}px;
`;
export const SelectionsCounterContainer = styled.div`
margin-top: 10px;
${(props) =>
!props.isVisible &&
css`
visibility: hidden;
`}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MultipleSelectionDropdown/index.jsx
import React, {
Fragment,
useState,
useLayoutEffect,
useEffect,
useRef
} from "react";
import { noop, get } from "lodash";
import Icon from "@tvg/atomic-ui/_static/Icons";
import Checkbox from "@tvg/atomic-ui/_atom/Checkbox";
import { arrowDown, arrowUp } from "@tvg/atomic-ui/_static/Icons/icons";
import {
FilterContainer,
SelectButton,
IconContainer,
Selections,
SelectionsHeader,
ClearButton,
Overlay,
CheckboxName,
CheckboxContainer,
SelectionsCounter,
SelectionsCounterContainer,
HeaderOverlay
} from "@tvg/atomic-ui/_molecule/MultipleSelectionDropdown/styled-components";
import buildColor from "@tvg/atomic-ui/_static/ColorPalette";
const MultipleSelectionDropdown = ({
name,
isExpanded,
setExpanded,
isDisabled,
setFilter,
filterCount,
filterKeys,
filterValues,
offsetBottom
}) => {
const [filterWidth, setFilterWidth] = useState(0);
const [selectionsTop, setSelectionsTop] = useState(0);
const filterRef = useRef(null);
const selectionsRef = useRef(null);
useLayoutEffect(() => {
setFilterWidth(get(filterRef, "current.clientWidth", 0));
if (selectionsRef.current) {
const selectionsRect = selectionsRef.current.getBoundingClientRect();
setSelectionsTop(get(selectionsRect, "top", 0));
}
}, []);
useEffect(() => {
if (isExpanded && selectionsRef && selectionsRef.current) {
selectionsRef.current.scrollTo({ top: 0 });
}
}, [selectionsRef, isExpanded]);
return (
<Fragment>
<SelectionsCounterContainer
isVisible={!!filterCount}
filterWidth={filterWidth}
>
<SelectionsCounter filterWidth={filterWidth}>
{filterCount}
</SelectionsCounter>
</SelectionsCounterContainer>
<FilterContainer>
{isExpanded && <HeaderOverlay onClick={() => setExpanded(false)} />}
{isExpanded && <Overlay onClick={() => setExpanded(false)} />}
<SelectButton
ref={filterRef}
id={`${name}MultiselectFilterButton`}
disabled={isDisabled && !filterCount}
isDisabled={isDisabled && !filterCount}
isExpanded={isExpanded}
onClick={() => setExpanded(true)}
>
<span>{name}</span>
<IconContainer>
<Icon
icon={isExpanded ? arrowUp : arrowDown}
color={buildColor(
"grey",
isDisabled && !filterCount ? "500" : "800"
)}
size={14}
/>
</IconContainer>
</SelectButton>
<Selections
ref={selectionsRef}
offsetTop={selectionsTop}
offsetBottom={offsetBottom}
isExpanded={isExpanded}
>
<SelectionsHeader>
<span>{name}</span>
<ClearButton
disabled={filterCount === 0}
isDisabled={filterCount === 0}
onClick={() => setFilter("clear")}
>
Clear
</ClearButton>
</SelectionsHeader>
{filterKeys.map((key, index) => (
<CheckboxContainer key={key}>
<Checkbox
qaLabel={`${name}FilterCheckbox`}
checked={filterValues[index]}
onChange={() => setFilter(key)}
cursorPointer
/>
<CheckboxName onClick={() => setFilter(key)}>{key}</CheckboxName>
</CheckboxContainer>
))}
</Selections>
</FilterContainer>
</Fragment>
);
};
MultipleSelectionDropdown.defaultProps = {
name: "Filter",
setExpanded: noop,
isExpanded: false,
isDisabled: true,
selectedFilters: {
Canceled: false,
Refunded: false,
Won: false,
Lost: false
},
filterCount: 0,
filterKeys: [],
filterValues: []
};
export default MultipleSelectionDropdown;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MyBetsCounter/styled-components.js
import styled, { css } from "styled-components";
import tvgConf from "@tvg/conf";
import buildColor from "../../_static/ColorPalette";
import { fontBold, fontCondensedNormal } from "../../_static/Typography";
const isDesktop = tvgConf().device === "desktop";
export const CounterContainer = styled.div`
display: flex;
align-items: center;
padding-right: 12px;
`;
export const NormalCounter = styled.span`
font-weight: 700;
font-family: ${fontBold};
${isDesktop
? css`
padding-right: 0;
line-height: 24px;
font-size: 18px;
color: ${buildColor("blue", "600")};
`
: css`
padding-right: 4px;
font-size: 14px;
color: ${buildColor("grey", "900")};
`}
`;
export const DollarCounter = styled.span`
padding-left: 16px;
font-weight: 700;
font-family: ${fontBold};
${isDesktop
? css`
padding-right: 0;
padding-bottom: 2px;
font-size: 18px;
line-height: 24px;
color: ${buildColor("blue", "600")};
`
: css`
padding-right: 4px;
font-size: 14px;
color: ${buildColor("grey", "900")};
`};
`;
export const CounterDescription = styled.span`
font-size: 12px;
font-family: ${fontCondensedNormal};
color: ${buildColor("grey", "800")};
${isDesktop &&
css`
line-height: 14px;
color: ${buildColor("grey", "700")};
`}
`;
export const BetsContainer = styled.div`
display: flex;
flex-direction: column;
align-items: flex-end;
margin-left: 24px;
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MyBetsCounter/index.jsx
import React from "react";
import { formatCurrency } from "@tvg/formatter";
import tvgConf from "@tvg/conf";
import {
CounterContainer,
NormalCounter,
CounterDescription,
DollarCounter,
BetsContainer
} from "./styled-components";
const MyBetsCounter = (props) => {
const renderDesktop = () => (
<CounterContainer>
<BetsContainer>
<NormalCounter data-qa-label="bet-counter">
{props.betsCounter}
</NormalCounter>
<CounterDescription data-qa-label="bet-counter-description">
{props.betsCounter === 1 ? "BET" : "BETS"}
</CounterDescription>
</BetsContainer>
<BetsContainer>
<DollarCounter data-qa-label="amount-wagered">
{formatCurrency(props.wageredAmount)}
</DollarCounter>
<CounterDescription data-qa-label="amount-wagered-description">
AMOUNT WAGERED
</CounterDescription>
</BetsContainer>
</CounterContainer>
);
const renderMobile = () => (
<CounterContainer>
<NormalCounter data-qa-label="bet-counter">
{props.betsCounter}
</NormalCounter>
<CounterDescription data-qa-label="bet-counter-description">
{props.betsCounter === 1 ? "BET" : "BETS"}
</CounterDescription>
<DollarCounter data-qa-label="amount-wagered">
{formatCurrency(props.wageredAmount)}
</DollarCounter>
<CounterDescription data-qa-label="amount-wagered-description">
WAGERED
</CounterDescription>
</CounterContainer>
);
return tvgConf().device === "desktop" ? renderDesktop() : renderMobile();
};
MyBetsCounter.defaultProps = {
betsCounter: 0,
wageredAmount: 0
};
export default MyBetsCounter;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_templates/MyBetsHeaderDesktop/styled-components.ts
import styled, { css } from "styled-components";
import buildColor from "@tvg/atomic-ui/_static/ColorPalette";
import { fontBold } from "@tvg/atomic-ui/_static/Typography";
export const Container = styled.div`
position: sticky;
min-height: 88px;
width: 100%;
z-index: 10;
top: calc(var(--header-height, -8px) + 8px);
&::before {
content: "";
position: absolute;
top: -8px;
right: 0;
width: 100%;
height: 8px;
box-shadow: inset 0 1px 2px rgba(17, 43, 68, 0.08);
background-color: ${buildColor("blue", "900")};
}
&::after {
content: "";
position: absolute;
bottom: -12px;
right: 0;
width: 100%;
height: 12px;
box-shadow: inset 0 1px 2px rgba(17, 43, 68, 0.08);
background-color: ${buildColor("blue", "000")};
}
`;
export const HeaderContent = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
position: relative;
height: 88px;
padding: 0 24px;
border-radius: 4px 4px 0 0;
box-shadow: 0 -4px 0 ${buildColor("blue", "900")};
background-color: ${buildColor("white", "100")};
`;
export const FiltersContent = styled.div`
display: flex;
height: 56px;
padding: 0 24px;
background-color: ${buildColor("white", "100")};
`;
export const FlexColumn = styled.div`
display: flex;
flex: 1 1 0;
justify-content: ${(props: {
justify?: "center" | "flex-start" | "flex-end";
}) => props.justify || "flex-start"};
`;
export const Controllers = styled.div`
min-width: ${(props: { withFutures?: boolean }) =>
props.withFutures ? "321px" : "216px"};
`;
export const ClearAllButton = styled.button`
color: ${buildColor("blue_accent", "500")};
font-family: ${fontBold};
margin-left: 8px;
margin-right: 8px;
margin-block: auto;
background-color: white;
cursor: pointer;
${(props: { isDisabled?: boolean }) =>
props.isDisabled &&
css`
color: ${buildColor("blue_accent", "200")};
`}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_templates/MyBetsHeaderDesktop/index.tsx
import React, { FC } from "react";
import Title from "@tvg/atomic-ui/_atom/Title";
import SegmentedControl from "@tvg/atomic-ui/_molecule/SegmentedControl";
import buildColor from "@tvg/atomic-ui/_static/ColorPalette";
import MyBetsDesktopSettledFilters from "@tvg/atomic-ui/_molecule/MyBetsDesktopSettledFilters";
import MultipleSelectionDropdown from "@tvg/atomic-ui/_molecule/MultipleSelectionDropdown";
import MyBetsCounter from "@tvg/atomic-ui/_molecule/MyBetsCounter";
import { noop } from "lodash";
import { ActiveTabEnum } from "@tvg/sh-lib-my-bets/utils/types";
import {
Container,
HeaderContent,
FiltersContent,
FlexColumn,
Controllers,
ClearAllButton
} from "./styled-components";
import { Props } from "./types";
const MyBetsHeaderDesktopTemplate: FC<Props> = ({
title,
tabs,
selectedTab,
selectNewTimeFrame,
isStatusFilterExpanded,
setStatusFilter,
isStatusFilterDisabled,
setStatusExpanded,
currentStatusFilters,
statusFilterCount,
trackList,
setTrackListFilter,
isTrackFilterExpanded,
setTrackFilterExpanded,
isTracksFilterDisabled,
trackFilterCount,
trackListToggles,
counters,
betTypeList,
betTypeListToggles,
isBetTypeFilterExpanded,
setBetTypeFilterExpanded,
isBetTypesFilterDisabled,
setBetTypeListFilter,
betTypeFilterCount,
isClearAllDisabled,
clearAllFilters,
setShowDatePicker,
showDatePicker,
onDateChange,
dateRange,
showPresetDate,
onPresetDateChange,
toggleCustom,
isMonthSelector,
setIsMonthSelector,
selectedMonth,
setSelectedMonth,
filtersOffsetBottom
}) => (
<Container data-qa-label="myBets-header">
<HeaderContent>
<FlexColumn>
<Title
color={buildColor("blue", "900")}
uppercase={false}
fontFamilySecondary
>
{title}
</Title>
</FlexColumn>
<FlexColumn justify="center">
<Controllers
data-qa-label="myBets-controllers"
withFutures={tabs.length === 3}
>
<SegmentedControl tabs={tabs} withAnimation />
</Controllers>
</FlexColumn>
<FlexColumn justify="flex-end">
<MyBetsCounter
wageredAmount={counters.amount}
betsCounter={counters.counter}
/>
</FlexColumn>
</HeaderContent>
{selectedTab === "SETTLED" && (
<FiltersContent data-qa-label="myBets-filters">
<MyBetsDesktopSettledFilters
selectNewTimeFrame={selectNewTimeFrame}
setShowDatePicker={setShowDatePicker}
showDatePicker={showDatePicker}
onDateChange={onDateChange}
dateRange={dateRange}
showPresetDate={showPresetDate}
onPresetDateChange={onPresetDateChange}
toggleCustom={toggleCustom}
setIsMonthSelector={setIsMonthSelector}
isMonthSelector={isMonthSelector}
selectedMonth={selectedMonth}
setSelectedMonth={setSelectedMonth}
/>
<MultipleSelectionDropdown
name="Status"
isExpanded={isStatusFilterExpanded}
setExpanded={setStatusExpanded}
isDisabled={isStatusFilterDisabled}
setFilter={setStatusFilter}
selectedFilters={currentStatusFilters}
filterKeys={Object.keys(currentStatusFilters)}
filterValues={Object.values(currentStatusFilters)}
filterCount={statusFilterCount}
/>
<MultipleSelectionDropdown
name="Tracks"
isExpanded={isTrackFilterExpanded}
setExpanded={setTrackFilterExpanded}
isDisabled={isTracksFilterDisabled}
setFilter={setTrackListFilter}
filterKeys={trackList}
filterValues={trackListToggles}
filterCount={trackFilterCount}
offsetBottom={filtersOffsetBottom}
/>
<MultipleSelectionDropdown
name="Bet Type"
isExpanded={isBetTypeFilterExpanded}
setExpanded={setBetTypeFilterExpanded}
isDisabled={isBetTypesFilterDisabled}
setFilter={setBetTypeListFilter}
filterKeys={betTypeList}
filterValues={betTypeListToggles}
filterCount={betTypeFilterCount}
offsetBottom={filtersOffsetBottom}
/>
<ClearAllButton
isDisabled={isClearAllDisabled}
disabled={isClearAllDisabled}
onClick={() => clearAllFilters()}
>
Clear All
</ClearAllButton>
</FiltersContent>
)}
</Container>
);
MyBetsHeaderDesktopTemplate.defaultProps = {
title: "Racing Bets",
selectedTab: ActiveTabEnum.ACTIVE,
tabs: [],
isStatusFilterExpanded: false,
setStatusFilter: () => {},
isStatusFilterDisabled: true,
setStatusExpanded: () => {},
statusFilterCount: 0,
trackList: [],
setTrackListFilter: () => {},
isTrackFilterExpanded: false,
setTrackFilterExpanded: () => {},
isTracksFilterDisabled: false,
trackFilterCount: 0,
trackListToggles: [],
betTypeList: [],
betTypeListToggles: [],
isBetTypeFilterExpanded: false,
setBetTypeFilterExpanded: () => {},
isBetTypesFilterDisabled: true,
setBetTypeListFilter: () => {},
betTypeFilterCount: 0,
isClearAllDisabled: true,
clearAllFilters: () => {},
toggleCustom: () => {},
customEndDate: undefined,
customStartDate: undefined,
setShowDatePicker: noop,
showDatePicker: undefined,
onDateChange: noop,
dateRange: {
to: new Date(),
from: undefined
},
showPresetDate: true,
onPresetDateChange: noop
};
export default MyBetsHeaderDesktopTemplate;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/Table/styled-components.ts
import styled, { css } from "styled-components";
import buildColor from "@tvg/atomic-ui/_static/ColorPalette";
import { fontMedium } from "@tvg/atomic-ui/_static/Typography";
export const TableWrapper = styled.table`
width: 100%;
border-radius: 4px;
background-color: ${buildColor("white", "100")};
border-collapse: separate;
`;
export const BodySectionWrapper = styled.tbody`
tr {
&:not(:last-of-type) td {
box-shadow: inset 0 -1px 0 ${buildColor("blue", "100")};
}
&:hover {
background-color: ${buildColor("blue_accent", "000")};
td:first-of-type {
box-shadow:
inset 0 -1px 0 ${buildColor("blue", "100")},
inset 2px 0 0 ${buildColor("blue_accent", "500")};
}
&:last-of-type td:first-of-type {
box-shadow: inset 2px 0 0 ${buildColor("blue_accent", "500")};
}
}
&:last-of-type {
border-radius: 0 0 4px 4px;
td:first-of-type {
border-radius: 0 0 0 4px;
}
td:last-of-type {
border-radius: 0 0 4px;
}
}
}
`;
export const HeadCellWrapper = styled.th<{
colSize?: string;
addShadow?: boolean;
isPositionRelative?: boolean;
}>`
text-align: left;
padding: 12px;
line-height: 17px;
font-size: 12px;
font-weight: 500;
font-family: ${fontMedium};
border-right: 1px solid ${buildColor("blue", "100")};
color: ${buildColor("grey", "900")};
background-color: ${buildColor("blue_accent", "000")};
width: ${(props) => props.colSize || "auto"};
box-shadow:
inset 0 -1px 0 ${buildColor("blue", "100")},
0 -4px 0 ${buildColor("blue", "000")};
background-clip: padding-box;
${(props) =>
props.addShadow &&
css`
&::after {
content: "";
position: absolute;
width: 100%;
bottom: -1px;
left: 0;
z-index: -1;
transform: scale(1);
box-shadow: 0 0 2px 1px rgba(17, 43, 68, 0.15);
}
`};
&:first-of-type {
border-radius: 4px 0 0;
}
&:last-of-type {
border-radius: 0 4px 0 0;
border-right: 0 none;
}
${(props) =>
props.isPositionRelative &&
css`
padding-bottom: 36px;
position: relative;
`}
`;
export const BodyCellWrapper = styled.td<{
colSize?: string;
isPositionRelative?: boolean;
}>`
padding: 12px;
vertical-align: top !important;
width: ${(props) => props.colSize || "auto"};
border-right: 1px solid ${buildColor("blue", "100")};
position: relative;
&:last-of-type {
border-right: 0 none;
}
${(props) =>
props.isPositionRelative &&
css`
padding-bottom: 36px;
position: relative;
`}
`;
export const HeadSectionWrapper = styled.thead<{
headerSticky?: boolean;
}>`
${(props) =>
props.headerSticky &&
css`
th {
position: sticky;
top: 0;
z-index: 6;
}
`};
`;
export const RowWrapper = styled.tr``;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/Table/index.tsx
/* eslint-disable react/no-array-index-key */
import React, { forwardRef } from "react";
import { TableProps, RowProps, CellProps } from "./types";
import {
TableWrapper,
RowWrapper,
HeadSectionWrapper,
BodySectionWrapper,
HeadCellWrapper,
BodyCellWrapper
} from "./styled-components";
const Table = forwardRef<HTMLTableElement, TableProps>(
(
{
children,
headerShadow,
headerSticky,
theadData,
qaLabel = "table",
...rest
},
ref
) => (
<TableWrapper {...rest} ref={ref} data-qa-label={qaLabel}>
{theadData && (
<HeadSectionWrapper headerSticky={headerSticky}>
<TableRow qaLabel={`${qaLabel}-thead-row`}>
{theadData.map((item, index) => (
<TableCell
key={`table-thead-cell-${index}`}
type="th"
colSize={item.size || "auto"}
addShadow={!!headerShadow}
>
{item.title}
</TableCell>
))}
</TableRow>
</HeadSectionWrapper>
)}
{children && <BodySectionWrapper>{children}</BodySectionWrapper>}
</TableWrapper>
)
);
const TableRow = forwardRef<HTMLTableRowElement, RowProps>(
({ children, qaLabel = "table-tbody-row", ...rest }, ref) => (
<RowWrapper {...rest} ref={ref} data-qa-label={qaLabel}>
{children}
</RowWrapper>
)
);
const TableCell = forwardRef<HTMLTableCellElement, CellProps>(
({ children, type = "td", qaLabel = "table-cell", ...rest }, ref) => {
if (type === "th") {
return (
<HeadCellWrapper
{...rest}
ref={ref}
data-qa-label={`${qaLabel}-${type}`}
>
{children}
</HeadCellWrapper>
);
}
return (
<BodyCellWrapper {...rest} ref={ref} data-qa-label={`${qaLabel}-${type}`}>
{children}
</BodyCellWrapper>
);
}
);
export default Object.assign(Table, {
Row: TableRow,
Cell: TableCell
});
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Masks/accountTransactionsList.jsx
import React, { PureComponent } from "react";
import styled, { keyframes } from "styled-components";
import color from "../ColorPalette";
const pulseAnimation = keyframes`
0% {
fill: ${color("blue", "000")};
}
50% {
fill: ${color("blue", "100")};
}
100% {
fill: ${color("blue", "000")};
}
`;
const SVG = styled.svg`
display: block;
width: 100%;
height: 113px;
rect.pulse {
animation: ${pulseAnimation} 1.25s infinite;
}
`;
export default class AccountTransactionsListMask extends PureComponent {
render() {
return (
<div data-qa-label="accountTransactionsListMask">
<SVG>
<g>
<rect
width="100%"
height="112"
transform="translate(0 1)"
fill={color("white", "100")}
/>
<path
d="M20 18.6C20 18.6 20 16.2 17 16.2M17 16.2C14 16.2 14 18.6 14 18.6C14 19.4 14 20.2 17 21C20 21.8 20 22.6 20 23.4C20 23.4 20 25.8 17 25.8M17 16.2V14M17 25.8C14 25.8 14 23.4 14 23.4M17 25.8V28M26.5 20.75L24 23.25L21.5 20.75M24 18V23.1953"
stroke={color("grey", "900")}
strokeWidth="1.5"
strokeLinejoin="round"
/>
<rect
className="pulse"
x="40"
y="13"
width="80"
height="16"
rx="2"
fill={color("blue", "000")}
/>
<rect
className="pulse"
x="306"
y="13"
width="57"
height="16"
rx="2"
fill={color("blue", "000")}
/>
<rect
className="pulse"
x="313"
y="33"
width="50"
height="12"
rx="2"
fill={color("blue", "000")}
/>
<rect
className="pulse"
x="320"
y="53"
width="43"
height="12"
rx="2"
fill={color("blue", "000")}
/>
<rect
className="pulse"
x="40"
y="89"
width="115"
height="12"
rx="2"
fill={color("blue", "000")}
/>
<rect
className="pulse"
x="12"
y="13"
width="16"
height="16"
rx="2"
fill={color("blue", "000")}
/>
<rect
className="pulse"
x="40"
y="33"
width="100"
height="12"
rx="2"
fill={color("blue", "000")}
/>
<rect
className="pulse"
x="40"
y="53"
width="38"
height="12"
rx="2"
fill={color("blue", "000")}
/>
</g>
</SVG>
</div>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Masks/accountTransactionsHeader.jsx
import React, { PureComponent } from "react";
import styled, { keyframes } from "styled-components";
import color from "../ColorPalette";
const pulseAnimation = keyframes`
0% {
fill: ${color("blue", "000")};
}
50% {
fill: ${color("blue", "100")};
}
100% {
fill: ${color("blue", "000")};
}
`;
const SVG = styled.svg`
display: block;
width: 100%;
height: 48px;
rect.pulse {
animation: ${pulseAnimation} 1.25s infinite;
}
`;
export default class AccountTransactionsHeaderMask extends PureComponent {
render() {
return (
<div data-qa-label="accountTransactionsHeaderMask">
<SVG>
<g>
<rect width="100%" height="48" fill={color("white", "100")} />
<rect
className="pulse"
x="12"
y="12"
width="112"
height="24"
rx="2"
fill={color("blue", "000")}
/>
<rect
className="pulse"
x="321"
y="16"
width="42"
height="16"
rx="2"
fill={color("blue", "000")}
/>
<rect
className="pulse"
x="301"
y="16"
width="16"
height="16"
rx="2"
fill={color("blue", "000")}
/>
</g>
</SVG>
</div>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Masks/results.jsx
import React, { PureComponent } from "react";
import styled from "styled-components";
import { titleFont } from "../Typography";
import buildColor from "../ColorPalette";
const SVGContainer = styled.div`
position: relative;
font-family: ${titleFont};
background: ${buildColor("white", "100")};
`;
const SVG = styled.svg`
display: block;
width: 100%;
height: 393px;
text {
fill: #c2c2c2;
font-size: 12px;
}
`;
const SVGAbsolute = styled(SVG)`
position: absolute;
top: 0;
right: 8px;
display: block;
width: 107px;
height: auto;
`;
export default class ResultsMask extends PureComponent {
render() {
return (
<SVGContainer data-qa-label="resultsMask">
<SVG>
<g fill="none" fillRule="evenodd">
<rect width="100%" height="1" y="248" fill="#F0F3F6" />
<rect width="100%" height="1" y="239" fill="#F0F3F6" />
<rect width="100%" height="1" y="199" fill="#F7F8FA" />
<rect width="100%" height="1" y="159" fill="#F7F8FA" />
<rect width="100%" height="1" y="96" fill="#F7F8FA" />
<rect width="100%" height="1" y="296" fill="#F0F3F6" />
<rect width="100%" height="1" y="344" fill="#F0F3F6" />
<rect width="100%" height="1" y="392" fill="#F0F3F6" />
<rect width="100%" height="1" y="31" fill="#F0F3F6" />
<rect width="100%" height="31" fill="#F7F8FA" />
</g>
<g fill="#f3f3f3" transform="translate(8 11)">
<rect width="72" height="8" y="249" />
<rect width="24" height="8" y="265" />
<rect width="72" height="8" y="297" />
<rect width="24" height="8" y="313" />
<rect width="72" height="8" y="345" />
<rect width="24" height="8" y="361" />
<rect width="72" height="8" y="393" />
<rect width="24" height="8" y="409" />
<text>
<tspan x="0" y="212">
4TH
</tspan>
</text>
<rect width="16" height="16" x="29" y="201" />
<rect width="88" height="16" x="53" y="201" />
<text>
<tspan x="0" y="172">
3RD
</tspan>
</text>
<rect width="16" height="16" x="29" y="161" />
<rect width="96" height="16" x="53" y="161" />
<text>
<tspan x="0" y="108">
2ND
</tspan>
</text>
<rect width="16" height="16" x="29" y="97" />
<rect width="56" height="16" x="53" y="97" />
<text>
<tspan x="0" y="45">
1ST
</tspan>
</text>
<rect width="16" height="16" x="29" y="34" />
<rect width="140" height="16" x="53" y="34" />
<text>
<tspan x="34.34" y="9">
#
</tspan>
</text>
<text>
<tspan x=".23" y="9">
POS
</tspan>
</text>
<text>
<tspan x="52.69" y="9">
RUNNER
</tspan>
</text>
</g>
</SVG>
<SVGAbsolute>
<g fill="#f3f3f3" fillRule="evenodd" transform="translate(0 11)">
<rect width="40" height="8" x="80" y="257" />
<rect width="40" height="8" x="80" y="305" />
<rect width="40" height="8" x="80" y="353" />
<rect width="40" height="8" x="80" y="401" />
<rect width="51" height="8" x="68" y="133" />
<rect width="51" height="8" y="70" />
<rect width="51" height="8" x="69" y="70" />
<text>
<tspan x=".21" y="11">
WIN
</tspan>
</text>
<text>
<tspan x="68.27" y="11">
PLACE
</tspan>
</text>
</g>
</SVGAbsolute>
</SVGContainer>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Masks/homepage.jsx
import React, { PureComponent } from "react";
import styled, { keyframes } from "styled-components";
import color from "../ColorPalette";
const pulseAnimation = keyframes`
0% {
fill: ${color("blue", "000")};
}
50% {
fill: ${color("blue", "100")};
}
100% {
fill: ${color("blue", "000")};
}
`;
const SVG = styled.svg`
display: block;
width: 100%;
height: 720px;
background: ${color("white", "100")};
rect.pulse {
animation: ${pulseAnimation} 1.25s infinite;
}
`;
export default class ResultsMask extends PureComponent {
render() {
return (
<div data-qa-label="homepageMask">
<SVG>
<g>
<rect fill={color("white", "100")} height="100%" width="100%" />
<rect fill={color("blue", "000")} height="40" width="100%" />
<rect
className="pulse"
width="120"
height="8"
x="8"
y="16"
rx="1"
ry="1"
fill={color("blue", "000")}
/>
<rect width="100%" height="1" y="40" fill={color("blue", "000")} />
<rect
className="pulse"
width="126"
height="8"
x="8"
y="64"
rx="1"
ry="1"
fill={color("blue", "000")}
/>
<rect width="100%" height="1" y="96" fill={color("blue", "000")} />
<rect
className="pulse"
width="86"
height="8"
x="8"
y="120"
rx="1"
ry="1"
fill={color("blue", "000")}
/>
<rect width="100%" height="1" y="152" fill={color("blue", "000")} />
<rect
className="pulse"
width="166"
height="8"
x="8"
y="176"
rx="1"
ry="1"
fill={color("blue", "000")}
/>
<rect width="100%" height="1" y="208" fill={color("blue", "000")} />
<rect
className="pulse"
width="246"
height="8"
x="8"
y="232"
rx="1"
ry="1"
fill={color("blue", "000")}
/>
<rect width="100%" height="1" y="264" fill={color("blue", "000")} />
<rect
className="pulse"
width="134"
height="8"
x="8"
y="288"
rx="1"
ry="1"
fill={color("blue", "000")}
/>
<rect width="100%" height="1" y="320" fill={color("blue", "000")} />
<rect
className="pulse"
width="190"
height="8"
x="8"
y="344"
rx="1"
ry="1"
fill={color("blue", "000")}
/>
<rect width="100%" height="1" y="376" fill={color("blue", "000")} />
<rect
className="pulse"
width="182"
height="8"
x="8"
y="400"
rx="1"
ry="1"
fill={color("blue", "000")}
/>
<rect width="100%" height="1" y="432" fill={color("blue", "000")} />
<rect
className="pulse"
width="222"
height="8"
x="8"
y="456"
rx="1"
ry="1"
fill={color("blue", "000")}
/>
<rect width="100%" height="1" y="488" fill={color("blue", "000")} />
<rect
className="pulse"
width="126"
height="8"
x="8"
y="512"
rx="1"
ry="1"
fill={color("blue", "000")}
/>
<rect width="100%" height="1" y="544" fill={color("blue", "000")} />
<rect
className="pulse"
width="86"
height="8"
x="8"
y="568"
rx="1"
ry="1"
fill={color("blue", "000")}
/>
<rect width="100%" height="1" y="600" fill={color("blue", "000")} />
<rect
className="pulse"
width="166"
height="8"
x="8"
y="624"
rx="1"
ry="1"
fill={color("blue", "000")}
/>
<rect width="100%" height="1" y="656" fill={color("blue", "000")} />
<rect
className="pulse"
width="246"
height="8"
x="8"
y="680"
rx="1"
ry="1"
fill={color("blue", "000")}
/>
<rect width="100%" height="1" y="712" fill={color("blue", "000")} />
</g>
</SVG>
</div>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Masks/mybets.jsx
import React, { PureComponent } from "react";
import styled, { keyframes } from "styled-components";
import buildColor from "../ColorPalette";
const pulseAnimation = keyframes`
0% {
fill: ${buildColor("blue", "100")};
}
50% {
fill: ${buildColor("blue", "200")};
}
100% {
fill: ${buildColor("blue", "100")};
}
`;
const SVG = styled.svg`
display: block;
width: 100%;
height: 720px;
background: ${buildColor("white", "100")};
rect.pulse {
animation: ${pulseAnimation} 1.25s infinite;
}
`;
export default class MyBetsMask extends PureComponent {
render() {
return (
<div data-qa-label="homepageMask">
<SVG>
<g>
<rect
fill={buildColor("white", "100")}
height="100%"
width="100%"
/>
<rect fill={buildColor("blue", "000")} height="40" width="100%" />
<rect
className="pulse"
width="150"
height="8"
x="8"
y="16"
rx="1"
ry="1"
fill={buildColor("blue", "100")}
/>
<rect
fill={buildColor("blue", "200")}
height="1"
width="100%"
y="40"
/>
<rect
className="pulse"
width="40"
height="8"
x="8"
y="64"
rx="1"
ry="1"
fill={buildColor("blue", "100")}
/>
<rect
className="pulse"
width="176"
height="8"
x="64"
y="64"
rx="1"
ry="1"
fill={buildColor("blue", "100")}
/>
<rect
className="pulse"
width="152"
height="8"
x="8"
y="96"
rx="1"
ry="1"
fill={buildColor("blue", "100")}
/>
<rect
className="pulse"
width="56"
height="8"
x="8"
y="116"
rx="1"
ry="1"
fill={buildColor("blue", "100")}
/>
<rect
className="pulse"
width="72"
height="8"
x="8"
y="136"
rx="1"
ry="1"
fill={buildColor("blue", "100")}
/>
<rect
fill={buildColor("blue", "200")}
height="1"
width="100%"
y="168"
/>
<rect
className="pulse"
width="40"
height="8"
x="8"
y="193"
rx="1"
ry="1"
fill={buildColor("blue", "100")}
/>
<rect
className="pulse"
width="128"
height="8"
x="64"
y="193"
rx="1"
ry="1"
fill={buildColor("blue", "100")}
/>
<rect
className="pulse"
width="168"
height="8"
x="8"
y="225"
rx="1"
ry="1"
fill={buildColor("blue", "100")}
/>
<rect
className="pulse"
width="64"
height="8"
x="8"
y="245"
rx="1"
ry="1"
fill={buildColor("blue", "100")}
/>
<rect
className="pulse"
width="40"
height="8"
x="8"
y="265"
rx="1"
ry="1"
fill={buildColor("blue", "100")}
/>
<rect
className="pulse"
width="40"
height="8"
x="8"
y="285"
rx="1"
ry="1"
fill={buildColor("blue", "100")}
/>
<rect
className="pulse"
width="136"
height="8"
x="8"
y="317"
rx="1"
ry="1"
fill={buildColor("blue", "100")}
/>
<rect
className="pulse"
width="64"
height="8"
x="8"
y="337"
rx="1"
ry="1"
fill={buildColor("blue", "100")}
/>
<rect
className="pulse"
width="80"
height="8"
x="8"
y="357"
rx="1"
ry="1"
fill={buildColor("blue", "100")}
/>
<rect
className="pulse"
width="40"
height="8"
x="8"
y="377"
rx="1"
ry="1"
fill={buildColor("blue", "100")}
/>
</g>
</SVG>
</div>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Masks/tracks.jsx
import React, { PureComponent } from "react";
import styled, { keyframes } from "styled-components";
import color from "../ColorPalette";
const SVGContainer = styled.div`
width: 100%;
position: absolute;
top: 0;
left: 0;
height: 100%;
overflow: hidden;
z-index: 30;
`;
const pulseAnimation = keyframes`
0% {
fill: ${color("blue", "000")};
}
50% {
fill: ${color("white", "100")};
}
100% {
fill: ${color("blue", "000")};
}
`;
const SVG = styled.svg`
display: block;
width: 100%;
height: 100%;
background: ${color("white", "100")};
rect.pulse {
animation: ${pulseAnimation} 1.25s infinite;
}
rect.stroke {
stroke: ${color("white", "100")};
stroke-width: 1;
}
`;
export default class TracksMask extends PureComponent {
render() {
return (
<SVGContainer data-qa-label="tracksMask">
<SVG>
<rect
className="filter-section"
fill={color("blue", "700")}
height="56"
width="100%"
transform="translate(0)"
/>
<g transform="translate(0 60)">
<rect fill={color("blue", "000")} height="100%" width="100%" />
<rect fill={color("white", "100")} height="40" width="100%" />
<rect
className="pulse"
width="158"
height="8"
x="8"
y="16"
rx="1"
ry="1"
fill={color("blue", "000")}
/>
<rect fill={color("white", "100")} height="1" width="100%" y="39" />
<rect
fill={color("white", "100")}
height="72"
width="100%"
y="40"
/>
<rect
className="stroke"
width="92"
height="40"
x="8"
y="56"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
className="stroke"
width="92"
height="40"
x="108"
y="56"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
className="stroke"
width="92"
height="40"
x="208"
y="56"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
className="stroke"
width="92"
height="40"
x="308"
y="56"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
className="stroke"
width="92"
height="40"
x="408"
y="56"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
className="stroke"
width="92"
height="40"
x="508"
y="56"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
className="stroke"
width="92"
height="40"
x="608"
y="56"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
className="stroke"
width="92"
height="40"
x="708"
y="56"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
className="stroke"
width="92"
height="40"
x="808"
y="56"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
fill={color("white", "100")}
height="1"
width="100%"
y="111"
/>
<rect
fill={color("white", "100")}
height="1"
width="100%"
y="120"
/>
<rect
fill={color("white", "100")}
height="40"
width="100%"
y="120"
/>
<rect
className="pulse"
width="94"
height="8"
x="8"
y="136"
rx="1"
ry="1"
fill={color("blue", "000")}
/>
<rect
fill={color("white", "100")}
height="1"
width="100%"
y="159"
/>
<rect
fill={color("white", "100")}
height="96"
width="100%"
y="160"
/>
<rect
className="pulse"
width="158"
height="8"
x="8"
y="176"
rx="1"
ry="1"
fill={color("blue", "000")}
/>
<rect
className="stroke"
width="92"
height="40"
x="8"
y="200"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
className="stroke"
width="92"
height="40"
x="108"
y="200"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
className="stroke"
width="92"
height="40"
x="208"
y="200"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
className="stroke"
width="92"
height="40"
x="308"
y="200"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
className="stroke"
width="92"
height="40"
x="408"
y="200"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
className="stroke"
width="92"
height="40"
x="508"
y="200"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
className="stroke"
width="92"
height="40"
x="608"
y="200"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
className="stroke"
width="92"
height="40"
x="708"
y="200"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
className="stroke"
width="92"
height="40"
x="808"
y="200"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
fill={color("white", "100")}
height="1"
width="100%"
y="255"
/>
<rect
fill={color("white", "100")}
height="40"
width="100%"
y="265"
/>
<rect
className="pulse"
width="118"
height="8"
x="8"
y="281"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
fill={color("white", "100")}
height="1"
width="100%"
y="265"
/>
<rect
fill={color("white", "100")}
height="1"
width="100%"
y="304"
/>
<g transform="translate(0 305)">
<rect fill={color("white", "100")} height="40" width="100%" />
<rect
className="pulse"
width="94"
height="8"
x="8"
y="16"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
fill={color("blue", "000")}
height="1"
width="100%"
y="40"
/>
</g>
<g transform="translate(0 346)">
<rect fill={color("white", "100")} height="40" width="100%" />
<rect
className="pulse"
width="173"
height="8"
x="8"
y="16"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
fill={color("blue", "000")}
height="1"
width="100%"
y="40"
/>
</g>
<g transform="translate(0 387)">
<rect fill={color("white", "100")} height="40" width="100%" />
<rect
className="pulse"
width="94"
height="8"
x="8"
y="16"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
fill={color("blue", "000")}
height="1"
width="100%"
y="40"
/>
</g>
<g transform="translate(0 428)">
<rect fill={color("white", "100")} height="40" width="100%" />
<rect
className="pulse"
width="173"
height="8"
x="8"
y="16"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
fill={color("blue", "000")}
height="1"
width="100%"
y="40"
/>
</g>
<g transform="translate(0 469)">
<rect fill={color("white", "100")} height="40" width="100%" />
<rect
className="pulse"
width="94"
height="8"
x="8"
y="16"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
fill={color("blue", "000")}
height="1"
width="100%"
y="40"
/>
</g>
<g transform="translate(0 510)">
<rect fill={color("white", "100")} height="40" width="100%" />
<rect
className="pulse"
width="134"
height="8"
x="8"
y="16"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
fill={color("blue", "000")}
height="1"
width="100%"
y="40"
/>
</g>
<g transform="translate(0 551)">
<rect fill={color("white", "100")} height="40" width="100%" />
<rect
className="pulse"
width="94"
height="8"
x="8"
y="16"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
fill={color("blue", "000")}
height="1"
width="100%"
y="40"
/>
</g>
<g transform="translate(0 592)">
<rect fill={color("white", "100")} height="40" width="100%" />
<rect
className="pulse"
width="134"
height="8"
x="8"
y="16"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
fill={color("blue", "000")}
height="1"
width="100%"
y="40"
/>
</g>
<g transform="translate(0 633)">
<rect fill={color("white", "100")} height="40" width="100%" />
<rect
className="pulse"
width="94"
height="8"
x="8"
y="16"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
fill={color("blue", "000")}
height="1"
width="100%"
y="40"
/>
</g>
<g transform="translate(0 674)">
<rect fill={color("white", "100")} height="40" width="100%" />
<rect
className="pulse"
width="173"
height="8"
x="8"
y="16"
rx="1"
ry="1"
fill={color("white", "100")}
/>
<rect
fill={color("blue", "000")}
height="1"
width="100%"
y="40"
/>
</g>
</g>
</SVG>
</SVGContainer>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Masks/races.jsx
import React, { PureComponent } from "react";
import styled, { keyframes } from "styled-components";
import buildColor from "../ColorPalette";
const SVGContainer = styled.div`
width: 100%;
`;
const pulseAnimation = keyframes`
0% {
fill: ${buildColor("blue", "100")};
}
50% {
fill: ${buildColor("blue", "200")};
}
100% {
fill: ${buildColor("blue", "100")};
}
`;
const SVG = styled.svg`
display: block;
width: 100%;
height: 720px;
background: ${buildColor("white", "100")};
rect.pulse {
animation: ${pulseAnimation} 1.25s infinite;
}
rect.stroke {
stroke: ${buildColor("blue", "200")};
stroke-width: 1;
}
`;
export default class RacesMask extends PureComponent {
render() {
return (
<SVGContainer data-qa-label="racesMask">
<SVG>
<g fill="none" fillRule="evenodd">
<g transform="translate(0 -48)">
<rect
className="stroke"
width="91"
height="47"
x="12.5"
y="48.5"
rx="4"
/>
<rect
className="stroke"
width="91"
height="47"
x="112.5"
y="48.5"
rx="4"
/>
<rect
className="pulse"
width="15"
height="8"
x="20"
y="77"
fill={buildColor("blue", "200")}
rx="1"
/>
<rect
className="pulse"
width="15"
height="8"
x="120"
y="77"
fill={buildColor("blue", "200")}
rx="1"
/>
<rect
className="pulse"
width="35"
height="8"
x="20"
y="59"
fill={buildColor("blue", "200")}
rx="1"
/>
<rect
className="pulse"
width="51"
height="8"
x="120"
y="59"
fill={buildColor("blue", "200")}
rx="1"
/>
<rect
className="stroke"
width="91"
height="47"
x="212.5"
y="48.5"
rx="4"
/>
<rect
className="pulse"
width="15"
height="8"
x="220"
y="77"
fill={buildColor("blue", "200")}
rx="1"
/>
<rect
className="pulse"
width="51"
height="8"
x="220"
y="59"
fill={buildColor("blue", "200")}
rx="1"
/>
<rect
className="stroke"
width="91"
height="47"
x="312.5"
y="48.5"
rx="4"
/>
</g>
<rect
className="pulse"
width="15"
height="8"
x="320"
y="29"
fill={buildColor("blue", "200")}
rx="1"
/>
<rect
className="pulse"
width="35"
height="8"
x="320"
y="11"
fill={buildColor("blue", "200")}
rx="1"
/>
<rect
className="stroke"
width="91"
height="47"
x="412.5"
y=".5"
rx="4"
/>
<rect
className="pulse"
width="15"
height="8"
x="420"
y="29"
fill={buildColor("blue", "200")}
rx="1"
/>
<rect
className="pulse"
width="51"
height="8"
x="420"
y="11"
fill={buildColor("blue", "200")}
rx="1"
/>
<rect
className="stroke"
width="91"
height="47"
x="512.5"
y=".5"
rx="4"
/>
<rect
className="pulse"
width="15"
height="8"
x="520"
y="29"
fill={buildColor("blue", "200")}
rx="1"
/>
<rect
className="pulse"
width="35"
height="8"
x="520"
y="11"
fill={buildColor("blue", "200")}
rx="1"
/>
<rect
className="stroke"
width="91"
height="47"
x="612.5"
y=".5"
rx="4"
/>
<rect
className="pulse"
width="15"
height="8"
x="620"
y="29"
fill={buildColor("blue", "200")}
rx="1"
/>
<rect
className="pulse"
width="35"
height="8"
x="620"
y="11"
fill={buildColor("blue", "200")}
rx="1"
/>
<rect
className="stroke"
width="91"
height="47"
x="712.5"
y=".5"
rx="4"
/>
<rect
className="stroke"
width="91"
height="47"
x="812.5"
y=".5"
rx="4"
/>
<rect
className="pulse"
width="15"
height="8"
x="720"
y="29"
fill={buildColor("blue", "200")}
rx="1"
/>
<rect
className="pulse"
width="15"
height="8"
x="820"
y="29"
fill={buildColor("blue", "200")}
rx="1"
/>
<rect
className="pulse"
width="35"
height="8"
x="720"
y="11"
fill={buildColor("blue", "200")}
rx="1"
/>
<rect
className="pulse"
width="35"
height="8"
x="820"
y="11"
fill={buildColor("blue", "200")}
rx="1"
/>
<rect
className="stroke"
width="91"
height="47"
x="912.5"
y=".5"
rx="4"
/>
<rect
className="pulse"
width="15"
height="8"
x="920"
y="29"
fill={buildColor("blue", "200")}
rx="1"
/>
<rect
className="pulse"
width="35"
height="8"
x="920"
y="11"
fill={buildColor("blue", "200")}
rx="1"
/>
</g>
</SVG>
</SVGContainer>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Masks/pagination.jsx
import React, { PureComponent } from "react";
import styled, { keyframes } from "styled-components";
import color from "../ColorPalette";
const pulseAnimation = keyframes`
0% {
fill: ${color("blue", "000")};
}
50% {
fill: ${color("blue", "100")};
}
100% {
fill: ${color("blue", "000")};
}
`;
const SVG = styled.svg`
display: block;
width: 100%;
height: 49px;
rect.pulse {
animation: ${pulseAnimation} 1.25s infinite;
}
`;
export default class PaginationMask extends PureComponent {
render() {
return (
<div data-qa-label="paginationMask">
<SVG>
<g>
<rect
width="100%"
height="48"
transform="translate(0 1)"
fill={color("white", "100")}
/>
<rect
className="pulse"
x="12"
y="17"
width="16"
height="16"
rx="2"
fill={color("blue", "000")}
/>
<rect
width="16"
height="16"
rx="2"
transform="matrix(-1 0 0 1 363 17)"
fill={color("blue", "000")}
/>
<rect
className="pulse"
x="32"
y="17"
width="40"
height="16"
rx="2"
fill={color("blue", "000")}
/>
<rect
width="40"
height="16"
rx="2"
transform="matrix(-1 0 0 1 343 17)"
fill={color("blue", "000")}
/>
<rect
className="pulse"
x="142"
y="9"
width="92"
height="32"
rx="2"
fill={color("blue", "000")}
/>
</g>
</SVG>
</div>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Masks/program-page.jsx
import React, { PureComponent } from "react";
import styled, { keyframes } from "styled-components";
import color from "../ColorPalette";
const SVGContainer = styled.div`
width: 100%;
`;
const pulseAnimation = keyframes`
0% {
fill: ${color("grey", "000")};
}
50% {
fill: ${color("grey", "100")};
}
100% {
fill: ${color("grey", "000")};
}
`;
const SVG = styled.svg`
display: block;
width: 100%;
height: 720px;
background: ${color("white", "100")};
rect.pulse {
animation: ${pulseAnimation} 1.25s infinite;
}
rect.stroke {
stroke: ${color("grey", "100")};
stroke-width: 1;
}
`;
export default class ProgramPageMask extends PureComponent {
render() {
return (
<SVGContainer data-qa-label="ProgramPageMask">
<SVG>
<rect
fill={color("blue", "700")}
x="0"
y="0"
width="100%"
height="120"
/>
<rect
fill={color("white", "100")}
x="0"
y="120"
width="100%"
height="48"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="8"
y="140"
width="56"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="80"
y="140"
width="56"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="152"
y="140"
width="56"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="224"
y="140"
width="56"
height="8"
rx="1"
/>
<rect
fill={color("grey", "100")}
x="0"
y="167"
width="100%"
height="1"
/>
<rect
fill={color("white", "100")}
x="0"
y="208"
width="100%"
height="503"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="0"
y="263"
width="100%"
height="1"
/>
<rect
fill={color("blue_accent", "000")}
x="0"
y="168"
width="100%"
height="40"
/>
<rect
fill={color("grey", "100")}
x="0"
y="207"
width="100%"
height="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="72"
y="224"
width="144"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="72"
y="240"
width="176"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="0"
y="319"
width="100%"
height="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="72"
y="280"
width="64"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="72"
y="296"
width="168"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="0"
y="375"
width="100%"
height="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="72"
y="336"
width="56"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="72"
y="352"
width="112"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="0"
y="431"
width="100%"
height="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="72"
y="392"
width="72"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="72"
y="408"
width="128"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="0"
y="487"
width="100%"
height="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="72"
y="448"
width="104"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="72"
y="464"
width="160"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="72"
y="504"
width="104"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="72"
y="560"
width="80"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="72"
y="520"
width="152"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="72"
y="576"
width="128"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="0"
y="543"
width="100%"
height="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="0"
y="599"
width="100%"
height="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="8"
y="184"
width="48"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="72"
y="184"
width="192"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="72"
y="616"
width="72"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="72"
y="632"
width="184"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="0"
y="655"
width="100%"
height="1"
/>
<rect
className="pulse"
fill={color("blue", "000")}
x="72"
y="672"
width="120"
height="8"
rx="1"
/>
<rect fill="#F3CFCF" x="0" y="208" width="24" height="55" />
<rect fill="#F2F4F4" x="0" y="264" width="24" height="55" />
<rect fill="#D8DCE8" x="0" y="320" width="24" height="55" />
<rect fill="#F6EFD8" x="0" y="376" width="24" height="55" />
<rect fill="#CFE0CF" x="0" y="432" width="24" height="55" />
<rect fill="#D6D6D6" x="0" y="488" width="24" height="55" />
<rect fill="#F7DED5" x="0" y="544" width="24" height="55" />
<rect fill="#F9EAEE" x="0" y="600" width="24" height="55" />
<rect fill="#D4EEED" x="0" y="656" width="24" height="55" />
<rect
fillOpacity="0.1"
fill={color("white", "100")}
x="8"
y="60"
width="216"
height="8"
rx="1"
/>
<rect
fillOpacity="0.1"
fill={color("white", "100")}
x="8"
y="20"
width="40"
height="8"
rx="1"
/>
<rect
fillOpacity="0.1"
fill={color("white", "100")}
x="64"
y="20"
width="176"
height="8"
rx="1"
/>
<rect
fillOpacity="0.1"
fill={color("white", "100")}
x="8"
y="80"
width="46%"
height="32"
rx="2"
/>
<rect
fillOpacity="0.1"
fill={color("white", "100")}
x="51%"
y="80"
width="46%"
height="32"
rx="2"
/>
</SVG>
</SVGContainer>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Masks/program-page-tablet.jsx
import React, { PureComponent } from "react";
import styled, { keyframes } from "styled-components";
import buildColor from "../ColorPalette";
import ProgramPageMask from "./program-page";
const pulseAnimation = keyframes`
0% {
fill: ${buildColor("blue", "100")};
}
50% {
fill: ${buildColor("blue", "200")};
}
100% {
fill: ${buildColor("blue", "100")};
}
`;
const MaskContainer = styled.div`
width: 100%;
padding: 8px;
display: flex;
align-items: flex-start;
justify-content: space-between;
`;
const SVG = styled.svg`
display: block;
width: 100%;
height: 720px;
rect.pulse {
animation: ${pulseAnimation} 1.25s infinite;
}
rect.stroke {
stroke: ${buildColor("blue", "200")};
stroke-width: 1;
}
`;
const TabletVideoContainer = styled.div`
flex-grow: 1;
min-width: 320px;
max-width: 60%;
border-right: 8px solid transparent;
`;
const TabletProgramPageContainer = styled.div`
min-width: 320px;
max-width: 40%;
flex-grow: 1;
border-left: 8px solid transparent;
`;
export default class ProgramPageTabletMask extends PureComponent {
render() {
return (
<MaskContainer data-qa-label="ProgramPageTabletMask">
<TabletVideoContainer>
<SVG>
<rect
fill={buildColor("blue", "000")}
x="0"
y="0"
width="100%"
height="317"
/>
<rect
fill={buildColor("blue", "200")}
x="0"
y="325"
width="100%"
height="1"
/>
<rect
fill={buildColor("blue", "000")}
x="0"
y="326"
width="100%"
height="40"
/>
<rect
fill={buildColor("blue", "200")}
x="0"
y="366"
width="100%"
height="1"
/>
<rect
className="pulse"
fill={buildColor("blue", "100")}
x="8"
y="341"
width="63"
height="8"
rx="1"
/>
<rect
fill={buildColor("white", "100")}
x="0"
y="367"
width="100%"
height="132"
/>
<rect
className="pulse"
fill={buildColor("blue", "100")}
x="8"
y="383"
width="56"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={buildColor("blue", "100")}
x="96"
y="383"
width="56"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={buildColor("blue", "100")}
x="184"
y="383"
width="56"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={buildColor("blue", "100")}
x="272"
y="383"
width="56"
height="8"
rx="1"
/>
<rect
fill={buildColor("blue", "200")}
x="0"
y="407"
width="100%"
height="1"
/>
<rect
className="pulse"
fill={buildColor("blue", "100")}
x="8"
y="424"
width="320"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={buildColor("blue", "100")}
x="8"
y="440"
width="284"
height="8"
rx="1"
/>
<rect
fill={buildColor("blue", "200")}
x="0"
y="499"
width="100%"
height="1"
/>
<rect
fill={buildColor("blue", "200")}
x="0"
y="507"
width="100%"
height="1"
/>
<rect
fill={buildColor("blue", "000")}
x="0"
y="508"
width="100%"
height="40"
/>
<rect
fill={buildColor("blue", "200")}
x="0"
y="548"
width="100%"
height="1"
/>
<rect
className="pulse"
fill={buildColor("blue", "100")}
x="8"
y="524"
width="63"
height="8"
rx="1"
/>
<rect
fill={buildColor("white", "100")}
x="0"
y="549"
width="100%"
height="84"
/>
<rect
className="pulse"
fill={buildColor("blue", "100")}
x="8"
y="565"
width="23"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={buildColor("blue", "100")}
x="63"
y="565"
width="120"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={buildColor("blue", "100")}
x="325"
y="565"
width="23"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={buildColor("blue", "100")}
x="8"
y="589"
width="325"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={buildColor("blue", "100")}
x="8"
y="605"
width="290"
height="8"
rx="1"
/>
<rect
fill={buildColor("blue", "200")}
x="0"
y="632"
width="100%"
height="1"
/>
<rect
fill={buildColor("white", "100")}
x="0"
y="633"
width="100%"
height="84"
/>
<rect
className="pulse"
fill={buildColor("blue", "100")}
x="8"
y="649"
width="23"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={buildColor("blue", "100")}
x="63"
y="649"
width="120"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={buildColor("blue", "100")}
x="325"
y="649"
width="23"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={buildColor("blue", "100")}
x="8"
y="669"
width="325"
height="8"
rx="1"
/>
<rect
className="pulse"
fill={buildColor("blue", "100")}
x="8"
y="687"
width="290"
height="8"
rx="1"
/>
<rect
fill={buildColor("blue", "200")}
x="0"
y="716"
width="100%"
height="1"
/>
</SVG>
</TabletVideoContainer>
<TabletProgramPageContainer>
<ProgramPageMask />
</TabletProgramPageContainer>
</MaskContainer>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Masks/talent-picks.jsx
import React, { PureComponent } from "react";
import styled, { keyframes } from "styled-components";
import color from "../ColorPalette";
const pulseAnimation = keyframes`
0% {
fill: ${color("grey", "000")};
}
50% {
fill: ${color("grey", "100")};
}
100% {
fill: ${color("grey", "000")};
}
`;
const SVG = styled.svg`
display: block;
width: 100%;
height: 720px;
rect.pulse {
animation: ${pulseAnimation} 1.25s infinite;
}
`;
const card = (
<g>
<rect fill={color("white", "100")} y="7" height="250" width="100%" />
<rect fill={color("grey", "000")} y="7" height="49" width="100%" />
<path
fill={color("grey", "100")}
d="m62.80412,50.51804c-3.22666,-1.39511 -11.27739,-3.25367 -16.37013,-4.92763c-0.39738,-0.13051 -0.47097,-0.99773 -0.47097,-2.79131c0,-1.92066 0.21735,-3.27955 0.68892,-4.27614c0.63489,-1.35883 1.66824,-4.2629 1.66824,-6.3009c0.76083,-0.88791 2.36979,-2.05238 3.0403,-5.38597c0.57964,-2.93566 -0.26681,-4.00469 -0.64752,-5.00128c-0.03682,-0.10867 -0.09146,-0.21735 -0.10927,-0.32608c-0.1449,-0.67051 0.05464,-4.25827 0.56238,-7.03007c0.34389,-1.90285 -0.09086,-5.94323 -2.71946,-9.29577c-1.64982,-2.11966 -4.43999,-4.89429 -12.12679,-5.07313c-0.11042,0.00518 -0.21163,0.01209 -0.31975,0.01781c-0.10867,-0.00577 -0.20989,-0.01264 -0.3203,-0.01781c-7.68674,0.17884 -10.47696,2.95347 -12.12679,5.07313c-2.628,3.3526 -3.06335,7.39292 -2.71886,9.29577c0.5072,2.77175 0.70674,6.35957 0.56183,7.03007c-0.01781,0.10867 -0.07245,0.21735 -0.10867,0.32608c-0.38071,0.99659 -1.22777,2.06562 -0.64752,5.00128c0.67051,3.33359 2.27953,4.49811 3.0403,5.38597c0,2.038 1.03336,4.94201 1.66764,6.3009c0.47212,0.99659 0.68892,2.35541 0.68892,4.27614c0,1.79358 -0.07305,2.66079 -0.47097,2.79131c-5.09214,1.67401 -13.14287,3.53258 -16.37013,4.92763c-1.37321,0.77172 -1.94828,2.49688 -1.94828,5.37218l57.50557,0c0,-2.8753 -0.57508,-4.60047 -1.94889,-5.37218l0.00022,0z"
/>
<rect
className="pulse"
width="120"
height="8"
x="72"
y="20"
rx="1"
ry="1"
fill={color("blue", "700")}
/>
<rect width="100%" height="1" y="7" fill={color("grey", "100")} />
<rect width="100%" height="1" y="56" fill={color("grey", "100")} />
<rect
className="pulse"
width="250"
height="8"
x="8"
y="77"
rx="1"
ry="1"
fill={color("blue", "700")}
/>
<rect width="100%" height="1" y="105" fill={color("grey", "100")} />
<rect
className="pulse"
width="50"
height="8"
x="8"
y="130"
rx="1"
ry="1"
fill={color("blue", "700")}
/>
<rect
className="pulse"
width="85"
height="8"
x="66"
y="130"
rx="1"
ry="1"
fill={color("blue", "700")}
/>
<rect
className="pulse"
width="16"
height="16"
x="8"
y="160"
rx="1"
ry="1"
fill={color("blue", "700")}
/>
<rect
className="pulse"
width="16"
height="16"
x="25"
y="160"
rx="1"
ry="1"
fill={color("blue", "700")}
/>
<rect
className="pulse"
width="16"
height="16"
x="42"
y="160"
rx="1"
ry="1"
fill={color("blue", "700")}
/>
<rect fill={color("grey", "000")} y="200" height="56" width="100%" />
<rect width="100%" height="1" y="200" fill={color("grey", "100")} />
<rect width="100%" height="1" y="256" fill={color("grey", "100")} />
</g>
);
export default class TalentPicksMask extends PureComponent {
render() {
return (
<div data-qa-label="talentPicksMasc" style={{ paddingTop: "8px" }}>
<SVG>
<rect fill={color("white", "100")} height="100%" width="100%" />
<svg>{card}</svg>
<svg y="272">{card}</svg>
<svg y="544">{card}</svg>
</SVG>
</div>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Masks/talent-pick-card.jsx
import React, { PureComponent } from "react";
import styled, { keyframes, css } from "styled-components";
import color from "../ColorPalette";
const SVGContainer = styled.div`
width: 100%;
margin-bottom: ${(props) => (props.isDesktop ? "12px" : 0)};
overflow: hidden;
`;
const pulseAnimation = keyframes`
0% {
fill: ${color("grey", "000")};
}
50% {
fill: ${color("blue", "000")};
}
100% {
fill: ${color("grey", "000")};
}
`;
const SVG = styled.svg`
${({ isDesktop }) =>
isDesktop
? css`
width: 663px;
height: 360px;
`
: css`
width: 1032px;
height: 352px;
`}
display: block;
rect.pulse {
animation: ${pulseAnimation} 1.25s infinite;
}
rect.stroke {
stroke: ${color("blue", "100")};
stroke-width: 1;
}
`;
/*
TODO: Use buildColor to set the mask color
*/
export default class HPTalentPicksMask extends PureComponent {
static defaultProps = {
isDesktop: false
};
render() {
return (
<SVGContainer
data-qa-label="HPTalentPicksMask"
isDesktop={this.props.isDesktop}
>
<SVG isDesktop={this.props.isDesktop}>
{this.props.isDesktop ? (
<g fill="none" fillRule="evenodd" transform="translate(-53 -1526)">
<rect width="1391" height="2692" fill="#E9EFF5" />
<g transform="translate(53 1526)">
<rect
width="663"
height="360"
fill="#FFF"
fillRule="nonzero"
rx="4"
/>
<rect
width="130"
height="8"
x="12"
y="24"
fill="#E9EFF5"
rx="1"
/>
<rect
width="312"
height="291"
x="12.5"
y="56.5"
fill="#FFF"
fillRule="nonzero"
stroke="#E9EFF5"
rx="4"
/>
<rect
width="130"
height="8"
x="24"
y="127"
fill="#E9EFF5"
rx="1"
/>
<rect width="20" height="20" x="53" y="152" fill="#E9EFF5" />
<rect width="20" height="20" x="53" y="264" fill="#E9EFF5" />
<rect width="20" height="20" x="24" y="152" fill="#E9EFF5" />
<rect width="20" height="20" x="24" y="180" fill="#E9EFF5" />
<rect width="20" height="20" x="24" y="208" fill="#E9EFF5" />
<rect width="20" height="20" x="24" y="236" fill="#E9EFF5" />
<rect width="20" height="20" x="24" y="264" fill="#E9EFF5" />
<rect width="20" height="20" x="53" y="236" fill="#E9EFF5" />
<rect width="20" height="20" x="53" y="180" fill="#E9EFF5" />
<rect width="20" height="20" x="53" y="208" fill="#E9EFF5" />
<rect width="20" height="20" x="74" y="151" fill="#E9EFF5" />
<rect width="20" height="20" x="74" y="152" fill="#E9EFF5" />
<rect width="20" height="20" x="74" y="236" fill="#E9EFF5" />
<rect width="20" height="20" x="74" y="180" fill="#E9EFF5" />
<rect width="20" height="20" x="74" y="208" fill="#E9EFF5" />
<rect width="20" height="20" x="95" y="152" fill="#E9EFF5" />
<rect width="20" height="20" x="95" y="236" fill="#E9EFF5" />
<rect width="20" height="20" x="95" y="180" fill="#E9EFF5" />
<rect width="20" height="20" x="116" y="180" fill="#E9EFF5" />
<rect
width="105"
height="39"
x="24.5"
y="296.5"
fill="#FFF"
stroke="#E9EFF5"
rx="2"
/>
<rect
width="175"
height="40"
x="138"
y="296"
fill="#E9EFF5"
rx="2"
/>
<path
fill="#FAFCFF"
d="M16,57 L321,57 C322.656854,57 324,58.3431458 324,60 L324,111 L13,111 L13,60 C13,58.3431458 14.3431458,57 16,57 Z"
/>
<rect
width="21"
height="8"
x="25"
y="71"
fill="#E9EFF5"
rx="1"
/>
<rect
width="109"
height="8"
x="78"
y="71"
fill="#E9EFF5"
rx="1"
/>
<rect
width="85"
height="8"
x="78"
y="89"
fill="#E9EFF5"
rx="1"
/>
<rect width="311" height="1" x="13" y="110" fill="#E9EFF5" />
<rect
width="312"
height="291"
x="337.5"
y="56.5"
fill="#FFF"
fillRule="nonzero"
stroke="#E9EFF5"
rx="4"
/>
<rect
width="130"
height="8"
x="349"
y="127"
fill="#E9EFF5"
rx="1"
/>
<rect width="20" height="20" x="378" y="152" fill="#E9EFF5" />
<rect width="20" height="20" x="378" y="264" fill="#E9EFF5" />
<rect width="20" height="20" x="349" y="152" fill="#E9EFF5" />
<rect width="20" height="20" x="349" y="180" fill="#E9EFF5" />
<rect width="20" height="20" x="349" y="208" fill="#E9EFF5" />
<rect width="20" height="20" x="349" y="236" fill="#E9EFF5" />
<rect width="20" height="20" x="349" y="264" fill="#E9EFF5" />
<rect width="20" height="20" x="378" y="236" fill="#E9EFF5" />
<rect width="20" height="20" x="378" y="180" fill="#E9EFF5" />
<rect width="20" height="20" x="378" y="208" fill="#E9EFF5" />
<rect width="20" height="20" x="399" y="151" fill="#E9EFF5" />
<rect width="20" height="20" x="399" y="152" fill="#E9EFF5" />
<rect width="20" height="20" x="399" y="236" fill="#E9EFF5" />
<rect width="20" height="20" x="399" y="180" fill="#E9EFF5" />
<rect width="20" height="20" x="399" y="208" fill="#E9EFF5" />
<rect width="20" height="20" x="420" y="152" fill="#E9EFF5" />
<rect width="20" height="20" x="420" y="236" fill="#E9EFF5" />
<rect width="20" height="20" x="420" y="180" fill="#E9EFF5" />
<rect width="20" height="20" x="441" y="180" fill="#E9EFF5" />
<rect
width="105"
height="39"
x="349.5"
y="296.5"
fill="#FFF"
stroke="#E9EFF5"
rx="2"
/>
<rect
width="175"
height="40"
x="463"
y="296"
fill="#E9EFF5"
rx="2"
/>
<path
fill="#FAFCFF"
d="M341,57 L646,57 C647.656854,57 649,58.3431458 649,60 L649,111 L338,111 L338,60 C338,58.3431458 339.343146,57 341,57 Z"
/>
<rect
width="21"
height="8"
x="350"
y="71"
fill="#E9EFF5"
rx="1"
/>
<rect
width="109"
height="8"
x="403"
y="71"
fill="#E9EFF5"
rx="1"
/>
<rect
width="85"
height="8"
x="403"
y="89"
fill="#E9EFF5"
rx="1"
/>
<rect width="311" height="1" x="338" y="110" fill="#E9EFF5" />
</g>
</g>
) : (
<g fill="none" fillRule="evenodd" transform="translate(-53 -602)">
<rect width="1391" height="2692" fill="#E9EFF5" />
<g transform="translate(53 602)">
<rect
width="1032"
height="352"
fill="#FFF"
fillRule="nonzero"
/>
<rect
width="291"
height="291"
x="12.5"
y="48.5"
fill="#FFF"
fillRule="nonzero"
stroke="#E9EFF5"
rx="4"
/>
<rect
width="130"
height="8"
x="24"
y="119"
fill="#E9EFF5"
rx="1"
/>
<rect
width="90"
height="8"
x="12"
y="21"
fill="#E9EFF5"
rx="1"
/>
<rect width="20" height="20" x="53" y="144" fill="#E9EFF5" />
<rect width="20" height="20" x="53" y="256" fill="#E9EFF5" />
<rect width="20" height="20" x="24" y="144" fill="#E9EFF5" />
<rect width="20" height="20" x="24" y="172" fill="#E9EFF5" />
<rect width="20" height="20" x="24" y="200" fill="#E9EFF5" />
<rect width="20" height="20" x="24" y="228" fill="#E9EFF5" />
<rect width="20" height="20" x="24" y="256" fill="#E9EFF5" />
<rect width="20" height="20" x="53" y="228" fill="#E9EFF5" />
<rect width="20" height="20" x="53" y="172" fill="#E9EFF5" />
<rect width="20" height="20" x="53" y="200" fill="#E9EFF5" />
<rect width="20" height="20" x="74" y="143" fill="#E9EFF5" />
<rect width="20" height="20" x="74" y="144" fill="#E9EFF5" />
<rect width="20" height="20" x="74" y="228" fill="#E9EFF5" />
<rect width="20" height="20" x="74" y="172" fill="#E9EFF5" />
<rect width="20" height="20" x="74" y="200" fill="#E9EFF5" />
<rect width="20" height="20" x="95" y="144" fill="#E9EFF5" />
<rect width="20" height="20" x="95" y="228" fill="#E9EFF5" />
<rect width="20" height="20" x="95" y="172" fill="#E9EFF5" />
<rect width="20" height="20" x="116" y="172" fill="#E9EFF5" />
<rect
width="90"
height="39"
x="24.5"
y="288.5"
fill="#FFF"
stroke="#E9EFF5"
rx="2"
/>
<rect
width="169"
height="40"
x="123"
y="288"
fill="#E9EFF5"
rx="2"
/>
<path
fill="#FAFCFF"
d="M16,49 L300,49 C301.656854,49 303,50.3431458 303,52 L303,103 L13,103 L13,52 C13,50.3431458 14.3431458,49 16,49 Z"
/>
<rect width="290" height="1" x="13" y="102" fill="#E9EFF5" />
<rect
width="21"
height="8"
x="25"
y="63"
fill="#E9EFF5"
rx="1"
/>
<rect
width="109"
height="8"
x="78"
y="63"
fill="#E9EFF5"
rx="1"
/>
<rect
width="85"
height="8"
x="78"
y="81"
fill="#E9EFF5"
rx="1"
/>
<rect
width="291"
height="291"
x="312.5"
y="48.5"
fill="#FFF"
fillRule="nonzero"
stroke="#E9EFF5"
rx="4"
/>
<rect
width="130"
height="8"
x="324"
y="119"
fill="#E9EFF5"
rx="1"
/>
<rect width="20" height="20" x="353" y="144" fill="#E9EFF5" />
<rect width="20" height="20" x="353" y="256" fill="#E9EFF5" />
<rect width="20" height="20" x="324" y="144" fill="#E9EFF5" />
<rect width="20" height="20" x="324" y="172" fill="#E9EFF5" />
<rect width="20" height="20" x="324" y="200" fill="#E9EFF5" />
<rect width="20" height="20" x="324" y="228" fill="#E9EFF5" />
<rect width="20" height="20" x="324" y="256" fill="#E9EFF5" />
<rect width="20" height="20" x="353" y="228" fill="#E9EFF5" />
<rect width="20" height="20" x="353" y="172" fill="#E9EFF5" />
<rect width="20" height="20" x="353" y="200" fill="#E9EFF5" />
<rect width="20" height="20" x="374" y="143" fill="#E9EFF5" />
<rect width="20" height="20" x="374" y="144" fill="#E9EFF5" />
<rect width="20" height="20" x="374" y="228" fill="#E9EFF5" />
<rect width="20" height="20" x="374" y="172" fill="#E9EFF5" />
<rect width="20" height="20" x="374" y="200" fill="#E9EFF5" />
<rect width="20" height="20" x="395" y="144" fill="#E9EFF5" />
<rect width="20" height="20" x="395" y="228" fill="#E9EFF5" />
<rect width="20" height="20" x="395" y="172" fill="#E9EFF5" />
<rect width="20" height="20" x="416" y="172" fill="#E9EFF5" />
<rect
width="90"
height="39"
x="324.5"
y="288.5"
fill="#FFF"
stroke="#E9EFF5"
rx="2"
/>
<rect
width="169"
height="40"
x="423"
y="288"
fill="#E9EFF5"
rx="2"
/>
<path
fill="#FAFCFF"
d="M316,49 L600,49 C601.656854,49 603,50.3431458 603,52 L603,103 L313,103 L313,52 C313,50.3431458 314.343146,49 316,49 Z"
/>
<rect width="290" height="1" x="313" y="102" fill="#E9EFF5" />
<rect
width="21"
height="8"
x="325"
y="63"
fill="#E9EFF5"
rx="1"
/>
<rect
width="109"
height="8"
x="378"
y="63"
fill="#E9EFF5"
rx="1"
/>
<rect
width="85"
height="8"
x="378"
y="81"
fill="#E9EFF5"
rx="1"
/>
<rect
width="291"
height="291"
x="612.5"
y="48.5"
fill="#FFF"
fillRule="nonzero"
stroke="#E9EFF5"
rx="4"
/>
<rect
width="130"
height="8"
x="624"
y="119"
fill="#E9EFF5"
rx="1"
/>
<rect width="20" height="20" x="653" y="144" fill="#E9EFF5" />
<rect width="20" height="20" x="653" y="256" fill="#E9EFF5" />
<rect width="20" height="20" x="624" y="144" fill="#E9EFF5" />
<rect width="20" height="20" x="624" y="172" fill="#E9EFF5" />
<rect width="20" height="20" x="624" y="200" fill="#E9EFF5" />
<rect width="20" height="20" x="624" y="228" fill="#E9EFF5" />
<rect width="20" height="20" x="624" y="256" fill="#E9EFF5" />
<rect width="20" height="20" x="653" y="228" fill="#E9EFF5" />
<rect width="20" height="20" x="653" y="172" fill="#E9EFF5" />
<rect width="20" height="20" x="653" y="200" fill="#E9EFF5" />
<rect width="20" height="20" x="674" y="143" fill="#E9EFF5" />
<rect width="20" height="20" x="674" y="144" fill="#E9EFF5" />
<rect width="20" height="20" x="674" y="228" fill="#E9EFF5" />
<rect width="20" height="20" x="674" y="172" fill="#E9EFF5" />
<rect width="20" height="20" x="674" y="200" fill="#E9EFF5" />
<rect width="20" height="20" x="695" y="144" fill="#E9EFF5" />
<rect width="20" height="20" x="695" y="228" fill="#E9EFF5" />
<rect width="20" height="20" x="695" y="172" fill="#E9EFF5" />
<rect width="20" height="20" x="716" y="172" fill="#E9EFF5" />
<rect
width="90"
height="39"
x="624.5"
y="288.5"
fill="#FFF"
stroke="#E9EFF5"
rx="2"
/>
<rect
width="169"
height="40"
x="723"
y="288"
fill="#E9EFF5"
rx="2"
/>
<path
fill="#FAFCFF"
d="M616,49 L900,49 C901.656854,49 903,50.3431458 903,52 L903,103 L613,103 L613,52 C613,50.3431458 614.343146,49 616,49 Z"
/>
<rect width="290" height="1" x="613" y="102" fill="#E9EFF5" />
<rect
width="21"
height="8"
x="625"
y="63"
fill="#E9EFF5"
rx="1"
/>
<rect
width="109"
height="8"
x="678"
y="63"
fill="#E9EFF5"
rx="1"
/>
<rect
width="85"
height="8"
x="678"
y="81"
fill="#E9EFF5"
rx="1"
/>
<rect
width="291"
height="291"
x="912.5"
y="48.5"
fill="#FFF"
fillRule="nonzero"
stroke="#E9EFF5"
rx="4"
/>
<rect
width="130"
height="8"
x="924"
y="119"
fill="#E9EFF5"
rx="1"
/>
<rect width="20" height="20" x="953" y="144" fill="#E9EFF5" />
<rect width="20" height="20" x="953" y="256" fill="#E9EFF5" />
<rect width="20" height="20" x="924" y="144" fill="#E9EFF5" />
<rect width="20" height="20" x="924" y="172" fill="#E9EFF5" />
<rect width="20" height="20" x="924" y="200" fill="#E9EFF5" />
<rect width="20" height="20" x="924" y="228" fill="#E9EFF5" />
<rect width="20" height="20" x="924" y="256" fill="#E9EFF5" />
<rect width="20" height="20" x="953" y="228" fill="#E9EFF5" />
<rect width="20" height="20" x="953" y="172" fill="#E9EFF5" />
<rect width="20" height="20" x="953" y="200" fill="#E9EFF5" />
<rect width="20" height="20" x="974" y="143" fill="#E9EFF5" />
<rect width="20" height="20" x="974" y="144" fill="#E9EFF5" />
<rect width="20" height="20" x="974" y="228" fill="#E9EFF5" />
<rect width="20" height="20" x="974" y="172" fill="#E9EFF5" />
<rect width="20" height="20" x="974" y="200" fill="#E9EFF5" />
<rect width="20" height="20" x="995" y="144" fill="#E9EFF5" />
<rect width="20" height="20" x="995" y="228" fill="#E9EFF5" />
<rect width="20" height="20" x="995" y="172" fill="#E9EFF5" />
<rect width="20" height="20" x="1016" y="172" fill="#E9EFF5" />
<rect
width="90"
height="39"
x="924.5"
y="288.5"
fill="#FFF"
stroke="#E9EFF5"
rx="2"
/>
<rect
width="169"
height="40"
x="1023"
y="288"
fill="#E9EFF5"
rx="2"
/>
<path
fill="#FAFCFF"
d="M916,49 L1200,49 C1201.65685,49 1203,50.3431458 1203,52 L1203,103 L913,103 L913,52 C913,50.3431458 914.343146,49 916,49 Z"
/>
<rect width="290" height="1" x="913" y="102" fill="#E9EFF5" />
<rect
width="21"
height="8"
x="925"
y="63"
fill="#E9EFF5"
rx="1"
/>
<rect
width="109"
height="8"
x="978"
y="63"
fill="#E9EFF5"
rx="1"
/>
<rect
width="85"
height="8"
x="978"
y="81"
fill="#E9EFF5"
rx="1"
/>
</g>
</g>
)}
</SVG>
</SVGContainer>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Masks/quicklinks.jsx
import React, { PureComponent } from "react";
import styled, { keyframes, css } from "styled-components";
import color from "../ColorPalette";
const SVGContainer = styled.div`
width: 100%;
${(props) =>
props.isVertical
? css`
height: 192px;
width: 224px;
`
: css`
position: ${props.device === "mobile" ? "sticky" : "fixed"};
height: 48px;
background-color: ${color("blue", "700")};
`};
`;
const pulseAnimation = keyframes`
0% {
fill: ${color("white", "10")};
}
50% {
fill: ${color("white", "20")};
}
100% {
fill: ${color("white", "10")};
}
`;
const SVG = styled.svg`
display: block;
width: 100%;
height: ${(props) => (props.isVertical ? "192px" : "48px")};
rect.pulse {
animation: ${pulseAnimation} 1.25s infinite;
}
`;
export default class QuickLinksMask extends PureComponent {
static defaultProps = {
isVertical: false,
device: "mobile"
};
render() {
return (
<SVGContainer
data-qa-label="quickLinksMask"
isVertical={this.props.isVertical}
device={this.props.device}
>
<SVG isVertical={this.props.isVertical}>
{this.props.isVertical ? (
<g fillRule="evenodd">
<rect
className="pulse"
width="96"
height="8"
x="12"
y="176"
fill={color("white", "10")}
rx="1"
/>
<rect
className="pulse"
width="120"
height="8"
x="12"
y="136"
fill={color("white", "10")}
rx="1"
/>
<rect
className="pulse"
width="96"
height="8"
x="12"
y="96"
fill={color("white", "10")}
rx="1"
/>
<rect
className="pulse"
width="120"
height="8"
x="12"
y="56"
fill={color("white", "10")}
rx="1"
/>
<rect
className="pulse"
width="136"
height="8"
x="12"
y="16"
fill={color("white", "10")}
rx="1"
/>
<rect
width="224"
height="200"
fill={color("white", "10")}
fillRule="nonzero"
rx="4"
/>
</g>
) : (
<g fillRule="evenodd">
<rect
className="pulse"
fill={color("white", "10")}
height="8"
rx="1"
width="88"
x="12"
y="20"
/>
<rect
className="pulse"
fill={color("white", "10")}
height="8"
rx="1"
width="88"
x="236"
y="20"
/>
<rect
className="pulse"
fill={color("white", "10")}
height="8"
rx="1"
width="88"
x="124"
y="20"
/>
<rect
className="pulse"
fill={color("white", "10")}
height="8"
rx="1"
width="88"
x="348"
y="20"
/>
<rect
className="pulse"
fill={color("white", "10")}
height="8"
rx="1"
width="88"
x="460"
y="20"
/>
</g>
)}
</SVG>
</SVGContainer>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Masks/topRaces.jsx
import React, { PureComponent } from "react";
import styled, { keyframes } from "styled-components";
import color from "../ColorPalette";
const pulseAnimation = keyframes`
0% {
fill: ${color("grey", "000")};
}
50% {
fill: ${color("blue", "000")};
}
100% {
fill: ${color("grey", "000")};
}
`;
const Container = styled.div`
width: 100%;
background-color: white;
`;
const SVG = styled.svg`
display: block;
height: 380px;
width: 100%;
rect.pulse {
animation: ${pulseAnimation} 1.25s infinite;
}
`;
export default class TopRacesMask extends PureComponent {
static defaultProps = {
device: "mobile"
};
render() {
return (
<Container>
<SVG>
{this.props.device !== "desktop" ? (
<g fill="none" fillRule="evenodd">
<rect width="1516" height="380" fill="#FFF" fillRule="nonzero" />
<rect
width="291"
height="319"
x="12.5"
y="48.5"
fill="#FFF"
fillRule="nonzero"
stroke="#E9EFF5"
rx="4"
/>
<rect
width="70"
height="8"
x="222"
y="344"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="60"
height="8"
x="24"
y="344"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect width="267" height="1" x="36" y="327" className="pulse" />
<rect
width="156"
height="8"
x="84"
y="306"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="84"
height="8"
x="84"
y="289"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect width="24" height="56" x="12" y="272" className="pulse" />
<rect width="267" height="1" x="36" y="271" className="pulse" />
<rect
width="124"
height="8"
x="84"
y="250"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="52"
height="8"
x="84"
y="233"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect width="24" height="55" x="12" y="216" className="pulse" />
<rect width="267" height="1" x="36" y="215" className="pulse" />
<rect
width="132"
height="8"
x="84"
y="194"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="100"
height="8"
x="84"
y="177"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect width="24" height="55" x="12" y="160" className="pulse" />
<rect width="290" height="1" x="13" y="159" className="pulse" />
<rect
width="64"
height="24"
x="23"
y="124"
className="pulse"
fillRule="nonzero"
rx="2"
/>
<rect
width="98"
height="8"
x="24"
y="82"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="20"
height="8"
x="24"
y="64"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="291"
height="319"
x="312.5"
y="48.5"
fill="#FFF"
fillRule="nonzero"
stroke="#E9EFF5"
rx="4"
/>
<rect
width="70"
height="8"
x="522"
y="344"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="60"
height="8"
x="324"
y="344"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect width="267" height="1" x="336" y="327" className="pulse" />
<rect
width="156"
height="8"
x="384"
y="306"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="84"
height="8"
x="384"
y="289"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect width="24" height="56" x="312" y="272" className="pulse" />
<rect width="267" height="1" x="336" y="271" className="pulse" />
<rect
width="124"
height="8"
x="384"
y="250"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="52"
height="8"
x="384"
y="233"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect width="24" height="55" x="312" y="216" className="pulse" />
<rect width="267" height="1" x="336" y="215" className="pulse" />
<rect
width="132"
height="8"
x="384"
y="194"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="100"
height="8"
x="384"
y="177"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect width="24" height="55" x="312" y="160" className="pulse" />
<rect width="290" height="1" x="313" y="159" className="pulse" />
<rect
width="64"
height="24"
x="323"
y="124"
className="pulse"
fillRule="nonzero"
rx="2"
/>
<rect
width="98"
height="8"
x="324"
y="82"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="20"
height="8"
x="324"
y="64"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="291"
height="319"
x="612.5"
y="48.5"
fill="#FFF"
fillRule="nonzero"
stroke="#E9EFF5"
rx="4"
/>
<rect
width="70"
height="8"
x="822"
y="344"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="60"
height="8"
x="624"
y="344"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect width="267" height="1" x="636" y="327" className="pulse" />
<rect
width="156"
height="8"
x="684"
y="306"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="84"
height="8"
x="684"
y="289"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect width="24" height="56" x="612" y="272" className="pulse" />
<rect width="267" height="1" x="636" y="271" className="pulse" />
<rect
width="124"
height="8"
x="684"
y="250"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="52"
height="8"
x="684"
y="233"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect width="24" height="55" x="612" y="216" className="pulse" />
<rect width="267" height="1" x="636" y="215" className="pulse" />
<rect
width="132"
height="8"
x="684"
y="194"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="100"
height="8"
x="684"
y="177"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect width="24" height="55" x="612" y="160" className="pulse" />
<rect width="290" height="1" x="613" y="159" className="pulse" />
<rect
width="64"
height="24"
x="623"
y="124"
className="pulse"
fillRule="nonzero"
rx="2"
/>
<rect
width="98"
height="8"
x="624"
y="82"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="20"
height="8"
x="624"
y="64"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="291"
height="319"
x="912.5"
y="48.5"
fill="#FFF"
fillRule="nonzero"
stroke="#E9EFF5"
rx="4"
/>
<rect
width="70"
height="8"
x="1122"
y="344"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="60"
height="8"
x="924"
y="344"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect width="267" height="1" x="936" y="327" className="pulse" />
<rect
width="156"
height="8"
x="984"
y="306"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="84"
height="8"
x="984"
y="289"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect width="24" height="56" x="912" y="272" className="pulse" />
<rect width="267" height="1" x="936" y="271" className="pulse" />
<rect
width="124"
height="8"
x="984"
y="250"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="52"
height="8"
x="984"
y="233"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect width="24" height="55" x="912" y="216" className="pulse" />
<rect width="267" height="1" x="936" y="215" className="pulse" />
<rect
width="132"
height="8"
x="984"
y="194"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="100"
height="8"
x="984"
y="177"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect width="24" height="55" x="912" y="160" className="pulse" />
<rect width="290" height="1" x="913" y="159" className="pulse" />
<rect
width="64"
height="24"
x="923"
y="124"
className="pulse"
fillRule="nonzero"
rx="2"
/>
<rect
width="98"
height="8"
x="924"
y="82"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="20"
height="8"
x="924"
y="64"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="291"
height="319"
x="1212.5"
y="48.5"
fill="#FFF"
fillRule="nonzero"
stroke="#E9EFF5"
rx="4"
/>
<rect
width="70"
height="8"
x="1422"
y="344"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="60"
height="8"
x="1224"
y="344"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect width="267" height="1" x="1236" y="327" className="pulse" />
<rect
width="156"
height="8"
x="1284"
y="306"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="84"
height="8"
x="1284"
y="289"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect width="24" height="56" x="1212" y="272" className="pulse" />
<rect width="267" height="1" x="1236" y="271" className="pulse" />
<rect
width="124"
height="8"
x="1284"
y="250"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="52"
height="8"
x="1284"
y="233"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect width="24" height="55" x="1212" y="216" className="pulse" />
<rect width="267" height="1" x="1236" y="215" className="pulse" />
<rect
width="132"
height="8"
x="1284"
y="194"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="100"
height="8"
x="1284"
y="177"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect width="24" height="55" x="1212" y="160" className="pulse" />
<rect width="290" height="1" x="1213" y="159" className="pulse" />
<rect
width="64"
height="24"
x="1223"
y="124"
className="pulse"
fillRule="nonzero"
rx="2"
/>
<rect
width="98"
height="8"
x="1224"
y="82"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="20"
height="8"
x="1224"
y="64"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="73"
height="8"
x="12"
y="20"
className="pulse"
fillRule="nonzero"
rx="1"
/>
</g>
) : (
<g fill="none" fillRule="evenodd" transform="translate(-208 -542)">
<rect width="1440" height="100%" fill="#E6E9EF" />
<g transform="translate(208 542)">
<g transform="translate(687 56)">
<rect
width="324"
height="319"
x=".5"
y=".5"
fill="#FFF"
fillRule="nonzero"
stroke="#D6E3F0"
rx="4"
/>
<rect
width="70"
height="8"
x="244"
y="296"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
<rect
width="60"
height="8"
x="12"
y="296"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
<rect
width="84"
height="8"
x="72"
y="241"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
<rect
width="156"
height="8"
x="72"
y="258"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
<rect width="24" height="56" y="224" fill="#E6E9EF" />
<rect
width="52"
height="8"
x="72"
y="185"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
<rect
width="124"
height="8"
x="72"
y="202"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
<rect width="24" height="55" y="168" fill="#E6E9EF" />
<rect
width="100"
height="8"
x="72"
y="129"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
<rect
width="132"
height="8"
x="72"
y="146"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
<rect width="24" height="55" y="112" fill="#E6E9EF" />
<rect width="325" height="1" y="111" fill="#D6E3F0" />
<rect width="325" height="1" y="279" fill="#D6E3F0" />
<rect width="301" height="1" x="24" y="167" fill="#D6E3F0" />
<rect width="301" height="1" x="24" y="223" fill="#D6E3F0" />
<rect
width="64"
height="24"
x="11"
y="76"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="2"
/>
<rect
width="98"
height="8"
x="12"
y="34"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
<rect
width="20"
height="8"
x="12"
y="16"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
</g>
<g transform="translate(349 56)">
<rect
width="325"
height="319"
x=".5"
y=".5"
fill="#FFF"
fillRule="nonzero"
stroke="#D6E3F0"
rx="4"
/>
<rect
width="70"
height="8"
x="244"
y="296"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
<rect
width="60"
height="8"
x="12"
y="296"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
<rect
width="84"
height="8"
x="72"
y="241"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
<rect
width="156"
height="8"
x="72"
y="258"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
<rect width="24" height="56" y="224" fill="#E6E9EF" />
<rect
width="52"
height="8"
x="72"
y="185"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
<rect
width="124"
height="8"
x="72"
y="202"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
<rect width="24" height="55" y="168" fill="#E6E9EF" />
<rect
width="100"
height="8"
x="72"
y="129"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
<rect
width="132"
height="8"
x="72"
y="146"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
<rect width="24" height="55" y="112" fill="#E6E9EF" />
<rect width="325" height="1" y="111" fill="#D6E3F0" />
<rect width="325" height="1" y="279" fill="#D6E3F0" />
<rect width="301" height="1" x="24" y="167" fill="#D6E3F0" />
<rect width="301" height="1" x="24" y="223" fill="#D6E3F0" />
<rect
width="64"
height="24"
x="11"
y="76"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="2"
/>
<rect
width="98"
height="8"
x="12"
y="34"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
<rect
width="20"
height="8"
x="12"
y="16"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
</g>
<g transform="translate(12 56)">
<rect
width="324"
height="319"
x=".5"
y=".5"
fill="#FFF"
fillRule="nonzero"
stroke="#D6E3F0"
rx="4"
/>
<rect
width="70"
height="8"
x="244"
y="296"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
<rect
width="60"
height="8"
x="12"
y="296"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
<rect
width="84"
height="8"
x="72"
y="241"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
<rect
width="156"
height="8"
x="72"
y="258"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
<rect width="24" height="56" y="224" fill="#E6E9EF" />
<rect
width="52"
height="8"
x="72"
y="185"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
<rect
width="124"
height="8"
x="72"
y="202"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
<rect width="24" height="55" y="168" fill="#E6E9EF" />
<rect
width="100"
height="8"
x="72"
y="129"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
<rect
width="132"
height="8"
x="72"
y="146"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
<rect width="24" height="55" y="112" fill="#E6E9EF" />
<rect width="325" height="1" y="111" fill="#D6E3F0" />
<rect width="325" height="1" y="279" fill="#D6E3F0" />
<rect width="301" height="1" x="24" y="167" fill="#D6E3F0" />
<rect width="301" height="1" x="24" y="223" fill="#D6E3F0" />
<rect
width="64"
height="24"
x="11"
y="76"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="2"
/>
<rect
width="98"
height="8"
x="12"
y="34"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
<rect
width="20"
height="8"
x="12"
y="16"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
</g>
<rect
width="73"
height="8"
x="12"
y="24"
fill="#E6E9EF"
fillRule="nonzero"
className="pulse"
rx="1"
/>
</g>
</g>
)}
</SVG>
</Container>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Masks/topRace.jsx
import React, { PureComponent } from "react";
import styled, { keyframes } from "styled-components";
import color from "../ColorPalette";
const pulseAnimation = keyframes`
0% {
fill: ${color("grey", "000")};
}
50% {
fill: ${color("blue", "000")};
}
100% {
fill: ${color("grey", "000")};
}
`;
const SVG = styled.svg`
width: auto;
height: 320px;
rect.pulse {
animation: ${pulseAnimation} 1.25s infinite;
}
`;
export default class TopRacesMask extends PureComponent {
render() {
return (
<SVG>
<g fill="none" fillRule="evenodd">
<rect
width="291"
height="319"
x=".5"
y=".5"
fill="#FFF"
fillRule="nonzero"
stroke="#E6E9EF"
rx="4"
/>
<rect
width="70"
height="8"
x="210"
y="296"
fill="#E6E9EF"
fillRule="nonzero"
rx="1"
/>
<rect
width="60"
height="8"
x="12"
y="296"
fill="#E6E9EF"
fillRule="nonzero"
rx="1"
/>
<g fill="#E6E9EF" transform="translate(0 112)">
<path d="M24 55h268v1H24z" />
<rect
width="100"
height="8"
x="72"
y="17"
fillRule="nonzero"
rx="1"
/>
<rect
width="132"
height="8"
x="72"
y="34"
fillRule="nonzero"
rx="1"
/>
<path d="M0 0h24v55H0z" />
</g>
<g fill="#E6E9EF" transform="translate(0 168)">
<path d="M24 55h268v1H24z" />
<rect
width="52"
height="8"
x="72"
y="17"
fillRule="nonzero"
rx="1"
/>
<rect
width="124"
height="8"
x="72"
y="34"
fillRule="nonzero"
rx="1"
/>
<path d="M0 0h24v55H0z" />
</g>
<g fill="#E6E9EF" transform="translate(0 224)">
<path d="M0 55h292v1H0z" />
<rect
width="84"
height="8"
x="72"
y="17"
fillRule="nonzero"
rx="1"
/>
<rect
width="156"
height="8"
x="72"
y="34"
fillRule="nonzero"
rx="1"
/>
<path d="M0 0h24v56H0z" />
</g>
<path
fill="#FFF"
fillRule="nonzero"
stroke="#E6E9EF"
d="M.5 111.5h291V4A3.5 3.5 0 0 0 288 .5H4A3.5 3.5 0 0 0 .5 4v107.5z"
/>
<rect
width="64"
height="24"
x="11"
y="76"
fill="#E6E9EF"
fillRule="nonzero"
rx="2"
/>
<rect
width="98"
height="8"
x="12"
y="34"
fill="#E6E9EF"
fillRule="nonzero"
rx="1"
/>
<rect
width="20"
height="8"
x="12"
y="16"
fill="#E6E9EF"
fillRule="nonzero"
rx="1"
/>
</g>
</SVG>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Masks/topPools.jsx
import React, { PureComponent } from "react";
import styled, { keyframes } from "styled-components";
import color from "../ColorPalette";
const SVGContainer = styled.div`
width: 100%;
margin-bottom: ${(props) => (props.isDesktop ? "12px" : 0)};
`;
const pulseAnimation = keyframes`
0% {
fill: ${color("grey", "000")};
}
50% {
fill: ${color("blue", "000")};
}
100% {
fill: ${color("grey", "000")};
}
`;
const SVG = styled.svg`
display: block;
width: 100%;
height: ${(props) => (props.isDesktop ? "440px" : "172px")};
rect.pulse {
animation: ${pulseAnimation} 1.25s infinite;
}
rect.stroke {
stroke: ${color("blue", "100")};
stroke-width: 1;
}
`;
/*
TODO: Use buildColor to set the mask color
*/
export default class TopPoolsMask extends PureComponent {
static defaultProps = {
isDesktop: false
};
render() {
return (
<SVGContainer
data-qa-label="topPoolsMask"
isDesktop={this.props.isDesktop}
>
<SVG isDesktop={this.props.isDesktop}>
{this.props.isDesktop ? (
<g fill="none" fillRule="evenodd">
<rect width="325" height="440" className="pulse" />
<rect
width="325"
height="440"
fill={color("white", "100")}
fillRule="nonzero"
/>
<rect
width="110"
height="8"
x="12"
y="25"
className="pulse"
rx="1"
/>
<rect
width="34"
height="8"
x="12"
y="67"
className="pulse"
rx="1"
/>
<rect
width="124"
height="8"
x="64"
y="67"
className="pulse"
rx="1"
/>
<rect
width="65"
height="8"
x="248"
y="76"
className="pulse"
rx="1"
/>
<rect
width="90"
height="8"
x="64"
y="87"
className="pulse"
rx="1"
/>
<rect
width="34"
height="8"
x="12"
y="131"
className="pulse"
rx="1"
/>
<rect
width="34"
height="8"
x="12"
y="195"
className="pulse"
rx="1"
/>
<rect
width="148"
height="8"
x="64"
y="131"
className="pulse"
rx="1"
/>
<rect
width="124"
height="8"
x="64"
y="195"
className="pulse"
rx="1"
/>
<rect
width="49"
height="8"
x="264"
y="140"
className="pulse"
rx="1"
/>
<rect
width="49"
height="8"
x="264"
y="204"
className="pulse"
rx="1"
/>
<rect
width="74"
height="8"
x="64"
y="151"
className="pulse"
rx="1"
/>
<rect
width="74"
height="8"
x="64"
y="215"
className="pulse"
rx="1"
/>
<rect width="301" height="1" x="12" y="111" className="pulse" />
<rect width="301" height="1" x="12" y="175" className="pulse" />
<rect width="301" height="1" x="12" y="239" className="pulse" />
<rect
width="34"
height="8"
x="12"
y="259"
className="pulse"
rx="1"
/>
<rect
width="140"
height="8"
x="64"
y="259"
className="pulse"
rx="1"
/>
<rect
width="57"
height="8"
x="256"
y="268"
className="pulse"
rx="1"
/>
<rect
width="90"
height="8"
x="64"
y="279"
className="pulse"
rx="1"
/>
<rect width="301" height="1" x="12" y="303" className="pulse" />
<rect
width="34"
height="8"
x="12"
y="323"
className="pulse"
rx="1"
/>
<rect
width="140"
height="8"
x="64"
y="323"
className="pulse"
rx="1"
/>
<rect
width="57"
height="8"
x="256"
y="332"
className="pulse"
rx="1"
/>
<rect
width="90"
height="8"
x="64"
y="343"
className="pulse"
rx="1"
/>
<rect width="301" height="1" x="12" y="367" className="pulse" />
<rect
width="34"
height="8"
x="12"
y="387"
className="pulse"
rx="1"
/>
<rect
width="164"
height="8"
x="64"
y="387"
className="pulse"
rx="1"
/>
<rect
width="33"
height="8"
x="280"
y="396"
className="pulse"
rx="1"
/>
<rect
width="90"
height="8"
x="64"
y="407"
className="pulse"
rx="1"
/>
</g>
) : (
<g fill="none" fillRule="evenodd">
<rect
width="1506"
height="172"
fill={color("white", "100")}
fillRule="nonzero"
/>
<rect
width="141"
height="111"
x="12.5"
y="48.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="141"
height="111"
x="162.5"
y="48.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="98"
height="8"
x="24"
y="82"
className="pulse"
rx="1"
/>
<rect
width="98"
height="8"
x="174"
y="82"
className="pulse"
rx="1"
/>
<rect
width="20"
height="8"
x="24"
y="64"
className="pulse"
rx="1"
/>
<rect
width="98"
height="8"
x="24"
y="136"
className="pulse"
rx="1"
/>
<rect
width="68"
height="8"
x="24"
y="118"
className="pulse"
rx="1"
/>
<rect
width="28"
height="8"
x="174"
y="64"
className="pulse"
rx="1"
/>
<rect
width="66"
height="8"
x="174"
y="136"
className="pulse"
rx="1"
/>
<rect
width="60"
height="8"
x="174"
y="118"
className="pulse"
rx="1"
/>
<rect
width="141"
height="111"
x="312.5"
y="48.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="74"
height="8"
x="324"
y="82"
className="pulse"
rx="1"
/>
<rect
width="28"
height="8"
x="324"
y="64"
className="pulse"
rx="1"
/>
<rect
width="74"
height="8"
x="324"
y="138"
className="pulse"
rx="1"
/>
<rect
width="28"
height="8"
x="324"
y="120"
className="pulse"
rx="1"
/>
<rect
width="141"
height="111"
x="462.5"
y="48.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="90"
height="8"
x="474"
y="82"
className="pulse"
rx="1"
/>
<rect
width="20"
height="8"
x="474"
y="64"
className="pulse"
rx="1"
/>
<rect
width="114"
height="8"
x="474"
y="137"
className="pulse"
rx="1"
/>
<rect
width="20"
height="8"
x="474"
y="119"
className="pulse"
rx="1"
/>
<rect
width="141"
height="111"
x="612.5"
y="48.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="98"
height="8"
x="624"
y="82"
className="pulse"
rx="1"
/>
<rect
width="36"
height="8"
x="624"
y="64"
className="pulse"
rx="1"
/>
<rect
width="82"
height="8"
x="624"
y="136"
className="pulse"
rx="1"
/>
<rect
width="68"
height="8"
x="624"
y="118"
className="pulse"
rx="1"
/>
<rect
width="141"
height="111"
x="762.5"
y="48.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="66"
height="8"
x="774"
y="82"
className="pulse"
rx="1"
/>
<rect
width="36"
height="8"
x="774"
y="64"
className="pulse"
rx="1"
/>
<rect
width="74"
height="8"
x="774"
y="136"
className="pulse"
rx="1"
/>
<rect
width="36"
height="8"
x="774"
y="118"
className="pulse"
rx="1"
/>
<rect
width="141"
height="111"
x="912.5"
y="48.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="141"
height="111"
x="1062.5"
y="48.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="82"
height="8"
x="924"
y="82"
className="pulse"
rx="1"
/>
<rect
width="82"
height="8"
x="1074"
y="82"
className="pulse"
rx="1"
/>
<rect
width="36"
height="8"
x="924"
y="64"
className="pulse"
rx="1"
/>
<rect
width="82"
height="8"
x="924"
y="136"
className="pulse"
rx="1"
/>
<rect
width="68"
height="8"
x="924"
y="118"
className="pulse"
rx="1"
/>
<rect
width="36"
height="8"
x="1074"
y="64"
className="pulse"
rx="1"
/>
<rect
width="82"
height="8"
x="1074"
y="136"
className="pulse"
rx="1"
/>
<rect
width="36"
height="8"
x="1074"
y="118"
className="pulse"
rx="1"
/>
<rect
width="141"
height="111"
x="1212.5"
y="48.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="141"
height="111"
x="1362.5"
y="48.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="82"
height="8"
x="1224"
y="82"
className="pulse"
rx="1"
/>
<rect
width="74"
height="8"
x="1374"
y="82"
className="pulse"
rx="1"
/>
<rect
width="36"
height="8"
x="1224"
y="64"
className="pulse"
rx="1"
/>
<rect
width="106"
height="8"
x="1224"
y="136"
className="pulse"
rx="1"
/>
<rect
width="68"
height="8"
x="1224"
y="118"
className="pulse"
rx="1"
/>
<rect
width="36"
height="8"
x="1374"
y="64"
className="pulse"
rx="1"
/>
<rect
width="58"
height="8"
x="1374"
y="136"
className="pulse"
rx="1"
/>
<rect
width="68"
height="8"
x="1374"
y="118"
className="pulse"
rx="1"
/>
<rect
width="121"
height="8"
x="12"
y="20"
className="pulse"
rx="1"
/>
</g>
)}
</SVG>
</SVGContainer>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Masks/topTracks.jsx
import React, { PureComponent } from "react";
import styled, { keyframes } from "styled-components";
import color from "../ColorPalette";
const SVGContainer = styled.div`
width: 100%;
margin-bottom: ${(props) => (props.isDesktop ? "12px" : 0)};
`;
const pulseAnimation = keyframes`
0% {
fill: ${color("grey", "000")};
}
50% {
fill: ${color("blue", "000")};
}
100% {
fill: ${color("grey", "000")};
}
`;
const SVG = styled.svg`
display: block;
width: 100%;
height: 620px;
rect.pulse {
animation: ${pulseAnimation} 1.25s infinite;
}
rect.stroke {
stroke: ${color("blue", "100")};
stroke-width: 1;
}
`;
/*
TODO: Use buildColor to set the mask color
*/
export default class TopTracksMask extends PureComponent {
static defaultProps = {
isDesktop: false
};
render() {
return (
<SVGContainer
data-qa-label="topTracksMask"
isDesktop={this.props.isDesktop}
>
<SVG isDesktop={this.props.isDesktop}>
{this.props.isDesktop ? (
<g fill="none" fillRule="evenodd">
<rect width="100%" height="620" className="pulse" />
<rect
width="100%"
height="620"
fill={color("white", "100")}
fillRule="nonzero"
/>
<rect
width="31"
height="47"
x="12.5"
y="88.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="31"
height="47"
x="12.5"
y="184.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="91"
height="47"
x="52.5"
y="88.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="60"
y="117"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="60"
y="99"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="52.5"
y="184.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="60"
y="213"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="60"
y="195"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="152.5"
y="88.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="160"
y="117"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="160"
y="99"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="152.5"
y="184.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="160"
y="213"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="160"
y="195"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="252.5"
y="88.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="260"
y="117"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="260"
y="99"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="252.5"
y="184.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="260"
y="213"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="260"
y="195"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="352.5"
y="88.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="360"
y="117"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="360"
y="99"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="352.5"
y="184.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="360"
y="213"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="360"
y="195"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="452.5"
y="88.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="460"
y="117"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="460"
y="99"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="452.5"
y="184.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="460"
y="213"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="460"
y="195"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="552.5"
y="88.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="560"
y="117"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="560"
y="99"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="552.5"
y="184.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="560"
y="213"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="560"
y="195"
className="pulse"
rx="1"
/>
<rect
width="31"
height="47"
x="619.5"
y="88.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="31"
height="47"
x="619.5"
y="184.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="73"
height="8"
x="12"
y="20"
className="pulse"
rx="1"
/>
<rect
width="99"
height="8"
x="12"
y="65"
className="pulse"
rx="1"
/>
<rect
width="99"
height="8"
x="12"
y="161"
className="pulse"
rx="1"
/>
<rect
width="31"
height="47"
x="12.5"
y="280.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="91"
height="47"
x="52.5"
y="280.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="60"
y="309"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="60"
y="291"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="152.5"
y="280.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="160"
y="309"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="160"
y="291"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="252.5"
y="280.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="260"
y="309"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="260"
y="291"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="352.5"
y="280.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="360"
y="309"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="360"
y="291"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="452.5"
y="280.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="460"
y="309"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="460"
y="291"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="552.5"
y="280.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="560"
y="309"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="560"
y="291"
className="pulse"
rx="1"
/>
<rect
width="31"
height="47"
x="619.5"
y="280.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="99"
height="8"
x="12"
y="257"
className="pulse"
rx="1"
/>
<rect
width="31"
height="47"
x="12.5"
y="376.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="91"
height="47"
x="52.5"
y="376.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="60"
y="405"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="60"
y="387"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="152.5"
y="376.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="160"
y="405"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="160"
y="387"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="252.5"
y="376.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="260"
y="405"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="260"
y="387"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="352.5"
y="376.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="360"
y="405"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="360"
y="387"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="452.5"
y="376.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="460"
y="405"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="460"
y="387"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="552.5"
y="376.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="560"
y="405"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="560"
y="387"
className="pulse"
rx="1"
/>
<rect
width="31"
height="47"
x="619.5"
y="376.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="99"
height="8"
x="12"
y="353"
className="pulse"
rx="1"
/>
<rect
width="31"
height="47"
x="12.5"
y="472.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="91"
height="47"
x="52.5"
y="472.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="60"
y="501"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="60"
y="483"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="152.5"
y="472.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="160"
y="501"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="160"
y="483"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="252.5"
y="472.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="260"
y="501"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="260"
y="483"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="352.5"
y="472.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="360"
y="501"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="360"
y="483"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="452.5"
y="472.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="460"
y="501"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="460"
y="483"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="552.5"
y="472.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="560"
y="501"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="560"
y="483"
className="pulse"
rx="1"
/>
<rect
width="31"
height="47"
x="619.5"
y="472.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="99"
height="8"
x="12"
y="449"
className="pulse"
rx="1"
/>
<rect
width="31"
height="47"
x="12.5"
y="568.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="91"
height="47"
x="52.5"
y="568.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="60"
y="597"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="60"
y="579"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="152.5"
y="568.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="160"
y="597"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="160"
y="579"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="252.5"
y="568.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="260"
y="597"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="260"
y="579"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="352.5"
y="568.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="360"
y="597"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="360"
y="579"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="452.5"
y="568.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="460"
y="597"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="460"
y="579"
className="pulse"
rx="1"
/>
<rect
width="91"
height="47"
x="552.5"
y="568.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="560"
y="597"
className="pulse"
rx="1"
/>
<rect
width="41"
height="8"
x="560"
y="579"
className="pulse"
rx="1"
/>
<rect
width="31"
height="47"
x="619.5"
y="568.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="99"
height="8"
x="12"
y="545"
className="pulse"
rx="1"
/>
</g>
) : (
<g fill="none" fillRule="evenodd">
<rect width="100%" height="620" fill={color("white", "100")} />
<rect
width="100%"
height="620"
fill={color("white", "100")}
fillRule="nonzero"
/>
<rect
width="91"
height="47"
x="12.5"
y="80.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="20"
y="109"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="20"
y="91"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="12.5"
y="176.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="20"
y="205"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="20"
y="187"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="112.5"
y="80.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="120"
y="109"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="120"
y="91"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="112.5"
y="176.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="120"
y="205"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="120"
y="187"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="212.5"
y="80.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="219"
y="109"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="220"
y="91"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="212.5"
y="176.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="219"
y="205"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="220"
y="187"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="312.5"
y="80.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="320"
y="109"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="320"
y="91"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="312.5"
y="176.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="320"
y="205"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="320"
y="187"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="412.5"
y="80.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="420"
y="109"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="420"
y="91"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="412.5"
y="176.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="420"
y="205"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="420"
y="187"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="512.5"
y="80.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="520"
y="109"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="520"
y="91"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="512.5"
y="176.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="520"
y="205"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="520"
y="187"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="612.5"
y="80.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="620"
y="109"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="620"
y="91"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="612.5"
y="176.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="620"
y="205"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="620"
y="187"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="712.5"
y="80.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="720"
y="109"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="720"
y="91"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="712.5"
y="176.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="720"
y="205"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="720"
y="187"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="73"
height="8"
x="12"
y="20"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="99"
height="8"
x="12"
y="57"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="99"
height="8"
x="12"
y="153"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="12.5"
y="272.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="20"
y="301"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="20"
y="283"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="112.5"
y="272.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="120"
y="301"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="120"
y="283"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="212.5"
y="272.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="219"
y="301"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="220"
y="283"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="312.5"
y="272.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="320"
y="301"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="320"
y="283"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="412.5"
y="272.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="420"
y="301"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="420"
y="283"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="512.5"
y="272.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="520"
y="301"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="520"
y="283"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="612.5"
y="272.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="620"
y="301"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="620"
y="283"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="712.5"
y="272.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="720"
y="301"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="720"
y="283"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="99"
height="8"
x="12"
y="249"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="12.5"
y="368.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="20"
y="397"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="20"
y="379"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="112.5"
y="368.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="120"
y="397"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="120"
y="379"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="212.5"
y="368.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="219"
y="397"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="220"
y="379"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="312.5"
y="368.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="320"
y="397"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="320"
y="379"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="412.5"
y="368.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="420"
y="397"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="420"
y="379"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="512.5"
y="368.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="520"
y="397"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="520"
y="379"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="612.5"
y="368.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="620"
y="397"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="620"
y="379"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="712.5"
y="368.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="720"
y="397"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="720"
y="379"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="99"
height="8"
x="12"
y="345"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="12.5"
y="464.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="20"
y="493"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="20"
y="475"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="112.5"
y="464.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="120"
y="493"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="120"
y="475"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="212.5"
y="464.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="219"
y="493"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="220"
y="475"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="312.5"
y="464.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="320"
y="493"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="320"
y="475"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="412.5"
y="464.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="420"
y="493"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="420"
y="475"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="512.5"
y="464.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="520"
y="493"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="520"
y="475"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="612.5"
y="464.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="620"
y="493"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="620"
y="475"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="712.5"
y="464.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="720"
y="493"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="720"
y="475"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="99"
height="8"
x="12"
y="441"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="12.5"
y="560.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="20"
y="589"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="20"
y="571"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="112.5"
y="560.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="120"
y="589"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="120"
y="571"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="212.5"
y="560.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="219"
y="589"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="220"
y="571"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="312.5"
y="560.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="320"
y="589"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="320"
y="571"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="412.5"
y="560.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="420"
y="589"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="420"
y="571"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="512.5"
y="560.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="520"
y="589"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="520"
y="571"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="612.5"
y="560.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="620"
y="589"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="620"
y="571"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="91"
height="47"
x="712.5"
y="560.5"
fill={color("white", "100")}
fillRule="nonzero"
className="stroke"
rx="4"
/>
<rect
width="20"
height="8"
x="720"
y="589"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="41"
height="8"
x="720"
y="571"
className="pulse"
fillRule="nonzero"
rx="1"
/>
<rect
width="99"
height="8"
x="12"
y="537"
className="pulse"
fillRule="nonzero"
rx="1"
/>
</g>
)}
</SVG>
</SVGContainer>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Masks/upcomingRaces.jsx
import React, { PureComponent } from "react";
import styled, { keyframes } from "styled-components";
import color from "../ColorPalette";
const pulseAnimation = keyframes`
0% {
fill: ${color("grey", "000")};
}
50% {
fill: ${color("blue", "000")};
}
100% {
fill: ${color("grey", "000")};
}
`;
const Container = styled.div`
width: 100%;
background-color: white;
overflow: hidden;
`;
const SVG = styled.svg`
display: block;
height: 172px;
width: 1366px;
rect.pulse {
animation: ${pulseAnimation} 1.25s infinite;
}
`;
export default class UpcomingRacesMask extends PureComponent {
render() {
return (
<Container>
<SVG>
<g fill="none" fillRule="evenodd">
<rect width="1366" height="1024" className="pulse" />
<rect width="1366" height="172" fill="#FFF" fillRule="nonzero" />
<rect
width="141"
height="111"
x="12.5"
y="48.5"
fill="#FFF"
fillRule="nonzero"
stroke="#CFDBE8"
rx="4"
/>
<rect
width="141"
height="111"
x="162.5"
y="48.5"
fill="#FFF"
fillRule="nonzero"
stroke="#CFDBE8"
rx="4"
/>
<rect
width="98"
height="8"
x="24"
y="82"
className="pulse"
rx="1"
/>
<rect
width="98"
height="8"
x="174"
y="82"
className="pulse"
rx="1"
/>
<rect
width="20"
height="8"
x="24"
y="64"
className="pulse"
rx="1"
/>
<rect
width="28"
height="8"
x="174"
y="64"
className="pulse"
rx="1"
/>
<rect
width="141"
height="111"
x="312.5"
y="48.5"
fill="#FFF"
fillRule="nonzero"
stroke="#CFDBE8"
rx="4"
/>
<rect
width="74"
height="8"
x="324"
y="82"
className="pulse"
rx="1"
/>
<rect
width="28"
height="8"
x="324"
y="64"
className="pulse"
rx="1"
/>
<rect
width="141"
height="111"
x="462.5"
y="48.5"
fill="#FFF"
fillRule="nonzero"
stroke="#CFDBE8"
rx="4"
/>
<rect
width="114"
height="8"
x="474"
y="82"
className="pulse"
rx="1"
/>
<rect
width="20"
height="8"
x="474"
y="64"
className="pulse"
rx="1"
/>
<rect
width="141"
height="111"
x="612.5"
y="48.5"
fill="#FFF"
fillRule="nonzero"
stroke="#CFDBE8"
rx="4"
/>
<rect
width="98"
height="8"
x="624"
y="82"
className="pulse"
rx="1"
/>
<rect
width="20"
height="8"
x="624"
y="64"
className="pulse"
rx="1"
/>
<rect
width="141"
height="111"
x="762.5"
y="48.5"
fill="#FFF"
fillRule="nonzero"
stroke="#CFDBE8"
rx="4"
/>
<rect
width="90"
height="8"
x="774"
y="82"
className="pulse"
rx="1"
/>
<rect
width="36"
height="8"
x="774"
y="64"
className="pulse"
rx="1"
/>
<rect
width="141"
height="111"
x="912.5"
y="48.5"
fill="#FFF"
fillRule="nonzero"
stroke="#CFDBE8"
rx="4"
/>
<rect
width="141"
height="111"
x="1062.5"
y="48.5"
fill="#FFF"
fillRule="nonzero"
stroke="#CFDBE8"
rx="4"
/>
<rect
width="82"
height="8"
x="924"
y="82"
className="pulse"
rx="1"
/>
<rect
width="82"
height="8"
x="1074"
y="82"
className="pulse"
rx="1"
/>
<rect
width="36"
height="8"
x="924"
y="64"
className="pulse"
rx="1"
/>
<rect
width="36"
height="8"
x="1074"
y="64"
className="pulse"
rx="1"
/>
<rect
width="141"
height="111"
x="1212.5"
y="48.5"
fill="#FFF"
fillRule="nonzero"
stroke="#CFDBE8"
rx="4"
/>
<rect
width="106"
height="8"
x="1224"
y="82"
className="pulse"
rx="1"
/>
<rect
width="36"
height="8"
x="1224"
y="64"
className="pulse"
rx="1"
/>
<rect
width="121"
height="8"
x="12"
y="20"
className="pulse"
rx="1"
/>
</g>
</SVG>
</Container>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Masks/quicklinks-expanded.jsx
import React, { PureComponent } from "react";
import styled, { css } from "styled-components";
import buildColor from "../ColorPalette";
const getContainerPosition = (device) => {
switch (device) {
case "mobile":
return css`
overflow: auto;
padding: 12px 8px 8px 12px;
`;
case "tablet":
return css`
position: absolute;
overflow: hidden;
padding: 12px 12px 8px 4px;
`;
default:
return css`
height: 160px;
overflow: hidden;
padding: 0 8px 8px 0;
`;
}
};
const SVGContainer = styled.nav`
width: 100%;
background-color: var(--fd-colors-racing-background-default);
${({ device }) => getContainerPosition(device)}
`;
const Rect = styled.rect`
width: ${({ device }) => (device !== "mobile" ? "calc(20% - 8px)" : "142px")};
`;
const SVG = styled.svg`
@media (max-width: 1024px) {
padding-left: 12px;
}
`;
const G = styled.g`
transform: ${({ index }) => `translateX(${20 * index}%) translateX(8px)`};
&:last-child > rect:first-child {
width: 20%;
}
`;
export default class QuickLinksMask extends PureComponent {
static defaultProps = { device: "mobile" };
renderTabletMask = () => (
<svg xmlns="http://www.w3.org/2000/svg" height="120" width="100%">
<g fill={`${buildColor("white", "10")}`} fillRule="evenodd">
<G index={0}>
<Rect
device={this.props.device}
height="120"
fillRule="nonzero"
rx="4"
/>
<rect
fillRule="nonzero"
width="calc(20% - 8px)"
height="32"
transform="translate(0,88)"
/>
<rect className="pulse" width="88" height="8" x="12" y="100" rx="1" />
</G>
<G index={1}>
<Rect
device={this.props.device}
height="120"
fillRule="nonzero"
rx="4"
/>
<rect
fillRule="nonzero"
width="calc(20% - 8px)"
height="32"
transform="translate(0,88)"
/>
<rect className="pulse" width="88" height="8" x="12" y="100" rx="1" />
</G>
<G index={2}>
<Rect
device={this.props.device}
width="142"
height="120"
fillRule="nonzero"
rx="4"
/>
<rect
fillRule="nonzero"
width="calc(20% - 8px)"
height="32"
transform="translate(0,88)"
/>
<rect className="pulse" width="88" height="8" x="12" y="100" rx="1" />
</G>
<G index={3}>
<Rect
device={this.props.device}
width="142"
height="120"
fillRule="nonzero"
rx="4"
/>
<rect
fillRule="nonzero"
width="calc(20% - 8px)"
height="32"
transform="translate(0,88)"
/>
<rect className="pulse" width="88" height="8" x="12" y="100" rx="1" />
</G>
<G index={4}>
<Rect
device={this.props.device}
height="120"
fillRule="nonzero"
rx="4"
/>
<rect
fillRule="nonzero"
width="calc(20%)"
height="32"
transform="translate(0,88)"
/>
<rect className="pulse" width="88" height="8" x="12" y="100" rx="1" />
</G>
</g>
</svg>
);
renderDesktopMask = () => (
<SVG xmlns="http://www.w3.org/2000/svg" width="100%" height="152">
<g fill={`${buildColor("white", "10")}`} fillRule="evenodd">
<G removeTranslate index={0}>
<Rect width="190" height="152" fillRule="nonzero" rx="4" />
<rect
fillRule="nonzero"
width="calc(20% - 8px)"
height="40"
transform="translate(0,112)"
/>
<rect
className="pulse"
width="120"
height="8"
x="12"
y="128"
rx="1"
/>
</G>
<G index={1}>
<Rect width="191" height="152" fillRule="nonzero" rx="4" />
<rect
fillRule="nonzero"
width="calc(20% - 8px)"
height="40"
transform="translate(0,112)"
/>
<rect
className="pulse"
width="120"
height="8"
x="12"
y="128"
rx="1"
/>
</G>
<G index={2}>
<Rect width="190" height="152" fillRule="nonzero" rx="4" />
<rect
fillRule="nonzero"
width="calc(20% - 8px)"
height="40"
transform="translate(0,112)"
/>
<rect
className="pulse"
width="120"
height="8"
x="12"
y="128"
rx="1"
/>
</G>
<G index={3}>
<Rect width="191" height="152" fillRule="nonzero" rx="4" />
<rect
fillRule="nonzero"
width="calc(20% - 8px)"
height="40"
transform="translate(0,112)"
/>
<rect
className="pulse"
width="120"
height="8"
x="12"
y="128"
rx="1"
/>
</G>
<G index={4}>
<Rect width="191" height="152" fillRule="nonzero" rx="4" />
<rect
fillRule="nonzero"
width="calc(20% - 8px)"
height="40"
transform="translate(0,112)"
/>
<rect
className="pulse"
width="120"
height="8"
x="12"
y="128"
rx="1"
/>
</G>
</g>
</SVG>
);
renderMobileMask = () => (
<svg xmlns="http://www.w3.org/2000/svg" width="744" height="120">
<g fill={`${buildColor("white", "10")}`} fillRule="evenodd">
<g transform="translate(601)">
<rect width="143" height="120" fillRule="nonzero" rx="4" />
<path
fillRule="nonzero"
d="M0 88h143v28a4 4 0 0 1-4 4H4a4 4 0 0 1-4-4V88z"
/>
<rect className="pulse" width="88" height="8" x="12" y="100" rx="1" />
</g>
<g transform="translate(451)">
<rect width="142" height="120" fillRule="nonzero" rx="4" />
<path
fillRule="nonzero"
d="M0 88h142v28a4 4 0 0 1-4 4H4a4 4 0 0 1-4-4V88z"
/>
<rect className="pulse" width="88" height="8" x="12" y="100" rx="1" />
</g>
<g transform="translate(301)">
<rect width="142" height="120" fillRule="nonzero" rx="4" />
<path
fillRule="nonzero"
d="M0 88h142v28a4 4 0 0 1-4 4H4a4 4 0 0 1-4-4V88z"
/>
<rect className="pulse" width="88" height="8" x="12" y="100" rx="1" />
</g>
<g transform="translate(151)">
<rect width="142" height="120" fillRule="nonzero" rx="4" />
<path
fillRule="nonzero"
d="M0 88h142v28a4 4 0 0 1-4 4H4a4 4 0 0 1-4-4V88z"
/>
<rect className="pulse" width="88" height="8" x="12" y="100" rx="1" />
</g>
<g>
<rect width="143" height="120" fillRule="nonzero" rx="4" />
<path
fillRule="nonzero"
d="M0 88h143v28a4 4 0 0 1-4 4H4a4 4 0 0 1-4-4V88z"
/>
<rect className="pulse" width="88" height="8" x="12" y="100" rx="1" />
</g>
</g>
</svg>
);
render() {
const { device } = this.props;
const mask = () => {
switch (device) {
case "desktop":
return this.renderDesktopMask();
case "tablet":
return this.renderTabletMask();
default:
return this.renderMobileMask();
}
};
return <SVGContainer device={device}>{mask()}</SVGContainer>;
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Masks/fundingControls.jsx
import React, { PureComponent } from "react";
import styled, { keyframes } from "styled-components";
import color from "../ColorPalette";
const pulseAnimation = keyframes`
0% {
fill: ${color("grey", "100")};
}
50% {
fill: ${color("grey", "000")};
}
100% {
fill: ${color("grey", "100")};
}
`;
const SVG = styled.svg`
display: block;
rect.pulse {
animation: ${pulseAnimation} 1.25s infinite;
}
`;
const Container = styled.div`
overflow-x: hidden;
width: 100%;
background-color: ${color("white", "100")};
padding-left: 12px;
padding-top: 10px;
`;
const Row = styled.div`
width: 100%;
height: 49px;
display: flex;
justify-content: space-between;
align-items: center;
padding-right: 12px;
`;
const Divider = styled.hr`
border: 1px solid ${color("grey", "200")};
margin-block-start: 0;
margin-block-end: 0;
margin-inline-start: auto;
margin-inline-end: auto;
border-top-style: none;
border-top-width: 0;
`;
export default class FundingControlsMask extends PureComponent {
render() {
return (
<Container>
<SVG
xmlns="http://www.w3.org/2000/svg"
width="116"
height="12"
viewBox="0 0 116 12"
>
<g fill="none" fillRule="evenodd">
<rect width="116" height="12" className="pulse" />
</g>
</SVG>
<Row>
<SVG
xmlns="http://www.w3.org/2000/svg"
width="56"
height="12"
viewBox="0 0 56 12"
>
<g fill="none" fillRule="evenodd">
<rect width="56" height="12" className="pulse" />
</g>
</SVG>
<SVG
xmlns="http://www.w3.org/2000/svg"
width="73"
height="31"
viewBox="0 0 73 31"
>
<g fill="none" fillRule="evenodd">
<rect
stroke={color("grey", "300")}
width="73"
height="31"
rx="4"
/>
</g>
</SVG>
</Row>
<Divider />
<Row>
<SVG
xmlns="http://www.w3.org/2000/svg"
width="116"
height="12"
viewBox="0 0 116 12"
>
<g fill="none" fillRule="evenodd">
<rect width="116" height="12" className="pulse" />
</g>
</SVG>
<SVG
xmlns="http://www.w3.org/2000/svg"
width="73"
height="31"
viewBox="0 0 73 31"
>
<g fill="none" fillRule="evenodd">
<rect
stroke={color("grey", "300")}
width="73"
height="31"
rx="4"
/>
</g>
</SVG>
</Row>
<Divider />
<Row>
<SVG
xmlns="http://www.w3.org/2000/svg"
width="86"
height="12"
viewBox="0 0 86 12"
>
<g fill="none" fillRule="evenodd">
<rect width="86" height="12" className="pulse" />
</g>
</SVG>
<SVG
xmlns="http://www.w3.org/2000/svg"
width="73"
height="31"
viewBox="0 0 73 31"
>
<g fill="none" fillRule="evenodd">
<rect
stroke={color("grey", "300")}
width="73"
height="31"
rx="4"
/>
</g>
</SVG>
</Row>
<Divider />
<Row>
<SVG
xmlns="http://www.w3.org/2000/svg"
width="46"
height="12"
viewBox="0 0 46 12"
>
<g fill="none" fillRule="evenodd">
<rect width="46" height="12" className="pulse" />
</g>
</SVG>
<SVG
xmlns="http://www.w3.org/2000/svg"
width="73"
height="31"
viewBox="0 0 73 31"
>
<g fill="none" fillRule="evenodd">
<rect
stroke={color("grey", "300")}
width="73"
height="31"
rx="4"
/>
</g>
</SVG>
</Row>
<Divider />
</Container>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Masks/depositLimits.jsx
import React, { PureComponent } from "react";
import styled, { keyframes } from "styled-components";
import color from "../ColorPalette";
const pulseAnimation = keyframes`
0% {
fill: ${color("grey", "100")};
}
50% {
fill: ${color("grey", "000")};
}
100% {
fill: ${color("grey", "100")};
}
`;
const SVG = styled.svg`
display: block;
rect.pulse {
animation: ${pulseAnimation} 1.25s infinite;
}
`;
const Container = styled.div`
overflow-x: hidden;
width: 100%;
background-color: ${color("white", "100")};
padding: 18px 0 18px 12px;
`;
const Content = styled.div`
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
padding-top: 18px;
margin: 0 -6px;
`;
const Pill = styled.div`
width: auto;
flex-grow: 1;
border: 1px solid ${color("grey", "100")};
border-radius: 4px;
height: 54px;
margin: 0 6px;
`;
export default class DepositLimitsMask extends PureComponent {
render() {
return (
<Container>
<SVG
xmlns="http://www.w3.org/2000/svg"
width="330"
height="12"
viewBox="0 0 330 12"
>
<g fill="none" fillRule="evenodd">
<rect width="330" height="12" className="pulse" />
</g>
</SVG>
<Content>
<Pill />
<Pill />
<Pill />
</Content>
</Container>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Masks/ipp.jsx
import React, { PureComponent } from "react";
import styled, { keyframes } from "styled-components";
import color from "../ColorPalette";
const pulseAnimation = keyframes`
0% {
fill: ${color("blue", "000")};
}
50% {
fill: ${color("blue", "100")};
}
100% {
fill: ${color("blue", "000")};
}
`;
const SVG = styled.svg`
display: block;
width: 100%;
height: 324px;
rect.pulse {
animation: ${pulseAnimation} 1.25s infinite;
}
`;
export default class IppMask extends PureComponent {
render() {
return (
<div data-qa-label="ippMask">
<SVG>
<rect
width="100%"
height="324"
fill={color("white", "100")}
rx=".5"
/>
<rect
className="pulse"
width="298"
height="12"
x="12"
y="84"
fill={color("white", "100")}
rx="1"
/>
<rect
className="pulse"
width="248"
height="12"
x="12"
y="60"
fill={color("white", "100")}
rx="1"
/>
<rect
className="pulse"
width="184"
height="12"
x="12"
y="36"
fill={color("white", "100")}
rx="1"
/>
<rect
className="pulse"
width="81"
height="12"
x="69"
y="12"
fill={color("white", "100")}
rx="1"
/>
<rect
className="pulse"
width="49"
height="12"
x="12"
y="12"
fill={color("white", "100")}
rx="1"
/>
<rect
className="pulse"
width="298"
height="12"
x="12"
y="192"
fill={color("white", "100")}
rx="1"
/>
<rect
className="pulse"
width="248"
height="12"
x="12"
y="168"
fill={color("white", "100")}
rx="1"
/>
<rect
className="pulse"
width="184"
height="12"
x="12"
y="144"
fill={color("white", "100")}
rx="1"
/>
<rect
className="pulse"
width="81"
height="12"
x="69"
y="120"
fill={color("white", "100")}
rx="1"
/>
<rect
className="pulse"
width="49"
height="12"
x="12"
y="120"
fill={color("white", "100")}
rx="1"
/>
<rect
className="pulse"
width="298"
height="12"
x="12"
y="300"
fill={color("white", "100")}
rx="1"
/>
<rect
className="pulse"
width="248"
height="12"
x="12"
y="276"
fill={color("white", "100")}
rx="1"
/>
<rect
className="pulse"
width="184"
height="12"
x="12"
y="252"
fill={color("white", "100")}
rx="1"
/>
<rect
className="pulse"
width="81"
height="12"
x="69"
y="228"
fill={color("white", "100")}
rx="1"
/>
<rect
className="pulse"
width="49"
height="12"
x="12"
y="228"
fill={color("white", "100")}
rx="1"
/>
<rect
width="100%"
height="1"
y="107"
fill={color("blue", "100")}
rx=".5"
/>
<rect width="100%" height="1" fill={color("blue", "100")} rx=".5" />
<rect
width="100%"
height="1"
y="215"
fill={color("blue", "100")}
rx=".5"
/>
<rect
width="100%"
height="1"
y="323"
fill={color("blue", "100")}
rx=".5"
/>
</SVG>
</div>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Masks/mybetsStandalone.jsx
import React from "react";
import styled, { keyframes } from "styled-components";
import buildColor from "../ColorPalette";
const pulseAnimation = keyframes`
0% {
fill: ${buildColor("blue", "000")};
}
50% {
fill: ${buildColor("blue", "100")};
}
100% {
fill: ${buildColor("blue", "000")};
}
`;
const MaskContainer = styled.div`
padding: 8px 0;
`;
const CardContainer = styled.div`
background: ${buildColor("grey", "000")};
padding: 0 12px;
&:not(:last-child) {
margin-bottom: 8px;
}
`;
const SVG = styled.svg`
rect {
animation: ${pulseAnimation} 1.25s infinite;
}
`;
const Card = () => {
const rectColor = buildColor("blue", "000");
return (
<CardContainer>
<SVG width="100%" height="236" fill={buildColor("grey", "000")}>
<rect y="40" width="248" height="16" rx="1" fill={rectColor} />
<rect y="104" width="100%" height="116" rx="1" fill={rectColor} />
<rect y="64" width="154" height="16" rx="1" fill={rectColor} />
<rect y="16" width="53" height="16" rx="1" fill={rectColor} />
</SVG>
</CardContainer>
);
};
const MyBetsStandaloneMask = ({ cardAmount }) => {
const renderContent = () => {
const cardArray = [...Array(cardAmount > 0 ? cardAmount : 2)].map(
// eslint-disable-next-line react/no-array-index-key
(value, index) => <Card key={`MyBetsCard-${index}`} />
);
return cardArray;
};
return (
<MaskContainer data-qa-label="myBetsStandaloneMask">
{renderContent()}
</MaskContainer>
);
};
MyBetsStandaloneMask.defaultProps = {
cardAmount: 2
};
export default MyBetsStandaloneMask;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Masks/mybetsDesktop.jsx
import React, { Fragment } from "react";
import styled, { keyframes } from "styled-components";
import buildColor from "../ColorPalette";
const pulseAnimation = keyframes`
0% {
fill: ${buildColor("blue", "000")};
}
50% {
fill: ${buildColor("blue", "100")};
}
100% {
fill: ${buildColor("blue", "000")};
}
`;
const MaskContainer = styled.div`
margin-top: 4px;
`;
const RowContainer = styled.div`
display: grid;
grid-template-columns: 85px 215px 175px 311px auto;
border-radius: 4px;
margin-bottom: 4px;
background-color: ${buildColor("grey", "000")};
&:last-of-type {
margin-bottom: 0;
}
`;
const CellContainer = styled.div`
padding: 0 12px;
`;
const SVG = styled.svg`
rect {
animation: ${pulseAnimation} 1.25s infinite;
}
svg {
overflow: visible;
}
`;
const Cell = ({ type }) => {
const rectColor = buildColor("blue", "000");
return (
<CellContainer>
<SVG width="100%" height="82" fill={buildColor("grey", "000")}>
{type === "status" && (
<rect y="12" width="41" height="14" rx="1" fill={rectColor} />
)}
{type === "raceDetails" && (
<Fragment>
<rect y="12" width="108" height="14" rx="1" fill={rectColor} />
<rect y="30" width="154" height="14" rx="1" fill={rectColor} />
</Fragment>
)}
{type === "betDetails" && (
<Fragment>
<rect y="12" width="138" height="14" rx="1" fill={rectColor} />
<rect y="30" width="67" height="14" rx="1" fill={rectColor} />
</Fragment>
)}
{type === "selections" && (
<Fragment>
<rect y="12" width="98" height="14" rx="1" fill={rectColor} />
<svg x="100%" y="56" width="118" height="14">
<rect
width="118"
height="14"
x="-118"
y="0"
rx="1"
fill={rectColor}
/>
</svg>
</Fragment>
)}
{type === "actions" && (
<Fragment>
<rect y="12" width="40" height="32" rx="1" fill={rectColor} />
<svg x="50%" y="12" width="40" height="32">
<rect
width="40"
height="32"
x="-20"
y="0"
rx="1"
fill={rectColor}
/>
</svg>
<svg x="100%" y="12" width="40" height="32">
<rect
width="40"
height="32"
x="-40"
y="0"
rx="1"
fill={rectColor}
/>
</svg>
</Fragment>
)}
</SVG>
</CellContainer>
);
};
const MyBetsDesktopMask = ({ rowsAmount }) => {
const renderContent = () => {
const rowArray = [...Array(rowsAmount)].map((_value, index) => (
// eslint-disable-next-line react/no-array-index-key
<RowContainer key={`MyBetsRow-${index}`}>
<Cell type="status" />
<Cell type="raceDetails" />
<Cell type="betDetails" />
<Cell type="selections" />
<Cell type="actions" />
</RowContainer>
));
return rowArray;
};
return (
<MaskContainer data-qa-label="myBetsDesktopMask">
{renderContent()}
</MaskContainer>
);
};
MyBetsDesktopMask.defaultProps = {
rowsAmount: 4
};
export default MyBetsDesktopMask;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Masks/desktopWallet.jsx
import React from "react";
import styled, { keyframes } from "styled-components";
import color from "../ColorPalette";
const pulseAnimation = keyframes`
0% {
fill: ${color("grey", "100")};
}
50% {
fill: ${color("grey", "000")};
}
100% {
fill: ${color("grey", "100")};
}
`;
const SVG = styled.svg`
display: block;
margin: 12px auto;
rect.pulse {
animation: ${pulseAnimation} 1.25s infinite;
}
`;
const DesktopWallet = () => (
<SVG
width="978"
height="557"
viewBox="0 0 978 557"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<g filter="url(#filter0_iii)">
<path d="M1 5C1 2.79086 2.79086 1 5 1H321V112H1V5Z" fill="#FAFCFF" />
<rect
x="21"
y="21"
width="100"
height="16"
fill="#E9EFF5"
className="pulse"
/>
<rect
x="21"
y="51"
width="200"
height="16"
fill="#E9EFF5"
className="pulse"
/>
</g>
<g filter="url(#filter1_i)">
<path
d="M321 1H973C975.209 1 977 2.79086 977 5V112H321V1Z"
fill="white"
/>
<rect
x="341"
y="48"
width="200"
height="16"
fill="#E9EFF5"
className="pulse"
/>
</g>
<g filter="url(#filter2_i)">
<rect
width="656"
height="111"
transform="translate(321 112)"
fill="white"
/>
<rect
x="341"
y="159"
width="200"
height="16"
fill="#E9EFF5"
className="pulse"
/>
</g>
<g filter="url(#filter3_i)">
<rect
width="656"
height="111"
transform="translate(321 223)"
fill="white"
/>
<rect
x="341"
y="270"
width="200"
height="16"
fill="#E9EFF5"
className="pulse"
/>
</g>
<g filter="url(#filter4_i)">
<rect
width="656"
height="111"
transform="translate(321 334)"
fill="white"
/>
<rect
x="341"
y="381"
width="200"
height="16"
fill="#E9EFF5"
className="pulse"
/>
</g>
<g filter="url(#filter5_i)">
<path
d="M321 445H977V552C977 554.209 975.209 556 973 556H321V445Z"
fill="white"
/>
<rect
x="341"
y="492"
width="200"
height="16"
fill="#E9EFF5"
className="pulse"
/>
</g>
<g filter="url(#filter6_iii)">
<rect
width="320"
height="111"
transform="translate(1 112)"
fill="#FAFCFF"
/>
<rect
x="21"
y="132"
width="100"
height="16"
fill="#E9EFF5"
className="pulse"
/>
<rect
x="21"
y="162"
width="200"
height="16"
fill="#E9EFF5"
className="pulse"
/>
</g>
<g filter="url(#filter7_iii)">
<rect
width="320"
height="111"
transform="translate(1 223)"
fill="#FAFCFF"
/>
<rect
x="21"
y="243"
width="100"
height="16"
fill="#E9EFF5"
className="pulse"
/>
<rect
x="21"
y="273"
width="200"
height="16"
fill="#E9EFF5"
className="pulse"
/>
</g>
<g filter="url(#filter8_iii)">
<rect
width="320"
height="111"
transform="translate(1 334)"
fill="#FAFCFF"
/>
<rect
x="21"
y="354"
width="100"
height="16"
fill="#E9EFF5"
className="pulse"
/>
<rect
x="21"
y="384"
width="200"
height="16"
fill="#E9EFF5"
className="pulse"
/>
</g>
<g filter="url(#filter9_ii)">
<path
d="M1 445H321V556H5C2.79086 556 1 554.209 1 552V445Z"
fill="#FAFCFF"
/>
<rect
x="21"
y="465"
width="100"
height="16"
fill="#E9EFF5"
className="pulse"
/>
<rect
x="21"
y="495"
width="200"
height="16"
fill="#E9EFF5"
className="pulse"
/>
</g>
<rect x="0.5" y="0.5" width="977" height="556" rx="4.5" stroke="#D6E3F0" />
<defs>
<filter
id="filter0_iii"
x="1"
y="1"
width="320"
height="111"
filterUnits="userSpaceOnUse"
colorInterpolationFilters="sRGB"
>
<feFlood floodOpacity="0" result="BackgroundImageFix" />
<feBlend
mode="normal"
in="SourceGraphic"
in2="BackgroundImageFix"
result="shape"
/>
<feColorMatrix
in="SourceAlpha"
type="matrix"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
result="hardAlpha"
/>
<feOffset dy="-1" />
<feComposite in2="hardAlpha" operator="arithmetic" k2="-1" k3="1" />
<feColorMatrix
type="matrix"
values="0 0 0 0 0.839216 0 0 0 0 0.890196 0 0 0 0 0.941176 0 0 0 1 0"
/>
<feBlend mode="normal" in2="shape" result="effect1_innerShadow" />
<feColorMatrix
in="SourceAlpha"
type="matrix"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
result="hardAlpha"
/>
<feOffset dx="19" />
<feComposite in2="hardAlpha" operator="arithmetic" k2="-1" k3="1" />
<feColorMatrix
type="matrix"
values="0 0 0 0 0.980392 0 0 0 0 0.988235 0 0 0 0 1 0 0 0 1 0"
/>
<feBlend
mode="normal"
in2="effect1_innerShadow"
result="effect2_innerShadow"
/>
<feColorMatrix
in="SourceAlpha"
type="matrix"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
result="hardAlpha"
/>
<feOffset dx="-1" />
<feComposite in2="hardAlpha" operator="arithmetic" k2="-1" k3="1" />
<feColorMatrix
type="matrix"
values="0 0 0 0 0.839216 0 0 0 0 0.890196 0 0 0 0 0.941176 0 0 0 1 0"
/>
<feBlend
mode="normal"
in2="effect2_innerShadow"
result="effect3_innerShadow"
/>
</filter>
<filter
id="filter1_i"
x="321"
y="1"
width="656"
height="111"
filterUnits="userSpaceOnUse"
colorInterpolationFilters="sRGB"
>
<feFlood floodOpacity="0" result="BackgroundImageFix" />
<feBlend
mode="normal"
in="SourceGraphic"
in2="BackgroundImageFix"
result="shape"
/>
<feColorMatrix
in="SourceAlpha"
type="matrix"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
result="hardAlpha"
/>
<feOffset dy="-1" />
<feComposite in2="hardAlpha" operator="arithmetic" k2="-1" k3="1" />
<feColorMatrix
type="matrix"
values="0 0 0 0 0.839216 0 0 0 0 0.890196 0 0 0 0 0.941176 0 0 0 1 0"
/>
<feBlend mode="normal" in2="shape" result="effect1_innerShadow" />
</filter>
<filter
id="filter2_i"
x="321"
y="112"
width="656"
height="111"
filterUnits="userSpaceOnUse"
colorInterpolationFilters="sRGB"
>
<feFlood floodOpacity="0" result="BackgroundImageFix" />
<feBlend
mode="normal"
in="SourceGraphic"
in2="BackgroundImageFix"
result="shape"
/>
<feColorMatrix
in="SourceAlpha"
type="matrix"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
result="hardAlpha"
/>
<feOffset dy="-1" />
<feComposite in2="hardAlpha" operator="arithmetic" k2="-1" k3="1" />
<feColorMatrix
type="matrix"
values="0 0 0 0 0.839216 0 0 0 0 0.890196 0 0 0 0 0.941176 0 0 0 1 0"
/>
<feBlend mode="normal" in2="shape" result="effect1_innerShadow" />
</filter>
<filter
id="filter3_i"
x="321"
y="223"
width="656"
height="111"
filterUnits="userSpaceOnUse"
colorInterpolationFilters="sRGB"
>
<feFlood floodOpacity="0" result="BackgroundImageFix" />
<feBlend
mode="normal"
in="SourceGraphic"
in2="BackgroundImageFix"
result="shape"
/>
<feColorMatrix
in="SourceAlpha"
type="matrix"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
result="hardAlpha"
/>
<feOffset dy="-1" />
<feComposite in2="hardAlpha" operator="arithmetic" k2="-1" k3="1" />
<feColorMatrix
type="matrix"
values="0 0 0 0 0.839216 0 0 0 0 0.890196 0 0 0 0 0.941176 0 0 0 1 0"
/>
<feBlend mode="normal" in2="shape" result="effect1_innerShadow" />
</filter>
<filter
id="filter4_i"
x="321"
y="334"
width="656"
height="111"
filterUnits="userSpaceOnUse"
colorInterpolationFilters="sRGB"
>
<feFlood floodOpacity="0" result="BackgroundImageFix" />
<feBlend
mode="normal"
in="SourceGraphic"
in2="BackgroundImageFix"
result="shape"
/>
<feColorMatrix
in="SourceAlpha"
type="matrix"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
result="hardAlpha"
/>
<feOffset dy="-1" />
<feComposite in2="hardAlpha" operator="arithmetic" k2="-1" k3="1" />
<feColorMatrix
type="matrix"
values="0 0 0 0 0.839216 0 0 0 0 0.890196 0 0 0 0 0.941176 0 0 0 1 0"
/>
<feBlend mode="normal" in2="shape" result="effect1_innerShadow" />
</filter>
<filter
id="filter5_i"
x="321"
y="445"
width="656"
height="111"
filterUnits="userSpaceOnUse"
colorInterpolationFilters="sRGB"
>
<feFlood floodOpacity="0" result="BackgroundImageFix" />
<feBlend
mode="normal"
in="SourceGraphic"
in2="BackgroundImageFix"
result="shape"
/>
<feColorMatrix
in="SourceAlpha"
type="matrix"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
result="hardAlpha"
/>
<feOffset dx="19" />
<feComposite in2="hardAlpha" operator="arithmetic" k2="-1" k3="1" />
<feColorMatrix
type="matrix"
values="0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 1 0"
/>
<feBlend mode="normal" in2="shape" result="effect1_innerShadow" />
</filter>
<filter
id="filter6_iii"
x="1"
y="112"
width="320"
height="111"
filterUnits="userSpaceOnUse"
colorInterpolationFilters="sRGB"
>
<feFlood floodOpacity="0" result="BackgroundImageFix" />
<feBlend
mode="normal"
in="SourceGraphic"
in2="BackgroundImageFix"
result="shape"
/>
<feColorMatrix
in="SourceAlpha"
type="matrix"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
result="hardAlpha"
/>
<feOffset dy="-1" />
<feComposite in2="hardAlpha" operator="arithmetic" k2="-1" k3="1" />
<feColorMatrix
type="matrix"
values="0 0 0 0 0.839216 0 0 0 0 0.890196 0 0 0 0 0.941176 0 0 0 1 0"
/>
<feBlend mode="normal" in2="shape" result="effect1_innerShadow" />
<feColorMatrix
in="SourceAlpha"
type="matrix"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
result="hardAlpha"
/>
<feOffset dx="19" />
<feComposite in2="hardAlpha" operator="arithmetic" k2="-1" k3="1" />
<feColorMatrix
type="matrix"
values="0 0 0 0 0.980392 0 0 0 0 0.988235 0 0 0 0 1 0 0 0 1 0"
/>
<feBlend
mode="normal"
in2="effect1_innerShadow"
result="effect2_innerShadow"
/>
<feColorMatrix
in="SourceAlpha"
type="matrix"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
result="hardAlpha"
/>
<feOffset dx="-1" />
<feComposite in2="hardAlpha" operator="arithmetic" k2="-1" k3="1" />
<feColorMatrix
type="matrix"
values="0 0 0 0 0.839216 0 0 0 0 0.890196 0 0 0 0 0.941176 0 0 0 1 0"
/>
<feBlend
mode="normal"
in2="effect2_innerShadow"
result="effect3_innerShadow"
/>
</filter>
<filter
id="filter7_iii"
x="1"
y="223"
width="320"
height="111"
filterUnits="userSpaceOnUse"
colorInterpolationFilters="sRGB"
>
<feFlood floodOpacity="0" result="BackgroundImageFix" />
<feBlend
mode="normal"
in="SourceGraphic"
in2="BackgroundImageFix"
result="shape"
/>
<feColorMatrix
in="SourceAlpha"
type="matrix"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
result="hardAlpha"
/>
<feOffset dy="-1" />
<feComposite in2="hardAlpha" operator="arithmetic" k2="-1" k3="1" />
<feColorMatrix
type="matrix"
values="0 0 0 0 0.839216 0 0 0 0 0.890196 0 0 0 0 0.941176 0 0 0 1 0"
/>
<feBlend mode="normal" in2="shape" result="effect1_innerShadow" />
<feColorMatrix
in="SourceAlpha"
type="matrix"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
result="hardAlpha"
/>
<feOffset dx="19" />
<feComposite in2="hardAlpha" operator="arithmetic" k2="-1" k3="1" />
<feColorMatrix
type="matrix"
values="0 0 0 0 0.980392 0 0 0 0 0.988235 0 0 0 0 1 0 0 0 1 0"
/>
<feBlend
mode="normal"
in2="effect1_innerShadow"
result="effect2_innerShadow"
/>
<feColorMatrix
in="SourceAlpha"
type="matrix"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
result="hardAlpha"
/>
<feOffset dx="-1" />
<feComposite in2="hardAlpha" operator="arithmetic" k2="-1" k3="1" />
<feColorMatrix
type="matrix"
values="0 0 0 0 0.839216 0 0 0 0 0.890196 0 0 0 0 0.941176 0 0 0 1 0"
/>
<feBlend
mode="normal"
in2="effect2_innerShadow"
result="effect3_innerShadow"
/>
</filter>
<filter
id="filter8_iii"
x="1"
y="334"
width="320"
height="111"
filterUnits="userSpaceOnUse"
colorInterpolationFilters="sRGB"
>
<feFlood floodOpacity="0" result="BackgroundImageFix" />
<feBlend
mode="normal"
in="SourceGraphic"
in2="BackgroundImageFix"
result="shape"
/>
<feColorMatrix
in="SourceAlpha"
type="matrix"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
result="hardAlpha"
/>
<feOffset dy="-1" />
<feComposite in2="hardAlpha" operator="arithmetic" k2="-1" k3="1" />
<feColorMatrix
type="matrix"
values="0 0 0 0 0.839216 0 0 0 0 0.890196 0 0 0 0 0.941176 0 0 0 1 0"
/>
<feBlend mode="normal" in2="shape" result="effect1_innerShadow" />
<feColorMatrix
in="SourceAlpha"
type="matrix"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
result="hardAlpha"
/>
<feOffset dx="19" />
<feComposite in2="hardAlpha" operator="arithmetic" k2="-1" k3="1" />
<feColorMatrix
type="matrix"
values="0 0 0 0 0.980392 0 0 0 0 0.988235 0 0 0 0 1 0 0 0 1 0"
/>
<feBlend
mode="normal"
in2="effect1_innerShadow"
result="effect2_innerShadow"
/>
<feColorMatrix
in="SourceAlpha"
type="matrix"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
result="hardAlpha"
/>
<feOffset dx="-1" />
<feComposite in2="hardAlpha" operator="arithmetic" k2="-1" k3="1" />
<feColorMatrix
type="matrix"
values="0 0 0 0 0.839216 0 0 0 0 0.890196 0 0 0 0 0.941176 0 0 0 1 0"
/>
<feBlend
mode="normal"
in2="effect2_innerShadow"
result="effect3_innerShadow"
/>
</filter>
<filter
id="filter9_ii"
x="1"
y="445"
width="320"
height="111"
filterUnits="userSpaceOnUse"
colorInterpolationFilters="sRGB"
>
<feFlood floodOpacity="0" result="BackgroundImageFix" />
<feBlend
mode="normal"
in="SourceGraphic"
in2="BackgroundImageFix"
result="shape"
/>
<feColorMatrix
in="SourceAlpha"
type="matrix"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
result="hardAlpha"
/>
<feOffset dx="19" />
<feComposite in2="hardAlpha" operator="arithmetic" k2="-1" k3="1" />
<feColorMatrix
type="matrix"
values="0 0 0 0 0.980392 0 0 0 0 0.988235 0 0 0 0 1 0 0 0 1 0"
/>
<feBlend mode="normal" in2="shape" result="effect1_innerShadow" />
<feColorMatrix
in="SourceAlpha"
type="matrix"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
result="hardAlpha"
/>
<feOffset dx="-1" />
<feComposite in2="hardAlpha" operator="arithmetic" k2="-1" k3="1" />
<feColorMatrix
type="matrix"
values="0 0 0 0 0.839216 0 0 0 0 0.890196 0 0 0 0 0.941176 0 0 0 1 0"
/>
<feBlend
mode="normal"
in2="effect1_innerShadow"
result="effect2_innerShadow"
/>
</filter>
</defs>
</SVG>
);
export default DesktopWallet;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Masks/desktopWalletHeader.jsx
import React from "react";
import styled, { keyframes } from "styled-components";
import color from "../ColorPalette";
const pulseAnimation = keyframes`
0% {
fill: ${color("grey", "100")};
}
50% {
fill: ${color("grey", "000")};
}
100% {
fill: ${color("grey", "100")};
}
`;
const SVG = styled.svg`
display: block;
margin: auto;
rect.pulse {
animation: ${pulseAnimation} 1.25s infinite;
}
`;
const DesktopWalletHeader = () => (
<SVG
width="1440"
height="104"
viewBox="0 0 1440 104"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<g filter="url(#filter0_dd)">
<path d="M0 2H1440V106H0V2Z" fill="white" />
</g>
<rect
x="109"
y="24"
width="180"
height="16"
fill="#E9EFF5"
className="pulse"
/>
<rect
x="109"
y="68"
width="294"
height="16"
fill="#E9EFF5"
className="pulse"
/>
<defs>
<filter
id="filter0_dd"
x="-4"
y="0"
width="1448"
height="112"
filterUnits="userSpaceOnUse"
colorInterpolationFilters="sRGB"
>
<feFlood floodOpacity="0" result="BackgroundImageFix" />
<feColorMatrix
in="SourceAlpha"
type="matrix"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
result="hardAlpha"
/>
<feOffset dy="1" />
<feGaussianBlur stdDeviation="1" />
<feColorMatrix
type="matrix"
values="0 0 0 0 0.0666667 0 0 0 0 0.168627 0 0 0 0 0.266667 0 0 0 0.08 0"
/>
<feBlend
mode="normal"
in2="BackgroundImageFix"
result="effect1_dropShadow"
/>
<feColorMatrix
in="SourceAlpha"
type="matrix"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
result="hardAlpha"
/>
<feOffset dy="2" />
<feGaussianBlur stdDeviation="2" />
<feColorMatrix
type="matrix"
values="0 0 0 0 0.0666667 0 0 0 0 0.168627 0 0 0 0 0.266667 0 0 0 0.06 0"
/>
<feBlend
mode="normal"
in2="effect1_dropShadow"
result="effect2_dropShadow"
/>
<feBlend
mode="normal"
in="SourceGraphic"
in2="effect2_dropShadow"
result="shape"
/>
</filter>
</defs>
</SVG>
);
export default DesktopWalletHeader;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Masks/trackPageContent.jsx
import React from "react";
import styled, { keyframes } from "styled-components";
import { buildColor } from "@tvg/design-system";
const pulseAnimation = keyframes`
0% {
fill: ${buildColor("blue", "000")};
}
50% {
fill: ${buildColor("blue", "100")};
}
100% {
fill: ${buildColor("blue", "000")};
}
`;
const MaskContainer = styled.div`
padding: 8px 0;
`;
const CardContainer = styled.div`
background: ${buildColor("grey", "000")};
padding: 0 12px;
&:not(:last-child) {
margin-bottom: 8px;
}
`;
const SVG = styled.svg`
rect {
animation: ${pulseAnimation} 1.25s infinite;
}
`;
const TrackPageContentMask = () => {
const rectColor = buildColor("blue", "000");
return (
<MaskContainer data-qa-label="trackPageContentMask">
<CardContainer>
<SVG width="100%" height="236" fill={buildColor("grey", "000")}>
<rect y="40" width="248" height="16" rx="1" fill={rectColor} />
<rect y="104" width="100%" height="116" rx="1" fill={rectColor} />
<rect y="64" width="154" height="16" rx="1" fill={rectColor} />
<rect y="16" width="53" height="16" rx="1" fill={rectColor} />
</SVG>
</CardContainer>
</MaskContainer>
);
};
export default TrackPageContentMask;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_templates/MyBetsStandalone/styled-components.js
import styled, { css } from "styled-components";
import buildColor from "../../_static/ColorPalette";
import { fontNormal, fontMedium } from "../../_static/Typography";
import Icon from "../../_static/Icons";
export const Container = styled.section`
display: flex;
flex-direction: column;
flex: 1 0 auto;
background-color: ${buildColor("blue", "000")};
font-family: ${fontMedium};
`;
export const Content = styled.div`
display: flex;
flex-direction: column;
flex-grow: 1;
padding-bottom: calc(8px + constant(safe-area-inset-bottom));
padding-bottom: calc(8px + env(safe-area-inset-bottom));
${({ hasBets, isLoading }) =>
hasBets &&
!isLoading &&
css`
& > div {
margin-top: 8px;
}
`};
${({ hasBets, isLoading }) =>
!hasBets &&
!isLoading &&
css`
align-items: center;
justify-content: center;
`};
`;
export const EmptyCase = styled.div`
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
width: 100%;
padding: 12px;
& > span {
margin-top: 8px;
font-family: ${fontNormal};
line-height: 18px;
}
& > button {
margin-top: 16px;
}
`;
export const InfoIconCircle = styled.div`
background-color: ${buildColor("white", "100")};
height: 62px;
margin-bottom: 20px;
padding: 20px;
border-radius: 50%;
`;
export const InfoIcon = styled(Icon)`
background-color: ${buildColor("blue_accent", "200")};
border-radius: 50%;
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_templates/MyBetsStandalone/index.jsx
import React from "react";
import { noop } from "lodash";
import tvgConf from "@tvg/conf";
import buildColor from "../../_static/ColorPalette";
import { infoOutline } from "../../_static/Icons/icons";
import Button from "../../_atom/Buttons/button";
import { MyBetsStandaloneMask } from "../../_static/Masks/index";
import {
Container,
Content,
EmptyCase,
InfoIconCircle,
InfoIcon
} from "./styled-components";
export const renderEmptyList = ({
onReturnBetting,
emptyTitle,
emptyMessage
}) => {
return (
<EmptyCase data-qa-label="myBets-empty-case">
<InfoIconCircle>
<InfoIcon
icon={infoOutline}
size={22}
color={buildColor("blue_accent", "500")}
/>
</InfoIconCircle>
<span data-qa-label="myBets-empty-case-title">{emptyTitle}</span>
{emptyMessage && (
<span data-qa-label="myBets-empty-case-message">{emptyMessage}</span>
)}
{onReturnBetting && (
<Button
type="secondary"
size="huge"
isStretched
isUppercase={false}
isBold={false}
hasShadow
onClick={onReturnBetting}
qaLabel="myBets-empty-case-button"
>
Return to Betting
</Button>
)}
</EmptyCase>
);
};
const MyBetsStandaloneTemplate = (props) => {
const {
children,
selectedTab,
bets,
isLoading,
isFetchingPagination,
onReturnBetting,
emptyTitle,
emptyMessage,
containerRef
} = props;
const renderContent = () => {
if (isLoading) {
return <MyBetsStandaloneMask />;
}
if (bets.length <= 0) {
return renderEmptyList({
onReturnBetting,
emptyTitle,
emptyMessage
});
}
return children;
};
return (
<Container data-qa-label="myBets" isIos={tvgConf().product === "ios2"}>
<Content
hasBets={!!bets.length}
isLoading={isLoading}
selectedTab={selectedTab}
data-qa-label="myBets-content"
ref={containerRef}
>
{renderContent()}
{isFetchingPagination && <MyBetsStandaloneMask cardAmount={1} />}
</Content>
</Container>
);
};
MyBetsStandaloneTemplate.defaultProps = {
children: null,
tabs: [],
timeFrameTabs: [],
selectedTab: "ACTIVE",
bets: [],
isLoading: false,
onReturnBetting: noop,
emptyTitle: "Empty title",
emptyMessage: "Empty message"
};
export default MyBetsStandaloneTemplate;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_templates/MyBetsBodyDesktop/styled-components.ts
import styled, { css } from "styled-components";
import buildColor from "@tvg/atomic-ui/_static/ColorPalette";
import { fontMedium } from "@tvg/atomic-ui/_static/Typography";
export const Container = styled.section<{
hasBets: boolean;
isLoading: boolean;
isSettledTab?: boolean;
isTablet?: boolean;
}>`
position: relative;
font-family: ${fontMedium};
background-color: ${buildColor("blue", "000")};
table th {
top: ${(props) =>
props.isSettledTab
? "calc(var(--header-height, -8px) + 164px)"
: "calc(var(--header-height, -8px) + 108px)"};
}
${(props) =>
(props.hasBets || props.isLoading) &&
css`
min-height: ${props.isSettledTab ? "55vh" : "61vh"};
padding: 12px 24px;
display: flex;
flex-direction: column;
`};
${(props) =>
!props.hasBets &&
!props.isLoading &&
css`
display: flex;
align-items: flex-start;
min-height: ${props.isSettledTab ? "55vh" : "61vh"};
> div {
position: absolute;
top: 60px;
}
`};
${(props) => css`
@media (min-height: 1000px) {
min-height: ${props.isSettledTab ? "65vh" : "70vh"};
}
`}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_templates/MyBetsBodyDesktop/index.tsx
import React from "react";
import Table from "@tvg/atomic-ui/_molecule/Table";
import { MyBetsDesktopMask } from "@tvg/atomic-ui/_static/Masks";
import { renderEmptyList } from "@tvg/atomic-ui/_templates/MyBetsStandalone";
import { Container } from "./styled-components";
import type { Props } from "./types";
const theadData = [
{ title: "Status", size: "85px" },
{ title: "Race Details", size: "215px" },
{ title: "Bet Details", size: "175px" },
{ title: "Selections", size: "311px" },
{ title: "" }
];
const MyBetsBodyDesktopTemplate = ({
isLoading,
bets,
emptyTitle,
emptyMessage,
children,
isFetchingPagination,
selectedTab,
scrollYPosition,
containerRef
}: Props) => {
const renderContent = () => {
if (isLoading) {
return (
<>
<Table theadData={theadData} />
<MyBetsDesktopMask />
</>
);
}
if (bets.length === 0) {
return renderEmptyList({
emptyTitle,
emptyMessage,
onReturnBetting: null
});
}
return (
<>
<Table
theadData={theadData}
headerShadow={scrollYPosition > 0}
headerSticky
>
{children}
</Table>
{isFetchingPagination && <MyBetsDesktopMask rowsAmount={2} />}
</>
);
};
return (
<Container
ref={containerRef}
hasBets={!!bets.length}
isLoading={isLoading}
isSettledTab={selectedTab === "SETTLED"}
data-qa-label="myBets"
>
{renderContent()}
</Container>
);
};
export default MyBetsBodyDesktopTemplate;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_templates/TrackRulesModal/styled-components.js
import styled from "styled-components";
import buildColor from "../../_static/ColorPalette";
import { fontNormal } from "../../_static/Typography";
export const Container = styled.div`
background-color: ${buildColor("white", "100")};
padding: 16px 12px;
`;
export const Text = styled.p`
font-size: 14px;
line-height: 18px;
color: ${buildColor("grey", "800")};
font-family: ${fontNormal};
&:not(:last-child) {
margin-bottom: 18px;
}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_templates/TrackRulesModal/index.jsx
import React from "react";
import ModalV2 from "@tvg/atomic-ui/_templates/ModalV2";
import tvgConf from "@tvg/conf";
import { Container, Text } from "./styled-components";
const TrackRulesModal = (props) => {
const { isOpen, onClose, subtitle, messages, layerOffset = 1 } = props;
const { device } = tvgConf();
const baseModalProps = {
title: "Scratch Rules",
subtitle,
titleType: "ipp",
isOpen,
onClose,
qaLabel: "track-rules",
hasShadow: true,
hasOverlay: true,
isFullWidth: false,
isContentTransparent: false,
isFullHeight: false,
layerOffset
};
const modalProps =
device === "mobile"
? {
...baseModalProps,
animation: "bottomFloating",
offsetTop: 200,
offsetBottom: 200,
offsetLeft: 8,
offsetRight: 8
}
: {
...baseModalProps,
animation: "fade",
offsetTop: 40,
offsetBottom: 0,
offsetLeft: 40,
offsetRight: 40
};
return (
<ModalV2 {...modalProps} hasBiggerHeader>
{() => (
<Container>
{messages.map((message) => (
<Text key={message.toString()}>{message}</Text>
))}
</Container>
)}
</ModalV2>
);
};
export default TrackRulesModal;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/utils/track.ts
import { get } from "lodash";
export const getTrackRulesMessage = (
messages: string,
betType: string,
isMultiRace: boolean,
isAlternates: boolean = false
) => {
const jsonMessages = JSON.parse(messages || "{}");
let subtitle = "";
const message = [];
if (isMultiRace) {
switch (betType) {
case "P3":
subtitle = get(jsonMessages, "P3.title", "");
get(jsonMessages, "P3.text", "")
.split("\n")
.forEach((textLine: string) => message.push(textLine.trim()));
break;
case "DB":
subtitle = get(jsonMessages, "DB.title", "");
message.push(get(jsonMessages, "DB.text", "").trim());
break;
default:
subtitle = get(jsonMessages, "P4.title", "");
message.push(
get(
jsonMessages,
isAlternates ? "P4.textAlternates" : "P4.text",
""
).trim()
);
}
} else {
subtitle = get(jsonMessages, "default.title", "");
message.push(get(jsonMessages, "default.text", "").trim());
}
return {
subtitle,
message
};
};
webpack://frontend-mybets/../../packages/tvg-comp-desktop-bet-ticket/src/store/selectors.ts
import { get } from "lodash";
import { BetGroupStatus } from "../types";
import { State } from "./reducers";
export const getBetSelections = (store: State) =>
get(store, "BetTicket.betSelections", []);
export const getScratchedSelections = (store: State) =>
get(store, "BetTicket.scratchedSelections");
export const getStartBetting = (store: State) =>
get(store, "BetTicket.startBetting");
export const getBetState = (store: State) => get(store, "BetTicket.betState");
export const getBetAmount = (store: State) => get(store, "BetTicket.betAmount");
export const getBetType = (store: State) => get(store, "BetTicket.betType");
export const getBetLeg = (store: State) => get(store, "BetTicket.betLeg");
export const getAllowAlternateSelection = (store: State) =>
get(store, "BetTicket.allowAlternateSelection");
export const getRaceOfBet = (store: State) => get(store, "BetTicket.raceOfBet");
export const getBetInfo = (store: State) => get(store, "BetTicket");
export const getTalentPick = (store: State) =>
get(store, "BetTicket.talentPick");
export const getBetGroupStatus = (store: State): BetGroupStatus =>
get(store, "BetTicket.betGroupStatus", {});
export const getProcessingBets = (store: State) =>
get(store, "BetTicket.processingBets", 0);
export const getSuccessBets = (store: State) =>
get(store, "BetTicket.successBets", 0);
export const getErrorBets = (store: State) =>
get(store, "BetTicket.errorBets", 0);
export const getHasUserSetAmount = (store: State) =>
get(store, "BetTicket.hasUserSetAmount");
export const getAddToBetSlipOrigin = (store: State) =>
get(store, "BetTicket.addToBetSlipOrigin");
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/LoadingSpinner/styled-components.ts
import styled, { keyframes } from "styled-components";
import { space } from "styled-system";
const PathAnimationOne = keyframes`
0% {
stroke-dashoffset: 67.69px;
}
41.3793% {
stroke-dashoffset: 68.69px;
animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1);
}
100% {
stroke-dashoffset: -69.69px;
}
`;
const PathAnimationTwo = keyframes`
0% {
stroke-dashoffset: 68.69px;
animation-timing-function: cubic-bezier(0.42, 0, 1, 1);
}
58.6207% {
stroke-dashoffset: -68.69px;
}
100% {
stroke-dashoffset: -68.69px;
}
`;
export const Svg = styled.svg`
${space}
`;
export const AnimatedCircleOne = styled.ellipse`
animation: ${PathAnimationOne} 2.9s linear infinite both;
`;
export const AnimatedCircleTwo = styled.ellipse`
animation: ${PathAnimationTwo} 2.9s linear infinite both;
`;
export const Circle = styled.ellipse``;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/LoadingSpinner/index.tsx
import React, { FC } from "react";
import { useColorTokens } from "@tvg/design-system/web/hooks";
import type { IconSizeVariants } from "../../theme";
import { useTheme } from "../../hooks";
import {
Svg,
AnimatedCircleOne,
AnimatedCircleTwo,
Circle
} from "./styled-components";
import type { LoadingSpinnerProps } from "./types";
export const LoadingSpinner: FC<LoadingSpinnerProps> = ({
size = "s",
color = "--fd-colors-component-button-tertiary-content-active",
bgColor = "--fd-colors-core-white-tint-020",
qaLabel = "loading-spinner",
...rest
}) => {
const { iconSizes } = useTheme();
const { iconSize, strokeWidth } = iconSizes[size as IconSizeVariants];
const filterColor = (receivedColor: string | undefined) =>
receivedColor && (receivedColor.includes("#") || color.includes("rgba"))
? receivedColor
: useColorTokens(receivedColor);
const filteredColor = color.startsWith("--")
? `var(${color})`
: filterColor(color);
const filterBgColor = bgColor.startsWith("--")
? `var(${bgColor})`
: filterColor(bgColor);
return (
<Svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
width={iconSize}
height={iconSize}
data-qa-label={qaLabel}
{...rest}
>
<Circle
rx="11"
ry="11"
fill="none"
stroke={filterBgColor}
strokeWidth={strokeWidth}
strokeDashoffset="0"
strokeLinecap="round"
transform="translate(12,12)"
/>
<AnimatedCircleOne
rx="11"
ry="11"
fill="none"
stroke={filteredColor}
strokeWidth={strokeWidth}
strokeDashoffset="67.69"
strokeDasharray="68.69"
strokeLinecap="round"
transform="translate(8,8) rotate(-90) translate(-4,4)"
/>
<AnimatedCircleTwo
rx="11"
ry="11"
fill="none"
stroke={filteredColor}
strokeWidth={strokeWidth}
strokeDashoffset="68.69"
strokeDasharray="68.69"
strokeLinecap="round"
transform="translate(8,8) rotate(-90) translate(-4,4)"
/>
</Svg>
);
};
export type { LoadingSpinnerProps };
webpack://frontend-mybets/../../packages/urp-lib-unified-modules/src/redux/selector/account/index.ts
import type { Store } from "redux";
import { get } from "lodash";
const reducerRootSelector = "unifiedModules.Account";
export const getAccountModalOpened = (store: Store) =>
get(store, `${reducerRootSelector}.isOpened`, false);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/PageHeader/components/styled-components.ts
import styled from "styled-components"; export const Button = styled.button` background-color: transparent; border: none; cursor: pointer; height: 20px; margin: 0; padding: 0; width: 20px; `;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/PageHeader/components/BackButton/index.tsx
import React from "react";
import { Icon } from "../../../Icon";
import { Button } from "../styled-components";
import type { BackButtonProps } from "./types";
export const BackButton = ({ onBack, ...rest }: BackButtonProps) => (
<Button onClick={onBack} {...rest}>
<Icon size="m" lineColor="--fd-colors-content-default" name="arrowLeft" />
</Button>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/PageHeader/components/CloseButton/index.tsx
import React from "react";
import { Icon } from "../../../Icon";
import { Button } from "../styled-components";
import type { CloseButtonProps } from "./types";
export const CloseButton = ({ onClose, ...rest }: CloseButtonProps) => (
<Button onClick={onClose} {...rest}>
<Icon size="m" lineColor="--fd-colors-content-default" name="close" />
</Button>
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/PageHeader/styled-components.ts
import styled from "styled-components";
import { space } from "styled-system";
import type { PageHeaderSize } from "./types";
const paddingMap = {
small: "12px",
medium: "20px 16px"
};
export const HeaderContainer = styled.div<{ size: PageHeaderSize }>`
background-color: var(--fd-colors-background-surface);
border-bottom: 1px solid var(--fd-colors-border-subtle);
border-radius: 4px 4px 0 0;
display: flex;
flex-direction: row;
gap: 16px;
height: max-content;
justify-content: space-between;
padding: ${({ size }) => paddingMap[size as PageHeaderSize]};
${space}
`;
export const HeaderSection = styled.div`
align-items: center;
display: flex;
flex-direction: column;
gap: 4px;
justify-content: flex-start;
width: 80%;
`;
export const Wrapper = styled.div`
width: 100%;
display: flex;
flex-direction: row;
justify-content: center;
height: max-content;
align-items: center;
gap: 8px;
`;
export const ActionContainer = styled.div`
width: 20px;
height: 20px;
min-width: 20px;
max-height: 20px;
`;
export const LinkWrapper = styled.div`
display: flex;
flex-direction: row;
gap: 4px;
justify-content: center;
width: max-content;
`;
export const Link = styled.a`
color: var(--fd-colors-link-default-base);
cursor: pointer;
font-family: "Roboto-Regular", sans-serif;
font-size: 14px;
font-style: normal;
font-weight: 400;
line-height: 125%;
text-align: center;
text-decoration: none;
&:hover {
color: var(--fd-colors-link-default-hover);
}
&:active {
color: var(--fd-colors-link-default-hover);
}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/PageHeader/index.tsx
import React, { type FC } from "react";
import { Header, Paragraph } from "../Typography";
import { Icon } from "../Icon";
import { BackButton } from "./components/BackButton";
import { CloseButton } from "./components/CloseButton";
import {
HeaderContainer,
HeaderSection,
ActionContainer,
Wrapper,
LinkWrapper,
Link
} from "./styled-components";
import type { PageHeaderProps, PageHeaderSize } from "./types";
export const PageHeader: FC<PageHeaderProps> = ({
title,
description,
showBackButton = false,
showCloseButton = false,
onBack,
onClose,
linkLabel = "Link",
linkUrl,
showLink = false,
qaLabel = "page-header",
saddle,
size = "medium",
...rest
}) => (
<HeaderContainer data-qa-label={qaLabel} size={size} {...rest}>
<ActionContainer>
{showBackButton && (
<BackButton data-qa-label={`${qaLabel}-back-button`} onBack={onBack} />
)}
</ActionContainer>
<HeaderSection>
<Wrapper>
{saddle}
<Header
p={0}
m={0}
tag="h3"
color="--fd-colors-content-strong"
fontSize={18}
textAlign="center"
width="max-content"
data-qa-label={`${qaLabel}-title`}
>
{title}
</Header>
</Wrapper>
{description && !showLink && (
<Paragraph
p={0}
m={0}
fontFamily="regular"
color="--fd-colors-content-subtle"
fontSize={14}
lineHeight="125%"
textAlign="center"
width="max-content"
data-qa-label={`${qaLabel}-description`}
>
{description}
</Paragraph>
)}
{showLink && (
<LinkWrapper>
<Icon
size="s"
lineColor="--fd-colors-system-info-content-accent"
backgroundColor="--fd-colors-system-info-background-subtle"
name="info"
data-qa-label={`${qaLabel}-icon-info`}
/>
<Link href={linkUrl} data-qa-label={`${qaLabel}-link`}>
{linkLabel}
</Link>
</LinkWrapper>
)}
</HeaderSection>
<ActionContainer>
{showCloseButton && (
<CloseButton
data-qa-label={`${qaLabel}-close-button`}
onClose={onClose}
/>
)}
</ActionContainer>
</HeaderContainer>
);
export type { PageHeaderProps, PageHeaderSize };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Modal/styled-components.ts
import styled, { css, keyframes } from "styled-components";
import { compose, space } from "styled-system";
import breakpoints from "../../../src/utils/breakpoints";
export const TOP_TRESHOLD = 40;
export const ANIMATION_DURATION = 400;
export const fadeIn = keyframes`
from { opacity: 0.5; }
to { opacity: 1; }
`;
const fadeOut = keyframes`
from {
opacity: 0.8;
}
to {
opacity: 0;
}
`;
const scaleUp = keyframes`
from {
transform: translate(-50%, 50%) scale(0.5);
opacity: 0.5;
}
to {
transform: translate(-50%, -50%) scale(1);
opacity: 1;
}
`;
const slideUp = keyframes`
from {
transform: translateY(100%);
opacity: 0.5;
}
to {
transform: translateY(0);
opacity: 1;
}
`;
const slideDown = keyframes`
from {
transform: translateY(0);
opacity: 1;
}
to {
transform: translateY(100%);
opacity: 0.5;
}
`;
const scaleDown = keyframes`
from {
transform: translate(-50%, -50%) scale(1);
opacity: 1;
}
to {
transform: translate(-50%, 50%) scale(0.5);
opacity: 0;
}
`;
const slideLeft = keyframes`
from { transform: translateX(-70%); }
to { transform: translateX(0); }
`;
const slideRight = keyframes`
from { transform: translateX(70%); }
to { transform: translateX(0); }
`;
const styles = compose(space);
export const Backdrop = styled.div`
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 999;
&[data-hide-overlay="true"] {
background: inherit;
}
&[data-hide-overlay="false"] {
background: var(--fd-colors-core-black-tint-070);
}
&[data-closing="true"] {
${css`
animation: ${fadeOut} ${ANIMATION_DURATION}ms ease-out;
`};
opacity: 0;
pointer-events: none;
}
&[data-closing="false"] {
${css`
animation: ${fadeIn} ${ANIMATION_DURATION}ms ease-out;
`};
opacity: 1;
pointer-events: auto;
}
`;
export const ModalContainer = styled.div<{
maxHeight?: string;
hasMaxHeight?: boolean;
maxWidth?: string;
overrideInset?: number;
}>`
box-sizing: border-box;
display: flex;
flex-direction: column;
justify-content: center;
position: fixed;
background: var(--fd-colors-background-surface);
z-index: 999;
overflow: hidden;
@media screen and ${breakpoints.tablet.min.sm} {
height: ${({ hasMaxHeight, maxHeight }) =>
hasMaxHeight ? `${maxHeight} || 98vh` : "auto"};
max-height: ${({ maxHeight }) => maxHeight || "98vh"};
max-width: ${({ maxWidth }) => maxWidth || "375px"};
width: 90%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
transform-origin: center;
border-radius: 4px;
box-shadow: var(--fd-shadows-elevations-all-around-high);
&[data-closing="true"] {
${css`
animation: ${scaleDown} ${ANIMATION_DURATION}ms
cubic-bezier(0.25, 1, 0.5, 1);
`};
}
&[data-closing="false"] {
${css`
animation: ${scaleUp} ${ANIMATION_DURATION}ms
cubic-bezier(0.25, 1, 0.5, 1);
`};
}
}
@media screen and ${breakpoints.tablet.max.sm} {
bottom: 0;
left: 0;
width: 100%;
border-radius: 8px 8px 0 0;
box-shadow: var(--fd-shadows-elevations-top-low);
&[data-closing="true"] {
${css`
animation: ${slideDown} ${ANIMATION_DURATION}ms
cubic-bezier(0.25, 1, 0.5, 1);
`};
}
&[data-closing="false"] {
${css`
animation: ${slideUp} ${ANIMATION_DURATION}ms
cubic-bezier(0.25, 1, 0.5, 1);
`};
}
${({ hasMaxHeight, overrideInset, maxHeight }) =>
hasMaxHeight
? css`
height: calc(
${maxHeight || "100vh"} -
${overrideInset !== undefined ? overrideInset : TOP_TRESHOLD}px
);
${overrideInset === 0 && "border-radius: 0;"}
`
: css`
height: auto;
max-height: calc(
${maxHeight || "100vh"} -
${overrideInset !== undefined ? overrideInset : TOP_TRESHOLD}px
);
`}
}
`;
export const ModalHeader = styled.div`
font-size: 1.25rem;
font-weight: bold;
margin-bottom: 16px;
`;
export const ModalContent = styled.div<{
hasMaxHeight?: boolean;
hasPadding?: boolean;
}>`
display: flex;
flex-direction: column;
width: -webkit-fill-available;
@-moz-document url-prefix() {
width: 100%;
}
${({ hasPadding }) =>
hasPadding
? css`
padding: 12px;
`
: css`
padding: 0;
`}
${({ hasMaxHeight }) =>
hasMaxHeight
? css`
height: 100%;
flex: 1;
`
: css`
height: auto;
`}
${styles}
`;
export const ModalFooter = styled.div`
bottom: 0;
left: 0;
display: flex;
flex-direction: column;
justify-content: center;
background: var(--fd-colors-background-surface);
padding: 0 12px 12px;
@media screen and ${breakpoints.tablet.max.sm} {
position: sticky;
}
`;
export const TopStickyArea = styled.div`
position: sticky;
top: 0;
z-index: 999;
width: 100%;
`;
export const ModalHeaderContainer = styled.div`
width: 100%;
overflow: hidden;
display: flex;
`;
export const PagesSlider = styled.div`
padding: 12px;
height: 100%;
overflow: hidden;
${styles}
&[data-slide="right"] {
${css`
animation: ${slideRight} ${ANIMATION_DURATION}ms forwards;
`};
}
&[data-slide="left"] {
${css`
animation: ${slideLeft} ${ANIMATION_DURATION}ms forwards;
`};
}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Scroll/styled-components.ts
import styled, { css } from "styled-components";
import {
layout,
space,
color,
margin,
padding,
width,
maxWidth,
height,
maxHeight
} from "styled-system";
import type { BorderToShow } from "./types";
const createBorder = (bordersToShow: BorderToShow) =>
Object.entries(bordersToShow).map(([key, value]) => {
if (value) {
return css`border-${key}: 1px solid var(--fd-colors-border-subtle);`;
}
return "";
});
export const ShadowWrapper = styled.div`
overflow: hidden;
&:not([data-scroll-position="top"])[data-hide-shadow="false"]::before {
content: "";
box-shadow: inset 3px 3px 3px rgba(17, 43, 68, 0.25);
display: flex;
height: 16px;
left: -6px;
pointer-events: none;
position: relative;
margin-bottom: -16px;
width: calc(100% - 10px);
z-index: 1000;
}
&:not([data-scroll-position="bottom"])[data-hide-shadow="false"]::after {
content: "";
box-shadow: inset 3px -3px 3px rgba(17, 43, 68, 0.25);
display: flex;
height: 16px;
left: -6px;
margin-top: -16px;
pointer-events: none;
width: calc(100% - 10px);
z-index: 1000;
position: relative;
}
${width}
${maxWidth}
${height}
${maxHeight}
${margin}
`;
export const ScrollContainer = styled.div<{
hasShadow: boolean;
borderToShow: BorderToShow;
}>`
overflow: auto;
overscroll-behavior: contain;
&::-webkit-scrollbar {
width: 16px;
${({ borderToShow }) => createBorder(borderToShow)}
}
&::-webkit-scrollbar-track {
background: transparent;
overflow: auto;
}
&::-webkit-scrollbar-thumb {
background: var(--fd-colors-component-data-input-icon-base);
border-radius: 16px;
border: 4px solid transparent;
background-clip: padding-box;
}
&::-webkit-scrollbar-thumb:hover {
background: var(--fd-colors-component-data-input-content-base);
border-radius: 16px;
border: 4px solid transparent;
background-clip: padding-box;
}
${color}
${({ hasShadow }) => (hasShadow ? padding : space)}
${layout}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Scroll/index.tsx
import React, {
useRef,
useLayoutEffect,
useState,
type FC,
useEffect,
Ref
} from "react";
import { ScrollContainer, ShadowWrapper } from "./styled-components";
import type { ScrollProps, BorderToShow } from "./types";
export const Scroll: FC<ScrollProps> = ({
children,
isDark = false,
qaLabel = "scroll",
showBorderTop = false,
showBorderRight = false,
showBorderBottom = false,
showBorderLeft = false,
hasShadow = false,
component = "div",
...props
}) => {
const [scrollPosition, setScrollPosition] = useState("top");
const [hideShadow, setHideShadow] = useState(false);
const scrollRef = useRef<HTMLDivElement>(null);
const borderToShow: BorderToShow = {
top: showBorderTop,
right: showBorderRight,
bottom: showBorderBottom,
left: showBorderLeft
};
useLayoutEffect(() => {
if (hasShadow && scrollRef.current) {
setHideShadow(
scrollRef.current?.clientHeight === scrollRef.current?.scrollHeight
);
scrollRef.current?.addEventListener("scroll", handleScroll);
return () => {
scrollRef.current?.removeEventListener("scroll", handleScroll);
};
}
return () => scrollRef.current?.removeEventListener("scroll", handleScroll);
}, [scrollRef, hasShadow]);
const handleScroll = () => {
if (scrollRef.current) {
if (props.onImperativeScroll) {
props.onImperativeScroll(
scrollRef.current as unknown as Ref<HTMLDivElement | null>
);
}
if (scrollRef.current?.scrollTop === 0) {
return setScrollPosition("top");
}
const differenceScroll =
scrollRef.current?.scrollTop +
scrollRef.current?.clientHeight -
scrollRef.current?.scrollHeight;
if (differenceScroll > -3 && differenceScroll < 3) {
return setScrollPosition("bottom");
}
return scrollPosition !== "middle" && setScrollPosition("middle");
}
return null;
};
useEffect(() => {
if (props.onRender && scrollRef) {
props.onRender(scrollRef);
}
}, [props?.onRender, scrollRef]);
return hasShadow ? (
<ShadowWrapper
data-scroll-position={scrollPosition}
data-hide-shadow={hideShadow}
data-qa-label={`${qaLabel}-shadow`}
{...props}
>
<ScrollContainer
ref={scrollRef}
data-mode={isDark ? "dark" : "light"}
data-qa-label={qaLabel}
borderToShow={borderToShow}
hasShadow={hasShadow}
as={component}
{...props}
>
{children}
</ScrollContainer>
</ShadowWrapper>
) : (
<ScrollContainer
ref={scrollRef}
data-mode={isDark ? "dark" : "light"}
data-qa-label={qaLabel}
borderToShow={borderToShow}
hasShadow={hasShadow}
as={component}
{...props}
>
{children}
</ScrollContainer>
);
};
export type { ScrollProps };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Modal/index.tsx
import React, { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { v4 as uuid } from "uuid";
import { useSelector } from "react-redux";
import { getAccountModalOpened } from "@urp/unified-modules/src/redux/selector/account";
import { PageHeader } from "../PageHeader";
import { AlertInLine } from "../AlertInLine";
import {
Backdrop,
ANIMATION_DURATION,
ModalContainer,
ModalContent,
ModalFooter,
TopStickyArea,
ModalHeaderContainer,
PagesSlider
} from "./styled-components";
import type { ModalProps } from "./types";
import { Scroll } from "../Scroll";
export const Modal = ({
isOpen,
headerProps,
customHeader,
alertProps = [],
onClose,
hasMaxHeight = false,
maxHeight,
hasPadding = true,
footerContent,
stickyAreaExtraContent,
onAfterClose,
qaLabel,
hideOverlayColor = false,
maxWidth,
hasPages = false,
hideHeader = false,
page,
overrideInset = undefined,
onOpen,
mode = "light",
children,
disableExitAnimation = false,
onScroll,
onRender,
disableBodyScroll = false,
...rest
}: ModalProps) => {
const portalRef = useRef<HTMLDivElement | null>(null);
const isAccountModalOpened = useSelector(getAccountModalOpened);
const stickyAreaRef = useRef<HTMLDivElement>(null);
const [isClosing, setIsClosing] = useState(false);
const [visible, setVisible] = useState(isOpen);
const [slideDirection, setSlideDirection] = useState<
"left" | "right" | "none"
>("none");
const prevPage = useRef<number | undefined>(undefined);
useEffect(() => {
let timer = 0;
if (isOpen) {
const portalElement = document.createElement("div");
const modalWrapper = document.getElementById("modals");
portalElement.id = `portal-${qaLabel || uuid()}`;
if (modalWrapper) {
modalWrapper.appendChild(portalElement);
} else {
document.body.appendChild(portalElement);
}
portalRef.current = portalElement;
document.body.style.overflow = "hidden";
if (onOpen) {
onOpen();
}
setIsClosing(false);
setVisible(true);
} else if (!disableExitAnimation && !isOpen && portalRef.current) {
setIsClosing(true);
document.body.style.overflow = "auto";
timer = setTimeout(() => {
setVisible(false);
setIsClosing(false);
if (portalRef.current) {
if (onAfterClose) onAfterClose();
document.getElementById(`portal-${qaLabel}`)?.remove();
portalRef.current.remove();
portalRef.current = null;
}
}, ANIMATION_DURATION - 20);
} else if (!isOpen && portalRef.current) {
setVisible(false);
document.body.style.overflow = "auto";
if (portalRef.current) {
if (onAfterClose) onAfterClose();
document.getElementById(`portal-${qaLabel}`)?.remove();
portalRef.current.remove();
portalRef.current = null;
}
}
return () => {
if (document.body) {
document.body.style.overflow = "auto";
}
return clearTimeout(timer);
};
}, [isOpen]);
useEffect(() => {
if (page !== undefined) {
if (prevPage.current !== page) {
if (prevPage.current !== undefined) {
setSlideDirection(prevPage.current > page ? "left" : "right");
setTimeout(() => {
setSlideDirection("none");
}, ANIMATION_DURATION + 10);
}
prevPage.current = page;
}
}
}, [page]);
useEffect(() => {
const portal = document.getElementById(`portal-${qaLabel}`);
if (portal) {
if (isAccountModalOpened) {
portal.style.visibility = "hidden";
}
if (!isAccountModalOpened) {
portal.style.visibility = "visible";
}
}
}, [isAccountModalOpened]);
if (!visible) return null;
const modalContent = (
<>
<Backdrop
onClick={onClose}
data-closing={isClosing}
data-hide-overlay={hideOverlayColor}
id={`backdrop-${qaLabel}`}
/>
<ModalContainer
id={qaLabel}
data-qa-label={qaLabel}
maxHeight={maxHeight}
maxWidth={maxWidth}
data-closing={isClosing}
hasMaxHeight={hasMaxHeight}
overrideInset={overrideInset}
>
{headerProps && !hideHeader ? (
<PageHeader {...headerProps} onClose={onClose} />
) : null}
{customHeader ? (
<ModalHeaderContainer data-qa-label="modalHeader">
{customHeader}
</ModalHeaderContainer>
) : null}
<TopStickyArea ref={stickyAreaRef}>
{alertProps?.length
? alertProps.map((props) => (
<AlertInLine
{...props}
onDismissPress={(e) => {
if (props.onDismissPress) {
props.onDismissPress(e);
}
}}
/>
))
: null}
{stickyAreaExtraContent}
</TopStickyArea>
{disableBodyScroll ? (
children
) : (
<Scroll
overflowY="auto"
overflowX={hasPages ? "hidden" : "auto"}
hasShadow
height="100%"
maxHeight={`calc(${(maxHeight && "100%") || "100vh"} - ${hideHeader || maxHeight ? "0" : "120px"})`}
isDark={mode === "dark"}
width="100%"
onImperativeScroll={onScroll}
onRender={onRender}
>
<ModalContent
padding={hasPages && 0}
hasMaxHeight={hasMaxHeight}
hasPadding={hasPadding}
{...rest}
>
{hasPages ? (
<PagesSlider data-slide={slideDirection}>
{children}
</PagesSlider>
) : (
children
)}
</ModalContent>
</Scroll>
)}
{footerContent && <ModalFooter>{footerContent}</ModalFooter>}
</ModalContainer>
</>
);
if (
typeof process !== "undefined" &&
process?.env?.JEST_WORKER_ID !== undefined
)
return modalContent;
if (portalRef.current) {
return createPortal(modalContent, portalRef.current);
}
return null;
};
export type { ModalProps };
webpack://frontend-mybets/../../node_modules/date-fns/esm/startOfDay/index.js
import toDate from '../toDate/index.js';
import requiredArgs from '../_lib/requiredArgs/index.js';
/**
* @name startOfDay
* @category Day Helpers
* @summary Return the start of a day for the given date.
*
* @description
* Return the start of a day for the given date.
* The result will be in the local timezone.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @returns {Date} the start of a day
* @throws {TypeError} 1 argument required
*
* @example
* // The start of a day for 2 September 2014 11:55:00:
* var result = startOfDay(new Date(2014, 8, 2, 11, 55, 0))
* //=> Tue Sep 02 2014 00:00:00
*/
export default function startOfDay(dirtyDate) {
requiredArgs(1, arguments);
var date = toDate(dirtyDate);
date.setHours(0, 0, 0, 0);
return date;
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/differenceInDays/index.js
import toDate from '../toDate/index.js';
import differenceInCalendarDays from '../differenceInCalendarDays/index.js';
import requiredArgs from '../_lib/requiredArgs/index.js'; // Like `compareAsc` but uses local time not UTC, which is needed
// for accurate equality comparisons of UTC timestamps that end up
// having the same representation in local time, e.g. one hour before
// DST ends vs. the instant that DST ends.
function compareLocalAsc(dateLeft, dateRight) {
var diff = dateLeft.getFullYear() - dateRight.getFullYear() || dateLeft.getMonth() - dateRight.getMonth() || dateLeft.getDate() - dateRight.getDate() || dateLeft.getHours() - dateRight.getHours() || dateLeft.getMinutes() - dateRight.getMinutes() || dateLeft.getSeconds() - dateRight.getSeconds() || dateLeft.getMilliseconds() - dateRight.getMilliseconds();
if (diff < 0) {
return -1;
} else if (diff > 0) {
return 1; // Return 0 if diff is 0; return NaN if diff is NaN
} else {
return diff;
}
}
/**
* @name differenceInDays
* @category Day Helpers
* @summary Get the number of full days between the given dates.
*
* @description
* Get the number of full day periods between two dates. Fractional days are
* truncated towards zero.
*
* One "full day" is the distance between a local time in one day to the same
* local time on the next or previous day. A full day can sometimes be less than
* or more than 24 hours if a daylight savings change happens between two dates.
*
* To ignore DST and only measure exact 24-hour periods, use this instead:
* `Math.floor(differenceInHours(dateLeft, dateRight)/24)|0`.
*
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the later date
* @param {Date|Number} dateRight - the earlier date
* @returns {Number} the number of full days according to the local timezone
* @throws {TypeError} 2 arguments required
*
* @example
* // How many full days are between
* // 2 July 2011 23:00:00 and 2 July 2012 00:00:00?
* var result = differenceInDays(
* new Date(2012, 6, 2, 0, 0),
* new Date(2011, 6, 2, 23, 0)
* )
* //=> 365
* // How many full days are between
* // 2 July 2011 23:59:00 and 3 July 2011 00:01:00?
* var result = differenceInDays(
* new Date(2011, 6, 3, 0, 1),
* new Date(2011, 6, 2, 23, 59)
* )
* //=> 0
* // How many full days are between
* // 1 March 2020 0:00 and 1 June 2020 0:00 ?
* // Note: because local time is used, the
* // result will always be 92 days, even in
* // time zones where DST starts and the
* // period has only 92*24-1 hours.
* var result = differenceInDays(
* new Date(2020, 5, 1),
* new Date(2020, 2, 1)
* )
//=> 92
*/
export default function differenceInDays(dirtyDateLeft, dirtyDateRight) {
requiredArgs(2, arguments);
var dateLeft = toDate(dirtyDateLeft);
var dateRight = toDate(dirtyDateRight);
var sign = compareLocalAsc(dateLeft, dateRight);
var difference = Math.abs(differenceInCalendarDays(dateLeft, dateRight));
dateLeft.setDate(dateLeft.getDate() - sign * difference); // Math.abs(diff in full days - diff in calendar days) === 1 if last calendar day is not full
// If so, result must be decreased by 1 in absolute value
var isLastDayNotFull = compareLocalAsc(dateLeft, dateRight) === -sign;
var result = sign * (difference - isLastDayNotFull); // Prevent negative zero
return result === 0 ? 0 : result;
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/differenceInCalendarDays/index.js
import getTimezoneOffsetInMilliseconds from '../_lib/getTimezoneOffsetInMilliseconds/index.js';
import startOfDay from '../startOfDay/index.js';
import requiredArgs from '../_lib/requiredArgs/index.js';
var MILLISECONDS_IN_DAY = 86400000;
/**
* @name differenceInCalendarDays
* @category Day Helpers
* @summary Get the number of calendar days between the given dates.
*
* @description
* Get the number of calendar days between the given dates. This means that the times are removed
* from the dates and then the difference in days is calculated.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the later date
* @param {Date|Number} dateRight - the earlier date
* @returns {Number} the number of calendar days
* @throws {TypeError} 2 arguments required
*
* @example
* // How many calendar days are between
* // 2 July 2011 23:00:00 and 2 July 2012 00:00:00?
* var result = differenceInCalendarDays(
* new Date(2012, 6, 2, 0, 0),
* new Date(2011, 6, 2, 23, 0)
* )
* //=> 366
* // How many calendar days are between
* // 2 July 2011 23:59:00 and 3 July 2011 00:01:00?
* var result = differenceInCalendarDays(
* new Date(2011, 6, 3, 0, 1),
* new Date(2011, 6, 2, 23, 59)
* )
* //=> 1
*/
export default function differenceInCalendarDays(dirtyDateLeft, dirtyDateRight) {
requiredArgs(2, arguments);
var startOfDayLeft = startOfDay(dirtyDateLeft);
var startOfDayRight = startOfDay(dirtyDateRight);
var timestampLeft = startOfDayLeft.getTime() - getTimezoneOffsetInMilliseconds(startOfDayLeft);
var timestampRight = startOfDayRight.getTime() - getTimezoneOffsetInMilliseconds(startOfDayRight); // Round the number of days to the nearest integer
// because the number of milliseconds in a day is not constant
// (e.g. it's different in the day of the daylight saving time clock shift)
return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_DAY);
}
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Mtp/constants.ts
import type { MtpTheme } from "./types";
export const sizeVariantStyles: MtpTheme = {
xs: {
mtpText: {
fontFamily: "medium",
fontSize: "14px",
fontWeight: "500",
lineHeight: "125%"
},
mtpExtraDates: {
fontFamily: "regular",
fontSize: "14px",
fontWeight: "400",
lineHeight: "125%"
}
},
s: {
mtpText: {
fontFamily: "medium",
fontSize: "18px",
fontWeight: "500",
lineHeight: "125%"
},
mtpExtraDates: {
fontFamily: "condensedRegular",
fontSize: "14px",
fontWeight: "400",
lineHeight: "110%"
}
},
m: {
mtpText: {
fontFamily: "medium",
fontSize: "24px",
fontWeight: "500",
lineHeight: "125%"
},
mtpExtraDates: {
fontFamily: "condensedRegular",
fontSize: "16px",
fontWeight: "400",
lineHeight: "100%"
}
},
xxs: {
mtpText: {
fontFamily: "medium",
fontSize: "14px",
fontWeight: "500",
lineHeight: "125%"
},
mtpExtraDates: {
fontFamily: "regular",
fontSize: "14px",
fontWeight: "400",
lineHeight: "100%"
}
},
l: {
mtpText: {
fontFamily: "regular",
fontSize: "28px",
fontWeight: "500",
lineHeight: "125%"
},
mtpExtraDates: {
fontFamily: "condensedRegular",
fontSize: "16px",
fontWeight: "400",
lineHeight: "100%"
}
}
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Mtp/styled-components.ts
import styled from "styled-components";
import {
space,
compose,
typography,
system,
color,
fontFamily,
fontSize,
layout,
flex,
alignItems,
flexDirection,
justifyContent,
type TypographyProps
} from "styled-system";
import type { ParagraphProps } from "../Typography";
const transformText = system({
whiteSpace: {
property: "whiteSpace"
}
});
const styles = compose(fontFamily, fontSize, transformText, typography, color);
export const DecoratedResulted = styled.span<ParagraphProps>`
${styles}
${space}
${layout}
${flex}
${alignItems}
${flexDirection}
${justifyContent}
`;
export const MtpWrapper = styled.div`
display: flex;
align-items: center;
${styles}
${space}
`;
export const ProExtensionWrapper = styled.span<TypographyProps>`
letter-spacing: -0.5px;
${fontSize}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Mtp/builder.tsx
/* eslint-disable security/detect-object-injection */
import React from "react";
import { differenceInDays, format, startOfDay } from "date-fns";
import { RaceStatusEnum } from "@tvg/ts-types/Race";
import type { MtpAlign, MtpSizes } from "./types";
import { Paragraph, ParagraphFonts } from "../Typography";
import { sizeVariantStyles } from "./constants";
import { DecoratedResulted, ProExtensionWrapper } from "./styled-components";
// Formatter depending on alignment
const formatter: Record<MtpAlign, Record<string, string>> = {
right: {
extraSmall: "dd MMM yyyy -",
default: "hh:mm a - dd MMM yyyy"
},
left: {
extraSmall: " - dd MMM yyyy",
default: " hh:mm a - dd MMM yyyy"
},
center: {
extraSmall: " - dd MMM yyyy",
default: " hh:mm a - dd MMM yyyy"
}
};
export const getResultedFontFamily = (
size: MtpSizes,
value: ParagraphFonts
) => {
if (size === "l" || size === "m") {
return "bold";
}
return value;
};
// Race off computation
export const GetRaceOffAndOfficialText = (
status: RaceStatusEnum,
size: MtpSizes,
postTime: string,
align: MtpAlign,
qaLabel: string,
mode: "dark" | "light"
) => {
if (status === RaceStatusEnum.RACE_OFF) {
return (
<Paragraph
data-mode={mode}
color="--fd-colors-system-component-mtp-content-race-off"
fontFamily={sizeVariantStyles[size].mtpText.fontFamily}
fontSize={sizeVariantStyles[size].mtpText.fontSize}
fontWeight={sizeVariantStyles[size].mtpText.fontWeight}
lineHeight={sizeVariantStyles[size].mtpText.lineHeight}
textAlign={align}
qaLabel={qaLabel}
margin={0}
>
{size === "xxs" ? "OFF" : "Race Off"}
</Paragraph>
);
}
// Compute format of the race resulted
const today = startOfDay(new Date());
const diffInDays = differenceInDays(new Date(postTime), today);
if (diffInDays > 0 && size !== "xxs") {
const formatParam =
formatter[align][size === "xs" ? "extraSmall" : "default"];
const extraData = format(new Date(postTime), formatParam);
return (
<Paragraph
data-mode={mode}
color="--fd-colors-system-component-mtp-content-resulted"
fontFamily={sizeVariantStyles[size].mtpExtraDates.fontFamily}
fontSize={sizeVariantStyles[size].mtpExtraDates.fontSize}
fontWeight={sizeVariantStyles[size].mtpExtraDates.fontWeight}
lineHeight={sizeVariantStyles[size].mtpExtraDates.lineHeight}
textAlign={align}
qaLabel={qaLabel}
margin={0}
>
{align === "right" && (
<>
<>{extraData}</>
</>
)}
<DecoratedResulted
data-mode={mode}
color="--fd-colors-system-component-mtp-content-resulted"
fontFamily={
["m", "l"].includes(size)
? "bold"
: sizeVariantStyles[size].mtpText.fontFamily
}
fontSize={sizeVariantStyles[size].mtpText.fontSize}
fontWeight={sizeVariantStyles[size].mtpText.fontWeight}
lineHeight={sizeVariantStyles[size].mtpText.lineHeight}
textAlign={align}
margin={0}
>
Resulted
</DecoratedResulted>
{align !== "right" && (
<>
<>{extraData}</>
</>
)}
</Paragraph>
);
}
return (
<Paragraph
data-mode={mode}
color="--fd-colors-system-component-mtp-content-resulted"
fontFamily={getResultedFontFamily(
size,
sizeVariantStyles[size].mtpText.fontFamily
)}
fontSize={sizeVariantStyles[size].mtpText.fontSize}
fontWeight={sizeVariantStyles[size].mtpText.fontWeight}
lineHeight={sizeVariantStyles[size].mtpText.lineHeight}
textAlign={align}
margin={0}
>
{size === "xxs" ? "RES" : "Resulted"}
</Paragraph>
);
};
// More than 60m computation
export const getPostTimeMoreThanSixtyMinutes = (
size: MtpSizes,
postTime: string,
isMtpPro: boolean
) => {
if (size === "xxs") {
const output = format(new Date(postTime), "hh:mm a");
const parts = output.split(" ");
return (
<>
{parts[0]}
<div>{parts[1]}</div>
</>
);
}
const today = startOfDay(new Date());
const diffInDays = differenceInDays(new Date(postTime), today);
if (diffInDays > 0) {
const date = format(new Date(postTime), "MMM dd, hh:mm a");
if (isMtpPro) {
return <ProExtensionWrapper fontSize="18px">{date} </ProExtensionWrapper>;
}
return date;
}
return format(new Date(postTime), "hh:mm a");
};
// compute font weight special cases
export const getWeight = (mtp: number, size: MtpSizes) => {
if ((size === "s" && mtp < 6) || size === "xs" || size === "xxs") {
return 500;
}
return 700;
};
const getFontSize = (size: MtpSizes) => {
if (size === "l") {
return "16px";
}
if (size === "m") {
return "14px";
}
return sizeVariantStyles[size].mtpExtraDates.fontSize;
};
// Less than 60m computation
export const getPostTimeLessThanSixtyMinutes = (
size: MtpSizes,
mtp: number,
align: MtpAlign,
color: string,
mode: "dark" | "light",
isMtpPro = false
) => {
if (size === "xxs") {
return `${mtp}m`;
}
if (["xs", "s"].includes(size)) {
return `${mtp} MTP`;
}
let formatMtp = `${mtp}`;
if (mtp < 9) {
formatMtp = `0${mtp}`;
}
let props = {};
if (isMtpPro) {
props = {
display: "flex",
flexDirection: "column",
justifyContent: "center",
fontSize: getFontSize(size)
};
}
return (
<>
{formatMtp}
<DecoratedResulted
data-mode={mode}
color={`var(${color})`}
fontFamily={sizeVariantStyles[size].mtpExtraDates.fontFamily}
fontSize={sizeVariantStyles[size].mtpExtraDates.fontSize}
fontWeight={sizeVariantStyles[size].mtpExtraDates.fontWeight}
lineHeight={sizeVariantStyles[size].mtpExtraDates.lineHeight}
textAlign={align}
{...props}
>
{isMtpPro ? (
<>
MINUTE{mtp > 1 ? "S" : ""}
<ProExtensionWrapper>TILL POST</ProExtensionWrapper>
</>
) : (
<>MINUTE{mtp > 1 ? "S" : ""} TILL POST</>
)}
</DecoratedResulted>
</>
);
};
// Get variants styles
export const getSizeVariantsStyles = (
size: MtpSizes,
mtp: number,
status: RaceStatusEnum
) => {
const defaultValue = sizeVariantStyles;
if ((size === "s" && mtp < 6) || status === RaceStatusEnum.RACE_OFF) {
defaultValue[size as keyof typeof defaultValue].mtpText.fontFamily = "bold";
defaultValue[size as keyof typeof defaultValue].mtpText.fontWeight = "700";
}
return defaultValue;
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Mtp/index.tsx
/* eslint-disable security/detect-object-injection */
import React from "react";
import { RaceStatusEnum } from "@tvg/ts-types/Race";
import type { MtpProps, FutureRace } from "./types";
import {
getPostTimeLessThanSixtyMinutes,
getPostTimeMoreThanSixtyMinutes,
GetRaceOffAndOfficialText,
getSizeVariantsStyles,
getWeight
} from "./builder";
import { Paragraph } from "../Typography";
import { DecoratedResulted, MtpWrapper } from "./styled-components";
export const Mtp: React.FC<MtpProps> = ({
status,
mtp,
postTime,
size = "s",
align = "left",
qaLabel = "mtp",
mode = "light",
isMtpPro = false,
futureRace = null,
isMobile = false,
...props
}) => {
const sizeVariantStyles = getSizeVariantsStyles(
size,
futureRace ? futureRace.mtp : mtp,
status
);
if (
[RaceStatusEnum.RACE_OFF, RaceStatusEnum.RACE_OFFICIAL].includes(status) &&
!futureRace
) {
return (
<MtpWrapper {...props} data-mode={mode}>
{GetRaceOffAndOfficialText(
status,
size,
postTime,
align,
qaLabel,
mode
)}
</MtpWrapper>
);
}
const decoratedFutureResultProps = {
display: "flex",
flexDirection: "column",
justifyContent: "center",
fontFamily: sizeVariantStyles.m.mtpText.fontFamily,
fontSize: !isMtpPro
? sizeVariantStyles.xs.mtpExtraDates.fontSize
: sizeVariantStyles.m.mtpExtraDates.fontSize,
lineHeight: "125%",
fontWeight: "500"
};
return mtp > 59 || futureRace ? (
<MtpWrapper {...props}>
<Paragraph
data-mode={mode}
color="--fd-colors-system-component-mtp-more-than-six-minutes"
fontSize={sizeVariantStyles[size].mtpText.fontSize}
fontWeight={sizeVariantStyles[size].mtpText.fontWeight}
lineHeight={sizeVariantStyles[size].mtpText.lineHeight}
fontFamily={sizeVariantStyles[size].mtpText.fontFamily}
textAlign={align}
qaLabel={qaLabel}
margin={0}
>
{futureRace && !isMobile && `Next: Leg ${futureRace.raceNumber} - `}
{futureRace && isMobile ? (
<DecoratedResulted {...decoratedFutureResultProps}>
Next:
{!isMtpPro ? (
` Leg ${futureRace.raceNumber}`
) : (
<span>Leg {futureRace.raceNumber}</span>
)}
</DecoratedResulted>
) : (
getPostTimeMoreThanSixtyMinutes(
size,
futureRace ? futureRace.postTime : postTime,
isMtpPro
)
)}
</Paragraph>
</MtpWrapper>
) : (
<MtpWrapper {...props}>
<Paragraph
data-mode={mode}
color={
mtp < 6
? "--fd-colors-system-component-mtp-less-than-six-minutes"
: "--fd-colors-system-component-mtp-more-than-six-minutes"
}
fontFamily={sizeVariantStyles[size].mtpText.fontFamily}
fontSize={sizeVariantStyles[size].mtpText.fontSize}
fontWeight={getWeight(mtp, size)}
lineHeight={sizeVariantStyles[size].mtpText.lineHeight}
textAlign={align}
qaLabel={qaLabel}
margin={0}
display={isMtpPro ? "flex" : ""}
>
{getPostTimeLessThanSixtyMinutes(
size,
mtp,
align,
mtp < 6
? "--fd-colors-system-component-mtp-less-than-six-minutes"
: "--fd-colors-system-component-mtp-more-than-six-minutes",
mode,
isMtpPro
)}
</Paragraph>
</MtpWrapper>
);
};
export type { MtpProps, FutureRace };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Button/styled-components.ts
import styled from "styled-components";
import {
space,
width,
layout,
flexbox,
border,
boxShadow,
compose,
variant as styledVariant
} from "styled-system";
import type { ColorPropertiesGroups, IconPosition, ButtonSize } from "./types";
export const buttonSizes = {
s: {
height: "26px",
padding: "4px 8px"
},
m: {
height: "32px",
padding: "7px 8px"
},
ml: {
height: "44px",
padding: "8px 8px"
},
l: {
height: "44px",
padding: "13px 16px"
}
};
const buttonStyles = compose(
space,
width,
layout,
flexbox,
boxShadow,
border,
styledVariant({ prop: "size", variants: buttonSizes })
);
export const StyledButton = styled.button<{
colorPalette: ColorPropertiesGroups;
iconPosition: IconPosition;
isLoading: boolean;
isStretched: boolean;
size: ButtonSize;
hasIcon: boolean;
}>`
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
border-radius: 4px;
gap: 8px;
flex-shrink: 0;
font-family: Roboto-Medium, sans-serif;
font-size: 14px;
font-style: normal;
font-weight: 500;
line-height: 125%;
color: ${({ colorPalette }) => colorPalette.default?.color};
background-color: ${({ colorPalette, isLoading }) =>
isLoading
? colorPalette.pressed?.background
: colorPalette.default?.background};
border: ${({ colorPalette }) => colorPalette.default?.border};
box-shadow: ${({ colorPalette }) => colorPalette.default?.boxShadow};
opacity: 1;
flex-grow: ${({ isStretched }) => (isStretched ? 1 : 0)};
${({ isStretched }) =>
isStretched ? "width: 100%;" : "align-self: flex-start;"};
flex-direction: ${({ iconPosition }) =>
iconPosition === "end" ? "row-reverse" : "row"};
${buttonStyles};
& svg path,
svg rect {
stroke: ${({ colorPalette, hasIcon }) =>
hasIcon && colorPalette.default.color};
}
@media (hover: hover) {
&:hover {
background-color: ${({ colorPalette }) =>
colorPalette.hovered?.background};
border: ${({ colorPalette }) => colorPalette.hovered?.border};
box-shadow: ${({ colorPalette }) => colorPalette.hovered?.boxShadow};
color: ${({ colorPalette }) => colorPalette.hovered?.color};
& svg path,
svg rect {
stroke: ${({ colorPalette }) => colorPalette.hovered?.color};
}
}
}
&:active {
background-color: ${({ colorPalette }) => colorPalette.pressed?.background};
border: ${({ colorPalette }) => colorPalette.pressed?.border};
box-shadow: ${({ colorPalette }) => colorPalette.pressed?.boxShadow};
color: ${({ colorPalette }) => colorPalette.pressed?.color};
& svg path,
svg rect {
stroke: ${({ colorPalette, hasIcon }) =>
hasIcon && colorPalette.pressed.color};
}
}
&:disabled {
background-color: ${({ colorPalette }) =>
colorPalette.disabled?.background};
border: ${({ colorPalette }) => colorPalette.disabled?.border};
box-shadow: ${({ colorPalette }) => colorPalette.disabled?.boxShadow};
color: ${({ colorPalette }) => colorPalette.disabled?.color};
cursor: default;
& svg path,
svg rect {
stroke: ${({ colorPalette, hasIcon }) =>
hasIcon && colorPalette.disabled.color};
}
}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Button/buttonsColorPalette.ts
export const primary = {
default: {
background: "var(--fd-colors-component-button-secondary-background-base)",
border:
"1px solid var(--fd-colors-component-button-secondary-background-base)",
boxShadow: "var(--fd-shadows-elevations-bottom-low)",
color: "var(--fd-colors-component-button-secondary-content-base)"
},
hovered: {
background: "var(--fd-colors-component-button-secondary-background-hover)",
border:
"1px solid var(--fd-colors-component-button-secondary-background-hover)",
boxShadow: "var(--fd-shadows-elevations-bottom-low)",
color: "var(--fd-colors-component-button-secondary-content-hover)"
},
pressed: {
background: "var(--fd-colors-component-button-secondary-background-active)",
border:
"1px solid var(--fd-colors-component-button-secondary-background-active)",
boxShadow: "var(--fd-shadows-elevations-bottom-low)",
color: "var(--fd-colors-component-button-secondary-content-active)"
},
disabled: {
background:
"var(--fd-colors-component-button-secondary-background-disabled)",
border:
"1px solid var(--fd-colors-component-button-secondary-background-disabled)",
boxShadow: "none",
color: "var(--fd-colors-component-button-secondary-content-disabled)"
}
};
export const primaryDark = {
default: {
background: "var(--fd-colors-component-button-secondary-background-base)",
border:
"1px solid var(--fd-colors-component-button-secondary-background-base)",
boxShadow: "var(--fd-shadows-elevations-bottom-low)",
color: "var(--fd-colors-component-button-secondary-content-base)"
},
hovered: {
background: "var(--fd-colors-component-button-secondary-background-hover)",
border:
"1px solid var(--fd-colors-component-button-secondary-background-hover)",
boxShadow: "var(--fd-shadows-elevations-bottom-low)",
color: "var(--fd-colors-component-button-secondary-content-hover)"
},
pressed: {
background: "var(--fd-colors-component-button-secondary-background-active)",
border:
"1px solid var(--fd-colors-component-button-secondary-background-active)",
boxShadow: "var(--fd-shadows-elevations-bottom-low)",
color: "var(--fd-colors-component-button-secondary-content-active)"
},
disabled: {
background: "var(--fd-colors-core-white-tint-005)",
border: "1px solid var(--fd-colors-core-white-tint-005)",
boxShadow: "none",
color: "var(--fd-colors-component-button-secondary-content-disabled)"
}
};
export const secondary = {
default: {
background: "var(--fd-colors-background-surface)",
border: `1px solid var(--fd-colors-component-button-tertiary-border-base)`,
boxShadow: "var(--fd-shadows-elevations-bottom-low)",
color: "var(--fd-colors-component-button-tertiary-content-base)"
},
hovered: {
background: "var(--fd-colors-component-button-tertiary-background-hover)",
border: `1px solid var(--fd-colors-component-button-tertiary-border-hover)`,
boxShadow: "var(--fd-shadows-elevations-bottom-low)",
color: "var(--fd-colors-component-button-tertiary-content-hover)"
},
pressed: {
background: "var(--fd-colors-component-button-tertiary-background-active)",
border: `1px solid var(--fd-colors-component-button-tertiary-border-active)`,
boxShadow: "var(--fd-shadows-elevations-bottom-low)",
color: "var(--fd-colors-component-button-tertiary-content-active)"
},
disabled: {
background:
"var(--fd-colors-component-button-tertiary-background-disabled)",
border: `1px solid var(--fd-colors-component-button-tertiary-border-disabled)`,
boxShadow: "none",
color: "var(--fd-colors-component-button-tertiary-content-disabled)"
}
};
export const secondaryDark = {
default: {
background:
"var(--fd-colors-component-button-transparent-background-hover)",
border:
"1px solid var(--fd-colors-component-button-transparent-background-hover)",
boxShadow: "var(--fd-shadows-elevations-bottom-low)",
color: "var(--fd-colors-component-button-transparent-content-base)"
},
hovered: {
background: "var(--fd-colors-core-white-tint-020)",
border: "1px solid var(--fd-colors-core-white-tint-020)",
boxShadow: "var(--fd-shadows-elevations-bottom-low)",
color: "var(--fd-colors-component-button-transparent-content-hover)"
},
pressed: {
background: "var(--fd-colors-core-white-tint-030)",
border: "1px solid var(--fd-colors-core-white-tint-030)",
boxShadow: "var(--fd-shadows-elevations-bottom-low)",
color: "var(--fd-colors-component-button-transparent-content-active)"
},
disabled: {
background:
"var(--fd-colors-component-button-transparent-background-disabled)",
border:
"1px solid var(--fd-colors-component-button-transparent-background-disabled)",
boxShadow: "none",
color: "var(--fd-colors-component-button-transparent-content-disabled)"
}
};
export const tertiary = {
default: {
background: "var(--fd-colors-component-button-button-link-background-base)",
border:
"1px solid var(--fd-colors-component-button-button-link-background-base)",
boxShadow: "none",
color: "var(--fd-colors-component-button-tertiary-content-base)"
},
hovered: {
background: "var(--fd-colors-component-button-tertiary-background-hover)",
border:
"1px solid var(--fd-colors-component-button-tertiary-background-hover)",
boxShadow: "var(--fd-shadows-elevations-bottom-low)",
color: "var(--fd-colors-component-button-tertiary-content-hover)"
},
pressed: {
background:
"var(--fd-colors-component-button-button-link-background-active)",
border:
"1px solid var(--fd-colors-component-button-button-link-background-active)",
boxShadow: "var(--fd-shadows-elevations-bottom-low)",
color: "var(--fd-colors-component-button-tertiary-content-active)"
},
disabled: {
background:
"var(--fd-colors-component-button-button-link-background-disabled)",
border:
"1px solid var(--fd-colors-component-button-button-link-background-disabled)",
boxShadow: "none",
color: "var(--fd-colors-component-button-tertiary-content-disabled)"
}
};
export const tertiaryDark = {
default: {
background: "var(--fd-colors-component-button-transparent-background-base)",
border:
"1px solid var(--fd-colors-component-button-transparent-background-base)",
boxShadow: "none",
color: "var(--fd-colors-component-button-transparent-content-base)"
},
hovered: {
background:
"var(--fd-colors-component-button-transparent-background-hover)",
border:
"1px solid var(--fd-colors-component-button-transparent-background-hover)",
boxShadow: "var(--fd-shadows-elevations-bottom-low)",
color: "var(--fd-colors-component-button-transparent-content-hover)"
},
pressed: {
background: "var(--fd-colors-core-white-tint-030)",
border: "1px solid var(--fd-colors-core-white-tint-030)",
boxShadow: "var(--fd-shadows-elevations-bottom-low)",
color: "var(--fd-colors-component-button-transparent-content-active)"
},
disabled: {
background:
"var(--fd-colors-component-button-transparent-background-disabled)",
border:
"1px solid var(--fd-colors-component-button-transparent-background-disabled)",
boxShadow: "none",
color: "var(--fd-colors-component-button-transparent-content-disabled)"
}
};
export const betting = {
default: {
background: "var(--fd-colors-component-button-primary-background-base)",
border:
"1px solid var(--fd-colors-component-button-primary-background-base)",
boxShadow: "var(--fd-shadows-elevations-bottom-low)",
color: "var(--fd-colors-component-button-primary-content-base)"
},
hovered: {
background: "var(--fd-colors-component-button-primary-background-hover)",
border:
"1px solid var(--fd-colors-component-button-primary-background-hover)",
boxShadow: "var(--fd-shadows-elevations-bottom-low)",
color: "var(--fd-colors-component-button-primary-content-hover)"
},
pressed: {
background: "var(--fd-colors-component-button-primary-background-active)",
border:
"1px solid var(--fd-colors-component-button-primary-background-active)",
boxShadow: "var(--fd-shadows-elevations-bottom-low)",
color: "var(--fd-colors-component-button-primary-content-active)"
},
disabled: {
background: "var(--fd-colors-component-button-primary-background-disabled)",
border:
"1px solid var(--fd-colors-component-button-primary-background-disabled)",
boxShadow: "none",
color: "var(--fd-colors-component-button-primary-content-disabled)"
}
};
export const promo = {
default: {
background: "var(--fd-colors-brand-tertiary-default)",
border: "1px solid var(--fd-colors-brand-tertiary-default)",
boxShadow: "var(--fd-shadows-elevations-bottom-low)",
color: "var(--fd-colors-content-on-light)"
},
hovered: {
background: "var(--fd-colors-core-yellow-l-3)",
border: "1px solid var(--fd-colors-core-yellow-l-3)",
boxShadow: "var(--fd-shadows-elevations-bottom-low)",
color: "var(--fd-colors-content-on-light)"
},
pressed: {
background: "var(--fd-colors-core-yellow-l-2)",
border: "1px solid var(--fd-colors-core-yellow-l-2)",
boxShadow: "var(--fd-shadows-elevations-bottom-low)",
color: "var(--fd-colors-content-on-light)"
},
disabled: {
background: "var(--fd-colors-component-button-primary-background-disabled)",
border:
"1px solid var(--fd-colors-component-button-primary-background-disabled)",
boxShadow: "none",
color: "var(--fd-colors-component-button-primary-content-disabled)"
}
};
export const destructive = {
default: {
background: "var(--fd-colors-component-button-destructive-background-base)",
border:
"1px solid var(--fd-colors-component-button-destructive-background-base)",
boxShadow: "var(--fd-shadows-elevations-bottom-low)",
color: "var(--fd-colors-component-button-destructive-content-base)"
},
hovered: {
background:
"var(--fd-colors-component-button-destructive-background-hover)",
border:
"1px solid var(--fd-colors-component-button-destructive-background-hover)",
boxShadow: "var(--fd-shadows-elevations-bottom-low)",
color: "var(--fd-colors-component-button-destructive-content-hover)"
},
pressed: {
background:
"var(--fd-colors-component-button-destructive-background-active)",
border:
"1px solid var(--fd-colors-component-button-destructive-background-active)",
boxShadow: "var(--fd-shadows-elevations-bottom-low)",
color: "var(--fd-colors-component-button-destructive-content-active)"
},
disabled: {
background:
"var(--fd-colors-component-button-destructive-background-disabled)",
border:
"1px solid var(--fd-colors-component-button-destructive-background-disabled)",
boxShadow: "none",
color: "var(--fd-colors-component-button-destructive-content-disabled)"
}
};
export const tertiaryDestructive = {
default: {
background: "var(--fd-colors-component-button-button-link-background-base)",
border:
"1px solid var(--fd-colors-component-button-button-link-background-base)",
boxShadow: "none",
color: "var(--fd-colors-link-destructive-base)"
},
hovered: {
background: "var(--fd-colors-core-red-l-5)",
border: "1px solid var(--fd-colors-core-red-l-5)",
boxShadow: "var(--fd-shadows-elevations-bottom-low)",
color: "var(--fd-colors-link-destructive-hover)"
},
pressed: {
background:
"var(--fd-colors-component-button-destructive-background-active)",
border:
"1px solid var(--fd-colors-component-button-destructive-background-active)",
boxShadow: "var(--fd-shadows-elevations-bottom-low)",
color: "var(--fd-colors-component-button-tertiary-content-active)"
},
disabled: {
background:
"var(--fd-colors-component-button-button-link-background-disabled)",
border:
"1px solid var(--fd-colors-component-button-button-link-background-disabled)",
boxShadow: "none",
color: "var(--fd-colors-component-button-tertiary-content-disabled)"
}
};
export const buttonsColorPalette = {
primary,
secondary,
tertiary,
betting,
promo,
destructive,
tertiaryDestructive,
primaryDark,
secondaryDark,
tertiaryDark
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Button/utils.ts
import type { ColorPropertiesGroups, ButtonVariant } from "./types";
import { buttonsColorPalette } from "./buttonsColorPalette";
export const createPalette = (
variant: ButtonVariant,
colorsObject?: ColorPropertiesGroups
) => {
const baseColors = buttonsColorPalette[variant as ButtonVariant];
return { ...baseColors, ...colorsObject };
};
webpack://frontend-mybets/../../packages/tvg-comp-desktop-bet-ticket/src/types.ts
import { BetType, VisualSelections } from "@tvg/ts-types/Bet";
import { BettingInterest, RaceWagerType } from "@tvg/ts-types/Race";
export type BetStateType = "none" | "success" | "error";
export type SpecialGroupBets = {
[key: string]: VisualSelections;
};
export interface BlacklistedWagerTypes {
blacklistedBets: string[];
}
export type WagerTypesSelected = {
horseNamesList: Array<string>;
wagerType: BetType;
betSelections: VisualSelections[];
selections: string[][];
betTotal: number;
wagerAmount: number;
};
export type BetDetailsParams = {
isSpecialGroup: boolean;
wagerTypes?: RaceWagerType[];
selections: SpecialGroupBets | VisualSelections[];
bettingInterests: BettingInterest[];
betAmount: number;
};
export enum BetStatusType {
NONE = "NONE",
PLACED = "PLACED",
ERROR = "ERROR",
PROCESSING = "PROCESSING"
}
export type Selections = Array<{
number: number | string;
numberColor: string;
saddleColor: string;
}>;
export interface BetStatus {
status: BetStatusType;
statusCode?: number;
errorMessage?: string;
}
export type BetGroupStatus = Record<string, BetStatus>;
export interface BetTicketGroupStatus {
betGroupStatus: BetGroupStatus;
processingBets: number;
errorBets: number;
successBets: number;
isRepeat?: boolean;
}
export interface BetTicketGroupType {
betGroupStatus: BetGroupStatus;
isRepeat?: boolean;
}
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Button/index.tsx
import React from "react";
import type { ButtonProps, ButtonIcon, ButtonVariant } from "./types";
import { Icon, type IconNames } from "../Icon";
import { LoadingSpinner } from "../LoadingSpinner";
import { StyledButton } from "./styled-components";
import { createPalette } from "./utils";
import { buttonsColorPalette } from "./buttonsColorPalette";
const getButtonIcon = (icon: ButtonIcon) =>
React.isValidElement(icon) ? (
icon
) : (
<Icon
name={icon as IconNames}
size="s"
lineColor="--fd-colors-component-button-secondary-content-base"
backgroundColor="transparent"
qaLabel="button-icon"
/>
);
export const Button = ({
variant = "primary",
size = "l",
children,
onClick,
isLoading = false,
iconPosition = "start",
icon,
overrideColors,
isStretched = false,
isDisabled = false,
qaLabel = "button",
...rest
}: ButtonProps) => {
const colorPalette = createPalette(variant, overrideColors);
return (
<StyledButton
size={size}
disabled={isDisabled}
colorPalette={colorPalette}
isStretched={isStretched}
isLoading={isLoading}
iconPosition={iconPosition}
onClick={onClick}
hasIcon={!!icon}
data-qa-label={qaLabel}
{...rest}
>
{isLoading ? (
<LoadingSpinner
size="s"
color={
isDisabled
? "--fd-colors-core-blue-d-1"
: "--fd-colors-component-button-tertiary-content-active"
}
bgColor={
isDisabled
? "--fd-colors-core-blue-l-4"
: "--fd-colors-core-white-tint-020"
}
/>
) : (
<>
{icon && getButtonIcon(icon)}
{children}
</>
)}
</StyledButton>
);
};
export { buttonsColorPalette };
export type { ButtonProps, ButtonVariant };
webpack://frontend-mybets/../../packages/tvg-lib-api/wtx/BetSelectionsHelper.ts
const DEFAULT_SEPARATOR = ",";
const CONSECUTIVE_SELECTIONS_SEPARATOR = "-";
let consecutiveSelections: string[];
let currentSelection: number[];
/**
* Calculate the correct string separator
* @param selections
*/
const getStringSeparator = (selections: Array<number>): string =>
selections.length === 2 && selections[1] - selections[0] > 1
? CONSECUTIVE_SELECTIONS_SEPARATOR
: DEFAULT_SEPARATOR;
/**
* Add consecutive selection
*/
const pushCurrentSelectionToConsecutiveSelections = (): void => {
consecutiveSelections.push(
currentSelection.join(getStringSeparator(currentSelection))
);
};
/**
* Process each selection and add it to the current selection
* @param selection
*/
const forEachSelectionCallback = (selection: number): void => {
if (currentSelection.length) {
if (selection - currentSelection[currentSelection.length - 1] === 1) {
if (currentSelection.length === 2) {
currentSelection[1] = selection;
} else {
currentSelection.push(selection);
}
} else {
pushCurrentSelectionToConsecutiveSelections();
currentSelection = [selection];
}
} else {
currentSelection.push(selection);
}
};
/**
* Calculate string in each step of selections
* @param selections
* @return {string}
*/
const stepSelectionsStringFilter = (selections: Array<number>): string => {
// Reset state
consecutiveSelections = [];
currentSelection = [];
if (!Array.isArray(selections)) {
return selections;
}
const sortedSelections = selections.sort((a, b) => a - b);
sortedSelections.forEach(forEachSelectionCallback);
pushCurrentSelectionToConsecutiveSelections();
return consecutiveSelections.join(DEFAULT_SEPARATOR);
};
export default stepSelectionsStringFilter;
webpack://frontend-mybets/../../packages/tvg-lib-api/wtx/BetHelper.ts
import { get, compact } from "lodash";
import { RaceWagerType } from "@tvg/ts-types/Race";
import stepSelectionsStringFilter from "./BetSelectionsHelper";
type UserSelections = Array<Array<number>>;
export type BetTotal = {
betCount: number;
betAmount?: number;
betCost: string;
wagerName: string;
wagerId: number;
wagerCode?: string;
wagersString: string;
userSelections?: UserSelections;
};
// This will filter bad selections of scratched runners before doing a bet
const filterBadSelections = (selections: UserSelections) =>
selections
.filter((selection) => selection)
.map((selection) => selection.filter((s) => s));
/**
* wager multiplier by betType
*/
const wagerMultiplier = {
WP: 2,
WS: 2,
PS: 2,
WPS: 3
};
/**
* step by bet type
*/
const betSteps = {
QN: 2,
QNB: 2,
EXB: 2,
TRB: 3,
SUB: 4,
H5B: 5,
OM: 2,
OMB: 2,
OMW: 2,
TI: 3,
TIB: 4
};
/**
* Build wager string from bet type and selection
* @param wagerType
* @param userSelections
* @return {string}
*/
const getWagerString = (
wagerType: RaceWagerType,
userSelections: UserSelections
): string => {
let wagerString = "";
for (let i = 0; i < wagerType.columnCount; i += 1) {
if (i !== 0) {
wagerString += " | ";
}
if (get(userSelections, `[${i}]`, []).length) {
wagerString += stepSelectionsStringFilter(userSelections[i]);
} else {
wagerString += "?";
}
}
return wagerString;
};
/**
* Calculate the cartesian product of a matrix
* @param matrix
* @return {Array<Array<number>>}
*/
const cartesianProductOf = (
matrix: Array<Array<number>>
): Array<Array<number>> =>
matrix.reduce(
(a: Array<Array<number>>, b: Array<number>) => {
const ret: Array<Array<number>> = [];
a.forEach((tempA) => {
b.forEach((tempB) => {
if (tempA.indexOf(tempB) < 0) {
ret.push(tempA.concat([tempB]));
}
});
});
return ret;
},
[[]]
);
/**
* Return minimal user selection per step by bet type
* @param wagerType
* @returns {number}
*/
const getMinUserSelectionPerStep = (wagerType: RaceWagerType) =>
get(betSteps, wagerType.type.code, 1);
/**
* Return bet multiplier by bet type
* @param wagerType
* @returns {number}
*/
const getWagerTypeMultiplier = (wagerType: RaceWagerType) =>
get(wagerMultiplier, wagerType.type.code, 1);
/**
* Calculate total number of fecta box bets
* @param userSelections
* @param numOfPositions
* @returns {number}
*/
const calculateFectaBoxTotalBets = (
userSelections: UserSelections,
numOfPositions: number
): number => {
let selections = get(userSelections, "[0].length");
let res = 1;
for (let i = 0; i < numOfPositions; i += 1) {
res *= selections;
selections -= 1;
}
return res;
};
/**
* Calculate total number of fecta wheels bets
* @param userSelections
* @returns {Array}
*/
const calculateFectaWheelsTotalBets = (
userSelections: UserSelections
): Array<Array<number>> => {
let res: Array<Array<number>> = [];
let firstColumn: Array<number> = [];
let selectionsLength = 0;
let i;
const otherColumns = [];
const userSelectionLength = userSelections.length;
for (i = 0; i < userSelectionLength; i += 1) {
const column = userSelections[i];
if (i === 0) {
firstColumn = column;
selectionsLength = firstColumn.length;
} else {
otherColumns.push(column);
}
}
for (i = 0; i < selectionsLength; i += 1) {
const firstColumnValue = [firstColumn[i]];
const matrix = otherColumns.slice(0);
matrix.unshift(firstColumnValue);
res = res.concat(cartesianProductOf(matrix));
}
return res;
};
/**
* Calculate number of bets on straight and legs bets
* @param userSelections
* @return {number}
*/
const calculateStraightAndLegsTotalBets = (userSelections: UserSelections) => {
let res = 1;
for (let i = 0; i < userSelections.length; i += 1) {
const legSelections = userSelections[i].length;
res *= legSelections;
}
return res;
};
/**
* Calculate total number of bets on Quinella
* @param userSelections
* @returns {number}
*/
const calculateQuinellaTotalBets = (userSelections: UserSelections): number => {
const selections = get(userSelections, "[0].length");
return selections === 2 ? 1 : 0;
};
/**
* Calculate total number of bets on Quinella Box
* @param userSelections
* @returns {number}
*/
const calculateQuinellaBoxTotalBets = (
userSelections: UserSelections
): number => {
const selections = get(userSelections, "[0].length");
return selections >= 2 ? (selections * (selections - 1)) / 2 : 0;
};
/**
* Calculate the possible combination of bets for Quinella wheel
* @param userSelections
* @returns {number}
*/
const calculateQuinellaWheelTotalBets = (
userSelections: UserSelections
): Array<Array<number>> => {
let res: Array<Array<number>> = [];
const firstColumn = userSelections[0];
const firstColumnLength = firstColumn.length;
const secColumn = userSelections[1];
const secColumnLength = secColumn.length;
const alreadyUsedKeys = [];
/* eslint-disable */
for (let i = 0; i < firstColumnLength; i += 1) {
const firstColumnValue = [firstColumn[i]];
const matrix: Array<Array<number>> = [[]];
for (let j = 0; j < secColumnLength; j += 1) {
const secColumnItem = secColumn[j];
const keyPar =
(BigInt(1) << BigInt(secColumnItem)) ^
// @ts-ignore
(BigInt(1) << BigInt(firstColumnValue)); // bitwise operation if 2nd column value is different from de 1st, calculate the bitwise value of the column to generate a unique key the pair combination
if (
// @ts-ignore
secColumnItem != firstColumnValue &&
alreadyUsedKeys.indexOf(keyPar) < 0
) {
matrix[0].push(secColumnItem);
}
alreadyUsedKeys.push(keyPar);
}
matrix.unshift(firstColumnValue);
res = res.concat(cartesianProductOf(matrix));
}
/* eslint-enable */
return res;
};
/**
* Calculate the possible combination of bets for Trio
* @param userSelections
* @returns {number}
*/
const calculateTrioTotalBets = (userSelections: UserSelections): number => {
const selections = get(userSelections, "[0].length");
return selections === 3 ? 1 : 0;
};
/**
* Calculate the possible combination of bets for Trio Box
* @param userSelections
* @returns {number}
*/
const calculateTrioBoxTotalBets = (userSelections: UserSelections): number => {
const selections = get(userSelections, "[0].length");
return selections >= 4
? (selections * (selections - 1) * (selections - 2)) / 6
: 0;
};
/**
* Calculate the possible combination of bets for Trio Wheel
* @param userSelections
* @returns {number}
*/
function calculateTrioWheelTotalBets(userSelections: UserSelections) {
const firstColLength = get(userSelections, "[0].length");
const secColLength = get(userSelections, "[1].length");
let res = 1;
if (
firstColLength < 1 ||
firstColLength > 2 ||
firstColLength + secColLength < 3
) {
res = 0;
} else if (firstColLength === 2) {
res = secColLength;
} else {
const filteredSelections = userSelections[1].filter(
(selection) => !userSelections[0].includes(selection)
);
res = filteredSelections.reduce(
(acc, _, i, self) => acc + self.slice(i + 1).length,
0
);
}
return res;
}
/**
* Calculate total number of bets for keys types
* @param userSelections
* @param numOfPositions
* @param isBox
* @returns {number}
*/
const calculateKeysTotalBets = (
userSelections: UserSelections,
numOfPositions: number,
isBox: boolean
) => {
let selections = 0;
let res = 1;
if (
get(userSelections, "[0]", []).length &&
get(userSelections, "[1]", []).length
) {
selections = userSelections[1].length;
for (let i = 0; i < numOfPositions - 1; i += 1) {
res *= selections;
selections -= 1;
}
if (isBox) {
res *= numOfPositions;
}
} else {
res = 0;
}
return res;
};
/**
* Calculate the bet count by bet type
* @param wagerType
* @param selections
* @return {number}
*/
const calculateBetCount = (
wagerType: RaceWagerType,
selections: UserSelections
): number => {
let betCount = 0;
if (wagerType.type.code === "QN" || wagerType.type.code === "OM") {
betCount = calculateQuinellaTotalBets(selections);
} else if (wagerType.type.code === "QNB" || wagerType.type.code === "OMB") {
betCount = calculateQuinellaBoxTotalBets(selections);
} else if (wagerType.type.code === "QNW" || wagerType.type.code === "OMW") {
betCount = calculateQuinellaWheelTotalBets(selections).length;
} else if (wagerType.type.code === "TI") {
betCount = calculateTrioTotalBets(selections);
} else if (wagerType.type.code === "TIB") {
betCount = calculateTrioBoxTotalBets(selections);
} else if (wagerType.type.code === "TIW") {
betCount = calculateTrioWheelTotalBets(selections);
} else if (wagerType.isKey) {
betCount = calculateKeysTotalBets(
selections,
wagerType.positionCount,
wagerType.isBox
);
} else if (wagerType.isBox) {
const numberOfPositions = getMinUserSelectionPerStep(wagerType);
betCount = calculateFectaBoxTotalBets(selections, numberOfPositions);
} else if (wagerType.columnCount > 1 && wagerType.legCount === 1) {
if (wagerType.isWheel) {
betCount = calculateFectaWheelsTotalBets(selections).length;
} else {
// calculate bet count for fecta bets
betCount = cartesianProductOf(selections).length;
}
} else {
const betTypeMultiplier = getWagerTypeMultiplier(wagerType);
betCount =
calculateStraightAndLegsTotalBets(selections) * betTypeMultiplier;
}
return betCount;
};
/**
* Calculate bet totals and if the selected params are valid
* @param Amount amount per bet
* @param WagerType wager type select
* @param userSelections matrix off user selections
* @returns {{}}
*/
const calculateBetTotal = (
amount: number,
wagerType: RaceWagerType,
userSelections: UserSelections
): BetTotal => {
const filteredUS = filterBadSelections(compact(userSelections));
const result: {
betCount: number;
betAmount?: number;
betCost: string;
wagerName: string;
wagerId: number;
wagerCode?: string;
wagersString: string;
userSelections?: number[][];
BIs: number[][];
} = {
betCount: 0,
betCost: "0.00",
wagerName: wagerType.type.name,
wagerId: wagerType.type.id,
wagersString: "",
BIs: filteredUS
};
if (!(amount > 0.0 && filteredUS && filteredUS.length > 0)) {
return result;
}
const betCount = calculateBetCount(wagerType, filteredUS);
result.betCount = betCount;
result.betAmount = amount;
result.betCost = (betCount * amount).toFixed(2);
result.wagerName = wagerType.type.name;
result.wagerId = wagerType.type.id;
result.wagerCode = wagerType.type.code;
result.wagersString = getWagerString(wagerType, filteredUS);
result.userSelections = filteredUS;
return result;
};
export const sortRunnersSelections = (
runnerNumberA: string | number,
runnerNumberB: string | number
) => +runnerNumberA - +runnerNumberB;
export default calculateBetTotal;
webpack://frontend-mybets/../../packages/urp-comp-betslip/src/types.ts
import React from "react";
import { Talent } from "@tvg/ts-types/Talent";
import { ButtonVariant } from "@tvg/design-system/web";
import { RaceProgram } from "@tvg/ts-types/Race";
import { WagerTypeCodesEnum } from "@tvg/ts-types/Wager";
export interface BetSlipProps {
race: RaceProgram;
races: RaceProgram[];
selections: string[][];
onDelete: () => void;
onPlaceBet?: (totalBetAmount: number) => void;
onCreatePick?: (totalBetAmount: number, talent: Talent) => void;
isVisible: boolean;
isLoading: boolean;
betType: WagerTypeCodesEnum;
isBettingDisabled?: boolean;
isFloating?: boolean;
isWagerPad?: boolean;
onClickAlternatesView?: () => void;
children?: React.ReactNode;
isTalentPick?: boolean;
}
export interface BetSlipContainerProps {
isBetSlipExpanded: boolean;
isError: boolean;
isExtendedSelections: boolean;
isFloating?: boolean;
}
export interface AlternateSelectionsMessages {
infoModal: {
title: string;
subtitle: string;
description: string;
};
betslipButton: string;
alternatesModal: {
title: string;
alert: {
title: string;
description: string;
};
buttons: {
cancel: string;
apply: string;
};
};
}
export interface BetslipAccountErrorMessages {
geolocationError: {
title: string;
message: string;
button: string;
};
accountComplianceError: {
title: string;
message: string;
button: string;
};
termsAndConditionsError: {
button: string;
};
}
export interface ButtonDescription {
text: string;
variant: ButtonVariant;
action: string;
}
export interface CustomAmountMessages {
title: string;
buttons: ButtonDescription[];
}
export enum SourceKeysEnum {
FDTV_PICKS = "FDTV Picks",
TRACKMASTER = "Trackmaster",
NUMBERFIRE = "numberFire",
SELECT_ALL_RUNNERS = "Select all modal",
RACE_CARD = "Race Card",
REPEAT_BET_RACE_CARD = "repeat_bet_race_card",
REPEAT_BET_MY_BETS = "repeat_bet_my_bets"
}
export type SourceValue =
| "fdtv_race_card"
| "trackmaster_race_card"
| "numberfire_race_card"
| "repeat_bet_race_card"
| "repeat_bet_my_bets"
| "Race Card";
export type PlaceBetGtm = {
raceNumber?: string;
trackName?: string;
betType?: string;
betAmount: number;
selectionSource?: string;
raceType?: string;
module?: string;
specialWagerType?: string;
};
export type RepeatBetEventPayload = {
betAmount: number;
betType: string;
module: string;
selectionSource: string;
raceType?: string;
specialWagerType?: string;
};
webpack://frontend-mybets/../../packages/tvg-comp-desktop-bet-ticket/src/utils/betUtils.ts
import { find, findIndex, flatten, get } from "lodash";
import { NullaryFn } from "@tvg/ts-types/Functional";
import { WagerType, WagerTypeCodesEnum } from "@tvg/ts-types/Wager";
import {
BettingInterest,
RaceInfoMyBets,
RaceProgram,
RaceWagerType,
Runner
} from "@tvg/ts-types/Race";
// @ts-ignore
import calculateBetTotal from "@tvg/api/wtx/BetHelper";
import BetUtils from "@tvg/utils/betSelection";
import { VisualSelection, VisualSelections } from "@tvg/ts-types/Bet";
import {
BetDetailsParams,
BlacklistedWagerTypes,
SpecialGroupBets,
WagerTypesSelected
} from "../types";
const betTypePosition = {
WN: [WagerTypeCodesEnum.WIN],
WP: [WagerTypeCodesEnum.WIN, WagerTypeCodesEnum.PLACE],
WS: [WagerTypeCodesEnum.WIN, WagerTypeCodesEnum.SHOW],
WPS: [
WagerTypeCodesEnum.WIN,
WagerTypeCodesEnum.PLACE,
WagerTypeCodesEnum.SHOW
],
PL: [WagerTypeCodesEnum.PLACE],
PS: [WagerTypeCodesEnum.PLACE, WagerTypeCodesEnum.SHOW],
SH: [WagerTypeCodesEnum.SHOW]
};
export const simpleBetTypes = [
WagerTypeCodesEnum.WIN,
WagerTypeCodesEnum.PLACE,
WagerTypeCodesEnum.SHOW,
WagerTypeCodesEnum.WIN_PLACE,
WagerTypeCodesEnum.WIN_SHOW,
WagerTypeCodesEnum.PLACE_SHOW,
WagerTypeCodesEnum.WIN_PLACE_SHOW
];
export const exoticBetTypes = [
WagerTypeCodesEnum.EXACTA,
WagerTypeCodesEnum.TRIFECTA,
WagerTypeCodesEnum.SUPERFECTA,
WagerTypeCodesEnum.SUPERHIGHFIVE
];
export const getActiveButtons = (
runnerNumber: string,
betSelectionsNumbers: string[][],
allowAlternateSelection: boolean
) => {
if (allowAlternateSelection) {
const selectionsArray = betSelectionsNumbers[0] || [];
const isRegularSelected = selectionsArray.includes(runnerNumber);
const isAlternateSelected = selectionsArray.includes(`${runnerNumber}B`);
return [isRegularSelected, isAlternateSelected];
}
if (betSelectionsNumbers.length > 0) {
return betSelectionsNumbers.map((selectionsArray: string[]) =>
selectionsArray.includes(runnerNumber)
);
}
return [false];
};
export const getBetTypeByPosition = (
betTypeCode: WagerTypeCodesEnum,
position: number
) => get(betTypePosition, `[${betTypeCode}][${position}]`, 0);
export const getBetTypePosition = (
betTypeCode: WagerTypeCodesEnum,
betType: WagerTypeCodesEnum
) =>
get(betTypePosition, `[${betTypeCode}]`, "WN").findIndex(
(bet: WagerTypeCodesEnum) => bet === betType
);
export const getBetSelectionsToShow = (
betSelections: VisualSelections[],
bettingInterests: BettingInterest[] = [],
isHorseName: boolean = false
): string[][] => {
// if we don't have betting interest info return the selections values
if (bettingInterests.length === 0) {
return betSelections.map((column) =>
column.map((selection) => `${selection}`)
);
}
const betSelectionsToShow: string[][] = [];
betSelections.forEach((selection) => {
const column: string[] = [];
selection.forEach((bet) => {
const betInterest = find(
bettingInterests,
(bi) => bet.number === bi?.biNumber?.toString()
);
get(betInterest, "runners", []).forEach((runner: Runner) => {
if (!get(runner, "scratched")) {
column.push(
isHorseName
? get(runner, "horseName")
: get(runner, "runnerId").toString()
);
}
});
});
betSelectionsToShow.push(column);
});
return betSelectionsToShow;
};
export const getBetDetails = ({
isSpecialGroup,
wagerTypes,
selections,
bettingInterests,
betAmount
}: BetDetailsParams) =>
wagerTypes?.reduce((wagerTypeList: WagerTypesSelected[], wagerType) => {
let betSelections: VisualSelections[] = [];
let allSelections: number;
const betTypeCode = get(wagerType, "type.code");
if (isSpecialGroup) {
betSelections = [get(selections, betTypeCode, [])];
allSelections = flatten(betSelections).length;
} else {
betSelections = selections as VisualSelections[];
allSelections = get(selections as VisualSelections[], 0, []).length;
}
const selectionsFiltered = getBetSelectionsToShow(
betSelections,
bettingInterests
);
const horseNameFiltered = getBetSelectionsToShow(
betSelections,
bettingInterests,
true
);
if (allSelections > 0) {
let betTotal = betAmount;
if (isSpecialGroup) {
betTotal =
betAmount * getMultiplierSpecialGroup(betTypeCode) * allSelections;
}
wagerTypeList.push({
wagerType,
betSelections,
selections: selectionsFiltered,
betTotal,
wagerAmount: betAmount,
horseNamesList: horseNameFiltered[0]
});
}
return wagerTypeList;
}, []) || [];
export const mapVisualSelectionsToNumber = (
betSelections: VisualSelections[]
) =>
betSelections.map((selections) =>
selections.reduce(
(currentSelections: number[], selection: VisualSelection): number[] => {
if (selection.isAlternate) return currentSelections; // Exclude alternates
const biNumber = +selection.number.replace(/[A-Za-z]/g, "");
return !biNumber || currentSelections.includes(biNumber)
? currentSelections
: [...currentSelections, biNumber];
},
[]
)
);
export const getOnlyAvailableBetTypes = (
betTypes: WagerType[],
blacklistedBetTypes: BlacklistedWagerTypes
): WagerType[] =>
betTypes.filter(
(betType) =>
!(blacklistedBetTypes?.blacklistedBets || []).includes(betType.code)
);
export const getOnlyAvailableRaceBetTypes = (
betTypes: RaceWagerType[],
blacklistedBetTypes: BlacklistedWagerTypes
): RaceWagerType[] =>
betTypes.filter(
(betType) =>
!(blacklistedBetTypes?.blacklistedBets || []).includes(betType.type.code)
);
const findWagerTypeByGroup = (wagerTypeId: string, searchWagerId: string) =>
wagerTypeId === searchWagerId;
// Remove selection from simple bet if present in more than 1 bet type
// eg: if selection exists on win and show it should be placed on win/show wager type and removed from win wager type
const extractArray = (
arrayToRemove: VisualSelections,
valueToExtract: string
): VisualSelections =>
arrayToRemove.filter(
(value) => !findWagerTypeByGroup(value.number, valueToExtract)
);
export const getWagerSelectionFromVisualSelections = (
betSelections: VisualSelections[]
) =>
betSelections.map((column) =>
[
...new Set(
column.map((visualSelection) => parseInt(visualSelection.number, 10))
)
].map((selection) => ({ order: selection }))
);
export const getSelectionFromVisualWithAlternates = (
betSelections: VisualSelections[]
) =>
betSelections.map((column) => {
const alternateSelection = column.find(
(selection) => selection.isAlternate
);
const alternate = alternateSelection
? parseInt(alternateSelection.number, 10)
: null;
const uniqueSelections = [
...new Set(
column
.filter((selection) => !selection.isAlternate)
.map((visualSelection) => parseInt(visualSelection.number, 10))
)
].map((selection) => ({ order: selection }));
return {
bettingInterests: uniqueSelections,
alternate
};
});
// Decoupling the WPS bets into multiple child bet types with the format of {[wagerTypeCode]: betSelections}
// simplified eg: [[1,2,3],[3,4],[5]] -> {win: [1,2], place:[4], show:[5], win/place: [3]}
export const getBetSelectionSpecialGroup = (
betSelections: VisualSelections[],
betTypeCode: WagerTypeCodesEnum
): SpecialGroupBets => {
let win = [
...get(
betSelections,
getBetTypePosition(betTypeCode, WagerTypeCodesEnum.WIN),
[]
)
];
let place = [
...get(
betSelections,
getBetTypePosition(betTypeCode, WagerTypeCodesEnum.PLACE),
[]
)
];
let show = [
...get(
betSelections,
getBetTypePosition(betTypeCode, WagerTypeCodesEnum.SHOW),
[]
)
];
const winPlace: VisualSelections = [];
const winShow: VisualSelections = [];
const placeShow: VisualSelections = [];
const winPlaceShow: VisualSelections = [];
win = win.reduce((winWagerList: VisualSelections, winWagerType) => {
if (Number.isNaN(parseInt(winWagerType.number, 10))) {
return winWagerList;
}
const placeWagerType = place.find((wagerType) =>
findWagerTypeByGroup(wagerType.number, winWagerType.number)
);
const showWagerType = show.find((wagerType) =>
findWagerTypeByGroup(wagerType.number, winWagerType.number)
);
if (placeWagerType && showWagerType) {
winPlaceShow.push(winWagerType);
place = extractArray(place, winWagerType.number);
show = extractArray(show, winWagerType.number);
} else if (placeWagerType) {
winPlace.push(placeWagerType);
place = extractArray(place, winWagerType.number);
} else if (showWagerType) {
winShow.push(showWagerType);
show = extractArray(show, winWagerType.number);
} else {
winWagerList.push(winWagerType);
}
return winWagerList;
}, []);
place = place.reduce((placeWagerList: VisualSelections, placeWagerType) => {
if (Number.isNaN(parseInt(placeWagerType.number, 10))) {
return placeWagerList;
}
const showWagerType = show.find((wagerType) =>
findWagerTypeByGroup(wagerType.number, placeWagerType.number)
);
if (showWagerType) {
placeShow.push(showWagerType);
show = extractArray(show, showWagerType.number);
} else {
placeWagerList.push(placeWagerType);
}
return placeWagerList;
}, []);
// There is no order for the bets to appear so this is the order for now to copy FDR WPS bets
return {
[WagerTypeCodesEnum.WIN as WagerTypeCodesEnum]: win,
[WagerTypeCodesEnum.WIN_PLACE as WagerTypeCodesEnum]: winPlace,
[WagerTypeCodesEnum.WIN_SHOW as WagerTypeCodesEnum]: winShow,
[WagerTypeCodesEnum.WIN_PLACE_SHOW as WagerTypeCodesEnum]: winPlaceShow,
[WagerTypeCodesEnum.PLACE as WagerTypeCodesEnum]: place,
[WagerTypeCodesEnum.PLACE_SHOW as WagerTypeCodesEnum]: placeShow,
[WagerTypeCodesEnum.SHOW as WagerTypeCodesEnum]: show
};
};
// Each wager type has a multiplier to calculate ticket value
export const getMultiplierSpecialGroup = (wagerId: string) => {
let multiplier = 0;
if (wagerId === WagerTypeCodesEnum.WIN_PLACE_SHOW) {
multiplier += 3;
} else if (
wagerId === WagerTypeCodesEnum.WIN_PLACE ||
wagerId === WagerTypeCodesEnum.WIN_SHOW ||
wagerId === WagerTypeCodesEnum.PLACE_SHOW
) {
multiplier += 2;
} else {
multiplier += 1;
}
return multiplier;
};
export const removeCoupledEntries = (selections: VisualSelections) =>
(selections || []).reduce(
// remove coupled entries so they don't enter on totals calculation should get valid numbers or should get coupled entry if eg: 1A or 1B
// if the coupled valid is not present by scratched eg: Should get 1A if the selection 1 is not present
// This is only for special group bets
(betsAcc: VisualSelections, bet: VisualSelection) => {
if (
!betsAcc.find(
(val) => parseInt(bet.number, 10) === parseInt(val.number, 10)
)
) {
return [...betsAcc, bet];
}
return [...betsAcc];
},
[]
);
// Using calculate bet total if it's not an special group type bet (WPS)
// and calculating each wager type separately to check the total if special group bet
export const getBetTotalAmount = (
isSpecialGroup: boolean,
betSelectionsStrings: string[][],
betAmount: number,
specialGroupBets?: SpecialGroupBets,
typeFromRace?: RaceWagerType | null
): string => {
const betSelectionsNumbers: number[][] = betSelectionsStrings.map(
(column): number[] =>
column.map((element): number => {
const isAlternate = element.endsWith("B");
const numericPart = element.match(/\d+/);
return !isAlternate && numericPart ? +numericPart[0] : 0;
})
);
if (
typeFromRace &&
!isSpecialGroup &&
typeFromRace.columnCount === betSelectionsNumbers.length
) {
const betTicket = calculateBetTotal(
betAmount,
typeFromRace,
betSelectionsNumbers
);
return betTicket.betCost;
}
let betTotal = 0;
if (isSpecialGroup && specialGroupBets) {
Object.keys(specialGroupBets).forEach((bet) => {
const numberOfBets = removeCoupledEntries(specialGroupBets[bet]).length;
betTotal += numberOfBets * betAmount * getMultiplierSpecialGroup(bet);
});
}
return betTotal.toString();
};
// There is some info that is getting fetched in different places since it's share, adding a common method here
// It should return full Seletions, the specialGroup type boolean, the selections decoupled if special and the total amount for bet calculated
export const getBettingInfo = (
betSelectionsNumbers: string[][],
betAmount: number,
race: RaceProgram | RaceInfoMyBets,
races: RaceProgram[] | RaceInfoMyBets[],
typeFromRace?: RaceWagerType | null,
shouldShowAlternates?: boolean
) => {
const numberOfWagerableRunners = [];
let specialGroupBets;
// Getting the special group flow from the service to know if wager type needs to be decoupled
const isSpecialGroup = !!typeFromRace?.specialGroup;
const legCount = typeFromRace?.legCount || 1;
let fullSelections = [] as VisualSelections[];
if (races && races.length > 0) {
const indexOfFirstRace = races.findIndex(
(element: RaceProgram | RaceInfoMyBets) => element.id === race?.id
);
if (legCount > 1 && indexOfFirstRace >= 0) {
for (let i = 0; i < legCount; i++) {
fullSelections.push(
BetUtils.getVisualSelections({
selections: [betSelectionsNumbers[i]],
bettingInterests: races[indexOfFirstRace + i].bettingInterests,
isLegSelections: typeFromRace ? typeFromRace.legCount > 1 : false,
shouldShowAlternates
})[0]
);
numberOfWagerableRunners.push(
races[indexOfFirstRace + i].numRunners || ""
);
}
} else {
if (race && race.bettingInterests) {
// Getting all selections to get coupled entries appear on the bet confirmation: eg: [1, 2, 3] -> [1, 1A, 2, 3]
fullSelections = BetUtils.getVisualSelections({
selections: betSelectionsNumbers,
bettingInterests: race?.bettingInterests,
isLegSelections: typeFromRace ? typeFromRace.legCount > 1 : false,
shouldShowAlternates
});
}
numberOfWagerableRunners.push(race?.numRunners || "");
}
}
if (isSpecialGroup) {
specialGroupBets = getBetSelectionSpecialGroup(
fullSelections,
typeFromRace?.type.code
);
}
// Getting total amount depending if special group or not calculation is different
const totalAmount = getBetTotalAmount(
isSpecialGroup,
betSelectionsNumbers,
betAmount,
specialGroupBets,
typeFromRace
);
return {
fullSelections,
isSpecialGroup,
specialGroupBets,
totalAmount,
numberOfWagerableRunners
};
};
export const asyncSubmit = async (
submitBetsFnArray: NullaryFn<Promise<{}>>[],
currentIndex: number = 0
) => {
const item = get(submitBetsFnArray, currentIndex);
if (typeof item === "function") {
item().then(() => {
const nextIndex = currentIndex + 1;
const hasNextItem = get(submitBetsFnArray, nextIndex, undefined);
if (hasNextItem) {
asyncSubmit(submitBetsFnArray, nextIndex);
}
});
}
};
export const exoticsBet = [
"QN",
"QNB",
"QNW",
"EX",
"EKB",
"EXB",
"EXW",
"EXK",
"TR",
"TRB",
"TRW",
"TRK",
"TKB",
"SU",
"SUB",
"SUK",
"SUW",
"SKB",
"SH5",
"H5W",
"S5K",
"5KB",
"OM",
"OMB",
"OMW",
"TI",
"TIB",
"TIW"
];
export const picksBet = [
"DB",
"GS",
"P3",
"P4",
"P5",
"P6",
"P7",
"P8",
"P9",
"P10",
"A3",
"A4",
"A5",
"A6",
"A7",
"A8",
"A9",
"A10",
"L3",
"L4",
"L5",
"L6",
"L7",
"L8",
"L9",
"L10",
"E12",
"SV"
];
export const buildRacesMatrix = (
raceID: string | undefined,
races: RaceProgram[],
legCount: number
): RaceProgram[] => {
const initialRaceIndex = findIndex(
races,
(element: RaceProgram) => element.id === raceID
);
if (initialRaceIndex >= 0) {
const finalRaceIndex = initialRaceIndex + legCount;
if (
finalRaceIndex <= races.length + 1 &&
finalRaceIndex !== initialRaceIndex
) {
return races.slice(initialRaceIndex, finalRaceIndex);
}
}
return [];
};
export const allLegRunnersSelected = (
column: number,
race: RaceProgram,
selections: string[][],
wagerType: RaceWagerType | undefined
) => {
if (column === null || !selections[column] || !race.bettingInterests) {
return ["nan"];
}
const notScratchedRunnerAvailable =
race.bettingInterests?.reduce((acc: string[], bi: BettingInterest) => {
if (isBiScratched(bi) === false) {
acc.push(`${bi.biNumber}`);
}
return acc;
}, []) || [];
const leg = (selections[column] || []).filter((sel) => !sel.endsWith("B"));
if (wagerType?.isKey) {
const wagerableNumComparison = selections[0][0]
? notScratchedRunnerAvailable.length - 1
: notScratchedRunnerAvailable.length;
return selections[1] && selections[1].length === wagerableNumComparison
? ["all"]
: ["none"];
}
if (leg.length >= notScratchedRunnerAvailable.length) {
return ["all"];
}
return ["none"];
};
export const getRaceSelectedRace = (
matrix: RaceProgram[],
column: number | null
): RaceProgram => {
if (column && column >= 0 && !!matrix[column]) {
return matrix[column];
}
return matrix[0];
};
export const getRaceWithMoreColumns = (matrix: RaceProgram[]): RaceProgram => {
let mostRunners = get(matrix, "[0]", undefined);
if (mostRunners && matrix && matrix.length) {
matrix.forEach((race: RaceProgram) => {
const newRaceBi = get(race, "bettingInterests", []);
const oldRaceBi = get(mostRunners, "bettingInterests", []);
if (newRaceBi.length > oldRaceBi.length) {
mostRunners = race;
}
});
}
return mostRunners;
};
export const getPickRunnerOdds = (bi: BettingInterest | undefined) =>
bi?.currentOdds.numerator
? `${bi?.currentOdds.numerator}${
bi?.currentOdds.denominator ? `/${bi?.currentOdds.denominator}` : ""
}`
: "";
export const isBiScratched = (bi: BettingInterest | undefined) =>
bi?.runners.reduce((acc, runner) => {
if (acc && runner.scratched) {
return true;
}
return false;
}, true);
export const filterRepeatedScratchedFromSelections = (
selections: VisualSelections[],
scratches: string[][]
) =>
scratches?.map((scratchedSelection: string[], index: number) =>
scratchedSelection.filter((item: string) =>
selections[index]?.find((value) => value.number === item)
)
);
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/types.ts
import { IconNames, ToastMessageProps } from "@tvg/design-system";
import { VisualSelections } from "@tvg/ts-types/Bet";
import { SpecialGroupBets } from "@tvg/desktop-bet/src/types";
import { Probable, Timeform } from "@tvg/ts-types/Race";
export enum BetError {
geoComplyTokenRejected = 136524,
geoComplyTokenMissing = 136463,
stateMismatch = 136525
}
export type Race = {
id: string;
raceNumber: string;
mtp: string;
track: {
trackName: string;
trackLocation: {
country: string;
};
};
status: { code: string };
};
export type Status = "SK" | "RO" | "O" | "IC";
export type FavoriteWithIdTracks = {
[code: string]: number;
};
export type Favorite = {
entityDob?: number | null;
entityName: string;
entityType: string;
favoriteId: number;
subscriptions?: FavoriteSubscriptions[];
};
export type FavoriteSubscriptions = {
eventType?: string;
channels?: ChannelsSubscriptions[];
};
export type ChannelsSubscriptions = {
type?: string;
};
export type RaceSurface = {
defaultCondition?: string;
name?: string;
shortName?: string;
};
export interface BlacklistedWagerTypes {
blacklistedBets: string[];
}
export type Selection = {
number: string;
numberColor: string;
saddleColor: string;
};
export type Selections = Array<Selection>;
export type PreferencesType = {
[key: string]: string | object;
};
export type PreferencesPayload = {
preferences: PreferencesType;
gotPreferences: boolean;
};
export type SaddleType = "thoroughbred" | "harness";
export type PlaceBetErrorMessage = {
title: string;
text: string;
buttonType: string;
};
export type PlaceBetError = {
code: number;
message: PlaceBetErrorMessage;
};
export type WtxPlaceBetError = {
response: {
data: {
code: number;
message: string;
};
};
};
export type SavedBets = {
betAmount: number;
betNumber: number;
totalAmount: string;
approxPayout: string;
wagerableRunners: string[] | undefined;
betProbables: Probable[];
fullSelections: VisualSelections[];
specialGroupBets: SpecialGroupBets | undefined;
betSelectionsNumbers: string[][];
};
export interface EmptyMessage {
title: string;
description: string;
}
export interface MyStableMessages {
label: string;
followingLabel: string;
success: string;
error: string;
}
export interface WillPay {
title: string;
description: string;
}
export interface InlinePastPerformanceResultRunners {
finishPosition: number;
finishStatus?: string;
currentOdds: {
numerator?: number;
denominator?: number;
};
timeform: Timeform | null;
favorite: boolean;
}
export interface InlinePastPerformance {
id: number;
date: string;
purse: number;
track: {
code: string;
};
surface: {
shortName: string;
defaultCondition: string;
};
distance: {
code: string;
value: number;
};
raceClass: {
shortName: string;
};
video?: {
replayFileName: string;
mobileAvailable: boolean;
flashAvailable: boolean;
};
results: {
runners: InlinePastPerformanceResultRunners[];
};
numRunners: string;
}
export enum RunnerModifierEnum {
DEFAULT = "default",
ADVANCED = "advanced",
PERFORMANCE = "performance"
}
export enum PickViewOptionsEnum {
QUICK_PICK = "quickPick",
HANDICAPPING = "handicapping"
}
export enum TabSelectionEnum {
RESULT = "result",
RACECARD = "racecard"
}
export enum TabSelectionPoolsNInfoEnum {
INFO_CHANGES = "infoChanges",
PROBABLES = "probables",
POOLS = "pools",
WILL_PAYS = "willPays"
}
export enum FiltersInlinePP {
RECENTRACE = "recentRace",
CURRENTRACE = "currentRace"
}
export interface InlinePPEmptyMessages {
recentRaces: string;
filteredRaces: string;
}
export interface InlinePPMessage {
maxResults: number;
emptyMessages: InlinePPEmptyMessages;
}
export enum RunnerSortOrderEnum {
ASC = "asc",
DESC = "desc"
}
export enum RunnerSortByEnum {
SADDLECLOTH = "biNumber",
ODDS = "currentOddNumeric",
STARTS = "numberOfStarts",
POWER_RATING = "powerRating",
WEIGHT = "weight",
WIN_PERCENTAGE = "winPercentage",
TOP3_PERCENTAGE = "top3WinPercentage",
JT_STARTS = "jockeyTrainerStarts",
JT_WIN_PERCENTAGE = "jockeyTrainerWinPercentage",
JT_TOP3_PERCENTAGE = "jockeyTrainerTop3Percentage",
AVG_SPEED = "avgSpeed",
HIGH_SPEED = "highSpeed",
AVG_CLASS_RATING = "avgClass",
EARLY_PACE = "averagePaceEarly",
MIDDLE_PACE = "averagePaceMiddle",
FINISH_PACE = "averagePaceFinish"
}
export type SortOption = {
label: string;
value: RunnerSortByEnum;
};
export type PreferenceRunnerModifier = {
modifier: RunnerModifierEnum | undefined;
order: RunnerSortOrderEnum | undefined;
sortBy: RunnerSortByEnum | undefined;
};
export type HandicappingTrackDataSource =
| "USGSA"
| "GSA"
| "SRW"
| "RAS"
| "EQB";
export type HandicappingTabValue = "timeform" | "handicapping" | "talentPick";
export interface HandicappingTab {
name: string;
icon: Extract<
IconNames,
"timeForm" | "numberFire" | "badge" | "trackMaster" | "rs" | "tvgPicks"
>;
value: HandicappingTabValue;
}
export type HandicappingTabsMap = Record<
HandicappingTrackDataSource,
HandicappingTab[]
>;
export interface HandicappingModuleMessage {
title?: string;
tabs?: HandicappingTabsMap;
}
export interface RaceWagerSummary {
totalBets: number;
totalAmount: number;
totalGambledCount: number;
totalGambledAmount: number;
}
export interface RepeatBetConfig {
maxAllowed: number;
errorMessage: {
title: string;
text: string;
};
}
export type handicappingRunnerFlagsName = {
flags: {
id: string;
name: string;
}[];
};
export interface TalentPickBet {
existingModalBet: {
title: string;
text: string;
};
}
export interface TrackListMessage {
title: string;
description: string;
}
export interface ForbiddentBettingStates {
blockedStates: [string] | [];
errorMessage: string;
}
export type ToastMessageStore = ToastMessageProps & { id: string };
export type BetslipAccountErrorDefault = {
geolocationError: {
title: string;
message: string;
button: string;
};
accountComplianceError: {
title: string;
message: string;
button: string;
};
termsAndConditionsError: {
button: string;
};
};
export type TracksInfo = {
id: string;
code: string;
name: string;
isFinished: boolean;
numberOfRaces: number;
currentRace: {
id: string;
number: string;
};
};
export type TracksListQuery = {
tracks: TracksInfo[];
};
export type Track = {
id: string;
code: string;
name: string;
isFinished: boolean;
currentRaceNumber: string;
numberOfRaces: number;
};
export type TrackListMediatorSubscription = {
type: string;
payload: {
data: Array<{
id: string;
track: {
code: string;
isFinished: boolean;
numberOfRaces: number;
currentRace: {
number: string;
};
};
}>;
};
};
export enum SourceKeysEnum {
FDTV_PICKS = "FDTV Picks",
TRACKMASTER = "Trackmaster",
NUMBERFIRE = "numberFire",
SELECT_ALL_RUNNERS = "Select all modal",
RACE_CARD = "Race Card",
REPEAT_BET_RACE_CARD = "repeat_bet_race_card",
REPEAT_BET_MY_BETS = "repeat_bet_my_bets"
}
export type SourceValue =
| "fdtv_race_card"
| "trackmaster_race_card"
| "numberfire_race_card"
| "repeat_bet_race_card"
| "repeat_bet_my_bets"
| "Race Card";
export interface AlternateSelectionsMessages {
infoModal: {
title: string;
subtitle: string;
description: string;
};
betslipButton: string;
alternatesModal: {
title: string;
alert: {
title: string;
description: string;
};
buttons: {
cancel: string;
apply: string;
};
};
}
export type BetPromoBannerContent = {
cta_label: string;
cta_url: {
url: string;
};
banner_image: {
alt: string;
filename: string;
};
};
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/utils/general.ts
import tvgConf from "@tvg/conf";
import { SourceKeysEnum, SourceValue } from "../types";
export const isFdr = () => tvgConf().brand === "fdr";
export const delay = (helper: { cancel: () => void }, ms: number) =>
new Promise((resolve, reject) => {
const timer = setTimeout(() => resolve("run"), ms);
helper.cancel = () => {
clearTimeout(timer);
reject("cancelled");
};
});
export const isHongKongRaces = (code: string) =>
code.includes("HKS") || code.includes("HKH");
export const buildQaLabel = (values: string[], separator: string = "-") =>
values.join(separator);
export const buildSelectionSource = (
origin: SourceKeysEnum | undefined,
defaultValue: SourceValue = "Race Card"
): SourceValue => {
if (origin === undefined) {
return defaultValue;
}
const originMap = new Map<SourceKeysEnum, SourceValue>([
[SourceKeysEnum.FDTV_PICKS, "fdtv_race_card"],
[SourceKeysEnum.TRACKMASTER, "trackmaster_race_card"],
[SourceKeysEnum.NUMBERFIRE, "numberfire_race_card"],
[SourceKeysEnum.SELECT_ALL_RUNNERS, "Race Card"],
[SourceKeysEnum.RACE_CARD, "Race Card"],
[SourceKeysEnum.REPEAT_BET_RACE_CARD, "repeat_bet_race_card"],
[SourceKeysEnum.REPEAT_BET_MY_BETS, "repeat_bet_my_bets"]
]);
// When we guarantee a true extensive 1 to 1 map with no undefined allowed
// this verification won't theoretically be necessary
return originMap.get(origin) ?? defaultValue;
};
export const getFdtvType = (pathname: string) => {
if (pathname) {
const isFdtv = pathname.includes("/live");
if (isFdtv) {
return pathname.includes("TVG2") ? "fdr_tv" : "fdtv_plus";
}
}
return "no_fdtv";
};
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/hooks/useSetBetSelections/utils.ts
import { WagerTypeCodesEnum } from "@tvg/ts-types/Wager";
import { RaceProgram, RaceWagerType } from "@tvg/ts-types/Race";
import BetUtils from "@tvg/utils/betSelection";
import { get } from "lodash";
import { RunnerBI } from "../useGetRunnerFromBI";
import { Selections } from "../../types";
export const isDuplicate = (selections: String[], runner: RunnerBI) =>
selections.some((item) => +item === +runner.biNumber);
export const getType: { [id: string]: number } = {
win: 0,
place: 1,
show: 2
};
export const getACrossTheBoardLength: { [id: string]: number } = {
[WagerTypeCodesEnum.WIN_PLACE]: 2,
[WagerTypeCodesEnum.PLACE_SHOW]: 2,
[WagerTypeCodesEnum.WIN_SHOW]: 2,
[WagerTypeCodesEnum.WIN_PLACE_SHOW]: 3
};
export const getEmptySelectionsMatrix = (
race: RaceProgram,
selectedBetTypeCode: WagerTypeCodesEnum
): string[][] => {
const activeWagerType = (race.wagerTypes || []).find(
// @ts-ignore
(wagerType) => wagerType.type.code === selectedBetTypeCode
);
// @ts-ignore
return BetUtils.setMatrixSizeByColumnCount(
get(activeWagerType, "columnCount", 1)
);
};
export const parseSimpleBets = (betSelections: string[][]): Selections[] =>
betSelections.map((selections: string[]) =>
selections.map((selection: string) => ({
number: selection,
saddleColor: "",
numberColor: ""
}))
);
export const getNumberOfSelections = (selections: string[][]) =>
(selections || []).filter((valid) => valid).flat().length;
export const filterScratchedSelections = (
selections: string[][],
scratchesList: string[][],
race: RaceProgram,
races: RaceProgram[],
selectedBetType: RaceWagerType
) => {
// find the initialRaceIndex for the leg picks
const initialRaceIndex = races.findIndex(
(element: RaceProgram) => element.id === race.id
);
// pick the scratches from the selections ...
const scratchSelections = [...scratchesList];
const filteredSelections = (selections || []).map(
(currentSelections: string[], index: number) =>
currentSelections.filter((selection) => {
const isAlternate = selection.endsWith("B");
const currentRace =
selectedBetType.legCount > 1 ? races[initialRaceIndex + index] : race;
const bettingInterests = currentRace?.bettingInterests;
const selectionBi = (bettingInterests || []).find((bettingInterest) => {
const biNumber = bettingInterest.biNumber.toString();
return (
biNumber === selection ||
(isAlternate && `${biNumber}B` === selection)
);
});
const selectionBiRunners = selectionBi?.runners || [];
const selectionBiRunnersScratched = selectionBiRunners.filter(
(runner) => runner.scratched
);
// update scratchSelections
selectionBiRunnersScratched.forEach((runner) => {
if (
scratchSelections[index] &&
!scratchSelections[index].includes(runner.runnerId)
) {
scratchSelections[index] = [
...scratchSelections[index],
runner.runnerId
];
}
});
const isSelectionValid =
selectionBiRunnersScratched.length === 0 ||
selectionBiRunners.length > selectionBiRunnersScratched.length;
return isSelectionValid;
})
);
return {
filteredSelections,
scratchSelections
};
};
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/utils/gtm/betSlipUndo.ts
import mediator from "@tvg/mediator";
export const betSlipUndoGTMEvent = () => {
mediator.base.dispatch({ type: "BETSLIP:UNDO" });
};
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/utils/wagersTypes/index.ts
import { get, flatMap, map, sortBy, trim, join } from "lodash";
import { RaceStatusEnum } from "@tvg/ts-types/Race";
const specialTypesMap: Record<string, string> = {
FUTURE: "future",
ADVANCE: "advance",
NONCONSECUTIVEPICK: "special_pick",
"ADVANCE,NONCONSECUTIVEPICK": "advance_special_pick",
"FUTURE,NONCONSECUTIVEPICK": "future_special_pick"
};
export const getSpecialWagerType = (race: unknown): string => {
const specialCardTypes = get(race, "track.specialCardTypes", []);
const normalized = join(
sortBy(
flatMap(specialCardTypes, (type) =>
map(type.specialCardTypeName.split(","), trim)
)
),
","
);
return specialTypesMap[normalized] || "none";
};
export const getReadableRaceStatus = (
code: RaceStatusEnum | string
): string => {
const statusMap: Record<RaceStatusEnum | string, string> = {
[RaceStatusEnum.OPEN]: "open",
[RaceStatusEnum.UP_NEXT]: "up_next",
[RaceStatusEnum.RACE_OFFICIAL]: "race_official",
[RaceStatusEnum.RACE_OFF]: "race_off",
[RaceStatusEnum.MANUALLY_OPENED]: "manually_open",
[RaceStatusEnum.MANUALLY_CLOSED]: "manually_closed"
};
return statusMap[code] ?? "";
};
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/utils/betParamsUtils.ts
import { RaceProgram, RaceWagerType } from "@tvg/ts-types/Race";
import { get, isNumber } from "lodash";
import BetUtils from "@tvg/utils/betSelection";
import { WagerTypeCodesEnum, WagerTypeWpsCodesEnum } from "@tvg/ts-types/Wager";
interface GetFinalSelections {
userSelection: string[][] | undefined;
finalSelections: string[][];
finalWagerType: RaceWagerType | undefined;
OriginalWagerType: RaceWagerType | undefined;
}
export type betParamsType = {
betType?: string;
betAmount?: number;
betSelections?: string[][] | undefined;
};
// handle selection
const getSelectionsFromParams = (
params: URLSearchParams
): string[][] | undefined => {
// handle old selection model
if (params.get("betselections")) {
// @ts-ignore
const userSelections = params
.get("betselections")
.split("|")
.map((selections) =>
Object.keys(
selections.split(",").reduce((acc, value) => {
const parsedNumber = parseInt(value, 10);
// @ts-ignore
acc[`${parsedNumber}`] = 0;
return acc;
}, {})
)
);
return userSelections;
}
// handle selectedRunner
if (params.get("selectedRunner")) {
// @ts-ignore
return [[params.get("selectedRunner")]];
}
// handle mep selection model
const keys: string[] = [];
params.forEach((__value, key) => keys.push(key));
const selectionsParams = keys.filter(
(entry: string) => entry && entry.startsWith("s") && isNumber(+entry[1])
);
if (selectionsParams.length) {
const selections = selectionsParams.map((selection) =>
Object.keys(
// @ts-ignore
params
.get(selection)
.split(",")
.reduce((acc, value) => {
// @ts-ignore
acc[`${value}`] = 0;
return acc;
}, {})
)
);
return selections;
}
return undefined;
};
export const removeBetParams = (params: URLSearchParams) => {
params.delete("wt");
params.delete("betselections");
params.delete("selectedRunner");
params.delete("betAmount");
params.delete("bet");
params.delete("betType");
// handle mep selection model
const keys: string[] = [];
params.forEach((__value, key) => keys.push(key));
const selectionsParams = keys.filter(
(entry: string) => entry && entry.startsWith("s") && isNumber(+entry[1])
);
selectionsParams.forEach((entry) => params.delete(`${entry}`));
};
export const hasParams = (arg: betParamsType) =>
arg.betType !== undefined ||
arg.betAmount !== undefined ||
arg.betSelections !== undefined;
const betColumns: { [key in WagerTypeWpsCodesEnum]: Array<number> } = {
[WagerTypeWpsCodesEnum.WIN]: [0],
[WagerTypeWpsCodesEnum.WIN_PLACE]: [0, 1],
[WagerTypeWpsCodesEnum.WIN_SHOW]: [0, 2],
[WagerTypeWpsCodesEnum.PLACE]: [1],
[WagerTypeWpsCodesEnum.PLACE_SHOW]: [1, 2],
[WagerTypeWpsCodesEnum.SHOW]: [2],
[WagerTypeWpsCodesEnum.WIN_PLACE_SHOW]: [0, 1, 2]
};
export const getFinalSelections = ({
userSelection,
finalSelections,
finalWagerType,
OriginalWagerType
}: GetFinalSelections): string[][] | undefined => {
if (!userSelection) {
return undefined;
}
if (finalSelections.length === userSelection.length) {
return userSelection;
}
// wps special fill case
if (finalWagerType && userSelection.length === 1) {
const columnDifference = [
WagerTypeCodesEnum.WIN_SHOW,
WagerTypeCodesEnum.PLACE_SHOW
].includes(finalWagerType.type.code)
? 1
: 0;
const wagerType = OriginalWagerType
? OriginalWagerType.type.code
: finalWagerType.type.code;
// find correct fill array
const fillPositions = get(betColumns, wagerType, []);
// fill array
fillPositions.forEach((column: number, index: number) => {
if (columnDifference !== 0 && column !== index) {
finalSelections[column - columnDifference] = userSelection[0];
} else {
finalSelections[column] = userSelection[0];
}
});
return finalSelections;
}
return userSelection;
};
export const getBetFromParams = (
params: URLSearchParams,
currentRace: RaceProgram
): betParamsType => {
// handle bet type
let betType: number | string | null | undefined =
params.get("wt") || params.get("betType");
let originalWagerType: RaceWagerType | undefined;
let searchWagerType: RaceWagerType | undefined;
// eslint-disable-next-line no-restricted-globals
if (betType) {
searchWagerType = get(currentRace, "wagerTypes", []).find(
(wt: RaceWagerType) => {
if (
wt.type.code !== betType &&
wt.type.id !== parseInt(`${betType}`, 10)
) {
// original bet type from url ( not grouped)
originalWagerType = wt.types?.find(
(wtIn: RaceWagerType) =>
wtIn.type.code === betType ||
wtIn.type.id === parseInt(`${betType}`, 10)
);
return !!originalWagerType;
}
return true;
}
);
betType = searchWagerType?.type.id;
}
// handle bet amount
const betAmount = params.get("betAmount") || params.get("bet");
return {
betType: betType ? `${betType}` : undefined,
betAmount: betAmount ? +betAmount : undefined,
betSelections: getFinalSelections({
userSelection: getSelectionsFromParams(params),
finalSelections: BetUtils.setMatrixSizeByColumnCount(
get(searchWagerType, "columnCount", 1)
),
finalWagerType: searchWagerType,
OriginalWagerType: originalWagerType
})
};
};
export default {
getBetFromParams,
hasParams,
getSelectionsFromParams,
removeBetParams
};
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/graphql/fragments/WagerTypes.ts
import { gql } from "@apollo/client";
const WagerTypesFragments = {
entry: gql`
fragment WagerTypes on Race {
wagerTypes {
positionCount
minWagerAmount
wagerAmounts
columnCount
legCount
isBox
isKey
isWheel
unitedWagerTypeCode
allowAlternateSelection
type {
id
name
code
}
group {
id
name
code
}
}
}
`
};
export default WagerTypesFragments;
webpack://frontend-mybets/../../node_modules/graphql-tag/lib/index.js
import { __assign } from "tslib";
import { parse } from 'graphql';
var docCache = new Map();
var fragmentSourceMap = new Map();
var printFragmentWarnings = true;
var experimentalFragmentVariables = false;
function normalize(string) {
return string.replace(/[\s,]+/g, ' ').trim();
}
function cacheKeyFromLoc(loc) {
return normalize(loc.source.body.substring(loc.start, loc.end));
}
function processFragments(ast) {
var seenKeys = new Set();
var definitions = [];
ast.definitions.forEach(function (fragmentDefinition) {
if (fragmentDefinition.kind === 'FragmentDefinition') {
var fragmentName = fragmentDefinition.name.value;
var sourceKey = cacheKeyFromLoc(fragmentDefinition.loc);
var sourceKeySet = fragmentSourceMap.get(fragmentName);
if (sourceKeySet && !sourceKeySet.has(sourceKey)) {
if (printFragmentWarnings) {
console.warn("Warning: fragment with name " + fragmentName + " already exists.\n"
+ "graphql-tag enforces all fragment names across your application to be unique; read more about\n"
+ "this in the docs: http://dev.apollodata.com/core/fragments.html#unique-names");
}
}
else if (!sourceKeySet) {
fragmentSourceMap.set(fragmentName, sourceKeySet = new Set);
}
sourceKeySet.add(sourceKey);
if (!seenKeys.has(sourceKey)) {
seenKeys.add(sourceKey);
definitions.push(fragmentDefinition);
}
}
else {
definitions.push(fragmentDefinition);
}
});
return __assign(__assign({}, ast), { definitions: definitions });
}
function stripLoc(doc) {
var workSet = new Set(doc.definitions);
workSet.forEach(function (node) {
if (node.loc)
delete node.loc;
Object.keys(node).forEach(function (key) {
var value = node[key];
if (value && typeof value === 'object') {
workSet.add(value);
}
});
});
var loc = doc.loc;
if (loc) {
delete loc.startToken;
delete loc.endToken;
}
return doc;
}
function parseDocument(source) {
var cacheKey = normalize(source);
if (!docCache.has(cacheKey)) {
var parsed = parse(source, {
experimentalFragmentVariables: experimentalFragmentVariables
});
if (!parsed || parsed.kind !== 'Document') {
throw new Error('Not a valid GraphQL document.');
}
docCache.set(cacheKey, stripLoc(processFragments(parsed)));
}
return docCache.get(cacheKey);
}
export function gql(literals) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
if (typeof literals === 'string') {
literals = [literals];
}
var result = literals[0];
args.forEach(function (arg, i) {
if (arg && arg.kind === 'Document') {
result += arg.loc.source.body;
}
else {
result += arg;
}
result += literals[i + 1];
});
return parseDocument(result);
}
export function resetCaches() {
docCache.clear();
fragmentSourceMap.clear();
}
export function disableFragmentWarnings() {
printFragmentWarnings = false;
}
export function enableExperimentalFragmentVariables() {
experimentalFragmentVariables = true;
}
export function disableExperimentalFragmentVariables() {
experimentalFragmentVariables = false;
}
var extras = {
gql: gql,
resetCaches: resetCaches,
disableFragmentWarnings: disableFragmentWarnings,
enableExperimentalFragmentVariables: enableExperimentalFragmentVariables,
disableExperimentalFragmentVariables: disableExperimentalFragmentVariables
};
(function (gql_1) {
gql_1.gql = extras.gql, gql_1.resetCaches = extras.resetCaches, gql_1.disableFragmentWarnings = extras.disableFragmentWarnings, gql_1.enableExperimentalFragmentVariables = extras.enableExperimentalFragmentVariables, gql_1.disableExperimentalFragmentVariables = extras.disableExperimentalFragmentVariables;
})(gql || (gql = {}));
gql["default"] = gql;
export default gql;
//# sourceMappingURL=index.js.map
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/graphql/fragments/TimeAndStatus.ts
import gql from "graphql-tag";
const TimeAndStatusFragments = {
entry: gql`
fragment TimeAndStatus on Race {
mtp
postTime
status {
code
}
raceDate
}
`
};
export default TimeAndStatusFragments;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/graphql/fragments/changes.ts
import { gql } from "@apollo/client";
const ChangesFragments = {
entry: gql`
fragment Changes on Race {
changes: changes {
surface {
course {
oldValue
newValue
date
}
distance {
date
oldValue {
value
code
name
shortName
}
newValue {
value
code
name
shortName
}
}
tempRailDistance {
oldValue
newValue
date
}
condition {
oldValue
newValue
date
}
}
horse {
scratched {
runnerId
horseName
date
scratched
reason
}
jockey {
runnerId
horseName
date
oldValue
newValue
}
}
}
}
`
};
export default ChangesFragments;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/graphql/fragments/RaceDetails.ts
import { gql } from "@apollo/client";
import ChangesFragments from "./changes";
const RaceDetailsFragments = {
entry: gql`
fragment RaceDetails on Race {
raceNumber: number
description
specialCardSourceRace {
raceDate
trackCode
trackName
raceNumber
}
distance
purse
isGreyhound
highlighted(product: $product, device: $device, brand: $brand) {
description
style
}
numRunners
numWagerableRunners
claimingPrice
surface {
name
shortName
defaultCondition
}
type {
name
code
shortName
}
raceClass {
name
shortName
}
talentPicks {
id
}
timeform {
analystVerdict
}
...Changes
}
${ChangesFragments.entry}
`
};
export default RaceDetailsFragments;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/graphql/fragments/Video.ts
import { gql } from "@apollo/client";
const VideoFragments = {
entry: gql`
fragment Video on Race {
video {
liveStreaming
onTvg
onTvg2
streams
hasReplay
replayFileName
mobileAvailable
isStreamHighDefinition
}
}
`
};
export default VideoFragments;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/graphql/fragments/HandicappingFragment.ts
import { gql } from "@apollo/client";
const HandicappingFragments = {
entry: gql`
fragment handicappingFragment on Runner {
ownerName
sire
damSire
dam
handicapping {
speedAndClass {
avgClassRating
highSpeed
avgSpeed
lastClassRating
avgDistance
}
averagePace {
finish
numRaces
middle
early
}
jockeyTrainer {
places
jockeyName
trainerName
shows
wins
starts
}
snapshot {
powerRating
daysOff
horseWins
horseStarts
}
pastResults {
totalNumberOfStarts
numberOfFirstPlace
numberOfSecondPlace
numberOfThirdPlace
winPercentage
winPercentageRanking
top3Percentage
top3PercentageRanking
}
}
}
`
};
export default HandicappingFragments;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/graphql/fragments/TimeformFragment.ts
import { gql } from "@apollo/client";
const TimeformFragments = {
entry: gql`
fragment timeformFragment on Runner {
timeform {
analystsComments
silkUrl
silkUrlSvg
freePick {
number
info
}
flags {
horseInFocus
warningHorse
jockeyUplift
trainerUplift
horsesForCoursePos
horsesForCourseNeg
hotTrainer
coldTrainer
highestLastSpeedRating
sectionalFlag
significantImprover
jockeyInForm
clearTopRated
interestingJockeyBooking
firstTimeBlinkers
}
}
}
`
};
export default TimeformFragments;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/graphql/fragments/BettingInterestsSubscription.ts
import { gql } from "@apollo/client";
import HandicappingFragments from "./HandicappingFragment";
import TimeformFragments from "./TimeformFragment";
const BettingInterestsFragments = {
entry: gql`
fragment BettingInterests on Race {
bettingInterests {
biNumber
favorite
currentOdds {
numerator
denominator
}
morningLineOdds {
numerator
denominator
}
recentOdds(pages: [{ current: 0, results: 4 }]) {
trending
odd
}
biPools {
wagerType {
id
code
name
}
poolRunnersData {
amount
}
}
runners {
runnerId
scratched
jockey
trainer
horseName
hasJockeyChanges
...timeformFragment
...handicappingFragment
handicapping {
freePick {
number
info
}
}
}
}
}
${HandicappingFragments.entry}
${TimeformFragments.entry}
`
};
export default BettingInterestsFragments;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/graphql/fragments/Probables.ts
import { gql } from "@apollo/client";
const ProbablesFragment = {
entry: gql`
fragment Probables on Race {
probables {
amount
minWagerAmount
wagerType {
id
code
name
}
betCombos {
runner1
runner2
payout
}
}
}
`
};
export default ProbablesFragment;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/graphql/fragments/RacePools.ts
import { gql } from "@apollo/client";
const RacePoolsFragment = {
entry: gql`
fragment RacePools on Race {
racePools {
wagerType {
id
code
name
}
amount
}
}
`
};
export default RacePoolsFragment;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/graphql/fragments/ResultsFragment.ts
import gql from "graphql-tag";
const ResultsFragments = {
entry: gql`
fragment Results on Race {
results {
runners {
betAmount
biNumber
finishPosition
placePayoff
runnerName
showPayoff
winPayoff
runnerNumber
timeform {
postRaceReport
accBeatenDistance
accBeatenDistanceStatus
}
}
payoffs {
selections {
payoutAmount
selection
}
wagerAmount
wagerType {
code
name
}
}
winningTime
}
}
`
};
export default ResultsFragments;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/graphql/fragments/Promos.ts
import { gql } from "@apollo/client";
const PromosFragments = {
entry: gql`
fragment Promos on Race {
promos(product: $product, brand: $brand) {
rootParentPromoID
isAboveTheLine
promoPath
isPromoTagShown
}
}
`
};
export default PromosFragments;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/graphql/queries/RaceProgramSubscription.ts
import { gql } from "@apollo/client";
import WagerTypesFragments from "../fragments/WagerTypes";
import TimeAndStatusFragments from "../fragments/TimeAndStatus";
import RaceDetailsFragments from "../fragments/RaceDetails";
import VideoFragments from "../fragments/Video";
import BettingInterestsFragments from "../fragments/BettingInterestsSubscription";
import ProbablesFragment from "../fragments/Probables";
import RacePoolsFragments from "../fragments/RacePools";
import ResultsFragments from "../fragments/ResultsFragment";
import PromosFragments from "../fragments/Promos";
export const GET_RACE_PROGRAM_SUBSCRIPTION = gql`
subscription raceUpdateByTvgRaceIds(
$wagerProfile: String!
$product: String
$device: String
$brand: String
$tvgRaceIds: [Long!]
) {
raceUpdateByTvgRaceIds(profile: $wagerProfile, tvgRaceIds: $tvgRaceIds) {
id
tvgRaceId
...RaceDetails
...TimeAndStatus
...Video
...WagerTypes
...BettingInterests
...Probables
...RacePools
...Results
...Promos
}
}
${WagerTypesFragments.entry}
${TimeAndStatusFragments.entry}
${RaceDetailsFragments.entry}
${VideoFragments.entry}
${BettingInterestsFragments.entry}
${ProbablesFragment.entry}
${RacePoolsFragments.entry}
${ResultsFragments.entry}
${PromosFragments.entry}
`;
webpack://frontend-mybets/../../node_modules/apollo-utilities/lib/bundle.esm.js
import { visit } from 'graphql/language/visitor';
import { InvariantError, invariant } from 'ts-invariant';
import { __assign, __spreadArrays } from 'tslib';
import stringify from 'fast-json-stable-stringify';
export { equal as isEqual } from '@wry/equality';
function isScalarValue(value) {
return ['StringValue', 'BooleanValue', 'EnumValue'].indexOf(value.kind) > -1;
}
function isNumberValue(value) {
return ['IntValue', 'FloatValue'].indexOf(value.kind) > -1;
}
function isStringValue(value) {
return value.kind === 'StringValue';
}
function isBooleanValue(value) {
return value.kind === 'BooleanValue';
}
function isIntValue(value) {
return value.kind === 'IntValue';
}
function isFloatValue(value) {
return value.kind === 'FloatValue';
}
function isVariable(value) {
return value.kind === 'Variable';
}
function isObjectValue(value) {
return value.kind === 'ObjectValue';
}
function isListValue(value) {
return value.kind === 'ListValue';
}
function isEnumValue(value) {
return value.kind === 'EnumValue';
}
function isNullValue(value) {
return value.kind === 'NullValue';
}
function valueToObjectRepresentation(argObj, name, value, variables) {
if (isIntValue(value) || isFloatValue(value)) {
argObj[name.value] = Number(value.value);
}
else if (isBooleanValue(value) || isStringValue(value)) {
argObj[name.value] = value.value;
}
else if (isObjectValue(value)) {
var nestedArgObj_1 = {};
value.fields.map(function (obj) {
return valueToObjectRepresentation(nestedArgObj_1, obj.name, obj.value, variables);
});
argObj[name.value] = nestedArgObj_1;
}
else if (isVariable(value)) {
var variableValue = (variables || {})[value.name.value];
argObj[name.value] = variableValue;
}
else if (isListValue(value)) {
argObj[name.value] = value.values.map(function (listValue) {
var nestedArgArrayObj = {};
valueToObjectRepresentation(nestedArgArrayObj, name, listValue, variables);
return nestedArgArrayObj[name.value];
});
}
else if (isEnumValue(value)) {
argObj[name.value] = value.value;
}
else if (isNullValue(value)) {
argObj[name.value] = null;
}
else {
throw process.env.NODE_ENV === "production" ? new InvariantError(17) : new InvariantError("The inline argument \"" + name.value + "\" of kind \"" + value.kind + "\"" +
'is not supported. Use variables instead of inline arguments to ' +
'overcome this limitation.');
}
}
function storeKeyNameFromField(field, variables) {
var directivesObj = null;
if (field.directives) {
directivesObj = {};
field.directives.forEach(function (directive) {
directivesObj[directive.name.value] = {};
if (directive.arguments) {
directive.arguments.forEach(function (_a) {
var name = _a.name, value = _a.value;
return valueToObjectRepresentation(directivesObj[directive.name.value], name, value, variables);
});
}
});
}
var argObj = null;
if (field.arguments && field.arguments.length) {
argObj = {};
field.arguments.forEach(function (_a) {
var name = _a.name, value = _a.value;
return valueToObjectRepresentation(argObj, name, value, variables);
});
}
return getStoreKeyName(field.name.value, argObj, directivesObj);
}
var KNOWN_DIRECTIVES = [
'connection',
'include',
'skip',
'client',
'rest',
'export',
];
function getStoreKeyName(fieldName, args, directives) {
if (directives &&
directives['connection'] &&
directives['connection']['key']) {
if (directives['connection']['filter'] &&
directives['connection']['filter'].length > 0) {
var filterKeys = directives['connection']['filter']
? directives['connection']['filter']
: [];
filterKeys.sort();
var queryArgs_1 = args;
var filteredArgs_1 = {};
filterKeys.forEach(function (key) {
filteredArgs_1[key] = queryArgs_1[key];
});
return directives['connection']['key'] + "(" + JSON.stringify(filteredArgs_1) + ")";
}
else {
return directives['connection']['key'];
}
}
var completeFieldName = fieldName;
if (args) {
var stringifiedArgs = stringify(args);
completeFieldName += "(" + stringifiedArgs + ")";
}
if (directives) {
Object.keys(directives).forEach(function (key) {
if (KNOWN_DIRECTIVES.indexOf(key) !== -1)
return;
if (directives[key] && Object.keys(directives[key]).length) {
completeFieldName += "@" + key + "(" + JSON.stringify(directives[key]) + ")";
}
else {
completeFieldName += "@" + key;
}
});
}
return completeFieldName;
}
function argumentsObjectFromField(field, variables) {
if (field.arguments && field.arguments.length) {
var argObj_1 = {};
field.arguments.forEach(function (_a) {
var name = _a.name, value = _a.value;
return valueToObjectRepresentation(argObj_1, name, value, variables);
});
return argObj_1;
}
return null;
}
function resultKeyNameFromField(field) {
return field.alias ? field.alias.value : field.name.value;
}
function isField(selection) {
return selection.kind === 'Field';
}
function isInlineFragment(selection) {
return selection.kind === 'InlineFragment';
}
function isIdValue(idObject) {
return idObject &&
idObject.type === 'id' &&
typeof idObject.generated === 'boolean';
}
function toIdValue(idConfig, generated) {
if (generated === void 0) { generated = false; }
return __assign({ type: 'id', generated: generated }, (typeof idConfig === 'string'
? { id: idConfig, typename: undefined }
: idConfig));
}
function isJsonValue(jsonObject) {
return (jsonObject != null &&
typeof jsonObject === 'object' &&
jsonObject.type === 'json');
}
function defaultValueFromVariable(node) {
throw process.env.NODE_ENV === "production" ? new InvariantError(18) : new InvariantError("Variable nodes are not supported by valueFromNode");
}
function valueFromNode(node, onVariable) {
if (onVariable === void 0) { onVariable = defaultValueFromVariable; }
switch (node.kind) {
case 'Variable':
return onVariable(node);
case 'NullValue':
return null;
case 'IntValue':
return parseInt(node.value, 10);
case 'FloatValue':
return parseFloat(node.value);
case 'ListValue':
return node.values.map(function (v) { return valueFromNode(v, onVariable); });
case 'ObjectValue': {
var value = {};
for (var _i = 0, _a = node.fields; _i < _a.length; _i++) {
var field = _a[_i];
value[field.name.value] = valueFromNode(field.value, onVariable);
}
return value;
}
default:
return node.value;
}
}
function getDirectiveInfoFromField(field, variables) {
if (field.directives && field.directives.length) {
var directiveObj_1 = {};
field.directives.forEach(function (directive) {
directiveObj_1[directive.name.value] = argumentsObjectFromField(directive, variables);
});
return directiveObj_1;
}
return null;
}
function shouldInclude(selection, variables) {
if (variables === void 0) { variables = {}; }
return getInclusionDirectives(selection.directives).every(function (_a) {
var directive = _a.directive, ifArgument = _a.ifArgument;
var evaledValue = false;
if (ifArgument.value.kind === 'Variable') {
evaledValue = variables[ifArgument.value.name.value];
process.env.NODE_ENV === "production" ? invariant(evaledValue !== void 0, 13) : invariant(evaledValue !== void 0, "Invalid variable referenced in @" + directive.name.value + " directive.");
}
else {
evaledValue = ifArgument.value.value;
}
return directive.name.value === 'skip' ? !evaledValue : evaledValue;
});
}
function getDirectiveNames(doc) {
var names = [];
visit(doc, {
Directive: function (node) {
names.push(node.name.value);
},
});
return names;
}
function hasDirectives(names, doc) {
return getDirectiveNames(doc).some(function (name) { return names.indexOf(name) > -1; });
}
function hasClientExports(document) {
return (document &&
hasDirectives(['client'], document) &&
hasDirectives(['export'], document));
}
function isInclusionDirective(_a) {
var value = _a.name.value;
return value === 'skip' || value === 'include';
}
function getInclusionDirectives(directives) {
return directives ? directives.filter(isInclusionDirective).map(function (directive) {
var directiveArguments = directive.arguments;
var directiveName = directive.name.value;
process.env.NODE_ENV === "production" ? invariant(directiveArguments && directiveArguments.length === 1, 14) : invariant(directiveArguments && directiveArguments.length === 1, "Incorrect number of arguments for the @" + directiveName + " directive.");
var ifArgument = directiveArguments[0];
process.env.NODE_ENV === "production" ? invariant(ifArgument.name && ifArgument.name.value === 'if', 15) : invariant(ifArgument.name && ifArgument.name.value === 'if', "Invalid argument for the @" + directiveName + " directive.");
var ifValue = ifArgument.value;
process.env.NODE_ENV === "production" ? invariant(ifValue &&
(ifValue.kind === 'Variable' || ifValue.kind === 'BooleanValue'), 16) : invariant(ifValue &&
(ifValue.kind === 'Variable' || ifValue.kind === 'BooleanValue'), "Argument for the @" + directiveName + " directive must be a variable or a boolean value.");
return { directive: directive, ifArgument: ifArgument };
}) : [];
}
function getFragmentQueryDocument(document, fragmentName) {
var actualFragmentName = fragmentName;
var fragments = [];
document.definitions.forEach(function (definition) {
if (definition.kind === 'OperationDefinition') {
throw process.env.NODE_ENV === "production" ? new InvariantError(11) : new InvariantError("Found a " + definition.operation + " operation" + (definition.name ? " named '" + definition.name.value + "'" : '') + ". " +
'No operations are allowed when using a fragment as a query. Only fragments are allowed.');
}
if (definition.kind === 'FragmentDefinition') {
fragments.push(definition);
}
});
if (typeof actualFragmentName === 'undefined') {
process.env.NODE_ENV === "production" ? invariant(fragments.length === 1, 12) : invariant(fragments.length === 1, "Found " + fragments.length + " fragments. `fragmentName` must be provided when there is not exactly 1 fragment.");
actualFragmentName = fragments[0].name.value;
}
var query = __assign(__assign({}, document), { definitions: __spreadArrays([
{
kind: 'OperationDefinition',
operation: 'query',
selectionSet: {
kind: 'SelectionSet',
selections: [
{
kind: 'FragmentSpread',
name: {
kind: 'Name',
value: actualFragmentName,
},
},
],
},
}
], document.definitions) });
return query;
}
function assign(target) {
var sources = [];
for (var _i = 1; _i < arguments.length; _i++) {
sources[_i - 1] = arguments[_i];
}
sources.forEach(function (source) {
if (typeof source === 'undefined' || source === null) {
return;
}
Object.keys(source).forEach(function (key) {
target[key] = source[key];
});
});
return target;
}
function getMutationDefinition(doc) {
checkDocument(doc);
var mutationDef = doc.definitions.filter(function (definition) {
return definition.kind === 'OperationDefinition' &&
definition.operation === 'mutation';
})[0];
process.env.NODE_ENV === "production" ? invariant(mutationDef, 1) : invariant(mutationDef, 'Must contain a mutation definition.');
return mutationDef;
}
function checkDocument(doc) {
process.env.NODE_ENV === "production" ? invariant(doc && doc.kind === 'Document', 2) : invariant(doc && doc.kind === 'Document', "Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a \"gql\" tag? http://docs.apollostack.com/apollo-client/core.html#gql");
var operations = doc.definitions
.filter(function (d) { return d.kind !== 'FragmentDefinition'; })
.map(function (definition) {
if (definition.kind !== 'OperationDefinition') {
throw process.env.NODE_ENV === "production" ? new InvariantError(3) : new InvariantError("Schema type definitions not allowed in queries. Found: \"" + definition.kind + "\"");
}
return definition;
});
process.env.NODE_ENV === "production" ? invariant(operations.length <= 1, 4) : invariant(operations.length <= 1, "Ambiguous GraphQL document: contains " + operations.length + " operations");
return doc;
}
function getOperationDefinition(doc) {
checkDocument(doc);
return doc.definitions.filter(function (definition) { return definition.kind === 'OperationDefinition'; })[0];
}
function getOperationDefinitionOrDie(document) {
var def = getOperationDefinition(document);
process.env.NODE_ENV === "production" ? invariant(def, 5) : invariant(def, "GraphQL document is missing an operation");
return def;
}
function getOperationName(doc) {
return (doc.definitions
.filter(function (definition) {
return definition.kind === 'OperationDefinition' && definition.name;
})
.map(function (x) { return x.name.value; })[0] || null);
}
function getFragmentDefinitions(doc) {
return doc.definitions.filter(function (definition) { return definition.kind === 'FragmentDefinition'; });
}
function getQueryDefinition(doc) {
var queryDef = getOperationDefinition(doc);
process.env.NODE_ENV === "production" ? invariant(queryDef && queryDef.operation === 'query', 6) : invariant(queryDef && queryDef.operation === 'query', 'Must contain a query definition.');
return queryDef;
}
function getFragmentDefinition(doc) {
process.env.NODE_ENV === "production" ? invariant(doc.kind === 'Document', 7) : invariant(doc.kind === 'Document', "Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a \"gql\" tag? http://docs.apollostack.com/apollo-client/core.html#gql");
process.env.NODE_ENV === "production" ? invariant(doc.definitions.length <= 1, 8) : invariant(doc.definitions.length <= 1, 'Fragment must have exactly one definition.');
var fragmentDef = doc.definitions[0];
process.env.NODE_ENV === "production" ? invariant(fragmentDef.kind === 'FragmentDefinition', 9) : invariant(fragmentDef.kind === 'FragmentDefinition', 'Must be a fragment definition.');
return fragmentDef;
}
function getMainDefinition(queryDoc) {
checkDocument(queryDoc);
var fragmentDefinition;
for (var _i = 0, _a = queryDoc.definitions; _i < _a.length; _i++) {
var definition = _a[_i];
if (definition.kind === 'OperationDefinition') {
var operation = definition.operation;
if (operation === 'query' ||
operation === 'mutation' ||
operation === 'subscription') {
return definition;
}
}
if (definition.kind === 'FragmentDefinition' && !fragmentDefinition) {
fragmentDefinition = definition;
}
}
if (fragmentDefinition) {
return fragmentDefinition;
}
throw process.env.NODE_ENV === "production" ? new InvariantError(10) : new InvariantError('Expected a parsed GraphQL query with a query, mutation, subscription, or a fragment.');
}
function createFragmentMap(fragments) {
if (fragments === void 0) { fragments = []; }
var symTable = {};
fragments.forEach(function (fragment) {
symTable[fragment.name.value] = fragment;
});
return symTable;
}
function getDefaultValues(definition) {
if (definition &&
definition.variableDefinitions &&
definition.variableDefinitions.length) {
var defaultValues = definition.variableDefinitions
.filter(function (_a) {
var defaultValue = _a.defaultValue;
return defaultValue;
})
.map(function (_a) {
var variable = _a.variable, defaultValue = _a.defaultValue;
var defaultValueObj = {};
valueToObjectRepresentation(defaultValueObj, variable.name, defaultValue);
return defaultValueObj;
});
return assign.apply(void 0, __spreadArrays([{}], defaultValues));
}
return {};
}
function variablesInOperation(operation) {
var names = new Set();
if (operation.variableDefinitions) {
for (var _i = 0, _a = operation.variableDefinitions; _i < _a.length; _i++) {
var definition = _a[_i];
names.add(definition.variable.name.value);
}
}
return names;
}
function filterInPlace(array, test, context) {
var target = 0;
array.forEach(function (elem, i) {
if (test.call(this, elem, i, array)) {
array[target++] = elem;
}
}, context);
array.length = target;
return array;
}
var TYPENAME_FIELD = {
kind: 'Field',
name: {
kind: 'Name',
value: '__typename',
},
};
function isEmpty(op, fragments) {
return op.selectionSet.selections.every(function (selection) {
return selection.kind === 'FragmentSpread' &&
isEmpty(fragments[selection.name.value], fragments);
});
}
function nullIfDocIsEmpty(doc) {
return isEmpty(getOperationDefinition(doc) || getFragmentDefinition(doc), createFragmentMap(getFragmentDefinitions(doc)))
? null
: doc;
}
function getDirectiveMatcher(directives) {
return function directiveMatcher(directive) {
return directives.some(function (dir) {
return (dir.name && dir.name === directive.name.value) ||
(dir.test && dir.test(directive));
});
};
}
function removeDirectivesFromDocument(directives, doc) {
var variablesInUse = Object.create(null);
var variablesToRemove = [];
var fragmentSpreadsInUse = Object.create(null);
var fragmentSpreadsToRemove = [];
var modifiedDoc = nullIfDocIsEmpty(visit(doc, {
Variable: {
enter: function (node, _key, parent) {
if (parent.kind !== 'VariableDefinition') {
variablesInUse[node.name.value] = true;
}
},
},
Field: {
enter: function (node) {
if (directives && node.directives) {
var shouldRemoveField = directives.some(function (directive) { return directive.remove; });
if (shouldRemoveField &&
node.directives &&
node.directives.some(getDirectiveMatcher(directives))) {
if (node.arguments) {
node.arguments.forEach(function (arg) {
if (arg.value.kind === 'Variable') {
variablesToRemove.push({
name: arg.value.name.value,
});
}
});
}
if (node.selectionSet) {
getAllFragmentSpreadsFromSelectionSet(node.selectionSet).forEach(function (frag) {
fragmentSpreadsToRemove.push({
name: frag.name.value,
});
});
}
return null;
}
}
},
},
FragmentSpread: {
enter: function (node) {
fragmentSpreadsInUse[node.name.value] = true;
},
},
Directive: {
enter: function (node) {
if (getDirectiveMatcher(directives)(node)) {
return null;
}
},
},
}));
if (modifiedDoc &&
filterInPlace(variablesToRemove, function (v) { return !variablesInUse[v.name]; }).length) {
modifiedDoc = removeArgumentsFromDocument(variablesToRemove, modifiedDoc);
}
if (modifiedDoc &&
filterInPlace(fragmentSpreadsToRemove, function (fs) { return !fragmentSpreadsInUse[fs.name]; })
.length) {
modifiedDoc = removeFragmentSpreadFromDocument(fragmentSpreadsToRemove, modifiedDoc);
}
return modifiedDoc;
}
function addTypenameToDocument(doc) {
return visit(checkDocument(doc), {
SelectionSet: {
enter: function (node, _key, parent) {
if (parent &&
parent.kind === 'OperationDefinition') {
return;
}
var selections = node.selections;
if (!selections) {
return;
}
var skip = selections.some(function (selection) {
return (isField(selection) &&
(selection.name.value === '__typename' ||
selection.name.value.lastIndexOf('__', 0) === 0));
});
if (skip) {
return;
}
var field = parent;
if (isField(field) &&
field.directives &&
field.directives.some(function (d) { return d.name.value === 'export'; })) {
return;
}
return __assign(__assign({}, node), { selections: __spreadArrays(selections, [TYPENAME_FIELD]) });
},
},
});
}
var connectionRemoveConfig = {
test: function (directive) {
var willRemove = directive.name.value === 'connection';
if (willRemove) {
if (!directive.arguments ||
!directive.arguments.some(function (arg) { return arg.name.value === 'key'; })) {
process.env.NODE_ENV === "production" || invariant.warn('Removing an @connection directive even though it does not have a key. ' +
'You may want to use the key parameter to specify a store key.');
}
}
return willRemove;
},
};
function removeConnectionDirectiveFromDocument(doc) {
return removeDirectivesFromDocument([connectionRemoveConfig], checkDocument(doc));
}
function hasDirectivesInSelectionSet(directives, selectionSet, nestedCheck) {
if (nestedCheck === void 0) { nestedCheck = true; }
return (selectionSet &&
selectionSet.selections &&
selectionSet.selections.some(function (selection) {
return hasDirectivesInSelection(directives, selection, nestedCheck);
}));
}
function hasDirectivesInSelection(directives, selection, nestedCheck) {
if (nestedCheck === void 0) { nestedCheck = true; }
if (!isField(selection)) {
return true;
}
if (!selection.directives) {
return false;
}
return (selection.directives.some(getDirectiveMatcher(directives)) ||
(nestedCheck &&
hasDirectivesInSelectionSet(directives, selection.selectionSet, nestedCheck)));
}
function getDirectivesFromDocument(directives, doc) {
checkDocument(doc);
var parentPath;
return nullIfDocIsEmpty(visit(doc, {
SelectionSet: {
enter: function (node, _key, _parent, path) {
var currentPath = path.join('-');
if (!parentPath ||
currentPath === parentPath ||
!currentPath.startsWith(parentPath)) {
if (node.selections) {
var selectionsWithDirectives = node.selections.filter(function (selection) { return hasDirectivesInSelection(directives, selection); });
if (hasDirectivesInSelectionSet(directives, node, false)) {
parentPath = currentPath;
}
return __assign(__assign({}, node), { selections: selectionsWithDirectives });
}
else {
return null;
}
}
},
},
}));
}
function getArgumentMatcher(config) {
return function argumentMatcher(argument) {
return config.some(function (aConfig) {
return argument.value &&
argument.value.kind === 'Variable' &&
argument.value.name &&
(aConfig.name === argument.value.name.value ||
(aConfig.test && aConfig.test(argument)));
});
};
}
function removeArgumentsFromDocument(config, doc) {
var argMatcher = getArgumentMatcher(config);
return nullIfDocIsEmpty(visit(doc, {
OperationDefinition: {
enter: function (node) {
return __assign(__assign({}, node), { variableDefinitions: node.variableDefinitions.filter(function (varDef) {
return !config.some(function (arg) { return arg.name === varDef.variable.name.value; });
}) });
},
},
Field: {
enter: function (node) {
var shouldRemoveField = config.some(function (argConfig) { return argConfig.remove; });
if (shouldRemoveField) {
var argMatchCount_1 = 0;
node.arguments.forEach(function (arg) {
if (argMatcher(arg)) {
argMatchCount_1 += 1;
}
});
if (argMatchCount_1 === 1) {
return null;
}
}
},
},
Argument: {
enter: function (node) {
if (argMatcher(node)) {
return null;
}
},
},
}));
}
function removeFragmentSpreadFromDocument(config, doc) {
function enter(node) {
if (config.some(function (def) { return def.name === node.name.value; })) {
return null;
}
}
return nullIfDocIsEmpty(visit(doc, {
FragmentSpread: { enter: enter },
FragmentDefinition: { enter: enter },
}));
}
function getAllFragmentSpreadsFromSelectionSet(selectionSet) {
var allFragments = [];
selectionSet.selections.forEach(function (selection) {
if ((isField(selection) || isInlineFragment(selection)) &&
selection.selectionSet) {
getAllFragmentSpreadsFromSelectionSet(selection.selectionSet).forEach(function (frag) { return allFragments.push(frag); });
}
else if (selection.kind === 'FragmentSpread') {
allFragments.push(selection);
}
});
return allFragments;
}
function buildQueryFromSelectionSet(document) {
var definition = getMainDefinition(document);
var definitionOperation = definition.operation;
if (definitionOperation === 'query') {
return document;
}
var modifiedDoc = visit(document, {
OperationDefinition: {
enter: function (node) {
return __assign(__assign({}, node), { operation: 'query' });
},
},
});
return modifiedDoc;
}
function removeClientSetsFromDocument(document) {
checkDocument(document);
var modifiedDoc = removeDirectivesFromDocument([
{
test: function (directive) { return directive.name.value === 'client'; },
remove: true,
},
], document);
if (modifiedDoc) {
modifiedDoc = visit(modifiedDoc, {
FragmentDefinition: {
enter: function (node) {
if (node.selectionSet) {
var isTypenameOnly = node.selectionSet.selections.every(function (selection) {
return isField(selection) && selection.name.value === '__typename';
});
if (isTypenameOnly) {
return null;
}
}
},
},
});
}
return modifiedDoc;
}
var canUseWeakMap = typeof WeakMap === 'function' && !(typeof navigator === 'object' &&
navigator.product === 'ReactNative');
var toString = Object.prototype.toString;
function cloneDeep(value) {
return cloneDeepHelper(value, new Map());
}
function cloneDeepHelper(val, seen) {
switch (toString.call(val)) {
case "[object Array]": {
if (seen.has(val))
return seen.get(val);
var copy_1 = val.slice(0);
seen.set(val, copy_1);
copy_1.forEach(function (child, i) {
copy_1[i] = cloneDeepHelper(child, seen);
});
return copy_1;
}
case "[object Object]": {
if (seen.has(val))
return seen.get(val);
var copy_2 = Object.create(Object.getPrototypeOf(val));
seen.set(val, copy_2);
Object.keys(val).forEach(function (key) {
copy_2[key] = cloneDeepHelper(val[key], seen);
});
return copy_2;
}
default:
return val;
}
}
function getEnv() {
if (typeof process !== 'undefined' && process.env.NODE_ENV) {
return process.env.NODE_ENV;
}
return 'development';
}
function isEnv(env) {
return getEnv() === env;
}
function isProduction() {
return isEnv('production') === true;
}
function isDevelopment() {
return isEnv('development') === true;
}
function isTest() {
return isEnv('test') === true;
}
function tryFunctionOrLogError(f) {
try {
return f();
}
catch (e) {
if (console.error) {
console.error(e);
}
}
}
function graphQLResultHasError(result) {
return result.errors && result.errors.length;
}
function deepFreeze(o) {
Object.freeze(o);
Object.getOwnPropertyNames(o).forEach(function (prop) {
if (o[prop] !== null &&
(typeof o[prop] === 'object' || typeof o[prop] === 'function') &&
!Object.isFrozen(o[prop])) {
deepFreeze(o[prop]);
}
});
return o;
}
function maybeDeepFreeze(obj) {
if (isDevelopment() || isTest()) {
var symbolIsPolyfilled = typeof Symbol === 'function' && typeof Symbol('') === 'string';
if (!symbolIsPolyfilled) {
return deepFreeze(obj);
}
}
return obj;
}
var hasOwnProperty = Object.prototype.hasOwnProperty;
function mergeDeep() {
var sources = [];
for (var _i = 0; _i < arguments.length; _i++) {
sources[_i] = arguments[_i];
}
return mergeDeepArray(sources);
}
function mergeDeepArray(sources) {
var target = sources[0] || {};
var count = sources.length;
if (count > 1) {
var pastCopies = [];
target = shallowCopyForMerge(target, pastCopies);
for (var i = 1; i < count; ++i) {
target = mergeHelper(target, sources[i], pastCopies);
}
}
return target;
}
function isObject(obj) {
return obj !== null && typeof obj === 'object';
}
function mergeHelper(target, source, pastCopies) {
if (isObject(source) && isObject(target)) {
if (Object.isExtensible && !Object.isExtensible(target)) {
target = shallowCopyForMerge(target, pastCopies);
}
Object.keys(source).forEach(function (sourceKey) {
var sourceValue = source[sourceKey];
if (hasOwnProperty.call(target, sourceKey)) {
var targetValue = target[sourceKey];
if (sourceValue !== targetValue) {
target[sourceKey] = mergeHelper(shallowCopyForMerge(targetValue, pastCopies), sourceValue, pastCopies);
}
}
else {
target[sourceKey] = sourceValue;
}
});
return target;
}
return source;
}
function shallowCopyForMerge(value, pastCopies) {
if (value !== null &&
typeof value === 'object' &&
pastCopies.indexOf(value) < 0) {
if (Array.isArray(value)) {
value = value.slice(0);
}
else {
value = __assign({ __proto__: Object.getPrototypeOf(value) }, value);
}
pastCopies.push(value);
}
return value;
}
var haveWarned = Object.create({});
function warnOnceInDevelopment(msg, type) {
if (type === void 0) { type = 'warn'; }
if (!isProduction() && !haveWarned[msg]) {
if (!isTest()) {
haveWarned[msg] = true;
}
if (type === 'error') {
console.error(msg);
}
else {
console.warn(msg);
}
}
}
function stripSymbols(data) {
return JSON.parse(JSON.stringify(data));
}
export { addTypenameToDocument, argumentsObjectFromField, assign, buildQueryFromSelectionSet, canUseWeakMap, checkDocument, cloneDeep, createFragmentMap, getDefaultValues, getDirectiveInfoFromField, getDirectiveNames, getDirectivesFromDocument, getEnv, getFragmentDefinition, getFragmentDefinitions, getFragmentQueryDocument, getInclusionDirectives, getMainDefinition, getMutationDefinition, getOperationDefinition, getOperationDefinitionOrDie, getOperationName, getQueryDefinition, getStoreKeyName, graphQLResultHasError, hasClientExports, hasDirectives, isDevelopment, isEnv, isField, isIdValue, isInlineFragment, isJsonValue, isNumberValue, isProduction, isScalarValue, isTest, maybeDeepFreeze, mergeDeep, mergeDeepArray, removeArgumentsFromDocument, removeClientSetsFromDocument, removeConnectionDirectiveFromDocument, removeDirectivesFromDocument, removeFragmentSpreadFromDocument, resultKeyNameFromField, shouldInclude, storeKeyNameFromField, stripSymbols, toIdValue, tryFunctionOrLogError, valueFromNode, valueToObjectRepresentation, variablesInOperation, warnOnceInDevelopment };
//# sourceMappingURL=bundle.esm.js.map
webpack://frontend-mybets/../../node_modules/graphql-anywhere/lib/bundle.esm.js
import { getMainDefinition, getFragmentDefinitions, createFragmentMap, shouldInclude, isField, resultKeyNameFromField, isInlineFragment, argumentsObjectFromField, getDirectiveInfoFromField, getInclusionDirectives } from 'apollo-utilities';
import { invariant } from 'ts-invariant';
function graphql(resolver, document, rootValue, contextValue, variableValues, execOptions) {
if (variableValues === void 0) { variableValues = {}; }
if (execOptions === void 0) { execOptions = {}; }
var mainDefinition = getMainDefinition(document);
var fragments = getFragmentDefinitions(document);
var fragmentMap = createFragmentMap(fragments);
var resultMapper = execOptions.resultMapper;
var fragmentMatcher = execOptions.fragmentMatcher || (function () { return true; });
var execContext = {
fragmentMap: fragmentMap,
contextValue: contextValue,
variableValues: variableValues,
resultMapper: resultMapper,
resolver: resolver,
fragmentMatcher: fragmentMatcher,
};
return executeSelectionSet(mainDefinition.selectionSet, rootValue, execContext);
}
function executeSelectionSet(selectionSet, rootValue, execContext) {
var fragmentMap = execContext.fragmentMap, contextValue = execContext.contextValue, variables = execContext.variableValues;
var result = {};
selectionSet.selections.forEach(function (selection) {
if (variables && !shouldInclude(selection, variables)) {
return;
}
if (isField(selection)) {
var fieldResult = executeField(selection, rootValue, execContext);
var resultFieldKey = resultKeyNameFromField(selection);
if (fieldResult !== undefined) {
if (result[resultFieldKey] === undefined) {
result[resultFieldKey] = fieldResult;
}
else {
merge(result[resultFieldKey], fieldResult);
}
}
}
else {
var fragment = void 0;
if (isInlineFragment(selection)) {
fragment = selection;
}
else {
fragment = fragmentMap[selection.name.value];
if (!fragment) {
throw new Error("No fragment named " + selection.name.value);
}
}
var typeCondition = fragment.typeCondition.name.value;
if (execContext.fragmentMatcher(rootValue, typeCondition, contextValue)) {
var fragmentResult = executeSelectionSet(fragment.selectionSet, rootValue, execContext);
merge(result, fragmentResult);
}
}
});
if (execContext.resultMapper) {
return execContext.resultMapper(result, rootValue);
}
return result;
}
function executeField(field, rootValue, execContext) {
var variables = execContext.variableValues, contextValue = execContext.contextValue, resolver = execContext.resolver;
var fieldName = field.name.value;
var args = argumentsObjectFromField(field, variables);
var info = {
isLeaf: !field.selectionSet,
resultKey: resultKeyNameFromField(field),
directives: getDirectiveInfoFromField(field, variables),
field: field,
};
var result = resolver(fieldName, rootValue, args, contextValue, info);
if (!field.selectionSet) {
return result;
}
if (result == null) {
return result;
}
if (Array.isArray(result)) {
return executeSubSelectedArray(field, result, execContext);
}
return executeSelectionSet(field.selectionSet, result, execContext);
}
function executeSubSelectedArray(field, result, execContext) {
return result.map(function (item) {
if (item === null) {
return null;
}
if (Array.isArray(item)) {
return executeSubSelectedArray(field, item, execContext);
}
return executeSelectionSet(field.selectionSet, item, execContext);
});
}
var hasOwn = Object.prototype.hasOwnProperty;
function merge(dest, src) {
if (src !== null && typeof src === 'object') {
Object.keys(src).forEach(function (key) {
var srcVal = src[key];
if (!hasOwn.call(dest, key)) {
dest[key] = srcVal;
}
else {
merge(dest[key], srcVal);
}
});
}
}
var hasOwnProperty = Object.prototype.hasOwnProperty;
function filter(doc, data, variableValues) {
if (variableValues === void 0) { variableValues = {}; }
if (data === null)
return data;
var resolver = function (fieldName, root, args, context, info) {
return root[info.resultKey];
};
return Array.isArray(data)
? data.map(function (dataObj) { return graphql(resolver, doc, dataObj, null, variableValues); })
: graphql(resolver, doc, data, null, variableValues);
}
function check(doc, data, variables) {
if (variables === void 0) { variables = {}; }
var resolver = function (fieldName, root, args, context, info) {
process.env.NODE_ENV === "production" ? invariant(hasOwnProperty.call(root, info.resultKey) ||
(!variables && hasVariableInclusions(info.field.directives)), 1) : invariant(hasOwnProperty.call(root, info.resultKey) ||
(!variables && hasVariableInclusions(info.field.directives)), info.resultKey + " missing on " + JSON.stringify(root));
return root[info.resultKey];
};
graphql(resolver, doc, data, {}, variables, {
fragmentMatcher: function () { return false; },
});
}
function hasVariableInclusions(directives) {
return getInclusionDirectives(directives).some(function (_a) {
var ifArgument = _a.ifArgument;
return ifArgument.value && ifArgument.value.kind === 'Variable';
});
}
var ANONYMOUS = '<<anonymous>>';
function PropTypeError(message) {
this.message = message;
this.stack = '';
}
PropTypeError.prototype = Error.prototype;
var reactPropTypeLocationNames = {
prop: 'prop',
context: 'context',
childContext: 'child context',
};
function createChainableTypeChecker(validate) {
function checkType(isRequired, props, propName, componentName, location, propFullName) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (props[propName] == null) {
var locationName = reactPropTypeLocationNames[location];
if (isRequired) {
if (props[propName] === null) {
return new PropTypeError("The " + locationName + " `" + propFullName + "` is marked as required " +
("in `" + componentName + "`, but its value is `null`."));
}
return new PropTypeError("The " + locationName + " `" + 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 propType(doc, mapPropsToVariables) {
if (mapPropsToVariables === void 0) { mapPropsToVariables = function (props) { return null; }; }
return createChainableTypeChecker(function (props, propName) {
var prop = props[propName];
try {
if (!prop.loading) {
check(doc, prop, mapPropsToVariables(props));
}
return null;
}
catch (e) {
return e;
}
});
}
export default graphql;
export { check, filter, propType };
//# sourceMappingURL=bundle.esm.js.map
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/graphql/fragments/Track.ts
import { gql } from "@apollo/client";
const TrackFragments = {
entry: gql`
fragment Track on Race {
track {
id
trackName: name
trackCode: code
perfAbbr
shortName
featured
numberOfRaces
specialCardTypes: specialCardTypes {
specialCardTypeAbbreviation
specialCardTypeName
}
trackLocation: location {
country
}
trackDataSource
}
}
`
};
export default TrackFragments;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/graphql/fragments/WillPays.ts
import { gql } from "@apollo/client";
const WillPays = {
entry: gql`
fragment WillPays on Race {
willPays {
wagerAmount
payOffType
type {
id
code
name
}
payouts {
bettingInterestNumber
payoutAmount
}
legResults {
legNumber
winningBi
}
}
}
`
};
export default WillPays;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/graphql/options.graph.ts
import { filter } from "graphql-anywhere";
import { attempt, first, get } from "lodash";
import {
ApolloClient,
DocumentNode,
NormalizedCacheObject,
WatchQueryFetchPolicy
} from "@apollo/client";
import tvgConf from "@tvg/conf";
import { formatPastRaceDate } from "@tvg/formatter/dates";
// @ts-ignore will update the queries in future
import { BetBasicInfo } from "@tvg/ts-types/Bet";
import { RaceProgram } from "@tvg/ts-types/Race";
import { WroWager, WroWagerGroup } from "@tvg/ts-types/WroWager";
import { getPortByBrand } from "@tvg/utils/generalUtils";
import TimeAndStatus from "./fragments/TimeAndStatus";
import Track from "./fragments/Track";
import RaceDetails from "./fragments/RaceDetails";
import WagerTypes from "./fragments/WagerTypes";
import Video from "./fragments/Video";
import Probables from "./fragments/Probables";
import Results from "./fragments/ResultsFragment";
import Promos from "./fragments/Promos";
import RacePools from "./fragments/RacePools";
import WillPays from "./fragments/WillPays";
import { RaceWagerSummary } from "../types";
const highlightedOptions = {
...tvgConf().graphContext(),
productPromo: tvgConf().product,
brandPromo: tvgConf().brand
};
const QUERY_VARIABLES = {
trackAbbr: null,
...highlightedOptions
};
const extractInfoFromRace = (processingRace: RaceProgram): RaceProgram => {
const raceInfo: RaceProgram = {};
if (processingRace.id) {
raceInfo.id = processingRace.id;
}
if (processingRace.tvgRaceId) {
raceInfo.tvgRaceId = processingRace.tvgRaceId;
}
if (processingRace.raceNumber) {
raceInfo.raceNumber = processingRace.raceNumber;
// needed to be retro-compatible with myBets!
raceInfo.number = processingRace.raceNumber;
}
if (processingRace.talentPicks) {
raceInfo.talentPicks = processingRace.talentPicks;
}
// Handle timeAndStatus
attempt(() => {
const timeAndStatus = filter(TimeAndStatus.entry, processingRace);
Object.assign(raceInfo, timeAndStatus);
});
// Handle track
attempt(() => {
const track = filter(Track.entry, processingRace);
Object.assign(raceInfo, track);
});
// Handle race
attempt(() => {
const race = filter(RaceDetails.entry, processingRace);
Object.assign(raceInfo, race);
});
// Handle wagerTypes
attempt(() => {
const wagerTypes = filter(WagerTypes.entry, processingRace);
Object.assign(raceInfo, wagerTypes);
});
// Handle video
attempt(() => {
const video = filter(Video.entry, processingRace);
Object.assign(raceInfo, video);
});
// Handle Probables
attempt(() => {
const probables = filter(Probables.entry as DocumentNode, processingRace);
Object.assign(raceInfo, probables);
});
// Handle Race Pools
attempt(() => {
const racePools = filter(RacePools.entry as DocumentNode, processingRace);
Object.assign(raceInfo, racePools);
});
// Handle Results
attempt(() => {
const results = filter(Results.entry, processingRace);
Object.assign(raceInfo, results);
});
// Handle Promos
attempt(() => {
const promos = filter(Promos.entry, processingRace);
Object.assign(raceInfo, promos);
});
// Handle Will Pays
attempt(() => {
const willPays = filter(WillPays.entry as DocumentNode, processingRace);
Object.assign(raceInfo, willPays);
});
// Handle race open for betting
attempt(() => {
if (get(processingRace, "status.code")) {
const wagerable =
["SK", "C", "RO"].indexOf(get(processingRace, "status.code")) < 0;
Object.assign(raceInfo, { wagerable });
}
});
return raceInfo;
};
const getRaces = (data: { races: RaceProgram[] }) =>
(get(data, "races") || []).map((race: RaceProgram) =>
extractInfoFromRace(race)
);
export const formatBets = (wagers: WroWager[]): Array<BetBasicInfo> =>
wagers
.filter((wager) => get(wager, "betStatus.code") !== "C")
.map((wager) => ({
id: wager.serialNumber,
trackName: wager.trackName,
raceNumber: wager.raceNumber,
raceTypeCode: wager.raceTypeAbbreviation,
// needed to retro-compatible with myBets!
raceTypeAbbreviation: wager.raceTypeAbbreviation,
raceDate: wager.raceDate,
racePostTime: wager.racePostTime,
betStatus: wager.betStatus,
betTotal: wager.betTotal,
wagerAmount: wager.wagerAmount,
betRefund: wager.betRefund || 0,
wagerType: wager.wagerType,
wagerReference: wager.wagerReference,
serialNumber: wager.serialNumber,
selections: wager.selections,
isKey: false,
isLeg: wager.wagerType.id < 400 && wager.wagerType.id > 300,
cancelable: wager.cancelable,
isCancelled: wager.betStatus.code === "C",
isLost: wager.betStatus.code === "L",
isRefunded: wager.betStatus.code === "R",
totalWinAmount:
wager.betStatus.code === "W" ? wager.winningsAmount : undefined
}));
export const getGroupWagerValue = (
trackCode: string,
raceNumber: number,
postTime: string
) => {
const postDate = formatPastRaceDate(postTime);
return `${postDate}#${trackCode}#${raceNumber}`;
};
const calculateBetsTotals = (wagers: WroWager[] = []): RaceWagerSummary =>
(wagers || []).reduce(
(accumulator, wager) => ({
totalBets: accumulator.totalBets + 1,
totalAmount: accumulator.totalAmount + wager.betTotal,
totalGambledCount:
get(wager, "betStatus.code") !== "C"
? accumulator.totalGambledCount + 1
: accumulator.totalGambledCount,
totalGambledAmount:
get(wager, "betStatus.code") !== "C"
? accumulator.totalGambledAmount + wager.betTotal
: accumulator.totalGambledAmount
}),
{
totalBets: 0,
totalAmount: 0,
totalGambledCount: 0,
totalGambledAmount: 0
}
);
// TODO: define the type!
const getUserRaceBets = (
data: { wagerHistory: { groupWagers: WroWagerGroup } },
trackCode: string,
raceNumber: number,
postTime: string
): { wagers: Array<BetBasicInfo>; totals: RaceWagerSummary } => {
const groupWagersValue = getGroupWagerValue(trackCode, raceNumber, postTime);
const wagers =
first(
(get(data, "wagerHistory.groupWagers", []) as WroWagerGroup[]).filter(
(groupWager) => groupWager.value === groupWagersValue
)
)?.wagers || [];
const formatedWagers = formatBets(wagers);
const totals = calculateBetsTotals(wagers);
return { wagers: formatedWagers, totals };
};
export default {
apolloOptions: (props: { wagerProfile: string; track: string }) => {
const variables = {
...QUERY_VARIABLES,
trackAbbr: (get(props, "track") || "").toUpperCase(),
wagerProfile: get(props, "wagerProfile") || getPortByBrand()
};
return {
skip: !props.track || !props.wagerProfile,
fetchPolicy: "cache-and-network" as WatchQueryFetchPolicy,
ssr: false,
returnPartialData: false,
variables
};
},
apolloOptionsBi: (props: {
wagerProfile: string;
tvgRaceIds: number[];
tvgRaceIdsBiPartial?: number[];
isAccountCompliant?: boolean;
}) => {
const variables = {
tvgRaceIds: get(props, "tvgRaceIds") || [],
tvgRaceIdsBiPartial: get(props, "tvgRaceIdsBiPartial") || [],
wagerProfile: get(props, "wagerProfile") || getPortByBrand()
};
return {
skip:
(!props.tvgRaceIds.length && !props.tvgRaceIdsBiPartial?.length) ||
!props.wagerProfile,
fetchPolicy: "cache-and-network" as WatchQueryFetchPolicy,
ssr: false,
returnPartialData: false,
variables
};
},
apolloOptionsRaceWagers: (props: {
accountId: number;
trackCode: string;
raceNumber: number;
behgClient: ApolloClient<NormalizedCacheObject>;
isAccountCompliant: boolean;
}) => {
const startDate = formatPastRaceDate(new Date());
const variables = {
accountId: props?.accountId,
raceNumber: props?.raceNumber,
trackCode: props?.trackCode || "",
startDate,
endDate: startDate
};
return {
skip: !(
props?.accountId &&
props?.raceNumber &&
props?.trackCode &&
props?.isAccountCompliant
),
fetchPolicy: "cache-and-network" as WatchQueryFetchPolicy,
client: props.behgClient,
ssr: false,
returnPartialData: false,
variables
};
},
apolloOptionsInlinePP: (props: {
wagerProfile: string;
entityRunnerId: string | undefined;
isOpen: boolean;
fcpClient: ApolloClient<NormalizedCacheObject>;
}) => {
const variables = {
entityRunnerId: get(props, "entityRunnerId") || "",
wagerProfile: get(props, "wagerProfile") || getPortByBrand()
};
const skip = !props.isOpen || !props.fcpClient;
const fetchPolicy: WatchQueryFetchPolicy = "cache-and-network";
// Using only the fetchPolicy was causing an infinite request loop
// https://github.com/apollographql/apollo-client/issues/6819
const nextFetchPolicy: WatchQueryFetchPolicy = "cache-first";
return {
skip,
fetchPolicy,
nextFetchPolicy,
ssr: false,
returnPartialData: false,
variables,
client: props.fcpClient
};
},
apolloOptionsLastWager: (props: {
accountNumber: string;
gasClient: ApolloClient<NormalizedCacheObject>;
isFirstWager: boolean;
}) => {
const variables = {
accountId: +get(props, "accountNumber")
};
const skip = !props.gasClient || props.isFirstWager || !variables.accountId;
return {
skip,
variables,
ssr: false,
client: props.gasClient,
fetchPolicy: "cache-and-network" as WatchQueryFetchPolicy
};
},
apolloOptionsTrackList(props: { wagerProfile: string }) {
const variables = {
wagerProfile: props.wagerProfile || getPortByBrand()
};
return {
skip: !props.wagerProfile,
fetchPolicy: "cache-and-network" as WatchQueryFetchPolicy,
ssr: false,
returnPartialData: false,
variables
};
},
getRaces,
getUserRaceBets
};
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/graphql/queries/RaceProgramQuery.ts
import { gql } from "@apollo/client";
import WagerTypesFragments from "../fragments/WagerTypes";
import TimeAndStatusFragments from "../fragments/TimeAndStatus";
import RaceDetailsFragments from "../fragments/RaceDetails";
import VideoFragments from "../fragments/Video";
import TrackFragments from "../fragments/Track";
import ResultsFragments from "../fragments/ResultsFragment";
import PromosFragments from "../fragments/Promos";
export const GET_PROGRAM_PAGE_RACE = gql`
query getGraphRace(
$trackAbbr: String
$wagerProfile: String
$product: String
$device: String
$brand: String
) {
races: races(
filter: { trackCode: [$trackAbbr] }
profile: $wagerProfile
sort: { byRaceNumber: ASC }
) {
id
tvgRaceId
...RaceDetails
...TimeAndStatus
...Track
...Video
...WagerTypes
...Promos
...Results
}
}
${WagerTypesFragments.entry}
${TimeAndStatusFragments.entry}
${RaceDetailsFragments.entry}
${VideoFragments.entry}
${TrackFragments.entry}
${PromosFragments.entry}
${ResultsFragments.entry}
`;
webpack://frontend-mybets/../../packages/urp-lib-amplitude/src/constants.ts
import { RaceStatusEnum } from "@tvg/ts-types/Race";
export const COMMON_EVENT_NAMES = {
SITE_CLICK: "Site Click",
PAGE_VIEWED: "PAGE VIEWED",
NAVIGATED: "Navigation Link Clicked",
OPEN: "Opened",
CLOSE: "Closed",
DELETED: "Deleted"
};
export const PAGE_NAME_KEYS = {
HOME: "home",
TRACK_INFORMATION: "track_information",
ALL_INFO_TRACK: "all_info_track",
PROGRAM_PAGE: "program_page",
PROMOS: "promos",
PROMOTIONS: "promotions",
PROMO_OFFER: "promo_offer"
};
export const MEP_PAGE_CONFIG = [
{
page: PAGE_NAME_KEYS.TRACK_INFORMATION,
urlReg: /^\/racetracks((?!race=).)*$/
},
{ page: PAGE_NAME_KEYS.PROGRAM_PAGE, urlReg: /\/racetracks\/.*\?race=.+/ },
{
page: PAGE_NAME_KEYS.PROMO_OFFER,
urlReg: /(\?promo=[^&\s]*|\/promos\/.*)/
},
{ page: PAGE_NAME_KEYS.PROMOTIONS, urlReg: /(\/\w+)?#promos/ },
{ page: PAGE_NAME_KEYS.PROGRAM_PAGE, urlReg: /\/live\/TVG\d?\/.*\?race=.+/ }
];
export const PAGE_NAMES = {
[PAGE_NAME_KEYS.HOME]: "Home",
[PAGE_NAME_KEYS.TRACK_INFORMATION]: "Track Information",
[PAGE_NAME_KEYS.ALL_INFO_TRACK]: "All Info Track",
[PAGE_NAME_KEYS.PROGRAM_PAGE]: "Program",
[PAGE_NAME_KEYS.PROMOS]: "Promotions",
[PAGE_NAME_KEYS.PROMOTIONS]: "Promotions",
[PAGE_NAME_KEYS.PROMO_OFFER]: "Promo Offer"
};
export const ALL_INFO_TRACK_DETAILS_REGEX = /\/all-info\/.*/;
export const URP_PAGE_CONFIG = [
{
page: PAGE_NAME_KEYS.TRACK_INFORMATION,
urlReg: /^\/racetracks((?!race=).)*$/
},
{ page: PAGE_NAME_KEYS.ALL_INFO_TRACK, urlReg: ALL_INFO_TRACK_DETAILS_REGEX },
{ page: PAGE_NAME_KEYS.PROGRAM_PAGE, urlReg: /\/racetracks/ },
{ page: PAGE_NAME_KEYS.PROGRAM_PAGE, urlReg: /\/live\/TVG\d?\/.*\?race=.+/ },
{ page: PAGE_NAME_KEYS.PROMO_OFFER, urlReg: /\/?promo=(?!s\b)/ }, // Mobile
{ page: PAGE_NAME_KEYS.PROMO_OFFER, urlReg: /\/promos\/[^?].+/ }, // Desktop
{ page: PAGE_NAME_KEYS.PROMOTIONS, urlReg: /(\/\w+)?#promos/ }, // Mobile
{ page: PAGE_NAME_KEYS.PROMOTIONS, urlReg: /^\/promos/ } // Desktop
];
export const RACE_STATUS_MAPPER = {
[RaceStatusEnum.OPEN]: "mtp",
[RaceStatusEnum.UP_NEXT]: "mtp",
[RaceStatusEnum.RACE_OFFICIAL]: "resulted",
[RaceStatusEnum.RACE_OFF]: "race_off"
};
export const DEVICE_ID_COOKIE = "amp_device_id";
export const DEVICE_ID_COOKIE_MAX_AGE = 31622400;
export const SESSION_ID_COOKIE = "amp_session_id";
export const SESSION_ID_COOKIE_MAX_AGE = 1800;
export const JURISDICTION_LOCAL_STORAGE_ITEM = "userAuthenticationState";
export const TRACKS_TABS_PATHS: Record<string, string> = {
"/tracks": "Today",
"/tracks/results": "Results",
"/tracks/all-info": "All Tracks"
};
export const XSELL_PREFIX = "FDR XS";
webpack://frontend-mybets/../../packages/urp-lib-racetracks/src/types.ts
import {
OptInPromotion,
Promo,
UserEligiblePromotion
} from "@tvg/ts-types/Promos";
import { RaceStatusEnum, RaceTypeCodeEnum } from "@tvg/ts-types/Race";
export enum RegionFiltersEnum {
US = "USA",
International = "INT"
}
export enum ToggleHideResultsEnum {
OFF = "0",
ON = "1"
}
export type FavoriteWithIdTracks = {
[code: string]: number;
};
export type Favorite = {
entityDob?: number | null;
entityName: string;
entityType: string;
favoriteId: number;
// @TODO: confirm if we need this...
subscriptions?: FavoriteSubscriptions[];
};
export type FavoriteSubscriptions = {
eventType?: string;
channels?: ChannelsSubscriptions[];
};
export type ChannelsSubscriptions = {
type?: string;
};
export type TracksFilterOption = {
label: string;
value: string;
};
export type TracksFilter = {
title: string;
options: Array<TracksFilterOption>;
};
export type TracksFilterMsg = {
raceTypes: TracksFilter;
regions: TracksFilter;
};
export type TracksSearchMsg = {
inputPlaceholder: string;
buttonText: string;
};
export type TabConfig = {
id: string;
title: string;
url: string;
enabled: boolean;
trackListLabel?: string;
};
export interface EmptyRaceInfo {
title?: string;
description?: string;
}
export type TabsTracks = {
tabs: TabConfig[];
tabsDesktop: TabConfig[];
todaysRacesEmpty: EmptyRaceInfo;
resultsEmpty: EmptyRaceInfo;
tracksInformationListEmpty: EmptyRaceInfo;
};
export enum TABS {
TODAY = "tracks",
RESULTS = "results",
ALL_TRACKS = "all-info"
}
export const TABS_NAMES = {
[TABS.TODAY]: "today",
[TABS.RESULTS]: "results",
[TABS.ALL_TRACKS]: "all tracks"
};
export enum FilterType {
SEARCH = "search",
FACET = "facet",
ALL_FILTERS = "all_filters"
}
export enum FilterName {
REGION = "region",
RACE_TYPE = "race_type",
TRACK_TYPE = "track_type",
BETTING_FEATURES = "betting_features",
DISTANCE = "distance"
}
export type FilterOptions = {
regionsFilter?: Array<string>;
raceTypesFilter?: Array<RaceTypeCodeEnum>;
tracksSearchQuery?: string;
trackTypesFilter?: TrackFilterValueEnum[];
racesFilter?: string[];
distancesFilter?: string[];
raceStatusFilter?: Array<RaceStatusEnum>;
};
export interface ApolloUserPromotions {
userPromotions: {
promotions: Promo[];
eligiblePromotions: UserEligiblePromotion[];
} | null;
}
export interface ApolloUserOptinPromotions {
userOptInPromotions: OptInPromotion[] | null;
}
export type TopTracksConfig = {
maxResults: number;
};
export enum TrackFilterValueEnum {
FEATURED = "featured",
FAVORITE = "favorites",
SPECIAL_WAGERS = "special_wagers"
}
export type TrackDetails = {
code: string;
name: string;
dates: string[];
location: {
country: string;
location: string;
state: string;
};
imageLink: string;
imageName: string;
};
export interface HorseResultEntity {
name: string;
dob: string;
entityRunnerId: number;
}
webpack://frontend-mybets/../../packages/urp-lib-racetracks/src/utils/races.ts
import { sortBy, get } from "lodash";
import { format } from "date-fns";
import type { UserOptedInPromos } from "@tvg/ts-types/User";
import {
Race,
RaceStatusEnum,
RaceTypeCodeEnum,
Promo,
RaceDistanceCodeEnum,
PastRaceResults,
ResultRunner,
RaceProgram as RaceProgramPP
} from "@tvg/ts-types/Race";
import type { TopPool } from "@tvg/ts-types/Pool";
import type { SeoTrack, Track } from "@tvg/ts-types/Track";
import { RaceProgram } from "@tvg/lhn/src/types";
import { CPPPromo } from "@urp/quick-links/src/types";
import {
FilterOptions,
HorseResultEntity,
RegionFiltersEnum,
TrackFilterValueEnum
} from "../types";
export const getTrackName = (trackName: string, delimiter = " - ") => {
const indexOfDelimiter = trackName.indexOf(delimiter);
return indexOfDelimiter > 0
? trackName.slice(indexOfDelimiter + delimiter.length)
: trackName;
};
export const findTrack = (
tracks: Array<Track>,
trackCode: string | undefined
) => tracks.find((track) => track.code === trackCode);
export const getRaceCacheId = (
trackCode: string | undefined,
raceNumber: string | undefined,
date: string | undefined
) => `${trackCode}-${raceNumber}-${date}`;
export const filterTracksByRegion = (
tracks: Array<SeoTrack | Track>,
regionsFilter: Array<string>
): Array<SeoTrack | Track> =>
regionsFilter.length > 0
? tracks.filter((track) =>
isRegionIncluded(
regionsFilter,
track.location?.country || RegionFiltersEnum.International
)
)
: tracks;
export const filterRacesByRegion = (
races: Race[],
regionsFilter: Array<string>
): Race[] =>
regionsFilter.length > 0
? races.filter((race) =>
isRegionIncluded(
regionsFilter,
race.track.location?.country || RegionFiltersEnum.International
)
)
: races;
export const filterRacesByTrackCode = (
races: Array<Race>,
trackCodes: Array<string>
) =>
trackCodes.length > 0
? races.filter((race) => trackCodes.includes(race.track.code))
: races;
export const filterRacesByRaceType = (
races: Array<Race>,
raceTypesFilter: Array<RaceTypeCodeEnum>
) =>
raceTypesFilter.length > 0
? races.filter((race) => raceTypesFilter.includes(race.type.code))
: races;
export const filterRacesByStatus = (
races: Array<Race>,
raceStatusFilter: Array<RaceStatusEnum>
) =>
raceStatusFilter.length > 0
? races.filter((race) => raceStatusFilter.includes(race.status.code))
: races;
export const isRegionIncluded = (regions: Array<string>, region: string) =>
regions.includes(region) ||
(regions.includes(RegionFiltersEnum.International) &&
region !== RegionFiltersEnum.US);
export const isTrackOpen = (openTracks: string[], trackCode: string): boolean =>
openTracks.includes(trackCode);
export const getOpenTracksRaces = (
openTracks: Array<string>,
tracks: Array<Track>,
races: Array<Race>
): Array<Track> =>
tracks.map((track) =>
openTracks.includes(track.code)
? {
...track,
races: races.filter((race) => race.track.code === track.code)
}
: track
);
export const filterTracksWithRaces = (
tracks: Array<Track>,
races: Array<Race>
) =>
tracks.filter((track) =>
races.some((race) => race.track.code === track.code)
);
export const getUpcomingRaces = (
allUpcomingRaces: Array<Race>,
maxResults: number
) => sortBy(allUpcomingRaces, ["mtp", "track.name"]).slice(0, maxResults);
export const getRacesWithTrackLocation = (
races: Array<Race>,
tracks: Array<Track>
) =>
races.map((race) => {
const track = findTrack(tracks, race.track.code);
return {
...race,
track: {
...race.track,
hasAboveTheLinePromo: !!track?.hasAboveTheLinePromo,
name: race.track.name,
location: {
country: track?.location?.country || "",
state: track?.location?.state || ""
}
}
};
});
export const getRacePromos = (race: Race) =>
race.promos?.filter((promo) => promo.isPromoTagShown) ?? [];
export const hasPromoAvailable = (race: Race): Promo[] =>
race.promos?.filter((promo) => promo.isAboveTheLine) ?? [];
export const isUserOptedInPromo = (
optedInPromos: UserOptedInPromos,
promos: Promo[]
) => promos.some((promo) => get(optedInPromos, promo.rootParentPromoID, false));
const isCPPPromoToday = (cardDates?: string[]) => {
const todayDate = format(new Date(), "yyyy-MM-dd");
return cardDates ? cardDates.includes(todayDate) : true;
};
export const hasTrackPromoCPP = (cppPromos: CPPPromo[], track: Track) =>
cppPromos.some(
(cppPromo) =>
cppPromo.bettingRules?.trackCodes?.includes(track.code) &&
isCPPPromoToday(cppPromo.bettingRules?.cardDates)
);
export const getRaceInfo = (race: Race | RaceProgram) => {
const [raceCode, raceNumber] = race.id.split("-");
return { raceCode, raceNumber };
};
export const hasRacePromoCPP = (
cppPromos: CPPPromo[],
race: Race | RaceProgram
) => {
const { raceCode, raceNumber } = getRaceInfo(race);
return cppPromos.some(
(cppPromo) =>
cppPromo.bettingRules?.trackCodes?.includes(raceCode) &&
cppPromo.bettingRules?.raceNumbers?.includes(raceNumber) &&
isCPPPromoToday(cppPromo.bettingRules?.cardDates)
);
};
export const getBetTypePromosCPP = (
cppPromos: CPPPromo[],
race: Race | RaceProgram | RaceProgramPP
) => {
const trackCodes = race?.id?.split("-")[0];
const raceNumber = race?.id?.split("-")[1];
return cppPromos
.filter(
(promo) =>
promo.bettingRules?.trackCodes?.includes(trackCodes as string) &&
promo.bettingRules?.raceNumbers?.includes(raceNumber as string) &&
isCPPPromoToday(promo.bettingRules?.cardDates)
)
.flatMap((promo) => promo.bettingRules?.racingBetTypes);
};
export const getPromoCPPPath = (
cppPromos: CPPPromo[],
race: Race | RaceProgram
) => {
const { raceCode } = getRaceInfo(race);
return `/promos/${
cppPromos.find((cppPromo) =>
cppPromo.bettingRules?.trackCodes?.includes(raceCode)
)?.path.url
}`;
};
export const hasRacePromoCPPOptedIn = (
cppPromos: CPPPromo[],
race: Race | RaceProgram,
isLogged: boolean
) => {
const { raceCode, raceNumber } = getRaceInfo(race);
const localStorageCPPOptedIn = localStorage.getItem("cppOptedInPromos");
return cppPromos.some(
(cppPromo) =>
cppPromo.bettingRules?.trackCodes?.includes(raceCode) &&
cppPromo.bettingRules?.raceNumbers?.includes(raceNumber) &&
(cppPromo.isOptedIn ||
localStorageCPPOptedIn?.includes(cppPromo.promoId)) &&
isCPPPromoToday(cppPromo.bettingRules?.cardDates) &&
isLogged
);
};
export const hasRacePromoCPPSameType = (
cppPromos: CPPPromo[],
race: Race | RaceProgram,
betType: string
) => {
const { raceCode, raceNumber } = getRaceInfo(race);
return cppPromos.some(
(cppPromo) =>
cppPromo.bettingRules?.trackCodes?.includes(raceCode) &&
cppPromo.bettingRules?.raceNumbers?.includes(raceNumber) &&
cppPromo.bettingRules?.racingBetTypes?.includes(betType) &&
isCPPPromoToday(cppPromo.bettingRules?.cardDates)
);
};
export const getCurrentCPPPromo = (
cppPromos: CPPPromo[],
race: Race | RaceProgram
) => {
const { raceCode, raceNumber } = getRaceInfo(race);
return cppPromos.find(
(cppPromo) =>
cppPromo.bettingRules?.trackCodes?.includes(raceCode) &&
cppPromo.bettingRules?.raceNumbers?.includes(raceNumber) &&
isCPPPromoToday(cppPromo.bettingRules?.cardDates)
);
};
export const getOptedInCPPPromos = (cppPromos: CPPPromo[]) =>
cppPromos.reduce((acc: { [key: string]: boolean }, cppPromo) => {
acc[cppPromo.promoId] = cppPromo.isOptedIn;
return acc;
}, {});
export const filterTrackByTrackType = (
tracks: Array<SeoTrack | Track>,
filter: Array<TrackFilterValueEnum>,
favoriteTracks: string[]
) =>
tracks.filter((track) => {
const isFavoriteTrack =
favoriteTracks.includes(track.code) || track.isFavorite;
const filterIncludesFeatured = filter.includes(
TrackFilterValueEnum.FEATURED
);
const isFeaturedTrack = track.featured;
const filterIncludesFavorites = filter.includes(
TrackFilterValueEnum.FAVORITE
);
const isSpecialWagerTrack = (track.specialCardTypes?.length ?? 0) > 0;
const filterIncludesSpecialWagers = filter.includes(
TrackFilterValueEnum.SPECIAL_WAGERS
);
const noFiltersActive = !(
filterIncludesFeatured ||
filterIncludesFavorites ||
filterIncludesSpecialWagers
);
const matchesFeatured = filterIncludesFeatured && isFeaturedTrack;
const matchesFavorites = filterIncludesFavorites && isFavoriteTrack;
const matchesSpecialWagers =
filterIncludesSpecialWagers && isSpecialWagerTrack;
return (
noFiltersActive ||
matchesFeatured ||
matchesFavorites ||
matchesSpecialWagers
);
});
export const filterRacesByDistanceInterval = (
races: Race[],
filters: string[]
) =>
races.filter((race) => {
const distance = race.raceDistance?.value;
if (
race.raceDistance?.code !== RaceDistanceCodeEnum.FURLONG ||
distance === undefined
)
return false;
return filters.some((filter) => {
const [lowFilter, highFilter] = filter.split("-");
const lowValue = Number.parseInt(lowFilter, 10);
const highValue = Number.parseInt(highFilter, 10);
if (
!Number.isNaN(lowValue) &&
Number.isNaN(highValue) &&
distance >= lowValue
)
return true;
if (
Number.isNaN(lowValue) &&
!Number.isNaN(highValue) &&
distance < highValue
)
return true;
if (
!Number.isNaN(lowValue) &&
!Number.isNaN(highValue) &&
distance >= lowValue &&
distance < highValue
)
return true;
return false;
});
});
export const filterRacesByRaceAttribute = (
races: Race[],
filters: string[],
topPools: TopPool[] = []
) =>
races.filter((race) => {
const availableRacePromos = hasPromoAvailable(race);
const isPartOfTopPools = topPools.find(
(topPool) =>
topPool.trackCode === race.track.code &&
topPool.race.raceNumber === race.raceNumber
);
return (
((race.video.onTvg || race.video.onTvg2) && filters.includes("fdtv")) ||
(!!availableRacePromos.length && filters.includes("promos")) ||
(isPartOfTopPools && filters.includes("topPools"))
);
});
export const hasFiltersApplied = (
filters: FilterOptions = {},
includeSearch: boolean = false
) =>
Object.keys(filters).reduce(
(acc, key) => acc || get(filters, key, []).length > 0,
false
) || !!(includeSearch && !!filters.tracksSearchQuery);
export const getDupsHorseResults = (horseResults: HorseResultEntity[]) => {
if (horseResults?.length === 0) return [];
const horseResultCounter = horseResults.reduce((acc, { name }) => {
const value = get(acc, name);
if (get(acc, name)) {
return { ...acc, [name]: value + 1 };
}
return { ...acc, [name]: 1 };
}, {});
return Object.keys(horseResultCounter).filter(
(key) => get(horseResultCounter, key) > 1
);
};
export const filterAndSortRunners = (
races: Array<PastRaceResults>
): Array<PastRaceResults> =>
races.map((race: PastRaceResults) => {
if (race.results?.allRunners) {
const filteredRunners = race.results.allRunners
.filter((runner: ResultRunner) => !!runner.finishPosition)
.sort(
(a: ResultRunner, b: ResultRunner) =>
a.finishPosition - b.finishPosition
);
return {
...race,
results: { ...race.results, runners: filteredRunners }
};
}
return race;
});
export const groupRacesByTrack = (
races: Race[],
tracks: Track[]
): { [trackCode: string]: Race[] } =>
races.reduce(
(acc, race: Race) => {
const trackCode = race.track.code;
if (trackCode && tracks.some((track) => track.code === trackCode)) {
if (!acc[trackCode]) {
acc[trackCode] = [];
}
acc[trackCode].push(race);
}
return acc;
},
{} as { [trackCode: string]: Race[] }
);
webpack://frontend-mybets/../../packages/tvg-lib-api/fem/index.ts
import tvgConf from "@tvg/conf";
import getProtocol from "../protocolSetter";
import requester from "../requester";
const femService = "service.fem";
const sendMetric = (accountId: string, metricData: {}) =>
requester()({
method: "POST",
url: `${getProtocol()}${tvgConf().config(
femService
)}/users/${accountId}/metrics`,
headers: { "x-tvg-context": tvgConf().context() },
data: metricData,
withCredentials: true
});
const FEM_SERVICES = {
sendMetric
};
export default FEM_SERVICES;
webpack://frontend-mybets/../../packages/tvg-lib-metrics-collector/src/index.js
import femService from "@tvg/api/fem";
import tvgConf from "@tvg/conf";
import { BRAND_FDR } from "@tvg/conf/src/brand";
import metricsConfig from "./metricsConfigurations";
export const getDefaultLabels = (app) => ({
"part-of": "frontend",
technology: "node",
application: app
});
export const mapMetricDataToService = (app, metrics) =>
metrics.map((metric) => {
const metricConfig =
typeof metric === "string"
? {
...(metricsConfig[metric] || {})
}
: {
...(metricsConfig[metric.name] || {}),
value: metric.value
};
return { ...metricConfig, tags: { ...getDefaultLabels(app) } };
});
const sendAppMetrics = (app, accountId, metrics) => {
try {
femService
.sendMetric(accountId, mapMetricDataToService(app, metrics))
.catch(() => {
console.log("Error sending metrics");
});
} catch (e) {
console.log(e, "Error sending metrics");
}
};
export const getApp = () => {
const { brand } = tvgConf();
const { device } = tvgConf();
if (brand === BRAND_FDR) {
return "frontend-fdm";
}
return device === "desktop" ? "frontend-desk" : "frontend-mbl";
};
export default sendAppMetrics;
webpack://frontend-mybets/../../node_modules/uuid/dist/esm-browser/v1.js
import rng from './rng.js';
import { unsafeStringify } from './stringify.js'; // **`v1()` - Generate time-based UUID**
//
// Inspired by https://github.com/LiosK/UUID.js
// and http://docs.python.org/library/uuid.html
let _nodeId;
let _clockseq; // Previous uuid creation time
let _lastMSecs = 0;
let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details
function v1(options, buf, offset) {
let i = buf && offset || 0;
const b = buf || new Array(16);
options = options || {};
let node = options.node || _nodeId;
let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not
// specified. We do this lazily to minimize issues related to insufficient
// system entropy. See #189
if (node == null || clockseq == null) {
const seedBytes = options.random || (options.rng || rng)();
if (node == null) {
// Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
}
if (clockseq == null) {
// Per 4.2.2, randomize (14 bit) clockseq
clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
}
} // UUID timestamps are 100 nano-second units since the Gregorian epoch,
// (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
// time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
// (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock
// cycle to simulate higher resolution clock
let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)
const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression
if (dt < 0 && options.clockseq === undefined) {
clockseq = clockseq + 1 & 0x3fff;
} // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
// time interval
if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
nsecs = 0;
} // Per 4.2.1.2 Throw error if too many uuids are requested
if (nsecs >= 10000) {
throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
}
_lastMSecs = msecs;
_lastNSecs = nsecs;
_clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
msecs += 12219292800000; // `time_low`
const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
b[i++] = tl >>> 24 & 0xff;
b[i++] = tl >>> 16 & 0xff;
b[i++] = tl >>> 8 & 0xff;
b[i++] = tl & 0xff; // `time_mid`
const tmh = msecs / 0x100000000 * 10000 & 0xfffffff;
b[i++] = tmh >>> 8 & 0xff;
b[i++] = tmh & 0xff; // `time_high_and_version`
b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`
b[i++] = clockseq & 0xff; // `node`
for (let n = 0; n < 6; ++n) {
b[i + n] = node[n];
}
return buf || unsafeStringify(b);
}
export default v1;
webpack://frontend-mybets/../../packages/tvg-lib-api/wtx/index.ts
import tvgConf from "@tvg/conf";
import { PRODUCTS_FDR_X_SELL } from "@tvg/conf/src/product";
import { get } from "lodash/fp";
import { v1 as generateUUID } from "uuid";
import getProtocol from "../protocolSetter";
import requester from "../requester";
const isNative = tvgConf().context().includes("iosnative");
if (isNative) {
// @ts-ignore -> This import only need on react native because the UUID library since UUID use native module to generate UUID.
import("react-native-get-random-values");
}
const X_GEO_PACKET = "X-Geo-Packet";
const X_GEO_TOKEN = "X-Geo-Token";
const X_SELL = "X-Sell";
const wtxService: string = "service.wtx";
const getWtxServiceUrl = (): string =>
`${getProtocol()}${tvgConf().config(wtxService)}`;
type raceType = {
trackAbbr: string | undefined | null;
raceNumber: string | undefined | null;
};
export type SuccessReceipt = {
price: number;
serialNumber: string;
};
export type ErrorReceipt = {
code: number;
message: string;
exception: string;
};
export type BetReceipt = {
success?: SuccessReceipt;
error?: ErrorReceipt;
statusCode: number;
};
export type WagerSummary = {
requested: number;
fulfilled: number;
failed: number;
price: number;
userBalance: number;
wagerReference: string;
};
export type Wager = {
summary: WagerSummary;
status: BetReceipt[];
};
export type CancelBetResponse = {
status: number;
config: {
url: string;
};
data: {
userBalance: number;
code: number;
message: string;
exception: string;
timestamp: string;
path: string;
};
};
export type LegSelectionsType = Array<{
bettingInterests: Array<{
order: number;
}>;
alternate?: number | null;
}>;
export type SelectionsType = Array<
Array<{
order: number;
}>
>;
const cancelBet = (
serialNumber: string,
wagerReference: string,
accountNumber: string
): Promise<CancelBetResponse> =>
requester()({
url: `${getWtxServiceUrl()}/users/${accountNumber}/wagers/${wagerReference}/${serialNumber}`,
method: "delete",
withCredentials: true,
headers: { "x-tvg-context": tvgConf().context() }
}) as unknown as Promise<CancelBetResponse>;
const placeBet = (
selections: SelectionsType,
betType: string,
betAmount: number,
betCost: number,
race: raceType,
location: unknown,
regionDetails: unknown,
accountNumber: string,
numberOfBets: number = 1
): Promise<Wager> => {
if (betAmount <= 0 && betCost <= 0) {
return Promise.reject(new Error("Invalid bet params"));
}
if (!selections.length) {
return Promise.reject(new Error("Invalid selections"));
}
if (!get("trackAbbr", race) || !get("raceNumber", race)) {
return Promise.reject(new Error("Invalid race params"));
}
const uuid = generateUUID();
const betToPlace = {
wagerReference: uuid,
track: race.trackAbbr,
race: race.raceNumber,
amount: betAmount,
price: +betCost.toFixed(2),
type: betType,
selections
};
const postData = {
wager: betToPlace,
regions: regionDetails,
location
};
const url = `${getWtxServiceUrl()}/users/${accountNumber}/wagers${
numberOfBets > 1 ? `?wagersToBePlaced=${numberOfBets}` : ""
}`;
const moreHeaders: Record<string, string | boolean | undefined> = {};
const geoPacket = isNative
? ""
: typeof window !== "undefined" && localStorage.getItem(X_GEO_TOKEN);
if (geoPacket) {
moreHeaders[X_GEO_PACKET] = geoPacket;
}
const isXSell = PRODUCTS_FDR_X_SELL.includes(tvgConf().product);
if (isXSell) {
moreHeaders[X_SELL] = true;
}
return requester()({
method: "post",
url,
data: postData,
withCredentials: true,
headers: {
"Content-Type": "application/json",
"X-XSRF-TOKEN": uuid,
"x-tvg-context": tvgConf().context(),
...moreHeaders
}
}).then(get("data"));
};
const placeWager = (
selections: LegSelectionsType,
betType: string,
betAmount: number,
betCost: number,
race: raceType,
location: unknown,
regionDetails: unknown,
accountNumber: string,
numberOfBets: number = 1
): Promise<Wager> => {
if (betAmount <= 0 && betCost <= 0) {
return Promise.reject(new Error("Invalid bet params"));
}
if (!selections.length) {
return Promise.reject(new Error("Invalid selections"));
}
if (!get("trackAbbr", race) || !get("raceNumber", race)) {
return Promise.reject(new Error("Invalid race params"));
}
const uuid = generateUUID();
const betToPlace = {
wagerReference: uuid,
track: race.trackAbbr,
race: race.raceNumber,
amount: betAmount,
price: +betCost.toFixed(2),
type: betType,
legSelections: selections
};
const postData = {
wager: betToPlace,
regions: regionDetails,
location
};
const url = `${getWtxServiceUrl()}/users/${accountNumber}/wagers${
numberOfBets > 1 ? `?wagersToBePlaced=${numberOfBets}` : ""
}`;
const moreHeaders: Record<string, string | boolean | undefined> = {};
const geoPacket = isNative
? ""
: typeof window !== "undefined" && localStorage.getItem(X_GEO_TOKEN);
if (geoPacket) {
moreHeaders[X_GEO_PACKET] = geoPacket;
}
const isXSell = PRODUCTS_FDR_X_SELL.includes(tvgConf().product);
if (isXSell) {
moreHeaders[X_SELL] = true;
}
return requester()({
method: "post",
url,
data: postData,
withCredentials: true,
headers: {
"Content-Type": "application/json",
"X-XSRF-TOKEN": uuid,
"x-tvg-context": tvgConf().context(),
...moreHeaders
}
}).then(get("data"));
};
const WTX_SERVICE = {
cancelBet,
placeBet,
placeWager
};
export default WTX_SERVICE;
webpack://frontend-mybets/../../packages/tvg-lib-shared-actions/UserActions.ts
import {
SetUserFavoriteTrack,
SetUserFavoriteTracks
} from "@tvg/tracks/src/v2/redux/actions";
import { ChannelUFC } from "@tvg/ts-types/Alerts";
import { FavoriteTrackWithId } from "@tvg/ts-types/User";
export type UpdateBalanceActionType = {
type: "USER_BALANCE_SUCCESS";
payload: { balance: number };
};
export type UpdateWalletBalancesActionType = {
type: "USER_WALLET_BALANCES_SUCCESS";
payload: {
balance: number;
bonus: number;
sharedDeposits: number;
sharedWinnings: number;
};
};
export type FailBalanceRequestAction = {
type: "USER_BALANCE_FAIL";
payload: Error;
error: true;
};
export type UpdatePromoFundsActionType = {
type: "USER_PROMO_FUNDS_SUCCESS";
payload: { promoFunds: number };
};
export type SetFavoriteTrackActionType = {
type: "SET_FAVORITE_TRACK";
payload: {
trackCode: string;
favoriteId?: number;
};
};
export type RemoveFavoriteTrackActionType = {
type: "REMOVE_FAVORITE_TRACK";
payload: {
trackCode: string;
};
};
export type SetDefaultBetPrefsAction = {
type: "SET_DEFAULT_BET_PREFERENCES";
payload: {};
};
export type SetNewPreferenceValue = {
type: "SET_NEW_PREFERENCE_VALUE";
payload: {
preferenceKey: string;
preferenceValue: string;
};
};
export type SetRaceAlertsActionType = {
type: "SET_RACE_ALERTS";
payload: {
channels: ChannelUFC[];
};
};
export type SetUserFavoriteTracksWithIdActionType = {
type: "SET_USER_FAVORITE_TRACKS_WITH_FAVORITE_ID";
payload: {
favoriteTracksWithId: FavoriteTrackWithId;
};
};
export type AddFavoriteTrackWithId = {
type: "SET_USER_FAVORITE_TRACKS_WITH_FAVORITE_ID";
payload: {
trackCode: string;
favoriteId: number;
};
};
export type SessionStartUpdate = {
type: "USER_SESSION_START_UPDATE";
payload: {
sessionStartAt: Date;
};
};
export const updateBalance = (balance: number): UpdateBalanceActionType => ({
type: "USER_BALANCE_SUCCESS",
payload: { balance }
});
export const failBalanceRequest = (err: Error): FailBalanceRequestAction => ({
type: "USER_BALANCE_FAIL",
payload: err,
error: true
});
export const updateWalletBalances = (
balance: number,
bonus: number,
sharedDeposits: number,
sharedWinnings: number
): UpdateWalletBalancesActionType => ({
type: "USER_WALLET_BALANCES_SUCCESS",
payload: { balance, bonus, sharedDeposits, sharedWinnings }
});
export const updatePromoFunds = (
promoFunds: number
): UpdatePromoFundsActionType => ({
type: "USER_PROMO_FUNDS_SUCCESS",
payload: { promoFunds }
});
export const setFavoriteTrack = (
trackCode: string,
favoriteId?: number
): SetFavoriteTrackActionType => ({
type: "SET_FAVORITE_TRACK",
payload: { trackCode, favoriteId }
});
export const removeFavoriteTrack = (
trackCode: string
): RemoveFavoriteTrackActionType => ({
type: "REMOVE_FAVORITE_TRACK",
payload: { trackCode }
});
export const setDefaultBetPrefs =
(preferences: {}): SetDefaultBetPrefsAction => ({
type: "SET_DEFAULT_BET_PREFERENCES",
payload: preferences
});
export const setNewPreferenceValue = (
preferenceKey: string,
preferenceValue: string
): SetNewPreferenceValue => ({
type: "SET_NEW_PREFERENCE_VALUE",
payload: { preferenceKey, preferenceValue }
});
export const setRaceAlerts = (
channels: ChannelUFC[]
): SetRaceAlertsActionType => ({
type: "SET_RACE_ALERTS",
payload: { channels }
});
export const setUserFavoriteTracksWithId = (
favoriteTracksWithId: FavoriteTrackWithId
): SetUserFavoriteTracksWithIdActionType => ({
type: "SET_USER_FAVORITE_TRACKS_WITH_FAVORITE_ID",
payload: { favoriteTracksWithId }
});
export const setUserFavoriteTracks = (
favoriteTracks: string[]
): SetUserFavoriteTracks => ({
type: "SET_USER_FAVORITE_TRACKS",
payload: { favoriteTracks }
});
export const setUserFavoriteTrack = (
trackCode: string,
favoriteId: number
): SetUserFavoriteTrack => ({
type: "SET_FAVORITE_TRACK",
payload: { trackCode, favoriteId }
});
export const sessionStartUpdate = (
sessionStartAt: Date
): SessionStartUpdate => ({
type: "USER_SESSION_START_UPDATE",
payload: {
sessionStartAt
}
});
webpack://frontend-mybets/../../packages/urp-lib-shared-redux/BetSource/utils.ts
export const SelectionSourceMapping: { [key: string]: string } = {
same_race_parlay: "same_race_parlay_card",
quick_picks: "quick_picks"
};
export const getSelectionSourceFromModule = (
betSourceModule: string | undefined | null
) => {
if (!betSourceModule) return undefined;
return SelectionSourceMapping[betSourceModule];
};
export const CustomBetMapping: { [key: string]: string } = {
same_race_parlay: "SRP",
quick_picks: "QP"
};
export const getCustomBetTypeFromModule = (
betSourceModule: string | undefined | null
) => {
if (!betSourceModule) return undefined;
return CustomBetMapping[betSourceModule];
};
webpack://frontend-mybets/../../packages/tvg-comp-desktop-bet-ticket/src/store/actions.ts
import { TalentPick } from "@tvg/ts-types/TalentPicks";
import { BetGroupStatus, BetStateType, BetTicketGroupType } from "../types";
export type SetStartBettingAction = {
type: "SET_START_BETTING";
payload: boolean;
};
export type SetHasUserSetAmountAction = {
type: "SET_HAS_USER_SET_AMOUNT";
payload: boolean;
};
export type SetRaceOfBet = {
type: "SET_RACE_OF_BET";
payload: string;
};
export type SetBetAmountAction = {
type: "SET_BET_AMOUNT";
payload: number;
};
export type SetSelectionScratchedAction = {
type: "SET_SELECTION_SCRATCHED";
payload: string[][];
};
export type SetBetTypeAction = {
type: "SET_BET_TYPE";
payload: number | null | undefined;
};
export type SetAllowAlternateAction = {
type: "SET_ALLOW_ALTERNATE";
payload: boolean;
};
export type SetBetSelectionsAction = {
type: "SET_BET_SELECTIONS";
payload: string[][];
};
export type SetBetSelectionsMatrixAction = {
type: "SET_SELECTIONS_MATRIX";
payload: { selections: string[][] };
};
export type ResetBetSelectionsAction = {
type: "RESET_BET_SELECTIONS";
};
export type ResetBetSelectctionsKeepWinAction = {
type: "RESET_BET_SELECTIONS_KEEP_WIN";
payload?: number;
};
export type ResetBettingAction = {
type: "RESET_BETTING";
};
export type SetBetStateAction = {
type: "SET_BET_STATE";
payload: BetStateType;
};
export type SetGroupBetTicketStatus = {
type: "SET_GROUP_BET_TICKET_STATUS";
payload: BetTicketGroupType;
};
export type SetGroupBetTicketStatusClear = {
type: "SET_GROUP_BET_TICKET_STATUS_CLEAR";
};
export type SetGroupBetTicketStatusClearAll = {
type: "SET_GROUP_BET_TICKET_STATUS_CLEAR_ALL";
};
export type SetPickLegAction = {
type: "SET_PICK_LEG";
payload: number;
};
export type SetPickAction = {
type: "SET_PICK";
payload: {
value: TalentPick | null | undefined;
};
};
export type SetGroupBetAddProcessing = {
type: "SET_GROUP_BET_ADD_PROCESSING";
};
export type SetGroupBetAddSuccess = {
type: "SET_GROUP_BET_ADD_SUCCESS";
};
export type SetGroupBetAddError = {
type: "SET_GROUP_BET_ADD_ERROR";
};
export type SetGroupBetRemoveProcessing = {
type: "SET_GROUP_BET_REMOVE_PROCESSING";
};
export type SetGroupBetRemoveSuccess = {
type: "SET_GROUP_BET_REMOVE_SUCCESS";
};
export type SetGroupBetRemoveError = {
type: "SET_GROUP_BET_REMOVE_ERROR";
};
export type SetBetSlipOpen = {
type: "SET_BET_SLIP_OPEN";
payload: boolean;
};
export type SetAddToBetSlipOrigin = {
type: "SET_ADD_TO_BET_SLIP_ORIGIN";
payload: string;
};
export type SetBetTipHeight = {
type: "SET_BET_TIP_HEIGHT";
payload: number;
};
export type Actions =
| SetStartBettingAction
| SetBetAmountAction
| SetSelectionScratchedAction
| SetBetTypeAction
| SetAllowAlternateAction
| SetBetSelectionsAction
| SetHasUserSetAmountAction
| SetBetSelectionsMatrixAction
| ResetBetSelectionsAction
| ResetBetSelectctionsKeepWinAction
| ResetBettingAction
| SetBetStateAction
| SetPickLegAction
| SetPickAction
| SetRaceOfBet
| SetGroupBetTicketStatus
| SetGroupBetTicketStatusClear
| SetGroupBetTicketStatusClearAll
| SetGroupBetAddProcessing
| SetGroupBetAddSuccess
| SetGroupBetAddError
| SetGroupBetRemoveProcessing
| SetGroupBetRemoveSuccess
| SetGroupBetRemoveError
| SetBetSlipOpen
| SetBetTipHeight
| SetAddToBetSlipOrigin;
export const setStartBetting = (
value: boolean = true
): SetStartBettingAction => ({
type: "SET_START_BETTING",
payload: value
});
export const setHasUserSetAmount = (
value: boolean
): SetHasUserSetAmountAction => ({
type: "SET_HAS_USER_SET_AMOUNT",
payload: value
});
export const setBetAmount = (value: number): SetBetAmountAction => ({
type: "SET_BET_AMOUNT",
payload: value
});
export const setSelectionScratched = (
value: string[][]
): SetSelectionScratchedAction => ({
type: "SET_SELECTION_SCRATCHED",
payload: value
});
export const setBetType = (
value: number | null | undefined
): SetBetTypeAction => ({
type: "SET_BET_TYPE",
payload: value
});
export const setAllowAlternate = (value: boolean): SetAllowAlternateAction => ({
type: "SET_ALLOW_ALTERNATE",
payload: value
});
export const setRaceOfBet = (value: string): SetRaceOfBet => ({
type: "SET_RACE_OF_BET",
payload: value
});
export const setSelectionRequest = (
selections: string[][]
): SetBetSelectionsAction => ({
type: "SET_BET_SELECTIONS",
payload: selections
});
export const setSelectionMatrixRequest = (selections: {
selections: string[][];
}): SetBetSelectionsMatrixAction => ({
type: "SET_SELECTIONS_MATRIX",
payload: selections
});
export const resetBetSelection = (): ResetBetSelectionsAction => ({
type: "RESET_BET_SELECTIONS"
});
export const resetBetSelectionsKeepWin = (
columnCount?: number
): ResetBetSelectctionsKeepWinAction => ({
type: "RESET_BET_SELECTIONS_KEEP_WIN",
payload: columnCount
});
export const resetBetting = (): ResetBettingAction => ({
type: "RESET_BETTING"
});
export const setBetState = (value: BetStateType): SetBetStateAction => ({
type: "SET_BET_STATE",
payload: value
});
export const setPickLeg = (value: number): SetPickLegAction => ({
type: "SET_PICK_LEG",
payload: value
});
export const setBetSlipOpen = (value: boolean): SetBetSlipOpen => ({
type: "SET_BET_SLIP_OPEN",
payload: value
});
export const setPickAction = (
value: TalentPick | null | undefined
): SetPickAction => ({
type: "SET_PICK",
payload: {
value
}
});
export const setGroupBetTicketStatusAction = (
betGroupStatus: BetGroupStatus,
isRepeat?: boolean
): SetGroupBetTicketStatus => ({
type: "SET_GROUP_BET_TICKET_STATUS",
payload: {
betGroupStatus,
isRepeat
}
});
export const setGroupBetTicketStatusClearAction = () => ({
type: "SET_GROUP_BET_TICKET_STATUS_CLEAR"
});
export const setGroupBetTicketStatusClearAllAction = () => ({
type: "SET_GROUP_BET_TICKET_STATUS_CLEAR_ALL"
});
export const setGroupBetAddProcessingAction = () => ({
type: "SET_GROUP_BET_ADD_PROCESSING"
});
export const setGroupBetAddSuccessAction = () => ({
type: "SET_GROUP_BET_ADD_SUCCESS"
});
export const setGroupBetAddErrorAction = () => ({
type: "SET_GROUP_BET_ADD_ERROR"
});
export const setGroupBetRemoveProcessingAction = () => ({
type: "SET_GROUP_BET_REMOVE_PROCESSING"
});
export const setGroupBetRemoveSuccessAction = () => ({
type: "SET_GROUP_BET_REMOVE_SUCCESS"
});
export const setGroupBetRemoveErrorAction = () => ({
type: "SET_GROUP_BET_REMOVE_ERROR"
});
export const setAddToBetSlipOriginAction = (origin: string) => ({
type: "SET_ADD_TO_BET_SLIP_ORIGIN",
payload: origin
});
webpack://frontend-mybets/../../packages/tvg-lib-utils/capiWtxMessagesUtils.ts
import { replace, toPairs, words } from "lodash";
export type CAPIVariable = {
[key: string]: string | number;
};
export const CAPIVariableRegex = (key?: string) =>
key ? new RegExp(`~${key}~`) : new RegExp("~[a-z]+[0-9]?~", "gi");
export const extractNumberOfText = (text: string, fixed?: number) => {
const regExOnlyNumber = new RegExp("(\\d*[\\.\\,])?\\d+", "g");
const stringNumbers = words(text, regExOnlyNumber);
let formattedNumbers = stringNumbers;
if (fixed) {
formattedNumbers = stringNumbers.map((stringNumber) =>
(+stringNumber).toFixed(fixed)
);
}
return formattedNumbers;
};
export const replaceCAPIVariables = (
message: string,
variables: CAPIVariable
) => {
let modifiedMessage = message;
toPairs(variables).forEach(([key, value]) => {
modifiedMessage = replace(
modifiedMessage,
CAPIVariableRegex(key),
String(value)
);
});
return modifiedMessage;
};
webpack://frontend-mybets/../../packages/tvg-lib-utils/appsflyerUtils.js
import mediator from "@tvg/mediator";
export const AppsFlyerEvents = {
AfPlaceWager: "rac_product_bet_successful",
AfPlaceFirstWager: "rac_product_first_bet_successful",
AfAppLunch: "af_app_launch",
AfLogin: "af_login",
AfBetCost: "af_bet_cost",
AfCompleteRegistration: "af_complete_registration"
};
const APPS_FLYER_TYPE = "APPSFLYER_EVENT";
const APP_FLYER_EMPTY_VALUES = { values: { "": "" } };
const sendToAppsFlyer = (payload) => {
const appsFlyerPayload = {
type: APPS_FLYER_TYPE,
payload: {
appsflyer: {
...APP_FLYER_EMPTY_VALUES,
...payload
}
}
};
if (
window &&
window.webkit &&
window.webkit.messageHandlers &&
window.webkit.messageHandlers.APPSFLYER_EVENT
) {
window.webkit.messageHandlers.APPSFLYER_EVENT.postMessage(appsFlyerPayload);
} else {
mediator.ios.dispatch(appsFlyerPayload);
}
};
export default sendToAppsFlyer;
webpack://frontend-mybets/../../packages/tvg-lib-api/uam/index.ts
import tvgConf from "@tvg/conf";
import { SSNObject, UserDetails, SignupDetails } from "@tvg/ts-types/User";
import { UamPreference } from "frontend-pctr/src/store/actions/types";
import getProtocol from "../protocolSetter";
import requester from "../requester";
import { serviceResponse } from "../types";
export const TVG_ACCOUNT_ID_NOT_FOUND_EXCEPTION = 158408;
export const FDR_EXPIRED_TOKEN_EXCEPTION = 158405;
export const FDR_USER_NOT_VERIFIED_EXCEPTION = 126777;
export const INELIGIBLE_RESIDENCY_STATE_FOR_RACING = 136527;
export const INELIGIBLE_RESIDENCY_STATE_FOR_RACING_MESSAGE =
"INELIGIBLE_RESIDENCY_STATE_FOR_RACING";
export const TERMS_AND_CONDITIONS_OR_ACKNOWLEDGES_NOT_ACCEPTED = 136528;
export const INELIGIBLE_LOCATION = 136530;
export const GEO_COMPLY_EXPIRED = 136531;
export const GEO_COMPLY_REJECTED = 136524;
export const INSUFFICIENT_FUNDS = 136518;
export const WAGER_LIMIT = 136521;
export const WAGER_SIZE_LIMIT = 136522;
export const UNVERIFIED_ACCOUNT = 136523;
const uamService: string = "service.uam";
const getUamServiceUrl = (): string =>
`${getProtocol()}${tvgConf().config(uamService)}`;
const getUserPrefs = (
accountNumber: string
): Promise<
serviceResponse<{
preferences: UamPreference[];
}>
> =>
requester()({
url: `${getUamServiceUrl()}/users/${accountNumber}/preferences`,
method: "get",
withCredentials: true,
headers: { "x-tvg-context": tvgConf().context() }
});
const setUserPref = (
accountNumber: string,
prefName: string,
prefValue: unknown
): Promise<serviceResponse> =>
requester()({
url: `${getUamServiceUrl()}/users/${accountNumber}/preferences`,
method: "put",
withCredentials: true,
headers: { "x-tvg-context": tvgConf().context() },
data: {
preferences: [
{
description: prefName,
metadata: prefValue
}
]
}
});
const getUserRaceFilters = (accountNumber: string): Promise<serviceResponse> =>
requester()({
url: `${getUamServiceUrl()}/users/${accountNumber}/preferences/raceFilters`,
method: "get",
withCredentials: true,
headers: { "x-tvg-context": tvgConf().context() }
});
const getUserRegionFilters = (
accountNumber: number
): Promise<serviceResponse> =>
requester()({
url: `${getUamServiceUrl()}/users/${accountNumber}/preferences/regionFilters`,
method: "get",
withCredentials: true,
headers: { "x-tvg-context": tvgConf().context() }
});
/**
* Saves race filters on the user preferences
* @param filters - an array with the filter code strings (eg. ["T", "H"]
* @param accountNumber - the account number
*/
const saveRaceFilters = (
filters: string[],
accountNumber: string
): Promise<serviceResponse> => {
const metadata = {
group: "ALL",
breed: filters
};
return requester()({
url: `${getUamServiceUrl()}/users/${accountNumber}/preferences`,
method: "put",
withCredentials: true,
headers: { "x-tvg-context": tvgConf().context() },
data: {
preferences: [
{
description: "raceFilters",
metadata: JSON.stringify(metadata)
}
]
}
});
};
/**
* Saves region filters on the user preferences
* @param filters - an array with the filter code strings (eg. ["USA", "INT"]
* @param accountNumber - the account number
*/
const saveRegionFilters = (
filters: string[],
accountNumber: string
): Promise<serviceResponse> => {
const metadata = {
group: "ALL",
regions: filters
};
return requester()({
url: `${getUamServiceUrl()}/users/${accountNumber}/preferences`,
method: "put",
withCredentials: true,
headers: { "x-tvg-context": tvgConf().context() },
data: {
preferences: [
{
description: "regionFilters",
metadata: JSON.stringify(metadata)
}
]
}
});
};
/**
* Saves region filters on the user preferences
* @param accountNumber - the account number
* @param exclusionType - exclusion type (eg. ["TIMOUT", "SELF_EXCLUSION", "SUSPEND"]
* @param periodInDays - period in days (null case 'exclusionType'==='SUSPEND')
*/
const selfExclusion = (
accountNumber: string,
exclusionType: string,
periodInDays: number | undefined
): Promise<serviceResponse> =>
requester()({
url: `${getUamServiceUrl()}/users/${accountNumber}/status/self-exclusion`,
method: "post",
withCredentials: true,
headers: { "x-tvg-context": tvgConf().context() },
data: {
exclusionType,
periodInDays
}
});
const getUserProfile = (userId: string): Promise<serviceResponse> =>
requester()({
method: "get",
url: `${getUamServiceUrl()}/users/${userId}/profile`,
headers: { "x-tvg-context": tvgConf().context() },
withCredentials: true
});
const getFDRUserProfile = (): Promise<serviceResponse> =>
requester()({
method: "get",
url: `${getUamServiceUrl()}/FDR/users/profile`,
headers: { "x-tvg-context": tvgConf().context() },
withCredentials: true
});
const getPromoValidation = (promoCode: string): Promise<serviceResponse> =>
requester()({
method: "get",
url: `${getUamServiceUrl()}/registration/promocodes/validation?promocode=${promoCode}`,
headers: { "x-tvg-context": tvgConf().context() }
});
const getZipCodeValidation = (zipcode: number): Promise<serviceResponse> =>
requester()({
method: "get",
url: `${getUamServiceUrl()}/registration/zipcodes/validation/${zipcode}`,
headers: { "x-tvg-context": tvgConf().context() }
});
const getStateValidation = (
stateAbbreviation: number
): Promise<serviceResponse> =>
requester()({
method: "get",
url: `${getUamServiceUrl()}/states/${stateAbbreviation}`,
headers: { "x-tvg-context": tvgConf().context() }
});
const postUserRegistration = ({
userDetails,
signupDetails,
enableOnfido
}: {
userDetails: UserDetails;
signupDetails: SignupDetails;
enableOnfido: boolean;
}): Promise<serviceResponse> =>
requester()({
method: "post",
url: `${getUamServiceUrl()}/users`,
headers: { "x-tvg-context": tvgConf().context(), "x-onfido": enableOnfido },
data: {
userDetails,
signupDetails
}
});
const postGetSSNValidation = ({
ssnObject
}: {
ssnObject: SSNObject;
}): Promise<serviceResponse> =>
requester()({
method: "post",
url: `${getUamServiceUrl()}/registration/ssn/validation`,
headers: { "x-tvg-context": tvgConf().context() },
data: ssnObject
});
const postOnfidoCheck = ({
accountId,
onfidoApplicantId,
verificationUuid
}: {
accountId: string;
onfidoApplicantId: string;
verificationUuid: string;
}): Promise<serviceResponse> =>
requester()({
method: "post",
url: `${getUamServiceUrl()}/users/${accountId}/onfido-check`,
headers: { "x-tvg-context": tvgConf().context() },
data: {
onfidoApplicantId,
verificationUuid
}
});
const getOnfidoCheck = ({
accountId,
checkId
}: {
accountId: string;
checkId: string;
}): Promise<serviceResponse> =>
requester()({
method: "get",
url: `${getUamServiceUrl()}/users/${accountId}/onfido-check/${checkId}`,
headers: { "x-tvg-context": tvgConf().context() }
});
const postFDRProfileMigration = (
userId: string,
stateAbbr: string,
email: string
): Promise<serviceResponse> =>
requester()({
method: "post",
url: `${getUamServiceUrl()}/FDR/users`,
headers: { "x-tvg-context": tvgConf().context(), "ghost-account": true },
withCredentials: true,
data: {
externalUserId: userId,
userDetails: {
email,
homeAddress: {
state: stateAbbr
}
},
signupDetails: {
rfr: document.cookie.match(`(^|;)\\s*RFR\\s*=\\s*([^;]+)`)?.pop() || ""
}
}
});
const UAM_SERVICE = {
getUserRaceFilters,
getUserRegionFilters,
saveRaceFilters,
saveRegionFilters,
getUserPrefs,
setUserPref,
selfExclusion,
getUserProfile,
getFDRUserProfile,
getPromoValidation,
getZipCodeValidation,
getStateValidation,
postUserRegistration,
postGetSSNValidation,
postOnfidoCheck,
getOnfidoCheck,
postFDRProfileMigration,
// Constrains
TVG_ACCOUNT_ID_NOT_FOUND_EXCEPTION,
FDR_USER_NOT_VERIFIED_EXCEPTION,
INELIGIBLE_RESIDENCY_STATE_FOR_RACING,
INELIGIBLE_RESIDENCY_STATE_FOR_RACING_MESSAGE,
TERMS_AND_CONDITIONS_OR_ACKNOWLEDGES_NOT_ACCEPTED,
INELIGIBLE_LOCATION,
GEO_COMPLY_EXPIRED,
GEO_COMPLY_REJECTED,
INSUFFICIENT_FUNDS,
WAGER_LIMIT,
WAGER_SIZE_LIMIT,
UNVERIFIED_ACCOUNT
};
export default UAM_SERVICE;
webpack://frontend-mybets/../../packages/tvg-lib-api/aw/index.ts
import { get } from "lodash";
import tvgConf from "@tvg/conf";
import requester from "@tvg/api/requester";
import {
WalletData,
UserJurisdictionsData,
UsersFanduel,
WalletDataRow
} from "./types";
const { config, getClientId } = tvgConf();
const baseURL = config("externalServices.fanduel");
const clientId = getClientId();
export const getWalletBalances = (authToken: string) =>
requester()({
baseURL,
url: "/account/wallet",
method: "get",
withCredentials: true,
headers: {
"X-Auth-Token": authToken,
Authorization: `Basic ${clientId}`
}
}).then(
(result: { data: { wallet_balances: WalletData } }) =>
get(result, "data.wallet_balances", []) as WalletDataRow[]
);
export const getUserJurisdictions = (
authToken: string,
userId: string,
jurisdiction: string
): Promise<UserJurisdictionsData> =>
requester()({
baseURL,
url: `/users/${userId}/jurisdictions/${jurisdiction}/product/RACING`,
method: "get",
withCredentials: true,
headers: {
"X-Auth-Token": authToken,
Authorization: `Basic ${clientId}`
}
}).then((result: { data: { user_jurisdictions: UserJurisdictionsData } }) =>
get(result, "data.user_jurisdictions")
);
export const getFanduelUserProfile = (
authToken: string
): Promise<UsersFanduel> =>
requester()({
baseURL,
url: `/users/current`,
method: "get",
withCredentials: true,
headers: {
"X-Auth-Token": authToken,
Authorization: `Basic ${clientId}`
}
}) as unknown as Promise<UsersFanduel>;
webpack://frontend-mybets/../../packages/urp-lib-unified-modules/src/utils/mediator/types.ts
export interface Payload<T = string, P = unknown> {
type: T;
payload?: P;
}
export enum UMEventsGeneric {
HotReload = "HOT_RELOAD"
}
export enum UMEventsAccount {
Session = "GET_SESSION",
Join = "TRIGGER_JOIN",
Logout = "TRIGGER_LOGOUT",
OpenSettings = "OPEN_USER_SETTINGS",
PresentModal = "PRESENT_MODAL",
AcceptTerms = "TRIGGER_ACCEPT_TERMS",
Verification = "TRIGGER_VERIFICATION",
KeepAlive = "KEEP_ALIVE",
SessionUpdate = "SESSION_UPDATE",
FirstLoad = "FIRST_LOAD"
}
export enum UMEventsWallet {
GetBalance = "GET_BALANCE",
Deposit = "DEPOSIT",
Tax = "TAX",
Transactions = "TRANSACTIONS",
Withdraw = "WITHDRAW",
Activity = "ACTIVITY",
AccountHome = "ACCOUNT_HOME"
}
export enum UMEventsAmplitude {
SetDeviceId = "SET_DEVICE_ID",
SetSessionId = "SET_SESSION_ID"
}
export enum UMEventsResponsibleGaming {
ResponsiblePlay = "RESPONSIBLE_PLAY",
RealityCheck = "REALITY_CHECK",
GlobalDepositLimits = "GLOBAL_DEPOSIT_LIMITS"
}
export const UMEvents = {
...UMEventsAccount,
...UMEventsWallet,
...UMEventsAmplitude,
...UMEventsGeneric,
...UMEventsResponsibleGaming
};
webpack://frontend-mybets/../../packages/urp-lib-unified-modules/src/utils/mediator/events.ts
import {
UMEventsAccount,
UMEventsAmplitude,
UMEventsGeneric,
UMEventsResponsibleGaming,
UMEventsWallet
} from "./types";
export const getUMEvent = (
event:
| UMEventsAccount
| UMEventsWallet
| UMEventsAmplitude
| UMEventsGeneric
| UMEventsResponsibleGaming
) => ({
trigger: event,
completion: `${event}_COMPLETE`
});
webpack://frontend-mybets/../../packages/urp-lib-unified-modules/src/utils/mediator/apps/web/events.ts
import { UMEvents } from "../../types";
import type { Events } from "../types";
export default {
// Account
[UMEvents.OpenSettings]: `UM_ACCOUNT_OPEN_SETTINGS`,
[UMEvents.FirstLoad]: `UM_ACCOUNT_FIRST_LOAD`,
[UMEvents.KeepAlive]: `UM_ACCOUNT_KEEP_ALIVE`,
[UMEvents.Logout]: `UM_ACCOUNT_LOGOUT`,
[UMEvents.Session]: `UM_ACCOUNT_SESSION`,
[UMEvents.SessionUpdate]: `UM_ACCOUNT_SESSION_UPDATE`,
[UMEvents.Verification]: `UM_ACCOUNT_VERIFICATION`,
[UMEvents.AcceptTerms]: `UM_ACCOUNT_ACCEPT_TERMS`,
// Generic
[UMEvents.PresentModal]: `UM_ACCOUNT_PRESENT_MODAL`,
// Wallet
[UMEvents.GetBalance]: `UM_ACCOUNT_GET_BALANCE`,
[UMEvents.Deposit]: `UM_ACCOUNT_DEPOSIT`,
[UMEvents.Tax]: `UM_ACCOUNT_TAX`,
[UMEvents.Transactions]: `UM_ACCOUNT_TRANSACTIONS`,
[UMEvents.Withdraw]: `UM_ACCOUNT_WITHDRAW`,
[UMEvents.Activity]: `UM_ACCOUNT_ACTIVITY`,
[UMEvents.AccountHome]: `UM_ACCOUNT_ACCOUNT_HOME`,
// Amplitude
[UMEvents.SetSessionId]: "UM_SET_SESSION_ID",
[UMEvents.SetDeviceId]: "UM_SET_DEVICE_ID",
// ResponsibleGaming
[UMEvents.ResponsiblePlay]: "UM_RESPONSIBLE_PLAY",
[UMEvents.RealityCheck]: "UM_REALITY_CHECK",
[UMEvents.GlobalDepositLimits]: "UM_GLOBAL_DEPOSIT_LIMITS"
} as Events;
webpack://frontend-mybets/../../packages/urp-lib-unified-modules/src/utils/mediator/apps/formatEvents.ts
import { isArray, omitBy } from "lodash";
import { getUMEvent } from "../events";
import type { Events } from "./types";
import type { UMEventsAccount, UMEventsWallet } from "../types";
export const formatEvents = (events: Events) =>
Object.entries(events).reduce(
(eventsAcc, currentEvent) => {
const [eventKey, mapEventValue] = currentEvent;
let eventTrigger;
let eventCompletion;
if (typeof mapEventValue === "string") {
const eventFormatted = getUMEvent(
mapEventValue as UMEventsAccount | UMEventsWallet
);
eventTrigger = eventFormatted.trigger;
eventCompletion = eventFormatted.completion;
} else if (isArray(mapEventValue)) {
eventTrigger = mapEventValue[0];
eventCompletion = mapEventValue[1];
} else {
throw new Error("[UM]: Wrong configuration on UM events");
}
const eventsWithCompletion = omitBy(
{
[eventKey]: eventTrigger,
[`${eventKey}_COMPLETE`]: eventCompletion
},
(event) => event === ""
);
return {
triggers: {
...eventsAcc.triggers,
...eventsWithCompletion
},
subscriptions: {
...eventsAcc.subscriptions,
...eventsWithCompletion
}
};
},
{
triggers: {},
subscriptions: {}
}
);
webpack://frontend-mybets/../../packages/urp-lib-unified-modules/src/utils/mediator/apps/web/index.ts
import events from "./events";
import { AppConfig } from "../types";
import { formatEvents } from "../formatEvents";
export default formatEvents(events) as AppConfig;
webpack://frontend-mybets/../../packages/urp-lib-unified-modules/src/utils/mediator/apps/hybrid/events.ts
import { UMEvents } from "../../types";
import type { Events } from "../types";
export default {
// Account
[UMEvents.OpenSettings]: `UM_ACCOUNT_OPEN_SETTINGS`,
[UMEvents.FirstLoad]: `UM_ACCOUNT_FIRST_LOAD`,
[UMEvents.KeepAlive]: `UM_ACCOUNT_KEEP_ALIVE`,
[UMEvents.Logout]: `UM_ACCOUNT_LOGOUT`,
[UMEvents.Session]: `UM_ACCOUNT_SESSION`,
[UMEvents.SessionUpdate]: `UM_ACCOUNT_SESSION_UPDATE`,
[UMEvents.Verification]: `UM_ACCOUNT_VERIFICATION`,
[UMEvents.AcceptTerms]: `UM_ACCOUNT_ACCEPT_TERMS`,
// Generic
[UMEvents.PresentModal]: `UM_ACCOUNT_PRESENT_MODAL`,
// Wallet
[UMEvents.GetBalance]: `UM_ACCOUNT_GET_BALANCE`,
[UMEvents.Deposit]: `UM_ACCOUNT_DEPOSIT`,
[UMEvents.Tax]: `UM_ACCOUNT_TAX`,
[UMEvents.Transactions]: `UM_ACCOUNT_TRANSACTIONS`,
[UMEvents.Withdraw]: `UM_ACCOUNT_WITHDRAW`,
[UMEvents.Activity]: `UM_ACCOUNT_ACTIVITY`,
[UMEvents.AccountHome]: `UM_ACCOUNT_ACCOUNT_HOME`,
// Amplitude
[UMEvents.SetSessionId]: "UM_SET_SESSION_ID",
[UMEvents.SetDeviceId]: "UM_SET_DEVICE_ID",
// Generic
[UMEvents.HotReload]: "UM_HOT_RELOAD",
// ResponsibleGaming
[UMEvents.ResponsiblePlay]: "UM_RESPONSIBLE_PLAY",
[UMEvents.RealityCheck]: "UM_REALITY_CHECK",
[UMEvents.GlobalDepositLimits]: "UM_GLOBAL_DEPOSIT_LIMITS"
} as Events;
webpack://frontend-mybets/../../packages/urp-lib-unified-modules/src/utils/mediator/apps/hybrid/index.ts
import events from "./events";
import { AppConfig } from "../types";
import { formatEvents } from "../formatEvents";
export default formatEvents(events) as AppConfig;
webpack://frontend-mybets/../../packages/urp-lib-unified-modules/src/utils/mediator/apps/xsell/events.ts
import { UMEvents } from "../../types";
import type { Events } from "../types";
export default {
// Account
[UMEvents.Session]: [
"x-sell/bridge/to-react/onTriggerLogin",
"x-sell/bridge/to-native/loginFlowComplete"
],
[UMEvents.Join]: ["x-sell/bridge/to-react/onTriggerJoin"],
[UMEvents.KeepAlive]: ["x-sell/bridge/to-react/onUserTouch"],
[UMEvents.AcceptTerms]: [
"x-sell/bridge/to-react/onTriggerAcceptTerms",
"UM_ACCOUNT_ACCEPT_TERMS_COMPLETED"
],
[UMEvents.Verification]: ["x-sell/bridge/to-react/onTriggerVerification"],
[UMEvents.OpenSettings]: ["x-sell/bridge/to-react/onTriggerAccountSummary"],
[UMEvents.FirstLoad]: ["x-sell/bridge/to-react/firstLoadComplete"],
// Wallet
[UMEvents.Deposit]: ["x-sell/bridge/to-react/onTriggerDeposit"],
// Only Subscription
[UMEvents.SessionUpdate]: [
undefined,
"x-sell/bridge/to-native/authDetailsUpdated"
],
[UMEvents.Logout]: [undefined, "x-sell/bridge/to-native/logoutFlowComplete"],
[UMEvents.PresentModal]: [
undefined,
"x-sell/bridge/to-native/accountAndWalletClosed"
]
} as Events;
webpack://frontend-mybets/../../packages/urp-lib-unified-modules/src/utils/mediator/apps/xsell/index.ts
import events from "./events";
import { AppConfig } from "../types";
import { formatEvents } from "../formatEvents";
export default formatEvents(events) as AppConfig;
webpack://frontend-mybets/../../packages/urp-lib-unified-modules/src/utils/mediator/index.ts
import mediator from "@tvg/mediator";
import { isMobile, isXSell } from "@tvg/sh-utils/mobileUtils";
import { get } from "lodash";
import { xSellConfig, webConfig, hybridConfig } from "./apps";
import { AppConfig, MediatorChannel } from "./apps/types";
let mediatorInstance: typeof mediator;
let eventMappedInstance: AppConfig | null = null;
const getMediatorChannel = (): MediatorChannel => {
if (!mediatorInstance) {
if (isMobile()) {
mediatorInstance = mediator.ios;
eventMappedInstance = isXSell() ? xSellConfig : hybridConfig;
} else {
mediatorInstance = mediator.base;
eventMappedInstance = webConfig;
}
}
return {
dispatch: (action) => {
const type = get(eventMappedInstance?.triggers, action?.type);
if (type) {
mediatorInstance.dispatch({
type,
payload: action.payload
});
} else {
console.warn(`[UM] Can't find event ${action?.type} to dispatch`);
}
},
subscribe: (eventType, callback) => {
const type = get(eventMappedInstance?.subscriptions, eventType);
if (type) {
mediatorInstance.subscribe(type, callback);
} else {
console.warn(`[UM] Can't find event ${eventType} to subscribe`);
}
}
};
};
export default getMediatorChannel();
webpack://frontend-mybets/../../packages/tvg-lib-ts-types/Amplitude.ts
export enum LoginModalMediatorEventType {
// TVG ONLY
START = "LOGIN_MODAL_START",
ATTEMPT = "LOGIN_MODAL_LOGIN_ATTEMPT",
SUCCESS = "LOGIN_MODAL_SUCCESS",
ERROR = "LOGIN_MODAL_LOGIN_ERROR",
FIELD_COMPLETE = "LOGIN_MODAL_FIELD_COMPLETE",
SELECT_STATE = "LOGIN_MODAL_SELECT_STATE",
FORGOT_CREDENTIALS = "LOGIN_MODAL_FORGOT_CREDENTIALS",
// FDR & TVG
LOCATION_MODAL_VIEWED = "LOGIN_MODAL_LOCATION_MODAL_VIEWED",
LOCATION_MODAL_CLOSED = "LOGIN_MODAL_LOCATION_MODAL_CLOSED",
LOCATION_MODAL_CTA_CLICKED = "LOGIN_MODAL_LOCATION_MODAL_CTA_CLICKED",
LOGIN_SERVICE_LOADED = "OPEN_LOGIN_SUCCESS",
LOGIN_MODAL_OPEN = "LOGIN_MODAL_OPENED",
REGISTRATION_MODAL_OPEN = "REGISTRATION_MODAL_OPENED",
LOGIN_ERROR_MODAL_VIEWED = "LOGIN_MODAL_DEFAULT_ERROR_VIEWED",
LOGIN_ERROR_MODAL_CTA_CLICKED = "LOGIN_MODAL_DEFAULT_ERROR_CTA_CLICKED",
LOGIN_ERROR_MODAL_CLOSED = "LOGIN_MODAL_DEFAULT_ERROR_CLOSED"
}
export enum ProgramPageMediatorEventType {
URP_RUNNER_SELECTION = "PPM_TVG5_RUNNER_SELECTION",
RUNNER_SELECTION = "PPM_RUNNER_SELECTION",
SELECT_ALL_RUNNERS = "PPM_SELECT_ALL_RUNNERS",
RESET_ALL_RUNNERS = "PPM_RESET_ALL_RUNNERS",
SELECT_BET_TYPE = "PPM_SELECT_BET_TYPE",
SET_BET_AMOUNT = "PPM_SET_BET_AMOUNT",
BET_TIMEOUT = "PPM_BET_TIMEOUT",
BET_NOW = "PPM_BET_NOW",
DELETE_BET_TICKET = "PPM_DELETE_BET_TICKET",
OPEN_RACE_NAVIGATION = "PPM_OPEN_RACE_NAVIGATION",
HANDICAP_STORE_PRODUCT = "PPM_HANDICAP_STORE_PRODUCT",
HANDICAP_STORE_SEE_ALL = "PPM_HANDICAP_STORE_SEE_ALL",
RUNNER_MODIFIER_FILTER_APPLIED = "PROGRAM_PAGE_RUNNER_MODIFIER_FILTER_APPLIED",
RUNNER_MODIFIER_SORT_APPLIED = "PROGRAM_PAGE_RUNNER_MODIFIER_SORT_APPLIED",
WILL_PAYS_SELECT_OPTION = "PPM_WILL_PAYS_SELECT_OPTION",
PROBABLES_SELECT_OPTION = "PPM_PROBABLES_SELECT_OPTION",
PROGRAM_RUNNER_INFO_MODAL_OPENED = "PROGRAM_RUNNER_INFO_MODAL_OPENED",
PROGRAM_RUNNER_INFO_MODAL_CLOSED = "PROGRAM_RUNNER_INFO_MODAL_CLOSED",
FAVORITE_INTERACTION = "PPM_FAVORITE_INTERACTION",
POOLS_AND_INFO_MODAL_OPENED = "POOLS_AND_INFO_MODAL_OPENED",
POOLS_AND_INFO_TAB_OPENED = "POOLS_AND_INFO_TAB_OPENED",
HANDICAPPING_TAB_OPENED = "HANDICAPPING_TAB_OPENED",
RUNNER_TAGS_EXPANDED = "RUNNER_TAGS_EXPANDED",
PROGRAM_FREE_PP_DOWNLOAD = "PROGRAM_FREE_PP_DOWNLOAD",
DROPDOWN_OPEN = "PPM_DROPDOWN_OPEN",
DROPDOWN_RACE_SELECTED = "PPM_DROPDOWN_RACE_SELECTED",
ALTERNATE_SELECTION = "ALTERNATE_SELECTION"
}
export enum GlobalWalletMediatorEventType {
BALANCE_EXPANDED = "BALANCE_EXPANDED",
NAVIGATION = "MORE_NAVIGATION",
ACCOUNT_NAVIGATION = "ACCOUNT_NAVIGATION",
OPEN_CONTENT = "MORE_OPEN_CONTENT",
SWITCH_TOGGLE = "MORE_SWITCH_TOGGLE",
SUPPORT_TOGGLE = "SUPPORT_MODAL_TOGGLE",
WITHDRAW_DEPOSIT = "WITHDRAWAL_AND_DEPOSIT_BUTTON",
VIEW_BALANCE_DETAILS = "VIEW_BALANCE_DETAILS",
PLAYABLE_BALANCE_MODAL = "PLAYABLE_BALANCE_MODAL"
}
export enum RaceCellMediatorEventType {
CLICKED = "RACE_CELL_CLICKED"
}
export enum RaceCellModule {
TRACKS_AZ = "tracks_az",
FAVORITES = "favorites",
UPCOMING_RACES = "upcoming_races",
TIL = "tracks_information",
POOLS = "top_pools",
TOP_TRACKS = "top_tracks",
WINNERS = "previous_winners"
}
export interface RaceCellEventData {
type: RaceCellMediatorEventType;
payload: {
module: RaceCellModule;
trackName: string;
raceNumber: string;
linkUrl: string;
raceHasPromos: boolean;
trackHasPromos: boolean;
promoOptedIn: "true" | "false" | "none";
isFDTV: boolean;
trackCountry: string;
tabActive?: string;
activeFilters?: Record<string, string>[];
filterName?: string;
filterValue?: string;
specialWagerType?:
| "advance"
| "future"
| "special_pick"
| "future_special_pick"
| "advance_special_pick"
| "none";
position?: number;
};
}
export enum TracksMediatorEventType {
TRACK_CLICK = "TRACKS_TRACK_CLICK",
RACE_NAVIGATION = "RACE_NAVIGATION",
FILTER_CLICK = "TRACKS_FILTER_CLICK",
TAB_OPENED = "TRACKS_TAB_OPENED",
FILTER_APPLIED = "TRACKS_FILTER_APPLIED",
SEARCH_APPLIED = "TRACKS_SEARCH_APPLIED",
TRACKS_FAVORITE = "TRACKS_FAVORITE",
ALL_FILTERS_MODAL_OPENED = "TRACKS_ALL_FILTERS_MODAL_OPENED"
}
export enum RaceTracksMediatorEventType {
PAGE_VIEW = "RACETRACKS:PAGE_VIEW",
TRACK_CLICK = "RACETRACKS:TRACK_CLICK",
RACE_CLICK = "RACETRACKS:RACE_CLICK",
ADD_FAVORITE_CLICK = "RACETRACKS:ADD_FAVORITE_CLICK",
ADD_FAVORITE_SUCCESS = "RACETRACKS:ADD_FAVORITE_SUCCESS",
SEE_ALL_TODAYS_RACING = "RACETRACKS:SEE_ALL_TODAYS_RACING",
RETURN_TO_RACETRACKS = "RACETRACKS:RETURN_TO_RACETRACKS"
}
export interface RaceTracksDataPayload {
trackName?: string;
raceNumber?: number;
mtp?: number;
destinationUrl?: string;
}
webpack://frontend-mybets/../../packages/urp-lib-unified-modules/src/utils/account/gtm/index.ts
import mediator from "@tvg/mediator";
import { LoginModalMediatorEventType } from "@tvg/ts-types/Amplitude";
import type { UserInfo } from "../../../types/account/user";
// All of those functions have weird name, but I can't identify if we can change and If is really necessary,
// so I'll keep, but if in future you know, please change that.
export const loginSuccessGtm = (accountId: string, userBalance?: number) => {
mediator.base.dispatch({
type: "FDR_LOGIN_SUCCESS",
payload: {
accountId,
userBalance
}
});
};
export const openLoginSuccessGtm = (user: UserInfo, isVerified: boolean) => {
mediator.base.dispatch({
type: LoginModalMediatorEventType.LOGIN_SERVICE_LOADED,
payload: { user, isVerified }
});
};
webpack://frontend-mybets/../../packages/urp-lib-unified-modules/src/hooks/useWallet/hooks/useSubscriptions/utils/completion/getBalance/setRacingWallet.ts
// @ts-nocheck
import { Dispatch } from "redux";
import { get, set, has } from "lodash";
import type { Balance } from "@fanduel/wallet-contract";
import {
failBalanceRequest,
updateWalletBalances
} from "@tvg/shared-actions/UserActions";
import * as mediatorClassic from "@tvg/mediator-classic/src";
import { loginSuccessGtm } from "../../../../../../../utils/account/gtm";
const balanceMap = {
RACING_PLAYABLE: "racingPlayable",
USER_RACING_BONUS: "racingBonus",
RACING_OTHER_CASH: "sharedDeposits",
SHARED_WINNINGS: "sharedWinnings"
};
export const setRacingWallet = (
balances: Set<Balance> | null,
dispatch: Dispatch,
accountNumber?: string
) => {
let balancePlayable: number | undefined;
if (balances) {
const racingWalletBalances = {};
balances.forEach((wallet) => {
// TODO: remove this accountTypeKey after the standardization of the keys sent by wallet lib (there's a mismatch between ios and android)
const accountTypeKey = has(wallet, "accountType")
? "accountType"
: "account_type";
/* @ts-ignore */
const walletKey = get(balanceMap, wallet[accountTypeKey]);
if (walletKey) {
set(racingWalletBalances, walletKey, wallet.balance);
}
});
balancePlayable = get(racingWalletBalances, balanceMap.RACING_PLAYABLE);
dispatch(
updateWalletBalances(
get(racingWalletBalances, "racingPlayable"),
get(racingWalletBalances, "racingBonus"),
get(racingWalletBalances, "sharedDeposits"),
get(racingWalletBalances, "sharedWinnings")
)
);
mediatorClassic.dispatch("BALANCE_UPDATE", balancePlayable);
} else {
dispatch(failBalanceRequest());
}
// TODO: Move this because is in wrong place.
if (accountNumber) {
loginSuccessGtm(accountNumber, balancePlayable);
}
};
webpack://frontend-mybets/../../packages/urp-lib-unified-modules/src/utils/wallet/getBalance/index.ts
import { Dispatch } from "redux";
import { isXSell } from "@tvg/sh-utils/mobileUtils";
import { getWalletBalances } from "@tvg/api/aw";
import { getAuthTokenCookie } from "@tvg/sh-utils/sessionUtils";
import { getUMEvent } from "../../mediator/events";
import { UMEvents } from "../../mediator/types";
import mediator from "../../mediator";
import { setRacingWallet } from "../../../hooks/useWallet/hooks/useSubscriptions/utils/completion/getBalance/setRacingWallet";
export const getBalance = (dispatch?: Dispatch, accountNumber?: string) => {
if (isXSell()) {
const authToken = getAuthTokenCookie();
if (authToken && dispatch) {
getWalletBalances(getAuthTokenCookie())
.then((balances) => {
const formattedBalances = new Set(
balances.map(({ account_type, ...rawBalances }) => ({
...rawBalances,
accountType: account_type
}))
);
setRacingWallet(formattedBalances, dispatch, accountNumber);
})
.catch(() => console.warn("[UM] Get balance failed"));
}
} else {
const event = getUMEvent(UMEvents.GetBalance);
const payload = accountNumber
? {
gtm: {
accountNumber
}
}
: {};
mediator.dispatch({
type: event.trigger,
payload
});
}
};
webpack://frontend-mybets/../../packages/urp-lib-unified-modules/src/hooks/useAccount/hooks/useSubscriptions/services/getProfile/index.ts
// @ts-nocheck
import type { Dispatch } from "redux";
import profileService, {
FDR_USER_NOT_VERIFIED_EXCEPTION,
INELIGIBLE_RESIDENCY_STATE_FOR_RACING_MESSAGE,
TVG_ACCOUNT_ID_NOT_FOUND_EXCEPTION
} from "@tvg/api/uam";
import { get } from "lodash";
// @ts-ignore
import { setUserData } from "@fdr/shared-actions/UserActions";
import {
fdrGhostAccountExceptionAction,
resetStateLocationSplashAction
} from "@urp/location-splash/src/actions";
import { isXSell } from "@tvg/sh-utils/mobileUtils";
// @ts-ignore
import type { User } from "@fanduel/account-contract";
import {
UserProfile,
UserInfo,
GetUserProfile
} from "../../../../../../types/account/user";
const getUserInfo = (
accountUser: User,
userProfile?: UserProfile
): UserInfo => ({
userName: accountUser.username,
emailAddress: accountUser.email,
profile: get(userProfile, "wagerProfile", "FDR-Generic"),
accountNumber: String(get(userProfile, "accountNumber", "")),
firstName: accountUser.firstName,
lastName: accountUser.lastName,
homeAddress: { state: get(userProfile, "state", "") },
fdUserId: accountUser.userId,
hasMadePreviousWager: get(userProfile, "hasWagered", null),
fullAvatarUrl: accountUser.fullAvatarUrl,
accountRoles: get(userProfile, "roles", [])
});
export const getUserProfile = async (
accountUser: User,
stateAbbr: string,
dispatch: Dispatch
): Promise<GetUserProfile> => {
if (accountUser) {
try {
const { data: userProfile } =
(await profileService.getFDRUserProfile()) as unknown as {
data: UserProfile;
};
const isVerified = get(userProfile, "isUserVerified", false) as boolean;
if (
(typeof userProfile.unmetCriteria === "string" ||
Array.isArray(userProfile.unmetCriteria)) &&
userProfile.unmetCriteria.includes(
INELIGIBLE_RESIDENCY_STATE_FOR_RACING_MESSAGE
)
) {
// eslint-disable-next-line @typescript-eslint/no-throw-literal
throw INELIGIBLE_RESIDENCY_STATE_FOR_RACING_MESSAGE;
}
const user = getUserInfo(accountUser, userProfile);
return { user, isVerified };
} catch (error) {
if (
get(error, "response.data.code") ===
TVG_ACCOUNT_ID_NOT_FOUND_EXCEPTION &&
stateAbbr
) {
try {
await profileService.postFDRProfileMigration(
accountUser.userId,
stateAbbr,
accountUser.email
);
if (typeof dispatch === "function") {
dispatch(resetStateLocationSplashAction());
}
return getUserProfile(accountUser, stateAbbr, dispatch);
} catch (migrationError) {
const errorCode = get(migrationError, "response.data.code");
const errorMessage = get(migrationError, "response.data.message");
if (
(typeof errorMessage === "string" || Array.isArray(errorMessage)) &&
errorMessage.includes(INELIGIBLE_RESIDENCY_STATE_FOR_RACING_MESSAGE)
) {
// eslint-disable-next-line
throw INELIGIBLE_RESIDENCY_STATE_FOR_RACING_MESSAGE;
}
if (errorCode === FDR_USER_NOT_VERIFIED_EXCEPTION) {
const userFormatted = getUserInfo(accountUser);
dispatch(
setUserData({
// @ts-ignore -> We need to normalize some fields, but the type is the same.
user: userFormatted
})
);
return { user: userFormatted as UserInfo, isVerified: false };
}
if (isXSell()) {
throw error;
}
dispatch(fdrGhostAccountExceptionAction());
return {
user: null,
isVerified: false
};
}
} else {
throw error;
}
}
} else {
return {
user: null,
isVerified: false
};
}
};
webpack://frontend-mybets/../../packages/fdr-lib-shared-actions/UserActions.ts
import { User } from "@fdr/types/ts/User";
import { logoutProcessInitiatedEvent } from "@urp/amplitude/src/modules/logout/utils";
type UserUpdateAction = { type: "USER_DATA_UPDATE"; payload: Partial<User> };
export type UserLogout = {
type: "USER_LOGOUT";
};
export type UserTermsAndConditions = {
type: "SET_USER_TERMS_AND_CONDITIONS";
payload: {
isTermsAccepted: boolean;
};
};
export type SetIsVerified = {
type: "SET_IS_VERIFIED";
payload: {
isVerified: boolean;
};
};
export type OpenInvalidResidentialAddressModal = {
type: "OPEN_INVALID_RESIDENTIAL_ADDRESS_MODAL";
};
export type CloseInvalidResidentialAddressModal = {
type: "CLOSE_INVALID_RESIDENTIAL_ADDRESS_MODAL";
};
export type InvalidResidentialAddressModalActions =
| OpenInvalidResidentialAddressModal
| CloseInvalidResidentialAddressModal;
export type Actions =
| UserUpdateAction
| UserLogout
| SetIsVerified
| InvalidResidentialAddressModalActions;
export type SetRaceAlertsUserId = {
type: "SET_RACE_ALERTS_USER_ID";
payload: string;
};
export const setUserData = (userData: Partial<User>): UserUpdateAction => ({
type: "USER_DATA_UPDATE",
payload: userData
});
export const setUserLoggedState = (isLogged: boolean | undefined) => ({
type: "USER_LOGGED_STATE",
payload: { isLogged }
});
export const logoutUser = (functionName?: string): UserLogout => {
const loggedOutBy = `${functionName} -> logoutUser()`;
logoutProcessInitiatedEvent({ loggedOutBy });
return { type: "USER_LOGOUT" };
};
export const setIsVerified = (isVerified: boolean): SetIsVerified => ({
type: "SET_IS_VERIFIED",
payload: {
isVerified
}
});
export const setUserTermsAndCondition = (
isTermsAccepted: boolean
): UserTermsAndConditions => ({
type: "SET_USER_TERMS_AND_CONDITIONS",
payload: {
isTermsAccepted
}
});
export const openInvalidResidentialAddressModal =
(): OpenInvalidResidentialAddressModal => ({
type: "OPEN_INVALID_RESIDENTIAL_ADDRESS_MODAL"
});
export const closeInvalidResidentialAddressModal =
(): CloseInvalidResidentialAddressModal => ({
type: "CLOSE_INVALID_RESIDENTIAL_ADDRESS_MODAL"
});
export const setRaceAlertsUserId = (userId: string): SetRaceAlertsUserId => ({
type: "SET_RACE_ALERTS_USER_ID",
payload: userId
});
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/utils/formatErrorMessage.ts
import { get } from "lodash";
import { PlaceBetErrorMessage } from "../types";
const defaultValues = {
text: "An error occurred while trying to place your bet.",
buttonType: "retry"
};
const formatErrorMessage = (
errorResponse: { default: { title: string; text?: string } } | string,
errorType: string = "default"
) => {
const simpleMessage = typeof errorResponse !== "object";
const errorMessage = simpleMessage
? errorResponse
: get(errorResponse, errorType, errorResponse.default);
const buttonType = get(errorResponse, "buttonType", defaultValues.buttonType);
let errorFormatted: PlaceBetErrorMessage;
if (typeof errorMessage !== "object") {
errorFormatted = {
title: "",
text: errorMessage || defaultValues.text,
buttonType
};
} else {
const text = get(errorMessage, `text`, defaultValues.text);
const title = get(errorMessage, `title`);
errorFormatted = {
title,
text,
buttonType
};
}
return errorFormatted;
};
export default formatErrorMessage;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/utils/gtm/betConfirmJourney.ts
import mediator from "@tvg/mediator";
import { PlaceBetGtm, ConfirmBetErrorGtm, ConfirmBetSuccessGtm } from "./types";
export const confirmBetGtmEvent = ({
raceNumber,
trackName,
betType,
betAmount,
selectionSource,
raceType,
module,
specialWagerType
}: PlaceBetGtm) => {
mediator.base.dispatch({
type: "BET:BET_CONFIRM",
payload: {
module,
raceNumber,
trackName,
betType,
betAmount,
selectionSource,
raceType,
specialWagerType
}
});
};
export const confirmBetErrorGtmEvent = ({
error,
raceNumber,
trackName,
selections,
betAmount,
runnerAmount,
betType,
module
}: ConfirmBetErrorGtm) => {
mediator.base.dispatch({
type: "BET:BET_ERROR",
payload: {
module,
error,
raceNumber,
trackName,
selections,
betAmount,
runnerAmount,
betType
}
});
};
export const confirmBetSuccessGtmEvent = ({
raceNumber,
trackName,
selections,
betAmount,
runnerAmount,
repeatBet,
betId,
betType,
selectionSource,
raceType,
module,
specialWagerType,
alternateSelectionApplied,
alternateSelectionCount,
betSettings,
promoBet
}: ConfirmBetSuccessGtm) => {
mediator.base.dispatch({
type: "BET:BET_SUCCESS",
payload: {
module,
raceNumber,
trackName,
selections,
betAmount,
runnerAmount,
repeatBet,
betId,
betType,
isRepeat: repeatBet ? "Repeat" : undefined,
selectionSource,
raceType,
specialWagerType,
alternateSelectionApplied,
alternateSelectionCount,
betSettings,
promoBet
}
});
};
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/hooks/usePlaceBet.ts
import { useCallback, useEffect, useRef, useState } from "react";
import { get, set, uniqBy, words } from "lodash";
import { useDispatch, useSelector } from "react-redux";
import {
getAddToBetSlipOrigin,
getBetAmount,
getBetGroupStatus,
getBetType,
getErrorBets,
getProcessingBets,
getSuccessBets
} from "@tvg/desktop-bet/src/store/selectors";
import formatCurrency from "@tvg/formatter/currency";
import getOptedInPromos from "@tvg/utils/PromoUtils";
import { hasRacePromoCPPOptedIn } from "@urp/lib-racetracks/src/utils/races";
import { RaceProgram as RaceProgramType } from "@tvg/lhn/src/types";
import { setGeolocationError } from "@tvg/sh-geolocation/src/redux/actions";
// @ts-ignore
import sendAppMetrics from "@tvg/metrics-collector";
import { Promo, RaceProgram, RaceWagerType } from "@tvg/ts-types/Race";
import wtx, { LegSelectionsType, Wager } from "@tvg/api/wtx";
import { updateBalance } from "@tvg/shared-actions/UserActions";
import { setUserTermsAndCondition } from "@fdr/shared-actions/UserActions";
import {
getCustomBetTypeFromModule,
getSelectionSourceFromModule
} from "@urp/shared-redux/BetSource/utils";
import {
resetBetSelection,
setGroupBetAddErrorAction,
setGroupBetAddProcessingAction,
setGroupBetAddSuccessAction,
setGroupBetRemoveProcessingAction,
setGroupBetTicketStatusAction,
setGroupBetTicketStatusClearAllAction,
setGroupBetTicketStatusClearAction,
setBetSlipOpen
} from "@tvg/desktop-bet/src/store/actions";
import calculateTotals from "@tvg/api/wtx/BetHelper";
import {
BetGroupStatus,
BetStatus,
BetStatusType,
SpecialGroupBets,
WagerTypesSelected
} from "@tvg/desktop-bet/src/types";
import {
CAPIVariableRegex,
extractNumberOfText,
replaceCAPIVariables
} from "@tvg/utils/capiWtxMessagesUtils";
import sendToAppsFlyer, { AppsFlyerEvents } from "@tvg/utils/appsflyerUtils";
import {
asyncSubmit,
getBetDetails,
getBetSelectionSpecialGroup,
getSelectionFromVisualWithAlternates,
mapVisualSelectionsToNumber
} from "@tvg/desktop-bet/src/utils/betUtils";
import {
isMobile,
isXSell,
onTriggerGeolocation
} from "@tvg/sh-utils/mobileUtils";
import { GeolocationReason } from "@tvg/sh-geolocation/src/solus/types/solus";
import {
INSUFFICIENT_FUNDS,
UNVERIFIED_ACCOUNT,
GEO_COMPLY_EXPIRED,
INELIGIBLE_LOCATION,
GEO_COMPLY_REJECTED,
TERMS_AND_CONDITIONS_OR_ACKNOWLEDGES_NOT_ACCEPTED
} from "@tvg/api/uam";
import { VisualSelections } from "@tvg/ts-types/Selections";
import { NullaryFn } from "@tvg/ts-types/Functional";
import {
getAccountNumber,
getIsTermsAccepted,
getCPPPromos,
getIsLogged
} from "@urp/store-selectors";
import { getBalance } from "@urp/unified-modules/src/utils/wallet/getBalance";
import { useLocation } from "react-router";
import { getUserProfile } from "@urp/unified-modules/src/hooks/useAccount/hooks/useSubscriptions/services/getProfile";
import {
getAddToBetSlipOriginMobile,
getGeoLocation,
getWtxErrorMessagesWithBehaviour,
getBetSourceModule,
getBonus,
getOptedInPromosStore
} from "../store/selectors";
import {
PlaceBetError,
WtxPlaceBetError,
BetError,
SourceKeysEnum
} from "../types";
import formatErrorMessage from "../utils/formatErrorMessage";
import {
confirmBetErrorGtmEvent,
confirmBetSuccessGtmEvent
} from "../utils/gtm/betConfirmJourney";
import { buildSelectionSource, isFdr } from "../utils/general";
import { getSpecialWagerType } from "../utils/wagersTypes";
interface HandleSubmitBetsInfo {
betSelectionsGroup: VisualSelections[];
betAmount: number;
race: RaceProgram;
selectedRepetition?: number;
forceWagerType?: number;
hasMadePreviousWager: boolean | null;
}
const errorBlockerCodes = [
INSUFFICIENT_FUNDS,
UNVERIFIED_ACCOUNT,
GEO_COMPLY_REJECTED,
INELIGIBLE_LOCATION
];
const sendToAppsFlyerPreviousWager = (
hasMadePreviousWager: boolean | null,
accountNumber: string,
betCost: number
): void => {
const isFdrBrand = isFdr();
if (!isFdrBrand || hasMadePreviousWager === null) {
return;
}
sendToAppsFlyer({
key: hasMadePreviousWager
? AppsFlyerEvents.AfPlaceWager
: AppsFlyerEvents.AfPlaceFirstWager,
values: {
accountId: accountNumber,
af_revenue: betCost.toString()
}
});
};
const usePlaceBet = () => {
const dispatch = useDispatch();
const [betDisable, setBetDisabled] = useState(false);
const [allBetsPlaced, setAllBetsPlaced] = useState(false);
const [errorMessages, setErrorMessages] = useState<PlaceBetError[]>([]);
const retryCounter = useRef(0);
const wtxErrorMessages = useSelector(getWtxErrorMessagesWithBehaviour);
const geolocation = useSelector(getGeoLocation);
const wageredAmount = useSelector(getBetAmount);
const accountNumber = useSelector(getAccountNumber);
const selectedBetType = useSelector(getBetType);
const isPlacingBet = useSelector(getProcessingBets);
const isPlacingBetSuccess = useSelector(getSuccessBets);
const isPlacingBetError = useSelector(getErrorBets);
const isTermsAccepted = useSelector(getIsTermsAccepted);
const betGroupStatus = useSelector(getBetGroupStatus);
const sourceOrigin = useSelector(getAddToBetSlipOrigin);
const sourceOriginMobile = useSelector(getAddToBetSlipOriginMobile);
const betSourceModule = useSelector(getBetSourceModule);
const optedInPromos = useSelector(getOptedInPromosStore);
const isLogged = useSelector(getIsLogged);
const cppPromos = useSelector(getCPPPromos);
const userBonus = useSelector(getBonus);
const fdrUser = useSelector((store) => ({
username: get(store, "userData.user.userName"),
email: get(store, "userData.user.emailAddress"),
firstName: get(store, "userData.user.firstName"),
lastName: get(store, "userData.user.lastName"),
userId: get(store, "userData.user.fdUserId"),
fullAvatarUrl: get(store, "userData.user.fullAvatarUrl")
}));
const location = useLocation();
const isRepeatBetMyBets =
location.search.includes("type=Repeat") ||
location.pathname.includes("my-bets");
const isWagerPad = location.pathname.includes("wagerpad");
const selectionSource = buildSelectionSource(
(sourceOriginMobile || sourceOrigin) as SourceKeysEnum,
isRepeatBetMyBets ? "repeat_bet_my_bets" : "Race Card"
);
useEffect(() => {
if (
isPlacingBet === 0 &&
isPlacingBetError === 0 &&
isPlacingBetSuccess > 0
) {
setAllBetsPlaced(true);
}
if (isPlacingBetError > 0) {
const errors = uniqBy(
Object.values<BetStatus>(betGroupStatus)
.map((betType) => ({
code: betType.statusCode as number,
errorMessage: betType.errorMessage as string
}))
.filter((error) => error.code),
(error) => error.code
);
setErrorMessages(
errors
.filter(
(error) =>
error.code !==
TERMS_AND_CONDITIONS_OR_ACKNOWLEDGES_NOT_ACCEPTED ||
(error.code ===
TERMS_AND_CONDITIONS_OR_ACKNOWLEDGES_NOT_ACCEPTED &&
!isTermsAccepted)
)
.map((error) => ({
code: error.code,
message: getErrorMessage(error.code, error.errorMessage)
}))
);
}
}, [
isPlacingBet,
isPlacingBetError,
isPlacingBetSuccess,
isTermsAccepted,
JSON.stringify(betGroupStatus)
]);
const getErrorMessage = (
code: number,
message: string,
errorType: string = "default"
) => {
const defaultMessage = {
default: {
title: "",
text: `Sorry, we cannot confirm your bet right now. Please try again in a few minutes or
<a
data-qa-label="message-contact-customer-service-link"
target="_blank"
href="https://support.fanduel.com/s/racing?categories=%5B%22Product.FanDuel_Racing%22%5D"
style="color: inherit; text-decoration: underline; font-weight: bold; font-family: inherit; display: contents;"
>
message our customer service
</a>`
}
};
const wtxMessage =
wtxErrorMessages[code] || wtxErrorMessages.default || defaultMessage;
const formattedMessage = formatErrorMessage(wtxMessage, errorType);
const textVariables = words(formattedMessage.text, CAPIVariableRegex());
if (textVariables.length) {
const betAmountLabel = wageredAmount.toFixed(2);
const varNumbers = extractNumberOfText(message, 2);
let errorMessageReplaced = replaceCAPIVariables(formattedMessage.text, {
betAmount: betAmountLabel
});
varNumbers.forEach((_, index) => {
const key = `number${index + 1}`;
const number = get(varNumbers, index, "0.00");
errorMessageReplaced = replaceCAPIVariables(errorMessageReplaced, {
[key]: number
});
});
set(formattedMessage, "text", errorMessageReplaced);
}
return formattedMessage;
};
const getPlacedBetTypes = () =>
Object.keys(betGroupStatus).filter(
(betType) => betGroupStatus[betType].status === "PLACED"
);
const getFilteredSpecialBetSelections = ({
betSelectionsGroup,
selectedWagerType
}: {
betSelectionsGroup: VisualSelections[];
selectedWagerType: RaceWagerType;
}): SpecialGroupBets => {
const selections = getBetSelectionSpecialGroup(
betSelectionsGroup,
selectedWagerType.type.code
);
const placedBets = getPlacedBetTypes();
return Object.keys(selections).reduce(
(selectionsAcc, betType: string) =>
placedBets.includes(betType)
? selectionsAcc
: {
...selectionsAcc,
[betType]: selections[betType]
},
{}
);
};
const filterWagerTypeCallback =
(selectedWagerType?: number) => (wagerType: RaceWagerType) =>
wagerType.type.id === selectedWagerType;
const handleSubmitBet = ({
betSelectionsGroup,
betAmount,
race,
selectedRepetition,
forceWagerType,
hasMadePreviousWager
}: HandleSubmitBetsInfo) => {
dispatch(setGroupBetTicketStatusClearAction());
const betWagerType = forceWagerType || selectedBetType;
let selectedWagerType = race.wagerTypes?.find(
filterWagerTypeCallback(betWagerType)
);
// This function only runs in forceWagerType because some id only have inside the types props.
// Because we already know the correct wagerType we want, we won't need to use our custom function to get specialBet
if (
forceWagerType &&
(!selectedWagerType || selectedWagerType?.types?.length)
) {
const subWagerTypes = race.wagerTypes?.reduce<RaceWagerType[]>(
(acc, wagerType) => {
if (wagerType?.types?.length) {
acc.push(...wagerType.types);
}
return acc;
},
[]
);
const selectedSubWagerType = subWagerTypes?.find(
filterWagerTypeCallback(betWagerType)
);
selectedWagerType = selectedSubWagerType || selectedWagerType;
}
if (!selectedWagerType) {
const defaultError = {
code: 400,
message: getErrorMessage(400, "")
};
setErrorMessages([defaultError]);
console.error(
`Tried to find ${betWagerType}, but not found. Place bet cancelled`
);
return;
}
const bettingInterests = isXSell()
? get(race, "bettingInterests[0]", [])
: get(race, "bettingInterests", []);
const isSpecialGroup = get(selectedWagerType, "specialGroup", false);
let specialGroupFilteredSelections: SpecialGroupBets | undefined;
if (isSpecialGroup) {
specialGroupFilteredSelections = getFilteredSpecialBetSelections({
betSelectionsGroup,
selectedWagerType
});
}
const specialSelections = getBetDetails({
isSpecialGroup,
wagerTypes: isSpecialGroup
? selectedWagerType?.types
: [selectedWagerType],
selections:
isSpecialGroup && specialGroupFilteredSelections
? specialGroupFilteredSelections
: betSelectionsGroup,
bettingInterests,
betAmount
});
const orderedSpecialSelections =
isSpecialGroup && specialGroupFilteredSelections
? Object.keys(specialGroupFilteredSelections).reduce<
Array<WagerTypesSelected>
>((orderedSelection, betType) => {
const selection = specialSelections.find(
(specialSelection) =>
specialSelection.wagerType.type.code === betType
);
if (selection) {
orderedSelection.push(selection);
}
return orderedSelection;
}, [])
: specialSelections;
const bets = orderedSpecialSelections.map((bet): NullaryFn<Promise<{}>> => {
const betSelections = get(bet, "betSelections", []);
const wagerTypeCode: string = get(bet, "wagerType.type.code", "");
const wagerSelection =
getSelectionFromVisualWithAlternates(betSelections);
const newBetStatus: BetGroupStatus = {
[wagerTypeCode]: {
status: BetStatusType.PROCESSING
}
};
dispatch(setGroupBetTicketStatusAction(newBetStatus, true));
dispatch(setGroupBetAddProcessingAction());
return async () =>
submitBet(
get(bet, "wagerType") as RaceWagerType,
betSelections,
wagerSelection,
get(bet, "wagerAmount") as number,
race,
hasMadePreviousWager,
selectedRepetition
) as unknown as Promise<{}>;
});
if (bets) {
asyncSubmit(bets);
}
};
const submitBet = (
wagerType: RaceWagerType,
betSelections: VisualSelections[],
wagerSelection: LegSelectionsType,
betAmount: number,
race: RaceProgram,
hasMadePreviousWager: boolean | null,
selectedRepetition = 0
) => {
const betSelectionsNumbers = mapVisualSelectionsToNumber(betSelections);
const totals = calculateTotals(
betAmount,
wagerType as RaceWagerType,
betSelectionsNumbers
);
const wagerTypeCode = get(wagerType, "type.code");
const raceIdentify = {
trackAbbr: get(race, "track.trackCode"),
raceNumber: get(race, "raceNumber")
};
const startBetTime = performance.now();
const betCost = betAmount * totals.betCount;
const specialWagerType = getSpecialWagerType(race);
return wtx
.placeWager(
wagerSelection,
wagerTypeCode,
betAmount,
betCost,
raceIdentify,
get(geolocation, "location"),
get(geolocation, "regions"),
accountNumber,
selectedRepetition
)
.then((response: Wager) => {
sendAppMetrics("frontend-desk", accountNumber, [
"bets_number",
{
name: "bet_placement_time",
value: Math.floor(performance.now() - startBetTime)
}
]);
if (response.summary) {
if (
response.summary.userBalance !== null &&
!Number.isNaN(response.summary.userBalance)
) {
dispatch(updateBalance(response.summary.userBalance));
}
}
if (isFdr()) {
getBalance(dispatch, accountNumber);
sendToAppsFlyerPreviousWager(
hasMadePreviousWager,
accountNumber,
betCost
);
}
const newBetStatus: BetGroupStatus = {
[wagerTypeCode]: {
status: BetStatusType.PLACED
}
};
retryCounter.current = 0;
dispatch(setGroupBetTicketStatusAction(newBetStatus, true));
dispatch(setGroupBetRemoveProcessingAction());
dispatch(setGroupBetAddSuccessAction());
const promo: Promo | null = getOptedInPromos(
get(race, "promos", []),
optedInPromos,
isLogged
);
const isCPPPromosOptedIn = hasRacePromoCPPOptedIn(
cppPromos,
race as RaceProgramType,
isLogged
);
confirmBetSuccessGtmEvent({
raceNumber: get(race, "raceNumber"),
trackName: get(race, "track.trackName"),
selections: betSelectionsNumbers.toString(),
betAmount: betCost,
runnerAmount: betAmount,
repeatBet: selectedRepetition,
betId: response.status[0]?.success?.serialNumber || "",
betType: betSourceModule
? getCustomBetTypeFromModule(betSourceModule)
: wagerTypeCode,
selectionSource: betSourceModule
? getSelectionSourceFromModule(betSourceModule)
: selectionSource,
raceType: race.type?.name,
module: isWagerPad ? "wagerpad" : undefined,
specialWagerType,
alternateSelectionApplied: wagerSelection.some(
(wager) => wager.alternate
),
alternateSelectionCount: wagerSelection.reduce((acc, wager) => {
if (wager.alternate) return acc + 1;
return acc;
}, 0),
betSettings: {
rewardName: "bonus_cash",
rewardAmount:
+userBonus >= +betCost
? formatCurrency(+betCost)
: formatCurrency(userBonus)
},
promoBet: !!promo?.isOptedIn || isCPPPromosOptedIn
});
if (isMobile()) {
sendToAppsFlyer({
key: AppsFlyerEvents.AfBetCost,
values: {
accountId: accountNumber,
af_revenue: betCost.toString()
}
});
}
})
.catch((error: WtxPlaceBetError) => {
sendAppMetrics("frontend-desk", accountNumber, [
"bets_number",
"place_bets_error"
]);
const statusCode = get(error.response, "data.code", 400);
const newBetStatus: BetGroupStatus = {
[wagerTypeCode]: {
status: BetStatusType.ERROR,
statusCode,
errorMessage: get(error.response, "data.message", "")
}
};
if (isFdr()) {
if (errorBlockerCodes.includes(statusCode)) {
setBetDisabled(true);
}
// Disables retry bet button when receiving these errors
if (
statusCode === INELIGIBLE_LOCATION ||
statusCode === GEO_COMPLY_REJECTED
) {
dispatch(setGeolocationError("GEOLOCATION_REJECTED", [], false));
}
if (
statusCode === TERMS_AND_CONDITIONS_OR_ACKNOWLEDGES_NOT_ACCEPTED
) {
dispatch(setUserTermsAndCondition(false));
}
if (
statusCode === BetError.geoComplyTokenMissing ||
statusCode === GEO_COMPLY_EXPIRED
) {
onTriggerGeolocation(GeolocationReason.PERIODIC);
}
if (
statusCode === BetError.stateMismatch &&
retryCounter.current < 3
) {
// @ts-ignore
getUserProfile(fdrUser, geolocation?.state, dispatch).then(() => {
submitBet(
wagerType,
betSelections,
wagerSelection,
betAmount,
race,
hasMadePreviousWager,
selectedRepetition
);
});
retryCounter.current += 1;
return;
}
}
dispatch(setGroupBetTicketStatusAction(newBetStatus, true));
dispatch(setGroupBetRemoveProcessingAction());
dispatch(setGroupBetAddErrorAction());
confirmBetErrorGtmEvent({
error: get(error.response, "data.code"),
raceNumber: get(race, "raceNumber"),
trackName: get(race, "trackName"),
selections: betSelectionsNumbers.toString(),
betAmount: betCost,
runnerAmount: betAmount,
betType: wagerTypeCode,
module: isWagerPad ? "wagerpad" : undefined
});
});
};
const resetBetting = useCallback(
(retainRunners: boolean = false) => {
if (allBetsPlaced) {
setAllBetsPlaced(false);
if (!retainRunners) {
dispatch(resetBetSelection());
dispatch(setBetSlipOpen(false));
}
}
dispatch(setGroupBetTicketStatusClearAllAction());
setErrorMessages([]);
setBetDisabled(false);
},
[allBetsPlaced]
);
const clearErrorMessages = useCallback(() => {
setErrorMessages([]);
}, []);
return {
allBetsPlaced,
errorMessages,
handleSubmitBet,
resetBetting,
betDisable,
clearErrorMessages
} as const;
};
export default usePlaceBet;
webpack://frontend-mybets/../../packages/tvg-lib-utils/PromoUtils.ts
import { forEach, get, has } from "lodash";
// @ts-ignore
import cookie from "react-cookie";
import queryString from "query-string";
import type { Promo, RacePanelLink, UserPromotions } from "@tvg/ts-types/Race";
import type { UserOptedInPromos } from "@tvg/ts-types/User";
const getOptedInPromos = (
promos: Promo[],
optedInPromos: UserOptedInPromos,
isUserLogged = false
): Promo | null => {
let aboveTheLineRacePromo: Promo | null = null;
let belowTheLineRacePromo: Promo | null = null;
promos.forEach((promo) => {
if (promo && promo.isAboveTheLine && aboveTheLineRacePromo === null) {
aboveTheLineRacePromo = promo;
} else if (
promo &&
!promo.isAboveTheLine &&
belowTheLineRacePromo === null &&
has(optedInPromos, `[${promo.rootParentPromoID}]`)
) {
belowTheLineRacePromo = promo;
}
});
if (
isUserLogged &&
belowTheLineRacePromo &&
optedInPromos[(belowTheLineRacePromo as Promo).rootParentPromoID] !==
undefined
) {
return {
...(belowTheLineRacePromo as Promo),
isOptedIn:
optedInPromos[(belowTheLineRacePromo as Promo).rootParentPromoID]
};
}
if (
isUserLogged &&
aboveTheLineRacePromo &&
optedInPromos[(aboveTheLineRacePromo as Promo).rootParentPromoID] !==
undefined
) {
return {
...(aboveTheLineRacePromo as Promo),
isOptedIn:
optedInPromos[(aboveTheLineRacePromo as Promo).rootParentPromoID]
};
}
return aboveTheLineRacePromo;
};
export const getHasPromo = (
useIsPromoTagShownFlag: boolean,
hasPromo: boolean,
isPromoTagShown: boolean
) => (useIsPromoTagShownFlag ? hasPromo && isPromoTagShown : hasPromo);
export const hasPromoFromGraph = (
race: RacePanelLink,
useIsPromoTagShownFlag = false
) => {
const hasPromo =
!!get(race, "promos[0].isAboveTheLine", false) ||
!!get(race, "userPromotions.length", false);
const isPromoTagShown =
get(race, "promos[0].isPromoTagShown", false) ||
get(race, "userPromotions[0].isPromoTagShown", false);
const isOptedIn = get(race, "userPromotions[0].optedIn", false);
return (
(hasPromo && isOptedIn) ||
getHasPromo(useIsPromoTagShownFlag, hasPromo, isPromoTagShown)
);
};
export const getRDAOptinStatus = (race: RacePanelLink) => {
const userPromotions = get(race, "userPromotions", []);
let aboveTheLine: UserPromotions | null = null;
let belowTheLine: UserPromotions | null = null;
userPromotions.forEach((promo) => {
if (!promo.isAboveTheLine && !belowTheLine) {
belowTheLine = promo;
}
if (promo.isAboveTheLine && !aboveTheLine) {
aboveTheLine = promo;
}
});
return belowTheLine
? (belowTheLine as UserPromotions).optedIn
: get(aboveTheLine, "optedIn", false);
};
export const setRFRCookie = (isApp: boolean, location: { search: string }) => {
const { referrer } = document;
const rfrParameters = {
"12_001_0001":
/https?:\/\/(www\.tvg|4njbets\.us\.betfair)(\.[a-z]{2,3}){1,2}\/?/,
"0_022_0208": /https?:\/\/www\.google(\.[a-z]{2,3}){1,2}\/?/,
"0_023_0209": /https?:\/\/www\.bing(\.[a-z]{2,3}){1,2}\/?/,
"0_024_0210": /https?:\/\/[a-z.]+\.yahoo(\.[a-z]{2,3}){1,2}\/?/
};
const getCookieValue = (name: string) =>
document.cookie.match(`(^|;)\\s*${name}\\s*=\\s*([^;]+)`)?.pop() || "";
const rfrCookieExists = !document.cookie.includes("RFR=");
const existingCookie = rfrCookieExists ? "" : getCookieValue("RFR");
const queryParams = queryString.parse(location.search.toLowerCase());
const rfr = get(queryParams, "rfr", false);
const rafCode = get(queryParams, "rcode", false);
const extraCookieConfig = "/";
const existingRfrType = (cookieValue: string) => {
switch (cookieValue) {
case "":
return "empty";
case Object.keys(rfrParameters)[0]:
return "tvg";
case Object.keys(rfrParameters)[1]:
case Object.keys(rfrParameters)[2]:
case Object.keys(rfrParameters)[3]:
return "seo";
case "10_001_0001":
return "raf";
default:
return "promo";
}
};
const rfrType = existingRfrType(existingCookie);
if (referrer) {
forEach(rfrParameters, (value, key) => {
// Don't override current rfr cookie when referrer is from tvg.com
if (
value.test(referrer.toLowerCase()) &&
key !== Object.keys(rfrParameters)[0] &&
rfrType !== "raf" &&
rfrType !== "promo"
) {
// set rfr value for seo journeys
cookie.save("RFR", key, { path: extraCookieConfig });
}
});
} else if (!isApp && rfrCookieExists && !rfr) {
// set tvg.com rfr value when no referrer and no cookie is set for direct journey
cookie.save("RFR", Object.keys(rfrParameters)[0], {
path: extraCookieConfig
});
}
if (rfr) {
// set rfr value for url journeys
cookie.save("RFR", rfr, { path: extraCookieConfig });
}
if (rafCode) {
// set rfr value for refer a friend referral
cookie.save("RFR", "10_001_0001", { path: extraCookieConfig });
}
};
export default getOptedInPromos;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/graphql/queries/RaceBettingInterestQuery.ts
import { gql } from "@apollo/client";
import HandicappingFragments from "../fragments/HandicappingFragment";
import TimeformFragments from "../fragments/TimeformFragment";
import Probables from "../fragments/Probables";
import RacePools from "../fragments/RacePools";
import WillPays from "../fragments/WillPays";
export const GET_RACES_BETTING_INTERESTS = gql`
query getGraphRaceBettingInterest(
$tvgRaceIds: [Long]
$tvgRaceIdsBiPartial: [Long]
$wagerProfile: String
) {
races: races(
tvgRaceIds: $tvgRaceIds
profile: $wagerProfile
sorts: [{ byRaceNumber: ASC }]
) {
id
tvgRaceId
bettingInterests {
biNumber
saddleColor
numberColor
favorite
currentOdds {
numerator
denominator
}
morningLineOdds {
numerator
denominator
}
recentOdds(pages: [{ current: 0, results: 4 }]) {
odd
trending
}
biPools {
wagerType {
id
code
name
}
poolRunnersData {
amount
}
}
runners {
runnerId
entityRunnerId
scratched
horseName
age
sex
weight
med
jockey
trainer
dob
hasJockeyChanges
...timeformFragment
handicapping {
freePick {
number
info
}
}
...handicappingFragment
}
}
...Probables
...RacePools
...WillPays
}
racesBiPartial: races(
tvgRaceIds: $tvgRaceIdsBiPartial
profile: $wagerProfile
sorts: [{ byRaceNumber: ASC }]
) {
id
tvgRaceId
bettingInterests {
biNumber
saddleColor
numberColor
favorite
currentOdds {
numerator
denominator
}
morningLineOdds {
numerator
denominator
}
runners {
runnerId
entityRunnerId
scratched
horseName
jockey
trainer
hasJockeyChanges
winProbability
}
}
}
}
${HandicappingFragments.entry}
${TimeformFragments.entry}
${Probables.entry}
${RacePools.entry}
${WillPays.entry}
`;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/graphql/fragments/GroupWagers.ts
import { gql } from "@apollo/client";
const GroupWagersFragment = {
entry: gql`
fragment groupWagersFragment on WagerGroupEntry {
wagers: value {
id
serialNumber
wagerAmount
betTotal: cost
betRefund
winningsAmount: winnings
betStatus {
code
name
}
transactionDate
wageringPlatform
wagerType {
id
code
name
}
promoQualifying
cancelableStatus {
code
name
}
cancelable
selections {
selectionString
modifier
selection {
bettingInterests {
currentOdds {
numerator
denominator
}
biNumber
isWinner
runners {
runnerId
scratched
horseName
}
payouts {
amount
wagerType {
code
}
}
}
alternateBettingInterest {
currentOdds {
numerator
denominator
}
biNumber
isWinner
runners {
runnerId
scratched
horseName
}
payouts {
amount
wagerType {
code
}
}
}
selectionType {
code
name
}
runners {
number
}
}
}
raceDate
racePostTime: postTime
raceTypeAbbreviation: raceType
tvgRaceId
trackName
wagerReference
}
}
`
};
export default GroupWagersFragment;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/graphql/fragments/WagerTotals.ts
import { gql } from "@apollo/client";
const WagerTotalsFragment = {
entry: gql`
fragment totals on WagerHistoryResponse {
totals {
totalBets: totalCount
totalAmount
totalGambledCount
totalGambledAmount
}
}
`
};
export default WagerTotalsFragment;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/graphql/queries/RaceWagerSubscription.ts
import { gql } from "@apollo/client";
import GroupWagersFragment from "../fragments/GroupWagers";
import WagerTotalsFragment from "../fragments/WagerTotals";
export const GET_RACE_WAGERS_SUBSCRIPTION = gql`
subscription GetGroupWagersSubscription(
$accountId: Int!
$trackCode: String
$raceNumber: Int
) {
wagerHistoryUpdate(
accountId: $accountId
trackCode: $trackCode
raceNumber: $raceNumber
) {
id
...totals
groupWagers(group: { group: RACE, order: DESC }) {
value: key
...groupWagersFragment
}
}
}
${WagerTotalsFragment.entry}
${GroupWagersFragment.entry}
`;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/graphql/queries/RaceWagersQuery.ts
import { gql } from "@apollo/client";
import GroupWagersFragment from "../fragments/GroupWagers";
import WagerTotalsFragment from "../fragments/WagerTotals";
export const GET_RACE_WAGERS = gql`
query getRaceWagers(
$accountId: Int!
$trackCode: String
$raceNumber: Int
$startDate: String
$endDate: String
) {
wagerHistory(
accountId: $accountId
trackCode: $trackCode
raceNumber: $raceNumber
beginDate: $startDate
endDate: $endDate
) {
id
...totals
groupWagers(group: { group: RACE, order: DESC }) {
value: key
...groupWagersFragment
}
}
}
${WagerTotalsFragment.entry}
${GroupWagersFragment.entry}
`;
webpack://frontend-mybets/../../packages/tvg-lib-api/capi/index.ts
import tvgConf from "@tvg/conf";
import type { TutorialListFromService } from "@tvg/ts-types/OnBoarding";
import requester from "../requester";
import getProtocol from "../protocolSetter";
const capiService: string = "service.capi";
export const tvgHeaders = () => ({
"content-type": "application/json",
"x-clientapp": tvgConf().brand,
"x-tvg-context": tvgConf().context(tvgConf().product, true),
"x-requested-with": "XMLHttpRequest"
});
const fetchMessagesByNamespaces = (namespaces: string) => {
const tvgConfObject = tvgConf();
return requester()({
method: "GET",
url: `${getProtocol()}${tvgConfObject.config(
capiService
)}/messages/namespace?product=${tvgConfObject.product}&device=${
tvgConfObject.device
}&brand=${tvgConfObject.brand}&namespace=${namespaces}`,
headers: { "x-tvg-context": tvgConf().context() },
withCredentials: false
});
};
const fetchFeatureToggles = () => {
const tvgConfObject = tvgConf();
return requester()({
method: "GET",
url: `${getProtocol()}${tvgConfObject.config(capiService)}/featureToggles/${
tvgConfObject.product
}/${tvgConfObject.device}/${tvgConfObject.brand}`,
headers: { "x-tvg-context": tvgConf().context() },
withCredentials: true
});
};
const fetchBalancePollerTime = () =>
requester()({
method: "get",
url: `${getProtocol()}${
tvgConf().config().service.capi
}/configs/balance-polling-time`,
headers: tvgHeaders(),
withCredentials: true
});
const fetchBrazePollerTime = () =>
requester()({
method: "get",
url: `${getProtocol()}${
tvgConf().config().service.capi
}/configs/inbox-polling-time`,
headers: tvgHeaders(),
withCredentials: true
});
const fetchTvProvidersByState = (residentialStateAbbr: string) =>
requester()({
method: "get",
url: `${getProtocol()}${
tvgConf().config().service.capi
}/signalProviders/search/findByState?state=${residentialStateAbbr}`,
headers: tvgHeaders(),
withCredentials: false
});
const fetchPromoOnboardingPollerTime = () =>
requester()({
method: "get",
url: `${getProtocol()}${
tvgConf().config().service.capi
}/configs/promo-steps-polling-time`,
headers: tvgHeaders(),
withCredentials: true
});
const fetchFreePastPerfomances = () => {
const tvgConfObject = tvgConf();
return requester()({
method: "get",
url: `${getProtocol()}${
tvgConf().config().service.capi
}/files/handicapping/available?brand=${tvgConfObject.brand}`,
headers: tvgHeaders(),
withCredentials: true
});
};
/**
* Gets the list of routes with available tutorials
* @returns {Promise<TutorialListFromService>}
*/
const fetchTutorialList = (): Promise<TutorialListFromService[]> => {
const conf = tvgConf();
const { product } = conf;
const url = `${conf.config().service.capi}/tutorial`;
const requestOptions = {
method: "GET",
url,
headers: {
"content-type": "application/json",
"x-tvg-context": conf.context(product, true),
"x-requested-with": "XMLHttpRequest"
},
params: {
isMinimized: true,
isActive: true
},
withCredentials: true
};
return requester()(requestOptions)
.then(({ data }) => data)
.catch((err: Error): Error => err);
};
const CAPI_SERVICES = {
fetchMessagesByNamespaces,
fetchFeatureToggles,
fetchBalancePollerTime,
fetchBrazePollerTime,
fetchTvProvidersByState,
fetchPromoOnboardingPollerTime,
fetchTutorialList,
fetchFreePastPerfomances
};
export default CAPI_SERVICES;
webpack://frontend-mybets/../../packages/tvg-lib-ts-types/Alerts.ts
export enum ChannelType {
Email = "email",
PushNotification = "push"
}
export enum EntityType {
Race = "race",
Runner = "runner",
Jockey = "jockey",
Trainer = "trainer",
Owner = "owner"
}
export const EntityLabel = {
[EntityType.Race]: "race",
[EntityType.Runner]: "Horse",
[EntityType.Jockey]: "Jockey",
[EntityType.Trainer]: "Trainer",
[EntityType.Owner]: "Owner"
};
export enum EventType {
All = "all",
RaceResults = "raceResults",
RaceDay = "raceDay",
TimeToRace = "timeToRace"
}
export interface SubscriptionChannel {
type: ChannelType;
}
export interface Subscription {
eventType: EventType;
channels: Array<SubscriptionChannel>;
}
export interface ChannelUFC {
favoriteId: number;
entityType: EntityType;
entityName: string;
entityDob?: number;
entityRunnerId?: number;
subscriptions: Array<Subscription>;
}
export interface Pagination {
currentPage: number;
totalPages: number;
totalResults: number;
}
export interface GetAlertsResponse {
pagination: Pagination;
favorites: Array<ChannelUFC>;
}
webpack://frontend-mybets/../../packages/tvg-lib-ts-types/Gtm.ts
export enum PP_RUNNER_MODIFIER_EVENT {
APPLY_FILTER = "PROGRAM_PAGE_RUNNER_MODIFIER_FILTER_APPLIED",
APPLY_SORT = "PROGRAM_PAGE_RUNNER_MODIFIER_SORT_APPLIED"
}
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/graphql/queries/TracksListQuery.ts
import { gql } from "@apollo/client";
export const GET_TRACKS_LIST = gql`
query GetTracksList($wagerProfile: String) {
tracks(profile: $wagerProfile, sort: { byName: ASC }) {
id
code
name
isFinished
numberOfRaces
currentRace(wagerable: true) {
id
number
}
}
}
`;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/components/ConfirmBetModal/hooks/useCancelLimits/constraints.ts
export const limitMapped = {
daily: {
count: {
current: "currentDayCancelledCount",
max: "dailyCancelCountLimit",
remaining: "remainingDayCancelledCount"
},
amount: {
current: "currentDayCancelledAmount",
max: "dailyCancelAmountLimit",
remaining: "remainingDayCancelledAmount"
}
},
monthly: {
count: {
current: "currentMonthCancelledCount",
max: "monthlyCancelCountLimit",
remaining: "remainingMonthCancelledCount"
},
amount: {
current: "currentMonthCanceledAmount",
max: "monthlyCancelAmountLimit",
remaining: "remainingMonthCancelledAmount"
}
}
};
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/components/ConfirmBetModal/hooks/useCancelLimits/types.ts
import { ApolloClient, NormalizedCacheObject } from "@apollo/client";
export interface RawCancelLimits {
monthlyCancelCountLimit: number;
dailyCancelCountLimit: number;
currentMonthCancelledCount: number;
currentDayCancelledCount: number;
remainingMonthCancelledAmount: number;
remainingMonthCancelledCount: number;
remainingDayCancelledAmount: number;
remainingDayCancelledCount: number;
wagerCostLimit: number;
}
export interface CancelLimit {
current: number;
max: number;
remaining: number;
limitReached?: boolean;
}
export type CancelLimitsPrediction = Record<LimitType, CancelLimit | null>;
export type CancelLimits = Record<LimitType, CancelLimit | null> & {
closest: LimitType | null;
prediction: Omit<CancelLimits, "prediction"> | null;
limitReached: boolean;
};
export interface ExtraVariablesTracks {
code: string;
country: string;
name: string;
}
export interface FormatGlobalLimits {
wagerCostLimit: number;
config: ConfigCancelGlobalLimits;
currentRace: string;
track?: ExtraVariablesTracks;
}
export interface NonCancellable {
trackCode: string;
trackCountry: string;
trackName: string;
isRaceCancelable: boolean;
}
export interface CancelLimitsGlobal {
nonCancellable: NonCancellable;
wagerCostLimit: number;
enabled: boolean;
}
export interface CancelLimitsByGroup {
daily: CancelLimits;
monthly: CancelLimits;
global: Partial<CancelLimitsGlobal>;
}
export interface ClosestLimits {
limitReached: boolean;
limitGroup: LimitGroup;
limitType: LimitType | GlobalLimitTypes;
}
export enum LimitType {
AMOUNT = "amount",
COUNT = "count"
}
export enum GlobalLimitTypes {
RACE_CANCELABLE = "nonCancellable"
}
export enum LimitGroup {
DAILY = "daily",
MONTHLY = "monthly",
GLOBAL = "global"
}
export enum ConfigCancelLimitFeedbackTypes {
DEFAULT = "default",
WARNING = "warning",
LIMIT_REACHED = "limit_reached"
}
export interface ConfigCancelLimitFeedbackUrl {
label: string;
url: string;
}
export interface ConfigCancelLimitFeedback {
title?: string;
description?: string;
link?: ConfigCancelLimitFeedbackUrl;
}
export type ConfigCancelLimitsFeedback = Record<
ConfigCancelLimitFeedbackTypes,
ConfigCancelLimitFeedback
> & {
enabled: boolean;
};
export interface ConfigCancelLimitsNonCancellableFeedback
extends ConfigCancelGroupLimits {
tracks: Array<string>;
}
export interface ConfigCancelGlobalLimits {
nonCancellable: Partial<ConfigCancelLimitsNonCancellableFeedback>;
enabled: boolean;
wagerCostLimit: number;
}
export interface ConfigCancelGroupLimitsFeedback {
default: ConfigCancelLimitFeedback;
prediction?: ConfigCancelLimitFeedback;
placed?: ConfigCancelLimitFeedback;
value?: number;
}
export interface ConfigCancelGroupLimits {
warning: ConfigCancelGroupLimitsFeedback;
limitReached: ConfigCancelGroupLimitsFeedback;
enabled: boolean;
}
export interface ConfigCancelLimitByGroup {
count: ConfigCancelGroupLimits;
amount: ConfigCancelGroupLimits;
enabled: boolean;
}
export interface ConfigCancelLimit {
global: ConfigCancelGlobalLimits;
monthly: ConfigCancelLimitByGroup;
daily: ConfigCancelLimitByGroup;
}
export interface PredictionProps {
count: number;
amount: number;
}
export interface FeedBackExtraValues {
forceFeedback: keyof Omit<ConfigCancelGroupLimitsFeedback, "value">;
prediction: PredictionProps;
track: ExtraVariablesTracks;
}
export interface Props {
needsFetch?: boolean;
accountNumber: string;
behgClient: ApolloClient<NormalizedCacheObject>;
config: ConfigCancelLimit;
feedbackExtraValues?: Partial<FeedBackExtraValues>;
currentRace?: string;
}
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/components/ConfirmBetModal/graphql/queries/CancelLimitsQuery.ts
import { gql } from "@apollo/client";
export const GET_GROUP_WAGER_CANCEL_LIMITS = gql`
query GetGroupWagersCancelLimits($accountId: Int!) {
wagerHistory(accountId: $accountId) {
cancelLimits {
monthlyCancelCountLimit
monthlyCancelAmountLimit
dailyCancelCountLimit
dailyCancelAmountLimit
currentMonthCancelledCount
currentDayCancelledCount
currentMonthCanceledAmount
currentDayCancelledAmount
remainingMonthCancelledAmount
remainingMonthCancelledCount
remainingDayCancelledAmount
remainingDayCancelledCount
}
}
}
`;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/components/ConfirmBetModal/hooks/useCancelLimits/index.ts
import { useEffect, useMemo, useState } from "react";
import { get } from "lodash";
import { useQuery } from "@apollo/client";
import {
CAPIVariable,
replaceCAPIVariables
} from "@tvg/utils/capiWtxMessagesUtils";
import { limitMapped } from "./constraints";
import {
CancelLimit,
CancelLimits,
CancelLimitsByGroup,
CancelLimitsGlobal,
CancelLimitsPrediction,
ClosestLimits,
ConfigCancelGlobalLimits,
ConfigCancelGroupLimits,
ConfigCancelGroupLimitsFeedback,
ConfigCancelLimit,
ConfigCancelLimitByGroup,
ConfigCancelLimitFeedback,
FormatGlobalLimits,
GlobalLimitTypes,
LimitGroup,
LimitType,
PredictionProps,
Props,
RawCancelLimits
} from "./types";
import ApolloOptions from "../../graphql/options.graph";
import { GET_GROUP_WAGER_CANCEL_LIMITS } from "../../graphql/queries/CancelLimitsQuery";
const formatLimits = (
limit: Partial<RawCancelLimits>,
limitGroup: LimitGroup,
config: ConfigCancelLimit,
prediction?: Partial<PredictionProps>
): CancelLimits => {
const countKeys: CancelLimit | null = get(
limitMapped,
`${limitGroup}.count`,
null
);
const amountKeys: CancelLimit | null = get(
limitMapped,
`${limitGroup}.amount`,
null
);
const remainingCount = get(limit, `${countKeys?.remaining}`, 0);
const count: CancelLimit | null = countKeys
? {
current: get(limit, countKeys.current, 0),
max: get(limit, countKeys.max, 0),
remaining: remainingCount,
limitReached: remainingCount <= 0
}
: null;
const remainingAmount = get(limit, `${amountKeys?.remaining}`, 0);
const amount: CancelLimit | null = amountKeys
? {
current: get(limit, amountKeys.current, 0),
max: get(limit, amountKeys.max, 0),
remaining: remainingAmount,
limitReached: remainingAmount <= 0
}
: null;
const configGroup = get(config, limitGroup, null);
const predictionRemainingCount = remainingCount - get(prediction, "count", 0);
const predictionRemainingAmount =
remainingAmount - get(prediction, "amount", 0);
const predictionLimits: CancelLimitsPrediction | null = prediction
? {
count: count && {
...count,
remaining:
predictionRemainingCount > 0 ? predictionRemainingCount : 0,
limitReached: predictionRemainingCount <= 0
},
amount: amount && {
...amount,
remaining:
predictionRemainingAmount > 0 ? predictionRemainingAmount : 0,
limitReached: predictionRemainingAmount <= 0
}
}
: null;
return {
count: count && {
...count
},
amount: amount && {
...amount
},
closest: getClosestLimitType(amount, count, configGroup),
prediction: predictionLimits && {
...predictionLimits,
closest: getClosestLimitType(
predictionLimits.amount,
predictionLimits.count,
configGroup
),
limitReached: !!(
predictionLimits?.amount?.limitReached ||
predictionLimits?.count?.limitReached
)
},
limitReached: !!(count?.limitReached || amount?.limitReached)
};
};
const formatGlobalLimits = ({
wagerCostLimit,
config,
currentRace,
track
}: FormatGlobalLimits): CancelLimitsGlobal => ({
enabled: config?.enabled,
nonCancellable: {
trackCode: track?.code || "",
trackCountry: track?.country || "",
trackName: track?.name || "",
isRaceCancelable:
!config.nonCancellable?.enabled ||
!config.nonCancellable?.tracks?.includes(currentRace)
},
// TODO: If we want to use wagerCostLimit need to create new templates.
wagerCostLimit
});
const getClosestLimitType = (
amount: CancelLimit | null,
count: CancelLimit | null,
config: ConfigCancelLimitByGroup | ConfigCancelGlobalLimits | null
) => {
if (!config) {
return null;
}
if (
typeof amount?.remaining === "number" &&
get(config, "amount.enabled", false)
) {
return typeof count?.remaining !== "number" ||
amount.remaining < count.remaining
? LimitType.AMOUNT
: LimitType.COUNT;
}
return LimitType.COUNT;
};
const getClosestLimits = (
limits: CancelLimitsByGroup,
config: ConfigCancelLimit
): ClosestLimits | null => {
const { global, daily, monthly } = limits;
let limitReached = false;
let limitGroup = LimitGroup.DAILY;
let closest: LimitType | GlobalLimitTypes | null = null;
let globalLimitOverride = false;
if (global?.enabled) {
if (limits.global?.nonCancellable?.isRaceCancelable === false) {
closest = GlobalLimitTypes.RACE_CANCELABLE;
limitReached = true;
}
if (closest) {
limitGroup = LimitGroup.GLOBAL;
globalLimitOverride = true;
}
}
if (
!globalLimitOverride &&
daily?.limitReached &&
config?.daily?.enabled &&
(config?.daily?.count?.enabled || config?.daily?.amount?.enabled)
) {
limitGroup = LimitGroup.DAILY;
limitReached = true;
} else if (
monthly?.limitReached &&
config?.monthly?.enabled &&
(config?.monthly?.count?.enabled || config?.monthly?.amount?.enabled)
) {
limitGroup = LimitGroup.MONTHLY;
limitReached = true;
}
if (!limitReached && limitGroup !== LimitGroup.GLOBAL) {
if (config?.daily?.enabled && config?.monthly?.enabled) {
const dailyLimit = get(daily, `${daily.closest}.remaining`, 0);
const monthlyLimit = get(monthly, `${monthly.closest}.remaining`, 0);
limitGroup =
dailyLimit <= monthlyLimit ? LimitGroup.DAILY : LimitGroup.MONTHLY;
} else if (config?.daily?.enabled) {
limitGroup = LimitGroup.DAILY;
} else if (config?.monthly?.enabled) {
limitGroup = LimitGroup.MONTHLY;
}
}
if (limitGroup !== LimitGroup.GLOBAL) {
closest = get(limits, `${limitGroup}.closest`, null);
}
return (
closest && {
limitReached,
limitGroup,
limitType: closest
}
);
};
export const getFeedbackMessage = (
message: ConfigCancelGroupLimitsFeedback | null,
variables: CancelLimit | null,
usePrediction: boolean,
forceFeedback?: keyof Omit<ConfigCancelGroupLimitsFeedback, "value">
): ConfigCancelLimitFeedback | null => {
let feedback: ConfigCancelLimitFeedback = get(message, "default", {});
const forcedFeedbackMessage = get(message, `${forceFeedback}`);
if (forcedFeedbackMessage) {
feedback = forcedFeedbackMessage;
} else if (usePrediction && message?.prediction) {
feedback = message.prediction;
}
const { title = "", description = "", link } = feedback;
const validVariables: CAPIVariable = (typeof variables === "object"
? variables
: {}) as unknown as CAPIVariable;
return {
title: replaceCAPIVariables(title, validVariables),
description: replaceCAPIVariables(description, validVariables),
link:
link?.url && link?.label
? {
url: link.url,
label: replaceCAPIVariables(link.label, validVariables)
}
: undefined
};
};
export const useCancelLimits = ({
needsFetch = true,
accountNumber,
behgClient,
config,
feedbackExtraValues,
currentRace = ""
}: Props) => {
const [formattedLimits, setFormattedLimits] =
useState<CancelLimitsByGroup | null>(null);
const [closestLimits, setClosestLimits] = useState<ClosestLimits | null>(
null
);
if (!config) {
console.warn(
"[UseCancelLimits Hook]: Please provide the configuration to receive correct closest limit"
);
}
const { data, loading } = useQuery(
GET_GROUP_WAGER_CANCEL_LIMITS,
ApolloOptions({
accountNumber,
behgClient,
hasConfig: !!config,
needsFetch
})
);
const limits: RawCancelLimits = useMemo(
() => get(data, "wagerHistory.cancelLimits", null),
[data, loading]
);
const feedbackAvailable = useMemo(
() => !!limits && !loading && config,
[limits, loading]
);
useEffect(() => {
if (feedbackAvailable) {
const dailyLimit = formatLimits(limits, LimitGroup.DAILY, config, {
amount: feedbackExtraValues?.prediction?.amount,
count: feedbackExtraValues?.prediction?.count
});
const monthlyLimit = formatLimits(limits, LimitGroup.MONTHLY, config, {
amount: feedbackExtraValues?.prediction?.amount,
count: feedbackExtraValues?.prediction?.count
});
const globalLimit = formatGlobalLimits({
wagerCostLimit: data?.wagerCostLimit,
config: config.global,
currentRace,
track: feedbackExtraValues?.track
});
const newFormattedLimits: CancelLimitsByGroup = {
global: globalLimit,
daily: dailyLimit,
monthly: monthlyLimit
};
setFormattedLimits(newFormattedLimits);
setClosestLimits(getClosestLimits(newFormattedLimits, config));
}
}, [feedbackAvailable, limits, JSON.stringify(config)]);
const feedback = useMemo(() => {
if (!formattedLimits || !config || !closestLimits) {
return null;
}
const closest = get(
formattedLimits,
`${closestLimits.limitGroup}.${closestLimits.limitType}`
);
const prediction = get(
formattedLimits,
`${closestLimits.limitGroup}.prediction.${closestLimits.limitType}`
);
if (!closest && !prediction) {
return null;
}
const closestConfig: ConfigCancelGroupLimits = get(
config,
`${closestLimits.limitGroup}.${closestLimits.limitType}`
);
if (
closestLimits.limitReached ||
(prediction?.limitReached && closestConfig?.limitReached.prediction)
) {
const isPrediction =
!closestLimits?.limitReached && prediction?.limitReached;
return getFeedbackMessage(
closestConfig.limitReached,
isPrediction ? prediction : closest,
isPrediction,
feedbackExtraValues?.forceFeedback
);
}
const useDefaultWarning =
typeof closest?.remaining === "number" &&
closest.remaining <= (closestConfig.warning.value || 0);
const usePrediction =
!!closestConfig.warning?.prediction &&
typeof prediction?.remaining === "number" &&
prediction.remaining <= (closestConfig.warning.value || 0);
if (!useDefaultWarning && !usePrediction) {
return null;
}
const isPrediction = !useDefaultWarning && usePrediction;
return getFeedbackMessage(
closestConfig.warning,
isPrediction ? prediction : closest,
isPrediction,
feedbackExtraValues?.forceFeedback
);
}, [
formattedLimits,
JSON.stringify(config),
JSON.stringify(feedbackExtraValues || {}),
closestLimits
]);
return {
limits: formattedLimits,
closestLimits,
feedback,
isLoading: loading
};
};
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/components/RepeatBetModal/styled-components.ts
import styled from "styled-components"; export const RepeatBetContainer = styled.div` flex-direction: column; display: flex; overflow: auto; max-height: calc(100vh - 120px); `; export const BetSumaryContainer = styled.div` padding: 12px; position: relative; `; export const ButtonsContainer = styled.div` position: absolute; bottom: 0; width: 100%; padding: 0 12px 12px; overflow: hidden; background-color: var(--fd-colors-background-surface); `; // a dummy element is used to prevent dropdown erratic behaviour export const DummyElement = styled.div` height: 120px; `;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/components/RepeatBetModal/components/Dropdown/styled-components.ts
import styled, { css } from "styled-components";
import { buildColor } from "@tvg/design-system";
export const Container = styled.div`
position: absolute;
bottom: -142px;
z-index: 10;
background: ${buildColor("white", "900")};
border: 1px solid #d6e3f0;
box-shadow: 0 2px 4px rgba(17, 43, 68, 0.18);
border-radius: 2px;
`;
export const List = styled.ul`
display: flex;
flex-direction: column;
`;
export const ListItem = styled.li`
display: flex;
flex-direction: column;
`;
export const Button = styled.button<{ isActive?: boolean }>`
display: flex;
align-items: center;
width: 170px;
padding: 12px;
background: ${buildColor("white", "900")};
height: 42px;
cursor: pointer;
&:hover {
background-color: ${buildColor("blue_accent", "000")};
}
${({ isActive }) =>
isActive &&
css`
background: ${buildColor("blue_accent", "000")};
box-shadow:
inset 2px 0 0 #5390ed,
inset 0 -1px 0 #d6e3f0;
`};
`;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/components/RepeatBetModal/components/Dropdown/index.tsx
import React, { useEffect, useRef } from "react";
import { animated, config, useTransition } from "@react-spring/web";
import { Paragraph } from "@tvg/design-system";
import { Scroll } from "@tvg/design-system/web";
import { Button, Container, List, ListItem } from "./styled-components";
export interface DropdownProps {
onSelectValue: (value: number) => void;
values: Array<{ label: string; value: number }>;
selectedValue: number;
isVisible: boolean;
onClickAway: () => void;
}
const AnimatedContainer = animated(Container);
const Dropdown = ({
onSelectValue,
values,
selectedValue,
isVisible,
onClickAway
}: DropdownProps) => {
const ref = useRef<HTMLDivElement>(null);
const transition = useTransition(isVisible, {
config: isVisible ? { ...config.stiff } : { duration: 1 },
from: { opacity: 0, transform: `translate3d(0px, 1px, 0px)` },
enter: { opacity: 1, transform: `translate3d(0px, 0px, 0px)` },
leave: { opacity: 0, transform: `translate3d(0px, 1px, 0px)` }
});
useEffect(() => {
const element = document.getElementById(`dropdown-button-${selectedValue}`);
if (element && element.scrollIntoView && isVisible) {
element.scrollIntoView({ behavior: "auto", block: "start" });
}
}, [isVisible]);
useEffect(() => {
const handleClickAway = (event: MouseEvent) => {
const target = event.target as HTMLElement;
const isSelectorButton =
target?.getAttribute("data-qa-label") &&
target?.getAttribute("data-qa-label")?.toString() ===
"repetition-selector-button";
if (ref.current && !ref.current.contains(target) && !isSelectorButton) {
onClickAway();
}
};
document.addEventListener("click", handleClickAway, true);
return () => {
document.removeEventListener("click", handleClickAway, true);
};
}, [ref, onClickAway]);
return (
<>
{transition(
(styles, isOpen) =>
isOpen &&
values.length > 0 && (
<AnimatedContainer
data-qa-label="repetition-selector-dropdown"
ref={ref}
style={styles}
>
<Scroll
height="142px"
width="170px"
overflowY="scroll"
overflowX="hidden"
>
<List>
{values.map((item, index) => (
<ListItem key={index.toString()}>
<Button
onClick={() => {
onSelectValue(item.value);
}}
data-qa-label={`dropdown-button-${item.value}`}
id={`dropdown-button-${item.value}`}
>
<Paragraph
fontSize="s"
color="grey.900"
qaLabel="dropdown-button-text"
>
{item.label}
</Paragraph>
</Button>
</ListItem>
))}
</List>
</Scroll>
</AnimatedContainer>
)
)}
</>
);
};
export default Dropdown;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/components/RepeatBetModal/components/RepeaterSelector/styled-component.ts
import styled from "styled-components";
import { buildColor } from "@tvg/design-system";
export const RepeaterSelectorWrapper = styled.div<{ color: string }>`
display: flex;
flex-direction: column;
padding: 12px;
background-color: ${({ color }) => color};
`;
export const SelectContainer = styled.div`
display: flex;
position: relative;
align-items: center;
justify-content: space-between;
button:first-child {
flex-grow: 1;
}
`;
export const Button = styled.button`
display: flex;
align-items: center;
padding: 0 10px;
min-width: 192px;
height: 44px;
background-color: ${buildColor("white", "900")};
box-shadow: 0 1px 3px rgba(17, 43, 68, 0.12);
border-radius: 2px;
cursor: pointer;
&:hover {
background-color: ${buildColor("blue_accent", "000")};
}
&:active {
background-color: ${buildColor("blue_accent", "100")};
}
&:disabled {
background-color: ${buildColor("blue", "000")};
color: #f00;
}
`;
export const ButtonContent = styled.div`
display: flex;
flex-grow: 1;
pointer-events: none;
`;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/components/RepeatBetModal/components/RepeaterSelector/index.tsx
import React, { useState } from "react";
import { Icon, Paragraph, useTheme } from "@tvg/design-system";
import { Button as ButtonDS } from "@tvg/design-system/web";
import { UnaryFn } from "@tvg/ts-types/Functional";
import Dropdown from "../Dropdown";
import {
Button,
ButtonContent,
RepeaterSelectorWrapper,
SelectContainer
} from "./styled-component";
export interface RepeaterSelectorProps {
isDisabled: boolean;
repetitions: number;
selectedRepetition: number;
setSelectedRepetition: UnaryFn<number, void>;
}
const RepeaterSelector: React.FC<RepeaterSelectorProps> = ({
isDisabled,
selectedRepetition,
setSelectedRepetition,
repetitions
}) => {
const [isVisible, setIsVisible] = useState(false);
const { colors } = useTheme();
return (
<RepeaterSelectorWrapper color={colors.blue[800]}>
<Paragraph
qaLabel="rbm-selector-title"
color={colors.white[900]}
fontFamily="medium"
mb="space-3"
>
<>Repeat bet (x{repetitions} max)</>
</Paragraph>
<SelectContainer>
<Button
data-qa-label="repetition-selector-button"
disabled={isDisabled}
onClick={() => {
setIsVisible((prevIsVisible) => !prevIsVisible);
}}
>
<ButtonContent
data-qa-label="repetition-selector-button-content"
onClick={() => setIsVisible((prevIsVisible) => !prevIsVisible)}
>
<Paragraph
fontFamily="bold"
fontSize="s"
color={isDisabled ? "blue.300" : "grey.900"}
qaLabel="repetition-selector-text"
>
{`x${selectedRepetition}`}
</Paragraph>
<Icon
ml="auto"
name={isVisible ? "chevronUp" : "chevronDown"}
size="s"
lineColor="blue_accent.500"
/>
</ButtonContent>
</Button>
<Dropdown
values={Array.from(Array(repetitions).keys()).map((elem) => ({
label: `x${elem + 1}`,
value: elem + 1
}))}
isVisible={isVisible}
selectedValue={selectedRepetition}
onSelectValue={(val) => {
setIsVisible(false);
setSelectedRepetition(val);
}}
onClickAway={() => setIsVisible(false)}
/>
<ButtonDS
qaLabel="rbm-set-toMax"
variant="tertiary"
ml="space-4"
onClick={() => setSelectedRepetition(repetitions)}
icon={
<Icon
name="refresh"
size="s"
lineColor={colors.blue_accent[500]}
backgroundColor="transparent"
/>
}
>
Set to max
</ButtonDS>
</SelectContainer>
</RepeaterSelectorWrapper>
);
};
export default RepeaterSelector;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/components/RepeatBetModal/components/Alerts/index.tsx
import React from "react";
import { AlertInLine } from "@tvg/design-system/web";
import { getUserCompliance } from "@urp/unified-modules/src/utils/account/getUserCompliance";
import { TERMS_AND_CONDITIONS_OR_ACKNOWLEDGES_NOT_ACCEPTED } from "@tvg/api/uam";
import { ConfigCancelLimitFeedback } from "../../../ConfirmBetModal/hooks/useCancelLimits/types";
import { PlaceBetError } from "../../../../types";
export interface AlertsProps {
isRaceWagerable: boolean;
showRaceOffAlert: boolean;
hasScratches: boolean;
errorMessages: Array<PlaceBetError>;
placeBetSuccess: boolean;
placeBetError: boolean;
isBlockedByState: boolean;
userBalance: number;
totalAmount: number;
blockedByStateErrorMessage: string;
feedback: ConfigCancelLimitFeedback | null;
betConfirmationMessages: { noLongerAvailableForBetting: string };
confirmModalMessages: { validBet: string; invalidBet: string };
}
const Alerts = ({
isRaceWagerable,
showRaceOffAlert,
hasScratches,
errorMessages,
placeBetSuccess,
placeBetError,
isBlockedByState,
userBalance,
totalAmount,
blockedByStateErrorMessage,
feedback,
betConfirmationMessages,
confirmModalMessages
}: AlertsProps) => (
<>
{!isRaceWagerable && showRaceOffAlert && (
<AlertInLine
type="fixed"
qaLabel="race-off-repeat-bet-alert"
message={
betConfirmationMessages?.noLongerAvailableForBetting ||
"The race has started and you can no longer bet"
}
variant="warning"
mb="space-4"
/>
)}
{isRaceWagerable && hasScratches && (
<AlertInLine
type="fixed"
qaLabel="scratches-repeat-bet-alert"
message={
+totalAmount > 0
? confirmModalMessages?.validBet
: confirmModalMessages?.invalidBet
}
variant="warning"
mb="space-4"
/>
)}
{placeBetError &&
errorMessages.map((errorMessage) => {
const readMoreProps = errorMessage.code ===
TERMS_AND_CONDITIONS_OR_ACKNOWLEDGES_NOT_ACCEPTED && {
linkLabel: "View and accept terms",
onLinkClick: () => getUserCompliance()
};
return (
<AlertInLine
type="fixed"
variant="error"
key={errorMessage.code}
title={
errorMessage.message.title
? errorMessage.message.title
: errorMessage.message.text
}
message={
errorMessage.message.title ? errorMessage.message.text : ""
}
qaLabel="error-messages-alert"
mb="space-4"
{...readMoreProps}
/>
);
})}
{!(placeBetSuccess || placeBetError) && userBalance < totalAmount && (
<AlertInLine
type="fixed"
qaLabel="insufficient-amount-repeatBet"
message="Insufficient funds to place the bet"
variant="warning"
mb="space-4"
/>
)}
{isBlockedByState && (
<AlertInLine
type="fixed"
variant="error"
message={blockedByStateErrorMessage}
qaLabel="state-blocked-error"
mb="space-4"
/>
)}
{feedback && (
<AlertInLine
type="fixed"
qaLabel="raceCancelLimits"
title={feedback.title}
message={feedback.description || ""}
variant="informational"
linkLabel={feedback.link && feedback.link.label}
onLinkClick={() => feedback.link && window.open(feedback.link.url)}
mb="space-4"
/>
)}
</>
);
export default Alerts;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/components/ConfirmBetModal/styled-components.ts
import styled from "styled-components";
export const ConfirmBetModalFooterWrapper = styled.div`
display: flex;
flex-direction: column;
margin-top: var(--fd-space-space-3);
gap: var(--fd-space-space-3);
`;
export const BetConfirmationContainer = styled.div`
padding: var(--fd-space-space-3);
flex-direction: column;
display: flex;
overflow: auto;
max-height: calc(85vh - 120px);
`;
export const BetSummarySpecialBetsContainer = styled.div`
& > div {
margin-top: var(--fd-space-space-2);
}
`;
export const AlertMessageContainer = styled.div`
display: flex;
`;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/components/RepeatBetModal/utils/gtm/onRepeatBetSuccesfully.ts
import mediator from "@tvg/mediator";
interface OnRepeatBetSuccessfullyEventPaylod {
betType: string;
betAmount: number;
raceType?: string;
}
const onRepeatBetSuccessfullyEvent = ({
betType,
betAmount,
raceType
}: OnRepeatBetSuccessfullyEventPaylod) =>
mediator.base.dispatch({
type: "PPM_ON_REPEAT_BET_SUCCESSFULLY",
payload: {
betAmount,
betType,
raceType
}
});
export default onRepeatBetSuccessfullyEvent;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/components/RepeatBetModal/components/RepeatBetModalHeader/styled-components.ts
import styled from "styled-components";
export const HeaderWrapper = styled.div<{ placeBetSuccess: boolean }>`
display: flex;
flex-direction: row;
align-items: center;
width: 100%;
padding: 16px;
justify-content: center;
position: relative;
`;
export const CloseButton = styled.div`
width: 20px;
height: 20px;
position: absolute;
right: 16px;
top: 16px;
cursor: pointer;
`;
export const SuccessWrapper = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
`;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/components/RepeatBetModal/components/RepeatBetModalHeader/index.tsx
import React from "react";
import formatCurrency from "@tvg/formatter/currency";
import { pluralize } from "@tvg/utils/generalUtils";
import { Header } from "@tvg/design-system";
import { Icon, Paragraph } from "@tvg/design-system/web";
import {
CloseButton,
HeaderWrapper,
SuccessWrapper
} from "./styled-components";
// Utils
interface RepeatBetModalHeaderProps {
showBalance: boolean;
placeBetSuccess: boolean;
repetitions: number;
userBalance: number;
onClose?: () => void;
}
const RepeatBetModalHeader: React.FC<RepeatBetModalHeaderProps> = ({
showBalance,
placeBetSuccess,
repetitions,
userBalance,
onClose
}) => (
<HeaderWrapper placeBetSuccess={placeBetSuccess} data-qa-label="page-header">
{placeBetSuccess ? (
<>
<Icon
name="success"
size="s"
mr="space-3"
lineColor="--fd-colors-system-positive-content-accent"
backgroundColor="--fd-colors-system-positive-background-subtle"
/>
<Header
qaLabel="page-header-title"
tag="h1"
fontFamily="bold"
fontSize={18}
color="green.700"
>
{`${pluralize(repetitions, "Bet", true, "s", "x")} Placed`}
</Header>
</>
) : (
<SuccessWrapper>
<Header
qaLabel="page-header-title"
tag="h1"
fontFamily="bold"
fontSize={18}
color="grey.900"
>
Repeat Bet
</Header>
{showBalance && (
<Paragraph qaLabel="rbm-subtitle" color="grey.800" fontSize="14px">
<>BALANCE {formatCurrency(userBalance)}</>
</Paragraph>
)}
</SuccessWrapper>
)}
<CloseButton onClick={onClose} data-qa-label="page-header-close-button">
<Icon size="m" lineColor="--fd-colors-content-default" name="close" />
</CloseButton>
</HeaderWrapper>
);
export default RepeatBetModalHeader;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/components/RepeatBetModal/index.tsx
import React, {
useContext,
useMemo,
useState,
useEffect,
useCallback
} from "react";
import ApolloContext from "@tvg/utils/apolloContext";
import ApolloContextClients from "@tvg/utils/types/ApolloContext";
// Store
import {
getBetGroupStatus,
getErrorBets,
getProcessingBets,
getSuccessBets
} from "@tvg/desktop-bet/src/store/selectors";
import { useSelector } from "react-redux";
// DS
import { BetTypeCell, Breed } from "@tvg/design-system";
import {
Mtp,
Button,
Paragraph,
Header,
Modal,
AlertInLine,
LoadingSpinner
} from "@tvg/design-system/web";
// Types
import { BetBasicInfo, BetRepeatInfo } from "@tvg/ts-types/Bet";
import { WagerTypeCodesEnum } from "@tvg/ts-types/Wager";
import { BetStatus, BetStatusType } from "@tvg/desktop-bet/src/types";
// Utils
import { get } from "lodash";
import BetUtils from "@tvg/utils/betSelection";
import formatCurrency from "@tvg/formatter/currency";
import { getCurrentProbableValue } from "@tvg/sh-lib-my-bets/utils/potentialReturn";
import { RaceProgram, RaceStatusEnum } from "@tvg/ts-types/Race";
import { NullaryFn, UnaryFn } from "@tvg/ts-types/Functional";
import { isRaceOff } from "@tvg/sh-lib-my-bets/utils/raceDetails";
import calculateTotals from "@tvg/api/wtx/BetHelper";
import { getBettingInfo } from "@tvg/desktop-bet/src/utils/betUtils";
import { getAccountNumber, getHasPreviousWagered } from "@urp/store-selectors";
import useGeocomplyBetDisabled from "@urp/betslip/src/hooks/useGeocomplyBetDisabled";
import { isFDR, pluralize } from "@tvg/utils/generalUtils";
import { isXSell } from "@tvg/sh-utils/mobileUtils";
import { replaceCAPIVariables } from "@tvg/utils/capiUtils";
import { getSelectionsRunnerNbr } from "../../utils/raceUtils";
// Hooks
import { useBetBlockedByState, usePlaceBet } from "../../hooks";
import { useCancelLimits } from "../ConfirmBetModal/hooks/useCancelLimits";
// Components
import {
RepeatBetContainer,
BetSumaryContainer,
ButtonsContainer,
DummyElement
} from "./styled-components";
import RepeaterSelector from "./components/RepeaterSelector";
import Alerts from "./components/Alerts";
import { AlertMessageContainer } from "../ConfirmBetModal/styled-components";
// Relative path Store
import {
getBonus,
getBonusFundsWagerMessages,
getBonusFundsFeedbackEnabled,
getBetConfirmationMessages,
getBetConfirmModalTexts,
getCancelLimitBetSlipEnabled,
getCancelLimitsBetSlipConf,
getEnableUrpConfirmModalRepeatBet,
getRepeatBetConfig,
getUserBalanceIsShown,
getEnableURPAlternates
} from "../../store/selectors";
import onRepeatBetSuccessfullyEvent from "./utils/gtm/onRepeatBetSuccesfully";
import { confirmBetGtmEvent } from "../../utils/gtm/betConfirmJourney";
import RepeatBetModalHeader from "./components/RepeatBetModalHeader";
import { getSpecialWagerType } from "../../utils/wagersTypes";
interface RepeatBetModalProps {
isRepeatBetModalOpen: boolean;
race: RaceProgram;
races: RaceProgram[];
raceWager: BetBasicInfo | BetRepeatInfo;
userBalance: number;
setRepeatBetModalOpen: UnaryFn<boolean, void>;
onResponsibleGamingError?: NullaryFn<void>;
closeModalCallback?: NullaryFn<void>;
isSpecialWager?: boolean;
}
const RepeatBetModal: React.FC<RepeatBetModalProps> = ({
isRepeatBetModalOpen,
race,
races,
raceWager,
userBalance,
setRepeatBetModalOpen,
onResponsibleGamingError,
closeModalCallback,
isSpecialWager
}) => {
const { behgClient } = useContext<ApolloContextClients>(ApolloContext);
const [isWagerableState, setWagerableState] = useState(true);
const [isInvalidBet, setIsInvalidBet] = useState(false);
const [isLoadingBonus, setIsLoadingBonus] = useState(true);
const [hasBonusBeforeBet, setHasBonusBeforeBet] = useState(false);
const {
handleSubmitBet,
resetBetting,
errorMessages,
betDisable,
clearErrorMessages
} = usePlaceBet();
if (isRaceOff(race.status?.code || RaceStatusEnum.OPEN)) {
setRepeatBetModalOpen(false);
}
const MAX_REPETITIONS = 20;
const [selectedRepetition, setSelectedRepetition] = useState(1);
let typeFromRace = BetUtils.getOriginalBetTypeFromRace(
race,
raceWager.wagerType.id as unknown as WagerTypeCodesEnum
);
// ====== hack because program page way of identify WPS ======
// Some functions like bet amount calculation it uses the columnCount to identify the type of calculation required to be done,
// and for example Win/Place/Show in those functions required the columnCount === 1 to enter in the correct formula.
// but some other fuctions like how the buttons should appear in the programPage required this to have the correct value of 3 (Ex: WPS bet type)
// so here we are disconnecting the object from the one used in the parents components so we can change the value withotu interfering in anything.
typeFromRace = typeFromRace?.specialGroup
? { ...typeFromRace, columnCount: 1 }
: typeFromRace;
const [isBlockedByState, blockedByStateErrorMessage] = useBetBlockedByState();
const { isBetDisabled: isGeoComplyBetDisabled } = useGeocomplyBetDisabled();
const isPlacingBetError = useSelector(getErrorBets);
const betGroupStatus = useSelector(getBetGroupStatus);
const betConfirmationMessages = useSelector(getBetConfirmationMessages);
const confirmModalMessages = useSelector(getBetConfirmModalTexts);
const cancelLimitConfig = useSelector(getCancelLimitsBetSlipConf);
const cancelLimitFeedbackEnabled = useSelector(getCancelLimitBetSlipEnabled);
const accountNumber = useSelector(getAccountNumber);
const repeatBetConfig = useSelector(getRepeatBetConfig);
const userBalanceIsShown = useSelector(getUserBalanceIsShown);
const isPlacingBetSuccess = useSelector(getSuccessBets);
const isPlacingBet = useSelector(getProcessingBets);
const selectionsRunnerNbr = getSelectionsRunnerNbr(raceWager);
const enableUrpConfirmModalRepeatBet = useSelector(
getEnableUrpConfirmModalRepeatBet
);
const userBonus = useSelector(getBonus);
const hasMadePreviousWager = useSelector(getHasPreviousWagered);
const bonusFundsWagerMessages = useSelector(getBonusFundsWagerMessages);
const isBonusFundsFeedbackEnabled = useSelector(getBonusFundsFeedbackEnabled);
const isAlternatesToggleOn = useSelector(getEnableURPAlternates);
const { numberOfWagerableRunners, fullSelections } = getBettingInfo(
selectionsRunnerNbr,
raceWager.wagerAmount,
race,
races,
typeFromRace,
isAlternatesToggleOn
);
const scratches = BetUtils.getSelectionsRunnerNbrScratched(fullSelections);
const handleNrOfScratches = Object.values(scratches).filter(
(value) => value.length
);
const placeBetError =
isPlacingBetError > 0 && isPlacingBet === 0 && errorMessages.length > 0;
const isLoading = isPlacingBet > 0;
const placeBetSuccess =
isPlacingBetSuccess > 0 && isPlacingBet === 0 && !placeBetError;
const type = get(typeFromRace, "type.code", WagerTypeCodesEnum.WIN);
const mtp = get(race, "mtp", "0");
const status = get(race, "status.code");
const postTime = get(race, "postTime");
const trackName = get(race, "track.trackName");
const betRaceNumber = get(race, "raceNumber");
const trackCode = get(race, "track.trackCode");
const trackCountry = get(race, "track.trackLocation.country");
const isRaceWagerable = get(race, "wagerable", false);
useEffect(() => {
clearErrorMessages();
}, [selectedRepetition]);
useEffect(() => {
const wagerableState =
status !== RaceStatusEnum.RACE_OFF &&
status !== RaceStatusEnum.RACE_OFFICIAL &&
status !== "C";
setWagerableState(wagerableState);
}, [status]);
useEffect(() => {
const isBetInvalid = fullSelections.some((selection) =>
selection.every((runner) => runner.scratched)
);
if (isBetInvalid) {
setIsInvalidBet(true);
}
}, [JSON.stringify(scratches), JSON.stringify(fullSelections)]);
useEffect(() => {
if (isRepeatBetModalOpen) clearErrorMessages();
}, [isRepeatBetModalOpen]);
useEffect(() => {
if (userBonus) {
setHasBonusBeforeBet(true);
}
if (placeBetSuccess) {
setIsLoadingBonus(false);
}
}, [userBonus]);
const approximatedPayout = useMemo(
() =>
getCurrentProbableValue(
get(race, "probables", []),
get(raceWager, "wagerType"),
get(raceWager, "wagerAmount", 0),
selectionsRunnerNbr
),
[race, raceWager, selectedRepetition]
);
const handleCloseModal = () => {
setRepeatBetModalOpen(false);
setSelectedRepetition(1);
clearErrorMessages();
if (closeModalCallback) closeModalCallback();
};
const completeSelections = useCallback(() => {
const validSelections = fullSelections.map((selection) =>
selection.filter((obj) => !obj.scratched)
);
const validSelectionsWithoutAlternates = validSelections.map(
(validSelection) => validSelection.filter((obj) => !obj.isAlternate)
);
const fullSelectionsWithoutAlternates = fullSelections.map(
(fullSelection) => fullSelection.filter((obj) => !obj.isAlternate)
);
if (!isAlternatesToggleOn) {
return handleNrOfScratches.length
? validSelectionsWithoutAlternates
: fullSelectionsWithoutAlternates;
}
return handleNrOfScratches.length ? validSelections : fullSelections;
}, [fullSelections, isAlternatesToggleOn, handleNrOfScratches]);
const handleRepeatBet = useCallback(() => {
const specialWagerType = getSpecialWagerType(race);
confirmBetGtmEvent({
betAmount: +raceWager.wagerAmount,
betType: raceWager.wagerType.name,
raceType: race.type?.name,
specialWagerType
});
handleSubmitBet({
betAmount: +raceWager.wagerAmount,
betSelectionsGroup: completeSelections(),
race,
selectedRepetition,
forceWagerType: get(typeFromRace, "type.id"),
hasMadePreviousWager
});
onRepeatBetSuccessfullyEvent({
betAmount: +raceWager.wagerAmount,
betType: raceWager.wagerType.name,
raceType: race.type?.name
});
}, [
race,
raceWager,
selectedRepetition,
completeSelections,
typeFromRace,
hasMadePreviousWager,
handleSubmitBet,
onRepeatBetSuccessfullyEvent,
confirmBetGtmEvent
]);
const handleSelections = useCallback(
() =>
Object.values(completeSelections()).map((arr) =>
arr
.filter((selection) => !selection.isAlternate) // Exclude alternate runners
.map((selection) => Number(selection.number.replace(/\D/g, "")))
),
[completeSelections]
);
// filter repeated if array has coupled runners
const uniqueSelectionsHandled = (handledSelections: Array<Array<number>>) =>
handledSelections.map((sel: Array<number>) =>
sel.filter((item, index) => sel.indexOf(item) === index)
);
const totals = typeFromRace
? calculateTotals(
raceWager.wagerAmount,
typeFromRace,
uniqueSelectionsHandled(handleSelections())
)
: 0;
const totalAmount =
selectedRepetition *
(typeof totals === "object" ? +totals.betCost : totals);
const { feedback } = useCancelLimits({
needsFetch: isRepeatBetModalOpen && cancelLimitFeedbackEnabled,
accountNumber,
behgClient,
config: cancelLimitConfig,
feedbackExtraValues: {
forceFeedback: placeBetSuccess ? "placed" : undefined,
prediction: {
amount: typeof totals === "object" ? +totals.betCost : totals,
count: selectedRepetition
},
track: {
code: trackCode,
name: trackName,
country: trackCountry
}
},
currentRace: trackCode
});
const isWagerableRace = isXSell() ? isWagerableState : isRaceWagerable;
const placeBetNotAllowed =
isBlockedByState ||
betDisable ||
isGeoComplyBetDisabled ||
userBalance < totalAmount ||
!isWagerableRace ||
placeBetSuccess;
const betsStatus = Object.values<BetStatus>(betGroupStatus).map(
(betType) => betType && betType.status
);
const showRaceOffAlert =
(status === RaceStatusEnum.RACE_OFF &&
Object.keys(betGroupStatus).length !== 0 &&
betsStatus.includes(BetStatusType.ERROR)) ||
(status === RaceStatusEnum.RACE_OFF &&
Object.keys(betGroupStatus).length === 0);
const isBetRepeatable = useMemo(
() =>
placeBetSuccess &&
!fullSelections.some((entry) => entry.some((value) => value.scratched)),
[placeBetSuccess, fullSelections]
);
const isResponsibleGamingError = !!(
errorMessages?.some(({ message }) => message.buttonType === "rgLimits") &&
isFDR() &&
onResponsibleGamingError
);
const bonusMessage = () => {
if (placeBetSuccess) {
const splitMessage =
bonusFundsWagerMessages?.betPlaced.split("#bonusValue#");
return (
<AlertMessageContainer>
{splitMessage[0]}
{isLoadingBonus ? <LoadingSpinner /> : formatCurrency(userBonus)}
{splitMessage[1]}
</AlertMessageContainer>
);
}
return replaceCAPIVariables(bonusFundsWagerMessages?.confirmBet, {
bonusValue:
+userBonus >= +totalAmount
? formatCurrency(+totalAmount)
: formatCurrency(userBonus)
});
};
return (
<Modal
isOpen={isRepeatBetModalOpen}
headerProps={{
title: placeBetSuccess
? `${pluralize(selectedRepetition, "Bet", true, "s", "x")} Placed`
: "Repeat Bet",
description: +userBalanceIsShown
? `BALANCE ${formatCurrency(userBalance)}`
: "",
showCloseButton: true
}}
padding={0}
onClose={handleCloseModal}
onAfterClose={() => resetBetting(false)}
qaLabel="repeat-bet-modal"
customHeader={
<RepeatBetModalHeader
userBalance={userBalance}
placeBetSuccess={placeBetSuccess}
repetitions={selectedRepetition}
showBalance={Boolean(+userBalanceIsShown)}
onClose={handleCloseModal}
/>
}
hideHeader
>
<RepeatBetContainer>
<Alerts
isRaceWagerable={isRaceWagerable}
showRaceOffAlert={showRaceOffAlert}
hasScratches={handleNrOfScratches.length > 0}
errorMessages={errorMessages}
placeBetSuccess={placeBetSuccess}
placeBetError={placeBetError}
isBlockedByState={isBlockedByState}
userBalance={userBalance}
totalAmount={totalAmount}
blockedByStateErrorMessage={blockedByStateErrorMessage}
feedback={feedback}
betConfirmationMessages={betConfirmationMessages}
confirmModalMessages={confirmModalMessages}
/>
{isBonusFundsFeedbackEnabled &&
((!placeBetSuccess && userBonus) ||
(placeBetSuccess && hasBonusBeforeBet)) ? (
<AlertInLine
type="fixed"
qaLabel="bonusConfirmUse"
message=""
variant="success"
>
{bonusMessage()}
</AlertInLine>
) : null}
<BetSumaryContainer>
<Mtp
mtp={+mtp}
status={status}
postTime={postTime as string}
qaLabel="confirm-bet-modal-mtp"
size="xs"
/>
<Header
tag="h3"
fontFamily="bold"
color="grey.900"
qaLabel="confirm-bet-modal-race-name"
mb="space-1"
>
{`${trackName} ${isSpecialWager ? "" : "R"}${!isSpecialWager ? betRaceNumber : ""}`}
</Header>
<BetTypeCell
mt={24}
qaLabel="rbm-bet-cell"
completeSelection={fullSelections}
selections={get(fullSelections, 0)}
scratches={scratches}
approximatedPayout={approximatedPayout}
numWagerableRunners={numberOfWagerableRunners}
betAmount={formatCurrency(raceWager.wagerAmount)}
betTicket={formatCurrency(
typeof totals === "object" ? +totals.betCost : totals
)}
type={type}
breed={
get(race, "type.name", "Thoroughbred").toLowerCase() as Breed
}
isKey={get(typeFromRace, "isKey", false)}
isBox={get(typeFromRace, "isBox", false)}
isWheel={get(typeFromRace, "isWheel", false)}
betStatus="NONE"
betTypeName={get(typeFromRace, "type.name", WagerTypeCodesEnum.WIN)}
isLeg={get(typeFromRace, "legCount", 1) > 1}
raceNumber={betRaceNumber}
isRepeatable={isBetRepeatable && enableUrpConfirmModalRepeatBet}
onRepeatBetHandler={() => resetBetting()}
displayAlternateSelection={isAlternatesToggleOn}
showAlternatePlaceholder={false}
isSpecialWager={isSpecialWager}
/>
{!placeBetSuccess && !isInvalidBet && (
<RepeaterSelector
isDisabled={isLoading || placeBetSuccess}
repetitions={repeatBetConfig.maxAllowed || MAX_REPETITIONS}
selectedRepetition={selectedRepetition}
setSelectedRepetition={setSelectedRepetition}
/>
)}
<DummyElement />
</BetSumaryContainer>
<ButtonsContainer>
{!placeBetSuccess && !isInvalidBet && (
<>
{isResponsibleGamingError ? (
<Button
variant="primary"
onClick={onResponsibleGamingError}
qaLabel="betConfirmation-rgLimitsBtn"
mt="space-7"
isStretched
>
View Limits
</Button>
) : (
<Button
variant="betting"
onClick={handleRepeatBet}
qaLabel="confirm-bet-modal-sucess-button"
mt="space-7"
isDisabled={isLoading || placeBetNotAllowed}
isLoading={isLoading}
isStretched
>
<Paragraph
qaLabel=""
fontFamily="medium"
color={
placeBetNotAllowed
? "--fd-colors-component-button-primary-content-disabled"
: "--fd-colors-component-button-primary-content-base"
}
>
<>
Confirm x{selectedRepetition} Repeat |{" "}
{formatCurrency(totalAmount)} Bet
</>
</Paragraph>
</Button>
)}
</>
)}
<Button
variant={placeBetSuccess ? "primary" : "secondary"}
onClick={handleCloseModal}
qaLabel="confirm-bet-modal-close-button"
mt="space-4"
isStretched
>
Close
</Button>
</ButtonsContainer>
</RepeatBetContainer>
</Modal>
);
};
export default RepeatBetModal;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/utils/raceUtils.ts
import { RaceProgram, RaceStatusEnum, RaceWagerType } from "@tvg/ts-types/Race";
import { WagerTypeCodesEnum } from "@tvg/ts-types/Wager";
import { BetBasicInfo, BetRepeatInfo } from "@tvg/ts-types/Bet";
import { get } from "lodash";
import BetSelectionUtils from "@tvg/utils/betSelectionUtils";
import { isHongKongRaces } from "./general";
export const filterHKRaces = (currentRace: RaceProgram) =>
isHongKongRaces(currentRace.track?.trackCode || "")
? BetSelectionUtils.filterHKCoupledEntries(
get(currentRace, "bettingInterests", [])
)
: currentRace.bettingInterests;
export const isRaceoff = (race: RaceProgram) =>
get(race, "status.code", "") === RaceStatusEnum.RACE_OFF;
export const isWagerable = (race: RaceProgram, isScrollableRaceCard: boolean) =>
get(race, "wagerable", false) &&
(get(race, "wagerTypes", []).length > 0 || isScrollableRaceCard);
export const isRefunded = (race: RaceProgram) =>
!!race.results && !get(race, "results.runners");
export const getSelectionsRunnerNbr = (
wager: BetBasicInfo | BetRepeatInfo
): Array<Array<string>> =>
(wager.selections?.selection || []).map((selection) =>
selection.runners.map((runner) => runner.number.toString())
);
export const formattedScrollableWagerType = (legCount: number = 0) =>
({
columnCount: 1,
specialGroup: false,
unitedWagerTypeCode: "WIN",
type: { id: 10, name: "Win", code: "WN" as WagerTypeCodesEnum },
isBox: false,
isKey: false,
isWheel: false,
group: { id: 10, name: "Win", code: "WN" as WagerTypeCodesEnum },
legCount,
minWagerAmount: 0,
wagerAmounts: [],
positionCount: 0,
types: []
}) as RaceWagerType;
export const arraysAreEqual = (a: string[], b: string[]) => {
if (a === b) return true;
if (!a || !b) return false;
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false;
}
return true;
};
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/hooks/useBetBlockedByState.ts
import { shallowEqual, useSelector } from "react-redux";
import { useEffect, useState } from "react";
import tvgConf from "@tvg/conf";
import { getResidenceState } from "@urp/store-selectors";
import {
getFeatureBettingBlockedByUserState,
getForbiddenBettingStates
} from "../store/selectors";
import { ForbiddentBettingStates } from "../types";
const useBetBlockedByState = (): [boolean, string] => {
const { blockedStates = [], errorMessage = "" }: ForbiddentBettingStates =
useSelector(getForbiddenBettingStates, shallowEqual);
const userState = useSelector(getResidenceState, shallowEqual).toLowerCase();
const featureEnabled = useSelector(
getFeatureBettingBlockedByUserState,
shallowEqual
);
const [isStateBlocked, setIsStateBlocked] = useState(false);
const isDesktop = tvgConf().device === "desktop";
useEffect(() => {
if (featureEnabled && isDesktop) {
const foundBlockedState = blockedStates.some(
(state: string) => state.toLowerCase() === userState.toLowerCase()
);
setIsStateBlocked(foundBlockedState);
}
}, [userState, isDesktop]);
return [isStateBlocked, errorMessage];
};
export default useBetBlockedByState;
webpack://frontend-mybets/../../packages/urp-comp-betslip/src/hooks/useGeocomplyBetDisabled.ts
import { useEffect, useState } from "react";
import { isEmpty } from "lodash";
import { useDispatch, useSelector } from "react-redux";
import {
getGeolocationStatus,
getGeolocationError,
getGeolocationErrorRetryable
} from "@tvg/sh-geolocation/src/redux/selectors";
import { GeolocationStatus } from "@tvg/sh-geolocation/src/types";
import { getGeoTokenCookie } from "@tvg/sh-utils/sessionUtils";
import { getIsLogged } from "@urp/store-selectors";
import { tryGeolocationRetry } from "@tvg/sh-geolocation/src/redux/actions";
import { isFdr } from "../utils/general";
type UseGeocomplyBetDisabled = {
isBetDisabled: boolean;
isGeolocationErrorRetryable: boolean | undefined;
isGeolocationError: boolean;
};
export const useGeocomplyBetDisabled = (): UseGeocomplyBetDisabled => {
const dispatch = useDispatch();
const [isBetDisabled, setIsBetDisabled] = useState<boolean>(false);
const geolocationStatus = useSelector(getGeolocationStatus);
const geolocationError = useSelector(getGeolocationError);
const isGeolocationErrorRetryable: boolean | undefined = useSelector(
getGeolocationErrorRetryable
);
const isLogged = useSelector(getIsLogged);
useEffect(() => {
if (isFdr()) {
const isGeolocationError =
!isEmpty(geolocationError) ||
geolocationStatus === GeolocationStatus.REJECTED ||
geolocationStatus === GeolocationStatus.FAILURE;
const isGeolocationRunningUpdate =
geolocationStatus === GeolocationStatus.PROGRESS;
// prevent token disappear for unknow reason (without errors)
if (
isLogged &&
!getGeoTokenCookie() &&
!isGeolocationError &&
!isGeolocationRunningUpdate
) {
dispatch(tryGeolocationRetry(true));
}
setIsBetDisabled(
!isLogged ||
isGeolocationError ||
!isGeolocationErrorRetryable ||
isGeolocationRunningUpdate
);
}
}, [
geolocationStatus,
geolocationError,
isGeolocationErrorRetryable,
isLogged
]);
return {
isBetDisabled,
isGeolocationErrorRetryable,
isGeolocationError: isLogged && !isEmpty(geolocationError)
};
};
export default useGeocomplyBetDisabled;
webpack://frontend-mybets/../../packages/urp-comp-betslip/src/utils/general.ts
import tvgConf from "@tvg/conf";
import { SourceKeysEnum, SourceValue } from "../types";
export const isFdr = () => tvgConf().brand === "fdr";
export const buildSelectionSource = (
origin: SourceKeysEnum | undefined,
defaultValue: SourceValue = "Race Card"
): SourceValue => {
if (origin === undefined) {
return defaultValue;
}
const originMap = new Map<SourceKeysEnum, SourceValue>([
[SourceKeysEnum.FDTV_PICKS, "fdtv_race_card"],
[SourceKeysEnum.TRACKMASTER, "trackmaster_race_card"],
[SourceKeysEnum.NUMBERFIRE, "numberfire_race_card"],
[SourceKeysEnum.SELECT_ALL_RUNNERS, "Race Card"],
[SourceKeysEnum.RACE_CARD, "Race Card"],
[SourceKeysEnum.REPEAT_BET_RACE_CARD, "repeat_bet_race_card"],
[SourceKeysEnum.REPEAT_BET_MY_BETS, "repeat_bet_my_bets"]
]);
// When we guarantee a true extensive 1 to 1 map with no undefined allowed
// this verification won't theoretically be necessary
return originMap.get(origin) ?? defaultValue;
};
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/components/ConfirmBetModal/graphql/options.graph.ts
import { ApolloClient, NormalizedCacheObject } from "@apollo/client";
import { QueryHookOptions } from "@apollo/client/react/types/types";
export interface Props {
accountNumber: string;
behgClient: ApolloClient<NormalizedCacheObject>;
hasConfig: boolean;
needsFetch: boolean;
}
export default ({
accountNumber,
behgClient,
hasConfig,
needsFetch
}: Props): QueryHookOptions => {
const variables = {
accountId: +accountNumber
};
return {
skip: !needsFetch || !hasConfig || !variables.accountId,
client: behgClient,
fetchPolicy: "network-only",
ssr: false,
variables
};
};
webpack://frontend-mybets/../../packages/urp-lib-unified-modules/src/utils/responsibleGaming/openScreen/index.ts
import { UMEventsResponsibleGaming } from "../../mediator/types";
import { getUMEvent } from "../../mediator/events";
import mediator from "../../mediator";
export const openResponsibleGamingScreen = (
screen: UMEventsResponsibleGaming
) => {
const event = getUMEvent(screen);
mediator.dispatch({
type: event.trigger
});
};
webpack://frontend-mybets/../../node_modules/date-fns/esm/differenceInMinutes/index.js
import differenceInMilliseconds from '../differenceInMilliseconds/index.js';
import requiredArgs from '../_lib/requiredArgs/index.js';
var MILLISECONDS_IN_MINUTE = 60000;
/**
* @name differenceInMinutes
* @category Minute Helpers
* @summary Get the number of minutes between the given dates.
*
* @description
* Get the signed number of full (rounded towards 0) minutes between the given dates.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the later date
* @param {Date|Number} dateRight - the earlier date
* @returns {Number} the number of minutes
* @throws {TypeError} 2 arguments required
*
* @example
* // How many minutes are between 2 July 2014 12:07:59 and 2 July 2014 12:20:00?
* var result = differenceInMinutes(
* new Date(2014, 6, 2, 12, 20, 0),
* new Date(2014, 6, 2, 12, 7, 59)
* )
* //=> 12
*
* @example
* // How many minutes are from 10:01:59 to 10:00:00
* var result = differenceInMinutes(
* new Date(2000, 0, 1, 10, 0, 0),
* new Date(2000, 0, 1, 10, 1, 59)
* )
* //=> -1
*/
export default function differenceInMinutes(dirtyDateLeft, dirtyDateRight) {
requiredArgs(2, arguments);
var diff = differenceInMilliseconds(dirtyDateLeft, dirtyDateRight) / MILLISECONDS_IN_MINUTE;
return diff > 0 ? Math.floor(diff) : Math.ceil(diff);
}
webpack://frontend-mybets/../../node_modules/date-fns/esm/differenceInMilliseconds/index.js
import toDate from '../toDate/index.js';
import requiredArgs from '../_lib/requiredArgs/index.js';
/**
* @name differenceInMilliseconds
* @category Millisecond Helpers
* @summary Get the number of milliseconds between the given dates.
*
* @description
* Get the number of milliseconds between the given dates.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the later date
* @param {Date|Number} dateRight - the earlier date
* @returns {Number} the number of milliseconds
* @throws {TypeError} 2 arguments required
*
* @example
* // How many milliseconds are between
* // 2 July 2014 12:30:20.600 and 2 July 2014 12:30:21.700?
* var result = differenceInMilliseconds(
* new Date(2014, 6, 2, 12, 30, 21, 700),
* new Date(2014, 6, 2, 12, 30, 20, 600)
* )
* //=> 1100
*/
export default function differenceInMilliseconds(dirtyDateLeft, dirtyDateRight) {
requiredArgs(2, arguments);
var dateLeft = toDate(dirtyDateLeft);
var dateRight = toDate(dirtyDateRight);
return dateLeft.getTime() - dateRight.getTime();
}
webpack://frontend-mybets/../../packages/tvg-lib-utils/RaceHeaderUtils.js
import { get, has, map, omit, forEach, pickBy } from "lodash";
import { formatPurse } from "@tvg/formatter/currency";
import { differenceInMinutes } from "date-fns";
const createRaceDataForHeader = (race, enableRaceChanges = false) => {
const keysRace = [
"numRunners",
"distance",
"surface.shortName",
"surface.defaultCondition",
"raceClass.shortName",
"type.shortName",
"purse"
];
const changesKeyMap = {
distance: "distance",
"surface.shortName": "course",
"surface.defaultCondition": "condition"
};
const keyGreyhoundsRace = ["distance", "raceClass.name"];
const dataArr = get(race, "isGreyhound") ? keyGreyhoundsRace : keysRace;
const surfaceChanges = pickBy(get(race, "changes.surface"));
const resArr = [];
forEach(dataArr, (item) => {
const defRes = {
item,
changed:
enableRaceChanges &&
Object.keys(surfaceChanges).indexOf(changesKeyMap[item]) !== -1
};
if (has(race, item)) {
if (item === "raceClass.shortName" && get(race, "claimingPrice") > 0) {
resArr.push({
...defRes,
value: `${formatPurse(get(race, "claimingPrice"))} ${get(race, item)}`
});
} else if (item === "purse") {
resArr.push({
...defRes,
value: formatPurse(get(race, "purse"))
});
} else {
const raceItem = get(race, item);
if (raceItem) {
resArr.push({
...defRes,
value: item === "numRunners" ? `${raceItem} runners` : raceItem
});
}
}
}
});
return map(resArr, (e) => omit(e, "item"));
};
export const getVideoFeedback = (
currentRace,
firstRace,
lastRace,
enableReplays
) => {
let replayValue = false;
if (
enableReplays &&
get(currentRace, "video.hasReplay", false) &&
get(currentRace, "video.replayFileName") &&
get(currentRace, "video.mobileAvailable")
) {
replayValue = true;
}
if (!get(currentRace, "video.liveStreaming")) {
return replayValue ? "NOT_AVAILABLE_REPLAY" : "NOT_AVAILABLE_NO_REPLAY";
}
const firstRaceDate = new Date(get(firstRace, "postTime"));
const lastRaceDate = new Date(get(lastRace, "postTime"));
const dateNow = new Date();
const firstRaceDiff = differenceInMinutes(dateNow, firstRaceDate);
const lastRaceDiff = differenceInMinutes(lastRaceDate, dateNow);
// one hour and a half before the first race
if (firstRaceDiff < -90) {
return replayValue ? "NOT_AVAILABLE_REPLAY" : "NOT_AVAILABLE_NO_REPLAY";
}
// between 1 hour and a half and 1 hour before the first race
if (firstRaceDiff >= -90 && firstRaceDiff < -60) {
return replayValue ? "STARTING_SOON_REPLAY" : "STARTING_SOON_NO_REPLAY";
}
// half an hour after the last race
if (lastRaceDiff < -30) {
return replayValue ? "FINISHED_REPLAY" : "FINISHED_NO_REPLAY";
}
return replayValue ? "AVAILABLE_REPLAY" : "AVAILABLE_NO_REPLAY";
};
const getImportanceLevel = (level) => (level === "Normal" ? "0" : "1");
const RaceHeaderUtils = {
createRaceDataForHeader,
getVideoFeedback,
getImportanceLevel
};
export default RaceHeaderUtils;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/utils/video.ts
import mediator from "@tvg/mediator";
import { RaceInfoMyBets } from "@tvg/ts-types/Race";
import RaceHeaderUtils from "@tvg/utils/RaceHeaderUtils";
import { NullaryFn } from "@tvg/ts-types/Functional";
import { handleRaceHeaderGtm, RaceHeaderGTM } from "./gtm";
export const onVideoRedirect = (
closeModal: NullaryFn<void>,
gtmProps: RaceHeaderGTM = {
selectedTab: "ACTIVE",
selectedSettledTab: "TODAY",
activeBets: 0,
settledBets: 0
}
) => {
closeModal();
handleRaceHeaderGtm("MYBETS_USER_CLICKS_VIDEO_LIVE_BUTTON", gtmProps);
};
export const deviceLockRotationToggle =
(videoFullscreenTilt: boolean) =>
(lock: boolean = true) => {
if (videoFullscreenTilt) {
mediator.ios.dispatch({
type: "IPHONE_LOCK_SCREEN_ROTATION",
payload: { lockScreenRotation: lock ? 0 : 2 }
});
}
};
export const getVideoFeedback = (
race: RaceInfoMyBets,
firstRace?: RaceInfoMyBets,
lastRace?: RaceInfoMyBets
) => RaceHeaderUtils.getVideoFeedback(race, firstRace, lastRace, true);
webpack://frontend-mybets/../../packages/sh-lib-my-bets/hooks/useAllRacesFromTrack.ts
import { useEffect, useState } from "react";
import { RaceInfoMyBets } from "@tvg/ts-types/Race";
type Props = {
races: RaceInfoMyBets[];
trackCode: string;
};
function useAllRacesFromTrack(props: Props) {
const { races, trackCode } = props;
const [allRacesFromTrack, setAllRacesFromTrack] = useState<RaceInfoMyBets[]>(
[]
);
useEffect(() => {
if (races) {
setAllRacesFromTrack(races.filter((race) => race.id.includes(trackCode)));
}
}, [races, trackCode]);
return allRacesFromTrack;
}
export default useAllRacesFromTrack;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/Icons/iconsDuotone.js
export const america = {
id: "america",
shapes: [
{
path: "M86.3223 18.7519C86.5134 19.094 86.2076 19.8352 85.9401 20.5194C85.6917 21.1846 86.2458 21.8878 86.9529 21.8117C87.7364 21.7167 88.5199 22.0588 88.9594 22.705L90.5073 24.9476C90.641 25.1377 90.6793 25.3847 90.6219 25.5938L90.2015 27.2282C90.0678 27.7034 90.4691 28.1595 90.9659 28.1025C91.5774 28.0264 92.1698 27.7794 92.6476 27.3993L95.9917 24.8146C96.0108 24.8146 96.0108 24.7956 96.0299 24.7956L100.463 20.7094C100.502 20.6714 100.521 20.6334 100.559 20.5954L102.393 17.2125C102.508 17.0224 102.68 16.8704 102.909 16.8134L108.489 15.369C108.642 15.331 108.757 15.236 108.795 15.0839L111.184 8.37508C111.318 8.03298 111.662 7.80492 112.025 7.84293L115.044 8.14702C115.312 8.16602 115.56 8.33707 115.675 8.56513L118.407 13.7726C118.579 14.0956 118.503 14.4757 118.254 14.7228L113.936 18.7899C113.84 18.8849 113.783 19.018 113.802 19.151L114.184 23.5792C114.203 23.8453 114.088 24.1114 113.878 24.2824L109.407 27.7034C109.311 27.7794 109.235 27.8934 109.235 28.0264L108.967 31.4284C108.948 31.6944 108.795 31.9225 108.585 32.0555L106.846 33.1198C106.731 33.1769 106.674 33.2909 106.636 33.4049L105.814 37.415C105.795 37.51 105.814 37.6241 105.852 37.7001L108.088 41.9953C108.241 42.2803 108.203 42.6224 107.993 42.8695L104.113 47.5638L104.094 47.5828L97.96 55.9071C97.8645 56.0401 97.8454 56.1921 97.9027 56.3442L100.635 62.7679C100.654 62.8059 100.674 62.863 100.674 62.901L102.451 70.9592C102.508 71.2633 102.413 71.5673 102.164 71.7574C102.011 71.8714 101.82 71.9284 101.629 71.9284H98.1893C97.9218 71.9284 97.6543 71.7954 97.5205 71.5673L93.947 66.0748C93.8897 65.9988 93.8706 65.9228 93.8323 65.8278L93.2208 63.3761C93.1826 63.205 93.0489 63.091 92.8769 63.053L88.4626 62.1027C88.4434 62.1027 88.4434 62.1027 88.4243 62.1027L82.5195 61.3805C82.4239 61.3615 82.3284 61.3806 82.2328 61.4376L78.8313 63.4521C78.7931 63.4711 78.7549 63.4901 78.7167 63.5091L75.1241 64.8585C75.0094 64.8965 74.8948 64.9155 74.7801 64.9155L66.9834 64.3074C66.8687 64.3074 66.7732 64.3264 66.6776 64.3834L61.3461 68.2414C61.2314 68.3174 61.155 68.4505 61.155 68.6025L61.1741 73.1828C61.1741 73.4488 61.0403 73.6959 60.8301 73.848C60.6964 73.943 60.5244 74 60.3715 74C60.2759 74 60.1804 73.981 60.0848 73.943L55.3457 72.1755C55.1546 72.0995 55.0017 71.9664 54.9062 71.7764L51.7531 65.3716C51.7149 65.2766 51.6384 65.2006 51.5429 65.1626L48.2178 63.6992C48.0649 63.6232 47.8738 63.6612 47.7401 63.7752L46.3642 64.9535C46.1922 65.1056 45.9629 65.1626 45.7336 65.1436C45.5042 65.1056 45.3132 64.9915 45.1794 64.8015L42.0836 60.4113C42.0454 60.3543 41.9881 60.3163 41.9308 60.2782L35.7966 56.9333C35.7393 56.8953 35.6628 56.8763 35.5864 56.8763H29.0891C28.9362 56.8763 28.8025 56.8383 28.6687 56.7623L20.9484 52.011C20.9102 51.992 20.8529 51.954 20.7956 51.954L15.6169 50.9467C15.4449 50.9087 15.2729 50.8137 15.1582 50.6806L9.73113 44.4279C9.65469 44.3519 9.61647 44.2569 9.57825 44.1618L7.41887 37.8521C7.39976 37.8141 7.39976 37.7761 7.38065 37.7381L6.34874 31.8845C6.34874 31.8655 6.34874 31.8655 6.34874 31.8465L5.50792 25.8789C5.48881 25.7648 5.50792 25.6508 5.52702 25.5368L7.03668 20.5194C7.05579 20.4814 7.05579 20.4624 7.0749 20.4244L11.0497 10.3136C11.0688 10.2566 11.0879 10.1806 11.0879 10.1236L10.763 5.10618C10.7439 4.82111 10.8777 4.53603 11.1261 4.38399C11.3746 4.23195 11.6803 4.21294 11.9478 4.34598L14.4703 5.67634C14.6996 5.79037 14.9863 5.69535 15.1009 5.44828L15.5022 4.49802C15.6551 4.13692 16.0564 3.92786 16.4386 4.02289L26.2227 6.49356C26.2418 6.49356 26.2418 6.49356 26.2609 6.49356L37.5738 8.43209H37.5929L50.7212 9.95251C50.7403 9.95251 50.7403 9.95251 50.7594 9.95251L64.4609 10.3896C64.5565 10.3896 64.652 10.4086 64.7476 10.4466L67.1172 11.4349C67.1745 11.4539 67.2318 11.4729 67.2892 11.4729L69.3721 11.5109C69.4676 11.5109 69.5632 11.5299 69.6396 11.5679L72.0283 12.4612C72.0665 12.4802 72.1239 12.4802 72.1621 12.4802L74.8374 12.5752C75.1241 12.5942 75.3725 12.7463 75.5063 12.9743C75.64 13.2214 75.64 13.5065 75.5063 13.7535L75.3343 14.0766C75.1432 14.4377 75.5063 14.8558 75.8885 14.7038L77.9714 13.8866C78.2963 13.7726 78.6402 13.8486 78.8696 14.1146L80.1308 15.559C80.2454 15.6921 80.4174 15.7491 80.5894 15.6921L83.5514 14.8749C83.7807 14.8178 84.0291 14.8558 84.2202 14.9889L86.3223 18.7519Z",
fill: "#D6E3F0",
strokeLinejoin: "round"
}
]
};
// eslint-disable-next-line
export const play = {
id: "play",
shapes: [
{
path: "M9.99998 19.0664C15.0072 19.0664 19.0664 15.0072 19.0664 9.99998C19.0664 4.99275 15.0072 0.933594 9.99998 0.933594C4.99275 0.933594 0.933594 4.99275 0.933594 9.99998C0.933594 15.0072 4.99275 19.0664 9.99998 19.0664ZM7.18748 14.3598V5.62914L14.075 10.0064L7.18748 14.3598Z",
fillRule: "evenodd",
fill: null,
strokeWidth: 1.5
}
]
};
export const trash = {
id: "trash",
shapes: [
{
path: "M2.99995 4.25L3.90785 13.352C3.96017 13.8621 4.38985 14.25 4.90263 14.25H11.0973C11.61 14.25 12.0397 13.8621 12.0921 13.352L13 4.25H10.5H5.49995H2.99995Z",
fill: null,
strokeWidth: 0,
fillRule: "evenodd",
clipRule: "evenodd"
},
{
path: "M6.49995 6V12.25M9.49995 6V12.25M2.99995 4.25H5.49995M2.99995 4.25H1M2.99995 4.25L3.90785 13.352C3.96017 13.8621 4.38985 14.25 4.90263 14.25H11.0973C11.61 14.25 12.0397 13.8621 12.0921 13.352L13 4.25M13 4.25H10.5M13 4.25H15M10.5 4.25H5.49995M10.5 4.25V2.75C10.5 2.19772 10.0522 1.75 9.49995 1.75H6.49995C5.94767 1.75 5.49995 2.19772 5.49995 2.75V4.25",
fill: null,
strokeWidth: 1.5
}
]
};
export const repeat = {
id: "repeat",
shapes: [
{
path: "M9.16068 2.74744C11.4249 2.74744 14.25 4.4967 14.25 7.99998C14.25 11.5033 11.4249 13.2525 9.16068 13.2525H6.83944C4.65301 13.2525 1.75 11.5033 1.75 7.99998C1.75 4.4967 4.57526 2.74744 6.83944 2.74744H9.16068Z",
fill: null,
strokeWidth: 0,
fillRule: "evenodd",
clipRule: "evenodd"
},
{
path: "M4 2.74746L6.21161 0.535828M4 2.74746L6.21161 4.95907M4 2.74746H9.16056C11.4247 2.74746 14.25 4.49672 14.25 8.00001C14.25 8.74763 14.1178 9.41537 13.8886 10.0033M12 13.2526L9.78839 11.0409M12 13.2526L9.78839 15.4642M12 13.2526H6.83932C4.57513 13.2526 1.75 11.5033 1.75 8.00001C1.75 7.2561 1.87739 6.59129 2.09974 6.00552",
fill: null,
strokeWidth: 1.5,
strokeLinejoin: "round"
}
]
};
export const question = {
id: "question",
shapes: [
{
path: "M15.2501 8.00276C15.2501 12.007 12.0041 15.2531 7.99983 15.2531C3.99559 15.2531 0.749512 12.007 0.749512 8.00276C0.749512 3.99852 3.99559 0.752441 7.99983 0.752441C12.0041 0.752441 15.2501 3.99852 15.2501 8.00276Z",
fill: null,
strokeWidth: 0
},
{
path: "M7.99982 12V10.5M5.99982 5.99997C5.99982 5.99997 5.99982 3.99997 7.99982 3.99997C9.99982 3.99997 9.99982 5.99997 9.99982 5.99997C9.99982 7.99997 7.99982 7.49997 7.99982 9.49997M15.2501 8.00276C15.2501 12.007 12.0041 15.2531 7.99983 15.2531C3.99559 15.2531 0.749512 12.007 0.749512 8.00276C0.749512 3.99852 3.99559 0.752441 7.99983 0.752441C12.0041 0.752441 15.2501 3.99852 15.2501 8.00276Z",
fill: null,
strokeWidth: 1.5
}
]
};
export const info = {
id: "info",
shapes: [
{
path: "M15.2504 8.00276C15.2504 12.007 12.0043 15.2531 8.0001 15.2531C3.99586 15.2531 0.749786 12.007 0.749786 8.00276C0.749786 3.99852 3.99586 0.752441 8.0001 0.752441C12.0043 0.752441 15.2504 3.99852 15.2504 8.00276Z",
fill: null,
strokeWidth: 0
},
{
path: "M8.00009 12V6.99997M8.00009 5.49997V3.99997M15.2504 8.00276C15.2504 12.007 12.0043 15.2531 8.0001 15.2531C3.99586 15.2531 0.749786 12.007 0.749786 8.00276C0.749786 3.99852 3.99586 0.752441 8.0001 0.752441C12.0043 0.752441 15.2504 3.99852 15.2504 8.00276Z",
fill: null,
strokeWidth: 1.5
}
]
};
export const infoOutline = {
id: "infoOutline",
shapes: [
{
path: "M977.017 512.177c0 256.271-207.749 464.02-464.02 464.02-256.271 0-464.02-207.749-464.02-464.02 0-256.272 207.749-464.02 464.02-464.02 256.271 0 464.02 207.748 464.02 464.02z",
fill: null
},
{
path: "M512.997 96.156c-229.762 0-416.02 186.259-416.02 416.021 0 229.761 186.258 416.02 416.02 416.02 229.762 0 416.02-186.259 416.02-416.02 0-229.762-186.258-416.02-416.02-416.02zM.977 512.177C.977 229.396 230.216.157 512.997.157c282.781 0 512.023 229.239 512.023 512.02 0 282.781-229.242 512.023-512.023 512.023C230.216 1024.2.977 794.958.977 512.177zm560.019-256.179v96h-96v-96h96zm0 192v320h-96v-320h96z",
fill: null,
fillRule: "evenodd",
clipRule: "evenodd"
}
]
};
export const betCanceled = {
id: "betCanceled",
shapes: [
{
path: "M12.25 1.75H3.75C3.19772 1.75 2.75 2.19772 2.75 2.75V14.5L5 13.5L6.5 14.5L8 13.5L9.5 14.5L11 13.5L13.25 14.5V2.75C13.25 2.19772 12.8023 1.75 12.25 1.75Z",
fill: null,
strokeWidth: 0
},
{
path: "M8 13.5L6.5 14.5L5 13.5L2.75 14.5V2.75C2.75 2.19772 3.19772 1.75 3.75 1.75H12.25C12.8023 1.75 13.25 2.19772 13.25 2.75V8M5 5.75H8M5 8.75H9M10.5 9.5L13 12M13 12L15.5 14.5M13 12L10.5 14.5M13 12L15.5 9.5",
fill: null,
strokeWidth: 1.5,
strokeLinejoin: "round"
}
]
};
export const key = {
id: "key",
shapes: [
{
path: "M2.86982 14.1147C4.43099 15.6759 6.95866 15.6759 8.51983 14.1147C9.64129 12.9932 9.95956 11.3781 9.46983 9.97469L14.2498 5.19469L14.2498 2.73468L11.7956 2.73468L7.00983 7.51469C5.60873 7.02998 3.9886 7.34592 2.86983 8.46469C1.30866 10.0259 1.30865 12.5535 2.86982 14.1147ZM5.68982 12.0447C6.10352 12.0447 6.43982 11.7084 6.43982 11.2947C6.43982 10.881 6.10352 10.5447 5.68982 10.5447C5.27611 10.5447 4.93982 10.881 4.93982 11.2947C4.93982 11.7084 5.27612 12.0447 5.68982 12.0447Z",
fill: null,
fillRule: "evenodd",
clipRule: "evenodd",
strokeWidth: 0
},
{
path: "M10.6805 6.97898L10.6805 8.57088M12.3339 5.44859L12.3339 6.97898M2.86983 8.46469C1.30866 10.0259 1.30865 12.5535 2.86982 14.1147C4.43099 15.6759 6.95866 15.6759 8.51983 14.1147C9.64129 12.9932 9.95956 11.3781 9.46983 9.97469L14.2498 5.19469L14.2498 2.73468L11.7956 2.73468L7.00983 7.51469C5.60873 7.02998 3.9886 7.34592 2.86983 8.46469ZM6.43982 11.2947C6.43982 11.7084 6.10352 12.0447 5.68982 12.0447C5.27612 12.0447 4.93982 11.7084 4.93982 11.2947C4.93982 10.881 5.27612 10.5447 5.68982 10.5447C6.10352 10.5447 6.43982 10.881 6.43982 11.2947Z",
fill: null,
strokeWidth: 1.5
}
]
};
export const optedIn = {
id: "optedIn",
shapes: [
{
path: "M8.43448 2.25195H13.2484C13.8007 2.25195 14.2484 2.69967 14.2484 3.25195V8.06592C14.2484 8.34424 14.1325 8.60997 13.9284 8.79921L7.79696 14.4844C7.40275 14.8499 6.79008 14.8384 6.40993 14.4582L2.04216 10.0905C1.66202 9.71032 1.65046 9.09765 2.01598 8.70343L7.70119 2.57203C7.89043 2.36794 8.15616 2.25195 8.43448 2.25195Z",
fill: null,
strokeWidth: 0
},
{
path: "M5.99992 7.5L7.99992 9.5L11.9999 5.5M13.2484 2.25195H8.43448C8.15616 2.25195 7.89043 2.36794 7.70119 2.57203L2.01598 8.70343C1.65046 9.09765 1.66202 9.71032 2.04216 10.0905L6.40993 14.4582C6.79008 14.8384 7.40275 14.8499 7.79696 14.4844L13.9284 8.79921C14.1325 8.60997 14.2484 8.34424 14.2484 8.06592V3.25195C14.2484 2.69967 13.8007 2.25195 13.2484 2.25195Z",
fill: null,
strokeWidth: 1.5,
strokeLinejoin: "round"
}
]
};
export const referFriend = {
id: "referFriend",
shapes: [
{
path: "M4.84685 8.99805H11.153C11.8295 8.99805 12.4223 9.45084 12.6002 10.1035L13.3874 12.991C13.5609 13.6271 13.082 14.254 12.4226 14.254H3.57723C2.91789 14.254 2.43901 13.6271 2.61244 12.991L3.39967 10.1035C3.57761 9.45084 4.17038 8.99805 4.84685 8.99805Z",
fill: null,
strokeWidth: 0
},
{
path: "M10.5015 4.247C10.5015 5.62848 9.38156 6.74839 8.00008 6.74839C6.6186 6.74839 5.49868 5.62848 5.49868 4.247C5.49868 2.86552 6.6186 1.74561 8.00008 1.74561C9.38156 1.74561 10.5015 2.86552 10.5015 4.247Z",
fill: null
},
{
path: "M8.50003 14.2544H3.57735C2.91801 14.2544 2.43913 13.6275 2.61256 12.9914L3.39979 10.1038C3.57773 9.45119 4.1705 8.9984 4.84698 8.9984H8.50003M9.75 12.0002H15.2031M12.75 9.50021L15.25 12.0002L12.75 14.5002M10.5015 4.247C10.5015 5.62848 9.38156 6.74839 8.00008 6.74839C6.6186 6.74839 5.49868 5.62848 5.49868 4.247C5.49868 2.86552 6.6186 1.74561 8.00008 1.74561C9.38156 1.74561 10.5015 2.86552 10.5015 4.247Z",
fill: null,
strokeWidth: 1.5,
strokeLinejoin: "round"
}
]
};
export const doubleArrowRight = {
id: "doubleArrowRight",
shapes: [
{
path: "M10 4.27466L16.25 10.5247L10 16.7747M3.75 4.27466L10 10.5247L3.75 16.7747",
fill: null,
strokeWidth: 1.5,
strokeLinejoin: "round"
}
]
};
export const successDouble = {
id: "success",
shapes: [
{
path: "M15.2501 8.00276C15.2501 12.007 12.0041 15.2531 7.99983 15.2531C3.99559 15.2531 0.749512 12.007 0.749512 8.00276C0.749512 3.99852 3.99559 0.752441 7.99983 0.752441C12.0041 0.752441 15.2501 3.99852 15.2501 8.00276Z",
fill: null
},
{
path: "M4.49988 7.99997L6.99988 10.5L11.9999 5.49997M15.2501 8.00276C15.2501 12.007 12.0041 15.2531 7.99983 15.2531C3.99559 15.2531 0.749512 12.007 0.749512 8.00276C0.749512 3.99852 3.99559 0.752441 7.99983 0.752441C12.0041 0.752441 15.2501 3.99852 15.2501 8.00276Z",
fill: null,
strokeColor: "#329A47",
strokeWidth: 1.5
}
]
};
export const lock = {
id: "lock",
shapes: [
{
path: "M11.25 7.73621V4.7431C11.25 4.7431 11.25 1.75 8 1.75C4.75 1.75 4.75 4.7431 4.75 4.7431V7.73621",
fill: "#ffffff",
strokeColor: "#384048",
strokeWidth: 1.5
},
{
xRect: 2.75,
yRect: 7.73633,
widthRect: 10.5,
heightRect: 6.51379,
rxRect: 1,
fill: "#DEE1E3",
strokeColor: "#384048",
strokeWidth: 1.5
},
{
path: "M8 10V12",
fill: null,
strokeColor: "#384048",
strokeWidth: 1.5
}
]
};
export const file = {
id: "file",
shapes: [
{
path: "M3 2H10V5H13V13H3V2Z",
fill: "#DEE1E3"
},
{
path: "M11 13.5H3.75C3.19772 13.5 2.75 13.0523 2.75 12.5V5.25M13.25 13V10.75V5.5L9.75 2H2M9.75 2.05339V5.5H13.198",
fill: null,
strokeColor: "#384048",
strokeWidth: 1.5,
strokeLinejoin: "round"
},
{
path: "M1 1L15 15",
fill: null,
strokeColor: "#384048",
strokeWidth: 1.5,
strokeLinejoin: "round"
}
]
};
export const chevronUp = {
id: "chevronUp",
shapes: [
{
path: "M3 10.0493L8 5.04932L13 10.0493",
fill: null,
strokeWidth: 1.5,
strokeLinejoin: "round"
}
]
};
export const chevronDown = {
id: "chevronDown",
shapes: [
{
path: "M13 6L8 11L3 6",
fill: null,
strokeWidth: 1.5,
strokeLinejoin: "round"
}
]
};
export const chevronRight = {
id: "chevronRight",
shapes: [
{
path: "M5 3L10 8L5 13",
fill: null,
strokeColor: "#626D78",
strokeWidth: 1.5,
strokeLinejoin: "round"
}
]
};
export const arrowForward = {
id: "arrowForward",
shapes: [
{
path: "M12.1895 8.74999H2.00012C1.72398 8.74999 1.50012 8.52613 1.50012 8.24999V7.74999C1.50012 7.47384 1.72398 7.24999 2.00012 7.24999H12.1895L8.82334 3.88386C8.62808 3.6886 8.62808 3.37202 8.82334 3.17676L9.17689 2.8232C9.37216 2.62794 9.68874 2.62794 9.884 2.8232L14.5304 7.46965C14.8233 7.76254 14.8233 8.23742 14.5304 8.53031L9.884 13.1768C9.68874 13.372 9.37216 13.372 9.17689 13.1768L8.82334 12.8232C8.62808 12.6279 8.62808 12.3114 8.82334 12.1161L12.1895 8.74999Z",
fill: null
}
]
};
export const close = {
id: "close",
shapes: [
{
path: "M3.50012 3.5L12.5001 12.5M12.5001 3.5L3.50012 12.5",
fill: null,
strokeWidth: 1.5,
strokeLinejoin: "round"
}
]
};
export const successRound = {
id: "successRound",
shapes: [
{
path: "M15.2505 8.00276C15.2505 12.007 12.0044 15.2531 8.00013 15.2531C3.99589 15.2531 0.749817 12.007 0.749817 8.00276C0.749817 3.99852 3.99589 0.752441 8.00013 0.752441C12.0044 0.752441 15.2505 3.99852 15.2505 8.00276Z",
fill: null,
strokeWidth: 0
},
{
path: "M4.50018 7.99997L7.00018 10.5L12.0002 5.49997M15.2505 8.00276C15.2505 12.007 12.0044 15.2531 8.00013 15.2531C3.99589 15.2531 0.749817 12.007 0.749817 8.00276C0.749817 3.99852 3.99589 0.752441 8.00013 0.752441C12.0044 0.752441 15.2505 3.99852 15.2505 8.00276Z",
fill: null,
strokeWidth: 1.5
}
]
};
export const errorRound = {
id: "errorRound",
shapes: [
{
path: "M15.2505 8.00276C15.2505 12.007 12.0044 15.2531 8.00013 15.2531C3.99589 15.2531 0.749817 12.007 0.749817 8.00276C0.749817 3.99852 3.99589 0.752441 8.00013 0.752441C12.0044 0.752441 15.2505 3.99852 15.2505 8.00276Z",
fill: null,
strokeWidth: 0
},
{
path: "M5.00018 4.99997L8.00018 7.99997M8.00018 7.99997L11.0002 11M8.00018 7.99997L5.00018 11M8.00018 7.99997L11.0002 4.99997M15.2505 8.00276C15.2505 12.007 12.0044 15.2531 8.00013 15.2531C3.99589 15.2531 0.749817 12.007 0.749817 8.00276C0.749817 3.99852 3.99589 0.752441 8.00013 0.752441C12.0044 0.752441 15.2505 3.99852 15.2505 8.00276Z",
fill: null,
strokeWidth: 1.5
}
]
};
export const exclamationMarkRound = {
id: "exclamationMarkRound",
shapes: [
{
path: "M7.29302 1.21052C7.68354 0.819999 8.3167 0.82 8.70723 1.21052L14.7896 7.29287C15.1801 7.68339 15.1801 8.31656 14.7896 8.70708L8.70723 14.7894C8.3167 15.1799 7.68354 15.1799 7.29302 14.7894L1.21067 8.70708C0.820149 8.31656 0.82015 7.68339 1.21067 7.29287L7.29302 1.21052Z",
fill: null,
strokeWidth: 0
},
{
path: "M8.00012 8.99997L8.00012 4.49997M8.00012 11.5L8.00012 9.99997M1.21067 8.70708L7.29302 14.7894C7.68354 15.1799 8.3167 15.1799 8.70723 14.7894L14.7896 8.70708C15.1801 8.31656 15.1801 7.68339 14.7896 7.29287L8.70723 1.21052C8.3167 0.82 7.68354 0.819999 7.29302 1.21052L1.21067 7.29287C0.820149 7.68339 0.820149 8.31656 1.21067 8.70708Z",
fill: null,
strokeWidth: 1.5
}
]
};
export const exclamationMark = {
id: "exclamationMark",
shapes: [
{
path: "M15.2503 8.00279C15.2503 12.007 12.0043 15.2531 8.00001 15.2531C3.99577 15.2531 0.749695 12.007 0.749695 8.00279C0.749695 3.99855 3.99577 0.752472 8.00001 0.752472C12.0043 0.752472 15.2503 3.99855 15.2503 8.00279Z",
fill: null
},
{
path: "M8 9V4M8 12V10.5M15.2503 8.00279C15.2503 12.007 12.0043 15.2531 8.00001 15.2531C3.99577 15.2531 0.749695 12.007 0.749695 8.00279C0.749695 3.99855 3.99577 0.752472 8.00001 0.752472C12.0043 0.752472 15.2503 3.99855 15.2503 8.00279Z",
fill: null,
strokeWidth: 1.5
}
]
};
export const questionMarkRound = {
id: "questionMarkRound",
shapes: [
{
path: "M15.2501 8.00276C15.2501 12.007 12.0041 15.2531 7.99983 15.2531C3.99559 15.2531 0.749512 12.007 0.749512 8.00276C0.749512 3.99852 3.99559 0.752441 7.99983 0.752441C12.0041 0.752441 15.2501 3.99852 15.2501 8.00276Z",
fill: null,
strokeWidth: 0
},
{
path: "M7.99982 12V10.5M5.99982 5.99997C5.99982 5.99997 5.99982 3.99997 7.99982 3.99997C9.99982 3.99997 9.99982 5.99997 9.99982 5.99997C9.99982 7.99997 7.99982 7.49997 7.99982 9.49997M15.2501 8.00276C15.2501 12.007 12.0041 15.2531 7.99983 15.2531C3.99559 15.2531 0.749512 12.007 0.749512 8.00276C0.749512 3.99852 3.99559 0.752441 7.99983 0.752441C12.0041 0.752441 15.2501 3.99852 15.2501 8.00276Z",
fill: null,
strokeWidth: 1.5
}
]
};
export const scratchedBox = {
id: "scratchedBox",
shapes: [
{
path: "M0 1a1 1 0 011-1h18a1 1 0 011 1v18a1 1 0 01-1 1H1a1 1 0 01-1-1V1z",
strokeWidth: 0,
fill: "transparent"
},
{
path: "M.972 20H19a1 1 0 001-1V1a1 1 0 00-1-1H1a1 1 0 00-1 1v18.027A1 1 0 00.972 20zM17.38 1.5H1.5v15.879L17.379 1.5zM2.5 18.5h16v-16l-16 16z",
strokeWidth: 0,
fill: null,
fillRule: "evenodd",
clipRule: "evenodd"
}
]
};
export const userTick = {
id: "userTick",
shapes: [
{
path: "M4.84685 8.99829H11.153C11.8295 8.99829 12.4223 9.45109 12.6002 10.1037L13.3874 12.9912C13.5609 13.6274 13.082 14.2543 12.4226 14.2543H3.57723C2.91789 14.2543 2.43901 13.6274 2.61244 12.9912L3.39967 10.1037C3.57761 9.45109 4.17038 8.99829 4.84685 8.99829Z",
strokeWidth: 0,
fill: "#DEE1E3"
},
{
path: "M10.5014 4.24676C10.5014 5.62824 9.38144 6.74815 7.99996 6.74815C6.61847 6.74815 5.49856 5.62824 5.49856 4.24676C5.49856 2.86527 6.61847 1.74536 7.99996 1.74536C9.38144 1.74536 10.5014 2.86527 10.5014 4.24676Z",
strokeWidth: 0,
fill: "#DEE1E3"
},
{
path: "M8.49991 14.2541H3.57723C2.91789 14.2541 2.43901 13.6272 2.61244 12.9911L3.39967 10.1036C3.57761 9.45095 4.17038 8.99815 4.84685 8.99815H8.49991M9.49988 12L11.4999 14L15.4999 9.99996M10.5014 4.24676C10.5014 5.62824 9.38144 6.74815 7.99996 6.74815C6.61847 6.74815 5.49856 5.62824 5.49856 4.24676C5.49856 2.86527 6.61847 1.74536 7.99996 1.74536C9.38144 1.74536 10.5014 2.86527 10.5014 4.24676Z",
fill: null,
strokeColor: "#384048",
strokeWidth: 1.5,
strokeLinejoin: "round"
}
]
};
// viewBoxSize 32
export const cup = {
id: "cup",
shapes: [
{
path: "M8.50001 3.5H23.5001L23.5 7C23.5 7 23.5 7.17955 23.4907 7.5C23.4519 8.82849 23.2524 12.5786 22.226 15.9965C21.1996 19.4143 19.3463 22.5 16 22.5C12.6537 22.5 10.8004 19.4143 9.77399 15.9965C8.74756 12.5786 8.54808 8.82849 8.50931 7.5C8.49995 7.17955 8.49995 7 8.49995 7L8.50001 3.5Z",
clipRule: "evenodd",
fillRule: "evenodd",
fill: "#ECEDEE"
},
{
path: "M16 22.5L16 28.5M16 22.5C12.6537 22.5 10.8004 19.4143 9.77399 15.9965M16 22.5C19.3463 22.5 21.1996 19.4143 22.226 15.9965M8.49995 7L8.50001 3.5H23.5001L23.5 7C23.5 7 23.5 7.17955 23.4907 7.5M8.49995 7C8.49995 7 8.49997 11.7541 9.77399 15.9965M8.49995 7C8.49995 7 8.49995 7.17955 8.50931 7.5M16 28.5H9.99995M16 28.5H22M8.50931 7.5H3.49995C3.49995 7.5 3.49995 15.8018 9.77399 15.9965M8.50931 7.5C8.54808 8.82849 8.74756 12.5786 9.77399 15.9965M22.226 15.9965C28.5 15.8018 28.5 7.5 28.5 7.5H23.4907M22.226 15.9965C23.2524 12.5786 23.4519 8.82849 23.4907 7.5",
strokeColor: "#818A92",
strokeWidth: 2,
strokeLinejoin: "round",
fill: null
}
]
};
export const warning = {
id: "warning",
shapes: [
{
path: "M1.82179 14.25H14.1775C14.5524 14.25 14.794 13.8527 14.6214 13.5198L8.44387 1.606C8.25732 1.24622 7.74269 1.24621 7.55612 1.60598L1.37792 13.5198C1.20532 13.8527 1.44687 14.25 1.82179 14.25Z",
fill: null
},
{
path: "M8.00002 6V10M8.00002 11V12.5M7.55612 1.60598L1.37792 13.5198C1.20532 13.8527 1.44687 14.25 1.82179 14.25H14.1775C14.5524 14.25 14.794 13.8527 14.6214 13.5198L8.44387 1.606C8.25732 1.24622 7.74269 1.24621 7.55612 1.60598Z",
fill: null,
strokeColor: "",
strokeWidth: 1.5
}
]
};
export const announcements = {
id: "announcements",
shapes: [
{
path: "M21.375 6.15001V17.85M21.375 6.15001V3M21.375 6.15001L4.55169 8.59275C3.44554 8.75337 2.625 9.70165 2.625 10.8194V13.1806C2.625 14.2984 3.44554 15.2467 4.55169 15.4073M21.375 17.85V21M21.375 17.85L13.875 16.761M21.375 17.85L4.55169 15.4073M5.625 15.5631V19.875H13.875V16.761M5.625 15.5631L4.55169 15.4073M5.625 15.5631L13.875 16.761",
fill: null,
strokeColor: "#5390ED",
strokeWidth: 2
}
]
};
export const bell = {
id: "bell",
shapes: [
{
path: "M8.04184 9.5H4.04184H1L1.54977 8.18073C1.87307 7.40492 1.99063 6.56185 2.0538 5.72376C2.18661 3.96205 2.88002 1 6.04181 1C9.25134 1 9.9174 4.05217 10.0355 5.80272C10.0886 6.59026 10.1885 7.38276 10.471 8.1198L11 9.5H8.04184Z",
fillRule: "evenodd",
clipRule: "evenodd",
fill: "white",
fillOpacity: 0.1
},
{
path: "M8.04184 9.5H11L10.471 8.1198C10.1885 7.38276 10.0886 6.59026 10.0355 5.80272C9.9174 4.05217 9.25134 1 6.04181 1C2.88002 1 2.18661 3.96205 2.0538 5.72376C1.99063 6.56185 1.87307 7.40492 1.54977 8.18073L1 9.5H4.04184M8.04184 9.5V10C8.04184 11.1046 7.14641 12 6.04184 12C4.93727 12 4.04184 11.1046 4.04184 10V9.5M8.04184 9.5H4.04184",
fill: null,
strokeWidth: 1.5,
strokeLinejoin: "round",
strokeColor: "#818A92"
}
]
};
export const crossedBell = {
id: "crossedBell",
shapes: [
{
path: "M1 1L15 15M12.4791 9.25L12.4292 9.1198C12.1467 8.38276 12.0468 7.59026 11.9937 6.80272C11.8756 5.05217 11.2095 2 8 2C7.17748 2 6.52201 2.20046 6 2.52809M4.48091 4.5C4.18574 5.26496 4.06104 6.07454 4.01211 6.72219C3.9488 7.56028 3.83126 8.40492 3.50796 9.18073L2.95819 10.5H6M6 10.5V11C6 12.1046 6.89543 13 8 13C9.10457 13 10 12.1046 10 11L10 10.5H6Z",
fill: null,
strokeColor: "#5390ED",
strokeWidth: 1.5,
strokeLinejoin: "round"
}
]
};
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/OptedInTag/styled-components.ts
import styled, { css } from "styled-components";
import buildColor from "@tvg/atomic-ui/_static/ColorPalette";
import { fontCondensedNormal } from "@tvg/atomic-ui/_static/Typography";
export const Wrapper = styled.div<{
isInline: boolean;
}>`
align-items: center;
justify-content: center;
background-color: ${buildColor("green", "100")};
${({ isInline }) =>
isInline
? css`
display: inline-flex;
height: 24px;
padding: 4px 8px;
border-radius: 12px;
`
: css`
display: flex;
height: 30px;
padding: 0 8px;
border-top: 1px solid ${buildColor("green", "200")};
border-bottom: 1px solid ${buildColor("green", "200")};
`}
`;
export const Text = styled.span<{
isInline: boolean;
}>`
font-family: ${fontCondensedNormal};
color: ${buildColor("green", "800")};
text-transform: uppercase;
font-size: ${({ isInline }) => (isInline ? "14px" : "12px")};
line-height: 17px;
margin-left: 4px;
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/OptedInTag/index.tsx
import React from "react";
import Icon from "@tvg/atomic-ui/_static/Icons";
import buildColor from "@tvg/atomic-ui/_static/ColorPalette";
import { optedIn } from "@tvg/atomic-ui/_static/Icons/iconsDuotone";
import { Wrapper, Text } from "./styled-components";
export type Props = {
isInline?: boolean;
qaLabel?: string;
};
const OptedInTag = ({
isInline = false,
qaLabel = "myBets-betTicket-optedInTag"
}: Props) => (
<Wrapper data-qa-label={`${qaLabel}-container`} isInline={isInline}>
<Icon
icon={optedIn}
viewBoxSize={16}
size={16}
color={buildColor("green", "200")}
stroke={buildColor("green", "700")}
/>
<Text data-qa-label={`${qaLabel}-text`} isInline={isInline}>
opted in
</Text>
</Wrapper>
);
export default OptedInTag;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MyBetsDesktopRaceDetails/styled-components.ts
import styled, { css } from "styled-components";
import buildColor from "@tvg/atomic-ui/_static/ColorPalette";
import {
fontMedium,
fontCondensedNormal
} from "@tvg/atomic-ui/_static/Typography";
export const TitleWrapper = styled.div<{ shouldRedirect?: boolean }>`
display: flex;
font-family: ${fontMedium};
font-size: 14px;
color: ${buildColor("grey", "900")};
line-height: 18px;
font-weight: 500;
margin-bottom: 4px;
max-width: 190px;
white-space: pre;
${({ shouldRedirect }) =>
shouldRedirect &&
css`
cursor: pointer;
`}
`;
export const TrackName = styled.p`
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
`;
export const RaceNumber = styled.p`
margin-left: 4px;
`;
export const PlacedWrapper = styled.p`
font-family: ${fontCondensedNormal};
font-size: 12px;
color: ${buildColor("grey", "800")};
line-height: 13px;
font-weight: 400;
text-transform: uppercase;
& + div {
margin-top: 8px;
}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MyBetsDesktopRaceDetails/index.tsx
import React from "react";
import { format, parseISO } from "date-fns";
import {
TitleWrapper,
PlacedWrapper,
TrackName,
RaceNumber
} from "./styled-components";
type Props = {
trackName: string;
raceNumber?: number;
transactionDate: string;
onClick: () => void;
shouldRedirect?: boolean;
isSpecialWager?: boolean;
};
const MyBetsDesktopRaceDetails = ({
trackName,
raceNumber,
transactionDate,
onClick,
shouldRedirect,
isSpecialWager = false
}: Props) => (
<>
<TitleWrapper onClick={onClick} shouldRedirect={shouldRedirect}>
<TrackName>{trackName}</TrackName>
{raceNumber && !isSpecialWager && <RaceNumber>R{raceNumber}</RaceNumber>}
</TitleWrapper>
{transactionDate && (
<PlacedWrapper>
Placed {format(parseISO(transactionDate), "h:mma - MM/dd/yyyy")}
</PlacedWrapper>
)}
</>
);
export default MyBetsDesktopRaceDetails;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MyBetsDesktopBetDetails/styled-components.ts
import styled, { css } from "styled-components";
import buildColor from "@tvg/atomic-ui/_static/ColorPalette";
import {
fontNormal,
fontCondensedNormal
} from "@tvg/atomic-ui/_static/Typography";
import Text from "@tvg/atomic-ui/_atom/Text";
const IconTextInlineStyles = css`
display: flex;
align-items: center;
svg {
margin-left: 4px;
}
`;
export const TitleWrapper = styled.p`
font-family: ${fontNormal};
font-size: 14px;
color: ${(props: { isCanceled: boolean }) =>
props.isCanceled ? buildColor("grey", "600") : buildColor("grey", "900")};
line-height: 18px;
font-weight: 400;
margin-bottom: 4px;
max-width: 150px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
${(props: { isCanceled: boolean }) =>
props.isCanceled &&
css`
text-decoration: line-through;
`}
`;
export const BetTotalWrapper = styled.p`
font-family: ${fontCondensedNormal};
font-size: 12px;
color: ${(props: { isCanceled: boolean }) =>
props.isCanceled ? buildColor("grey", "600") : buildColor("grey", "800")};
line-height: 13px;
font-weight: 400;
text-transform: uppercase;
${(props: { isCanceled: boolean }) =>
props.isCanceled &&
css`
text-decoration: line-through;
`}
`;
export const WillPayWrapper = styled.div`
display: flex;
flex-direction: column;
margin-top: 16px;
`;
export const PayoutWrapper = styled.div`
margin-top: 16px;
`;
export const PayoutButtonWrapper = styled.button`
${IconTextInlineStyles};
background-color: transparent;
outline: none;
border: none;
cursor: pointer;
`;
export const HeaderText = styled(Text)`
font-size: 14px;
font-weight: 400;
line-height: 18px;
font-family: ${fontNormal};
color: ${buildColor("grey", "900")};
`;
export const HeaderTitle = styled(Text)`
color: ${buildColor("grey", "800")};
font-family: ${fontCondensedNormal};
font-size: 12px;
line-height: 16px;
text-transform: uppercase;
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MyBetsDesktopBetDetails/index.tsx
import React, { FC } from "react";
import formatCurrency from "@tvg/formatter/currency";
import type { WagerType } from "@tvg/types/Wager";
import Icon from "@tvg/atomic-ui/_static/Icons";
import { question } from "@tvg/atomic-ui/_static/Icons/iconsDuotone";
import buildColor from "@tvg/atomic-ui/_static/ColorPalette";
import {
TitleWrapper,
BetTotalWrapper,
WillPayWrapper,
PayoutWrapper,
PayoutButtonWrapper,
HeaderText,
HeaderTitle
} from "./styled-components";
type Props = {
wagerAmount: number;
wagerType: typeof WagerType;
betTotal: number;
isCanceled: boolean;
shouldShowPotentialReturn: boolean;
probableValue: string;
onApproxPayout: () => void;
showMinMaxWillPays: boolean;
minWillPays: number;
maxWillPays: number;
};
const MyBetsDesktopBetDetails: FC<Props> = ({
wagerAmount,
wagerType,
betTotal,
isCanceled,
shouldShowPotentialReturn,
probableValue,
onApproxPayout,
showMinMaxWillPays,
minWillPays,
maxWillPays
}) => (
<>
<TitleWrapper data-qa-label="my-bets-payout-title" isCanceled={isCanceled}>
{formatCurrency(wagerAmount)} {wagerType.name}
</TitleWrapper>
<BetTotalWrapper
data-qa-label="my-bets-payout-bet-total"
isCanceled={isCanceled}
>
{formatCurrency(betTotal)} ticket
</BetTotalWrapper>
{!isCanceled && showMinMaxWillPays && (
<WillPayWrapper>
<HeaderText data-qa-label="my-bets-payout-value">
{`${formatCurrency(minWillPays, "USD")} - ${formatCurrency(
maxWillPays,
"USD"
)}`}
</HeaderText>
<HeaderTitle data-qa-label="my-bets-payout-button-text">
Will Pays
</HeaderTitle>
</WillPayWrapper>
)}
{shouldShowPotentialReturn && (
<PayoutWrapper>
<HeaderText data-qa-label="my-bets-payout-value">
{probableValue}
</HeaderText>
<PayoutButtonWrapper
data-qa-label="my-bets-payout-button"
// @ts-ignore
onClick={onApproxPayout}
>
<HeaderTitle data-qa-label="my-bets-payout-button-text">
approx. payout
</HeaderTitle>
<Icon
icon={question}
viewBoxSize={16}
size={14}
color={buildColor("blue_accent", "100")}
stroke={buildColor("blue_accent", "500")}
/>
</PayoutButtonWrapper>
</PayoutWrapper>
)}
</>
);
MyBetsDesktopBetDetails.defaultProps = {
isCanceled: false,
shouldShowPotentialReturn: false,
probableValue: "",
onApproxPayout: () => {}
};
export default MyBetsDesktopBetDetails;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MyBetsMTP/styled-components.js
import styled, { css } from "styled-components";
import buildColor from "../../_static/ColorPalette";
import { fontMedium } from "../../_static/Typography";
export const RaceStatus = styled.div`
display: flex;
font-size: 14px;
${(props) =>
props.device === "desktop"
? css`
flex-direction: column;
& > span {
color: ${buildColor("grey", "800")};
}
`
: css`
margin-bottom: 4px;
`};
time {
line-height: 19px;
${(props) =>
props.device === "desktop" &&
css`
display: inline;
& > span {
white-space: normal;
}
`}
}
`;
export const LegStatus = styled.span`
font-family: ${fontMedium};
font-size: 14px;
line-height: 19px;
margin-right: 4px;
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/MTP/styled-components.js
import styled, { css } from "styled-components";
import { formatPeriod } from "@tvg/formatter/dates";
import { fontNormal, fontMedium } from "../../_static/Typography";
import buildColor from "../../_static/ColorPalette";
const MTPTime = styled.time.attrs((props) => ({
dateTime: props.postTime.toString()
}))`
display: inline-flex;
flex-direction: ${(props) => (props.multipleLine ? "column" : "row")};
align-items: center;
justify-content: center;
min-height: ${(props) =>
!props.paddingless && (props.multipleLine ? "40px" : "32px")};
padding: ${(props) => !props.multipleLine && !props.paddingless && "0 16px"};
min-width: ${(props) => props.multipleLine && "56px"};
height: 100%;
border-radius: ${(props) => props.darken && "2px"};
font-size: 12px;
line-height: ${(props) => (props.bigger ? "16px" : "14px")};
background-color: ${(props) => props.darken && buildColor("black", "30")};
color: ${(props) => props.darken && buildColor("white", "100")};
${(props) =>
props.showRaceDate && "text-align: center; text-transform: uppercase;"};
&::before {
${(props) =>
props.mtp <= props.mtpCloseThreshold &&
!props.isRaceOff &&
"content: '';"};
display: block;
width: 8px;
height: 8px;
margin-right: ${(props) => !props.multipleLine && "4px"};
margin-bottom: ${(props) => props.multipleLine && "4px"};
border-radius: 50%;
background-color: ${buildColor("red", "500")};
}
&::after {
display: inline-block;
content: ${(props) =>
!props.isRaceOff &&
!props.showRaceDate &&
props.mtp > props.mtpThreshold &&
`"${formatPeriod(props.postTime).toString()}"`};
margin-left: ${(props) => !props.multipleLine && "3px"};
}
@media (pointer: coarse) {
line-height: ${(props) => (props.bigger ? "15px" : "13px")};
}
`;
export const RaceClosedStatus = styled.span`
width: 32px;
height: 16px;
display: flex;
font-size: 12px;
align-items: center;
justify-content: center;
border-radius: 1px;
background-color: ${(props) =>
props.status === "RO"
? buildColor("grey", "200")
: buildColor("green", "600")};
color: ${(props) =>
props.status === "RO"
? buildColor("black", "100")
: buildColor("white", "100")};
padding-top: 1px;
font-family: ${fontMedium};
`;
const getMTPStyle = (mtp, isOnBiggestWinner) => {
let mtpStyle = `color: ${
!isOnBiggestWinner ? buildColor("grey", "700") : buildColor("blue", "300")
};
font-family: ${fontNormal}`;
if (mtp <= 5)
mtpStyle = `color: ${buildColor("orange", "600")};
font-family: ${fontMedium};`;
else if (mtp < 60)
mtpStyle = `color: ${
!isOnBiggestWinner ? buildColor("grey", "900") : buildColor("blue", "200")
};
font-family: ${fontMedium}`;
return mtpStyle;
};
const getLegacyMTPStyle = (mtp, isOnBiggestWinner) => {
let mtpStyle = `color: ${
!isOnBiggestWinner ? buildColor("grey", "800") : buildColor("blue", "300")
};
font-family: ${fontNormal};`;
if (mtp <= 10) {
mtpStyle = `color: ${buildColor("red", "600")};
font-family: ${fontMedium};`;
} else if (mtp < 60) {
mtpStyle = `color: ${
!isOnBiggestWinner ? buildColor("grey", "900") : buildColor("blue", "200")
};
font-family: ${fontMedium};`;
}
return mtpStyle;
};
export const PlainMTP = styled.time.attrs((props) => ({
dateTime: props.postTime
}))`
display: ${(props) => (props.isMyBets ? "flex" : "inline")};
height: ${(props) => (props.isMyBets ? "auto" : "16px")};
font-size: 14px;
${({ mtp, isOnBiggestWinner, isMTPNewRules }) => {
const returnCSS = isMTPNewRules
? getMTPStyle(mtp, isOnBiggestWinner)
: getLegacyMTPStyle(mtp, isOnBiggestWinner);
return returnCSS;
}}
`;
export const PlainMTPText = styled.span`
display: block;
font-family: ${({ isRaceOff, isMyBets }) =>
isRaceOff || isMyBets ? fontMedium : fontNormal};
font-size: 14px;
font-weight: 400;
letter-spacing: 0;
${(props) => {
if (props.isRaceOff) {
return css`
color: ${buildColor("green", "600")};
`;
}
if (props.isResulted) {
return css`
color: ${buildColor("grey", "700")};
`;
}
return css`
color: ${buildColor("grey", "800")};
`;
}}
white-space: pre;
`;
export default MTPTime;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/MTP/index.jsx
import React, { PureComponent } from "react";
import {
formatPostTime,
formatPeriod,
formatRaceDate
} from "@tvg/formatter/dates";
import MTPTime, {
RaceClosedStatus,
PlainMTP,
PlainMTPText
} from "./styled-components";
/*
* Be careful with this flag!!!
* TODO: This shall be refactored later
* */
export const isRaceOff = (status) => status === "SK" || status === "RO";
export default class MTP extends PureComponent {
static defaultProps = {
mtp: 0,
postTime: new Date().toISOString(),
status: "O",
multipleLine: false,
darken: false,
bigger: false,
paddingless: false,
showRaceDate: false,
isHighlightedBellowThreshold: false,
className: "",
isPlainMTP: false,
isOnBiggestWinner: false,
isMyBets: false,
dateDiff: 0,
isMTPNewRules: false
};
mtpThreshold = 60;
mtpCloseThreshold = 10;
renderMTP() {
if (!isRaceOff(this.props.status)) {
if (this.props.mtp > this.mtpThreshold) {
return formatPostTime(this.props.postTime, this.props.showRaceDate);
}
return `${this.props.mtp.toString()}m`;
}
return (
<RaceClosedStatus status={this.props.status}>
{this.props.status === "RO" ? "RES" : "OFF"}
</RaceClosedStatus>
);
}
renderPlainMtp = () => {
switch (this.props.status) {
case "SK":
return (
<PlainMTPText data-qa-label="mtpRaceOff" isRaceOff>
Race off
</PlainMTPText>
);
case "RO":
return (
<PlainMTPText
data-qa-label="mtpResult"
isMyBets={this.props.isMyBets}
isResulted
>
{this.props.isMyBets ? "Resulted" : "Result"}
</PlainMTPText>
);
default: {
const mtpSuffix = this.props.isMyBets ? " MTP" : "m";
return this.props.mtp > 60
? `${formatPostTime(this.props.postTime, false)} ${formatPeriod(
this.props.postTime
)}`
: `${this.props.mtp}${mtpSuffix}`;
}
}
};
renderRaceDate = () => (
<PlainMTPText>{` - ${formatRaceDate(this.props.postTime)}`}</PlainMTPText>
);
render() {
return this.props.isPlainMTP ? (
<PlainMTP
className={this.props.className}
data-qa-label="mtp"
postTime={this.props.postTime}
mtp={this.props.mtp}
isOnBiggestWinner={this.props.isOnBiggestWinner}
isMyBets={this.props.isMyBets}
isMTPNewRules={this.props.isMTPNewRules}
>
{this.renderPlainMtp()}
{this.props.dateDiff < 0 && this.renderRaceDate()}
</PlainMTP>
) : (
<MTPTime
data-qa-label="mtp"
className={this.props.className}
postTime={this.props.postTime}
mtp={this.props.mtp}
mtpCloseThreshold={this.mtpCloseThreshold}
mtpThreshold={this.mtpThreshold}
isRaceOff={isRaceOff(this.props.status)}
multipleLine={this.props.multipleLine}
darken={this.props.darken}
bigger={this.props.bigger}
paddingless={this.props.paddingless}
showRaceDate={this.props.showRaceDate}
>
{this.renderMTP()}
</MTPTime>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MyBetsMTP/index.jsx
import React from "react";
import { formatPeriod, formatPostTime, formatRaceDate } from "@tvg/formatter";
import { LegStatus, RaceStatus } from "./styled-components";
import { PlainMTPText } from "../../_atom/MTP/styled-components";
import MTP from "../../_atom/MTP";
const MyBetsMTP = (props) => {
const {
qaLabel,
showRaceLeg,
legNumber,
isFutureBet,
raceDate,
currentDate,
raceMtp,
racePostTime,
raceStatusCode,
raceDateDiff,
isMTPNewRules,
device
} = props;
return (
<RaceStatus data-qa-label={`${qaLabel}-wrapper`} device={device}>
{showRaceLeg && legNumber > 0 && (
<LegStatus data-qa-label={`${qaLabel}-leg-status`}>{`Leg ${legNumber} ${
device === "desktop" ? "" : "-"
}`}</LegStatus>
)}
{isFutureBet && raceDate && raceDate !== currentDate ? (
<PlainMTPText data-qa-label={qaLabel}>
{`${formatPostTime(racePostTime)} `}
{formatPeriod(racePostTime)} - {formatRaceDate(raceDate)}
</PlainMTPText>
) : (
<MTP
mtp={raceMtp}
postTime={racePostTime}
status={raceStatusCode}
dateDiff={raceDateDiff}
isPlainMTP
isMyBets
isMTPNewRules={isMTPNewRules}
/>
)}
</RaceStatus>
);
};
MyBetsMTP.defaultProps = {
qaLabel: "mybets-mtp",
showRaceLeg: false,
legNumber: 1,
isFutureBet: false,
raceDate: "",
currentDate: "",
raceMtp: 60,
racePostTime: "",
raceStatusCode: "O",
raceDateDiff: "",
isMTPNewRules: true,
device: "mobile"
};
export default MyBetsMTP;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MyBetsDesktopStatus/styled-components.ts
import styled from "styled-components";
import buildColor from "@tvg/atomic-ui/_static/ColorPalette";
import { fontNormal } from "@tvg/atomic-ui/_static/Typography";
export const StatusWrapper = styled.div`
display: flex;
flex-direction: column;
svg + p {
margin-top: 5px;
}
`;
export const StatusText = styled.p`
font-family: ${fontNormal};
font-size: 14px;
line-height: 17px;
font-weight: 500;
color: ${buildColor("grey", "700")};
&.canceled,
&.loser,
&.winner,
&.refunded {
font-size: 12px;
}
&.canceled,
&.loser {
color: ${buildColor("grey", "800")};
}
&.winner,
&.refunded {
color: ${buildColor("grey", "900")};
}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MyBetsDesktopStatus/index.tsx
import React from "react";
import { formatPastRaceDate } from "@tvg/formatter/dates";
import buildColor from "@tvg/atomic-ui/_static/ColorPalette";
import Icon from "@tvg/atomic-ui/_static/Icons";
import {
info,
betCanceled,
successRound
} from "@tvg/atomic-ui/_static/Icons/iconsDuotone";
import MyBetsMTP from "@tvg/atomic-ui/_molecule/MyBetsMTP";
import { StatusWrapper, StatusText } from "./styled-components";
import type { Props } from "./types";
const MyBetsDesktopStatus = ({
mtp,
raceStatusCode,
legStatusCode,
legNumber,
showRaceLeg = false,
selectedTab,
isMTPNewRules = false,
statusName,
raceDate,
racePostTime,
dateDiff,
qaLabel = ""
}: Props) => {
switch (statusName) {
case "active":
return (
<MyBetsMTP
device="desktop"
showRaceLeg={!!showRaceLeg}
legNumber={legNumber}
isFutureBet={selectedTab === "FUTURES"}
raceDate={raceDate}
currentDate={formatPastRaceDate(new Date())}
raceMtp={mtp}
racePostTime={racePostTime}
raceStatusCode={legStatusCode || raceStatusCode}
raceDateDiff={dateDiff}
isMTPNewRules={isMTPNewRules}
/>
);
case "canceled":
return (
<StatusWrapper data-qa-label={`${qaLabel}-status-wrapper`}>
<Icon
qaLabel={`${qaLabel}-status-icon`}
icon={betCanceled}
viewBoxSize={16}
size={16}
color={buildColor("white", "10")}
stroke={buildColor("grey", "800")}
/>
<StatusText
className="canceled"
data-qa-label={`${qaLabel}-status-text`}
>
Cancelled
</StatusText>
</StatusWrapper>
);
case "loser":
return (
<StatusWrapper data-qa-label={`${qaLabel}-status-wrapper`}>
<Icon
qaLabel={`${qaLabel}-status-icon`}
icon={betCanceled}
viewBoxSize={16}
size={16}
color={buildColor("white", "10")}
stroke={buildColor("grey", "800")}
/>
<StatusText
className="loser"
data-qa-label={`${qaLabel}-status-text`}
>
Lost
</StatusText>
</StatusWrapper>
);
case "winner":
return (
<StatusWrapper data-qa-label={`${qaLabel}-status-wrapper`}>
<Icon
qaLabel={`${qaLabel}-status-icon`}
icon={successRound}
viewBoxSize={16}
size={16}
color={buildColor("green", "100")}
stroke={buildColor("green", "600")}
/>
<StatusText
className="winner"
data-qa-label={`${qaLabel}-status-text`}
>
Won
</StatusText>
</StatusWrapper>
);
case "refunded":
return (
<StatusWrapper data-qa-label={`${qaLabel}-status-wrapper`}>
<Icon
qaLabel={`${qaLabel}-status-icon`}
icon={info}
viewBoxSize={16}
size={16}
color={buildColor("blue_accent", "200")}
stroke={buildColor("blue_accent", "600")}
/>
<StatusText
className="refunded"
data-qa-label={`${qaLabel}-status-text`}
>
Refunded
</StatusText>
</StatusWrapper>
);
default:
return (
<StatusWrapper data-qa-label={`${qaLabel}-status-wrapper`}>
<StatusText data-qa-label={`${qaLabel}-status-text`}>
Resolved
</StatusText>
</StatusWrapper>
);
}
};
export default MyBetsDesktopStatus;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/WonIllustration/Illustrations.jsx
import React from "react";
import buildColor from "../../_static/ColorPalette";
export const TVGLogo = () => (
<svg
width="41"
height="11"
viewBox="0 0 41 11"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M33.231 2.86552C31.3785 2.86552 30.0099 3.60725 29.5156 5.49764C29.0647 7.22552 29.9538 8.13688 32.2088 8.13688C33.6917 8.13688 34.5571 7.66807 35.0635 6.96462H33.1912L33.745 4.84272H40.2183L38.8233 10.1849H36.8699L36.5799 9.31893C35.1786 10.1733 33.607 10.501 30.9953 10.501C27.8055 10.501 23.6249 9.85764 24.7533 5.53726C24.9428 4.81245 25.235 4.18737 25.6043 3.64776L20.2934 10.1849H15.5163L13.4845 3.18296H9.51629L7.68791 10.1849H3.13712L4.96506 3.18296H0.515991L1.13307 0.818416H12.798V0.817525H17.8009L18.7658 6.82616H18.798L22.9007 0.817525H24.8362L24.8357 0.816635H30.3491C31.4295 0.587348 32.5467 0.500977 33.5904 0.500977C38.6557 0.500977 40.7659 1.63094 40.4926 4.03777H35.3597C35.357 3.55293 35.0971 3.25197 34.7197 3.08724C34.3285 2.91761 33.8262 2.86552 33.231 2.86552Z"
fill={buildColor("green", "700")}
/>
</svg>
);
export const Laurel = ({ direction }) =>
direction === "left" ? (
<svg
width="20"
height="33"
viewBox="0 0 20 33"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M7.47955 0.617188C0.730745 2.59239 4.74955 8.75319 4.74955 8.75319C4.74955 8.75319 9.52555 7.14159 7.47955 0.617188ZM6.79195 16.7296V16.7272C6.98995 16.6408 11.7071 14.5432 10.0943 9.39399C10.0943 9.39399 5.22355 9.72999 6.15835 14.7988C5.34115 12.9232 3.57835 10.2796 0.016745 9.71079C-0.391255 19.72 6.79195 16.7296 6.79195 16.7296ZM12.2771 15.9856C15.5219 21.0376 11.2043 24.3376 11.1191 24.4012C11.0159 24.4864 5.01115 29.368 2.31235 19.7404C5.63275 19.2868 8.07475 20.9464 9.53515 22.408C7.46755 17.59 12.2771 15.9856 12.2771 15.9856ZM16.4603 21.3244C16.4603 21.3244 12.4691 24.4864 16.2719 28.3492C14.1839 27.6292 10.9463 27.106 7.99075 29.1352C15.2903 36.8344 18.4859 29.3632 18.4859 29.3632L18.4847 29.3608C19.1423 27.9784 20.3723 24.2656 16.4603 21.3244Z"
fill={buildColor("green", "500")}
/>
</svg>
) : (
<svg
width="20"
height="33"
viewBox="0 0 20 33"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M11.9523 0.617188C18.7011 2.59239 14.6811 8.75319 14.6811 8.75319C14.6811 8.75319 9.90629 7.14159 11.9523 0.617188ZM12.6387 16.7296L12.6399 16.7272C12.4419 16.6408 7.72469 14.5432 9.33749 9.39399C9.33749 9.39399 14.2071 9.72999 13.2723 14.7988C14.0895 12.9232 15.8523 10.2796 19.4151 9.71079C19.8231 19.72 12.6387 16.7296 12.6387 16.7296ZM7.15349 15.9844C3.90869 21.0376 8.22749 24.3364 8.31149 24.4012C8.41589 24.4864 14.4207 29.368 17.1183 19.7404C13.7991 19.2868 11.3571 20.9464 9.89669 22.408C11.9631 17.59 7.15349 15.9844 7.15349 15.9844ZM2.97029 21.3244C2.97029 21.3244 6.96269 24.4864 3.15989 28.348C5.24789 27.628 8.48429 27.106 11.4411 29.1352C4.14149 36.8344 0.94469 29.3632 0.94469 29.3632L0.947089 29.3608C0.288289 27.9784 -0.940515 24.2656 2.97029 21.3244Z"
fill={buildColor("green", "500")}
/>
</svg>
);
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/WonIllustration/styled-components.js
import styled, { css } from "styled-components";
import { fontBold, fontNormal } from "../../_static/Typography";
import buildColor from "../../_static/ColorPalette";
export const Container = styled.div`
${({ hideLogo }) =>
!hideLogo &&
css`
min-width: 140px;
`}
position: relative;
display: flex;
align-items: flex-end;
z-index: 2;
justify-content: flex-end;
`;
export const TextContainer = styled.div`
display: flex;
flex-direction: column;
align-items: center;
margin: 0 4px;
${({ shouldWrap }) =>
shouldWrap &&
css`
max-width: min-content;
`};
`;
export const WinAmountContainer = styled.div`
background-color: ${buildColor("green", "600")};
transform: skew(-15deg);
padding: 0 4px;
text-align: center;
${({ shouldWrap }) =>
!shouldWrap &&
css`
min-width: 90px;
`};
`;
export const WinAmountValue = styled.span`
display: inline-flex;
font-family: ${fontBold};
font-size: 14px;
transform: skew(15deg);
color: ${buildColor("white", "100")};
`;
export const WinAmountDescriptionWrapper = styled.div`
display: flex;
margin-top: 2px;
align-items: center;
`;
export const WinAmountDescription = styled.span`
font-family: ${fontNormal};
font-size: 12px;
font-style: normal;
font-weight: 700;
color: ${buildColor("green", "700")};
text-transform: uppercase;
text-align: center;
margin-right: 2px;
${({ hideLogo }) =>
!hideLogo &&
css`
padding-top: 1px;
`}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/WonIllustration/index.jsx
import React from "react";
import formatCurrency from "@tvg/formatter/currency";
import { TVGLogo, Laurel } from "./Illustrations";
import {
Container,
TextContainer,
WinAmountContainer,
WinAmountValue,
WinAmountDescription,
WinAmountDescriptionWrapper
} from "./styled-components";
const MAX_VALUE_FOR_WRAPPING = 1000;
const WonIllustration = (props) => {
const { qaLabel, winAmount, hideLogo } = props;
const description = hideLogo ? "Won on fanduel" : "Won on";
const shouldWrap = hideLogo && winAmount < MAX_VALUE_FOR_WRAPPING;
return (
<Container data-qa-label={qaLabel} hideLogo={hideLogo}>
<Laurel direction="left" data-qa-label={`${qaLabel}-laurel-left`} />
<TextContainer shouldWrap={shouldWrap}>
<WinAmountContainer
data-qa-label={`${qaLabel}-amount-container`}
shouldWrap={shouldWrap}
>
<WinAmountValue data-qa-label={`${qaLabel}-amount`}>
{formatCurrency(winAmount || 0)}
</WinAmountValue>
</WinAmountContainer>
<WinAmountDescriptionWrapper data-qa-label={`${qaLabel}-description`}>
<WinAmountDescription hideLogo={hideLogo}>
{description}
</WinAmountDescription>
{!hideLogo && <TVGLogo />}
</WinAmountDescriptionWrapper>
</TextContainer>
<Laurel direction="right" data-qa-label={`${qaLabel}-laurel-right`} />
</Container>
);
};
WonIllustration.defaultProps = {
winAmount: 0,
qaLabel: "wonIllustration",
hideLogo: false
};
export default WonIllustration;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/WagerSettledStatus/styled-components.ts
import styled from "styled-components";
import buildColor from "@tvg/atomic-ui/_static/ColorPalette";
import {
fontMedium,
fontCondensedNormal
} from "@tvg/atomic-ui/_static/Typography";
export const Container = styled.div<{
device?: "mobile" | "tablet" | "desktop";
}>`
> div {
justify-content: center;
& + span {
margin-top: ${(props) => (props.device === "desktop" ? "12px" : "4px")};
}
}
`;
export const TextWrapper = styled.span`
display: flex;
align-items: center;
justify-content: center;
text-transform: uppercase;
font-weight: 400;
font-size: 12px;
line-height: 14px;
font-family: ${fontCondensedNormal};
color: ${buildColor("grey", "800")};
& + span {
margin-top: 4px;
}
`;
export const AmountValue = styled.strong`
font-weight: 500;
font-size: 14px;
line-height: 19px;
margin-right: 4px;
font-family: ${fontMedium};
color: ${buildColor("grey", "900")};
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/WagerSettledStatus/index.tsx
import React from "react";
import formatCurrency from "@tvg/formatter/currency";
import WonIllustration from "@tvg/atomic-ui/_atom/WonIllustration";
import { isFDR } from "@tvg/utils/generalUtils";
import { Container, TextWrapper, AmountValue } from "./styled-components";
import type { Props } from "./types";
const renderRefundStatus = (betRefund: number, qaLabel: string) => (
<TextWrapper data-qa-label={`${qaLabel}-text`}>
<AmountValue>+{formatCurrency(betRefund || 0)}</AmountValue> refund
</TextWrapper>
);
const isFdrBrand = isFDR();
const WagerSettledStatus = ({
statusName,
winningsAmount,
betRefund,
betAmount,
device = "mobile",
qaLabel = "wager-settled-status"
}: Props) => {
switch (statusName) {
case "winner":
return (
<Container data-qa-label={qaLabel} device={device}>
{winningsAmount > betAmount ? (
<WonIllustration winAmount={winningsAmount} hideLogo={isFdrBrand} />
) : (
<TextWrapper data-qa-label={`${qaLabel}-text`}>
<AmountValue>{formatCurrency(winningsAmount || 0)}</AmountValue>{" "}
return
</TextWrapper>
)}
{betRefund > 0 && renderRefundStatus(betRefund, qaLabel)}
</Container>
);
case "loser":
return (
<Container data-qa-label={qaLabel}>
<TextWrapper data-qa-label={`${qaLabel}-text`}>
<AmountValue>{formatCurrency(0)}</AmountValue> return
</TextWrapper>
{betRefund > 0 && renderRefundStatus(betRefund, qaLabel)}
</Container>
);
case "refunded":
return (
<Container data-qa-label={qaLabel}>
{renderRefundStatus(betRefund, qaLabel)}
</Container>
);
default:
return null;
}
};
export default WagerSettledStatus;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/PickBetRebet/styled-components.js
import styled, { css } from "styled-components";
import { Link } from "react-router-dom";
import buildColor from "../../_static/ColorPalette";
export const PickBetsContainer = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
padding: 8px 12px;
background-color: ${buildColor("white", "100")};
border-top: 1px solid ${buildColor("blue", "100")};
${({ hasRoundBottomBorder }) =>
hasRoundBottomBorder &&
css`
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
`}
${({ bigLayout }) =>
bigLayout &&
css`
flex-direction: column;
border-top: 0;
background: #e9eff5;
border-radius: 4px;
`}
`;
export const PickBetsTextWrapper = styled.div`
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: ${({ bigLayout }) =>
bigLayout ? "center" : "space-between"};
`;
export const PickBetsLinkContainer = styled(Link)`
display: flex;
flex-direction: row;
flex-shrink: 0;
text-decoration: none;
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/PickBetRebet/index.jsx
import React, { Fragment } from "react";
import { first, noop } from "lodash";
import { TVGThemeProvider, Paragraph } from "@tvg/design-system";
import { Button } from "@tvg/design-system/web";
import {
PickBetsContainer,
PickBetsTextWrapper,
PickBetsLinkContainer
} from "./styled-components";
const PickBetRebet = ({
raceUrl,
handleRebetClickEvent,
rebetWagerTypeName,
rebetSearch,
isContentDisplayed,
bigLayout,
isTVG4
}) => {
const PickBetWrapper = isTVG4 ? Fragment : PickBetsLinkContainer;
return (
<TVGThemeProvider>
<PickBetsContainer
bigLayout={bigLayout}
hasRoundBottomBorder={!isContentDisplayed}
>
<PickBetsTextWrapper bigLayout={bigLayout}>
<Paragraph
fontFamily="medium"
color="blue_accent.800"
qaLabel="pick-bets-rebet-title"
>{`${rebetWagerTypeName} Available`}</Paragraph>
<Paragraph
qaLabel="pick-bets-rebet-description"
fontSize="xs"
marginBottom={bigLayout ? "space-4" : ""}
>
Bet using your remaining selections
</Paragraph>
</PickBetsTextWrapper>
<PickBetWrapper
data-qa-label="myBets-pickbets-link"
to={{
pathname: raceUrl && first(raceUrl.split("?")),
search: rebetSearch,
state: {
openVideo: false
}
}}
>
<Button
variant="betting"
iconPosition="end"
icon="arrowRight"
onClick={handleRebetClickEvent}
qaLabel="button"
size="m"
isStretched
>
Create Bet
</Button>
</PickBetWrapper>
</PickBetsContainer>
</TVGThemeProvider>
);
};
PickBetRebet.defaultProps = {
raceUrl: "",
handleRebetClickEvent: noop,
rebetWagerTypeName: "",
rebetSearch: "",
isContentDisplayed: true,
bigLayout: false,
isTVG4: false
};
export default React.memo(PickBetRebet);
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/WagerActionButtons/styled-components.ts
import styled from "styled-components";
import ButtonDefault from "@tvg/atomic-ui/_atom/Buttons/default";
import buildColor from "@tvg/atomic-ui/_static/ColorPalette";
import { fontNormal } from "@tvg/atomic-ui/_static/Typography";
export const ActionsWrapper = styled.div`
display: flex;
flex-direction: column;
`;
export const ContentRow = styled.div`
display: flex;
align-items: center;
justify-content: flex-end;
`;
export const IconButton = styled(ButtonDefault)`
display: flex;
flex-direction: column;
align-items: center;
width: 40px;
font-family: ${fontNormal};
font-size: 12px;
font-weight: 500;
line-height: 17px;
svg {
padding: 10px;
border-radius: 50%;
}
&:hover svg,
&:focus svg {
background-color: ${(props: { isCancelButton?: boolean }) =>
props.isCancelButton
? buildColor("red", "100")
: buildColor("grey", "100")};
}
&:active svg {
background-color: ${(props: { isCancelButton?: boolean }) =>
props.isCancelButton
? buildColor("red", "200")
: buildColor("grey", "200")};
}
`;
export const DeleteButtonWrapper = styled.div`
&:active {
svg {
path {
fill: transparent;
}
}
}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/WagerActionButtons/index.tsx
import React, { FC } from "react";
import { noop } from "lodash";
import PickBetRebet from "@tvg/atomic-ui/_molecule/PickBetRebet";
import { Icon } from "@tvg/design-system";
import { Button } from "@tvg/design-system/web";
import { Props } from "./types";
import { ActionsWrapper, DeleteButtonWrapper } from "./styled-components";
const WagerActionButtons: FC<Props> = ({
isWagerCancelable = false,
onCancelWager = noop,
shouldShowRebet = false,
handleRebetClickEvent = noop,
onRepeatBets = noop,
showRepeatButton = false,
rebetWagerTypeName = "",
isBetActive = true
}) => (
<ActionsWrapper>
{showRepeatButton && (
<Button
qaLabel="myBets-betTicked-repeat-bet"
variant="secondary"
size="m"
iconPosition="start"
icon="repeat"
isStretched
mb="space-3"
onClick={onRepeatBets}
>
{isBetActive ? "Repeat" : "Re-Bet"}
</Button>
)}
{shouldShowRebet && (
<PickBetRebet
handleRebetClickEvent={handleRebetClickEvent}
isTVG4
bigLayout
rebetWagerTypeName={rebetWagerTypeName}
/>
)}
{isWagerCancelable && (
<DeleteButtonWrapper>
<Button
qaLabel="myBets-betTicked-cancelButton"
onClick={onCancelWager}
variant="tertiaryDestructive"
size="m"
isStretched
mb="space-3"
iconPosition="start"
icon={<Icon name="trash" size="s" />}
>
Cancel
</Button>
</DeleteButtonWrapper>
)}
</ActionsWrapper>
);
export default WagerActionButtons;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/WagerVideoActions/index.tsx
import React from "react";
import { Icon } from "@tvg/design-system";
import { Button } from "@tvg/design-system/web";
import type { Props } from "./types";
const WagerVideoActions = ({
hasLiveVideo,
onLiveVideo,
mtp,
isMultiRace,
hasPastPerformance,
onWatchReplay,
showSeeResult,
currentRaceNumber
}: Props) => (
<>
{hasLiveVideo && (
<Button
qaLabel="myBets-watchLive"
onClick={onLiveVideo}
size="m"
iconPosition="start"
isStretched
icon={
<Icon
name="video"
size="s"
lineColor={mtp <= 5 ? "white.900" : "blue_accent.500"}
/>
}
mb="space-3"
{...{ variant: mtp <= 5 ? "primary" : "secondary" }}
>
{`Watch ${!isMultiRace ? "Live" : "R" + currentRaceNumber}`}
</Button>
)}
{hasPastPerformance && (
<Button
qaLabel="myBets-watchReplay"
onClick={onWatchReplay}
variant="primary"
size="m"
iconPosition="start"
icon="replay"
mb="space-3"
isStretched
>
Watch Replay
</Button>
)}
{showSeeResult && (
<Button
qaLabel="myBets-seeResults"
onClick={onWatchReplay}
variant="secondary"
size="m"
mb="space-3"
isStretched
>
See Results
</Button>
)}
</>
);
export default WagerVideoActions;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Popper/styled-components.ts
import styled, { css } from "styled-components";
import type { CSSProperties } from "react";
import type {
ContentLayoutProps,
Placement,
TriggerLayoutProps
} from "./types";
const calculatePlacement = (
placement: Placement,
triggerLayout: TriggerLayoutProps,
contentLayout: ContentLayoutProps,
isLeftSideRendered?: boolean
): CSSProperties => {
const {
x: triggerX,
y: triggerY,
width: triggerWidth,
height: triggerHeight
} = triggerLayout;
const { width: contentWidth, height: contentHeight } = contentLayout;
const viewportWidth = window.innerWidth; // using window.screen.width will not work for wagerpad
const viewportHeight = window.screen.height; // using window.innerHeight will not work for elements rendered outside the viewport
const placementMap: Record<Placement, { top: number; left: number }> = {
"top-left": {
top: triggerY - contentHeight,
left: triggerX
},
"top-right": {
top: triggerY - contentHeight,
left: triggerX + triggerWidth - contentWidth
},
"top-mid": {
top: triggerY - contentHeight,
left: triggerX + triggerWidth / 2 - contentWidth / 2
},
"bottom-left": {
top: triggerY + triggerHeight,
left: triggerX
},
"bottom-right": {
top: triggerY + triggerHeight,
left: triggerX + triggerWidth - contentWidth
},
"bottom-mid": {
top: triggerY + triggerHeight,
left: triggerX + triggerWidth / 2 - contentWidth / 2
},
left: {
top: triggerY + triggerHeight / 2 - contentHeight / 2,
left: triggerX - contentWidth
},
right: {
top: triggerY + triggerHeight / 2 - contentHeight / 2,
left: triggerX + triggerWidth
},
"drop-down": {
top: triggerY + triggerHeight,
left: triggerX
}
};
const result = placementMap[placement as keyof typeof placementMap];
let { left, top } = result;
if (left + contentWidth > viewportWidth) {
left = viewportWidth - contentWidth - 10;
}
if (top + contentHeight > viewportHeight) {
top = viewportHeight - contentHeight - 10;
}
if (isLeftSideRendered && left < 0) {
left = 5;
}
return { top: `${top}px`, left: `${left}px` };
};
const calculateLeftPlacement = (placement: Placement) => {
switch (placement) {
case "top-mid":
case "bottom-mid":
return css`
left: 45%;
`;
case "top-left":
case "bottom-left":
return css`
left: 5%;
`;
default:
return css`
left: 88%;
`;
}
};
const calculateBorderPlacement = (placement: Placement) => {
switch (placement) {
case "top-left":
case "top-mid":
case "top-right":
return css`
border-top: 10px solid var(--fd-colors-background-layer);
bottom: 5px;
`;
default:
return css`
border-bottom: 10px solid var(--fd-colors-background-layer);
top: 5px;
`;
}
};
export const PopperContainer = styled.div`
cursor: default;
`;
export const PopperContent = styled.div.attrs<{
placement: Placement;
triggerLayout: TriggerLayoutProps;
contentLayout: ContentLayoutProps;
isVisible: boolean;
isLeftSideRendered?: boolean;
layer: number;
}>(
({ placement, triggerLayout, contentLayout, layer, isLeftSideRendered }) => ({
style: {
position: "absolute",
zIndex: layer || 1999,
left: 0,
top: 0,
...calculatePlacement(
placement,
triggerLayout,
contentLayout,
isLeftSideRendered
)
}
})
)<{
placement: Placement;
triggerLayout: TriggerLayoutProps;
contentLayout: ContentLayoutProps;
isVisible: boolean;
layer: number;
isLeftSideRendered?: boolean;
showCaret: boolean;
}>`
z-index: ${({ layer }) => layer || 1999};
background-color: transparent;
border-radius: 4px;
opacity: ${({ isVisible }) => (isVisible ? 1 : 0)};
pointer-events: ${({ showCaret, isVisible }) =>
isVisible && showCaret ? "auto" : "none"};
transform: ${({ isVisible }) =>
isVisible
? "scale(1) translateY(0) translateX(0)"
: "scale(0.95) translateY(16px) translateX(-12px)"};
transition:
opacity 200ms ease-in-out,
transform 200ms cubic-bezier(0.2, 0.8, 0.8, 1);
&[data-hidden="true"] {
visibility: hidden;
opacity: 0;
}
${({ placement, showCaret }) => {
const left = calculateLeftPlacement(placement);
const border = calculateBorderPlacement(placement);
return (
showCaret &&
css`
& ::before {
content: "";
position: absolute;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
${left};
${border};
}
`
);
}};
`;
export const Trigger = styled.div`
background: none;
border: none;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Popper/index.tsx
import React, { useEffect, useLayoutEffect, useRef, useState } from "react";
import { noop } from "lodash";
import { PopperContainer, PopperContent, Trigger } from "./styled-components";
import type { PopperProps } from "./types";
import useOnClickOutside from "../../hooks/useOnClickOutside";
export const Popper: React.FC<PopperProps> = ({
placement = "top-right",
on = "hover",
isOpen = false,
isDisabled = true,
content,
layer = 1999,
isLeftSideRendered = false,
showCaret = false,
children,
forceClose = false,
closeDelay,
onClickOuside = noop
}) => {
const [isVisible, setIsVisible] = useState(isOpen);
const triggerRef = useRef<HTMLDivElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const [triggerLayout, setTriggerLayout] = useState<{
x: number;
y: number;
width: number;
height: number;
} | null>(null);
const [contentLayout, setContentLayout] = useState<{
width: number;
height: number;
}>({
width: 0,
height: 0
});
useOnClickOutside(
contentRef,
() => {
if (on === "click") {
setIsVisible(false);
onClickOuside();
}
},
triggerRef
);
const measureTriggerLayout = () => {
if (!triggerRef.current) return;
const rect = triggerRef.current.getBoundingClientRect();
const containerRect =
triggerRef.current.offsetParent?.getBoundingClientRect();
const offsetX = containerRect?.left || 0;
const offsetY = containerRect?.top || 0;
setTriggerLayout({
x: rect.left - offsetX,
y: rect.top - offsetY,
width: rect.width,
height: rect.height
});
};
const measureContentLayout = () => {
if (!contentRef.current) return;
const rect = contentRef.current.getBoundingClientRect();
setContentLayout({
width: rect.width,
height: rect.height
});
};
useLayoutEffect(() => {
measureTriggerLayout();
measureContentLayout();
}, [isVisible]);
const handleMouseEnter = () => {
if (on === "hover" && !isDisabled) {
setIsVisible(true);
}
};
const handleMouseLeave = () => {
if (on === "hover" && !isDisabled) {
setIsVisible(false);
}
};
const handleClick = () => {
if (on === "click" && !isDisabled) {
setIsVisible((prev) => !prev);
}
};
useLayoutEffect(() => {
const handlePosition = () => {
measureTriggerLayout();
measureContentLayout();
};
window.addEventListener("scroll", handlePosition, true);
window.addEventListener("resize", handlePosition, true);
return () => {
window.removeEventListener("scroll", handlePosition, true);
window.removeEventListener("resize", handlePosition, true);
};
}, [isVisible]);
useEffect(() => {
setIsVisible(isOpen);
}, [isOpen]);
useEffect(() => {
const timer = setTimeout(() => {
contentRef.current?.removeAttribute("data-hidden");
}, 300);
return () => clearTimeout(timer);
}, []);
useEffect(() => {
if (forceClose) {
setIsVisible(false);
}
}, [forceClose]);
useEffect(() => {
if (closeDelay && isVisible) {
const timer = setTimeout(() => {
setIsVisible(false);
}, closeDelay);
return () => clearTimeout(timer);
}
return undefined;
}, [closeDelay, isVisible]);
return (
<PopperContainer ref={containerRef}>
<Trigger
ref={triggerRef}
onClick={handleClick}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
data-qa-label="popper-trigger"
>
{children}
</Trigger>
{triggerLayout && (
<PopperContent
ref={contentRef}
placement={placement}
triggerLayout={triggerLayout}
contentLayout={contentLayout}
isVisible={isVisible}
layer={layer}
isLeftSideRendered={isLeftSideRendered}
showCaret={showCaret}
data-hidden="true"
>
{content}
</PopperContent>
)}
</PopperContainer>
);
};
export type { PopperProps };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/hooks/useOnClickOutside/index.ts
import { type RefObject, useEffect } from "react";
const useOnClickOutside = (
ref: RefObject<HTMLElement>,
handler: (event: MouseEvent | TouchEvent) => void,
excludeRef?: RefObject<HTMLElement>
) => {
useEffect(() => {
const listener = (event: MouseEvent | TouchEvent) => {
if (!ref.current || ref.current.contains(event.target as Node)) {
return;
}
if (excludeRef?.current?.contains(event.target as Node)) {
return;
}
handler(event);
};
document.addEventListener("mousedown", listener);
document.addEventListener("touchstart", listener as EventListener);
return () => {
document.removeEventListener("mousedown", listener);
document.removeEventListener("touchstart", listener);
};
}, [ref, handler, excludeRef]);
};
export default useOnClickOutside;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/TooltipDescriptive/styled-components.ts
import styled from "styled-components";
import {
color,
background,
space,
borderRadius,
width,
compose,
variant
} from "../../../src/theming/styledSystem";
import type { TooltipDescriptiveWrapperProps } from "./types";
const OFFSET_SPACE: string = "12px";
const styles = compose(
color,
background,
space,
borderRadius,
width,
variant({
prop: "placement",
variants: {
left: { marginRight: OFFSET_SPACE },
right: { marginLeft: OFFSET_SPACE },
"top-mid": { marginBottom: OFFSET_SPACE },
"top-left": { marginBottom: OFFSET_SPACE },
"top-right": { marginBottom: OFFSET_SPACE },
"bottom-mid": { marginTop: OFFSET_SPACE },
"bottom-left": { marginTop: OFFSET_SPACE },
"bottom-right": { marginTop: OFFSET_SPACE }
}
})
);
export const Wrapper = styled.div<TooltipDescriptiveWrapperProps>`
box-shadow: 0 2px 4px 0 rgba(10 10 10 / 10%);
margin: 4px;
border-radius: 4px;
${styles};
@media screen and (width <= 360px) {
margin-right: 48px;
}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/TooltipDescriptive/content.tsx
import React, { cloneElement, isValidElement, FC } from "react";
import type { TooltipDescriptiveContent } from "./types";
import { Header, Paragraph } from "../Typography";
import { Wrapper as StyledWrapper } from "./styled-components";
const Content: FC<TooltipDescriptiveContent> = ({
placement,
header,
body,
actionLink,
isDarkMode,
widthContent = "284px",
...rest
}) => (
<StyledWrapper
{...rest}
placement={placement}
backgroundColor={
!isDarkMode
? "var(--fd-colors-brand-secondary-shade)"
: "var(--fd-colors-background-layer)"
}
p="space-4"
width={widthContent}
>
{header &&
(isValidElement(header) ? (
cloneElement(header)
) : (
<Header
qaLabel="tooltip-descriptive-header"
tag="h3"
marginBottom="space-3"
color={
isDarkMode
? "--fd-colors-content-strong"
: "--fd-colors-content-on-dark"
}
>
{header}
</Header>
))}
{isValidElement(body) ? (
cloneElement(body)
) : (
<Paragraph
qaLabel="tooltip-descriptive-body"
color={
isDarkMode ? "--fd-colors-content-default" : "--fd-colors-core-white"
}
>
{body}
</Paragraph>
)}
{actionLink && isValidElement(actionLink) && cloneElement(actionLink)}
</StyledWrapper>
);
export default Content;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/TooltipDescriptive/index.tsx
import React, { FC } from "react";
import { noop } from "lodash";
import type {
TooltipDescriptiveProps,
TooltipDescriptivePlacement
} from "./types";
import { Popper } from "../Popper";
import Content from "./content";
const CLOSE_DELAY: number = 30000;
export const TooltipDescriptive: FC<TooltipDescriptiveProps> = ({
children,
qaLabel,
placement = "top-mid",
isOpen = false,
isDisabled = false,
isDarkMode = false,
closeDelay = CLOSE_DELAY,
forceClose = false,
onAction = "click",
layer = 1999,
isLeftSideRendered = false,
showCaret = false,
onClickOuside = noop,
...rest
}) => (
<Popper
on={onAction}
placement={placement}
isOpen={isOpen}
isDisabled={isDisabled}
layer={layer}
forceClose={forceClose}
closeDelay={closeDelay}
isLeftSideRendered={isLeftSideRendered}
showCaret={showCaret}
onClickOuside={onClickOuside}
content={
<Content
data-qa-label={qaLabel}
placement={placement}
isDarkMode={isDarkMode}
{...rest}
/>
}
>
{children}
</Popper>
);
export type { TooltipDescriptiveProps, TooltipDescriptivePlacement };
export default TooltipDescriptive;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/MyBetsRow/styled-components.ts
import styled from "styled-components"; export const AlertLinkWrapper = styled.div` cursor: pointer; `; export const PromosOnboardingWrapper = styled.div` max-width: 159px; `;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/MyBetsRow/index.tsx
import React, { isValidElement, useCallback } from "react";
import { get, noop } from "lodash";
import OptedInTag from "@tvg/atomic-ui/_atom/OptedInTag";
import Table from "@tvg/atomic-ui/_molecule/Table";
import MyBetsDesktopRaceDetails from "@tvg/atomic-ui/_molecule/MyBetsDesktopRaceDetails";
import MyBetsDesktopBetDetails from "@tvg/atomic-ui/_molecule/MyBetsDesktopBetDetails";
import MyBetsDesktopStatus from "@tvg/atomic-ui/_molecule/MyBetsDesktopStatus";
import WagerSettledStatus from "@tvg/atomic-ui/_molecule/WagerSettledStatus";
import WagerActionButtons from "@tvg/atomic-ui/_molecule/WagerActionButtons";
import WagerVideoActions from "@tvg/atomic-ui/_molecule/WagerVideoActions";
import {
TooltipDescriptive,
AlertInLine,
Paragraph
} from "@tvg/design-system/web";
import { Props } from "./types";
import { AlertLinkWrapper, PromosOnboardingWrapper } from "./styled-components";
import onRepeatBet from "./utils/gtm/onRepeatBet";
const TOOLTIP_TIMER = 60000;
const MyBetsRow = ({
wager,
mtp,
raceStatusCode,
legStatusCode,
legNumber,
showRaceLeg = false,
selectedTab,
isMTPNewRules = false,
raceNumber,
isCanceled,
dateDiff,
betAmount,
qaLabel,
isOptedIn,
isWagerCancelable,
onCancelWager,
renderRunnerSelections,
shouldShowPotentialReturn = false,
probableValue = "",
onApproxPayout = () => {},
shouldShowRebet = false,
handleRebetClickEvent = noop,
onRepeatBets = noop,
showRepeatButton = false,
rebetWagerTypeName = "",
showMinMaxWillPays = false,
minWillPays = 0,
maxWillPays = 0,
isBetActive = true,
onRaceDetails = () => {},
onLiveVideo = () => {},
onWatchReplay = noop,
hasPastPerformance = false,
shouldRedirect = true,
showSeeResult = false,
hasLiveVideo = true,
showScratchedNotification = false,
shouldNotHideScratchNotification = false,
scratchedTitle = "",
scratchedLegText = "",
setShouldNotHideScratchNotification = noop,
isMultiRace = false,
currentRaceNumber = 0,
trackRulesMessages = null,
showPromoOnboarding = false,
promoOnboardingComponent = null,
actionWrapperColSize = "auto"
}: Props) => {
const getPromoComponent = useCallback(() => {
if (showPromoOnboarding && isValidElement(promoOnboardingComponent)) {
return promoOnboardingComponent;
}
return isOptedIn && <OptedInTag isInline />;
}, [showPromoOnboarding, isOptedIn]);
return (
<Table.Row qaLabel={`${qaLabel}-${get(wager, "id", "")}`}>
<Table.Cell qaLabel={`${qaLabel}-status-${get(wager, "id", "")}`}>
<MyBetsDesktopStatus
mtp={mtp}
raceStatusCode={raceStatusCode}
legStatusCode={legStatusCode}
legNumber={legNumber}
showRaceLeg={showRaceLeg}
selectedTab={selectedTab}
isMTPNewRules={isMTPNewRules}
statusName={get(wager, "betStatus.name", "")}
raceDate={get(wager, "raceDate", "")}
racePostTime={get(wager, "racePostTime", "")}
dateDiff={dateDiff}
qaLabel={qaLabel}
/>
</Table.Cell>
<Table.Cell qaLabel={`${qaLabel}-race-details-${get(wager, "id", "")}`}>
<MyBetsDesktopRaceDetails
trackName={get(wager, "trackName")}
raceNumber={raceNumber}
transactionDate={get(wager, "transactionDate")}
onClick={onRaceDetails}
shouldRedirect={shouldRedirect}
isSpecialWager={get(wager, "isSpecialWager", false)}
/>
<PromosOnboardingWrapper>{getPromoComponent()}</PromosOnboardingWrapper>
</Table.Cell>
<Table.Cell qaLabel={`${qaLabel}-bet-details-${get(wager, "id", "")}`}>
<MyBetsDesktopBetDetails
isCanceled={!!isCanceled}
wagerAmount={get(wager, "wagerAmount", 0)}
wagerType={get(wager, "wagerType", {})}
betTotal={get(wager, "betTotal", 0)}
shouldShowPotentialReturn={shouldShowPotentialReturn}
probableValue={probableValue}
onApproxPayout={onApproxPayout}
showMinMaxWillPays={showMinMaxWillPays}
minWillPays={minWillPays}
maxWillPays={maxWillPays}
/>
</Table.Cell>
<Table.Cell
qaLabel={`${qaLabel}-selections-${get(wager, "id", "")}`}
isPositionRelative
>
{showScratchedNotification && shouldNotHideScratchNotification && (
<AlertInLine
message=""
title={scratchedTitle}
type="floating"
variant="informational"
qaLabel="bet-notification-rules"
marginBottom="space-5"
onDismissPress={() => setShouldNotHideScratchNotification(false)}
>
<Paragraph
color="--fd-colors-system-info-content-on-subtle"
qaLabel="alert-inline-message"
fontFamily="regular"
mb="space-1"
>
{scratchedLegText}
</Paragraph>
{trackRulesMessages ? (
<TooltipDescriptive
qaLabel={`notification-scratch-${get(wager, "id", "unk")}`}
header={get(trackRulesMessages, "subtitle")}
body={get(trackRulesMessages, "message", []).join(", ")}
placement="bottom-mid"
layer={5}
closeDelay={TOOLTIP_TIMER}
>
<AlertLinkWrapper>
<Paragraph
color="--fd-colors-system-info-link-on-subtle"
qaLabel="notification-scratch-tooltip"
fontFamily="regular"
>
See Rules
</Paragraph>
</AlertLinkWrapper>
</TooltipDescriptive>
) : null}
</AlertInLine>
)}
{renderRunnerSelections}
</Table.Cell>
<Table.Cell
qaLabel={`${qaLabel}-actions-${get(wager, "id", "")}`}
colSize={actionWrapperColSize}
>
<WagerVideoActions
hasLiveVideo={hasLiveVideo}
onLiveVideo={onLiveVideo}
mtp={mtp}
isMultiRace={isMultiRace}
hasPastPerformance={hasPastPerformance}
onWatchReplay={onWatchReplay}
showSeeResult={showSeeResult}
currentRaceNumber={currentRaceNumber}
/>
<WagerSettledStatus
device="desktop"
statusName={get(wager, "betStatus.name", "")}
winningsAmount={get(wager, "winningsAmount", 0)}
betRefund={get(wager, "betRefund", 0)}
betAmount={betAmount}
/>
<WagerActionButtons
isWagerCancelable={isWagerCancelable}
onCancelWager={onCancelWager}
onRepeatBets={() => {
onRepeatBets();
onRepeatBet({
betType: get(wager, "wagerType.name"),
betAmount: get(wager, "wagerAmount"),
raceType: get(wager, "raceTypeAbbreviation"),
selectionSource: "repeat_bet_mybets",
module: "my_bets"
});
}}
handleRebetClickEvent={handleRebetClickEvent}
shouldShowRebet={shouldShowRebet}
showRepeatButton={showRepeatButton}
rebetWagerTypeName={rebetWagerTypeName}
isBetActive={isBetActive}
/>
</Table.Cell>
</Table.Row>
);
};
export default MyBetsRow;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/MyBetsRow/utils/gtm/onRepeatBet.ts
import mediator from "@tvg/mediator";
interface OnClickRepeatBetEventPayload {
betAmount: number;
betType: string;
module: string;
selectionSource: string;
raceType?: string;
}
const onRepeatBet = ({
betAmount,
betType,
module = "",
selectionSource,
raceType
}: OnClickRepeatBetEventPayload) => {
mediator.base.dispatch({
type: "MYBETS_ADD_TO_BETSLIP",
payload: {
betAmount,
betType,
module,
selectionSource,
raceType
}
});
};
export default onRepeatBet;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/utils/pickBets.ts
import { get, isEmpty } from "lodash";
import {
RaceInfoMyBets,
RaceWagerType,
FavoriteRunners,
BettingInterest
} from "@tvg/ts-types/Race";
import {
BetSelection,
BetRunnerDetails,
ScratchedRunnersByLeg
} from "@tvg/ts-types/Bet";
import { WagerTypeCodesEnum } from "@tvg/ts-types/Wager";
import { SixFn } from "@tvg/ts-types/Functional";
import { handleCreateBetGtm } from "./gtm";
export const getCurrentWagerResults = (
races: RaceInfoMyBets[],
raceNumber: number,
totalWagers: number
): RaceInfoMyBets[] =>
races
.slice(raceNumber - 1, raceNumber + totalWagers - 1)
.filter(
(race: RaceInfoMyBets) =>
race.status.code !== "IC" && race.status.code !== "O"
);
export const checkForScratchedRunnersByLeg = (
selections: BetSelection[][],
totalResults: number
): boolean =>
selections
.slice(totalResults)
.map((selection: BetSelection[]) =>
selection.map((runners: BetSelection) =>
runners.runners.every((runner: BetRunnerDetails) => runner.isScratched)
)
)
.map((checks) => checks.every((check) => check))
.includes(true);
export const getScratchedLegNumbersIndex = (
selections: BetSelection[][]
): number[] =>
selections &&
selections
.map((selection: BetSelection[]) =>
selection
.filter((runners: BetSelection) => runners.runners.length > 0)
.map((runners: BetSelection) =>
runners.runners.every(
(runner: BetRunnerDetails) => runner.isScratched
)
)
.some((leg) => leg)
)
.reduce<Array<boolean>>((a, b) => a.concat(b), [])
.map((check: boolean, index) => (check ? index : -1))
.filter((leg: number) => leg > -1);
export const getWinningLegsBiNumbers = (results: RaceInfoMyBets[]): number[] =>
results.map((result: RaceInfoMyBets) =>
get(result, "results.runners[0].biNumber", 0)
);
export const verifyWagerWinningLegs = (
winningLegs: number[],
selections: BetSelection[][]
): boolean =>
winningLegs
.map((leg: number, index) =>
get(selections, `[${index}]`, [])
.map((runner: BetSelection) => +runner.runnerNumber === +leg)
.includes(true)
)
.every((leg) => leg === true);
export const getEligibleSelections = (
selections: BetSelection[][],
totalResults: number
): string[][] =>
selections.slice(totalResults).map((selection) =>
selection.reduce<Array<string>>((accSelection, currSelection) => {
const runners = get(currSelection, "runners") || [];
if (runners.some((runner) => !runner.isScratched)) {
accSelection.push(currSelection.runnerNumber.toString());
}
if (currSelection.alternate) {
const alternateNumber = `${currSelection.alternate.biNumber}B`;
const alternateRunners = get(currSelection.alternate, "runners") || [];
if (
!accSelection.includes(alternateNumber) &&
alternateRunners.some((runner) => !runner.isScratched)
) {
accSelection.push(alternateNumber);
}
}
return accSelection;
}, [])
);
export const pickBetWagerTypes = [
"WN",
"DB",
"P3",
"P4",
"P5",
"P6",
"P7",
"P8",
"P9",
"P10",
"P11",
"P12"
];
export const getEligibleNextRaceWagerTypeConfigs = (
race: RaceInfoMyBets | null,
pendingSelections: number
): RaceWagerType | typeof undefined =>
get(race, "wagerTypes", []).find(
(config: RaceWagerType) =>
config.type.code === pickBetWagerTypes[pendingSelections - 1]
);
export const betTypeChecker = (code: WagerTypeCodesEnum): boolean =>
pickBetWagerTypes.includes(code);
const selectionsToStringReducer = (
selectionString: string,
selections: BetSelection[],
index: number
) =>
get(selections, "length", 0)
? `${selectionString}&s${index}=${selections
.map((v) =>
v.alternate?.biNumber
? `${v.runnerNumber},${v.alternate.biNumber}B`
: v.runnerNumber
)
.toString()}`
: selectionString;
const selectionsToStringBetSlipReducer = (
selectionString: string[],
selections: BetSelection[]
) =>
get(selections, "length", 0)
? [...selectionString, selections.map((v) => v.runnerNumber).join()]
: [];
const reBetSelectionsToStringReducer = (
selectionString: string,
selections: string[],
index: number
) =>
get(selections, "length", 0)
? `${selectionString}&s${index}=${selections.map((v) => v).toString()}`
: selectionString;
export const stringifySelections = (selections: BetSelection[][]): string =>
selections.reduce(selectionsToStringReducer, "");
export const stringifySelectionsBetSlip = (
selections: BetSelection[][]
): string => selections.reduce(selectionsToStringBetSlipReducer, []).join(";");
export const stringifyReBetSelections = (selections: string[][]) =>
selections.reduce(reBetSelectionsToStringReducer, "");
const scratchesToStringReducer = (acc: string, value: number) => {
const seperator = acc.length ? ", " : "";
return `${acc}${seperator}${value + 1}`;
};
export const stringifyLegScratches = (scratchIndexes: number[]): string =>
scratchIndexes
.reduce(scratchesToStringReducer, "")
.replace(/,(?=[^,]*$)/, " &");
export const calculateBetTotalAmount = (
wagerSelections: string[][],
wagerAmount: number
): number =>
wagerSelections
.filter((selection) => !Number.isNaN(selection))
.map((selection) => selection.length)
.reduce((accumulator, currentValue) => accumulator * currentValue) *
wagerAmount;
export const getFavoriteRunnerByLeg = (
selections: BetSelection[][],
races: RaceInfoMyBets[],
raceNumber: number | string,
raceDate: string
): FavoriteRunners => {
const slicedRaces = races.slice(
+raceNumber - 1,
+raceNumber + get(selections, "length", 0) - 1
);
const isRaceToday = get(races, "0.raceDate", "") === raceDate;
if (!isRaceToday) {
return {};
}
return slicedRaces.reduce((accumulator, race: RaceInfoMyBets, index) => {
const raceFavorites: BettingInterest[] = race.bettingInterests.filter(
(runner) =>
(runner.favorite || runner.isFavorite) && !runner.runners[0].scratched
);
let filterBySingleFavorite = {};
if (raceFavorites.length === 1 && race.results) {
const raceFavorite = raceFavorites[0];
const isFavoriteWinner =
race.results &&
race.results.runners &&
race.results.runners.some(
(runner) =>
runner.finishPosition === 1 &&
runner.biNumber === raceFavorites[0].biNumber
);
filterBySingleFavorite = {
runnerNumber: +raceFavorite.biNumber,
runnerName: raceFavorite.runners[0].horseName,
isWinner: isFavoriteWinner,
isFavorite: raceFavorite.favorite || raceFavorite.isFavorite
};
}
return {
...accumulator,
[index]: filterBySingleFavorite
};
}, {});
};
export const getScratchedRunnersByLeg = (
selections: BetSelection[][]
): ScratchedRunnersByLeg =>
selections.reduce((acc, selection: BetSelection[], index) => {
const legScratches = selection
.map((runners: BetSelection) =>
runners.runners.filter((runner: BetRunnerDetails) => runner.isScratched)
)
.reduce((a, b) => a.concat(b), []);
return {
...acc,
[index]: legScratches
};
}, {});
export const checkScratchedLegsForFavorite = (
scratchedLegsByIndex: number[],
favoriteRunnerByLeg: FavoriteRunners
): boolean =>
(scratchedLegsByIndex || []).some(
(legIndex: number) =>
Object.keys(get(favoriteRunnerByLeg, legIndex, {})).length > 0
);
export const checkLegForScratchedFavorite = (
scratchedLegsByIndex: number[],
favoriteRunnerByLeg: FavoriteRunners,
scratchedRunnersByLeg: ScratchedRunnersByLeg
): number[] =>
scratchedLegsByIndex.filter((legIndex) =>
scratchedRunnersByLeg[legIndex].filter(
(runner) =>
!isEmpty(runner) &&
Object.keys(get(favoriteRunnerByLeg, legIndex, {})).length > 0 &&
+runner.runnerId !== +favoriteRunnerByLeg[legIndex].runnerNumber
)
);
export const handleRebetClickEvent = (
callback: SixFn<
string,
number,
WagerTypeCodesEnum,
number,
number,
string,
void
>,
rebetWagerAmount: number,
betAmount: number,
rebetWagerTypeCode: WagerTypeCodesEnum,
selections: string,
nextRaceNumber: number,
currentOpenLeg?: RaceInfoMyBets
) => {
// @ts-ignore
callback();
handleCreateBetGtm({
runnerAmount: rebetWagerAmount,
trackName: get(currentOpenLeg, "trackName", ""),
betAmount,
betType: rebetWagerTypeCode,
repeatBet: 0,
sport: get(currentOpenLeg, "isGreyhound", false)
? "Greyhounds Racing"
: "Horse Racing",
runnerSelectionList: selections.replace(/&s\d=/g, " ").trim(),
raceNumber: +nextRaceNumber
});
};
export const formatRepeatBetsSelections = (
selections: string[][],
currentWagerTypeCode: string,
wagerAmount: number
) =>
`&wt=${currentWagerTypeCode}&bet=${wagerAmount}${stringifyReBetSelections(
selections
)}`;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/hooks/usePickBetRebet.ts
import { useEffect, useState } from "react";
import { get } from "lodash";
import { BetSelection } from "@tvg/ts-types/Bet";
import { RaceInfoMyBets, RaceWagerType } from "@tvg/ts-types/Race";
import { NullaryFn, SixFn } from "@tvg/ts-types/Functional";
import { WagerType, WagerTypeCodesEnum } from "@tvg/ts-types/Wager";
import {
calculateBetTotalAmount,
checkForScratchedRunnersByLeg,
getCurrentWagerResults,
getEligibleNextRaceWagerTypeConfigs,
getEligibleSelections,
getWinningLegsBiNumbers,
handleRebetClickEvent,
stringifyReBetSelections,
verifyWagerWinningLegs
} from "../utils/pickBets";
export type PickBetRebet = {
allRacesFromTrack: RaceInfoMyBets[];
mainWagerDetails: string[];
currentRace?: RaceInfoMyBets;
currentOpenLeg?: RaceInfoMyBets;
callback: SixFn<
string,
number,
WagerTypeCodesEnum,
number,
number,
string,
void
>;
selections: BetSelection[][];
enablePickBetRebet: boolean;
isPickBet: boolean;
isCurrentRaceDate: boolean;
isSettledBet: boolean;
};
export type PickBetRebetResult = [
NullaryFn<void>,
string,
string,
boolean,
string,
string,
number,
number,
Array<Array<string>>,
WagerType | {}
];
export const usePickBetRebet = ({
allRacesFromTrack,
mainWagerDetails,
currentRace,
currentOpenLeg,
selections,
callback,
enablePickBetRebet,
isPickBet,
isCurrentRaceDate,
isSettledBet
}: PickBetRebet): PickBetRebetResult => {
const [shouldShowRebet, setShouldShowRebet] = useState(false);
const [totalWagerResults, setTotalWagerResults] = useState(0);
const [
eligibleNextRaceWagerTypeConfigs,
setEligibleNextRaceWagerTypeConfigs
] = useState<RaceWagerType>();
useEffect(() => {
try {
if (enablePickBetRebet && isPickBet && !isSettledBet) {
const wagerRaceNumber = get(mainWagerDetails, 2);
const currentOpenLegStatusCode = get(currentOpenLeg, "status.code", "");
const totalWagerSelections = selections.length;
// Map races(legs) that are resulted
const listOfLegsResulted = getCurrentWagerResults(
allRacesFromTrack,
+wagerRaceNumber,
totalWagerSelections
);
const legsResultedLength = listOfLegsResulted.length;
// Count of missing legs to run
const totalPendingLegs = totalWagerSelections - legsResultedLength;
const tempEligibleNextRaceWagerTypeConfigs =
currentOpenLeg &&
getEligibleNextRaceWagerTypeConfigs(currentOpenLeg, totalPendingLegs);
// Validation to check straight away that there are no next wager
const hasNextLeg = legsResultedLength === totalWagerSelections;
// Validation to check if we have any result (leg that has finished already)
const noWagerResults = listOfLegsResulted.every(
(race) => race.results === null
);
const isNextRaceClosed =
currentOpenLegStatusCode === "RO" ||
currentOpenLegStatusCode === "SK";
const containsScratchedLeg = checkForScratchedRunnersByLeg(
selections,
legsResultedLength
);
const isCurrentRaceInRaceOff =
get(currentRace, "status.code", "") === "SK";
const winningLegsBiNumber = getWinningLegsBiNumbers(listOfLegsResulted);
const isWinningBet = verifyWagerWinningLegs(
winningLegsBiNumber,
selections
);
setTotalWagerResults(legsResultedLength);
setEligibleNextRaceWagerTypeConfigs(
tempEligibleNextRaceWagerTypeConfigs
);
if (
!hasNextLeg &&
!noWagerResults &&
!containsScratchedLeg &&
!isNextRaceClosed &&
!isCurrentRaceInRaceOff &&
!isWinningBet &&
isCurrentRaceDate &&
tempEligibleNextRaceWagerTypeConfigs
) {
setShouldShowRebet(true);
} else {
setShouldShowRebet(false);
}
}
} catch (e) {
// Something failed while check should show rebet
console.warn("[usePickBetRebet]: Error:", e);
}
}, [
enablePickBetRebet,
isPickBet,
allRacesFromTrack,
currentOpenLeg,
isCurrentRaceDate,
selections
]);
const currentOpenLegRaceNumber = get(currentOpenLeg, "number", 0);
const eligibleWagerSelections = getEligibleSelections(
selections,
totalWagerResults
);
const rebetWagerType = get(eligibleNextRaceWagerTypeConfigs, "type", {});
const rebetWagerTypeName = get(
eligibleNextRaceWagerTypeConfigs,
"type.name",
""
);
const rebetWagerTypeCode = get(
eligibleNextRaceWagerTypeConfigs,
"type.code",
""
);
const rebetWagerTypeId = get(eligibleNextRaceWagerTypeConfigs, "type.id", "");
const rebetWagerAmount = get(
eligibleNextRaceWagerTypeConfigs,
"wagerAmounts[0]",
""
);
const rebetSelections = stringifyReBetSelections(eligibleWagerSelections);
const betAmount = get(eligibleWagerSelections, "length", 0)
? calculateBetTotalAmount(eligibleWagerSelections, rebetWagerAmount)
: 0;
const rebetSearch = `?race=${currentOpenLegRaceNumber}&wt=${rebetWagerTypeCode}&bet=${rebetWagerAmount}${rebetSelections}&type=Rebet`;
return [
() =>
handleRebetClickEvent(
callback,
rebetWagerAmount,
betAmount,
rebetWagerTypeCode,
rebetSelections,
currentOpenLegRaceNumber,
currentOpenLeg
),
rebetWagerTypeName,
rebetSearch,
shouldShowRebet,
rebetWagerTypeId,
rebetSelections,
rebetWagerAmount,
betAmount,
eligibleWagerSelections,
rebetWagerType
];
};
export default usePickBetRebet;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/hooks/useSelections.ts
import { useEffect, useState, useMemo } from "react";
import { get, first } from "lodash";
import type { WagerTypeCodesEnum } from "@tvg/ts-types/Wager";
import type { WroWager } from "@tvg/ts-types/WroWager";
import type { Selections } from "@tvg/ts-types/Selections";
import type { BettingInterests, BIPayouts, BIRunner } from "@tvg/ts-types/Bet";
import type {
RaceInfoMyBets,
RaceInfoMyBetsResults,
Willpay,
WillpayPayout
} from "@tvg/ts-types/Race";
import { BetSelection } from "@tvg/ts-types/Bet";
import { isFavoriteRunner } from "../utils/general";
import { getWinnerBI } from "../utils/raceDetails";
export interface Props {
wager: WroWager;
isMultiRace: boolean;
raceNumber: number;
currentRace?: RaceInfoMyBets;
currentRaceDate: string;
finalBettedLeg: number;
showWillPays: boolean;
allRacesFromTrack: RaceInfoMyBets[];
currentWagerTypeCode: WagerTypeCodesEnum;
isActive: boolean;
results: RaceInfoMyBetsResults[] | null;
isExotic: boolean;
}
export const getAlternateDetails = (
biRunner: BettingInterests,
allRacesFromTrack: RaceInfoMyBets[],
raceNumberIndex: number
) => {
const selectedBI = get(
allRacesFromTrack,
`${raceNumberIndex}.bettingInterests`,
[]
).find((bi: BettingInterests) => bi.biNumber === biRunner.biNumber);
const runners = (biRunner?.runners || []).map((currentRunner: BIRunner) => ({
runnerId: currentRunner.runnerId,
runnerName: currentRunner.horseName,
saddleColor: selectedBI?.saddleColor,
numberColor: selectedBI?.numberColor,
isScratched: currentRunner.scratched,
isAlternate: true,
currentOdds: selectedBI?.currentOdds
}));
const isWinner = get(biRunner, "isWinner", null);
return { ...biRunner, isWinner, runners };
};
function useSelections({
wager,
isMultiRace,
raceNumber,
currentRace,
currentRaceDate,
finalBettedLeg,
showWillPays,
allRacesFromTrack,
currentWagerTypeCode,
isActive,
isExotic
}: Props): BetSelection[][] {
const initialSelections = useMemo(
() =>
get(wager, "selections.selection", []).map(
(selection: Selections, selectionIndex: number) => {
const currentRaceNumberIndex = isMultiRace
? +raceNumber - 1 + selectionIndex
: +raceNumber - 1;
const alternate = selection.alternateBettingInterest
? getAlternateDetails(
selection.alternateBettingInterest,
allRacesFromTrack,
currentRaceNumberIndex
)
: null;
return selection.bettingInterests.map(
(biRunner: BettingInterests) => {
const biNumber = get(biRunner, "biNumber", 0);
const selectedBI = get(
allRacesFromTrack,
`${currentRaceNumberIndex}.bettingInterests`,
[]
).find(
(bi: BettingInterests) => bi.biNumber === biRunner.biNumber
);
const currentOdds = get(biRunner, "currentOdds", {});
const runners = get(biRunner, "runners") || [];
const runnersDetails = runners.map((currentRunner: BIRunner) => ({
runnerId: currentRunner.runnerId,
runnerName: currentRunner.horseName,
saddleColor: selectedBI?.saddleColor,
numberColor: selectedBI?.numberColor,
isScratched: currentRunner.scratched,
isAlternate: false
}));
const payouts = get(biRunner, "payouts") || [];
let isWinner = get(biRunner, "isWinner", null);
let willPayAmount = 0;
let isFavorite = false;
if (!isMultiRace) {
isFavorite = isFavoriteRunner(
currentRaceDate,
biNumber,
currentRace
);
if (payouts.length > 0) {
willPayAmount = payouts.reduce(
(willPaysAmount: number, currentPayout: BIPayouts) =>
willPaysAmount + currentPayout.amount,
0
);
}
} else {
const finalLegWillPays = get(
allRacesFromTrack,
`${finalBettedLeg - 1}.willPays`
);
const currentLeg = get(
allRacesFromTrack,
currentRaceNumberIndex
);
if (isWinner === null && isActive) {
const raceResultsPath = `${currentRaceNumberIndex}.results`;
const currentRaceResults = get(
allRacesFromTrack,
raceResultsPath
);
if (currentRaceResults && currentRaceResults.runners) {
const winnersBI = getWinnerBI(
currentRaceResults,
(isExotic ? currentRaceNumberIndex : 0) + 1
);
isWinner =
!!winnersBI &&
!!winnersBI.find(
(winnerBi) => winnerBi.biNumber === biNumber
);
}
}
if (showWillPays && finalLegWillPays) {
const willPays = first<Willpay>(
finalLegWillPays.filter(
(currentWillPays: Willpay) =>
currentWillPays.type.code === currentWagerTypeCode
)
);
const willPayDetails = first<WillpayPayout>(
(get(willPays, "payouts") || []).filter(
(payout: WillpayPayout) =>
+payout.bettingInterestNumber === biNumber
)
);
if (willPays && willPayDetails) {
willPayAmount =
(+willPayDetails.payoutAmount / +willPays.wagerAmount) *
+wager.wagerAmount;
}
}
if (currentLeg) {
isFavorite = isFavoriteRunner(
currentRaceDate,
biNumber,
currentLeg
);
}
}
return {
runnerNumber: biNumber,
runners: runnersDetails,
alternate,
willPayAmount,
payouts,
currentOdds,
isFavorite,
isWinner
};
}
);
}
),
[
wager,
allRacesFromTrack,
isMultiRace,
raceNumber,
currentRaceDate,
finalBettedLeg,
showWillPays,
currentWagerTypeCode,
isActive,
isExotic,
currentRace
]
);
const [selections, setSelections] =
useState<BetSelection[][]>(initialSelections);
useEffect(() => {
setSelections(initialSelections);
}, [initialSelections]);
return selections;
}
export default useSelections;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/hooks/useMinMaxWillPays.ts
import { useEffect, useState } from "react";
import { BetSelection } from "@tvg/ts-types/Bet";
const useMinMaxWillPays = (selections: BetSelection[][]) => {
const [minWillPays, setMinWillPays] = useState(0);
const [maxWillPays, setMaxWillPays] = useState(0);
const [showMinMaxWillPays, setShowMinMaxWillPays] = useState(false);
useEffect(() => {
setMinWillPays(
Math.min(
...selections.map((selection) =>
selection.reduce(
(min, sel) =>
sel.willPayAmount === 0
? min
: Math.min(min, sel.willPayAmount || Infinity),
Infinity
)
)
)
);
setMaxWillPays(
Math.max(
...selections.map((selection) =>
selection.reduce(
(max, sel) => Math.max(max, sel.willPayAmount || 0),
0
)
)
)
);
setShowMinMaxWillPays(minWillPays > 0 && maxWillPays > 0);
}, [selections, minWillPays, maxWillPays]);
return {
minWillPays,
maxWillPays,
showMinMaxWillPays
};
};
export default useMinMaxWillPays;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/hooks/useResults.ts
import { useEffect, useState } from "react";
import { get } from "lodash";
import { RaceInfoMyBets, RaceInfoMyBetsResults } from "@tvg/ts-types/Race";
type Props = {
allRacesFromTrack: RaceInfoMyBets[];
};
function useResults(props: Props): Array<RaceInfoMyBetsResults> {
const { allRacesFromTrack } = props;
const [results, setResults] = useState<Array<RaceInfoMyBetsResults>>([]);
useEffect(() => {
if (allRacesFromTrack) {
setResults(
allRacesFromTrack.map((race) =>
get(race, "results", [] as RaceInfoMyBetsResults)
)
);
}
}, [allRacesFromTrack]);
return results;
}
export default useResults;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/hooks/useScratchNotification.ts
import { Dispatch, SetStateAction, useEffect, useState } from "react";
import { BetSelection, BetStatusCodesEnum } from "@tvg/ts-types/Bet";
import { FavoriteRunners } from "@tvg/ts-types/Race";
import { WagerTypeCodesEnum } from "@tvg/ts-types/Wager";
import {
checkLegForScratchedFavorite,
checkScratchedLegsForFavorite,
getScratchedLegNumbersIndex,
getScratchedRunnersByLeg,
stringifyLegScratches
} from "../utils/pickBets";
import { isPickBetSub } from "../utils/raceDetails";
export type ScratchNotification = {
selections: BetSelection[][];
isPickBet: boolean;
betStatusCode: BetStatusCodesEnum;
favoriteRunnerByLeg: FavoriteRunners;
currentWagerTypeCode: WagerTypeCodesEnum;
isCurrentRaceDate: boolean;
betRefund: number;
};
export const useScratchNotification = ({
selections,
isPickBet,
betStatusCode,
favoriteRunnerByLeg,
currentWagerTypeCode,
isCurrentRaceDate,
betRefund
}: ScratchNotification): [
boolean,
boolean,
Dispatch<SetStateAction<boolean>>,
string,
string,
boolean
] => {
const [showScratchedNotification, setShowScratchedNotification] =
useState(false);
const [
shouldNotHideScratchNotification,
setShouldNotHideScratchNotification
] = useState(true);
const [scratchedTitle, setScratchedTitle] = useState("");
const [scratchedLegText, setScratchedLegText] = useState("");
const [hasAlternates, setHasAlternates] = useState(false);
// Handle show notification
useEffect(() => {
const scratchedLegsByIndex = getScratchedLegNumbersIndex(selections);
const showScratched =
!!scratchedLegsByIndex.length &&
(isPickBet || betStatusCode !== "A") &&
betStatusCode !== "C";
setShowScratchedNotification(showScratched);
if (selections) {
setHasAlternates(
selections.flat().some((selection) => !!selection.alternate)
);
}
}, [isPickBet, betStatusCode, selections]);
useEffect(() => {
const scratchedRunnersByLeg = getScratchedRunnersByLeg(selections);
const scratchedLegsByIndex = getScratchedLegNumbersIndex(selections);
const verifiedReplacementsByLegIndex = checkLegForScratchedFavorite(
scratchedLegsByIndex || [],
favoriteRunnerByLeg,
scratchedRunnersByLeg
);
const isPickBetReplacementEligible =
isPickBetSub(currentWagerTypeCode) &&
checkScratchedLegsForFavorite(
scratchedLegsByIndex,
favoriteRunnerByLeg
) &&
verifiedReplacementsByLegIndex.length > 0;
if (isPickBet && betStatusCode === "A") {
setScratchedTitle("Runner Scratched");
if (scratchedLegsByIndex.length > 1) {
setScratchedLegText(
`Scratches occurred in Legs ${stringifyLegScratches(
scratchedLegsByIndex
)}`
);
} else {
setScratchedLegText(
`Scratch occurred in Leg ${scratchedLegsByIndex[0] + 1}`
);
}
}
if (betStatusCode !== "A") {
if (isPickBetReplacementEligible && isCurrentRaceDate) {
setScratchedTitle("Scratch Replacement");
if (verifiedReplacementsByLegIndex.length > 1) {
setScratchedLegText(
`Selections in Legs ${stringifyLegScratches(
verifiedReplacementsByLegIndex
)} were replaced.`
);
} else {
setScratchedLegText(
`Selection in Leg ${
verifiedReplacementsByLegIndex[0] + 1
} was replaced`
);
}
} else if (
isPickBet &&
betRefund > 0 &&
(betStatusCode === "W" || betStatusCode === "R")
) {
setScratchedTitle("Scratch Refund");
if (verifiedReplacementsByLegIndex.length > 1) {
setScratchedLegText(
`Selections in Legs ${stringifyLegScratches(
scratchedLegsByIndex
)} were refunded.`
);
} else {
setScratchedLegText(
`Selection in Leg ${scratchedLegsByIndex[0] + 1} was refunded`
);
}
} else if (
betRefund > 0 &&
(betStatusCode === "W" || betStatusCode === "R")
) {
setScratchedTitle("Scratch Refund");
setScratchedLegText(
"Due to a scratch on certain selections, you have received a refund."
);
} else if (isPickBet && betRefund === 0) {
setScratchedTitle("Runner Scratched");
if (scratchedLegsByIndex.length > 1) {
setScratchedLegText(
`Scratches occurred in Legs ${stringifyLegScratches(
scratchedLegsByIndex
)}`
);
} else {
setScratchedLegText(
`Scratch occurred in Leg ${scratchedLegsByIndex[0] + 1}`
);
}
} else {
setScratchedTitle("Runner Scratched");
setScratchedLegText("Scratch occurred.");
}
}
}, [selections, betStatusCode, isCurrentRaceDate, isPickBet, betRefund]);
return [
showScratchedNotification,
shouldNotHideScratchNotification,
setShouldNotHideScratchNotification,
scratchedTitle,
scratchedLegText,
hasAlternates
];
};
export default useScratchNotification;
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/redux/selectors/index.ts
import { get, size } from "lodash";
import { Store } from "redux";
import { StoryblokComponentPropsFormatted } from "../../types/storyblok";
import { PromoOnboarding } from "../../types/promoOnboarding";
import {
PromoMappedSteps,
PromoOnboardingStep,
PromoStepType
} from "../../types/promoSteps";
import { StoryblokPlaceName } from "../../types/promoOnboardingComponents";
const REDUCER_BASE_PATH = "promosOnboarding";
export const getStoryblokPromos = (store: Store): PromoOnboarding =>
get(store, REDUCER_BASE_PATH, {} as PromoOnboarding);
export const getPromoOnboardingAllSteps = (store: Store): PromoMappedSteps =>
get(store, `${REDUCER_BASE_PATH}.steps`, {});
export const getPromoOnboardingCompletedSteps = (store: Store): number =>
get(store, `${REDUCER_BASE_PATH}.completedSteps`, 0);
export const getPromoOnboardingCurrentStepType = (
store: Store
): PromoStepType => get(store, `${REDUCER_BASE_PATH}.currentStepType`);
export const getPromoOnboardingIsPromoExpired = (store: Store): boolean =>
get(store, `${REDUCER_BASE_PATH}.isPromoExpired`, false);
export const getPromoOnboardingNumberOfSteps = (store: Store): number =>
get(store, `${REDUCER_BASE_PATH}.numberSteps`, 0);
export const getPromoOnboardingPromoId = (store: Store): number | undefined =>
get(store, `${REDUCER_BASE_PATH}.promotionId`);
export const getPromoOnboardingRebateLimit = (store: Store): number =>
get(store, `${REDUCER_BASE_PATH}.rebateLimit`, 0);
export const getPromoOnboardingRemaingDays = (store: Store): number =>
get(store, `${REDUCER_BASE_PATH}.remainingDays`, 0);
export const getPromoOnboardingPromoRootId = (
store: Store
): number | undefined => get(store, `${REDUCER_BASE_PATH}.rootId`);
export const hasPromoOnboardingActivated = (store: Store) => {
const steps = getPromoOnboardingAllSteps(store);
return !!size(steps);
};
export const getStoryblokPromoByStep = (
store: Store,
step: PromoStepType
): PromoOnboardingStep | null =>
get(store, `${REDUCER_BASE_PATH}.steps.${step}`, null);
export const getStoryblokCurrentStep = (
store: Store,
step?: PromoStepType
): PromoOnboardingStep | null => {
const currentStep = step || getPromoOnboardingCurrentStepType(store);
return get(store, `${REDUCER_BASE_PATH}.steps.${currentStep}`, null);
};
export const getStoryblokPromoByPlace = (
store: Store,
place: StoryblokPlaceName,
step?: PromoStepType
): StoryblokComponentPropsFormatted | null => {
const currentStep = step || getPromoOnboardingCurrentStepType(store);
return get(
store,
`${REDUCER_BASE_PATH}.steps.${currentStep}.places.${place}`,
null
);
};
export const getPromoOnboardingPollerTime = (store: Store): number =>
get(store, `${REDUCER_BASE_PATH}.pollerTime`, 60);
export const getPromosOnboardingToggle = (store: Store): boolean =>
get(store, `capi.featureToggles.promosOnboarding`, false);
export const getPromoOnboardingCustomMessage = (store: Store): boolean =>
get(store, `capi.messages.myBetsPromoOnboardingCustomMessage`, "");
export const getPromosOnboardingWalletSteps = (store: Store): string[] => {
const steps = get(
store,
"capi.messages.promoOnboardingWalletSteps",
"$~amountToShow~ in wagering credit will be refunded if you don't win."
);
return steps.split("\r\n") || [];
};
export const getPromosOnboardingWalletSuccessHeaders = (
store: Store
): string[] => {
const headers = get(
store,
"capi.messages.promoOnboardingWalletSuccessHeaders",
""
);
return headers.split("\r\n") || [];
};
export const hasPromoOnboardingComponent = (
store: Store,
place: StoryblokPlaceName,
step?: PromoStepType
): boolean =>
!!get(getStoryblokPromoByPlace(store, place, step), "component", false);
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/constraints/onboardingDictionary.ts
import { AlertInline, Tag } from "@tvg/design-system/src/index";
import { ComponentDictionary } from "../types/promoOnboardingComponents";
export const ONBOARDING_DICTIONARY: ComponentDictionary = {
alert_inline: {
component: AlertInline,
defaultProps: {
qaLabel: "promoOnboardingAlertInline",
type: "fixed",
hasDismissButton: false
}
},
tag: {
component: Tag,
defaultProps: {
qaLabel: "promoOnboardingTag",
size: "m",
icon: "optedIn",
variant: "promo",
label: ""
}
},
unknown: {
component: null,
defaultProps: {}
}
};
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/utils/getStoryblokComponent.ts
import { createElement } from "react";
import { get } from "lodash";
import { StoryblokComponentPropsFormatted } from "../types/storyblok";
import { ONBOARDING_DICTIONARY } from "../constraints/onboardingDictionary";
import {
StoryblokBlock,
StorybookAvailableComponents
} from "../types/promoOnboardingComponents";
export const getStoryblokComponent = (
storyblokComponent: StoryblokComponentPropsFormatted
) => {
const { component: componentName, props } = storyblokComponent;
const storyblokBlok: StoryblokBlock<StorybookAvailableComponents> = get(
ONBOARDING_DICTIONARY,
componentName,
{} as StoryblokBlock<unknown>
);
const componentRender = get(storyblokBlok, "component", null);
const componentProps = {
...get(storyblokBlok, "defaultProps", {}),
...props
};
return componentRender && createElement(componentRender, componentProps);
};
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/types/promoOnboardingComponents.ts
import { FunctionComponent } from "react";
import { AlertInlineProps, TagProps } from "@tvg/design-system";
export enum StoryblokComponentName {
ALERT_INLINE = "alert_inline",
TAG = "tag",
UNKNOWN = ""
}
export enum StoryblokPlaceName {
PROGRAM_PAGE = "program_page",
TRACKS = "tracks_page",
BETSLIP_CONFIRMATION = "betslip_confirmation",
BETSLIP_PLACED = "betslip_placed",
MYBETS_WAGER_FOOTER = "bet_ticket",
MYBETS_CANCEL = "cancel_bet",
MYBETS_RACE_DETAILS = "mybets_race_details",
WALLET_HOME = "wallet_home",
WALLET_HOME_DESKTOP = "wallet_home_desktop",
WALLET_QUICK_DEPOSIT = "wallet_quick_deposit",
WALLET_DEPOSIT_TOP = "wallet_deposit_top",
WALLET_DEPOSIT_TAG = "wallet_deposit_tag",
UNKNOWN = ""
}
export interface PromoOnboardingComponent<T = unknown> {
component: StoryblokComponentName;
props: T;
}
export type PromoComponent<T = unknown> = Partial<
Record<StoryblokPlaceName, PromoOnboardingComponent<T>>
>;
export interface StoryblokBlock<T> {
component: FunctionComponent<T>;
defaultProps: Partial<T>;
}
export interface ComponentDictionary {
alert_inline: StoryblokBlock<AlertInlineProps>;
tag: StoryblokBlock<TagProps>;
unknown: Object;
}
export type StorybookAvailableComponents = Partial<AlertInlineProps | TagProps>;
export type StoryblokComponentProps = StorybookAvailableComponents & {
component: StoryblokComponentName;
};
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/utils/getValueFromProposition.ts
import { capitalize, first, get } from "lodash";
import { WagerTypeCodesInvertedEnum } from "@tvg/ts-types/Wager";
import {
DepositProposition,
WagerProposition
} from "../types/promoPropositions";
export enum VariableModifier {
MAX = "max",
MIN = "min",
NONE = ""
}
export const extractVariableModifier = (
variable: string
): { variableName: string; modifier: VariableModifier } => {
const modifierMatch = variable.match(/(.*)_(.*)/);
if (modifierMatch) {
return {
variableName: modifierMatch[2],
modifier: modifierMatch[1] as VariableModifier
};
}
return {
variableName: variable,
modifier: VariableModifier.NONE
};
};
export const getValueWithModifier = (
variable: string,
propositions: Array<DepositProposition | WagerProposition> = [],
modifier: VariableModifier
) => {
// The following logic applies to the following DEPOSIT STEP variables:
// bonusAmount, bonusPercentage and minimumDepositAmount
if (modifier !== VariableModifier.NONE) {
const variableArray = propositions.reduce(
(acc: Array<number>, proposition) => {
const originalVar = get(proposition, variable);
const newVar =
typeof originalVar === "string"
? +originalVar.replace("%", "").trim()
: originalVar;
return typeof newVar === "number" ? [...acc, newVar] : acc;
},
[]
);
if (modifier === VariableModifier.MAX) {
return Math.max(...variableArray);
}
if (modifier === VariableModifier.MIN) {
return Math.min(...variableArray);
}
}
// The following logic applies to the following WAGER STEP variables:
// raceDate, raceNumber, trackCode and wagerTypeCode
if (propositions.length > 1) {
if (variable === "wagerTypeCode") {
return "Multiple Wager Types";
}
if (variable === "trackCode") {
return "Multiple Tracks";
}
if (variable === "raceNumber") {
return "Multiple Races";
}
if (variable === "raceDate") {
return "Multiple Dates";
}
}
const variableValue = get(first(propositions), variable);
if (
variable === "wagerTypeCode" &&
variableValue in WagerTypeCodesInvertedEnum
) {
const wagerTypeName: string = get(
WagerTypeCodesInvertedEnum,
variableValue
);
return capitalize(wagerTypeName);
}
if (variable === "trackCode" && variableValue === "ALL") {
return "All Tracks";
}
if (variable === "raceNumber" && variableValue === 0) {
return "All Races";
}
if (variable === "raceDate" && !variableValue) {
return "Any Date";
}
return variableValue;
};
export const getValueFromProposition = (
variable: string,
propositions: Array<WagerProposition> | Array<DepositProposition>
) => {
const { variableName, modifier } = extractVariableModifier(variable);
return getValueWithModifier(variableName, propositions, modifier);
};
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/helpers/formatStoryblokText.ts
import { get, replace } from "lodash";
import { PromoOnboarding } from "../types/promoOnboarding";
import { PromoOnboardingStep } from "../types/promoSteps";
import { getValueFromProposition } from "../utils/getValueFromProposition";
const variableRegex = new RegExp("({{)(\\w*)(}})", "g");
export const formatStoryblokText = (
text: string,
promo: PromoOnboarding,
currentStep: PromoOnboardingStep
) => {
let editedText = text;
const matches = editedText.match(variableRegex);
if (matches) {
const variables = matches.map((match) =>
match.replace(variableRegex, (_, __, varName) => varName)
);
variables.forEach((variable) => {
const varToSearch = `{{${variable}}}`;
const replaceRegex = new RegExp(varToSearch, "g");
let newText = get(promo, variable);
if (!newText) {
// Try to find again but inside the step.
newText = get(currentStep, variable);
// Now try to find it again inside the propositions.
if (!newText) {
newText =
getValueFromProposition(
variable,
get(currentStep, "depositPropositions") ||
get(currentStep, "wagerPropositions") ||
[]
) || varToSearch;
}
}
editedText = replace(editedText, replaceRegex, newText);
});
}
return editedText;
};
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/hooks/usePromosOnboardingComponent.ts
import { useState, useEffect, FunctionComponentElement } from "react";
import { getStoryblokComponent } from "../utils/getStoryblokComponent";
import { StoryblokComponentPropsFormatted } from "../types/storyblok";
import {
StoryblokComponentName,
StorybookAvailableComponents
} from "../types/promoOnboardingComponents";
import { PromoOnboarding } from "../types/promoOnboarding";
import { PromoOnboardingStep } from "../types/promoSteps";
import { formatComponentWithDynamicVariables } from "../helpers/formatComponentWithDynamicVariables";
export const usePromosOnboardingComponent = (
promoOnboarding: StoryblokComponentPropsFormatted | null,
promo: PromoOnboarding | null,
currentStep: PromoOnboardingStep | null,
customMessage?: string | null
) => {
const [promoComponent, setPromoComponent] =
useState<FunctionComponentElement<StorybookAvailableComponents> | null>(
null
);
useEffect(() => {
const swappedMessage = (() => {
switch (promoOnboarding?.component) {
case StoryblokComponentName.ALERT_INLINE:
return { message: customMessage };
case StoryblokComponentName.TAG:
return { label: customMessage };
default:
return {};
}
})();
const componentWithCustomMessage = customMessage
? {
...promoOnboarding,
props: { ...promoOnboarding?.props, ...swappedMessage }
}
: promoOnboarding;
const formattedComponent =
componentWithCustomMessage && promo && currentStep
? formatComponentWithDynamicVariables(
componentWithCustomMessage as StoryblokComponentPropsFormatted,
promo,
currentStep
)
: promoOnboarding;
setPromoComponent(
promoOnboarding &&
getStoryblokComponent(
formattedComponent as StoryblokComponentPropsFormatted
)
);
}, [promoOnboarding]);
return promoComponent;
};
webpack://frontend-mybets/../../packages/tvg-lib-ts-types/Device.ts
export enum Device {
MOBILE = "mobile",
TABLET = "tablet",
DESKTOP = "desktop"
}
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/types/storyblok.ts
import { PromoAcquisition } from "./promos";
import { PromoMappedSteps, PromoStepType } from "./promoSteps";
import {
StoryblokComponentName,
StoryblokComponentProps,
StoryblokPlaceName,
StorybookAvailableComponents
} from "./promoOnboardingComponents";
export type StoryblokComponentPropsFormatted<T = StorybookAvailableComponents> =
{
component: StoryblokComponentName;
props: T;
};
export type StoryblokMessagesFormatted = Partial<
Record<StoryblokPlaceName, StoryblokComponentPropsFormatted>
>;
export interface StoryblokRenderPlace {
component: string;
places: Array<StoryblokPlaceName>;
}
export interface StoryblokMessages {
component: string;
promo_component: Array<StoryblokComponentProps>;
render_place: Array<StoryblokRenderPlace>;
}
export interface StoryblokStepDescription {
plugin: string;
type: PromoStepType;
description?: string;
description_lost?: string;
description_win?: string;
description_processing?: string;
}
export interface StoryblokStep {
component: string;
messages: Array<StoryblokMessages>;
step_config: StoryblokStepDescription;
}
export interface StoryblokContent {
component: string;
steps: Array<StoryblokStep>;
}
export enum StoryblokVersion {
PUBLISHED = "published",
DRAFT = "draft"
}
export interface StoryblokDraftConfig {
draft?: StoryblokDraft;
draftForceService?: PromoAcquisition;
}
export type StoryblokDraft = boolean | StoryblokVersion;
export interface StoryBlokComponentsFormatted {
steps: PromoMappedSteps;
}
export enum StoryblokPlugin {
TEXT = "promo-onboarding-component"
}
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/constraints/config.ts
import tvgConf from "@tvg/conf";
export const STORYBLOK_CONTENT_PATH = "promo-onboarding";
export const STORYBLOK_URL = "https://api.storyblok.com/v1/cdn/stories";
export const STORYBLOK_SPACES_URL = `https://api.storyblok.com/v1/cdn/spaces/${STORYBLOK_CONTENT_PATH}`;
export const {
storyblokToken: STORYBLOK_TOKEN,
storyblokVersion: STORYBLOK_VERSION
} = tvgConf().config();
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/utils/getStoryblokVersion.ts
import { StoryblokDraft, StoryblokVersion } from "../types/storyblok";
import { STORYBLOK_VERSION } from "../constraints/config";
export const getStoryblokVersion = (
draft?: StoryblokDraft
): StoryblokVersion => {
if (typeof draft === "boolean") {
return draft ? StoryblokVersion.DRAFT : StoryblokVersion.PUBLISHED;
}
return draft || STORYBLOK_VERSION;
};
webpack://frontend-mybets/../../node_modules/date-fns/esm/getTime/index.js
import toDate from '../toDate/index.js';
import requiredArgs from '../_lib/requiredArgs/index.js';
/**
* @name getTime
* @category Timestamp Helpers
* @summary Get the milliseconds timestamp of the given date.
*
* @description
* Get the milliseconds timestamp of the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the given date
* @returns {Number} the timestamp
* @throws {TypeError} 1 argument required
*
* @example
* // Get the timestamp of 29 February 2012 11:45:05.123:
* var result = getTime(new Date(2012, 1, 29, 11, 45, 5, 123))
* //=> 1330515905123
*/
export default function getTime(dirtyDate) {
requiredArgs(1, arguments);
var date = toDate(dirtyDate);
var timestamp = date.getTime();
return timestamp;
}
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/utils/fetchStoryBlokCacheVersion.ts
import axios from "axios";
import { get } from "lodash";
import { getTime } from "date-fns";
import { getStoryblokVersion } from "./getStoryblokVersion";
import { StoryblokDraft } from "../types/storyblok";
import { STORYBLOK_SPACES_URL, STORYBLOK_TOKEN } from "../constraints/config";
export const fetchStoryBlokCacheVersion = async (
draft?: StoryblokDraft
): Promise<number | null> => {
const cacheTimestamp = getTime(Date.now());
try {
const response = await axios({
method: "GET",
url: STORYBLOK_SPACES_URL,
headers: {
"content-type": "application/json"
},
params: {
version: getStoryblokVersion(draft),
token: STORYBLOK_TOKEN
}
});
return get(response, "data.space.version", cacheTimestamp);
} catch (error: unknown) {
console.error("Error trying to get cache version in storyblok", error);
return cacheTimestamp;
}
};
export default fetchStoryBlokCacheVersion;
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/types/promoSteps.ts
import { DepositProposition, WagerProposition } from "./promoPropositions";
import { PromoComponent } from "./promoOnboardingComponents";
export type PromoStepResponseType = "DepositStep" | "WagerStep" | "PayoutStep";
export enum PromoStepType {
DEPOSIT = "DEPOSIT_STEP",
WAGER = "WAGER_STEP",
PAYOUT = "PAYOUT_STEP",
UNKNOWN = ""
}
export enum PromoStepDescriptionKey {
DEFAULT = "default",
LOSS = "loss",
WIN = "win",
PROCESSING = "processing"
}
export type PromoStepDescriptions = Partial<
Record<PromoStepDescriptionKey, string>
>;
export enum PromoStepWagerStatus {
PLACED = "P",
WIN = "W",
LOST = "L"
}
export interface PromoGenericStep {
isFulfilled?: boolean;
places: PromoComponent;
description: PromoStepDescriptions;
stepType?: PromoStepType;
"@type"?: PromoStepResponseType;
}
export interface DepositStep extends PromoGenericStep {
stepType?: PromoStepType.DEPOSIT;
depositDate?: string;
depositPropositions?: Array<DepositProposition>;
"@type"?: "DepositStep";
}
export interface WagerStep extends PromoGenericStep {
isGreyHound?: boolean;
raceDate?: string;
raceNumber?: number;
serialNumber?: string;
stepType?: PromoStepType.WAGER;
trackCode?: string;
trackName?: string;
wagerStatus?: PromoStepWagerStatus;
wagerDate?: string;
wagerPropositions?: Array<WagerProposition>;
"@type"?: "WagerStep";
}
export interface PayoutStep extends PromoGenericStep {
payoutUUID: string;
amount: number;
timestamp: string;
"@type"?: "PayoutStep";
}
export type PromoOnboardingStep = WagerStep | PayoutStep | DepositStep;
export type PromoMappedSteps = Partial<
Record<PromoStepType, PromoOnboardingStep>
>;
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/utils/fetchStoryblok.ts
import axios from "axios";
import { StoryblokDraft } from "../types/storyblok";
import {
STORYBLOK_CONTENT_PATH,
STORYBLOK_TOKEN,
STORYBLOK_URL
} from "../constraints/config";
import { getStoryblokVersion } from "./getStoryblokVersion";
import { fetchStoryBlokCacheVersion } from "./fetchStoryBlokCacheVersion";
export const fetchStoryblok = async (
promoId: number,
draft?: StoryblokDraft
) => {
const storyblokUrl = `${STORYBLOK_URL}/${STORYBLOK_CONTENT_PATH}/${promoId}`;
const cacheVersion = await fetchStoryBlokCacheVersion(draft);
return axios({
method: "GET",
url: storyblokUrl,
headers: {
"content-type": "application/json"
},
params: {
version: getStoryblokVersion(draft),
token: STORYBLOK_TOKEN,
resolve_relations: "global_ref.reference",
cv: cacheVersion
}
});
};
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_templates/PromoPreview/styled-components.ts
import styled from "styled-components";
import { buildColor } from "@tvg/design-system";
export const PromoPreviewWrapper = styled.div`
display: flex;
flex-direction: column;
padding: 24px;
background-color: ${buildColor("white", "900")};
`;
export const PromoPreviewHeader = styled.div`
display: flex;
flex-direction: row;
justify-content: space-between;
`;
webpack://frontend-mybets/../../packages/tvg-comp-promos-onboarding/src/components/preview/helpers/formatStepName.ts
import { get } from "lodash";
import { PromoStepType } from "@tvg/sh-lib-promos-onboarding/types/promoSteps";
const formattedStepName: Record<PromoStepType, string> = {
[PromoStepType.DEPOSIT]: "Deposit Step",
[PromoStepType.WAGER]: "Wager Step",
[PromoStepType.PAYOUT]: "Payout Step",
[PromoStepType.UNKNOWN]: ""
};
export const formatStepName = (step: PromoStepType): string =>
get(formattedStepName, step, "");
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/PromoPreviewStep/styled-components.ts
import styled, { css } from "styled-components";
export const StepWrapper = styled.div`
display: flex;
flex-direction: column;
margin-bottom: 24px;
`;
export const RowWrapper = styled.tr``;
export const ColumnWrapper = styled.td<{
addPadding?: boolean;
}>`
${({ addPadding }) =>
addPadding &&
css`
padding: 0 12px;
`}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/PromoPreviewStep/index.tsx
import React from "react";
import { get } from "lodash";
import { formatStepName } from "@tvg/promos-onboarding/src/components/preview/helpers/formatStepName";
import { Header } from "@tvg/design-system";
import Table from "../../_molecule/Table";
import { StepWrapper, RowWrapper, ColumnWrapper } from "./styled-components";
import { Props } from "./types";
const theadData = [
{ title: "Render Places", size: "150px" },
{ title: "Component Preview", size: "300px" }
];
export const PromoPreviewStep = ({ step, components }: Props) => (
<StepWrapper key={get(step, "_uid", "")}>
<Header tag="h2" marginBottom="space-4" qaLabel="PromoStep-Heading">
{formatStepName(get(step, "step_config.type", ""))}
</Header>
<Table theadData={theadData}>
{!!get(components, "length", 0) &&
components.map((component, index) => (
<RowWrapper key={get(step, `messages[${index}]._uid`, "")}>
<ColumnWrapper addPadding>
{get(component, "renderPlaces", "")}
</ColumnWrapper>
<ColumnWrapper>{get(component, "component", "")}</ColumnWrapper>
</RowWrapper>
))}
</Table>
</StepWrapper>
);
export default PromoPreviewStep;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_templates/PromoPreview/index.tsx
import React from "react";
import { get } from "lodash";
import { Header, Button } from "@tvg/design-system";
import { PromoPreviewWrapper, PromoPreviewHeader } from "./styled-components";
import { Props } from "./types";
import PromoPreviewStep from "../../_organism/PromoPreviewStep";
export const PromoPreviewTemplate = ({
steps,
components,
refetchStoryblok
}: Props) => (
<PromoPreviewWrapper>
<PromoPreviewHeader>
<Header tag="h1" marginBottom="space-7" qaLabel="PromoPreview-Heading">
Steps
</Header>
<Button
variant="primary"
icon="refresh"
onPress={refetchStoryblok}
qaLabel="PromoPreview-RefetchButton"
>
Refresh preview
</Button>
</PromoPreviewHeader>
{steps.map((step, index) => (
<PromoPreviewStep
key={get(step, "_uid", "")}
step={step}
components={components[+index]}
/>
))}
</PromoPreviewWrapper>
);
export default PromoPreviewTemplate;
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/helpers/formatStoryblokProps.ts
import { get, omit } from "lodash";
import { StoryblokPlugin } from "../types/storyblok";
import { StoryblokComponentProps } from "../types/promoOnboardingComponents";
export const formatStoryblokProps = (componentProps: StoryblokComponentProps) =>
Object.entries(omit(componentProps, ["component"])).reduce(
(propsFormatted, [key, value]) => {
if (
typeof value === "object" &&
get(value, "plugin") === StoryblokPlugin.TEXT
) {
return {
...propsFormatted,
[key]: get(value, "value", "")
};
}
return {
...propsFormatted,
[key]: value
};
},
{}
);
webpack://frontend-mybets/../../packages/tvg-comp-promos-onboarding/src/components/preview/index.tsx
import React, { useState, useEffect } from "react";
import { get } from "lodash";
import { fetchStoryblok } from "@tvg/sh-lib-promos-onboarding/utils/fetchStoryblok";
import {
StoryblokVersion,
StoryblokStep
} from "@tvg/sh-lib-promos-onboarding/types/storyblok";
import PromoPreviewTemplate from "@tvg/atomic-ui/_templates/PromoPreview";
import { ComponentPreview } from "./types";
import { formatPreviewComponents } from "./helpers/formatPreviewComponents";
import { PreviewProps } from "../sharedComponentTypes";
export const PromoPreviewComponent = ({
previewContentId = ""
}: PreviewProps) => {
const [shouldFetchStoryblok, setShouldFetchStoryblok] = useState(true);
const [previewSteps, setPreviewSteps] = useState<StoryblokStep[]>([]);
const [previewComponents, setPreviewComponents] = useState<
ComponentPreview[][]
>([]);
useEffect(() => {
if (shouldFetchStoryblok) {
fetchStoryblok(+previewContentId, StoryblokVersion.DRAFT)
.then((response) => {
const steps: Array<StoryblokStep> = get(
response,
"data.story.content.steps",
[]
);
setPreviewSteps(steps);
setShouldFetchStoryblok(false);
})
.catch((error) => {
// eslint-disable-next-line no-console
console.error(error);
});
}
}, [previewContentId, shouldFetchStoryblok]);
useEffect(() => {
const formattedPreviewComponents = formatPreviewComponents(previewSteps);
setPreviewComponents(formattedPreviewComponents);
}, [previewSteps]);
return (
<PromoPreviewTemplate
steps={previewSteps}
components={previewComponents}
refetchStoryblok={() => {
setShouldFetchStoryblok(true);
}}
/>
);
};
export default PromoPreviewComponent;
webpack://frontend-mybets/../../packages/tvg-comp-promos-onboarding/src/components/preview/helpers/formatPreviewComponents.ts
import { get } from "lodash";
import { getStoryblokComponent } from "@tvg/sh-lib-promos-onboarding/utils/getStoryblokComponent";
import { formatStoryblokProps } from "@tvg/sh-lib-promos-onboarding/helpers/formatStoryblokProps";
import {
StoryblokStep,
StoryblokComponentPropsFormatted
} from "@tvg/sh-lib-promos-onboarding/types/storyblok";
import { ComponentPreview } from "../types";
export const formatPreviewComponents = (steps: StoryblokStep[]) => {
const componentsByStep: ComponentPreview[][] = [];
steps.forEach((step, index) => {
const componentsInCurrentStep = get(step, "messages", []);
componentsInCurrentStep.forEach((currentComponent) => {
const { component, ...rest } = get(
currentComponent,
"promo_component[0]",
{}
);
const props = formatStoryblokProps(rest);
const formattedComponent: StoryblokComponentPropsFormatted = {
component,
props
};
const currentRenderedComponent =
getStoryblokComponent(formattedComponent);
const renderPlaces = get(
currentComponent,
"render_place[0].places",
[]
).reduce(
(places: string, currentPlace: string) =>
`${places ? places + ", " : ""}${currentPlace}`,
""
);
if (!get(componentsByStep, index)) {
componentsByStep[+index] = [];
}
componentsByStep[+index].push({
component: currentRenderedComponent,
renderPlaces
});
});
});
return componentsByStep;
};
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/PromoProgress/styled-components.ts
import styled, { css, FlattenSimpleInterpolation } from "styled-components";
import { buildColor } from "@tvg/design-system";
import { Device } from "@tvg/ts-types/Device";
const getPromoProgressContainerStyle = (
device: Device,
isHomePageSection: boolean
): FlattenSimpleInterpolation => {
let styles: FlattenSimpleInterpolation;
if (device === Device.MOBILE) {
styles = css`
flex-direction: column;
padding: 12px;
`;
} else {
styles = css`
flex-direction: row;
padding: 20px;
justify-content: space-between;
align-items: center;
`;
}
if (isHomePageSection) {
styles =
device === Device.DESKTOP
? css`
${styles};
border-bottom: 1px solid ${buildColor("blue", "100")};
`
: css`
${styles};
margin-bottom: 8px;
`;
}
return styles;
};
export const PromoProgressContainer = styled.div<{
device: Device;
isDarkMode?: boolean;
isHomePageSection?: boolean;
}>`
display: flex;
flex: 1;
background-color: ${({ isDarkMode }) =>
isDarkMode ? buildColor("blue", "800") : buildColor("blue_accent", "000")};
${({ device, isHomePageSection }) =>
getPromoProgressContainerStyle(device, !!isHomePageSection)};
`;
export const InfoContainer = styled.div<{
device?: Device;
}>`
display: flex;
flex-wrap: wrap;
justify-content: space-between;
${({ device }) =>
device !== Device.MOBILE &&
css`
flex-direction: column;
margin-right: 20px;
width: 25%;
`}
`;
export const HeaderContainer = styled.div<{
device?: Device;
}>`
${({ device }) =>
device !== Device.MOBILE
? css`
flex: 0;
order: 0;
`
: css`
flex: 50%;
`};
`;
export const DaysContainer = styled.div<{
device?: Device;
}>`
display: flex;
${({ device }) =>
device !== Device.MOBILE
? css`
flex: 0;
order: 2;
margin-top: 8px;
justify-content: start;
`
: css`
flex: 50%;
justify-content: flex-end;
`}
`;
export const DetailsContainer = styled.div<{
device?: Device;
}>`
margin-top: 2px;
flex: 100%;
${({ device }) =>
device !== Device.MOBILE &&
css`
order: 1;
`}
`;
export const ProgressBarContainer = styled.div<{
device?: Device;
}>`
flex: 1;
${({ device }) =>
device === Device.MOBILE &&
css`
margin-bottom: 12px;
`}
`;
export const ButtonContainer = styled.div<{
device?: Device;
}>`
${({ device }) =>
device !== Device.MOBILE &&
css`
min-width: 112px;
margin-left: 20px;
`}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/PromoProgress/index.tsx
import React from "react";
import { Button, ProgressBar, Header, Paragraph } from "@tvg/design-system";
import { noop } from "lodash";
import { Device } from "@tvg/ts-types/Device";
import {
PromoProgressContainer,
InfoContainer,
HeaderContainer,
DaysContainer,
DetailsContainer,
ProgressBarContainer,
ButtonContainer
} from "./styled-components";
import { Props } from "./types";
export const PromoProgress = ({
qaLabel = "promoProgress",
CTALabel = "",
onCTAPress = noop,
promoDescription = "",
progressBarIcon = "$",
progressBarSteps = [],
completedSteps = 0,
promoTitle = "",
showRemainingDays = false,
remainingDays = 0,
CTAShow = true,
isDarkMode = false,
device = Device.MOBILE,
isHomePageSection = false
}: Props) => (
<PromoProgressContainer
data-qa-label={qaLabel}
isDarkMode={isDarkMode}
isHomePageSection={isHomePageSection}
device={device}
>
<InfoContainer device={device}>
<HeaderContainer device={device}>
<Header
qaLabel="promoProgressTitle"
tag="h2"
color={isDarkMode ? "white.900" : "blue.600"}
mb="space-1"
fontFamily="bold"
>
{promoTitle}
</Header>
</HeaderContainer>
{showRemainingDays && !!remainingDays && (
<DaysContainer device={device}>
<Paragraph
qaLabel="promoProgressRemainDays"
color={isDarkMode ? "blue_accent.200" : "blue_accent.500"}
textTransform="uppercase"
fontSize="xs"
fontFamily="condensedRegular"
>
{`${remainingDays} Days left`}
</Paragraph>
</DaysContainer>
)}
<DetailsContainer>
<Paragraph
qaLabel="promoProgressDescription"
color={isDarkMode ? "blue_accent.200" : "grey.800"}
mb="space-1"
>
{promoDescription}
</Paragraph>
</DetailsContainer>
</InfoContainer>
<ProgressBarContainer device={device}>
<ProgressBar
completedSteps={completedSteps}
icon={progressBarIcon}
isDarkMode={isDarkMode}
>
{progressBarSteps.map((description) => (
<ProgressBar.Step
key={description}
stepDescription={description}
qaLabel={`progress-bar-step-${description.toLowerCase()}`}
/>
))}
</ProgressBar>
</ProgressBarContainer>
{CTAShow && CTALabel && typeof onCTAPress === "function" && (
<ButtonContainer device={device}>
<Button
qaLabel="promoProgressCTA"
onPress={onCTAPress}
variant="primary"
isStretched
>
{CTALabel}
</Button>
</ButtonContainer>
)}
</PromoProgressContainer>
);
export default PromoProgress;
webpack://frontend-mybets/../../packages/tvg-comp-promos-onboarding/src/utils/gtm.ts
import mediator from "@tvg/mediator";
export const promoOnboardingCTAClickGTM = (
linkLabel: string,
promoId?: number,
promoName?: string
) =>
mediator.base.dispatch({
type: "PROMOS_ONBOARDING:CTA_CLICK",
payload: {
link: linkLabel,
promoId,
promoName
}
});
webpack://frontend-mybets/../../packages/tvg-comp-promos-onboarding/src/components/progress/constraints/promoCTA.ts
import { noop } from "lodash";
import { PromoCTA } from "../types";
export const defaultCTA: PromoCTA = {
CTALabel: "",
onCTAPress: noop,
CTAShow: false
};
webpack://frontend-mybets/../../packages/tvg-lib-utils/routeRedirectUtils.ts
import mediator from "@tvg/mediator";
import { isTvg5 } from "@tvg/utils/generalUtils";
import buildRaceUrl from "@tvg/formatter/url";
import { History } from "@tvg/ts-types/History";
export const genericRedirect = (
history: History,
route: string,
isDesktop = false,
event = ""
) => {
const { location } = history;
if (location && location.pathname === route) {
return;
}
if (!isDesktop || isTvg5()) {
history.push(route);
} else {
mediator.base.dispatch({
type: "TVG4_NAVIGATION",
payload: { route, event }
});
}
};
export const goToWallet = (history: History, isDesktop = false) => {
genericRedirect(history, "/wallet", isDesktop, "Wallet");
};
export const goToTracksPage = (history: History, isDesktop = false) => {
genericRedirect(history, "/races", isDesktop, "Races");
};
export const goToProgramPage = (
history: History,
trackCode: string,
trackName: string,
raceNumber: number,
isGreyHound: boolean,
isDesktop = false
) => {
genericRedirect(
history,
buildRaceUrl(trackCode, trackName, raceNumber, isGreyHound),
isDesktop,
"Program Page"
);
};
export const hasRoutePath = (path: string, config: Array<{ path: string }>) =>
config.some((route) => {
if (route.path === "*") {
return false;
}
if (route.path === path) {
return true;
}
const regexPattern = new RegExp(
// eslint-disable-next-line no-useless-escape
`^${route.path.replace(/:[^\/]+/g, "[^/]+")}$`
);
return regexPattern.test(path);
});
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/utils/checkOnboardingPromoAvailable.ts
import { get } from "lodash";
import {
PromoMappedSteps,
PromoStepType,
PromoStepWagerStatus
} from "../types/promoSteps";
export const checkOnboardingPromoAvailable = (
steps: PromoMappedSteps
): boolean => {
const wagerStep = get(steps, PromoStepType.WAGER);
const payoutStep = get(steps, `${PromoStepType.PAYOUT}.timestamp`);
const wagerStatus = get(steps, `${PromoStepType.WAGER}.wagerStatus`);
const depositDate = get(steps, `${PromoStepType.DEPOSIT}.depositDate`);
return wagerStep
? !payoutStep && wagerStatus !== PromoStepWagerStatus.WIN
: !payoutStep && !depositDate;
};
webpack://frontend-mybets/../../packages/tvg-comp-promos-onboarding/src/components/progress/constraints/promoCurrentStatus.ts
import { PromoCurrentStatus } from "../types";
import { defaultCTA } from "./promoCTA";
export const defaultStatus: PromoCurrentStatus = {
...defaultCTA,
promoDescription: "",
progressBarIcon: "$",
progressBarSteps: [],
completedSteps: 0,
promoTitle: "",
remainingDays: 0,
showRemainingDays: true
};
webpack://frontend-mybets/../../packages/tvg-comp-promos-onboarding/src/components/progress/helpers/formatPromoCurrentStatus.ts
import { History } from "@tvg/ts-types/History";
import { mathPercentageFormatted } from "@tvg/utils/mathUtils";
import { get, has } from "lodash";
import {
PromoMappedSteps,
PromoOnboardingStep,
PromoStepDescriptions,
PromoStepType,
PromoStepWagerStatus
} from "@tvg/sh-lib-promos-onboarding/types/promoSteps";
import { PromoOnboarding } from "@tvg/sh-lib-promos-onboarding/types/promoOnboarding";
import tvgConf from "@tvg/conf";
import { PromoCurrentStatus } from "../types";
import { getCTA } from "../utils/getPromoCTA";
import { getPromoDescription } from "../utils/getPromoDescription";
import { getPromoStepsLabel } from "../utils/getPromoStepsLabel";
import { getCompletedSteps } from "../utils/getCompletedSteps";
import { defaultStatus } from "../constraints/promoCurrentStatus";
export const formatPromoCurrentStatus = (
storyblokPromos: PromoOnboarding,
history: History
): PromoCurrentStatus | null => {
const isDesktop = tvgConf().device === "desktop";
const promoSteps: PromoMappedSteps = get(
storyblokPromos,
"steps",
{} as PromoMappedSteps
);
const hasPromoPayoutStep = has(promoSteps, `${PromoStepType.PAYOUT}.@type`);
const currentStepType = hasPromoPayoutStep
? PromoStepType.PAYOUT
: get(storyblokPromos, "currentStepType");
const currentStep: PromoOnboardingStep | null = get(
promoSteps,
currentStepType,
null
);
if (!currentStep) {
return null;
}
const stepDescription: PromoStepDescriptions = get(
currentStep,
`description`,
{} as PromoStepDescriptions
);
const stepIsFulfilled = get(currentStep, `isFulfilled`, false);
const CTA = getCTA(
currentStepType,
stepIsFulfilled,
currentStep,
history,
isDesktop
);
const wagerStatus = get(currentStep, "wagerStatus");
const promoRedeem =
wagerStatus && wagerStatus !== PromoStepWagerStatus.PLACED;
const promoDescription = getPromoDescription(
stepDescription,
storyblokPromos,
currentStep
);
const progressBarSteps = ["Register", ...getPromoStepsLabel(promoSteps)];
const completedSteps = getCompletedSteps(
get(storyblokPromos, "completedSteps", 0),
promoRedeem ? PromoStepType.PAYOUT : currentStepType,
stepIsFulfilled || promoRedeem
);
const promoTitle =
currentStepType === PromoStepType.PAYOUT && stepIsFulfilled
? "Promotion Redeemed"
: `${mathPercentageFormatted(
progressBarSteps.length,
completedSteps
)} Complete`;
const remainingDays = get(storyblokPromos, "remainingDays", 0);
return {
...defaultStatus,
...CTA,
promoDescription,
progressBarSteps,
completedSteps,
promoTitle,
remainingDays,
showRemainingDays: !promoRedeem && currentStepType !== PromoStepType.PAYOUT
};
};
export default formatPromoCurrentStatus;
webpack://frontend-mybets/../../packages/tvg-comp-promos-onboarding/src/components/progress/utils/getPromoCTA.ts
import { History } from "@tvg/ts-types/History";
import {
PromoOnboardingStep,
PromoStepType,
WagerStep
} from "@tvg/sh-lib-promos-onboarding/types/promoSteps";
import { PromoCTA } from "../types";
import { defaultCTA } from "../constraints/promoCTA";
import { getDepositCTA } from "./CTA/getDepositCTA";
import { getBetCTA } from "./CTA/getBetCTA";
import { getWatchLiveCTA } from "./CTA/getWatchLiveCTA";
export const getCTA = (
stepType: PromoStepType,
isFulfilled: boolean,
promoOnboardingStep: PromoOnboardingStep,
history: History,
isDesktop: boolean
): PromoCTA => {
switch (stepType) {
case PromoStepType.DEPOSIT:
return getDepositCTA(isFulfilled, history, isDesktop);
case PromoStepType.WAGER:
if (isFulfilled) {
return getWatchLiveCTA(
history,
promoOnboardingStep as WagerStep,
isDesktop
);
}
return getBetCTA(history, isDesktop);
default:
return defaultCTA;
}
};
webpack://frontend-mybets/../../packages/tvg-comp-promos-onboarding/src/components/progress/utils/CTA/getDepositCTA.ts
import { History } from "@tvg/ts-types/History";
import { goToWallet } from "@tvg/utils/routeRedirectUtils";
import { PromoCTA } from "../../types";
export const getDepositCTA = (
isFulfilled: boolean,
history: History,
isDesktop: boolean
) =>
({
CTALabel: "Deposit Now",
onCTAPress: () => {
goToWallet(history, isDesktop);
},
CTAShow: !isFulfilled
}) as PromoCTA;
webpack://frontend-mybets/../../packages/tvg-comp-promos-onboarding/src/components/progress/utils/CTA/getWatchLiveCTA.ts
import { History } from "@tvg/ts-types/History";
import {
PromoStepWagerStatus,
WagerStep
} from "@tvg/sh-lib-promos-onboarding/types/promoSteps";
import { goToProgramPage } from "@tvg/utils/routeRedirectUtils";
import { PromoCTA } from "../../types";
export const getWatchLiveCTA = (
history: History,
promoOnboardingStep: WagerStep,
isDesktop: boolean
) => {
const { trackCode, trackName, raceNumber, isGreyHound, wagerStatus } =
promoOnboardingStep;
return {
CTALabel: "Watch Live",
onCTAPress: () => {
if (trackCode && trackName && raceNumber) {
goToProgramPage(
history,
trackCode,
trackName,
raceNumber,
!!isGreyHound,
isDesktop
);
}
},
CTAShow: wagerStatus === PromoStepWagerStatus.PLACED
} as PromoCTA;
};
webpack://frontend-mybets/../../packages/tvg-comp-promos-onboarding/src/components/progress/utils/CTA/getBetCTA.ts
import { History } from "@tvg/ts-types/History";
import { goToTracksPage } from "@tvg/utils/routeRedirectUtils";
import { PromoCTA } from "../../types";
export const getBetCTA = (history: History, isDesktop: boolean) =>
({
CTALabel: "Bet Now",
onCTAPress: () => {
goToTracksPage(history, isDesktop);
},
CTAShow: true
}) as PromoCTA;
webpack://frontend-mybets/../../packages/tvg-comp-promos-onboarding/src/components/progress/utils/getPromoDescription.ts
import { get } from "lodash";
import {
PromoOnboardingStep,
PromoStepDescriptionKey,
PromoStepDescriptions,
PromoStepType,
PromoStepWagerStatus
} from "@tvg/sh-lib-promos-onboarding/types/promoSteps";
import { formatStoryblokText } from "@tvg/sh-lib-promos-onboarding/helpers/formatStoryblokText";
import { PromoOnboarding } from "@tvg/sh-lib-promos-onboarding/types/promoOnboarding";
import { checkOnboardingPromoAvailable } from "@tvg/sh-lib-promos-onboarding/utils/checkOnboardingPromoAvailable";
const getPromoFinishedDescriptionsKey = (
wagerStatus?: PromoStepWagerStatus
): PromoStepDescriptionKey => {
switch (wagerStatus) {
case PromoStepWagerStatus.WIN: {
return PromoStepDescriptionKey.WIN;
}
case PromoStepWagerStatus.LOST: {
return PromoStepDescriptionKey.LOSS;
}
default: {
return PromoStepDescriptionKey.DEFAULT;
}
}
};
const getPromoAvailableDescriptionKey = (
wagerStatus?: PromoStepWagerStatus
): PromoStepDescriptionKey =>
wagerStatus && wagerStatus === PromoStepWagerStatus.PLACED
? PromoStepDescriptionKey.PROCESSING
: PromoStepDescriptionKey.DEFAULT;
export const getPromoDescription = (
messages: PromoStepDescriptions,
promoOnboarding: PromoOnboarding,
currentStep: PromoOnboardingStep
): string => {
const defaultText = get(messages, "default", "");
const promoSteps = get(promoOnboarding, "steps", {});
const wagerStatus = get(promoSteps, `${PromoStepType.WAGER}.wagerStatus`);
const promoAvailable = checkOnboardingPromoAvailable(promoSteps);
const messageKey = promoAvailable
? getPromoAvailableDescriptionKey(wagerStatus)
: getPromoFinishedDescriptionsKey(wagerStatus);
const description = get(messages, messageKey, "");
return formatStoryblokText(
description || defaultText,
promoOnboarding,
currentStep
);
};
webpack://frontend-mybets/../../packages/tvg-comp-promos-onboarding/src/components/progress/utils/getPromoStepsLabel.ts
import {
PromoMappedSteps,
PromoStepType
} from "@tvg/sh-lib-promos-onboarding/types/promoSteps";
export const getPromoStepsLabel = (
promoSteps: PromoMappedSteps
): Array<string> =>
(Object.keys(promoSteps) as Array<PromoStepType>).reduce((steps, step) => {
let label = "";
switch (step) {
case PromoStepType.DEPOSIT:
label = "Deposit";
break;
case PromoStepType.WAGER:
label = "Wager";
break;
default:
return steps;
}
return [...steps, label];
}, [] as Array<string>);
webpack://frontend-mybets/../../packages/tvg-comp-promos-onboarding/src/components/progress/utils/getCompletedSteps.ts
import { PromoStepType } from "@tvg/sh-lib-promos-onboarding/types/promoSteps";
// Those vars is to make offset registration and payout step because this step is only on FE side.
export const OFFSET_REGISTRATION_STEP = 1;
export const OFFSET_PAYOUT_STEP = 2;
export const getCompletedSteps = (
completedSteps: number,
currentStepType: PromoStepType,
isFulfilled: boolean
) =>
currentStepType === PromoStepType.PAYOUT && isFulfilled
? completedSteps + OFFSET_PAYOUT_STEP
: completedSteps + OFFSET_REGISTRATION_STEP;
webpack://frontend-mybets/../../packages/tvg-lib-utils/mathUtils.ts
export const mathPercentage = (total: number, done: number) =>
total > 0 ? (100 * done) / total : 0;
export const mathClamp = (value: number, min: number, max: number) =>
Math.min(Math.max(value, min), max);
export const mathPercentageFormatted = (
total: number,
done: number,
fractionDigits: number = 0
) => {
const percentage = mathClamp(mathPercentage(total, done), 0, 100);
const percentageFixed =
fractionDigits > 0
? percentage.toFixed(fractionDigits)
: Math.floor(percentage);
return `${percentageFixed}%`;
};
webpack://frontend-mybets/../../packages/tvg-comp-promos-onboarding/src/components/progress/index.tsx
import React, { useCallback, useMemo } from "react";
import { useSelector } from "react-redux";
import PromoProgress from "@tvg/atomic-ui/_molecule/PromoProgress";
import { getStoryblokPromos } from "@tvg/sh-lib-promos-onboarding/redux/selectors";
import { useNavigate } from "@tvg/custom-hooks";
import { Device } from "@tvg/ts-types/Device";
import { promoOnboardingCTAClickGTM } from "../../utils/gtm";
import { useCurrentProgress } from "./hooks/useCurrentProgress";
import { ProgressProps } from "../sharedComponentTypes";
export const PromoProgressComponent = ({
device = Device.MOBILE,
isDarkMode = false,
isHomePageSection = false
}: ProgressProps) => {
const history = useNavigate();
const storyblokPromos = useSelector(getStoryblokPromos);
const promoCurrentStatus = useCurrentProgress(history, storyblokPromos);
const handleCTA = useCallback(() => {
if (typeof promoCurrentStatus?.onCTAPress === "function") {
promoCurrentStatus.onCTAPress();
promoOnboardingCTAClickGTM(
promoCurrentStatus.CTALabel,
storyblokPromos.promotionId,
storyblokPromos.promoName
);
}
}, [promoCurrentStatus, storyblokPromos]);
return useMemo(
() =>
promoCurrentStatus && (
<PromoProgress
{...promoCurrentStatus}
device={device}
onCTAPress={handleCTA}
isDarkMode={isDarkMode}
isHomePageSection={isHomePageSection}
/>
),
[promoCurrentStatus, storyblokPromos]
);
};
export default PromoProgressComponent;
webpack://frontend-mybets/../../packages/tvg-comp-promos-onboarding/src/components/progress/hooks/useCurrentProgress.ts
import { useEffect, useState } from "react";
import { History } from "@tvg/ts-types/History";
import { PromoOnboarding } from "@tvg/sh-lib-promos-onboarding/types/promoOnboarding";
import { PromoCurrentStatus } from "../types";
import { formatPromoCurrentStatus } from "../helpers/formatPromoCurrentStatus";
export const useCurrentProgress = (
history: History,
storyblokPromos: PromoOnboarding | null
) => {
const [promoCurrentStatus, setPromoCurrentStatus] =
useState<PromoCurrentStatus | null>(null);
useEffect(() => {
if (storyblokPromos) {
setPromoCurrentStatus(formatPromoCurrentStatus(storyblokPromos, history));
} else {
setPromoCurrentStatus(null);
}
}, [storyblokPromos]);
return promoCurrentStatus;
};
webpack://frontend-mybets/../../packages/tvg-comp-promos-onboarding/src/types.ts
import { StoryblokPlaceName } from "@tvg/sh-lib-promos-onboarding/types/promoOnboardingComponents";
import { Device } from "@tvg/ts-types/Device";
export interface Props {
placeToRender: StoryblokPlaceName;
componentName: InternalComponentNames;
isInternalComponent: boolean;
isDarkMode: boolean;
shouldUpdate: boolean;
device: Device;
isShown: boolean;
isHomePageSection: boolean;
previewContentId: string;
customMessage?: string;
}
export enum InternalComponentNames {
PROGRESS = "progress",
PREVIEW = "preview",
UNKNOWN = ""
}
webpack://frontend-mybets/../../packages/tvg-comp-promos-onboarding/src/utils/getInternalComponent.ts
import { createElement } from "react";
import { Device } from "@tvg/ts-types/Device";
import PromoPreviewComponent from "../components/preview";
import PromoProgressComponent from "../components/progress";
import { InternalComponentNames } from "../types";
import {
GenericProps,
PreviewProps,
ProgressProps
} from "../components/sharedComponentTypes";
export const getInternalComponent = (
componentName: InternalComponentNames,
device: Device = Device.MOBILE,
options: Partial<GenericProps> = {}
) => {
switch (componentName) {
case InternalComponentNames.PROGRESS: {
const { isDarkMode, isHomePageSection } = options as ProgressProps;
return createElement(PromoProgressComponent, {
isDarkMode: !!isDarkMode,
device,
isHomePageSection: !!isHomePageSection
});
}
case InternalComponentNames.PREVIEW: {
const { previewContentId } = options as PreviewProps;
return createElement(PromoPreviewComponent, {
previewContentId
});
}
default: {
return null;
}
}
};
export default getInternalComponent;
webpack://frontend-mybets/../../packages/tvg-comp-promos-onboarding/src/index.tsx
import { useSelector } from "react-redux";
import { Store } from "redux";
import {
getPromosOnboardingToggle,
getStoryblokCurrentStep,
getStoryblokPromoByPlace,
getStoryblokPromos
} from "@tvg/sh-lib-promos-onboarding/redux/selectors";
import { usePromosOnboardingComponent } from "@tvg/sh-lib-promos-onboarding/hooks/usePromosOnboardingComponent";
import { StoryblokPlaceName } from "@tvg/sh-lib-promos-onboarding/types/promoOnboardingComponents";
import tvgConf from "@tvg/conf";
import getInternalComponent from "./utils/getInternalComponent";
import { InternalComponentNames, Props } from "./types";
const PromosOnboarding = ({
placeToRender = StoryblokPlaceName.UNKNOWN,
isInternalComponent = false,
componentName = InternalComponentNames.UNKNOWN,
isDarkMode = false,
device,
isShown = true,
isHomePageSection = false,
previewContentId = "",
customMessage = ""
}: Partial<Props>) => {
const storyblokPromo = useSelector((store: Store) =>
placeToRender ? getStoryblokPromoByPlace(store, placeToRender) : null
);
const promoObject = useSelector((store: Store) => getStoryblokPromos(store));
const promoCurrentStep = useSelector((store: Store) =>
getStoryblokCurrentStep(store)
);
const promosOnboardingToggle = useSelector(getPromosOnboardingToggle);
const promoOnboardingComponent = !isInternalComponent
? usePromosOnboardingComponent(
storyblokPromo,
promoObject,
promoCurrentStep,
customMessage
)
: null;
if (!promosOnboardingToggle || !isShown) {
return null;
}
return isInternalComponent
? getInternalComponent(componentName, device || tvgConf().device, {
isDarkMode,
isHomePageSection,
previewContentId
})
: promoOnboardingComponent;
};
export default PromosOnboarding;
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/helpers/formatComponentWithDynamicVariables.ts
import { get } from "lodash";
import { PromoOnboarding } from "../types/promoOnboarding";
import { StorybookAvailableComponents } from "../types/promoOnboardingComponents";
import { PromoOnboardingStep } from "../types/promoSteps";
import { StoryblokComponentPropsFormatted } from "../types/storyblok";
import { formatStoryblokText } from "./formatStoryblokText";
export const formatComponentWithDynamicVariables = (
promoOnboardingComponent: StoryblokComponentPropsFormatted,
promo: PromoOnboarding,
currentStep: PromoOnboardingStep
): StoryblokComponentPropsFormatted => {
const formattedProps = Object.entries(
get(promoOnboardingComponent, "props", {})
).reduce((acc: StorybookAvailableComponents, [key, value]) => {
if (typeof value === "string") {
return {
...acc,
[key]: formatStoryblokText(value, promo, currentStep)
};
}
return { ...acc };
}, {});
return {
...promoOnboardingComponent,
props: formattedProps
} as StoryblokComponentPropsFormatted;
};
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/utils/matchPlacedWager.ts
import { get } from "lodash";
import { WagerStep } from "../types/promoSteps";
import type { MyBetsWager } from "../types/wager";
export const validateSerialNumber = (
promoSerialNumber: string,
wagerSerialNumber: string
) =>
!!promoSerialNumber && promoSerialNumber.trim() === wagerSerialNumber.trim();
export const matchPlacedWager = (
step: WagerStep,
wager: Partial<MyBetsWager>
) => {
const promoSerialNumber = get(step, "serialNumber", "");
const wagerSerialNumber = get(wager, "serialNumber", "");
return validateSerialNumber(promoSerialNumber, wagerSerialNumber);
};
webpack://frontend-mybets/../../node_modules/@amplitude/analytics-connector/dist/analytics-connector.esm.js
var ApplicationContextProviderImpl = /** @class */ (function () {
function ApplicationContextProviderImpl() {
}
ApplicationContextProviderImpl.prototype.getApplicationContext = function () {
return {
versionName: this.versionName,
language: getLanguage(),
platform: 'Web',
os: undefined,
deviceModel: undefined,
};
};
return ApplicationContextProviderImpl;
}());
var getLanguage = function () {
return ((typeof navigator !== 'undefined' &&
((navigator.languages && navigator.languages[0]) ||
navigator.language)) ||
'');
};
var EventBridgeImpl = /** @class */ (function () {
function EventBridgeImpl() {
this.queue = [];
}
EventBridgeImpl.prototype.logEvent = function (event) {
if (!this.receiver) {
if (this.queue.length < 512) {
this.queue.push(event);
}
}
else {
this.receiver(event);
}
};
EventBridgeImpl.prototype.setEventReceiver = function (receiver) {
this.receiver = receiver;
if (this.queue.length > 0) {
this.queue.forEach(function (event) {
receiver(event);
});
this.queue = [];
}
};
return EventBridgeImpl;
}());
/******************************************************************************
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.
***************************************************************************** */
var __assign = function () {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var isEqual = function (obj1, obj2) {
var primitive = ['string', 'number', 'boolean', 'undefined'];
var typeA = typeof obj1;
var typeB = typeof obj2;
if (typeA !== typeB) {
return false;
}
for (var _i = 0, primitive_1 = primitive; _i < primitive_1.length; _i++) {
var p = primitive_1[_i];
if (p === typeA) {
return obj1 === obj2;
}
}
// check null
if (obj1 == null && obj2 == null) {
return true;
}
else if (obj1 == null || obj2 == null) {
return false;
}
// if got here - objects
if (obj1.length !== obj2.length) {
return false;
}
//check if arrays
var isArrayA = Array.isArray(obj1);
var isArrayB = Array.isArray(obj2);
if (isArrayA !== isArrayB) {
return false;
}
if (isArrayA && isArrayB) {
//arrays
for (var i = 0; i < obj1.length; i++) {
if (!isEqual(obj1[i], obj2[i])) {
return false;
}
}
}
else {
//objects
var sorted1 = Object.keys(obj1).sort();
var sorted2 = Object.keys(obj2).sort();
if (!isEqual(sorted1, sorted2)) {
return false;
}
//compare object values
var result_1 = true;
Object.keys(obj1).forEach(function (key) {
if (!isEqual(obj1[key], obj2[key])) {
result_1 = false;
}
});
return result_1;
}
return true;
};
var ID_OP_SET = '$set';
var ID_OP_UNSET = '$unset';
var ID_OP_CLEAR_ALL = '$clearAll';
// Polyfill for Object.entries
if (!Object.entries) {
Object.entries = function (obj) {
var ownProps = Object.keys(obj);
var i = ownProps.length;
var resArray = new Array(i);
while (i--) {
resArray[i] = [ownProps[i], obj[ownProps[i]]];
}
return resArray;
};
}
var IdentityStoreImpl = /** @class */ (function () {
function IdentityStoreImpl() {
this.identity = { userProperties: {} };
this.listeners = new Set();
}
IdentityStoreImpl.prototype.editIdentity = function () {
// eslint-disable-next-line @typescript-eslint/no-this-alias
var self = this;
var actingUserProperties = __assign({}, this.identity.userProperties);
var actingIdentity = __assign(__assign({}, this.identity), { userProperties: actingUserProperties });
return {
setUserId: function (userId) {
actingIdentity.userId = userId;
return this;
},
setDeviceId: function (deviceId) {
actingIdentity.deviceId = deviceId;
return this;
},
setUserProperties: function (userProperties) {
actingIdentity.userProperties = userProperties;
return this;
},
setOptOut: function (optOut) {
actingIdentity.optOut = optOut;
return this;
},
updateUserProperties: function (actions) {
var actingProperties = actingIdentity.userProperties || {};
for (var _i = 0, _a = Object.entries(actions); _i < _a.length; _i++) {
var _b = _a[_i], action = _b[0], properties = _b[1];
switch (action) {
case ID_OP_SET:
for (var _c = 0, _d = Object.entries(properties); _c < _d.length; _c++) {
var _e = _d[_c], key = _e[0], value = _e[1];
actingProperties[key] = value;
}
break;
case ID_OP_UNSET:
for (var _f = 0, _g = Object.keys(properties); _f < _g.length; _f++) {
var key = _g[_f];
delete actingProperties[key];
}
break;
case ID_OP_CLEAR_ALL:
actingProperties = {};
break;
}
}
actingIdentity.userProperties = actingProperties;
return this;
},
commit: function () {
self.setIdentity(actingIdentity);
return this;
},
};
};
IdentityStoreImpl.prototype.getIdentity = function () {
return __assign({}, this.identity);
};
IdentityStoreImpl.prototype.setIdentity = function (identity) {
var originalIdentity = __assign({}, this.identity);
this.identity = __assign({}, identity);
if (!isEqual(originalIdentity, this.identity)) {
this.listeners.forEach(function (listener) {
listener(identity);
});
}
};
IdentityStoreImpl.prototype.addIdentityListener = function (listener) {
this.listeners.add(listener);
};
IdentityStoreImpl.prototype.removeIdentityListener = function (listener) {
this.listeners.delete(listener);
};
return IdentityStoreImpl;
}());
var safeGlobal = typeof globalThis !== 'undefined'
? globalThis
: typeof global !== 'undefined'
? global
: self;
var AnalyticsConnector = /** @class */ (function () {
function AnalyticsConnector() {
this.identityStore = new IdentityStoreImpl();
this.eventBridge = new EventBridgeImpl();
this.applicationContextProvider = new ApplicationContextProviderImpl();
}
AnalyticsConnector.getInstance = function (instanceName) {
if (!safeGlobal['analyticsConnectorInstances']) {
safeGlobal['analyticsConnectorInstances'] = {};
}
if (!safeGlobal['analyticsConnectorInstances'][instanceName]) {
safeGlobal['analyticsConnectorInstances'][instanceName] =
new AnalyticsConnector();
}
return safeGlobal['analyticsConnectorInstances'][instanceName];
};
return AnalyticsConnector;
}());
export { AnalyticsConnector };
webpack://frontend-mybets/../../node_modules/@amplitude/experiment-core/dist/experiment-core.esm.js
/******************************************************************************
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.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol */
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function (d, b) {
d.__proto__ = b;
} || function (d, b) {
for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
};
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function () {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function (resolve) {
resolve(value);
});
}
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e) {
reject(e);
}
}
function step(result) {
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = {
label: 0,
sent: function () {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
},
f,
y,
t,
g;
return g = {
next: verb(0),
"throw": verb(1),
"return": verb(2)
}, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
return this;
}), g;
function verb(n) {
return function (v) {
return step([n, v]);
};
}
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return {
value: op[1],
done: false
};
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2]) _.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [6, e];
y = 0;
} finally {
f = t = 0;
}
if (op[0] & 5) throw op[1];
return {
value: op[0] ? op[1] : void 0,
done: true
};
}
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator,
m = s && o[s],
i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return {
value: o && o[i++],
done: !o
};
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o),
r,
ar = [],
e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
} catch (error) {
e = {
error: error
};
} finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
} finally {
if (e) throw e.error;
}
}
return ar;
}
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
var EvaluationOperator = {
IS: 'is',
IS_NOT: 'is not',
CONTAINS: 'contains',
DOES_NOT_CONTAIN: 'does not contain',
LESS_THAN: 'less',
LESS_THAN_EQUALS: 'less or equal',
GREATER_THAN: 'greater',
GREATER_THAN_EQUALS: 'greater or equal',
VERSION_LESS_THAN: 'version less',
VERSION_LESS_THAN_EQUALS: 'version less or equal',
VERSION_GREATER_THAN: 'version greater',
VERSION_GREATER_THAN_EQUALS: 'version greater or equal',
SET_IS: 'set is',
SET_IS_NOT: 'set is not',
SET_CONTAINS: 'set contains',
SET_DOES_NOT_CONTAIN: 'set does not contain',
SET_CONTAINS_ANY: 'set contains any',
SET_DOES_NOT_CONTAIN_ANY: 'set does not contain any',
REGEX_MATCH: 'regex match',
REGEX_DOES_NOT_MATCH: 'regex does not match',
};
var stringToUtf8ByteArray = function (str) {
var out = [];
var p = 0;
for (var i = 0; i < str.length; i++) {
var c = str.charCodeAt(i);
if (c < 128) {
out[p++] = c;
}
else if (c < 2048) {
out[p++] = (c >> 6) | 192;
out[p++] = (c & 63) | 128;
}
else if ((c & 0xfc00) == 0xd800 &&
i + 1 < str.length &&
(str.charCodeAt(i + 1) & 0xfc00) == 0xdc00) {
// Surrogate Pair
c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);
out[p++] = (c >> 18) | 240;
out[p++] = ((c >> 12) & 63) | 128;
out[p++] = ((c >> 6) & 63) | 128;
out[p++] = (c & 63) | 128;
}
else {
out[p++] = (c >> 12) | 224;
out[p++] = ((c >> 6) & 63) | 128;
out[p++] = (c & 63) | 128;
}
}
return Uint8Array.from(out);
};
var C1_32 = -0x3361d2af;
var C2_32 = 0x1b873593;
var R1_32 = 15;
var R2_32 = 13;
var M_32 = 5;
var N_32 = -0x19ab949c;
var hash32x86 = function (input, seed) {
if (seed === void 0) { seed = 0; }
var data = stringToUtf8ByteArray(input);
var length = data.length;
var nBlocks = length >> 2;
var hash = seed;
// body
for (var i = 0; i < nBlocks; i++) {
var index_1 = i << 2;
var k = readIntLe(data, index_1);
hash = mix32(k, hash);
}
// tail
var index = nBlocks << 2;
var k1 = 0;
switch (length - index) {
case 3:
k1 ^= data[index + 2] << 16;
k1 ^= data[index + 1] << 8;
k1 ^= data[index];
k1 = Math.imul(k1, C1_32);
k1 = rotateLeft(k1, R1_32);
k1 = Math.imul(k1, C2_32);
hash ^= k1;
break;
case 2:
k1 ^= data[index + 1] << 8;
k1 ^= data[index];
k1 = Math.imul(k1, C1_32);
k1 = rotateLeft(k1, R1_32);
k1 = Math.imul(k1, C2_32);
hash ^= k1;
break;
case 1:
k1 ^= data[index];
k1 = Math.imul(k1, C1_32);
k1 = rotateLeft(k1, R1_32);
k1 = Math.imul(k1, C2_32);
hash ^= k1;
break;
}
hash ^= length;
return fmix32(hash) >>> 0;
};
var mix32 = function (k, hash) {
var kResult = k;
var hashResult = hash;
kResult = Math.imul(kResult, C1_32);
kResult = rotateLeft(kResult, R1_32);
kResult = Math.imul(kResult, C2_32);
hashResult ^= kResult;
hashResult = rotateLeft(hashResult, R2_32);
hashResult = Math.imul(hashResult, M_32);
return (hashResult + N_32) | 0;
};
var fmix32 = function (hash) {
var hashResult = hash;
hashResult ^= hashResult >>> 16;
hashResult = Math.imul(hashResult, -0x7a143595);
hashResult ^= hashResult >>> 13;
hashResult = Math.imul(hashResult, -0x3d4d51cb);
hashResult ^= hashResult >>> 16;
return hashResult;
};
var rotateLeft = function (x, n, width) {
if (width === void 0) { width = 32; }
if (n > width)
n = n % width;
var mask = (0xffffffff << (width - n)) >>> 0;
var r = (((x & mask) >>> 0) >>> (width - n)) >>> 0;
return ((x << n) | r) >>> 0;
};
var readIntLe = function (data, index) {
if (index === void 0) { index = 0; }
var n = (data[index] << 24) |
(data[index + 1] << 16) |
(data[index + 2] << 8) |
data[index + 3];
return reverseBytes(n);
};
var reverseBytes = function (n) {
return (((n & -0x1000000) >>> 24) |
((n & 0x00ff0000) >>> 8) |
((n & 0x0000ff00) << 8) |
((n & 0x000000ff) << 24));
};
var select = function (selectable, selector) {
var e_1, _a;
if (!selector || selector.length === 0) {
return undefined;
}
try {
for (var selector_1 = __values(selector), selector_1_1 = selector_1.next(); !selector_1_1.done; selector_1_1 = selector_1.next()) {
var selectorElement = selector_1_1.value;
if (!selectorElement || !selectable || typeof selectable !== 'object') {
return undefined;
}
selectable = selectable[selectorElement];
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (selector_1_1 && !selector_1_1.done && (_a = selector_1.return)) _a.call(selector_1);
}
finally { if (e_1) throw e_1.error; }
}
if (!selectable) {
return undefined;
}
else {
return selectable;
}
};
// major and minor should be non-negative numbers separated by a dot
var MAJOR_MINOR_REGEX = '(\\d+)\\.(\\d+)';
// patch should be a non-negative number
var PATCH_REGEX = '(\\d+)';
// prerelease is optional. If provided, it should be a hyphen followed by a
// series of dot separated identifiers where an identifer can contain anything in [-0-9a-zA-Z]
var PRERELEASE_REGEX = '(-(([-\\w]+\\.?)*))?';
// version pattern should be major.minor(.patchAndPreRelease) where .patchAndPreRelease is optional
var VERSION_PATTERN = "^".concat(MAJOR_MINOR_REGEX, "(\\.").concat(PATCH_REGEX).concat(PRERELEASE_REGEX, ")?$");
var SemanticVersion = /** @class */ (function () {
function SemanticVersion(major, minor, patch, preRelease) {
if (preRelease === void 0) { preRelease = undefined; }
this.major = major;
this.minor = minor;
this.patch = patch;
this.preRelease = preRelease;
}
SemanticVersion.parse = function (version) {
if (!version) {
return undefined;
}
var matchGroup = new RegExp(VERSION_PATTERN).exec(version);
if (!matchGroup) {
return undefined;
}
var major = Number(matchGroup[1]);
var minor = Number(matchGroup[2]);
if (isNaN(major) || isNaN(minor)) {
return undefined;
}
var patch = Number(matchGroup[4]) || 0;
var preRelease = matchGroup[5] || undefined;
return new SemanticVersion(major, minor, patch, preRelease);
};
SemanticVersion.prototype.compareTo = function (other) {
if (this.major > other.major)
return 1;
if (this.major < other.major)
return -1;
if (this.minor > other.minor)
return 1;
if (this.minor < other.minor)
return -1;
if (this.patch > other.patch)
return 1;
if (this.patch < other.patch)
return -1;
if (this.preRelease && !other.preRelease)
return -1;
if (!this.preRelease && other.preRelease)
return 1;
if (this.preRelease && other.preRelease) {
if (this.preRelease > other.preRelease)
return 1;
if (this.preRelease < other.preRelease)
return -1;
return 0;
}
return 0;
};
return SemanticVersion;
}());
var EvaluationEngine = /** @class */ (function () {
function EvaluationEngine() {
}
EvaluationEngine.prototype.evaluate = function (context, flags) {
var e_1, _a;
var results = {};
var target = {
context: context,
result: results,
};
try {
for (var flags_1 = __values(flags), flags_1_1 = flags_1.next(); !flags_1_1.done; flags_1_1 = flags_1.next()) {
var flag = flags_1_1.value;
// Evaluate flag and update results.
var variant = this.evaluateFlag(target, flag);
if (variant) {
results[flag.key] = variant;
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (flags_1_1 && !flags_1_1.done && (_a = flags_1.return)) _a.call(flags_1);
}
finally { if (e_1) throw e_1.error; }
}
return results;
};
EvaluationEngine.prototype.evaluateFlag = function (target, flag) {
var e_2, _a;
var result;
try {
for (var _b = __values(flag.segments), _c = _b.next(); !_c.done; _c = _b.next()) {
var segment = _c.value;
result = this.evaluateSegment(target, flag, segment);
if (result) {
// Merge all metadata into the result
var metadata = __assign(__assign(__assign({}, flag.metadata), segment.metadata), result.metadata);
result = __assign(__assign({}, result), { metadata: metadata });
break;
}
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_2) throw e_2.error; }
}
return result;
};
EvaluationEngine.prototype.evaluateSegment = function (target, flag, segment) {
var e_3, _a, e_4, _b;
if (!segment.conditions) {
// Null conditions always match
var variantKey = this.bucket(target, segment);
if (variantKey !== undefined) {
return flag.variants[variantKey];
}
else {
return undefined;
}
}
try {
// Outer list logic is "or" (||)
for (var _c = __values(segment.conditions), _d = _c.next(); !_d.done; _d = _c.next()) {
var conditions = _d.value;
var match = true;
try {
for (var conditions_1 = (e_4 = void 0, __values(conditions)), conditions_1_1 = conditions_1.next(); !conditions_1_1.done; conditions_1_1 = conditions_1.next()) {
var condition = conditions_1_1.value;
match = this.matchCondition(target, condition);
if (!match) {
break;
}
}
}
catch (e_4_1) { e_4 = { error: e_4_1 }; }
finally {
try {
if (conditions_1_1 && !conditions_1_1.done && (_b = conditions_1.return)) _b.call(conditions_1);
}
finally { if (e_4) throw e_4.error; }
}
// On match, bucket the user.
if (match) {
var variantKey = this.bucket(target, segment);
if (variantKey !== undefined) {
return flag.variants[variantKey];
}
else {
return undefined;
}
}
}
}
catch (e_3_1) { e_3 = { error: e_3_1 }; }
finally {
try {
if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
}
finally { if (e_3) throw e_3.error; }
}
return undefined;
};
EvaluationEngine.prototype.matchCondition = function (target, condition) {
var propValue = select(target, condition.selector);
// We need special matching for null properties and set type prop values
// and operators. All other values are matched as strings, since the
// filter values are always strings.
if (!propValue) {
return this.matchNull(condition.op, condition.values);
}
else if (this.isSetOperator(condition.op)) {
var propValueStringList = this.coerceStringArray(propValue);
if (!propValueStringList) {
return false;
}
return this.matchSet(propValueStringList, condition.op, condition.values);
}
else {
var propValueString = this.coerceString(propValue);
if (propValueString !== undefined) {
return this.matchString(propValueString, condition.op, condition.values);
}
else {
return false;
}
}
};
EvaluationEngine.prototype.getHash = function (key) {
return hash32x86(key);
};
EvaluationEngine.prototype.bucket = function (target, segment) {
var e_5, _a, e_6, _b;
if (!segment.bucket) {
// A null bucket means the segment is fully rolled out. Select the
// default variant.
return segment.variant;
}
// Select the bucketing value.
var bucketingValue = this.coerceString(select(target, segment.bucket.selector));
if (!bucketingValue || bucketingValue.length === 0) {
// A null or empty bucketing value cannot be bucketed. Select the
// default variant.
return segment.variant;
}
// Salt and has the value, and compute the allocation and distribution
// values.
var keyToHash = "".concat(segment.bucket.salt, "/").concat(bucketingValue);
var hash = this.getHash(keyToHash);
var allocationValue = hash % 100;
var distributionValue = Math.floor(hash / 100);
try {
for (var _c = __values(segment.bucket.allocations), _d = _c.next(); !_d.done; _d = _c.next()) {
var allocation = _d.value;
var allocationStart = allocation.range[0];
var allocationEnd = allocation.range[1];
if (allocationValue >= allocationStart &&
allocationValue < allocationEnd) {
try {
for (var _e = (e_6 = void 0, __values(allocation.distributions)), _f = _e.next(); !_f.done; _f = _e.next()) {
var distribution = _f.value;
var distributionStart = distribution.range[0];
var distributionEnd = distribution.range[1];
if (distributionValue >= distributionStart &&
distributionValue < distributionEnd) {
return distribution.variant;
}
}
}
catch (e_6_1) { e_6 = { error: e_6_1 }; }
finally {
try {
if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
}
finally { if (e_6) throw e_6.error; }
}
}
}
}
catch (e_5_1) { e_5 = { error: e_5_1 }; }
finally {
try {
if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
}
finally { if (e_5) throw e_5.error; }
}
return segment.variant;
};
EvaluationEngine.prototype.matchNull = function (op, filterValues) {
var containsNone = this.containsNone(filterValues);
switch (op) {
case EvaluationOperator.IS:
case EvaluationOperator.CONTAINS:
case EvaluationOperator.LESS_THAN:
case EvaluationOperator.LESS_THAN_EQUALS:
case EvaluationOperator.GREATER_THAN:
case EvaluationOperator.GREATER_THAN_EQUALS:
case EvaluationOperator.VERSION_LESS_THAN:
case EvaluationOperator.VERSION_LESS_THAN_EQUALS:
case EvaluationOperator.VERSION_GREATER_THAN:
case EvaluationOperator.VERSION_GREATER_THAN_EQUALS:
case EvaluationOperator.SET_IS:
case EvaluationOperator.SET_CONTAINS:
case EvaluationOperator.SET_CONTAINS_ANY:
return containsNone;
case EvaluationOperator.IS_NOT:
case EvaluationOperator.DOES_NOT_CONTAIN:
case EvaluationOperator.SET_DOES_NOT_CONTAIN:
case EvaluationOperator.SET_DOES_NOT_CONTAIN_ANY:
return !containsNone;
default:
return false;
}
};
EvaluationEngine.prototype.matchSet = function (propValues, op, filterValues) {
switch (op) {
case EvaluationOperator.SET_IS:
return this.setEquals(propValues, filterValues);
case EvaluationOperator.SET_IS_NOT:
return !this.setEquals(propValues, filterValues);
case EvaluationOperator.SET_CONTAINS:
return this.matchesSetContainsAll(propValues, filterValues);
case EvaluationOperator.SET_DOES_NOT_CONTAIN:
return !this.matchesSetContainsAll(propValues, filterValues);
case EvaluationOperator.SET_CONTAINS_ANY:
return this.matchesSetContainsAny(propValues, filterValues);
case EvaluationOperator.SET_DOES_NOT_CONTAIN_ANY:
return !this.matchesSetContainsAny(propValues, filterValues);
default:
return false;
}
};
EvaluationEngine.prototype.matchString = function (propValue, op, filterValues) {
var _this = this;
switch (op) {
case EvaluationOperator.IS:
return this.matchesIs(propValue, filterValues);
case EvaluationOperator.IS_NOT:
return !this.matchesIs(propValue, filterValues);
case EvaluationOperator.CONTAINS:
return this.matchesContains(propValue, filterValues);
case EvaluationOperator.DOES_NOT_CONTAIN:
return !this.matchesContains(propValue, filterValues);
case EvaluationOperator.LESS_THAN:
case EvaluationOperator.LESS_THAN_EQUALS:
case EvaluationOperator.GREATER_THAN:
case EvaluationOperator.GREATER_THAN_EQUALS:
return this.matchesComparable(propValue, op, filterValues, function (value) { return _this.parseNumber(value); }, this.comparator);
case EvaluationOperator.VERSION_LESS_THAN:
case EvaluationOperator.VERSION_LESS_THAN_EQUALS:
case EvaluationOperator.VERSION_GREATER_THAN:
case EvaluationOperator.VERSION_GREATER_THAN_EQUALS:
return this.matchesComparable(propValue, op, filterValues, function (value) { return SemanticVersion.parse(value); }, this.versionComparator);
case EvaluationOperator.REGEX_MATCH:
return this.matchesRegex(propValue, filterValues);
case EvaluationOperator.REGEX_DOES_NOT_MATCH:
return !this.matchesRegex(propValue, filterValues);
default:
return false;
}
};
EvaluationEngine.prototype.matchesIs = function (propValue, filterValues) {
if (this.containsBooleans(filterValues)) {
var lower_1 = propValue.toLowerCase();
if (lower_1 === 'true' || lower_1 === 'false') {
return filterValues.some(function (value) { return value.toLowerCase() === lower_1; });
}
}
return filterValues.some(function (value) { return propValue === value; });
};
EvaluationEngine.prototype.matchesContains = function (propValue, filterValues) {
var e_7, _a;
try {
for (var filterValues_1 = __values(filterValues), filterValues_1_1 = filterValues_1.next(); !filterValues_1_1.done; filterValues_1_1 = filterValues_1.next()) {
var filterValue = filterValues_1_1.value;
if (propValue.toLowerCase().includes(filterValue.toLowerCase())) {
return true;
}
}
}
catch (e_7_1) { e_7 = { error: e_7_1 }; }
finally {
try {
if (filterValues_1_1 && !filterValues_1_1.done && (_a = filterValues_1.return)) _a.call(filterValues_1);
}
finally { if (e_7) throw e_7.error; }
}
return false;
};
EvaluationEngine.prototype.matchesComparable = function (propValue, op, filterValues, typeTransformer, typeComparator) {
var _this = this;
var propValueTransformed = typeTransformer(propValue);
var filterValuesTransformed = filterValues
.map(function (filterValue) {
return typeTransformer(filterValue);
})
.filter(function (filterValue) {
return filterValue !== undefined;
});
if (propValueTransformed === undefined ||
filterValuesTransformed.length === 0) {
return filterValues.some(function (filterValue) {
return _this.comparator(propValue, op, filterValue);
});
}
else {
return filterValuesTransformed.some(function (filterValueTransformed) {
return typeComparator(propValueTransformed, op, filterValueTransformed);
});
}
};
EvaluationEngine.prototype.comparator = function (propValue, op, filterValue) {
switch (op) {
case EvaluationOperator.LESS_THAN:
case EvaluationOperator.VERSION_LESS_THAN:
return propValue < filterValue;
case EvaluationOperator.LESS_THAN_EQUALS:
case EvaluationOperator.VERSION_LESS_THAN_EQUALS:
return propValue <= filterValue;
case EvaluationOperator.GREATER_THAN:
case EvaluationOperator.VERSION_GREATER_THAN:
return propValue > filterValue;
case EvaluationOperator.GREATER_THAN_EQUALS:
case EvaluationOperator.VERSION_GREATER_THAN_EQUALS:
return propValue >= filterValue;
default:
return false;
}
};
EvaluationEngine.prototype.versionComparator = function (propValue, op, filterValue) {
var compareTo = propValue.compareTo(filterValue);
switch (op) {
case EvaluationOperator.LESS_THAN:
case EvaluationOperator.VERSION_LESS_THAN:
return compareTo < 0;
case EvaluationOperator.LESS_THAN_EQUALS:
case EvaluationOperator.VERSION_LESS_THAN_EQUALS:
return compareTo <= 0;
case EvaluationOperator.GREATER_THAN:
case EvaluationOperator.VERSION_GREATER_THAN:
return compareTo > 0;
case EvaluationOperator.GREATER_THAN_EQUALS:
case EvaluationOperator.VERSION_GREATER_THAN_EQUALS:
return compareTo >= 0;
default:
return false;
}
};
EvaluationEngine.prototype.matchesRegex = function (propValue, filterValues) {
return filterValues.some(function (filterValue) {
return Boolean(new RegExp(filterValue).exec(propValue));
});
};
EvaluationEngine.prototype.containsNone = function (filterValues) {
return filterValues.some(function (filterValue) {
return filterValue === '(none)';
});
};
EvaluationEngine.prototype.containsBooleans = function (filterValues) {
return filterValues.some(function (filterValue) {
switch (filterValue.toLowerCase()) {
case 'true':
case 'false':
return true;
default:
return false;
}
});
};
EvaluationEngine.prototype.parseNumber = function (value) {
var _a;
return (_a = Number(value)) !== null && _a !== void 0 ? _a : undefined;
};
EvaluationEngine.prototype.coerceString = function (value) {
if (!value) {
return undefined;
}
if (typeof value === 'object') {
return JSON.stringify(value);
}
return String(value);
};
EvaluationEngine.prototype.coerceStringArray = function (value) {
var _this = this;
if (Array.isArray(value)) {
var anyArray = value;
return anyArray
.map(function (e) { return _this.coerceString(e); })
.filter(Boolean);
}
var stringValue = String(value);
try {
var parsedValue = JSON.parse(stringValue);
if (Array.isArray(parsedValue)) {
var anyArray = value;
return anyArray
.map(function (e) { return _this.coerceString(e); })
.filter(Boolean);
}
else {
return undefined;
}
}
catch (_a) {
return undefined;
}
};
EvaluationEngine.prototype.isSetOperator = function (op) {
switch (op) {
case EvaluationOperator.SET_IS:
case EvaluationOperator.SET_IS_NOT:
case EvaluationOperator.SET_CONTAINS:
case EvaluationOperator.SET_DOES_NOT_CONTAIN:
case EvaluationOperator.SET_CONTAINS_ANY:
case EvaluationOperator.SET_DOES_NOT_CONTAIN_ANY:
return true;
default:
return false;
}
};
EvaluationEngine.prototype.setEquals = function (xa, ya) {
var xs = new Set(xa);
var ys = new Set(ya);
return xs.size === ys.size && __spreadArray([], __read(ys), false).every(function (y) { return xs.has(y); });
};
EvaluationEngine.prototype.matchesSetContainsAll = function (propValues, filterValues) {
var e_8, _a;
if (propValues.length < filterValues.length) {
return false;
}
try {
for (var filterValues_2 = __values(filterValues), filterValues_2_1 = filterValues_2.next(); !filterValues_2_1.done; filterValues_2_1 = filterValues_2.next()) {
var filterValue = filterValues_2_1.value;
if (!this.matchesIs(filterValue, propValues)) {
return false;
}
}
}
catch (e_8_1) { e_8 = { error: e_8_1 }; }
finally {
try {
if (filterValues_2_1 && !filterValues_2_1.done && (_a = filterValues_2.return)) _a.call(filterValues_2);
}
finally { if (e_8) throw e_8.error; }
}
return true;
};
EvaluationEngine.prototype.matchesSetContainsAny = function (propValues, filterValues) {
var e_9, _a;
try {
for (var filterValues_3 = __values(filterValues), filterValues_3_1 = filterValues_3.next(); !filterValues_3_1.done; filterValues_3_1 = filterValues_3.next()) {
var filterValue = filterValues_3_1.value;
if (this.matchesIs(filterValue, propValues)) {
return true;
}
}
}
catch (e_9_1) { e_9 = { error: e_9_1 }; }
finally {
try {
if (filterValues_3_1 && !filterValues_3_1.done && (_a = filterValues_3.return)) _a.call(filterValues_3);
}
finally { if (e_9) throw e_9.error; }
}
return false;
};
return EvaluationEngine;
}());
var topologicalSort = function (flags, flagKeys) {
var e_1, _a;
var available = __assign({}, flags);
var result = [];
var startingKeys = flagKeys || Object.keys(available);
try {
for (var startingKeys_1 = __values(startingKeys), startingKeys_1_1 = startingKeys_1.next(); !startingKeys_1_1.done; startingKeys_1_1 = startingKeys_1.next()) {
var flagKey = startingKeys_1_1.value;
var traversal = parentTraversal(flagKey, available);
if (traversal) {
result.push.apply(result, __spreadArray([], __read(traversal), false));
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (startingKeys_1_1 && !startingKeys_1_1.done && (_a = startingKeys_1.return)) _a.call(startingKeys_1);
}
finally { if (e_1) throw e_1.error; }
}
return result;
};
var parentTraversal = function (flagKey, available, path) {
var e_2, _a;
if (path === void 0) { path = []; }
var flag = available[flagKey];
if (!flag) {
return undefined;
}
else if (!flag.dependencies || flag.dependencies.length === 0) {
delete available[flag.key];
return [flag];
}
path.push(flag.key);
var result = [];
var _loop_1 = function (parentKey) {
if (path.some(function (p) { return p === parentKey; })) {
throw Error("Detected a cycle between flags ".concat(path));
}
var traversal = parentTraversal(parentKey, available, path);
if (traversal) {
result.push.apply(result, __spreadArray([], __read(traversal), false));
}
};
try {
for (var _b = __values(flag.dependencies), _c = _b.next(); !_c.done; _c = _b.next()) {
var parentKey = _c.value;
_loop_1(parentKey);
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_2) throw e_2.error; }
}
result.push(flag);
path.pop();
delete available[flag.key];
return result;
};
/**
* base64.ts
*
* Licensed under the BSD 3-Clause License.
* http://opensource.org/licenses/BSD-3-Clause
*
* References:
* http://en.wikipedia.org/wiki/Base64
*
* @author Dan Kogai (https://github.com/dankogai)
*/
const version = '3.7.5';
/**
* @deprecated use lowercase `version`.
*/
const VERSION = version;
const _hasatob = typeof atob === 'function';
const _hasbtoa = typeof btoa === 'function';
const _hasBuffer = typeof Buffer === 'function';
const _TD = typeof TextDecoder === 'function' ? new TextDecoder() : undefined;
const _TE = typeof TextEncoder === 'function' ? new TextEncoder() : undefined;
const b64ch = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
const b64chs = Array.prototype.slice.call(b64ch);
const b64tab = (a => {
let tab = {};
a.forEach((c, i) => tab[c] = i);
return tab;
})(b64chs);
const b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/;
const _fromCC = String.fromCharCode.bind(String);
const _U8Afrom = typeof Uint8Array.from === 'function' ? Uint8Array.from.bind(Uint8Array) : it => new Uint8Array(Array.prototype.slice.call(it, 0));
const _mkUriSafe = src => src.replace(/=/g, '').replace(/[+\/]/g, m0 => m0 == '+' ? '-' : '_');
const _tidyB64 = s => s.replace(/[^A-Za-z0-9\+\/]/g, '');
/**
* polyfill version of `btoa`
*/
const btoaPolyfill = bin => {
// console.log('polyfilled');
let u32,
c0,
c1,
c2,
asc = '';
const pad = bin.length % 3;
for (let i = 0; i < bin.length;) {
if ((c0 = bin.charCodeAt(i++)) > 255 || (c1 = bin.charCodeAt(i++)) > 255 || (c2 = bin.charCodeAt(i++)) > 255) throw new TypeError('invalid character found');
u32 = c0 << 16 | c1 << 8 | c2;
asc += b64chs[u32 >> 18 & 63] + b64chs[u32 >> 12 & 63] + b64chs[u32 >> 6 & 63] + b64chs[u32 & 63];
}
return pad ? asc.slice(0, pad - 3) + "===".substring(pad) : asc;
};
/**
* does what `window.btoa` of web browsers do.
* @param {String} bin binary string
* @returns {string} Base64-encoded string
*/
const _btoa = _hasbtoa ? bin => btoa(bin) : _hasBuffer ? bin => Buffer.from(bin, 'binary').toString('base64') : btoaPolyfill;
const _fromUint8Array = _hasBuffer ? u8a => Buffer.from(u8a).toString('base64') : u8a => {
// cf. https://stackoverflow.com/questions/12710001/how-to-convert-uint8-array-to-base64-encoded-string/12713326#12713326
const maxargs = 0x1000;
let strs = [];
for (let i = 0, l = u8a.length; i < l; i += maxargs) {
strs.push(_fromCC.apply(null, u8a.subarray(i, i + maxargs)));
}
return _btoa(strs.join(''));
};
/**
* converts a Uint8Array to a Base64 string.
* @param {boolean} [urlsafe] URL-and-filename-safe a la RFC4648 §5
* @returns {string} Base64 string
*/
const fromUint8Array = (u8a, urlsafe = false) => urlsafe ? _mkUriSafe(_fromUint8Array(u8a)) : _fromUint8Array(u8a);
// This trick is found broken https://github.com/dankogai/js-base64/issues/130
// const utob = (src: string) => unescape(encodeURIComponent(src));
// reverting good old fationed regexp
const cb_utob = c => {
if (c.length < 2) {
var cc = c.charCodeAt(0);
return cc < 0x80 ? c : cc < 0x800 ? _fromCC(0xc0 | cc >>> 6) + _fromCC(0x80 | cc & 0x3f) : _fromCC(0xe0 | cc >>> 12 & 0x0f) + _fromCC(0x80 | cc >>> 6 & 0x3f) + _fromCC(0x80 | cc & 0x3f);
} else {
var cc = 0x10000 + (c.charCodeAt(0) - 0xD800) * 0x400 + (c.charCodeAt(1) - 0xDC00);
return _fromCC(0xf0 | cc >>> 18 & 0x07) + _fromCC(0x80 | cc >>> 12 & 0x3f) + _fromCC(0x80 | cc >>> 6 & 0x3f) + _fromCC(0x80 | cc & 0x3f);
}
};
const re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;
/**
* @deprecated should have been internal use only.
* @param {string} src UTF-8 string
* @returns {string} UTF-16 string
*/
const utob = u => u.replace(re_utob, cb_utob);
//
const _encode = _hasBuffer ? s => Buffer.from(s, 'utf8').toString('base64') : _TE ? s => _fromUint8Array(_TE.encode(s)) : s => _btoa(utob(s));
/**
* converts a UTF-8-encoded string to a Base64 string.
* @param {boolean} [urlsafe] if `true` make the result URL-safe
* @returns {string} Base64 string
*/
const encode = (src, urlsafe = false) => urlsafe ? _mkUriSafe(_encode(src)) : _encode(src);
/**
* converts a UTF-8-encoded string to URL-safe Base64 RFC4648 §5.
* @returns {string} Base64 string
*/
const encodeURI = src => encode(src, true);
// This trick is found broken https://github.com/dankogai/js-base64/issues/130
// const btou = (src: string) => decodeURIComponent(escape(src));
// reverting good old fationed regexp
const re_btou = /[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g;
const cb_btou = cccc => {
switch (cccc.length) {
case 4:
var cp = (0x07 & cccc.charCodeAt(0)) << 18 | (0x3f & cccc.charCodeAt(1)) << 12 | (0x3f & cccc.charCodeAt(2)) << 6 | 0x3f & cccc.charCodeAt(3),
offset = cp - 0x10000;
return _fromCC((offset >>> 10) + 0xD800) + _fromCC((offset & 0x3FF) + 0xDC00);
case 3:
return _fromCC((0x0f & cccc.charCodeAt(0)) << 12 | (0x3f & cccc.charCodeAt(1)) << 6 | 0x3f & cccc.charCodeAt(2));
default:
return _fromCC((0x1f & cccc.charCodeAt(0)) << 6 | 0x3f & cccc.charCodeAt(1));
}
};
/**
* @deprecated should have been internal use only.
* @param {string} src UTF-16 string
* @returns {string} UTF-8 string
*/
const btou = b => b.replace(re_btou, cb_btou);
/**
* polyfill version of `atob`
*/
const atobPolyfill = asc => {
// console.log('polyfilled');
asc = asc.replace(/\s+/g, '');
if (!b64re.test(asc)) throw new TypeError('malformed base64.');
asc += '=='.slice(2 - (asc.length & 3));
let u24,
bin = '',
r1,
r2;
for (let i = 0; i < asc.length;) {
u24 = b64tab[asc.charAt(i++)] << 18 | b64tab[asc.charAt(i++)] << 12 | (r1 = b64tab[asc.charAt(i++)]) << 6 | (r2 = b64tab[asc.charAt(i++)]);
bin += r1 === 64 ? _fromCC(u24 >> 16 & 255) : r2 === 64 ? _fromCC(u24 >> 16 & 255, u24 >> 8 & 255) : _fromCC(u24 >> 16 & 255, u24 >> 8 & 255, u24 & 255);
}
return bin;
};
/**
* does what `window.atob` of web browsers do.
* @param {String} asc Base64-encoded string
* @returns {string} binary string
*/
const _atob = _hasatob ? asc => atob(_tidyB64(asc)) : _hasBuffer ? asc => Buffer.from(asc, 'base64').toString('binary') : atobPolyfill;
//
const _toUint8Array = _hasBuffer ? a => _U8Afrom(Buffer.from(a, 'base64')) : a => _U8Afrom(_atob(a).split('').map(c => c.charCodeAt(0)));
/**
* converts a Base64 string to a Uint8Array.
*/
const toUint8Array = a => _toUint8Array(_unURI(a));
//
const _decode = _hasBuffer ? a => Buffer.from(a, 'base64').toString('utf8') : _TD ? a => _TD.decode(_toUint8Array(a)) : a => btou(_atob(a));
const _unURI = a => _tidyB64(a.replace(/[-_]/g, m0 => m0 == '-' ? '+' : '/'));
/**
* converts a Base64 string to a UTF-8 string.
* @param {String} src Base64 string. Both normal and URL-safe are supported
* @returns {string} UTF-8 string
*/
const decode = src => _decode(_unURI(src));
/**
* check if a value is a valid Base64 string
* @param {String} src a value to check
*/
const isValid = src => {
if (typeof src !== 'string') return false;
const s = src.replace(/\s+/g, '').replace(/={0,2}$/, '');
return !/[^\s0-9a-zA-Z\+/]/.test(s) || !/[^\s0-9a-zA-Z\-_]/.test(s);
};
//
const _noEnum = v => {
return {
value: v,
enumerable: false,
writable: true,
configurable: true
};
};
/**
* extend String.prototype with relevant methods
*/
const extendString = function () {
const _add = (name, body) => Object.defineProperty(String.prototype, name, _noEnum(body));
_add('fromBase64', function () {
return decode(this);
});
_add('toBase64', function (urlsafe) {
return encode(this, urlsafe);
});
_add('toBase64URI', function () {
return encode(this, true);
});
_add('toBase64URL', function () {
return encode(this, true);
});
_add('toUint8Array', function () {
return toUint8Array(this);
});
};
/**
* extend Uint8Array.prototype with relevant methods
*/
const extendUint8Array = function () {
const _add = (name, body) => Object.defineProperty(Uint8Array.prototype, name, _noEnum(body));
_add('toBase64', function (urlsafe) {
return fromUint8Array(this, urlsafe);
});
_add('toBase64URI', function () {
return fromUint8Array(this, true);
});
_add('toBase64URL', function () {
return fromUint8Array(this, true);
});
};
/**
* extend Builtin prototypes with relevant methods
*/
const extendBuiltins = () => {
extendString();
extendUint8Array();
};
const gBase64 = {
version: version,
VERSION: VERSION,
atob: _atob,
atobPolyfill: atobPolyfill,
btoa: _btoa,
btoaPolyfill: btoaPolyfill,
fromBase64: decode,
toBase64: encode,
encode: encode,
encodeURI: encodeURI,
encodeURL: encodeURI,
utob: utob,
btou: btou,
decode: decode,
isValid: isValid,
fromUint8Array: fromUint8Array,
toUint8Array: toUint8Array,
extendString: extendString,
extendUint8Array: extendUint8Array,
extendBuiltins: extendBuiltins
};
var FetchError = /** @class */ (function (_super) {
__extends(FetchError, _super);
function FetchError(statusCode, message) {
var _this = _super.call(this, message) || this;
_this.statusCode = statusCode;
Object.setPrototypeOf(_this, FetchError.prototype);
return _this;
}
return FetchError;
}(Error));
var SdkEvaluationApi = /** @class */ (function () {
function SdkEvaluationApi(deploymentKey, serverUrl, httpClient) {
this.deploymentKey = deploymentKey;
this.serverUrl = serverUrl;
this.httpClient = httpClient;
}
SdkEvaluationApi.prototype.getVariants = function (user, options) {
return __awaiter(this, void 0, void 0, function () {
var userJsonBase64, headers, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
userJsonBase64 = gBase64.encodeURL(JSON.stringify(user));
headers = {
Authorization: "Api-Key ".concat(this.deploymentKey),
'X-Amp-Exp-User': userJsonBase64,
};
if (options === null || options === void 0 ? void 0 : options.flagKeys) {
headers['X-Amp-Exp-Flag-Keys'] = gBase64.encodeURL(JSON.stringify(options.flagKeys));
}
if (options === null || options === void 0 ? void 0 : options.trackingOption) {
headers['X-Amp-Exp-Track'] = options.trackingOption;
}
return [4 /*yield*/, this.httpClient.request({
requestUrl: "".concat(this.serverUrl, "/sdk/v2/vardata?v=0"),
method: 'GET',
headers: headers,
timeoutMillis: options === null || options === void 0 ? void 0 : options.timeoutMillis,
})];
case 1:
response = _a.sent();
if (response.status != 200) {
throw new FetchError(response.status, "Fetch error response: status=".concat(response.status));
}
return [2 /*return*/, JSON.parse(response.body)];
}
});
});
};
return SdkEvaluationApi;
}());
var SdkFlagApi = /** @class */ (function () {
function SdkFlagApi(deploymentKey, serverUrl, httpClient) {
this.deploymentKey = deploymentKey;
this.serverUrl = serverUrl;
this.httpClient = httpClient;
}
SdkFlagApi.prototype.getFlags = function (options) {
return __awaiter(this, void 0, void 0, function () {
var headers, response, flagsArray;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
headers = {
Authorization: "Api-Key ".concat(this.deploymentKey),
};
if ((options === null || options === void 0 ? void 0 : options.libraryName) && (options === null || options === void 0 ? void 0 : options.libraryVersion)) {
headers['X-Amp-Exp-Library'] = "".concat(options.libraryName, "/").concat(options.libraryVersion);
}
return [4 /*yield*/, this.httpClient.request({
requestUrl: "".concat(this.serverUrl, "/sdk/v2/flags"),
method: 'GET',
headers: headers,
timeoutMillis: options === null || options === void 0 ? void 0 : options.timeoutMillis,
})];
case 1:
response = _a.sent();
if (response.status != 200) {
throw Error("Flags error response: status=".concat(response.status));
}
flagsArray = JSON.parse(response.body);
return [2 /*return*/, flagsArray.reduce(function (map, flag) {
map[flag.key] = flag;
return map;
}, {})];
}
});
});
};
return SdkFlagApi;
}());
var safeGlobal = typeof globalThis !== 'undefined' ? globalThis : global || self;
var Poller = /** @class */ (function () {
function Poller(action, ms) {
this.poller = undefined;
this.action = action;
this.ms = ms;
}
Poller.prototype.start = function () {
if (this.poller) {
return;
}
this.poller = safeGlobal.setInterval(this.action, this.ms);
void this.action();
};
Poller.prototype.stop = function () {
if (!this.poller) {
return;
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
safeGlobal.clearInterval(this.poller);
this.poller = undefined;
};
return Poller;
}());
export { EvaluationEngine, EvaluationOperator, FetchError, Poller, SdkEvaluationApi, SdkFlagApi, safeGlobal, topologicalSort };
webpack://frontend-mybets/../../node_modules/@amplitude/experiment-js-client/dist/experiment.esm.js
import { AnalyticsConnector } from '@amplitude/analytics-connector';
import { safeGlobal, topologicalSort, FetchError, EvaluationEngine, Poller, SdkFlagApi, SdkEvaluationApi } from '@amplitude/experiment-core';
import { UAParser } from '@amplitude/ua-parser-js';
/**
* @deprecated Update your version of the amplitude analytics-js SDK to 8.17.0+ and for seamless
* integration with the amplitude analytics SDK.
*/
var AmplitudeUserProvider = /** @class */ (function () {
function AmplitudeUserProvider(amplitudeInstance) {
this.amplitudeInstance = amplitudeInstance;
}
AmplitudeUserProvider.prototype.getUser = function () {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
return {
device_id: (_b = (_a = this.amplitudeInstance) === null || _a === void 0 ? void 0 : _a.options) === null || _b === void 0 ? void 0 : _b.deviceId,
user_id: (_d = (_c = this.amplitudeInstance) === null || _c === void 0 ? void 0 : _c.options) === null || _d === void 0 ? void 0 : _d.userId,
version: (_f = (_e = this.amplitudeInstance) === null || _e === void 0 ? void 0 : _e.options) === null || _f === void 0 ? void 0 : _f.versionName,
language: (_h = (_g = this.amplitudeInstance) === null || _g === void 0 ? void 0 : _g.options) === null || _h === void 0 ? void 0 : _h.language,
platform: (_k = (_j = this.amplitudeInstance) === null || _j === void 0 ? void 0 : _j.options) === null || _k === void 0 ? void 0 : _k.platform,
os: this.getOs(),
device_model: this.getDeviceModel(),
};
};
AmplitudeUserProvider.prototype.getOs = function () {
var _a, _b, _c, _d, _e, _f;
return [
(_c = (_b = (_a = this.amplitudeInstance) === null || _a === void 0 ? void 0 : _a._ua) === null || _b === void 0 ? void 0 : _b.browser) === null || _c === void 0 ? void 0 : _c.name,
(_f = (_e = (_d = this.amplitudeInstance) === null || _d === void 0 ? void 0 : _d._ua) === null || _e === void 0 ? void 0 : _e.browser) === null || _f === void 0 ? void 0 : _f.major,
]
.filter(function (e) { return e !== null && e !== undefined; })
.join(' ');
};
AmplitudeUserProvider.prototype.getDeviceModel = function () {
var _a, _b, _c;
return (_c = (_b = (_a = this.amplitudeInstance) === null || _a === void 0 ? void 0 : _a._ua) === null || _b === void 0 ? void 0 : _b.os) === null || _c === void 0 ? void 0 : _c.name;
};
return AmplitudeUserProvider;
}());
/**
* @deprecated Update your version of the amplitude analytics-js SDK to 8.17.0+ and for seamless
* integration with the amplitude analytics SDK.
*/
var AmplitudeAnalyticsProvider = /** @class */ (function () {
function AmplitudeAnalyticsProvider(amplitudeInstance) {
this.amplitudeInstance = amplitudeInstance;
}
AmplitudeAnalyticsProvider.prototype.track = function (event) {
this.amplitudeInstance.logEvent(event.name, event.properties);
};
AmplitudeAnalyticsProvider.prototype.setUserProperty = function (event) {
var _a;
var _b;
// if the variant has a value, set the user property and log an event
this.amplitudeInstance.setUserProperties((_a = {},
_a[event.userProperty] = (_b = event.variant) === null || _b === void 0 ? void 0 : _b.value,
_a));
};
AmplitudeAnalyticsProvider.prototype.unsetUserProperty = function (event) {
var _a;
// if the variant does not have a value, unset the user property
this.amplitudeInstance['_logEvent']('$identify', null, null, {
$unset: (_a = {}, _a[event.userProperty] = '-', _a),
});
};
return AmplitudeAnalyticsProvider;
}());
/******************************************************************************
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.
***************************************************************************** */
var __assign = function () {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function (resolve) {
resolve(value);
});
}
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e) {
reject(e);
}
}
function step(result) {
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = {
label: 0,
sent: function () {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
},
f,
y,
t,
g;
return g = {
next: verb(0),
"throw": verb(1),
"return": verb(2)
}, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
return this;
}), g;
function verb(n) {
return function (v) {
return step([n, v]);
};
}
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return {
value: op[1],
done: false
};
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2]) _.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [6, e];
y = 0;
} finally {
f = t = 0;
}
if (op[0] & 5) throw op[1];
return {
value: op[0] ? op[1] : void 0,
done: true
};
}
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator,
m = s && o[s],
i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return {
value: o && o[i++],
done: !o
};
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o),
r,
ar = [],
e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
} catch (error) {
e = {
error: error
};
} finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
} finally {
if (e) throw e.error;
}
}
return ar;
}
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
function unfetch (e, n) {
return n = n || {}, new Promise(function (t, r) {
var s = new XMLHttpRequest(),
o = [],
u = [],
i = {},
a = function () {
return {
ok: 2 == (s.status / 100 | 0),
statusText: s.statusText,
status: s.status,
url: s.responseURL,
text: function () {
return Promise.resolve(s.responseText);
},
json: function () {
return Promise.resolve(JSON.parse(s.responseText));
},
blob: function () {
return Promise.resolve(new Blob([s.response]));
},
clone: a,
headers: {
keys: function () {
return o;
},
entries: function () {
return u;
},
get: function (e) {
return i[e.toLowerCase()];
},
has: function (e) {
return e.toLowerCase() in i;
}
}
};
};
for (var l in s.open(n.method || "get", e, !0), s.onload = function () {
s.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm, function (e, n, t) {
o.push(n = n.toLowerCase()), u.push([n, t]), i[n] = i[n] ? i[n] + "," + t : t;
}), t(a());
}, s.onerror = r, s.withCredentials = "include" == n.credentials, n.headers) s.setRequestHeader(l, n.headers[l]);
s.send(n.body || null);
});
}
/**
* @packageDocumentation
* @internal
*/
var fetch = safeGlobal.fetch || unfetch;
/*
* Copied from:
* https://github.com/github/fetch/issues/175#issuecomment-284787564
*/
var timeout = function (promise, timeoutMillis) {
// Don't timeout if timeout is null or invalid
if (timeoutMillis == null || timeoutMillis <= 0) {
return promise;
}
return new Promise(function (resolve, reject) {
safeGlobal.setTimeout(function () {
reject(Error('Request timeout after ' + timeoutMillis + ' milliseconds'));
}, timeoutMillis);
promise.then(resolve, reject);
});
};
var _request = function (requestUrl, method, headers, data, timeoutMillis) {
var call = function () { return __awaiter(void 0, void 0, void 0, function () {
var response, simpleResponse;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, fetch(requestUrl, {
method: method,
headers: headers,
body: data,
})];
case 1:
response = _b.sent();
_a = {
status: response.status
};
return [4 /*yield*/, response.text()];
case 2:
simpleResponse = (_a.body = _b.sent(),
_a);
return [2 /*return*/, simpleResponse];
}
});
}); };
return timeout(call(), timeoutMillis);
};
/**
* Wrap the exposed HttpClient in a CoreClient implementation to work with
* FlagsApi and EvaluationApi.
*/
var WrapperClient = /** @class */ (function () {
function WrapperClient(client) {
this.client = client;
}
WrapperClient.prototype.request = function (request) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.client.request(request.requestUrl, request.method, request.headers, null, request.timeoutMillis)];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
return WrapperClient;
}());
var FetchHttpClient = { request: _request };
/**
* Determines the primary source of variants before falling back.
*
* @category Source
*/
var Source;
(function (Source) {
/**
* The default way to source variants within your application. Before the
* assignments are fetched, `getVariant(s)` will fallback to local storage
* first, then `initialVariants` if local storage is empty. This option
* effectively falls back to an assignment fetched previously.
*/
Source["LocalStorage"] = "localStorage";
/**
* This bootstrap option is used primarily for servers-side rendering using an
* Experiment server SDK. This bootstrap option always prefers the config
* `initialVariants` over data in local storage, even if variants are fetched
* successfully and stored locally.
*/
Source["InitialVariants"] = "initialVariants";
})(Source || (Source = {}));
/**
* Indicates from which source the variant() function determines the variant
*
* @category Source
*/
var VariantSource;
(function (VariantSource) {
VariantSource["LocalStorage"] = "storage";
VariantSource["InitialVariants"] = "initial";
VariantSource["SecondaryLocalStorage"] = "secondary-storage";
VariantSource["SecondaryInitialVariants"] = "secondary-initial";
VariantSource["FallbackInline"] = "fallback-inline";
VariantSource["FallbackConfig"] = "fallback-config";
VariantSource["LocalEvaluation"] = "local-evaluation";
})(VariantSource || (VariantSource = {}));
/**
* Returns true if the VariantSource is one of the fallbacks (inline or config)
*
* @param source a {@link VariantSource}
* @returns true if source is {@link VariantSource.FallbackInline} or {@link VariantSource.FallbackConfig}
*/
var isFallback = function (source) {
return (!source ||
source === VariantSource.FallbackInline ||
source === VariantSource.FallbackConfig ||
source === VariantSource.SecondaryInitialVariants);
};
/**
Defaults for Experiment Config options
| **Option** | **Default** |
|------------------|-----------------------------------|
| **debug** | `false` |
| **instanceName** | `$default_instance` |
| **fallbackVariant** | `null` |
| **initialVariants** | `null` |
| **initialFlags** | `undefined` |
| **source** | `Source.LocalStorage` |
| **serverUrl** | `"https://api.lab.amplitude.com"` |
| **flagsServerUrl** | `"https://flag.lab.amplitude.com"` |
| **serverZone** | `"US"` |
| **assignmentTimeoutMillis** | `10000` |
| **retryFailedAssignment** | `true` |
| **automaticExposureTracking** | `true` |
| **pollOnStart** | `true` |
| **fetchOnStart** | `true` |
| **automaticFetchOnAmplitudeIdentityChange** | `false` |
| **userProvider** | `null` |
| **analyticsProvider** | `null` |
| **exposureTrackingProvider** | `null` |
*
* @category Configuration
*/
var Defaults = {
debug: false,
instanceName: '$default_instance',
fallbackVariant: {},
initialVariants: {},
initialFlags: undefined,
source: Source.LocalStorage,
serverUrl: 'https://api.lab.amplitude.com',
flagsServerUrl: 'https://flag.lab.amplitude.com',
serverZone: 'US',
fetchTimeoutMillis: 10000,
retryFetchOnFailure: true,
automaticExposureTracking: true,
pollOnStart: true,
fetchOnStart: true,
automaticFetchOnAmplitudeIdentityChange: false,
userProvider: null,
analyticsProvider: null,
exposureTrackingProvider: null,
httpClient: FetchHttpClient,
};
var version = "1.10.2";
var ConnectorUserProvider = /** @class */ (function () {
function ConnectorUserProvider(identityStore) {
this.identityStore = identityStore;
}
ConnectorUserProvider.prototype.identityReady = function (ms) {
return __awaiter(this, void 0, void 0, function () {
var identity;
var _this = this;
return __generator(this, function (_a) {
identity = this.identityStore.getIdentity();
if (!identity.userId && !identity.deviceId) {
return [2 /*return*/, Promise.race([
new Promise(function (resolve) {
var listener = function () {
resolve(undefined);
_this.identityStore.removeIdentityListener(listener);
};
_this.identityStore.addIdentityListener(listener);
}),
new Promise(function (resolve, reject) {
safeGlobal.setTimeout(reject, ms, 'Timed out waiting for Amplitude Analytics SDK to initialize. ' +
'You must ensure that the analytics SDK is initialized prior to calling fetch().');
}),
])];
}
return [2 /*return*/];
});
});
};
ConnectorUserProvider.prototype.getUser = function () {
var identity = this.identityStore.getIdentity();
var userProperties = undefined;
try {
userProperties = identity.userProperties;
}
catch (_a) {
console.warn('[Experiment] failed to cast user properties');
}
return {
user_id: identity.userId,
device_id: identity.deviceId,
user_properties: userProperties,
};
};
return ConnectorUserProvider;
}());
var ConnectorExposureTrackingProvider = /** @class */ (function () {
function ConnectorExposureTrackingProvider(eventBridge) {
this.eventBridge = eventBridge;
}
ConnectorExposureTrackingProvider.prototype.track = function (exposure) {
this.eventBridge.logEvent({
eventType: '$exposure',
eventProperties: exposure,
});
};
return ConnectorExposureTrackingProvider;
}());
var DefaultUserProvider = /** @class */ (function () {
function DefaultUserProvider(applicationContextProvider, userProvider) {
this.ua = new UAParser(typeof navigator !== 'undefined' ? navigator.userAgent : null).getResult();
this.contextProvider = applicationContextProvider;
this.userProvider = userProvider;
}
DefaultUserProvider.prototype.getUser = function () {
var _a;
var user = ((_a = this.userProvider) === null || _a === void 0 ? void 0 : _a.getUser()) || {};
var context = this.contextProvider.getApplicationContext();
return __assign({ version: context.versionName, language: context.language, platform: context.platform, os: context.os || this.getOs(this.ua), device_model: context.deviceModel || this.getDeviceModel(this.ua) }, user);
};
DefaultUserProvider.prototype.getOs = function (ua) {
var _a, _b;
return [(_a = ua.browser) === null || _a === void 0 ? void 0 : _a.name, (_b = ua.browser) === null || _b === void 0 ? void 0 : _b.major]
.filter(function (e) { return e !== null && e !== undefined; })
.join(' ');
};
DefaultUserProvider.prototype.getDeviceModel = function (ua) {
var _a;
return (_a = ua.os) === null || _a === void 0 ? void 0 : _a.name;
};
return DefaultUserProvider;
}());
var LocalStorage = /** @class */ (function () {
function LocalStorage() {
}
LocalStorage.prototype.get = function (key) {
return localStorage.getItem(key);
};
LocalStorage.prototype.put = function (key, value) {
localStorage.setItem(key, value);
};
LocalStorage.prototype.delete = function (key) {
localStorage.removeItem(key);
};
return LocalStorage;
}());
var getVariantStorage = function (deploymentKey, instanceName, storage) {
var truncatedDeployment = deploymentKey.substring(deploymentKey.length - 6);
var namespace = "amp-exp-".concat(instanceName, "-").concat(truncatedDeployment);
return new LoadStoreCache(namespace, storage, transformVariantFromStorage);
};
var getFlagStorage = function (deploymentKey, instanceName, storage) {
if (storage === void 0) { storage = new LocalStorage(); }
var truncatedDeployment = deploymentKey.substring(deploymentKey.length - 6);
var namespace = "amp-exp-".concat(instanceName, "-").concat(truncatedDeployment, "-flags");
return new LoadStoreCache(namespace, storage);
};
var LoadStoreCache = /** @class */ (function () {
function LoadStoreCache(namespace, storage, transformer) {
this.cache = {};
this.namespace = namespace;
this.storage = storage;
this.transformer = transformer;
}
LoadStoreCache.prototype.get = function (key) {
return this.cache[key];
};
LoadStoreCache.prototype.getAll = function () {
return __assign({}, this.cache);
};
LoadStoreCache.prototype.put = function (key, value) {
this.cache[key] = value;
};
LoadStoreCache.prototype.putAll = function (values) {
var e_1, _a;
try {
for (var _b = __values(Object.keys(values)), _c = _b.next(); !_c.done; _c = _b.next()) {
var key = _c.value;
this.cache[key] = values[key];
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
};
LoadStoreCache.prototype.remove = function (key) {
delete this.cache[key];
};
LoadStoreCache.prototype.clear = function () {
this.cache = {};
};
LoadStoreCache.prototype.load = function () {
var e_2, _a;
var rawValues = this.storage.get(this.namespace);
var jsonValues;
try {
jsonValues = JSON.parse(rawValues) || {};
}
catch (_b) {
// Do nothing
return;
}
var values = {};
try {
for (var _c = __values(Object.keys(jsonValues)), _d = _c.next(); !_d.done; _d = _c.next()) {
var key = _d.value;
try {
var value = void 0;
if (this.transformer) {
value = this.transformer(jsonValues[key]);
}
else {
value = jsonValues[key];
}
if (value) {
values[key] = value;
}
}
catch (_e) {
// Do nothing
}
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
}
finally { if (e_2) throw e_2.error; }
}
this.clear();
this.putAll(values);
};
LoadStoreCache.prototype.store = function (values) {
if (values === void 0) { values = this.cache; }
this.storage.put(this.namespace, JSON.stringify(values));
};
return LoadStoreCache;
}());
var transformVariantFromStorage = function (storageValue) {
if (typeof storageValue === 'string') {
// From v0 string format
return {
key: storageValue,
value: storageValue,
};
}
else if (typeof storageValue === 'object') {
// From v1 or v2 object format
var key = storageValue['key'];
var value = storageValue['value'];
var payload = storageValue['payload'];
var metadata = storageValue['metadata'];
var experimentKey = storageValue['expKey'];
if (metadata && metadata.experimentKey) {
experimentKey = metadata.experimentKey;
}
else if (experimentKey) {
metadata = metadata || {};
metadata['experimentKey'] = experimentKey;
}
var variant = {};
if (key) {
variant.key = key;
}
else if (value) {
variant.key = value;
}
if (value)
variant.value = value;
if (metadata)
variant.metadata = metadata;
if (payload)
variant.payload = payload;
if (experimentKey)
variant.expKey = experimentKey;
return variant;
}
};
/**
* Event for tracking a user's exposure to a variant. This event will not count
* towards your analytics event volume.
*
* @deprecated use ExposureTrackingProvider instead
*/
var exposureEvent = function (user, key, variant, source) {
var _a;
var name = '[Experiment] Exposure';
var value = variant === null || variant === void 0 ? void 0 : variant.value;
var userProperty = "[Experiment] ".concat(key);
return {
name: name,
user: user,
key: key,
variant: variant,
userProperty: userProperty,
properties: {
key: key,
variant: value,
source: source,
},
userProperties: (_a = {},
_a[userProperty] = value,
_a),
};
};
var isNullOrUndefined = function (value) {
return value === null || value === undefined;
};
var isNullUndefinedOrEmpty = function (value) {
if (isNullOrUndefined(value))
return true;
return value && Object.keys(value).length === 0;
};
var isLocalEvaluationMode = function (flag) {
var _a;
return ((_a = flag === null || flag === void 0 ? void 0 : flag.metadata) === null || _a === void 0 ? void 0 : _a.evaluationMode) === 'local';
};
var Backoff = /** @class */ (function () {
function Backoff(attempts, min, max, scalar) {
this.started = false;
this.done = false;
this.attempts = attempts;
this.min = min;
this.max = max;
this.scalar = scalar;
}
Backoff.prototype.start = function (fn) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!this.started) {
this.started = true;
}
else {
throw Error('Backoff already started');
}
return [4 /*yield*/, this.backoff(fn, 0, this.min)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
Backoff.prototype.cancel = function () {
this.done = true;
clearTimeout(this.timeoutHandle);
};
Backoff.prototype.backoff = function (fn, attempt, delay) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
if (this.done) {
return [2 /*return*/];
}
this.timeoutHandle = safeGlobal.setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
var nextAttempt, nextDelay;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, fn()];
case 1:
_a.sent();
return [3 /*break*/, 3];
case 2:
_a.sent();
nextAttempt = attempt + 1;
if (nextAttempt < this.attempts) {
nextDelay = Math.min(delay * this.scalar, this.max);
this.backoff(fn, nextAttempt, nextDelay);
}
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
}); }, delay);
return [2 /*return*/];
});
});
};
return Backoff;
}());
var convertUserToContext = function (user) {
var e_1, _a;
var _b, _c;
if (!user) {
return {};
}
var context = { user: user };
var groups = {};
if (!user.groups) {
return context;
}
try {
for (var _d = __values(Object.keys(user.groups)), _e = _d.next(); !_e.done; _e = _d.next()) {
var groupType = _e.value;
var groupNames = user.groups[groupType];
if (groupNames.length > 0 && groupNames[0]) {
var groupName = groupNames[0];
var groupNameMap = {
group_name: groupName,
};
// Check for group properties
var groupProperties = (_c = (_b = user.group_properties) === null || _b === void 0 ? void 0 : _b[groupType]) === null || _c === void 0 ? void 0 : _c[groupName];
if (groupProperties && Object.keys(groupProperties).length > 0) {
groupNameMap['group_properties'] = groupProperties;
}
groups[groupType] = groupNameMap;
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
}
finally { if (e_1) throw e_1.error; }
}
if (Object.keys(groups).length > 0) {
context['groups'] = groups;
}
delete context.user['groups'];
delete context.user['group_properties'];
return context;
};
var convertVariant = function (value) {
if (value === null || value === undefined) {
return {};
}
if (typeof value == 'string') {
return {
key: value,
value: value,
};
}
else {
return value;
}
};
var convertEvaluationVariantToVariant = function (evaluationVariant) {
if (!evaluationVariant) {
return {};
}
var experimentKey = undefined;
if (evaluationVariant.metadata) {
experimentKey = evaluationVariant.metadata['experimentKey'];
}
var variant = {};
if (evaluationVariant.key)
variant.key = evaluationVariant.key;
if (evaluationVariant.value)
variant.value = evaluationVariant.value;
if (evaluationVariant.payload)
variant.payload = evaluationVariant.payload;
if (experimentKey)
variant.expKey = experimentKey;
if (evaluationVariant.metadata)
variant.metadata = evaluationVariant.metadata;
return variant;
};
/**
* A wrapper for an analytics provider which only sends one exposure event per
* flag, per variant, per session. In other words, wrapping an analytics
* provider in this class will prevent the same exposure event to be sent twice
* in one session.
*/
var SessionAnalyticsProvider = /** @class */ (function () {
function SessionAnalyticsProvider(analyticsProvider) {
// In memory record of flagKey and variant value to in order to only set
// user properties and track an exposure event once per session unless the
// variant value changes
this.setProperties = {};
this.unsetProperties = {};
this.analyticsProvider = analyticsProvider;
}
SessionAnalyticsProvider.prototype.track = function (event) {
if (this.setProperties[event.key] == event.variant.value) {
return;
}
else {
this.setProperties[event.key] = event.variant.value;
delete this.unsetProperties[event.key];
}
this.analyticsProvider.track(event);
};
SessionAnalyticsProvider.prototype.setUserProperty = function (event) {
if (this.setProperties[event.key] == event.variant.value) {
return;
}
this.analyticsProvider.setUserProperty(event);
};
SessionAnalyticsProvider.prototype.unsetUserProperty = function (event) {
if (this.unsetProperties[event.key]) {
return;
}
else {
this.unsetProperties[event.key] = 'unset';
delete this.setProperties[event.key];
}
this.analyticsProvider.unsetUserProperty(event);
};
return SessionAnalyticsProvider;
}());
var SessionExposureTrackingProvider = /** @class */ (function () {
function SessionExposureTrackingProvider(exposureTrackingProvider) {
this.tracked = {};
this.exposureTrackingProvider = exposureTrackingProvider;
}
SessionExposureTrackingProvider.prototype.track = function (exposure) {
var trackedExposure = this.tracked[exposure.flag_key];
if (trackedExposure && trackedExposure.variant === exposure.variant) {
return;
}
else {
this.tracked[exposure.flag_key] = exposure;
this.exposureTrackingProvider.track(exposure);
}
};
return SessionExposureTrackingProvider;
}());
/**
* @packageDocumentation
* @module experiment-js-client
*/
// Configs which have been removed from the public API.
// May be added back in the future.
var fetchBackoffTimeout = 10000;
var fetchBackoffAttempts = 8;
var fetchBackoffMinMillis = 500;
var fetchBackoffMaxMillis = 10000;
var fetchBackoffScalar = 1.5;
var flagPollerIntervalMillis = 60000;
var euServerUrl = 'https://api.lab.eu.amplitude.com';
var euFlagsServerUrl = 'https://flag.lab.eu.amplitude.com';
/**
* The default {@link Client} used to fetch variations from Experiment's
* servers.
*
* @category Core Usage
*/
var ExperimentClient = /** @class */ (function () {
/**
* Creates a new ExperimentClient instance.
*
* In most cases you will want to use the `initialize` factory method in
* {@link Experiment}.
*
* @param apiKey The Client key for the Experiment project
* @param config See {@link ExperimentConfig} for config options
*/
function ExperimentClient(apiKey, config) {
var _this = this;
var _a, _b;
this.engine = new EvaluationEngine();
this.poller = new Poller(function () { return _this.doFlags(); }, flagPollerIntervalMillis);
this.isRunning = false;
this.apiKey = apiKey;
// Merge configs with defaults and wrap providers
this.config = __assign(__assign(__assign({}, Defaults), config), {
// Set server URLs separately
serverUrl: (config === null || config === void 0 ? void 0 : config.serverUrl) ||
(((_a = config === null || config === void 0 ? void 0 : config.serverZone) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === 'eu'
? euServerUrl
: Defaults.serverUrl), flagsServerUrl: (config === null || config === void 0 ? void 0 : config.flagsServerUrl) ||
(((_b = config === null || config === void 0 ? void 0 : config.serverZone) === null || _b === void 0 ? void 0 : _b.toLowerCase()) === 'eu'
? euFlagsServerUrl
: Defaults.flagsServerUrl) });
// Transform initialVariants
if (this.config.initialVariants) {
for (var flagKey in this.config.initialVariants) {
this.config.initialVariants[flagKey] = transformVariantFromStorage(this.config.initialVariants[flagKey]);
}
}
if (this.config.userProvider) {
this.userProvider = this.config.userProvider;
}
if (this.config.analyticsProvider) {
this.analyticsProvider = new SessionAnalyticsProvider(this.config.analyticsProvider);
}
if (this.config.exposureTrackingProvider) {
this.exposureTrackingProvider = new SessionExposureTrackingProvider(this.config.exposureTrackingProvider);
}
// Setup Remote APIs
var httpClient = new WrapperClient(this.config.httpClient || FetchHttpClient);
this.flagApi = new SdkFlagApi(this.apiKey, this.config.flagsServerUrl, httpClient);
this.evaluationApi = new SdkEvaluationApi(this.apiKey, this.config.serverUrl, httpClient);
// Storage & Caching
var storage = new LocalStorage();
this.variants = getVariantStorage(this.apiKey, this.config.instanceName, storage);
this.flags = getFlagStorage(this.apiKey, this.config.instanceName, storage);
try {
this.flags.load();
this.variants.load();
}
catch (e) {
// catch localStorage undefined error
}
this.mergeInitialFlagsWithStorage();
}
/**
* Start the SDK by getting flag configurations from the server and fetching
* variants for the user. The promise returned by this function resolves when
* local flag configurations have been updated, and the {@link fetch()}
* result has been received (if the request was made).
*
* To force this function not to fetch variants, set the {@link fetchOnStart}
* configuration option to `false` when initializing the SDK.
*
* Finally, this function will start polling for flag configurations at a
* fixed interval. To disable polling, set the {@link pollOnStart}
* configuration option to `false` on initialization.
*
* @param user The user to set in the SDK.
* @see fetchOnStart
* @see pollOnStart
* @see fetch
* @see variant
*/
ExperimentClient.prototype.start = function (user) {
var _a;
return __awaiter(this, void 0, void 0, function () {
var flagsReadyPromise, fetchOnStart;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (this.isRunning) {
return [2 /*return*/];
}
else {
this.isRunning = true;
}
this.setUser(user);
flagsReadyPromise = this.doFlags();
fetchOnStart = (_a = this.config.fetchOnStart) !== null && _a !== void 0 ? _a : true;
if (!fetchOnStart) return [3 /*break*/, 2];
return [4 /*yield*/, Promise.all([this.fetch(user), flagsReadyPromise])];
case 1:
_b.sent();
return [3 /*break*/, 4];
case 2: return [4 /*yield*/, flagsReadyPromise];
case 3:
_b.sent();
_b.label = 4;
case 4:
if (this.config.pollOnStart) {
this.poller.start();
}
return [2 /*return*/];
}
});
});
};
/**
* Stop the local flag configuration poller.
*/
ExperimentClient.prototype.stop = function () {
if (!this.isRunning) {
return;
}
this.poller.stop();
this.isRunning = false;
};
/**
* Assign the given user to the SDK and asynchronously fetch all variants
* from the server. Subsequent calls may omit the user from the argument to
* use the user from the previous call.
*
* If an {@link ExperimentUserProvider} has been set, the argument user will
* be merged with the provider user, preferring user fields from the argument
* user and falling back on the provider for fields which are null or
* undefined.
*
* If configured, fetch retries the request in the background on failure.
* Variants received from a successful retry are stored in local storage for
* access.
*
* If you are using the `initialVariants` config option to preload this SDK
* from the server, you generally do not need to call `fetch`.
*
* @param user The user to fetch variants for.
* @param options Options for this specific fetch call.
* @returns Promise that resolves when the request for variants completes.
* @see ExperimentUser
* @see ExperimentUserProvider
*/
ExperimentClient.prototype.fetch = function (user, options) {
if (user === void 0) { user = this.user; }
return __awaiter(this, void 0, void 0, function () {
var e_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
this.setUser(user || {});
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.fetchInternal(user, this.config.fetchTimeoutMillis, this.config.retryFetchOnFailure, options)];
case 2:
_a.sent();
return [3 /*break*/, 4];
case 3:
e_1 = _a.sent();
console.error(e_1);
return [3 /*break*/, 4];
case 4: return [2 /*return*/, this];
}
});
});
};
/**
* Returns the variant for the provided key.
*
* Access the variant from {@link Source}, falling back on the given
* fallback, then the configured fallbackVariant.
*
* If an {@link ExposureTrackingProvider} is configured and the
* {@link automaticExposureTracking} configuration option is `true`, this
* function will call the provider with an {@link Exposure} event. The
* exposure event does not count towards your event volume within Amplitude.
*
* @param key The key to get the variant for.
* @param fallback The highest priority fallback.
* @see ExperimentConfig
* @see ExposureTrackingProvider
*/
ExperimentClient.prototype.variant = function (key, fallback) {
var _a, _b;
if (!this.apiKey) {
return { value: undefined };
}
var sourceVariant = this.variantAndSource(key, fallback);
if (this.config.automaticExposureTracking) {
this.exposureInternal(key, sourceVariant);
}
this.debug("[Experiment] variant for ".concat(key, " is ").concat(((_a = sourceVariant.variant) === null || _a === void 0 ? void 0 : _a.key) || ((_b = sourceVariant.variant) === null || _b === void 0 ? void 0 : _b.value)));
return sourceVariant.variant || {};
};
/**
* Track an exposure event for the variant associated with the flag/experiment
* {@link key}.
*
* This method requires that an {@link ExposureTrackingProvider} be
* configured when this client is initialized, either manually, or through the
* Amplitude Analytics SDK integration from set up using
* {@link Experiment.initializeWithAmplitudeAnalytics}.
*
* @param key The flag/experiment key to track an exposure for.
* @see ExposureTrackingProvider
*/
ExperimentClient.prototype.exposure = function (key) {
var sourceVariant = this.variantAndSource(key);
this.exposureInternal(key, sourceVariant);
};
/**
* Returns all variants for the user.
*
* The primary source of variants is based on the
* {@link Source} configured in the {@link ExperimentConfig}.
*
* @see Source
* @see ExperimentConfig
*/
ExperimentClient.prototype.all = function () {
if (!this.apiKey) {
return {};
}
var evaluatedVariants = this.evaluate();
for (var flagKey in evaluatedVariants) {
var flag = this.flags.get(flagKey);
if (!isLocalEvaluationMode(flag)) {
delete evaluatedVariants[flagKey];
}
}
return __assign(__assign(__assign({}, this.secondaryVariants()), this.sourceVariants()), evaluatedVariants);
};
/**
* Clear all variants in the cache and storage.
*/
ExperimentClient.prototype.clear = function () {
this.variants.clear();
try {
void this.variants.store();
}
catch (e) {
// catch localStorage undefined error
}
};
/**
* Get a copy of the internal {@link ExperimentUser} object if it is set.
*
* @returns a copy of the internal user object if set.
*/
ExperimentClient.prototype.getUser = function () {
var _a;
if (!this.user) {
return this.user;
}
if ((_a = this.user) === null || _a === void 0 ? void 0 : _a.user_properties) {
var userPropertiesCopy = __assign({}, this.user.user_properties);
return __assign(__assign({}, this.user), { user_properties: userPropertiesCopy });
}
else {
return __assign({}, this.user);
}
};
/**
* Copy in and set the user within the experiment client.
*
* @param user the user to set within the experiment client.
*/
ExperimentClient.prototype.setUser = function (user) {
var _a;
if (!user) {
this.user = null;
return;
}
if ((_a = this.user) === null || _a === void 0 ? void 0 : _a.user_properties) {
var userPropertiesCopy = __assign({}, user.user_properties);
this.user = __assign(__assign({}, user), { user_properties: userPropertiesCopy });
}
else {
this.user = __assign({}, user);
}
};
/**
* Get the user provider set by {@link setUserProvider} or null if the user
* provider has not been set.
*
* @returns The user provider set by {@link setUserProvider} or null.
* @deprecated use ExperimentConfig.userProvider instead
*/
ExperimentClient.prototype.getUserProvider = function () {
return this.userProvider;
};
/**
* Sets a user provider that will inject identity information into the user
* for {@link fetch()} requests. The user provider will only set user fields
* in outgoing requests which are null or undefined.
*
* See {@link ExperimentUserProvider} for more details
* @param userProvider
* @deprecated use ExperimentConfig.userProvider instead
*/
ExperimentClient.prototype.setUserProvider = function (userProvider) {
this.userProvider = userProvider;
return this;
};
ExperimentClient.prototype.mergeInitialFlagsWithStorage = function () {
var _this = this;
if (this.config.initialFlags) {
var initialFlags = JSON.parse(this.config.initialFlags);
initialFlags.forEach(function (flag) {
if (!_this.flags.get(flag.key)) {
_this.flags.put(flag.key, flag);
}
});
}
};
ExperimentClient.prototype.evaluate = function (flagKeys) {
var e_2, _a;
var user = this.addContext(this.user);
var flags = topologicalSort(this.flags.getAll(), flagKeys);
var context = convertUserToContext(user);
var evaluationVariants = this.engine.evaluate(context, flags);
var variants = {};
try {
for (var _b = __values(Object.keys(evaluationVariants)), _c = _b.next(); !_c.done; _c = _b.next()) {
var flagKey = _c.value;
variants[flagKey] = convertEvaluationVariantToVariant(evaluationVariants[flagKey]);
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_2) throw e_2.error; }
}
return variants;
};
ExperimentClient.prototype.variantAndSource = function (key, fallback) {
var sourceVariant = {};
if (this.config.source === Source.LocalStorage) {
sourceVariant = this.localStorageVariantAndSource(key, fallback);
}
else if (this.config.source === Source.InitialVariants) {
sourceVariant = this.initialVariantsVariantAndSource(key, fallback);
}
var flag = this.flags.get(key);
if (isLocalEvaluationMode(flag) || (!sourceVariant.variant && flag)) {
sourceVariant = this.localEvaluationVariantAndSource(key, flag, fallback);
}
return sourceVariant;
};
/**
* This function assumes the flag exists and is local evaluation mode. For
* local evaluation, fallback order goes:
*
* 1. Local evaluation
* 2. Inline function fallback
* 3. Initial variants
* 4. Config fallback
*
* If there is a default variant and no fallback, return the default variant.
*/
ExperimentClient.prototype.localEvaluationVariantAndSource = function (key, flag, fallback) {
var _a;
var defaultSourceVariant = {};
// Local evaluation
var variant = this.evaluate([flag.key])[key];
var source = VariantSource.LocalEvaluation;
var isLocalEvaluationDefault = (_a = variant === null || variant === void 0 ? void 0 : variant.metadata) === null || _a === void 0 ? void 0 : _a.default;
if (!isNullOrUndefined(variant) && !isLocalEvaluationDefault) {
return {
variant: convertVariant(variant),
source: source,
hasDefaultVariant: false,
};
}
else if (isLocalEvaluationDefault) {
defaultSourceVariant = {
variant: convertVariant(variant),
source: source,
hasDefaultVariant: true,
};
}
// Inline fallback
if (!isNullOrUndefined(fallback)) {
return {
variant: convertVariant(fallback),
source: VariantSource.FallbackInline,
hasDefaultVariant: defaultSourceVariant.hasDefaultVariant,
};
}
// Initial variants
var initialVariant = this.config.initialVariants[key];
if (!isNullOrUndefined(initialVariant)) {
return {
variant: convertVariant(initialVariant),
source: VariantSource.SecondaryInitialVariants,
hasDefaultVariant: defaultSourceVariant.hasDefaultVariant,
};
}
// Configured fallback, or default variant
var fallbackVariant = convertVariant(this.config.fallbackVariant);
var fallbackSourceVariant = {
variant: fallbackVariant,
source: VariantSource.FallbackConfig,
hasDefaultVariant: defaultSourceVariant.hasDefaultVariant,
};
if (!isNullUndefinedOrEmpty(fallbackVariant)) {
return fallbackSourceVariant;
}
return defaultSourceVariant;
};
/**
* For Source.LocalStorage, fallback order goes:
*
* 1. Local Storage
* 2. Inline function fallback
* 3. InitialFlags
* 4. Config fallback
*
* If there is a default variant and no fallback, return the default variant.
*/
ExperimentClient.prototype.localStorageVariantAndSource = function (key, fallback) {
var _a;
var defaultSourceVariant = {};
// Local storage
var localStorageVariant = this.variants.get(key);
var isLocalStorageDefault = (_a = localStorageVariant === null || localStorageVariant === void 0 ? void 0 : localStorageVariant.metadata) === null || _a === void 0 ? void 0 : _a.default;
if (!isNullOrUndefined(localStorageVariant) && !isLocalStorageDefault) {
return {
variant: convertVariant(localStorageVariant),
source: VariantSource.LocalStorage,
hasDefaultVariant: false,
};
}
else if (isLocalStorageDefault) {
defaultSourceVariant = {
variant: convertVariant(localStorageVariant),
source: VariantSource.LocalStorage,
hasDefaultVariant: true,
};
}
// Inline fallback
if (!isNullOrUndefined(fallback)) {
return {
variant: convertVariant(fallback),
source: VariantSource.FallbackInline,
hasDefaultVariant: defaultSourceVariant.hasDefaultVariant,
};
}
// Initial variants
var initialVariant = this.config.initialVariants[key];
if (!isNullOrUndefined(initialVariant)) {
return {
variant: convertVariant(initialVariant),
source: VariantSource.SecondaryInitialVariants,
hasDefaultVariant: defaultSourceVariant.hasDefaultVariant,
};
}
// Configured fallback, or default variant
var fallbackVariant = convertVariant(this.config.fallbackVariant);
var fallbackSourceVariant = {
variant: fallbackVariant,
source: VariantSource.FallbackConfig,
hasDefaultVariant: defaultSourceVariant.hasDefaultVariant,
};
if (!isNullUndefinedOrEmpty(fallbackVariant)) {
return fallbackSourceVariant;
}
return defaultSourceVariant;
};
/**
* For Source.InitialVariants, fallback order goes:
*
* 1. Initial variants
* 2. Local storage
* 3. Inline function fallback
* 4. Config fallback
*
* If there is a default variant and no fallback, return the default variant.
*/
ExperimentClient.prototype.initialVariantsVariantAndSource = function (key, fallback) {
var _a;
var defaultSourceVariant = {};
// Initial variants
var initialVariantsVariant = this.config.initialVariants[key];
if (!isNullOrUndefined(initialVariantsVariant)) {
return {
variant: convertVariant(initialVariantsVariant),
source: VariantSource.InitialVariants,
hasDefaultVariant: false,
};
}
// Local storage
var localStorageVariant = this.variants.get(key);
var isLocalStorageDefault = (_a = localStorageVariant === null || localStorageVariant === void 0 ? void 0 : localStorageVariant.metadata) === null || _a === void 0 ? void 0 : _a.default;
if (!isNullOrUndefined(localStorageVariant) && !isLocalStorageDefault) {
return {
variant: convertVariant(localStorageVariant),
source: VariantSource.LocalStorage,
hasDefaultVariant: false,
};
}
else if (isLocalStorageDefault) {
defaultSourceVariant = {
variant: convertVariant(localStorageVariant),
source: VariantSource.LocalStorage,
hasDefaultVariant: true,
};
}
// Inline fallback
if (!isNullOrUndefined(fallback)) {
return {
variant: convertVariant(fallback),
source: VariantSource.FallbackInline,
hasDefaultVariant: defaultSourceVariant.hasDefaultVariant,
};
}
// Configured fallback, or default variant
var fallbackVariant = convertVariant(this.config.fallbackVariant);
var fallbackSourceVariant = {
variant: fallbackVariant,
source: VariantSource.FallbackConfig,
hasDefaultVariant: defaultSourceVariant.hasDefaultVariant,
};
if (!isNullUndefinedOrEmpty(fallbackVariant)) {
return fallbackSourceVariant;
}
return defaultSourceVariant;
};
ExperimentClient.prototype.fetchInternal = function (user, timeoutMillis, retry, options) {
return __awaiter(this, void 0, void 0, function () {
var variants, e_3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// Don't even try to fetch variants if API key is not set
if (!this.apiKey) {
throw Error('Experiment API key is empty');
}
this.debug("[Experiment] Fetch all: retry=".concat(retry));
// Proactively cancel retries if active in order to avoid unnecessary API
// requests. A new failure will restart the retries.
if (retry) {
this.stopRetries();
}
_a.label = 1;
case 1:
_a.trys.push([1, 4, , 5]);
return [4 /*yield*/, this.doFetch(user, timeoutMillis, options)];
case 2:
variants = _a.sent();
return [4 /*yield*/, this.storeVariants(variants, options)];
case 3:
_a.sent();
return [2 /*return*/, variants];
case 4:
e_3 = _a.sent();
if (retry && this.shouldRetryFetch(e_3)) {
void this.startRetries(user, options);
}
throw e_3;
case 5: return [2 /*return*/];
}
});
});
};
ExperimentClient.prototype.doFetch = function (user, timeoutMillis, options) {
return __awaiter(this, void 0, void 0, function () {
var results, variants, _a, _b, key;
var e_4, _c;
return __generator(this, function (_d) {
switch (_d.label) {
case 0: return [4 /*yield*/, this.addContextOrWait(user, 10000)];
case 1:
user = _d.sent();
this.debug('[Experiment] Fetch variants for user: ', user);
return [4 /*yield*/, this.evaluationApi.getVariants(user, {
timeoutMillis: timeoutMillis,
flagKeys: options === null || options === void 0 ? void 0 : options.flagKeys,
})];
case 2:
results = _d.sent();
variants = {};
try {
for (_a = __values(Object.keys(results)), _b = _a.next(); !_b.done; _b = _a.next()) {
key = _b.value;
variants[key] = convertEvaluationVariantToVariant(results[key]);
}
}
catch (e_4_1) { e_4 = { error: e_4_1 }; }
finally {
try {
if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
}
finally { if (e_4) throw e_4.error; }
}
this.debug('[Experiment] Received variants: ', variants);
return [2 /*return*/, variants];
}
});
});
};
ExperimentClient.prototype.doFlags = function () {
return __awaiter(this, void 0, void 0, function () {
var flags;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.flagApi.getFlags({
libraryName: 'experiment-js-client',
libraryVersion: version,
timeoutMillis: this.config.fetchTimeoutMillis,
})];
case 1:
flags = _a.sent();
this.flags.clear();
this.flags.putAll(flags);
try {
this.flags.store();
}
catch (e) {
// catch localStorage undefined error
}
this.mergeInitialFlagsWithStorage();
return [2 /*return*/];
}
});
});
};
ExperimentClient.prototype.storeVariants = function (variants, options) {
return __awaiter(this, void 0, void 0, function () {
var failedFlagKeys, _loop_1, this_1, key, key;
return __generator(this, function (_a) {
failedFlagKeys = options && options.flagKeys ? options.flagKeys : [];
if (failedFlagKeys.length === 0) {
this.variants.clear();
}
_loop_1 = function (key) {
failedFlagKeys = failedFlagKeys.filter(function (flagKey) { return flagKey !== key; });
this_1.variants.put(key, variants[key]);
};
this_1 = this;
for (key in variants) {
_loop_1(key);
}
for (key in failedFlagKeys) {
this.variants.remove(key);
}
try {
this.variants.store();
}
catch (e) {
// catch localStorage undefined error
}
this.debug('[Experiment] Stored variants: ', variants);
return [2 /*return*/];
});
});
};
ExperimentClient.prototype.startRetries = function (user, options) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
this.debug('[Experiment] Retry fetch');
this.retriesBackoff = new Backoff(fetchBackoffAttempts, fetchBackoffMinMillis, fetchBackoffMaxMillis, fetchBackoffScalar);
void this.retriesBackoff.start(function () { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.fetchInternal(user, fetchBackoffTimeout, false, options)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
}); });
return [2 /*return*/];
});
});
};
ExperimentClient.prototype.stopRetries = function () {
if (this.retriesBackoff) {
this.retriesBackoff.cancel();
}
};
ExperimentClient.prototype.addContext = function (user) {
var _a, _b;
var providedUser = (_a = this.userProvider) === null || _a === void 0 ? void 0 : _a.getUser();
var mergedUserProperties = __assign(__assign({}, user === null || user === void 0 ? void 0 : user.user_properties), providedUser === null || providedUser === void 0 ? void 0 : providedUser.user_properties);
return __assign(__assign(__assign({ library: "experiment-js-client/".concat(version) }, (_b = this.userProvider) === null || _b === void 0 ? void 0 : _b.getUser()), user), { user_properties: mergedUserProperties });
};
ExperimentClient.prototype.addContextOrWait = function (user, ms) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!(this.userProvider instanceof DefaultUserProvider)) return [3 /*break*/, 2];
if (!(this.userProvider.userProvider instanceof ConnectorUserProvider)) return [3 /*break*/, 2];
return [4 /*yield*/, this.userProvider.userProvider.identityReady(ms)];
case 1:
_a.sent();
_a.label = 2;
case 2: return [2 /*return*/, this.addContext(user)];
}
});
});
};
ExperimentClient.prototype.sourceVariants = function () {
if (this.config.source == Source.LocalStorage) {
return this.variants.getAll();
}
else if (this.config.source == Source.InitialVariants) {
return this.config.initialVariants;
}
};
ExperimentClient.prototype.secondaryVariants = function () {
if (this.config.source == Source.LocalStorage) {
return this.config.initialVariants;
}
else if (this.config.source == Source.InitialVariants) {
return this.variants.getAll();
}
};
ExperimentClient.prototype.exposureInternal = function (key, sourceVariant) {
var _a, _b, _c, _d, _e, _f;
this.legacyExposureInternal(key, sourceVariant.variant, sourceVariant.source);
var exposure = { flag_key: key };
// Do not track exposure for fallback variants that are not associated with
// a default variant.
var fallback = isFallback(sourceVariant.source);
if (fallback && !sourceVariant.hasDefaultVariant) {
return;
}
if ((_a = sourceVariant.variant) === null || _a === void 0 ? void 0 : _a.expKey) {
exposure.experiment_key = (_b = sourceVariant.variant) === null || _b === void 0 ? void 0 : _b.expKey;
}
var metadata = (_c = sourceVariant.variant) === null || _c === void 0 ? void 0 : _c.metadata;
if (!fallback && !(metadata === null || metadata === void 0 ? void 0 : metadata.default)) {
if ((_d = sourceVariant.variant) === null || _d === void 0 ? void 0 : _d.key) {
exposure.variant = sourceVariant.variant.key;
}
else if ((_e = sourceVariant.variant) === null || _e === void 0 ? void 0 : _e.value) {
exposure.variant = sourceVariant.variant.value;
}
}
if (metadata)
exposure.metadata = metadata;
(_f = this.exposureTrackingProvider) === null || _f === void 0 ? void 0 : _f.track(exposure);
};
ExperimentClient.prototype.legacyExposureInternal = function (key, variant, source) {
var _a, _b, _c, _d, _e;
if (this.analyticsProvider) {
var user = this.addContext(this.getUser());
var event_1 = exposureEvent(user, key, variant, source);
if (isFallback(source) || !(variant === null || variant === void 0 ? void 0 : variant.value)) {
(_b = (_a = this.analyticsProvider) === null || _a === void 0 ? void 0 : _a.unsetUserProperty) === null || _b === void 0 ? void 0 : _b.call(_a, event_1);
}
else if (variant === null || variant === void 0 ? void 0 : variant.value) {
(_d = (_c = this.analyticsProvider) === null || _c === void 0 ? void 0 : _c.setUserProperty) === null || _d === void 0 ? void 0 : _d.call(_c, event_1);
(_e = this.analyticsProvider) === null || _e === void 0 ? void 0 : _e.track(event_1);
}
}
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
ExperimentClient.prototype.debug = function (message) {
var optionalParams = [];
for (var _i = 1; _i < arguments.length; _i++) {
optionalParams[_i - 1] = arguments[_i];
}
if (this.config.debug) {
console.debug.apply(console, __spreadArray([message], __read(optionalParams), false));
}
};
ExperimentClient.prototype.shouldRetryFetch = function (e) {
if (e instanceof FetchError) {
return e.statusCode < 400 || e.statusCode >= 500 || e.statusCode === 429;
}
return true;
};
return ExperimentClient;
}());
var instances = {};
/**
* Initializes a singleton {@link ExperimentClient} identified by the configured
* instance name.
*
* @param apiKey The deployment API Key
* @param config See {@link ExperimentConfig} for config options
*/
var initialize = function (apiKey, config) {
// Store instances by appending the instance name and api key. Allows for
// initializing multiple default instances for different api keys.
var instanceName = (config === null || config === void 0 ? void 0 : config.instanceName) || Defaults.instanceName;
var instanceKey = "".concat(instanceName, ".").concat(apiKey);
var connector = AnalyticsConnector.getInstance(instanceName);
if (!instances[instanceKey]) {
config = __assign(__assign({}, config), { userProvider: new DefaultUserProvider(connector.applicationContextProvider, config === null || config === void 0 ? void 0 : config.userProvider) });
instances[instanceKey] = new ExperimentClient(apiKey, config);
}
return instances[instanceKey];
};
/**
* Initialize a singleton {@link ExperimentClient} which automatically
* integrates with the installed and initialized instance of the amplitude
* analytics SDK.
*
* You must be using amplitude-js SDK version 8.17.0+ for this integration to
* work.
*
* @param apiKey The deployment API Key
* @param config See {@link ExperimentConfig} for config options
*/
var initializeWithAmplitudeAnalytics = function (apiKey, config) {
// Store instances by appending the instance name and api key. Allows for
// initializing multiple default instances for different api keys.
var instanceName = (config === null || config === void 0 ? void 0 : config.instanceName) || Defaults.instanceName;
var instanceKey = "".concat(instanceName, ".").concat(apiKey);
var connector = AnalyticsConnector.getInstance(instanceName);
if (!instances[instanceKey]) {
config = __assign({ userProvider: new DefaultUserProvider(connector.applicationContextProvider, new ConnectorUserProvider(connector.identityStore)), exposureTrackingProvider: new ConnectorExposureTrackingProvider(connector.eventBridge) }, config);
instances[instanceKey] = new ExperimentClient(apiKey, config);
if (config.automaticFetchOnAmplitudeIdentityChange) {
connector.identityStore.addIdentityListener(function () {
instances[instanceKey].fetch();
});
}
}
return instances[instanceKey];
};
/**
* Provides factory methods for storing singleton instances of {@link ExperimentClient}
* @category Core Usage
*/
var Experiment = {
initialize: initialize,
initializeWithAmplitudeAnalytics: initializeWithAmplitudeAnalytics,
};
/**
* A stub {@link Client} implementation that does nothing for all methods
*/
var StubExperimentClient = /** @class */ (function () {
function StubExperimentClient() {
}
StubExperimentClient.prototype.getUser = function () {
return {};
};
StubExperimentClient.prototype.start = function (user) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/];
});
});
};
StubExperimentClient.prototype.stop = function () { };
StubExperimentClient.prototype.setUser = function (user) { };
StubExperimentClient.prototype.fetch = function (user) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this];
});
});
};
StubExperimentClient.prototype.getUserProvider = function () {
return null;
};
StubExperimentClient.prototype.setUserProvider = function (uerProvider) {
return this;
};
StubExperimentClient.prototype.variant = function (key, fallback) {
return Defaults.fallbackVariant;
};
StubExperimentClient.prototype.all = function () {
return {};
};
StubExperimentClient.prototype.clear = function () { };
StubExperimentClient.prototype.exposure = function (key) { };
return StubExperimentClient;
}());
export { AmplitudeAnalyticsProvider, AmplitudeUserProvider, Experiment, ExperimentClient, Source, StubExperimentClient };
webpack://frontend-mybets/../../packages/urp-lib-amplitude-experiments/src/useExperiments.ts
import { useState } from "react";
import {
Experiment,
ExperimentClient,
ExperimentConfig,
ExperimentUser
} from "@amplitude/experiment-js-client";
import { Variant } from "./types";
/**
* Base hook to instantiate experiments
* @param deploymentKey Deployment key for the experiment we are fetching
* @param withAnalytics Flag that decides if experiments is plugged in to Analytics or not
* @returns experiment client, getVariant, setUserExperiment
*/
const useExperiments = (
deploymentKey: string,
config?: ExperimentConfig,
withAnalytics: boolean = true
) => {
const [experiment, setExperiment] = useState<ExperimentClient>(
withAnalytics
? Experiment.initializeWithAmplitudeAnalytics(
deploymentKey,
// https://www.docs.developers.amplitude.com/experiment/sdks/javascript-sdk/#configuration
{
automaticFetchOnAmplitudeIdentityChange: true,
...config
}
)
: Experiment.initialize(deploymentKey, {})
);
/**
*
* @param user Fetch Experiment's data for a given user (recommended only for experiments not initialized with analytics)
* @returns experiment client
*/
const setUserExperiment = (user: ExperimentUser) =>
experiment
.fetch(user)
.then((res) => {
setExperiment(res);
return res;
})
.catch((e) => {
// eslint-disable-next-line no-console
console.error("Experiments ->", e);
return null;
});
/**
* Gets the variant by the experiment key and it returns an undefined as a fallback
* @param experimentKey key of experiment
* @returns Variant or undefined
*/
const getVariant = <V, P>(experimentKey: string): Variant<V, P> | undefined =>
experiment.variant(experimentKey, undefined) as Variant<V, P> | undefined;
return {
experiment,
getVariant,
setUserExperiment
};
};
export default useExperiments;
webpack://frontend-mybets/../../packages/urp-lib-amplitude-experiments/src/constants.ts
import tvgConf from "@tvg/conf";
import { get } from "lodash";
import { EnvKey, KeysList } from "./types";
const KEYS_LIST: KeysList = {
qa: {
fdr_fe: {
web: "client-sJeHwbwoOdpgTjlausdjWW5szEQK3PMG"
},
tvg: {
web: "client-jnKlEobFN5VznDxIalCa79Cxx11b03PZ"
},
sbk: {
ios: "client-hGUIVcs9WJyi9qBb65hmoxoNWgcwcJdg",
android: "client-em33htTASmGwBq2PuooW9BGrBaHPL8v3",
web: "client-YA2sGyaXthgkCAsBCEbrx4OD6Oy02ItY"
}
},
staging: {
tvg: {
web: "client-DybuPFka20yiegOqJwv7R3t4TZBFgvzd"
},
fdr_fe: {
web: "client-WGddpVy4j4U8ouXQajgXL5qwQNrjiM0v"
},
sbk: {
ios: "client-hGUIVcs9WJyi9qBb65hmoxoNWgcwcJdg",
android: "client-em33htTASmGwBq2PuooW9BGrBaHPL8v3",
web: "client-YA2sGyaXthgkCAsBCEbrx4OD6Oy02ItY"
}
},
production: {
fdr_fe: {
web: "client-UxgLTJk47Cc6ce5aUb7gcwUvH1tCcDSp"
},
tvg: {
web: "client-QWuoGcQ3o0cUyK9IvZLiB3BZZ2eSa6QN"
},
sbk: {
ios: "client-25U3VqPyrxX2F1Nc4FmbKBcXTLCXkAi3",
android: "client-qENtN9i7TECUlin6ww2zU9th6496lKQi",
web: "client-5xlIVGL8e7Nfnt2H6wIgLm7p8Ked2VTH"
}
}
};
const { environment = "production" } = tvgConf();
const mapEnvironment = (env: string) => {
if (env === "aws-stg" || env === "staging") return "staging";
if (env === "aws-prd" || env === "production") return "production";
if (env === "aws-int" || env === "qa") return "qa";
return "production";
};
export const ENV_KEYS: EnvKey = get(
KEYS_LIST,
mapEnvironment(environment),
KEYS_LIST.production
);
webpack://frontend-mybets/../../packages/urp-lib-amplitude-experiments/src/experiments/useTvg5/types.ts
export enum ValueEnum {
TVG4 = "tvg4",
TVG5 = "tvg5"
}
export interface Props {
accountNumber: string;
}
webpack://frontend-mybets/../../packages/urp-lib-amplitude-experiments/src/experiments/useTalentPickNewOption/types.ts
export enum VariantEnum {
HOME = "home-header-section",
SECTION = "account-panel-section",
OPTION = "account-panel-option"
}
export interface Payload {
to?: string;
label?: string;
qaLabel?: string;
iconName?: string;
}
webpack://frontend-mybets/../../packages/urp-lib-amplitude-experiments/src/types.ts
export interface Variant<V, P> {
value: V | undefined;
payload: P | null;
}
export interface EnvKey {
fdr_fe: {
web: string;
};
tvg: {
web: string;
};
sbk: {
ios: string;
android: string;
web: string;
};
}
export interface KeysList {
qa: EnvKey;
staging: EnvKey;
production: EnvKey;
}
export enum VariantEnum {
CONTROL = "control",
TREATMENT = "treatment"
}
webpack://frontend-mybets/../../packages/urp-lib-amplitude-experiments/src/experiments/useTvg5/constants.ts
import { ENV_KEYS } from "../../constants";
export const EXPERIMENT_KEY =
"qfd-374-replace-beta-program-by-amplitude-experiment";
export const DEPLOYMENT_KEY = ENV_KEYS.tvg.web;
export const TVG5_COOKIE = "useTvg5";
webpack://frontend-mybets/../../packages/urp-lib-amplitude-experiments/src/utils.ts
import { getDeviceId } from "@amplitude/analytics-browser";
import { Variant } from "@amplitude/experiment-js-client";
import { isAndroid, isIos, isXSell } from "@tvg/sh-utils/mobileUtils";
import { getFdUserId } from "@urp/store-selectors";
import { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import { ENV_KEYS } from "./constants";
import { VariantEnum } from "./types";
import useExperiments from "./useExperiments";
export const getXsellKeys = () => {
if (isIos()) return ENV_KEYS.sbk.ios;
if (isAndroid()) return ENV_KEYS.sbk.android;
return ENV_KEYS.sbk.web;
};
export const DEPLOYMENT_KEY = isXSell() ? getXsellKeys() : ENV_KEYS.fdr_fe.web;
export const useIsTreatmentVariant = (experimentKey: string) => {
const { getVariant } = useExperiments(DEPLOYMENT_KEY);
const variant = getVariant<VariantEnum, boolean>(experimentKey);
return variant?.value === VariantEnum.TREATMENT;
};
export const useIsTreatmentVariantByUser = (experimentKey: string) => {
const { setUserExperiment, getVariant } = useExperiments(DEPLOYMENT_KEY);
const [variant, setVariant] = useState<Variant>();
const accountNumber = useSelector(getFdUserId);
const deviceId = getDeviceId();
useEffect(() => {
setUserExperiment({ user_id: accountNumber, device_id: deviceId }).then(
() => {
setVariant(getVariant<VariantEnum, number>(experimentKey));
}
);
}, [accountNumber, deviceId]);
return variant?.value === VariantEnum.TREATMENT;
};
webpack://frontend-mybets/../../packages/urp-lib-amplitude-experiments/src/experiments/useAutoPlayPPVideos/types.ts
export enum VariantEnum {
CONTROL = "control",
TREATMENT = "treatment",
OFF = "off"
}
export interface AutoPlayConfig {
autoPlay: boolean;
mtpThreshold: number;
}
webpack://frontend-mybets/../../packages/urp-lib-amplitude-experiments/src/experiments/useAutoPlayPPVideos/utils.ts
import { Variant } from "../../types";
import { DEFAULT_PAYLOAD } from "./constants";
import { AutoPlayConfig, VariantEnum } from "./types";
export const parseResponse = (
variant: Variant<VariantEnum, number> | undefined
): AutoPlayConfig => ({
autoPlay: variant?.value === VariantEnum.TREATMENT,
mtpThreshold:
variant?.payload && !Number.isNaN(variant.payload)
? variant.payload
: DEFAULT_PAYLOAD
});
webpack://frontend-mybets/../../packages/urp-lib-amplitude-experiments/src/experiments/useURPProgramPageOnXSell/index.ts
import { isXSell } from "@tvg/sh-utils/mobileUtils";
import { EXPERIMENT_KEY } from "./constants";
import { DEPLOYMENT_KEY } from "../../utils";
import useExperiments from "../../useExperiments";
type Variant = {
shouldEnablePPOnXSell: boolean;
};
export const useURPProgramPageOnXSell = () => {
const { getVariant } = useExperiments(DEPLOYMENT_KEY);
const variant = getVariant<unknown, Variant>(EXPERIMENT_KEY);
return isXSell() && !!variant?.payload?.shouldEnablePPOnXSell;
};
webpack://frontend-mybets/../../packages/urp-lib-amplitude-experiments/src/experiments/useURPProgramPageOnXSell/constants.ts
export const EXPERIMENT_KEY = "mcn-826-urp-pp-on-x-sell";
webpack://frontend-mybets/../../packages/sh-lib-my-bets/utils/betsBetCard.ts
import { BetSelection } from "@tvg/ts-types/Bet";
import { Selections } from "@tvg/ts-types/Selections";
export const calculateShowBetsDetailedView = (
selections: BetSelection[][] | Selections[][],
showWillPays: boolean
): boolean[] => {
const selectionsLength = selections.length - 1;
return selections.map(
(_obj, index) =>
!!(selectionsLength > 0 && index === selectionsLength && showWillPays)
);
};
webpack://frontend-mybets/../../packages/sh-lib-my-bets/utils/runnerNumberGroupUtils.ts
import { get, includes } from "lodash";
import { BetSelection } from "@tvg/ts-types/Bet";
import { WagerTypeCodesEnum } from "@tvg/ts-types/Wager";
const getWagerTypeIndex = (wagerCode: string, payoutsTitle: string[] = []) => {
const payoutsCharCode = payoutsTitle.map((title) => title[0]);
const charWagerCode = wagerCode[0];
return payoutsCharCode.findIndex(
(payoutCode) => payoutCode.toLowerCase() === charWagerCode.toLowerCase()
);
};
export const getWillPaysSimpleRace = (
runner: BetSelection,
payoutsTitles: string[] = []
) => {
const payoutsTitlesLength = payoutsTitles.length;
const payoutsTable = new Array(payoutsTitlesLength).fill(null);
(get(runner, "payouts") || []).forEach((payout) => {
const wagerCode = get(payout, "wagerType.code");
const amount = get(payout, "amount", 0);
const payoutsTableIndex = getWagerTypeIndex(wagerCode, payoutsTitles);
if (payoutsTableIndex >= 0) {
payoutsTable[payoutsTableIndex] = amount;
}
});
return payoutsTable;
};
export const getPayoutsHeaderTitle = (
wagerTypeCode: WagerTypeCodesEnum,
runners: BetSelection[]
) => {
const wagerCode = wagerTypeCode || "";
const raceFinished = !!runners.find(
(runner) => get(runner, "payouts.length") > 0
);
const hasPayouts = {
win: raceFinished && wagerCode.includes("W"),
place: raceFinished && wagerCode.includes("P"),
show: raceFinished && wagerCode.includes("S")
};
return Object.entries(hasPayouts).reduce(
(accPayouts: string[], currPayout) => {
const [payoutKey, payoutValue] = currPayout;
if (payoutValue) {
return [...accPayouts, payoutKey];
}
return accPayouts;
},
[]
);
};
export const checkFavoriteSequence = (
runner: BetSelection,
favorites: string[],
lastFavoriteAdded: string,
doubleEntryRegex: RegExp
) =>
lastFavoriteAdded &&
!includes(favorites, runner.runnerNumber) &&
((doubleEntryRegex.test(runner.runnerNumber) &&
(lastFavoriteAdded === runner.runnerNumber ||
parseInt(lastFavoriteAdded, 10) === parseInt(runner.runnerNumber, 10))) ||
parseInt(lastFavoriteAdded, 10) + 1 === parseInt(runner.runnerNumber, 10));
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/RunnerNumber/styled-components.js
import styled, { css } from "styled-components";
import Icon from "../../_static/Icons";
import { generateTransition, cubic } from "../../_static/Transitions";
import { fontMedium } from "../../_static/Typography";
import buildColor from "../../_static/ColorPalette";
export const StarIcon = styled(Icon)`
position: absolute;
${({ isBetsStandalone }) =>
isBetsStandalone
? css`
top: -5px;
left: -5px;
`
: css`
top: -4px;
right: -2px;
`}
`;
export const SelectIcon = styled(Icon)`
transform: ${(props) =>
props.isRotated ? "rotate(180deg)" : "rotate(0deg)"};
will-change: transform;
transition: ${generateTransition(cubic, "transform")};
`;
export const WinnerIconWrapper = styled.div`
position: absolute;
bottom: -4px;
right: -4px;
width: 12px;
height: 12px;
background: ${buildColor("green", "500")};
border-radius: 50%;
border: 1px solid ${buildColor("green", "000")};
z-index: 2;
`;
export const WinnerIcon = styled(Icon)`
position: absolute;
top: 1px;
left: 1px;
`;
const sharedScratchedStyles = css`
position: absolute;
top: 0;
left: 0;
width: 20px;
height: 20px;
`;
export const RunnerNumberAtom = styled.span`
font-size: 12px;
color: ${(props) => props.numberColor};
position: relative;
text-shadow: ${(props) => props.textShadow};
background: ${(props) => props.gradient};
border: ${(props) => props.border};
display: flex;
align-items: center;
justify-content: center;
background-color: ${(props) => props.saddleColor};
flex-direction: ${(props) => props.flexDirection};
font-family: ${fontMedium};
border-radius: 1px;
${({
isBetsStandalone,
isActiveMultiRaceLegOver,
isWinnerBI,
isRaceOver,
isScratched,
isBetsDetailedView,
isAllRunners
}) =>
(isBetsStandalone && isActiveMultiRaceLegOver && !isWinnerBI) ||
(isBetsStandalone && !isRaceOver && isScratched && !isBetsDetailedView) ||
(isBetsStandalone && isAllRunners && isActiveMultiRaceLegOver)
? css`
opacity: 0.2;
`
: css`
opacity: 1;
`}
${({ isBetsStandalone, isWinnerBI, isUnknownWinnerStatus }) =>
isBetsStandalone
? css`
height: 20px;
min-width: 20px;
padding: 0 2px;
${(isWinnerBI || isUnknownWinnerStatus) && "z-index: 2;"}
`
: css`
width: 100%;
height: 100%;
min-width: 16px;
min-height: 16px;
font-weight: bold;
`}
${({
isBetsStandalone,
isScratched,
isBetsDetailedView,
isRaceOver,
isUnknownWinnerStatus
}) =>
!isUnknownWinnerStatus &&
isBetsStandalone &&
isScratched &&
!isBetsDetailedView &&
isRaceOver &&
css`
&::before {
content: "";
${sharedScratchedStyles};
background-color: ${buildColor("white", "40")};
z-index: 2;
}
`}
`;
export const ScratchedBoxIconContainer = styled.div`
${sharedScratchedStyles};
z-index: 1;
`;
export const AlternateIconContainer = styled.div`
display: inline-flex;
position: absolute;
top: -8px;
right: -8px;
z-index: 2;
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/RunnerNumber/SaddleColors/thoroughbred.js
const colors = [
{
number: 0,
numberColor: "#FFFFFF",
saddleColor: "#C20E0E"
},
{
number: 1,
numberColor: "#FFFFFF",
saddleColor: "#C20E0E"
},
{
number: 2,
numberColor: "#000000",
saddleColor: "#BCC8C8"
},
{
number: 3,
numberColor: "#FFFFFF",
saddleColor: "#3B4E8C"
},
{
number: 4,
numberColor: "#000000",
saddleColor: "#D3B13C"
},
{
number: 5,
numberColor: "#FFFFFF",
saddleColor: "#116410"
},
{
number: 6,
numberColor: "#FFFFFF",
saddleColor: "#303030"
},
{
number: 7,
numberColor: "#000000",
saddleColor: "#D65A2F"
},
{
number: 8,
numberColor: "#000000",
saddleColor: "#E095AA"
},
{
number: 9,
numberColor: "#000000",
saddleColor: "#2AAAA5"
},
{
number: 10,
numberColor: "#FFFFFF",
saddleColor: "#713A98"
},
{
number: 11,
numberColor: "#FFFFFF",
saddleColor: "#6B6B6B"
},
{
number: 12,
numberColor: "#000000",
saddleColor: "#4EA958"
},
{
number: 13,
numberColor: "#FFFFFF",
saddleColor: "#58514D"
},
{
number: 14,
numberColor: "#FFFFFF",
saddleColor: "#94335A"
},
{
number: 15,
numberColor: "#FFFFFF",
saddleColor: "#69522F"
},
{
number: 16,
numberColor: "#FFFFFF",
saddleColor: "#4C6E9F"
},
{
number: 17,
numberColor: "#FFFFFF",
saddleColor: "#373786"
},
{
number: 18,
numberColor: "#FFFFFF",
saddleColor: "#285F23"
},
{
number: 19,
numberColor: "#FFFFFF",
saddleColor: "#32496D"
},
{
number: 20,
numberColor: "#FFFFFF",
saddleColor: "#671334"
}
];
export default colors;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/RunnerNumber/SaddleColors/harness.js
const colors = [
{
number: 0,
numberColor: "#FFFFFF",
saddleColor: "#AF0000"
},
{
number: 1,
numberColor: "#FFFFFF",
saddleColor: "#AF0000"
},
{
number: 2,
numberColor: "#FFFFFF",
saddleColor: "#253C85"
},
{
number: 3,
numberColor: "#000000",
saddleColor: "#B2B4B1"
},
{
number: 4,
numberColor: "#FFFFFF",
saddleColor: "#1C5B1B"
},
{
number: 5,
numberColor: "#FFFFFF",
saddleColor: "#252525"
},
{
number: 6,
numberColor: "#000000",
saddleColor: "#B69E00"
},
{
number: 7,
numberColor: "#000000",
saddleColor: "#B27492"
},
{
number: 8,
numberColor: "#FFFFFF",
saddleColor: "#6B6B6B"
},
{
number: 9,
numberColor: "#FFFFFF",
saddleColor: "#610F9A"
},
{
number: 10,
numberColor: "#FFFFFF",
saddleColor: "#263D88"
},
{
number: 11,
numberColor: "#FFFFFF",
saddleColor: "#3B5E90"
},
{
number: 12,
numberColor: "#FFFFFF",
saddleColor: "#A90000"
},
{
number: 13,
numberColor: "#FFFFFF",
saddleColor: "#1D5E1C"
},
{
number: 14,
numberColor: "#FFFFFF",
saddleColor: "#725933"
},
{
number: 15,
numberColor: "#FFFFFF",
saddleColor: "#C0C0C0"
}
];
export default colors;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/RunnerNumber/SaddleColors/greyhound.js
const whiteTextStroke = `-1px -1px 0 white,
-1px 0 0 white,
-1px 1px 0 white,
1px -1px 0 white,
1px 0 0 white,
1px 1px 0 white,
0 1px 0 white`;
const colors = [
{
number: 0,
numberColor: "#ffffff",
saddleColor: "#c30d0d"
},
{
number: 1,
numberColor: "#ffffff",
saddleColor: "#c30d0d"
},
{
number: 2,
numberColor: "#ffffff",
saddleColor: "#3b4e8c"
},
{
number: 3,
numberColor: "#000000",
saddleColor: "#ffffff",
border: "solid 1px #CCC"
},
{
number: 4,
numberColor: "#ffffff",
saddleColor: "#116410"
},
{
number: 5,
numberColor: "#c20e0e",
saddleColor: "#303030",
textShadow: whiteTextStroke
},
{
number: 6,
numberColor: "#000000",
saddleColor: "#d3b13c"
},
{
number: 7,
numberColor: "#000000",
saddleColor: "#5d9634",
textShadow: whiteTextStroke,
border: "solid 1px #CCC",
gradient: `linear-gradient(
to bottom,
white 0,
white 14%,
#5d9634 14%,
#5d9634 29%,
white 29%,
white 43%,
#5d9634 43%,
#5d9634 57%,
white 57%,
white 71%,
#5d9634 71%,
#5d9634 86%,
white 86%,
white 100%
)`
},
{
number: 8,
numberColor: "#ffffff",
saddleColor: "#303030",
gradient: `linear-gradient(
to right,
#303030 12.5%,
#d3b13c 12.5%,
#d3b13c 25%,
#303030 25%,
#303030 75%,
#d3b13c 75%,
#d3b13c 87.5%,
#303030 87.5%
)`
},
{
number: 9,
numberColor: "#ffffff",
saddleColor: "#713a98"
}
];
export default colors;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/RunnerNumber/SaddleColors/index.js
import thoroughbred from "./thoroughbred";
import harness from "./harness";
import greyhound from "./greyhound";
import buildColor from "../../../_static/ColorPalette";
const empty = {
number: 0,
saddleColor: buildColor("blue", "000"),
numberColor: buildColor("grey", "900")
};
const getSaddleColor = (raceType, saddleNumber) => {
if (isNaN(saddleNumber)) {
return empty;
}
switch (raceType.toUpperCase()) {
case "H":
return harness[saddleNumber] || harness[0];
case "G":
return greyhound[saddleNumber] || greyhound[0];
case "T":
default:
return thoroughbred[saddleNumber] || thoroughbred[0];
}
};
export default getSaddleColor;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/RunnerNumber/index.jsx
import React, { PureComponent } from "react";
import {
SelectIcon,
StarIcon,
WinnerIconWrapper,
WinnerIcon,
RunnerNumberAtom,
ScratchedBoxIconContainer,
AlternateIconContainer
} from "./styled-components";
import getColor from "./SaddleColors";
import {
starOutlineFill,
arrowDown,
star,
tick
} from "../../_static/Icons/icons";
import { scratchedBox } from "../../_static/Icons/iconsDuotone";
import buildColor from "../../_static/ColorPalette";
import Icon from "../../_static/Icons";
const DoubleArrowIcon = () => (
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
>
<g clipPath="url(#clip0_12166_13982)">
<path
d="M5.5 5.4999C5.5 5.77604 5.72386 5.9999 6 5.9999L11.6667 5.9999L10.4187 7.31024C10.2283 7.51021 10.236 7.8267 10.436 8.01714L11.1601 8.7068C11.2561 8.79825 11.3845 8.84781 11.5171 8.84458C11.6497 8.84134 11.7755 8.78558 11.867 8.68955L14.7241 5.68955C15.092 5.30335 15.092 4.69645 14.7241 4.31024L11.867 1.31024C11.7755 1.21422 11.6497 1.15845 11.5171 1.15522C11.3845 1.15199 11.2561 1.20155 11.1601 1.293L10.436 1.98266C10.236 2.1731 10.2283 2.48959 10.4187 2.68955L11.6667 3.9999L6 3.9999C5.86739 3.9999 5.74021 4.05258 5.64645 4.14635C5.55268 4.24011 5.5 4.36729 5.5 4.4999L5.5 5.4999Z"
fill="white"
stroke="#05285A"
strokeLinejoin="round"
/>
<path
d="M10.5 10.5001C10.5 10.3675 10.4473 10.2403 10.3536 10.1465C10.2598 10.0528 10.1326 10.0001 10 10.0001L4.33333 10.0001L5.58128 8.68976C5.67273 8.59373 5.72229 8.46531 5.71906 8.33274C5.71583 8.20017 5.66006 8.07431 5.56404 7.98286L4.8399 7.2932C4.63993 7.10276 4.32345 7.11048 4.133 7.31045L1.27586 10.3104C0.908046 10.6967 0.908046 11.3035 1.27586 11.6898L4.133 14.6898C4.22446 14.7858 4.35031 14.8415 4.48288 14.8448C4.61545 14.848 4.74387 14.7985 4.8399 14.707L5.56404 14.0173C5.764 13.8269 5.77172 13.5104 5.58128 13.3104L4.33333 12.0001L10 12.0001C10.2761 12.0001 10.5 11.7762 10.5 11.5001L10.5 10.5001Z"
fill="white"
stroke="#05285A"
strokeLinejoin="round"
/>
</g>
<defs>
<clipPath id="clip0_12166_13982">
<rect width="16" height="16" fill="white" />
</clipPath>
</defs>
</svg>
);
export default class RunnerNumber extends PureComponent {
static defaultProps = {
qaLabel: "runnerNumber",
runnerId: "",
raceTypeCode: "T",
isFavorite: false,
arrowDirection: "none",
isBetsStandalone: false,
isScratched: false,
isAllRunners: false,
isWinnerBI: false,
isActiveMultiRaceLegOver: false,
isRaceOver: false,
isBetsDetailedView: false,
isUnknownWinnerStatus: false,
isAlternate: false
};
render() {
const saddle = getColor(
this.props.raceTypeCode,
parseInt(this.props.runnerId, 10)
);
return (
<RunnerNumberAtom
data-qa-label={`${this.props.qaLabel}-${this.props.runnerId}`}
saddleColor={
!this.props.isAllRunners
? this.props.saddleColor || saddle.saddleColor
: buildColor("blue", "100")
}
numberColor={
!this.props.isAllRunners
? this.props.numberColor || saddle.numberColor
: buildColor("black", "100")
}
gradient={
!this.props.isAllRunners ? saddle.gradient : buildColor("blue", "100")
}
textShadow={saddle.textShadow}
isFavorite={this.props.isFavorite}
border={saddle.border}
flexDirection={this.props.arrowDirection !== "none" ? "column" : "row"}
isRotated={this.props.arrowDirection === "up"}
isBetsStandalone={this.props.isBetsStandalone}
isScratched={this.props.isScratched}
isWinnerBI={this.props.isWinnerBI}
isActiveMultiRaceLegOver={this.props.isActiveMultiRaceLegOver}
isBetsDetailedView={this.props.isBetsDetailedView}
isAllRunners={this.props.isAllRunners}
isRaceOver={this.props.isRaceOver}
isUnknownWinnerStatus={this.props.isUnknownWinnerStatus}
>
{this.props.isAlternate && (
<AlternateIconContainer>
<DoubleArrowIcon />
</AlternateIconContainer>
)}
{this.props.isBetsStandalone && this.props.isScratched && (
<ScratchedBoxIconContainer>
<Icon
icon={scratchedBox}
viewBoxSize={20}
size={20}
color={buildColor("grey", "900")}
/>
</ScratchedBoxIconContainer>
)}
{this.props.isWinnerBI && !this.props.isScratched && (
<WinnerIconWrapper>
<WinnerIcon
size={8}
icon={tick}
color={buildColor("green", "000")}
/>
</WinnerIconWrapper>
)}
{this.props.isFavorite && (
/* TODO update icon according to design for bet standalone */
<StarIcon
size={this.props.isBetsStandalone ? 12 : 9}
icon={this.props.isBetsStandalone ? star : starOutlineFill}
color={buildColor("yellow", "500")}
isBetsStandalone={this.props.isBetsStandalone}
/>
)}
{!this.props.runnerId ? "?" : this.props.runnerId}
{this.props.arrowDirection !== "none" && (
<SelectIcon
isRotated={this.props.arrowDirection === "up"}
icon={arrowDown}
size={12}
color={saddle.numberColor}
/>
)}
</RunnerNumberAtom>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MybetsRunnerNumberGroup/constant.ts
// @ts-ignore
import buildColor from "../../_static/ColorPalette";
import {
successRound,
errorRound,
questionMarkRound,
exclamationMarkRound
// @ts-ignore
} from "../../_static/Icons/iconsDuotone";
export const iconStyles = {
open: {
border: "transparent",
background: "transparent",
dotColor: buildColor("grey", "600"),
textColor: buildColor("grey", "800"),
iconColor: buildColor("grey", "600"),
trackingColor: buildColor("grey", "300")
},
raceOff: {
border: buildColor("grey", "800"),
background: buildColor("white", "100"),
textColor: buildColor("grey", "900"),
iconColor: buildColor("grey", "800"),
dotColor: buildColor("grey", "800"),
trackingColor: buildColor("grey", "300")
},
unknown: {
border: buildColor("grey", "800"),
background: buildColor("white", "100"),
textColor: buildColor("grey", "900"),
iconColor: buildColor("grey", "800"),
dotColor: buildColor("grey", "800"),
trackingColor: buildColor("grey", "300")
// TODO: future unknown status
// border: buildColor("orange", "600"),
// background: buildColor("orange", "200"),
// textColor: buildColor("grey", "800"),
// iconColor: buildColor("orange", "600"),
// trackingColor: buildColor("orange", "300"),
// icon: exclamationMark
},
win: {
border: buildColor("green", "700"),
background: buildColor("green", "100"),
textColor: buildColor("green", "700"),
iconColor: buildColor("green", "700"),
trackingColor: buildColor("green", "300"),
icon: successRound
},
lost: {
border: buildColor("red", "700"),
background: buildColor("red", "100"),
textColor: buildColor("red", "700"),
iconColor: buildColor("red", "700"),
trackingColor: buildColor("red", "300"),
icon: errorRound
},
pending: {
border: buildColor("orange", "900"),
background: buildColor("orange", "200"),
textColor: buildColor("orange", "600"),
iconColor: buildColor("orange", "600"),
trackingColor: buildColor("orange", "300"),
icon: questionMarkRound
},
attention: {
border: buildColor("grey", "900"),
background: buildColor("orange", "400"),
textColor: buildColor("orange", "700"),
iconColor: buildColor("grey", "900"),
trackingColor: buildColor("orange", "300"),
icon: exclamationMarkRound
}
};
export default iconStyles;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MybetsRunnerNumberGroup/styled-components.ts
import styled, { css, keyframes } from "styled-components";
import { get } from "lodash";
import {
fontMedium,
fontNormal,
fontBold,
fontCondensedNormal,
defaultSize
// @ts-ignore
} from "../../_static/Typography";
// @ts-ignore
import buildColor from "../../_static/ColorPalette";
// @ts-ignore
import Icon from "../../_static/Icons";
// @ts-ignore
import { iconStyles } from "./constant";
const textStyling = css`
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
`;
const fadeIn = keyframes`
0% {
opacity: 0;
}
100% {
opacity: 1;
}
`;
const getIconStyle = (raceStatus: string, element: string) =>
element
? get(iconStyles, `${raceStatus}.${element}`)
: get(iconStyles, `${raceStatus}`);
/* Use z-index on runnerNumber when (ex: winner) to surpass these styles */
const MutedStyles = (color = "white", variation = "80") => css`
position: relative;
&::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: ${buildColor(color, variation)};
z-index: 1;
}
`;
export const RunnerNumberContainer = styled.div`
display: flex;
flex-direction: column;
flex-grow: 1;
width: 100%;
`;
export const RunnerNumberGroupMolecule = styled.ol<{
isBetsDetailedView: boolean;
betStatusName: string;
raceStatus: string;
}>`
list-style-type: none;
display: flex;
width: 100%;
${({ isBetsDetailedView }) =>
isBetsDetailedView
? css`
flex-direction: column;
`
: css`
align-items: center;
flex-wrap: wrap;
`}
/* surpass muted styles in detailed view on these bet status */
${({ isBetsDetailedView, betStatusName, raceStatus }) =>
isBetsDetailedView &&
raceStatus !== "unknown" &&
["winner", "canceled", "loser", "refunded"].includes(betStatusName) &&
css`
z-index: 2;
/* Text color for all bets status but not active */
.runner-name {
color: ${buildColor("grey", "700")};
}
`}
${({ raceStatus }) =>
raceStatus === "unknown" &&
css`
z-index: 2;
`}
`;
export const ListItem = styled.li<{ isBetsDetailedView?: boolean }>`
display: flex;
align-items: center;
&:not(:first-child) {
${({ isBetsDetailedView }) =>
isBetsDetailedView
? css`
margin-top: 2px;
`
: css`
margin-left: 4px;
`}
}
`;
export const RunnerNameContainer = styled.div<{
isWinnerBI?: boolean;
isUnknownWinnerStatus?: boolean;
isActiveMultiRaceLegOver?: boolean;
}>`
display: flex;
flex-direction: row;
margin-left: 8px;
${textStyling}
/* Text styles for winner runners */
${({ isWinnerBI, isUnknownWinnerStatus }) =>
isWinnerBI &&
!isUnknownWinnerStatus &&
css`
& > .runner-name {
font-family: ${fontMedium};
color: ${buildColor("grey", "900")};
}
`}
${({ isWinnerBI, isUnknownWinnerStatus, isActiveMultiRaceLegOver }) =>
!isWinnerBI &&
!isUnknownWinnerStatus &&
isActiveMultiRaceLegOver &&
css`
& > .runner-name {
color: ${buildColor("grey", "700")};
}
`}
`;
export const RunnerName = styled.span<{ isScratched?: boolean }>`
font-family: ${fontNormal};
font-size: 14px;
line-height: 18px;
${textStyling};
color: ${({ isScratched }) =>
buildColor("grey", isScratched ? "700" : "900")};
${({ isScratched }) =>
isScratched &&
css`
text-decoration: line-through;
`}
`;
export const DetailedViewInfoContainer = styled.div`
display: flex;
flex-direction: row;
margin-left: auto;
align-items: center;
flex: 1;
justify-content: flex-end;
`;
export const Tag = styled.span`
display: flex;
margin-left: 6px;
`;
export const RaceOdds = styled.span<{
isBetsDetailedView?: boolean;
showReplacement?: boolean;
}>`
font-family: ${fontBold};
font-size: 14px;
line-height: 18px;
`;
export const WillPaysInfoContainer = styled.div<{ isDesktop: boolean }>`
display: flex;
width: 100%;
margin-top: 2px;
margin-bottom: 8px;
${({ isDesktop }) =>
isDesktop &&
css`
margin-left: 2px;
margin-top: 4px;
`}
`;
export const WillPaysInfoDesktopText = styled.span`
font-family: ${fontNormal};
font-size: 12px;
color: ${buildColor("blue_accent", "700")};
`;
export const WillPays = styled.span<{ hasMargin?: boolean }>`
font-family: ${fontMedium};
font-size: ${defaultSize};
line-height: 18px;
text-align: right;
font-weight: 500;
color: ${buildColor("grey", "900")};
flex: 1;
display: flex;
align-self: center;
justify-content: flex-end;
${({ hasMargin }) =>
hasMargin &&
`
&:not(:last-child) {
flex-grow: 2;
}
`}
`;
export const WillPaysLabel = styled.span`
position: absolute;
top: 6px;
right: 26px;
font-family: ${fontCondensedNormal};
font-size: 12px;
color: ${buildColor("grey", "800")};
`;
export const PickBetContainer = styled.div<{
showUpperHorizontalRule: boolean;
isBetsDetailedView: boolean;
isDesktop: boolean;
showHorizontalRule: boolean;
isCanceled: boolean;
raceStatus: string;
}>`
position: relative;
&:not(:first-child) {
margin-top: 2px;
${({ showUpperHorizontalRule }) =>
showUpperHorizontalRule &&
css`
margin-top: 15px;
`};
}
&:not(:last-child) {
${({ isBetsDetailedView, isDesktop, showHorizontalRule }) => {
if (isBetsDetailedView) {
if (isDesktop) {
if (!showHorizontalRule) {
return "";
}
return css`
padding-bottom: 13px;
`;
}
return css`
padding-bottom: 6px;
`;
}
if (!isDesktop) {
return css`
padding-bottom: 8px;
`;
}
return css``;
}};
${({ isCanceled, isDesktop, raceStatus }) =>
!isCanceled && !isDesktop
? css`
&::after {
content: "";
width: 2px;
height: calc(100% - 18px);
background: ${getIconStyle(raceStatus, "trackingColor")};
border-radius: 1px;
position: absolute;
top: 20px;
left: 9px;
z-index: 2;
}
`
: ""}
}
`;
export const PickBetsWrapper = styled.div`
display: flex;
position: relative;
`;
export const PickBetLabelIconContainer = styled.div<{
isDesktop: boolean;
raceStatus: string;
}>`
display: flex;
align-items: center;
justify-content: ${({ isDesktop, raceStatus }) =>
isDesktop && (raceStatus === "open" || raceStatus === "raceOff")
? "right"
: "center"};
flex-shrink: 0;
height: 20px;
width: 20px;
margin-right: ${({ isDesktop }) => (isDesktop ? "6px" : "8px")};
position: relative;
z-index: 2;
`;
export const PickBetLabelRunnersWrapper = styled.div<{
detailExpanded: boolean;
}>`
display: flex;
flex-grow: 1;
${({ detailExpanded }) =>
detailExpanded &&
css`
flex-direction: column;
align-items: flex-start;
`}
`;
export const PickBetHrContainer = styled.div<{
isDesktop?: boolean;
isTopHr?: boolean;
}>`
position: absolute;
left: 0;
right: 0;
padding: ${({ isDesktop }) => (isDesktop ? "0 2px 0 26px" : "0 2px 0 28px")};
z-index: 3;
${({ isTopHr, isDesktop }) => {
if (isTopHr) {
if (isDesktop) {
return css`
top: -9px;
`;
}
return css`
top: -6px;
`;
}
if (isDesktop) {
return css`
bottom: 6px;
`;
}
return css`
bottom: 3px;
`;
}}
`;
export const ExoticBetContainer = styled.div<{ isDesktop: boolean }>`
display: flex;
&:not(:last-child) {
margin-bottom: ${({ isDesktop }) => (isDesktop ? "2px" : "10px")};
}
`;
export const LabelItem = styled.div<{
isDesktop?: boolean;
pickBetsDetailExpanded?: boolean;
isPickBets?: boolean;
pickBetsLabelLength?: number;
}>`
height: 20px;
margin-left: ${({ isDesktop }) => (isDesktop ? "0" : "2px")};
display: inline-flex;
align-items: center;
flex-shrink: 0;
position: relative;
z-index: 2;
${({ pickBetsDetailExpanded }) =>
pickBetsDetailExpanded &&
css`
margin-bottom: 6px;
`}
${({ isPickBets, pickBetsLabelLength, isDesktop }) =>
isPickBets
? css`
margin-right: 8px;
justify-content: flex-start;
${pickBetsLabelLength === 11 &&
css`
min-width: 64px;
`}
${pickBetsLabelLength === 12 &&
css`
min-width: 71px;
`}
`
: css`
margin-right: ${isDesktop ? "6px" : "14px"};
justify-content: ${isDesktop ? "flex-start" : "flex-end"};
min-width: ${isDesktop ? "20px" : "24px"};
`}
`;
export const TextLabel = styled.div<{
isPickBets?: boolean;
isDesktop?: boolean;
raceStatus?: string;
}>`
font-family: ${({ isPickBets }) =>
isPickBets ? fontCondensedNormal : fontNormal};
font-size: ${({ isDesktop }) => (isDesktop ? "12px" : "14px")};
line-height: 18px;
color: ${({ raceStatus }) =>
raceStatus
? getIconStyle(raceStatus, "textColor")
: buildColor("grey", "800")};
`;
export const HorizontalRule = styled.hr.attrs({
"data-qa-label": "myBets-horizontalRule"
})<{
isPickBets?: boolean;
isDesktop?: boolean;
}>`
height: 1px;
background-color: ${buildColor("blue", "100")};
width: calc(100% - 4px);
border: none;
position: relative;
left: 2px;
z-index: 2;
margin: ${({ isPickBets, isDesktop }) => {
if (isPickBets) {
return "0";
}
if (isDesktop) {
return "6px 0 6px";
}
return "10px 0 0";
}};
animation: ${fadeIn} 0.2s cubic-bezier(0.39, 0.575, 0.565, 1) both;
`;
export const LabelIconWrapper = styled.div<{
raceStatus: string;
isDesktop: boolean;
}>`
position: relative;
width: 16px;
height: 16px;
${({ raceStatus, isDesktop }) => {
if (
(["open", "raceOff"].includes(raceStatus) && !isDesktop) ||
(["unknown"].includes(raceStatus) && isDesktop)
) {
return css`
border: 2px solid ${getIconStyle(raceStatus, "border")};
background: ${getIconStyle(raceStatus, "background")};
border-radius: 50%;
`;
}
return "";
}}
`;
export const LabelDot = styled.div<{ raceStatus: string }>`
position: absolute;
content: "";
width: 4px;
height: 4px;
top: calc(50% - 2px);
left: calc(50% - 2px);
background: ${({ raceStatus }) => getIconStyle(raceStatus, "dotColor")};
border-radius: 50%;
`;
export const LabelIcon = styled(Icon)`
${({ raceStatus }) =>
["open", "raceOff"].includes(raceStatus) &&
css`
position: absolute;
top: calc(50% - 5px);
left: calc(50% - 5px);
border-radius: 50%;
`}
`;
export const LabelText = styled.span<{ boldText: boolean }>`
font-family: ${({ boldText }) => (boldText ? fontBold : fontNormal)};
font-size: 12px;
align-self: flex-end;
color: ${({ boldText }) =>
boldText ? buildColor("grey", "900") : buildColor("grey", "800")};
`;
export const FavArrowIcon = styled(Icon)`
margin: 0 4px;
z-index: 4;
`;
export const PickBetsExpandButton = styled.button`
display: flex;
align-items: center;
justify-content: center;
height: 20px;
width: 24px;
outline: none;
background-color: transparent;
border-radius: 50%;
position: relative;
z-index: 4;
left: 2px;
&::before {
content: "";
position: absolute;
top: -4px;
left: -4px;
height: 32px;
width: 32px;
background-color: transparent;
border-radius: 50%;
z-index: -1;
}
&:active {
&::before {
background-color: ${buildColor("grey", "200")};
}
svg {
stroke: ${buildColor("grey", "900")};
}
}
`;
export const LegScratchNotificationContainer = styled.div<{
isDesktop: boolean;
}>`
display: flex;
flex-direction: column;
align-items: flex-start;
margin-top: ${({ isDesktop }) => (isDesktop ? "2px" : "-6px")};
margin-bottom: ${({ isDesktop }) => (isDesktop ? "0" : "8px")};
${({ isDesktop }) =>
isDesktop &&
css`
margin-left: 2px;
`}
`;
export const LegScratchNotification = styled.span`
font-family: ${fontMedium};
font-size: 12px;
line-height: 17px;
color: ${buildColor("orange", "700")};
`;
export const RunnerInfoContainer = styled.span<{
isBetsDetailedView?: boolean;
cols: number;
isDesktop?: boolean;
betStatusName: string;
}>`
display: flex;
align-items: center;
${({ isBetsDetailedView, cols }) =>
isBetsDetailedView &&
cols &&
css`
width: ${cols > 2 ? "105px" : "210px"};
`}
${({ isBetsDetailedView, cols, isDesktop }) =>
isBetsDetailedView &&
cols &&
isDesktop &&
css`
width: 105px;
`}
${({ isBetsDetailedView, betStatusName, isDesktop }) =>
!isBetsDetailedView &&
isDesktop &&
["winner", "canceled", "loser", "refunded"].includes(betStatusName) &&
MutedStyles()}
`;
export const PayoutHeader = styled.div<{ cols: number; isDesktop: boolean }>`
display: flex;
flex: 1;
justify-content: flex-end;
::before {
content: "";
${({ cols }) =>
cols &&
css`
width: ${cols > 2 ? "105px" : "193px"};
`};
${({ isDesktop }) =>
isDesktop &&
css`
width: 105px;
`};
}
`;
export const PayoutHeaderItem = styled.span<{ hasTwoColumns: boolean }>`
text-align: right;
text-transform: uppercase;
font-family: ${fontCondensedNormal};
font-size: 12px;
font-weight: 400;
color: ${buildColor("grey", "900")};
flex: 1;
${({ hasTwoColumns }) =>
hasTwoColumns &&
css`
&:not(:last-child) {
flex-grow: 2;
}
`}
`;
export const PayoutSeparator = styled.hr`
width: calc(100% + 20px);
margin-left: -10px;
border: 0;
border-bottom: 1px solid ${buildColor("blue", "100")};
`;
export const ListItemWrapper = styled.ul<{ isBetsDetailedView?: boolean }>`
display: flex;
flex-direction: ${({ isBetsDetailedView }) =>
isBetsDetailedView ? "column" : "row"};
flex: 1;
`;
export const SelectionList = styled.div<{
isBetsDetailedView?: boolean;
isDesktop?: boolean;
}>`
display: flex;
margin: 0 2px 2px;
${({ isBetsDetailedView, isDesktop }) =>
isBetsDetailedView &&
css`
&:not(:only-child, :last-child) {
margin-bottom: ${isDesktop ? "4px" : "12px"};
}
`}
`;
export const DetailAction = styled.div`
position: absolute;
width: 100%;
height: 20px;
z-index: 3;
`;
export const AlternateSeparatorContainer = styled.div`
display: inline-flex;
align-items: center;
height: 20px;
padding: 0 3px;
margin-bottom: 2px;
`;
export const AlternateSeparator = styled.div`
height: 12px;
width: 1px;
background-color: #6a6f73;
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MybetsRunnerNumberGroup/components/AlternateRunners.tsx
import React from "react";
import { BetRunnerDetails } from "@tvg/ts-types/Bet";
// @ts-ignore
import RunnerNumber from "../../../_atom/RunnerNumber";
import {
AlternateSeparator,
AlternateSeparatorContainer,
ListItem,
ListItemWrapper,
RunnerInfoContainer,
RunnerName,
RunnerNameContainer,
SelectionList
} from "../styled-components";
interface AlternateRunnersProps {
alternateRunners: BetRunnerDetails[];
isBetsDetailedView: boolean;
isDesktop: boolean;
titles: string[];
betStatusName: string;
raceTypeCode: string;
isActiveMultiRaceLegOver: boolean;
isRaceOver: boolean;
isUnknownWinnerStatus: boolean;
}
const AlternateRunners = ({
alternateRunners,
isBetsDetailedView,
isDesktop,
titles,
betStatusName,
raceTypeCode,
isActiveMultiRaceLegOver,
isRaceOver,
isUnknownWinnerStatus
}: AlternateRunnersProps) => (
<>
{!isBetsDetailedView && (
<AlternateSeparatorContainer>
<AlternateSeparator />
</AlternateSeparatorContainer>
)}
{alternateRunners?.map((runner: BetRunnerDetails, index: number) => (
<SelectionList
key={`selection-list--${index.toString()}`}
isBetsDetailedView={isBetsDetailedView}
isDesktop={isDesktop}
>
<ListItemWrapper isBetsDetailedView={isBetsDetailedView}>
<ListItem
data-qa-label="alternate-runnerNumber-ListItem"
isBetsDetailedView={isBetsDetailedView}
>
<RunnerInfoContainer
data-qa-label="alternate-saddle-row"
isBetsDetailedView={isBetsDetailedView}
cols={titles.length}
betStatusName={betStatusName}
isDesktop={isDesktop}
>
<RunnerNumber
qaLabel={`saddle-container-${runner.runnerId}`}
runnerId={runner.runnerId}
saddleColor={runner.saddleColor}
numberColor={runner.numberColor}
raceTypeCode={raceTypeCode}
isBetsStandalone
isScratched={runner.isScratched}
isActiveMultiRaceLegOver={
isActiveMultiRaceLegOver && !isBetsDetailedView
}
isRaceOver={isRaceOver}
isBetsDetailedView={isBetsDetailedView}
isUnknownWinnerStatus={isUnknownWinnerStatus}
isAlternate
/>
{isBetsDetailedView && (
<RunnerNameContainer
data-qa-label="runnerName"
isUnknownWinnerStatus={isUnknownWinnerStatus}
isActiveMultiRaceLegOver={
isActiveMultiRaceLegOver && isBetsDetailedView
}
>
<RunnerName
className="runner-name"
isScratched={runner?.isScratched ?? false}
>
{runner?.runnerName ?? ""}
</RunnerName>
</RunnerNameContainer>
)}
</RunnerInfoContainer>
</ListItem>
</ListItemWrapper>
</SelectionList>
))}
</>
);
export default AlternateRunners;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MybetsRunnerNumberGroup/components/PayoutsHeader.tsx
import React from "react";
import {
PayoutHeader,
PayoutHeaderItem,
PayoutSeparator
} from "../styled-components";
export interface PayoutsHeaderProps {
titles: string[];
isCanceled: boolean;
isDesktop: boolean;
}
const PayoutsHeaderComp = ({
titles,
isCanceled,
isDesktop
}: PayoutsHeaderProps) => {
if (titles.length > 1 && !isCanceled) {
return (
<>
<PayoutHeader cols={titles.length} isDesktop={isDesktop}>
{titles.map((title, index) => (
<PayoutHeaderItem
key={index.toString()}
hasTwoColumns={titles.length === 2}
>
{title}
</PayoutHeaderItem>
))}
</PayoutHeader>
<PayoutSeparator />
</>
);
}
return null;
};
export default PayoutsHeaderComp;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/IconDescription/styled-components.js
import styled from "styled-components";
import colorBuilder from "../../_static/ColorPalette";
import { fontNormal, defaultSize } from "../../_static/Typography";
export const IconContainer = styled.div`
display: inline-grid;
grid-template-columns: 1fr auto;
grid-column-gap: ${(props) => props.iconMargin};
color: ${colorBuilder("grey", "800")};
font-size: ${(props) =>
props.fontSize ? `${props.fontSize}px` : defaultSize};
font-weight: normal;
font-family: ${fontNormal};
letter-spacing: 0;
`;
export const DescriptionText = styled.span`
color: ${(props) => props.color};
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/IconDescription/index.jsx
import React from "react";
import Icon from "../../_static/Icons";
import buildColor from "../../_static/ColorPalette";
import * as allIcons from "../../_static/Icons/icons";
import * as duotoneIcons from "../../_static/Icons/iconsDuotone";
import { IconContainer, DescriptionText } from "./styled-components";
const IconDescription = ({
icon,
description,
size,
color,
stroke,
variation,
strokeVariation,
isDuotone,
viewBoxSize,
textColor,
textColorVariation,
iconMargin,
id,
fontSize
}) => (
<IconContainer iconMargin={`${iconMargin || "10"}px`} fontSize={fontSize}>
<Icon
qaLabel={`icon_${id}`}
icon={isDuotone ? duotoneIcons[icon] : allIcons[icon]}
color={buildColor(color || "grey", variation || "800")}
stroke={
stroke && strokeVariation ? buildColor(stroke, strokeVariation) : null
}
size={size}
viewBoxSize={viewBoxSize}
/>
<DescriptionText
color={buildColor(textColor || "grey", textColorVariation || "800")}
data-qa-label={`description_${id}`}
>
{description}
</DescriptionText>
</IconContainer>
);
IconDescription.defaultProps = {
icon: "lock",
description: "",
size: 16,
color: "grey",
stroke: "grey",
variation: "800",
strokeVariation: "800",
isDuotone: false,
textColor: "grey",
textColorVariation: "800",
iconMargin: 10,
viewBoxSize: 1024,
fontSize: 14
};
export default IconDescription;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MybetsRunnerNumberGroup/components/LabelIcon.tsx
import React from "react";
import { get } from "lodash";
import { iconStyles } from "../constant";
import { LabelIcon, LabelText, LabelDot } from "../styled-components";
export interface LabelIconProps {
raceStatus: string;
label: string;
qaLabel?: string;
isDesktop: boolean;
}
const LabelIconComp = ({
raceStatus,
label,
qaLabel = "myBets-label-icon",
isDesktop
}: LabelIconProps) => {
const iconProps = {
icon: get(iconStyles, `${raceStatus}.icon`),
viewBoxSize: 16,
size: 16,
color: get(iconStyles, `${raceStatus}.background`),
stroke: get(iconStyles, `${raceStatus}.iconColor`)
};
if (isDesktop && (raceStatus === "open" || raceStatus === "raceOff")) {
return <LabelText boldText={raceStatus === "raceOff"}>{label}</LabelText>;
}
return iconProps.icon ? (
<LabelIcon {...iconProps} data-qa-label={qaLabel} />
) : (
<LabelDot raceStatus={raceStatus} data-qa-label={qaLabel} />
);
};
export default LabelIconComp;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MybetsRunnerNumberGroup/components/ScratchNotifications.tsx
import React from "react";
import {
isMultiRaceBet,
isPickBetSub
} from "@tvg/sh-lib-my-bets/utils/raceDetails";
import { WagerTypeCodesEnum } from "@tvg/ts-types/Wager";
import {
LegScratchNotificationContainer,
LegScratchNotification
} from "../styled-components";
export interface ScratchNotificationsProps {
wagerTypeCode: WagerTypeCodesEnum;
isDesktop: boolean;
hasAlternateReplacement: boolean;
}
const ScratchNotifications = ({
wagerTypeCode,
isDesktop,
hasAlternateReplacement
}: ScratchNotificationsProps) => {
const showFavoriteMsg = wagerTypeCode && isPickBetSub(wagerTypeCode);
const showScratchMsgDetails = wagerTypeCode && isMultiRaceBet(wagerTypeCode);
if (!showScratchMsgDetails) {
return null;
}
return (
<LegScratchNotificationContainer isDesktop={isDesktop}>
{hasAlternateReplacement && (
<LegScratchNotification data-qa-label="LegScratchNotification">
Scratch will be replaced with the alternate selection.
</LegScratchNotification>
)}
{showFavoriteMsg && !hasAlternateReplacement && (
<LegScratchNotification data-qa-label="LegScratchNotification">
Scratch will be replaced with the FAV.
</LegScratchNotification>
)}
<LegScratchNotification data-qa-label="LegScratchNotification">
Awaiting official result to confirm the bet status.
</LegScratchNotification>
</LegScratchNotificationContainer>
);
};
export default ScratchNotifications;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MybetsRunnerNumberGroup/components/PickBetLayout.tsx
import React from "react";
import { BetSelection } from "@tvg/ts-types/Bet";
import { WagerTypeCodesEnum } from "@tvg/ts-types/Wager";
import {
DetailAction,
HorizontalRule,
LabelIconWrapper,
LabelItem,
PickBetContainer,
PickBetHrContainer,
PickBetLabelIconContainer,
PickBetLabelRunnersWrapper,
PickBetsExpandButton,
PickBetsWrapper,
RunnerNumberContainer,
TextLabel,
WillPaysInfoContainer,
WillPaysInfoDesktopText,
WillPaysLabel
} from "../styled-components";
// @ts-ignore
import IconDescription from "../../IconDescription";
// @ts-ignore
import Icon from "../../../_static/Icons";
// @ts-ignore
import { chevronDown, chevronUp } from "../../../_static/Icons/iconsDuotone";
// @ts-ignore
import buildColor from "../../../_static/ColorPalette";
import LabelIcon from "./LabelIcon";
import ScratchNotifications from "./ScratchNotifications";
export interface PickBetLayoutProps {
raceStatus: string;
isDesktop: boolean;
isBetsDetailedView: boolean;
showUpperHorizontalRule: boolean;
isCanceled: boolean;
showHorizontalRule: boolean;
isFirstRowOfRunners: boolean;
runners: BetSelection[];
hasDetails: boolean;
onDetailedView?: () => void;
label: string;
pickBetsLabelLength: number;
isLastRowOfRunners: boolean;
runnersHaveWillPayAmount: boolean;
isPickBet: boolean;
wagerTypeCode: WagerTypeCodesEnum;
isRaceOver: boolean;
hasAlternates: boolean;
hasAlternateReplacement: boolean;
runnerNumberGroup: React.ReactNode;
}
const PickBetLayout = ({
raceStatus,
isBetsDetailedView,
showHorizontalRule,
isCanceled,
isDesktop,
showUpperHorizontalRule,
isFirstRowOfRunners,
runners,
onDetailedView,
hasDetails,
label,
pickBetsLabelLength,
isLastRowOfRunners,
runnersHaveWillPayAmount,
wagerTypeCode,
isPickBet,
isRaceOver,
hasAlternates,
runnerNumberGroup,
hasAlternateReplacement
}: PickBetLayoutProps) => (
<PickBetContainer
data-qa-label="myBets-pickBets-container"
raceStatus={raceStatus}
isCanceled={isCanceled}
isBetsDetailedView={isBetsDetailedView}
isDesktop={isDesktop}
showHorizontalRule={showHorizontalRule}
showUpperHorizontalRule={isDesktop && showUpperHorizontalRule}
>
{!isCanceled &&
!isFirstRowOfRunners &&
isBetsDetailedView &&
(runners.length > 1 || hasAlternates) && (
<PickBetHrContainer
data-qa-label="myBets-hr-container"
isTopHr
isDesktop={isDesktop}
>
<HorizontalRule data-qa-label="myBets-horizontal-line" isPickBets />
</PickBetHrContainer>
)}
<PickBetsWrapper data-qa-label="myBets-pickBets-wrapper">
{hasDetails && <DetailAction onClick={onDetailedView} />}
{!isCanceled && (
<PickBetLabelIconContainer
isDesktop={isDesktop}
raceStatus={raceStatus}
>
<LabelIconWrapper
isDesktop={isDesktop}
raceStatus={raceStatus}
data-qa-label="myBets-icon-wrapper"
>
<LabelIcon
raceStatus={raceStatus}
label={label}
isDesktop={isDesktop}
/>
</LabelIconWrapper>
</PickBetLabelIconContainer>
)}
<PickBetLabelRunnersWrapper
data-qa-label="myBets-label-runners-wrapper"
detailExpanded={isBetsDetailedView}
>
{!isDesktop && (
<LabelItem
isPickBets
pickBetsLabelLength={pickBetsLabelLength}
pickBetsDetailExpanded={isBetsDetailedView}
data-qa-label="myBets-label-wrapper"
>
<TextLabel
data-qa-label="myBets-pickBets-label"
raceStatus={raceStatus}
isPickBets
>
{label}
</TextLabel>
</LabelItem>
)}
{isBetsDetailedView &&
isLastRowOfRunners &&
runnersHaveWillPayAmount && (
<WillPaysInfoContainer isDesktop={isDesktop}>
{isDesktop ? (
<WillPaysInfoDesktopText>
Will Pays subject to change due to scratches
</WillPaysInfoDesktopText>
) : (
<IconDescription
id="willpays-info"
icon="info"
isDuotone
size={16}
viewBoxSize={16}
color="blue_accent"
variation="200"
stroke="blue_accent"
strokeVariation="700"
textColor="blue_accent"
textColorVariation="700"
iconMargin={12}
description="Will Pays subject to change due to scratches"
fontSize={12}
/>
)}
</WillPaysInfoContainer>
)}
{isBetsDetailedView &&
isPickBet &&
wagerTypeCode &&
raceStatus === "attention" &&
!isRaceOver &&
!runnersHaveWillPayAmount &&
!isDesktop && (
<ScratchNotifications
wagerTypeCode={wagerTypeCode}
isDesktop={isDesktop}
hasAlternateReplacement={hasAlternateReplacement}
/>
)}
<RunnerNumberContainer data-qa-label="myBets-runner-number-container">
{runnerNumberGroup}
</RunnerNumberContainer>
{isBetsDetailedView &&
isPickBet &&
wagerTypeCode &&
raceStatus === "attention" &&
!isRaceOver &&
!runnersHaveWillPayAmount &&
isDesktop && (
<ScratchNotifications
wagerTypeCode={wagerTypeCode}
isDesktop={isDesktop}
hasAlternateReplacement={hasAlternateReplacement}
/>
)}
</PickBetLabelRunnersWrapper>
{hasDetails &&
isBetsDetailedView &&
isLastRowOfRunners &&
runnersHaveWillPayAmount &&
!isDesktop && <WillPaysLabel>WILL PAYS</WillPaysLabel>}
{hasDetails && !isDesktop && (
<PickBetsExpandButton onClick={onDetailedView}>
<Icon
icon={isBetsDetailedView ? chevronUp : chevronDown}
viewBoxSize={16}
size={16}
color="transparent"
stroke={buildColor("grey", "800")}
/>
</PickBetsExpandButton>
)}
</PickBetsWrapper>
{showHorizontalRule &&
isBetsDetailedView &&
(runners.length > 1 || hasAlternates) &&
!isCanceled && (
<PickBetHrContainer
data-qa-label="myBets-hr-container"
isDesktop={isDesktop}
>
<HorizontalRule data-qa-label="myBets-horizontal-line" isPickBets />
</PickBetHrContainer>
)}
</PickBetContainer>
);
export default PickBetLayout;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MybetsRunnerNumberGroup/components/ExoticBetsLayout.tsx
import React from "react";
// @ts-ignore
import Icon from "../../../_static/Icons";
// @ts-ignore
import { key } from "../../../_static/Icons/iconsDuotone";
// @ts-ignore
import buildColor from "../../../_static/ColorPalette";
import {
ExoticBetContainer,
HorizontalRule,
LabelItem,
RunnerNumberContainer,
TextLabel
} from "../styled-components";
export interface ExoticBetsLayoutProps {
isBetsDetailedView: boolean;
isDesktop: boolean;
label: string;
isKey: boolean;
showHorizontalRule: boolean;
runnerNumberGroup: React.ReactNode;
}
const ExoticBetsLayout = ({
isDesktop,
isKey,
label,
runnerNumberGroup,
isBetsDetailedView,
showHorizontalRule
}: ExoticBetsLayoutProps) => (
<ExoticBetContainer
data-qa-label="myBets-exoticBet-container"
isDesktop={isDesktop}
>
{(isKey || label) && (
<LabelItem isDesktop={isDesktop}>
{!isKey ? (
<TextLabel
data-qa-label="myBets-exoticBet-label"
isDesktop={isDesktop}
>
{label}
</TextLabel>
) : (
<Icon
qaLabel="myBets-exoticBet-icon"
icon={key}
viewBoxSize={16}
size={16}
color={buildColor("white", "10")}
stroke={buildColor("grey", "800")}
/>
)}
</LabelItem>
)}
<RunnerNumberContainer>
{runnerNumberGroup}
{showHorizontalRule && isBetsDetailedView && (
<HorizontalRule isDesktop={isDesktop} />
)}
</RunnerNumberContainer>
</ExoticBetContainer>
);
export default ExoticBetsLayout;
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/components/SimpleInlineInfo/styled-components.ts
import styled, { css } from "styled-components";
import { tvgColorPalette as colors } from "@tvg/design-system/src/theming/themes/common/tvgColorPalette";
import { fonts } from "@tvg/design-system/src/theming/themes/common/fonts";
export const InfoContainer = styled.div`
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
`;
export const Description = styled.span`
text-transform: capitalize;
display: block;
font-weight: bold;
text-align: left;
padding-bottom: 2px;
font-size: 12px;
${({ theme }) => `color: ${theme.colorTokens.content.default}`};
`;
export const OptionItem = styled.span`
position: relative;
font-size: 12px;
color: ${({ theme }) => theme.colorTokens.content.subtle};
&:not(:last-child) {
margin-right: 4px;
padding-right: 5px;
}
`;
export const InfoItems = styled.ul`
white-space: normal;
font-size: 12px;
line-height: 18px;
font-family: ${fonts.regular};
color: ${({ theme }) => theme.colorTokens.content.subtle};
`;
export const InfoItem = styled.li<{
isHighlighted: boolean;
hasChanges: boolean;
}>`
display: inline;
${({ isHighlighted }) =>
isHighlighted &&
css`
font-family: ${fonts.medium};
font-weight: 500;
`};
${({ hasChanges }) =>
hasChanges &&
css`
color: ${colors.orange[700]};
`};
`;
export const Separator = styled.span`
font-weight: normal;
line-height: 17px;
vertical-align: initial;
font-size: 12px;
font-family: ${fonts.regular};
${({ theme }) => `color: ${theme.colorTokens.background.neutral}`};
`;
export const FavoriteTag = styled.span`
margin-left: 2px;
padding: 1px 6px;
border-radius: 12px;
font-style: normal;
line-height: 14px;
text-align: center;
vertical-align: text-top;
font-family: ${fonts.condensedRegular};
font-weight: 500;
font-size: 12px;
${({ theme }) => `
color: ${theme.colorTokens.content.alert};
background: ${theme.colorTokens.background.alertSubtle};
`}
`;
export const IconContainer = styled.div`
display: inline-flex;
margin-right: 4px;
vertical-align: inherit;
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MybetsRunnerNumberGroup/components/ListItemDetails.tsx
import React from "react";
import { get } from "lodash";
import formatCurrency from "@tvg/formatter/currency";
import { BetSelection } from "@tvg/ts-types/Bet";
import { FavoriteTag as YellowTag } from "@tvg/ipp/src/components/SimpleInlineInfo/styled-components";
import {
DetailedViewInfoContainer,
RaceOdds,
Tag,
WillPays
} from "../styled-components";
export interface ListItemDetailsProps {
showDetails: boolean;
isWinnerBI: boolean;
isUnknownWinnerStatus: boolean;
runner: BetSelection;
isCanceled: boolean;
isBetRefund: boolean;
isLastRowOfRunners: boolean;
showTag: boolean;
isRaceOver: boolean;
}
const ListItemDetails = ({
showDetails,
isWinnerBI,
isUnknownWinnerStatus,
runner,
isBetRefund,
isCanceled,
isLastRowOfRunners,
showTag,
isRaceOver
}: ListItemDetailsProps) => (
<DetailedViewInfoContainer>
{showDetails && (
<>
{isWinnerBI && (
<RaceOdds>
{runner.alternate?.currentOdds ? (
// Show alternate odds if alternate is winner and has odds
<>
{get(runner.alternate, "currentOdds.numerator")}
{get(runner.alternate, "currentOdds.denominator")
? `/${get(runner.alternate, "currentOdds.denominator")}`
: ""}
</>
) : (
// Show runner odds if runner is winner and has odds
get(runner, "currentOdds") && (
<>
{get(runner, "currentOdds.numerator")}
{get(runner, "currentOdds.denominator")
? `/${get(runner, "currentOdds.denominator")}`
: ""}
</>
)
)}
</RaceOdds>
)}
{get(runner, "isFavorite", false) && isRaceOver && (
<Tag>
<YellowTag as="span">FAV</YellowTag>
</Tag>
)}
{!isCanceled &&
!isBetRefund &&
!isUnknownWinnerStatus &&
get(runner, "willPayAmount", 0) > 0 &&
isLastRowOfRunners && (
<WillPays>
{formatCurrency(get(runner, "willPayAmount", 0), "USD")}
</WillPays>
)}
</>
)}
{showTag && (
<Tag>
<YellowTag as="span">REFUND</YellowTag>
</Tag>
)}
</DetailedViewInfoContainer>
);
export default ListItemDetails;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MybetsRunnerNumberGroup/components/WillPaysDetails.tsx
import React from "react";
import { get } from "lodash";
import formatCurrency from "@tvg/formatter/currency";
import { BetSelection } from "@tvg/ts-types/Bet";
import { getWillPaysSimpleRace } from "@tvg/sh-lib-my-bets/utils/runnerNumberGroupUtils";
import { WillPays } from "../styled-components";
export interface WillPaysDetailsProps {
runner: BetSelection;
payoutsTitles?: string[];
runnerNumber: string;
payoutsTitlesLength: number;
}
const WillPaysDetails = ({
payoutsTitles,
runner,
runnerNumber,
payoutsTitlesLength
}: WillPaysDetailsProps) => (
<>
{getWillPaysSimpleRace(runner, payoutsTitles).map((amount) => (
<WillPays
key={`${runnerNumber}-${get(runner, "willPayAmount", "")}-willPays`}
hasMargin={payoutsTitlesLength < 3}
>
{typeof amount === "number" &&
amount > 0 &&
formatCurrency(amount, "USD")}
</WillPays>
))}
</>
);
export default WillPaysDetails;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MybetsRunnerNumberGroup/index.tsx
import React from "react";
import { includes, get, isEmpty } from "lodash";
import { isPickBetSub } from "@tvg/sh-lib-my-bets/utils/raceDetails";
import {
checkFavoriteSequence,
getPayoutsHeaderTitle
} from "@tvg/sh-lib-my-bets/utils/runnerNumberGroupUtils";
import { BetSelection } from "@tvg/ts-types/Bet";
// @ts-ignore
import RunnerNumber from "../../_atom/RunnerNumber";
import {
arrowForward
// @ts-ignore
} from "../../_static/Icons/iconsDuotone";
// @ts-ignore
import buildColor from "../../_static/ColorPalette";
// @ts-ignore
import Icon from "../../_static/Icons";
import {
RunnerNumberGroupMolecule,
ListItem,
RunnerNameContainer,
RunnerName,
FavArrowIcon,
RunnerInfoContainer,
ListItemWrapper,
SelectionList
} from "./styled-components";
import AlternateRunners from "./components/AlternateRunners";
import PayoutsHeader from "./components/PayoutsHeader";
import PickBetLayout from "./components/PickBetLayout";
import ExoticBetsLayout from "./components/ExoticBetsLayout";
import ListItemDetails from "./components/ListItemDetails";
import {
ListItemProps,
MyBetsRunnerNumberGroupProps,
ShortedSelectionsListProps
} from "./types";
import WillPaysDetails from "./components/WillPaysDetails";
const doubleEntryRegex = /^[0-9]+[a-zA-Z]+$/; // Double Entry validation regex
const getListItem = ({
idx,
runner,
isMultiRace = false,
isCanceled = false,
isFavorite = false,
isArrow = false,
raceTypeCode,
isUnknownWinnerStatus = false,
betStatusName = "",
isBetsDetailedView = false,
allRunnersSelected = false,
isLastRowOfRunners = false,
isWinnerBI = false,
wagerTypeCode,
isRaceOver = false,
isActiveMultiRaceLegOver = false,
payoutsTitles = [],
favoriteRunner,
isCurrentRaceDate = false,
isBetRefund = false,
isDesktop
}: ListItemProps) => {
const allowsPickBetSub = wagerTypeCode && isPickBetSub(wagerTypeCode);
const runners = get(runner, "runners", []) || [];
const showReplacement = runners.every(
(currentRunner) => currentRunner.isScratched
);
const payoutsTitlesLength = payoutsTitles.length;
const allRunnerIsScratched = get(runner, "runners", []).every(
(currRunner) => currRunner.isScratched
);
const showTag =
isBetRefund && allRunnerIsScratched && (isRaceOver || !isWinnerBI);
const showDetails =
isMultiRace &&
!showTag &&
(!allRunnerIsScratched || !runner?.alternate?.runners[0]?.isScratched) &&
!isCanceled;
const showWillPays = isDesktop
? !isCanceled && isBetsDetailedView && !isMultiRace
: isBetsDetailedView && !isMultiRace;
const runnerNumber = get(runner, "runnerNumber", "");
const hasAvailableAlternateRunners = runner?.alternate?.runners.some(
(altRunner) => !altRunner.isScratched
);
if (!isBetsDetailedView && allRunnersSelected) {
return (
<SelectionList
key={`Runner${!isArrow ? runnerNumber : `_arrow_${idx}`}`}
isBetsDetailedView={isBetsDetailedView}
isDesktop={isDesktop}
>
<ListItemWrapper isBetsDetailedView={isBetsDetailedView}>
<ListItem
data-qa-label="runnerNumber-ListItem"
isBetsDetailedView={false}
>
<RunnerInfoContainer
isBetsDetailedView={isBetsDetailedView}
cols={payoutsTitlesLength}
betStatusName={betStatusName}
isDesktop={isDesktop}
>
<RunnerNumber
runnerId="All"
raceTypeCode={raceTypeCode}
isFavorite={false}
isBetsStandalone
isAllRunners
isWinnerBI={runner.isWinner}
isUnknownWinnerStatus={isUnknownWinnerStatus}
isActiveMultiRaceLegOver={
isActiveMultiRaceLegOver && !isBetsDetailedView
}
/>
</RunnerInfoContainer>
</ListItem>
</ListItemWrapper>
</SelectionList>
);
}
// Display alternate runners as replacements if at least one alternate in a coupled entry is not scratched.
// If all alternates are scratched, skip them and proceed with rendering the favorite runner instead, inside the logic below.
if (showReplacement && hasAvailableAlternateRunners && isRaceOver) {
return (
<SelectionList key={`alternate-runner-section-list-${idx.toString()}`}>
<ListItemWrapper isBetsDetailedView={isBetsDetailedView}>
{runner?.alternate?.runners
.sort((a, b) => Number(a.isScratched) - Number(b.isScratched))
.map((altRunner, alternateIndex) => (
<ListItem
key={`alternate-runner-${alternateIndex.toString()}`}
data-qa-label="runnerNumber-ListItem"
isBetsDetailedView={isBetsDetailedView}
>
<RunnerInfoContainer
isBetsDetailedView={isBetsDetailedView}
cols={payoutsTitlesLength}
betStatusName={betStatusName}
isDesktop={isDesktop}
>
{alternateIndex === 0 &&
runners.map((mainScratchedRunner, mainScrIndex) => (
<RunnerNumber
key={`main-scratched-runner-${mainScrIndex.toString()}`}
qaLabel={`saddle-container-${mainScratchedRunner.runnerId}`}
runnerId={mainScratchedRunner.runnerId}
saddleColor={mainScratchedRunner.saddleColor}
numberColor={mainScratchedRunner.numberColor}
raceTypeCode={raceTypeCode}
isFavorite={isFavorite}
isBetsStandalone
isScratched={mainScratchedRunner.isScratched}
isWinnerBI={runner.isWinner && !isCanceled}
isActiveMultiRaceLegOver={
isActiveMultiRaceLegOver && !isBetsDetailedView
}
isRaceOver={isRaceOver}
isBetsDetailedView={isBetsDetailedView}
isUnknownWinnerStatus={isUnknownWinnerStatus}
/>
))}
<>
{alternateIndex === 0 && (
<FavArrowIcon
icon={arrowForward}
viewBoxSize={16}
size={16}
color={buildColor("orange", "600")}
/>
)}
<RunnerNumber
qaLabel={`saddle-container-${altRunner?.runnerId}`}
runnerId={altRunner?.runnerId}
saddleColor={altRunner.saddleColor}
numberColor={altRunner.numberColor}
raceTypeCode={raceTypeCode}
isFavorite={false}
isBetsStandalone
isScratched={altRunner.isScratched}
isWinnerBI={runner?.alternate?.isWinner ?? false}
isActiveMultiRaceLegOver={
isActiveMultiRaceLegOver && !isBetsDetailedView
}
isRaceOver={isRaceOver}
isBetsDetailedView={isBetsDetailedView}
/>
{isBetsDetailedView && (
<RunnerNameContainer
data-qa-label={`runnerName-${altRunner?.runnerId}`}
isWinnerBI={
(runner?.alternate?.isWinner ?? false) && !isCanceled
}
isUnknownWinnerStatus={isUnknownWinnerStatus}
isActiveMultiRaceLegOver={
isActiveMultiRaceLegOver && isBetsDetailedView
}
>
<RunnerName
className="runner-name"
isScratched={altRunner?.isScratched ?? false}
>
{altRunner?.runnerName ?? ""}
</RunnerName>
</RunnerNameContainer>
)}
</>
</RunnerInfoContainer>
</ListItem>
))}
</ListItemWrapper>
{showWillPays && (
<WillPaysDetails
runner={runner}
payoutsTitlesLength={payoutsTitlesLength}
runnerNumber={runnerNumber}
payoutsTitles={payoutsTitles}
/>
)}
{isBetsDetailedView && (
<ListItemDetails
isLastRowOfRunners={isLastRowOfRunners}
isRaceOver={isRaceOver}
isCanceled={isCanceled}
runner={runner}
isUnknownWinnerStatus={isUnknownWinnerStatus}
isWinnerBI={runner.isWinner || !!runner?.alternate?.isWinner}
showDetails={showDetails}
showTag={showTag}
isBetRefund={isBetRefund}
/>
)}
</SelectionList>
);
}
return (
<SelectionList
key={`Runner${!isArrow ? runnerNumber : `_arrow_${idx}`}`}
isBetsDetailedView={isBetsDetailedView}
isDesktop={isDesktop}
>
<ListItemWrapper isBetsDetailedView={isBetsDetailedView}>
{runners.map((currentRunner, index) => {
let toRender = null;
if (isArrow && index === runners.length - 1) {
toRender = (
<Icon
viewBoxSize={16}
size={20}
icon={arrowForward}
color={buildColor("black", "100")}
/>
);
}
if (!isArrow) {
// Check if no favorite is available and all runners are scratched
const allRunnersScratched = runners.every((r) => r.isScratched);
const noFavoriteAvailable =
!favoriteRunner || isEmpty(favoriteRunner);
if (allRunnersScratched && noFavoriteAvailable) {
toRender = (
<RunnerInfoContainer
data-qa-label="main-saddle-row"
isBetsDetailedView={isBetsDetailedView}
cols={payoutsTitlesLength}
betStatusName={betStatusName}
isDesktop={isDesktop}
>
<RunnerNumber
qaLabel={`saddle-container-${currentRunner.runnerId}`}
runnerId={currentRunner.runnerId}
saddleColor={currentRunner.saddleColor}
numberColor={currentRunner.numberColor}
raceTypeCode={raceTypeCode}
isFavorite={isFavorite}
isBetsStandalone
isScratched={currentRunner.isScratched}
isWinnerBI={isWinnerBI && !isCanceled}
isActiveMultiRaceLegOver={
isActiveMultiRaceLegOver && !isBetsDetailedView
}
isRaceOver={isRaceOver}
isBetsDetailedView={isBetsDetailedView}
isUnknownWinnerStatus={isUnknownWinnerStatus}
/>
{isRaceOver && !isCanceled && (
<>
<FavArrowIcon
icon={arrowForward}
viewBoxSize={16}
size={16}
color={buildColor("orange", "600")}
/>
<RunnerNumber
runnerId=""
raceTypeCode={raceTypeCode}
isFavorite={false}
isBetsStandalone
isScratched={false}
isWinnerBI={false}
isActiveMultiRaceLegOver={
isActiveMultiRaceLegOver && !isBetsDetailedView
}
isRaceOver={isRaceOver}
isBetsDetailedView={isBetsDetailedView}
isUnknownWinnerStatus={isUnknownWinnerStatus}
/>
</>
)}
</RunnerInfoContainer>
);
} else {
toRender = (
<>
<RunnerInfoContainer
isBetsDetailedView={isBetsDetailedView}
cols={payoutsTitlesLength}
betStatusName={betStatusName}
isDesktop={isDesktop}
>
<RunnerNumber
runnerId={currentRunner.runnerId}
raceTypeCode={raceTypeCode}
isFavorite={isFavorite}
isBetsStandalone
isScratched={currentRunner.isScratched}
isWinnerBI={isWinnerBI && !isCanceled}
isActiveMultiRaceLegOver={
isActiveMultiRaceLegOver && !isBetsDetailedView
}
isRaceOver={isRaceOver}
isBetsDetailedView={isBetsDetailedView}
isUnknownWinnerStatus={isUnknownWinnerStatus}
/>
{allowsPickBetSub &&
isCurrentRaceDate &&
favoriteRunner &&
!isEmpty(favoriteRunner) &&
isRaceOver &&
showReplacement &&
!isCanceled && (
<>
<FavArrowIcon
icon={arrowForward}
viewBoxSize={16}
size={16}
color={buildColor("orange", "600")}
/>
<RunnerNumber
runnerId={favoriteRunner?.runnerNumber}
raceTypeCode={raceTypeCode}
isFavorite={false}
isBetsStandalone
isScratched={false}
isWinnerBI={favoriteRunner?.isWinner}
isActiveMultiRaceLegOver={
isActiveMultiRaceLegOver && !isBetsDetailedView
}
isRaceOver={isRaceOver}
isBetsDetailedView={isBetsDetailedView}
/>
</>
)}
{isBetsDetailedView && (
<RunnerNameContainer
data-qa-label={`runnerName-${currentRunner?.runnerId}`}
isWinnerBI={isWinnerBI && !isCanceled}
isUnknownWinnerStatus={isUnknownWinnerStatus}
isActiveMultiRaceLegOver={
isActiveMultiRaceLegOver && isBetsDetailedView
}
>
{allowsPickBetSub &&
isCurrentRaceDate &&
favoriteRunner &&
!!favoriteRunner?.runnerName &&
isRaceOver &&
showReplacement ? (
<RunnerName className="runner-name">
{favoriteRunner?.runnerName ?? ""}
</RunnerName>
) : (
<RunnerName
className="runner-name"
isScratched={currentRunner?.isScratched ?? false}
>
{currentRunner?.runnerName ?? ""}
</RunnerName>
)}
</RunnerNameContainer>
)}
</RunnerInfoContainer>
</>
);
}
}
if (toRender) {
return (
<ListItem
data-qa-label="runnerNumber-ListItem"
key={`runnerNumberGroup-${get(
runner,
"runnerNumber",
""
)}-${index.toString()}-${isFavorite ? "Fav" : "Nfav"}`}
isBetsDetailedView={isBetsDetailedView}
>
{toRender}
</ListItem>
);
}
return toRender;
})}
</ListItemWrapper>
{showWillPays && (
<WillPaysDetails
runner={runner}
payoutsTitlesLength={payoutsTitlesLength}
runnerNumber={runnerNumber}
payoutsTitles={payoutsTitles}
/>
)}
{isBetsDetailedView && (showDetails || showTag) && (
<ListItemDetails
isLastRowOfRunners={isLastRowOfRunners}
isRaceOver={isRaceOver}
isCanceled={isCanceled}
runner={runner}
isUnknownWinnerStatus={isUnknownWinnerStatus}
isWinnerBI={!!runner.isWinner}
showDetails={showDetails}
showTag={showTag}
isBetRefund={isBetRefund}
/>
)}
</SelectionList>
);
};
export const getShortedSelectionsList = ({
runners,
favorites,
raceTypeCode,
isMultiRace = false,
isUnknownWinnerStatus = false,
wagerTypeCode,
isRaceOver,
isActiveMultiRaceLegOver,
isCanceled = false,
betStatusName = "",
isDesktop
}: ShortedSelectionsListProps) => {
let isFavorite;
let lastFavoriteAdded = "";
let startWithFavorite;
let i = 0;
const shortedSelections = [];
while (i < runners.length) {
const currentRunner = runners[i];
const isScratched = currentRunner.runners.some(
(r: { isScratched: boolean }) => r.isScratched
);
if (isScratched) {
isFavorite = includes(favorites, currentRunner.runnerNumber);
shortedSelections.push(
getListItem({
idx: i,
runner: currentRunner,
isMultiRace,
isCanceled,
isFavorite,
raceTypeCode,
isUnknownWinnerStatus,
betStatusName,
isWinnerBI: currentRunner?.isWinner ?? false,
wagerTypeCode,
isRaceOver,
isActiveMultiRaceLegOver,
isDesktop
})
);
i += 1;
} else {
let count = 1;
let countDE = 0;
while (
i + count < runners.length &&
(doubleEntryRegex.test(runners[i + count].runnerNumber) ||
parseInt(currentRunner.runnerNumber, 10) + (count - countDE) ===
parseInt(runners[i + count].runnerNumber, 10))
) {
if (
runners[i + count].runners.some(
(r: { isScratched: boolean }) => r.isScratched
) ||
get(runners[i + count], "isWinner", false)
) {
break;
}
if (doubleEntryRegex.test(runners[i + count].runnerNumber)) {
countDE += 1;
}
count += 1;
}
startWithFavorite = 0; // new runners sequence starts with a favorite (0 -> false, 1 -> true)
if (
count === 2 &&
checkFavoriteSequence(
currentRunner,
favorites,
lastFavoriteAdded,
doubleEntryRegex
)
) {
// check if the last runner added to the array was a favorite and if the next one is sequential to the favorite
startWithFavorite = 1;
}
if (count + startWithFavorite > 2) {
isFavorite = includes(favorites, currentRunner.runnerNumber);
// Add first runner
shortedSelections.push(
getListItem({
idx: i,
runner: currentRunner,
isMultiRace,
isCanceled,
isFavorite,
raceTypeCode,
isUnknownWinnerStatus,
betStatusName,
isWinnerBI: currentRunner?.isWinner ?? false,
wagerTypeCode,
isRaceOver,
isActiveMultiRaceLegOver,
isDesktop
})
);
// Add arrow
shortedSelections.push(
getListItem({
idx: i,
runner: currentRunner,
isMultiRace,
isCanceled,
isArrow: true,
raceTypeCode,
isUnknownWinnerStatus,
betStatusName,
isDesktop
})
);
// Add the last runner of arrow
const shortedIndex = i + count - 1;
isFavorite = includes(favorites, runners[shortedIndex].runnerNumber);
shortedSelections.push(
getListItem({
idx: shortedIndex,
runner: runners[shortedIndex],
isMultiRace,
isCanceled,
isFavorite,
raceTypeCode,
isUnknownWinnerStatus,
betStatusName,
isWinnerBI: runners[shortedIndex]?.isWinner ?? false,
wagerTypeCode,
isRaceOver,
isActiveMultiRaceLegOver,
isDesktop
})
);
lastFavoriteAdded = isFavorite
? runners[i + count - 1].runnerNumber
: "";
i += count;
} else {
// Single entry
isFavorite = includes(favorites, currentRunner.runnerNumber);
lastFavoriteAdded = isFavorite ? currentRunner.runnerNumber : "";
shortedSelections.push(
getListItem({
idx: i,
runner: currentRunner,
isMultiRace,
isCanceled,
isFavorite,
raceTypeCode,
isUnknownWinnerStatus,
betStatusName,
isWinnerBI: currentRunner?.isWinner ?? false,
wagerTypeCode,
isRaceOver,
isActiveMultiRaceLegOver,
isDesktop
})
);
i += 1;
}
}
}
return <>{shortedSelections}</>;
};
const MyBetsRunnerNumberGroup = ({
runners,
favoriteRunners,
raceTypeCode,
isBetsDetailedView = false,
isKey = false,
label,
showHorizontalRule = false,
showUpperHorizontalRule = false,
wagerTypeCode,
onDetailedView,
raceStatus,
isFirstRowOfRunners = false,
isLastRowOfRunners = false,
allRunnersSelected = false,
hasDetails = true,
betStatusName,
isPickBet = false,
isCanceled = false,
pickBetsLabelLength,
favoriteRunner,
isCurrentRaceDate = false,
isBetRefund = false,
isMultiRace = false,
isExotic = false,
isDesktop = false
}: MyBetsRunnerNumberGroupProps) => {
const notScratchedRunners = runners.filter((runner) =>
get(runner, "runners", []).every(
(currentRunner) => !currentRunner.isScratched
)
);
const runnersHaveWillPayAmount =
!isCanceled &&
!isBetRefund &&
notScratchedRunners.length > 0 &&
notScratchedRunners.some((runner) => get(runner, "willPayAmount", 0) > 0);
const isRaceOver = ["winner", "canceled", "loser", "refunded"].includes(
betStatusName
);
const isActiveMultiRaceLegOver =
isMultiRace &&
["win", "lost"].includes(raceStatus) &&
betStatusName === "active";
const isUnknownWinnerStatus = raceStatus === "unknown";
const hasScratchedRunners = runners.length > notScratchedRunners.length;
const alternateRunners = runners[0]?.alternate?.runners ?? [];
const hasAlternates = alternateRunners.length > 0;
const alternateRunnerReplacement = alternateRunners.filter(
(altRunner) => !altRunner.isScratched
);
const showAlternateReplacement =
hasScratchedRunners && !!alternateRunnerReplacement.length && isRaceOver;
const renderAllRunnersSelected = () => {
const allSelections = [];
allSelections.push(
getListItem({
idx: 0,
runner: runners[0],
isMultiRace,
isCanceled,
raceTypeCode,
isUnknownWinnerStatus,
betStatusName,
allRunnersSelected,
isActiveMultiRaceLegOver,
isDesktop
})
);
if (!isCanceled) {
runners.forEach((runner, idx) => {
if (get(runner, "isWinner", false)) {
allSelections.push(
getListItem({
idx,
runner,
isMultiRace,
isCanceled,
raceTypeCode,
isUnknownWinnerStatus,
betStatusName,
isWinnerBI: true,
isDesktop
})
);
}
});
}
return allSelections;
};
const buildSaddleList = (payoutsTitles: Array<string> = []) => {
if (!isBetsDetailedView && allRunnersSelected && !hasScratchedRunners) {
return renderAllRunnersSelected();
}
if (
!isBetsDetailedView &&
runners.length > 3 &&
notScratchedRunners.length > 0
) {
return getShortedSelectionsList({
runners,
favorites: favoriteRunners ?? [],
raceTypeCode,
isMultiRace,
isUnknownWinnerStatus,
allRunnersSelected,
wagerTypeCode,
isRaceOver,
isActiveMultiRaceLegOver,
isCanceled,
betStatusName,
isDesktop
});
}
return runners.map((biRunner, idx) =>
getListItem({
idx,
runner: biRunner,
isMultiRace,
isCanceled,
isFavorite: includes(favoriteRunners, biRunner.runnerNumber),
raceTypeCode,
isUnknownWinnerStatus,
betStatusName,
isBetsDetailedView,
allRunnersSelected,
isLastRowOfRunners,
isWinnerBI: biRunner?.isWinner ?? false,
wagerTypeCode,
isRaceOver,
isActiveMultiRaceLegOver,
payoutsTitles,
favoriteRunner,
isCurrentRaceDate,
isBetRefund,
isDesktop
})
);
};
const renderRunnerNumberGroup = () => {
const titles = getPayoutsHeaderTitle(
wagerTypeCode,
runners as BetSelection[]
);
return (
<RunnerNumberGroupMolecule
data-qa-label="runnerNumberGroup"
isBetsDetailedView={isBetsDetailedView}
betStatusName={betStatusName}
raceStatus={raceStatus}
>
{isBetsDetailedView && (
<PayoutsHeader
titles={titles}
isDesktop={isDesktop}
isCanceled={isCanceled}
/>
)}
{buildSaddleList(titles)}
{!showAlternateReplacement && alternateRunners.length > 0 && (
<AlternateRunners
alternateRunners={alternateRunners}
isBetsDetailedView={isBetsDetailedView}
isDesktop={isDesktop}
titles={titles}
betStatusName={betStatusName}
raceTypeCode={raceTypeCode}
isActiveMultiRaceLegOver={isActiveMultiRaceLegOver}
isRaceOver={isRaceOver}
isUnknownWinnerStatus={isUnknownWinnerStatus}
/>
)}
</RunnerNumberGroupMolecule>
);
};
if (isExotic) {
return (
<ExoticBetsLayout
isBetsDetailedView={isBetsDetailedView}
label={label}
isDesktop={isDesktop}
isKey={isKey}
showHorizontalRule={showHorizontalRule}
runnerNumberGroup={renderRunnerNumberGroup()}
/>
);
}
// Render Pick Bets
if (isMultiRace) {
return (
<PickBetLayout
runners={runners}
isDesktop={isDesktop}
isCanceled={isCanceled}
isBetsDetailedView={isBetsDetailedView}
onDetailedView={onDetailedView}
isPickBet={isPickBet}
isRaceOver={isRaceOver}
raceStatus={raceStatus}
label={label}
wagerTypeCode={wagerTypeCode}
hasAlternates={hasAlternates}
hasAlternateReplacement={!!alternateRunnerReplacement.length}
hasDetails={hasDetails}
isFirstRowOfRunners={isFirstRowOfRunners}
isLastRowOfRunners={isLastRowOfRunners}
runnersHaveWillPayAmount={runnersHaveWillPayAmount}
showHorizontalRule={showHorizontalRule}
showUpperHorizontalRule={showUpperHorizontalRule}
pickBetsLabelLength={pickBetsLabelLength}
runnerNumberGroup={renderRunnerNumberGroup()}
/>
);
}
// return default for simple bet types
return renderRunnerNumberGroup();
};
export default MyBetsRunnerNumberGroup;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MyBetsWagerFooter/styled-components.js
import styled, { css } from "styled-components";
import buildColor from "../../_static/ColorPalette";
import ButtonDefault from "../../_atom/Buttons/default";
import { fontMedium } from "../../_static/Typography";
export const BetCardFooter = styled.div.attrs({
"data-qa-label": "myBets-betTicket-footer"
})`
display: flex;
align-items: center;
justify-content: flex-end;
${({ isDesktop }) =>
!isDesktop &&
css`
height: 48px;
padding: 0 4px;
`};
${({ hasTopBorder, isDesktop }) =>
hasTopBorder &&
!isDesktop &&
`border-top: 1px solid ${buildColor("blue", "100")};`}
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
`;
export const FooterButton = styled(ButtonDefault)`
font-family: ${fontMedium};
text-decoration: none;
display: flex;
align-items: center;
height: 32px;
padding: 0 8px;
font-size: 14px;
border-radius: 2px;
color: ${({ isCancelButton }) =>
buildColor(
isCancelButton ? "red" : "grey",
isCancelButton ? "600" : "900"
)};
${({ isDetailsButton }) =>
isDetailsButton
? css`
margin-left: auto;
${({ isDesktop }) =>
isDesktop &&
`
margin-right: -6px;
`};
svg {
margin-left: 8px;
}
`
: css`
margin-right: 4px;
svg {
margin-right: 8px;
}
`};
svg {
flex-shrink: 0;
}
${({ isDetailsButton, isDesktop }) => {
if (isDesktop) {
return css`
position: absolute;
bottom: 8px;
right: 12px;
&:hover {
background-color: ${isDetailsButton
? buildColor("blue_accent", "100")
: buildColor("grey", "100")};
}
`;
}
return "";
}}
&:active {
background-color: ${({ isCancelButton, isDesktop }) => {
if (isCancelButton) {
return buildColor("red", "200");
}
if (isDesktop) {
return buildColor("blue_accent", "200");
}
return buildColor("grey", "200");
}};
}
${({ isDesktop }) =>
isDesktop &&
css`
color: ${buildColor("blue_accent", "500")};
`};
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MyBetsWagerFooter/index.jsx
import React from "react";
import { Link } from "react-router-dom";
import { first, noop } from "lodash";
import { Icon as DSIcon } from "@tvg/design-system";
import Icon from "../../_static/Icons";
import {
chevronDown,
chevronUp,
repeat,
trash
} from "../../_static/Icons/iconsDuotone";
import buildColor from "../../_static/ColorPalette";
import { BetCardFooter, FooterButton } from "./styled-components";
const parseSelectionsUrl = (url) => {
if (!url) return "";
const urlParsed = url.split("&");
if (urlParsed.length) {
urlParsed.shift();
urlParsed.pop();
return urlParsed.join("&");
}
return "";
};
const MyBetsWagerFooter = ({
closeModal,
raceUrl,
isDetailsOpened,
handleDetailsButton,
shouldRenderFooter,
isBetActive,
isWagerCancelable,
repeatButtonSearch,
showRepeatButton,
onCancelWager,
isContentDisplayed,
isDesktop,
onShareWager,
socialShareModalToggle
}) =>
shouldRenderFooter && (
<BetCardFooter hasTopBorder={isContentDisplayed} isDesktop={isDesktop}>
{socialShareModalToggle && (
<FooterButton
data-qa-label="myBets-social-share"
onClick={() => onShareWager(parseSelectionsUrl(repeatButtonSearch))}
>
<DSIcon
name="popout"
size="s"
lineColor={buildColor("blue", "900")}
/>
</FooterButton>
)}
{showRepeatButton && (
<FooterButton
data-qa-label="myBets-betTicked-repeatButton"
as={Link}
onClick={closeModal}
isDesktop={isDesktop}
to={{
pathname: first(raceUrl.split("?")),
search: repeatButtonSearch.substring(1)
}}
>
<Icon
icon={repeat}
viewBoxSize={16}
size={16}
color={buildColor("grey", "100")}
stroke={buildColor("blue", "900")}
/>
{isBetActive ? "Repeat bet" : "Re-Bet"}
</FooterButton>
)}
{isWagerCancelable && (
<FooterButton
qaLabel="myBets-betTicked-cancelButton"
isCancelButton
isDesktop={isDesktop}
onClick={onCancelWager}
>
<Icon
icon={trash}
viewBoxSize={16}
size={16}
color={buildColor("red", "000")}
stroke={
isDesktop
? buildColor("blue_accent", "500")
: buildColor("red", "600")
}
/>
Cancel
</FooterButton>
)}
<FooterButton
qaLabel="myBets-betTicked-detailsButton"
isDetailsButton
isDesktop={isDesktop}
showDetails={!isDetailsOpened}
onClick={handleDetailsButton}
>
{isDetailsOpened ? "Hide details" : "Show details"}
<Icon
icon={!isDetailsOpened ? chevronDown : chevronUp}
viewBoxSize={16}
size={16}
color="transparent"
stroke={
isDesktop
? buildColor("blue_accent", "500")
: buildColor("grey", "900")
}
/>
</FooterButton>
</BetCardFooter>
);
MyBetsWagerFooter.defaultProps = {
closeModal: noop,
raceUrl: "",
isDetailsOpened: false,
handleDetailsButton: noop,
shouldRenderFooter: false,
isBetActive: false,
isWagerCancelable: false,
repeatButtonSearch: "",
showRepeatButton: false,
onCancelWager: noop,
isDesktop: false
};
export default MyBetsWagerFooter;
webpack://frontend-mybets/../../packages/tvg-comp-my-bets-desktop/src/styled-components.ts
import styled from "styled-components"; export const BetSelections = styled.div``; export const BetSelectionsWrapper = styled.div` display: flex; flex-direction: column; margin-bottom: var(--fd-space-space-2); `;
webpack://frontend-mybets/../../packages/tvg-comp-my-bets-desktop/src/MyBetsSelections.tsx
import React, { useEffect } from "react";
import { BetSelection } from "@tvg/ts-types/Bet";
import {
checkAllDetailedViewIsOpen,
getSelectionLabel,
handleDetailsButton
} from "@tvg/sh-lib-my-bets/utils/general";
import {
getRaceStatus,
isPickBetSub
} from "@tvg/sh-lib-my-bets/utils/raceDetails";
import { calculateShowBetsDetailedView } from "@tvg/sh-lib-my-bets/utils/betsBetCard";
import MyBetsRunnerNumberGroup from "@tvg/atomic-ui/_molecule/MybetsRunnerNumberGroup";
import MyBetsWagerFooter from "@tvg/atomic-ui/_molecule/MyBetsWagerFooter";
import { get, noop, flatten } from "lodash";
import { MyBetsSelectionsProps } from "./types";
import { BetSelections, BetSelectionsWrapper } from "./styled-components";
const MyBetsSelections = (props: MyBetsSelectionsProps) => {
const {
wager,
raceNumber,
hasDetails,
isKey,
isBox,
isBetConfirmation,
selectedTab,
selectedSettledTab,
allRacesFromTrack,
currentOpenLeg,
activeBetsCounter,
settledBetsCounter,
betStatusName,
favoriteRunnerByLeg,
selections,
isCurrentRaceDate,
isCanceled,
isActive,
currentWagerTypeCode,
isMultiRace,
isPickBet,
isExotic,
showWillPays,
selectionSize
} = props;
const bettingInterests = allRacesFromTrack.map(
(race) => race.bettingInterests
);
const hasCoupledBI = selections.some((selection) =>
selection.some((runners) => runners.runners.length > 1)
);
const hasEnoughSelections = isExotic
? flatten(selections).length > selections.length
: flatten(selections).length > 1;
const hasBetsDetailButton =
((selections.length >= 1 && hasEnoughSelections) || hasCoupledBI) &&
!isCanceled;
const [showBetsDetailedView, setShowBetsDetailedView] = React.useState(
calculateShowBetsDetailedView(selections, showWillPays)
);
const [autoOpenedWillPays, setAutoOpenedWillPays] = React.useState(false);
const isDetailsOpened = checkAllDetailedViewIsOpen(showBetsDetailedView);
useEffect(() => {
const willPaysFetched =
currentOpenLeg &&
!!get(
allRacesFromTrack,
`[${+currentOpenLeg.number - 1}].willPays`,
false
);
if (
!showBetsDetailedView.length ||
!get(showBetsDetailedView, "[0].length", true)
) {
setShowBetsDetailedView(
calculateShowBetsDetailedView(selections, showWillPays)
);
} else if (showWillPays && willPaysFetched && !autoOpenedWillPays) {
const newDetailedView = showBetsDetailedView.map(
(leg: boolean, legIndex: number) =>
legIndex === showBetsDetailedView.length - 1 || leg
);
setAutoOpenedWillPays(true);
setShowBetsDetailedView(newDetailedView);
}
}, [selectedTab, selections, showWillPays]);
const shouldOpenDetails = selections.every(
(selection: Array<BetSelection>) =>
selection &&
selection.length === 1 &&
selection[0].runners.length === 1 &&
(selection[0]?.alternate?.runners?.length ?? 0) === 0
);
return (
<BetSelectionsWrapper>
<BetSelections>
{selections.map(
(selection, indexSelection, { length }: { length: number }) => {
const { key, label, pickBetsLabelLength } = getSelectionLabel({
selectionIndex: indexSelection,
selectionLength: length,
raceNumber: +raceNumber,
selectionsModifier: get(wager, "selections.modifier"),
isMultiRace,
isKey,
isBox,
isDesktop: true,
isSpecialWager: get(wager, "isSpecialWager", false)
});
const isAllRunnersScratched = selection.every((runner) =>
// @ts-ignore
runner.runners.every((r) => r.isScratched)
);
const legContainsScratch = selection.some((runner) =>
// @ts-ignore
runner.runners.every((r) => r.isScratched)
);
const betBettingInterests = [];
if (bettingInterests && bettingInterests.length > 0 && raceNumber) {
if (!isMultiRace) {
betBettingInterests.push(
get(
allRacesFromTrack.find(
(race) => +race.number === +raceNumber
),
"bettingInterests",
bettingInterests[+raceNumber - 1]
)
);
} else {
for (
let i = isBetConfirmation ? 0 : +raceNumber;
i < +raceNumber + selectionSize;
i += 1
) {
const raceArrayIterator = isBetConfirmation ? i : i - 1;
if (bettingInterests[+raceArrayIterator]) {
betBettingInterests.push(
get(
allRacesFromTrack.find((race) => +race.number === i),
"bettingInterests",
bettingInterests[+raceArrayIterator]
)
);
}
}
}
}
const resultsIndex = isMultiRace ? indexSelection : 0;
const currentBettingInterestsLength = get(
betBettingInterests,
`${resultsIndex}.length`,
0
);
const allRunnersSelected =
currentBettingInterestsLength === selection.length;
const favoriteRunner = get(
favoriteRunnerByLeg,
indexSelection,
undefined
);
const allowsPickBetSub = isPickBetSub(currentWagerTypeCode);
const selectionRaceStatus = getRaceStatus({
isAllRunnersScratched,
legContainsScratch,
selection,
selectionIndex: indexSelection,
races: allRacesFromTrack,
raceNumber,
selectionLength: length,
isMultiRace,
isCanceled,
betStatusName,
wagerType: currentWagerTypeCode,
favoriteRunner,
shouldShowReplacement: allowsPickBetSub
});
const isBetRefund =
get(wager, "betRefund", 0) > 0 &&
(betStatusName === "winner" || betStatusName === "refunded");
const isLastRowOfRunners = indexSelection === length - 1;
const alternateRunners = selection[0]?.alternate?.runners ?? [];
const hasAlternateRunners = alternateRunners.length > 0;
const hasMultipleSelections =
selection.length > 1 || hasAlternateRunners;
const hasMultipleSelectionsOnNextWager =
selections[indexSelection + 1] &&
(selections[indexSelection + 1].length > 1 ||
selections[indexSelection + 1].some((s) => !!s.alternate));
const isNotLastSelection = length !== indexSelection + 1;
const showHorizontalRule = isMultiRace
? (hasMultipleSelections && !isLastRowOfRunners) ||
hasMultipleSelectionsOnNextWager
: isNotLastSelection;
const showUpperHorizontalRule =
isMultiRace &&
showBetsDetailedView &&
showBetsDetailedView.filter((leg: boolean) => leg).length === 1 &&
get(showBetsDetailedView, `[${indexSelection}]`, false) === true;
const sortedSelection = selection.sort(
(a, b) => +get(a, "runnerNumber") - +get(b, "runnerNumber")
);
return (
<MyBetsRunnerNumberGroup
key={`runner-group${indexSelection.toString()}${get(
wager,
"id",
"unk"
)}`}
isDesktop
runners={sortedSelection}
raceTypeCode={get(wager, "raceTypeAbbreviation")}
isMultiRace={isMultiRace}
isExotic={isExotic}
isBetsStandalone
isBetsDetailedView={
shouldOpenDetails ||
isDetailsOpened ||
get(showBetsDetailedView, indexSelection, false)
}
isKey={key}
label={label}
showHorizontalRule={showHorizontalRule && isDetailsOpened}
showUpperHorizontalRule={showUpperHorizontalRule}
isFirstRowOfRunners={indexSelection === 0}
isLastRowOfRunners={isLastRowOfRunners}
wagerTypeCode={currentWagerTypeCode}
allRunnersSelected={allRunnersSelected}
hasDetails={hasDetails}
raceStatus={selectionRaceStatus}
betStatusName={betStatusName}
isPickBet={isPickBet}
isCanceled={isCanceled}
pickBetsLabelLength={pickBetsLabelLength}
favoriteRunner={favoriteRunner}
isCurrentRaceDate={isCurrentRaceDate}
isBetRefund={isBetRefund}
/>
);
}
)}
</BetSelections>
<MyBetsWagerFooter
isDetailsOpened={isDetailsOpened}
handleDetailsButton={() => {
handleDetailsButton(
selectedTab,
selectedSettledTab,
isDetailsOpened,
showBetsDetailedView,
setShowBetsDetailedView,
selections,
noop,
activeBetsCounter,
settledBetsCounter
);
}}
shouldRenderFooter={!shouldOpenDetails && hasBetsDetailButton}
isBetActive={isActive}
isContentDisplayed={isDetailsOpened}
isDesktop
/>
</BetSelectionsWrapper>
);
};
MyBetsSelections.defaultProps = {
wager: {},
raceNumber: 1,
statusCode: "O",
raceDate: "",
currentRaceDate: "",
allRacesFromTrack: [],
currentRace: {},
hasDetails: false,
isKey: false,
isBox: false,
isBetConfirmation: false,
selectedTab: "ACTIVE",
selectedSettledTab: "TODAY",
currentOpenLeg: {},
shouldShowPotentialReturn: false,
betStatusName: "",
favoriteRunnerByLeg: null,
selections: [],
isCanceled: false,
isActive: false,
currentWagerTypeCode: "",
isMultiRace: false,
isPickBet: false,
isExotic: false,
selectionSize: 0
};
export default MyBetsSelections;
webpack://frontend-mybets/../../packages/tvg-comp-my-bets-desktop/src/MyBetsRow.tsx
/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useCallback, useEffect, useState, useMemo } from "react";
import { Store } from "redux";
import { connect } from "react-redux";
import { compact, first, get, last } from "lodash";
import {
enableRepeatBetsMyBets,
getFeatureIsMTPNewRules,
getFeatureUseTvgPotReturn,
getMyBetsTrackRulesMessage,
getMyBetsTrackRulesToggle,
getPickBetRebetToggle,
getSelectedSettledTab,
getSelectedTab,
getShowSeeResult
} from "@tvg/sh-lib-my-bets/redux/selectors";
import {
getActiveLegs,
getRaceProps,
getRacesInPickBets,
isMultiRaceBet,
shouldShowWillPays
} from "@tvg/sh-lib-my-bets/utils/raceDetails";
import {
handleRaceHeaderGtm,
onApproxPayoutModalGtm,
onNavigateToTrackGtm,
onRepeatBetGTM
} from "@tvg/sh-lib-my-bets/utils/gtm";
import {
cleanBetCancelResult,
openBetCancelModal,
openMybetsPastPerformance
} from "@tvg/sh-lib-my-bets/redux/actions";
import {
getWagerBetStatus,
getWagerProps
} from "@tvg/sh-lib-my-bets/utils/general";
import { getVideoFeedback } from "@tvg/sh-lib-my-bets/utils/video";
import useAllRacesFromTrack from "@tvg/sh-lib-my-bets/hooks/useAllRacesFromTrack";
import MyBetsRowOrganism from "@tvg/atomic-ui/_organism/MyBetsRow";
import usePickBetRebet from "@tvg/sh-lib-my-bets/hooks/usePickBetRebet";
import useSelections from "@tvg/sh-lib-my-bets/hooks/useSelections";
import useMinMaxWillPays from "@tvg/sh-lib-my-bets/hooks/useMinMaxWillPays";
import useResults from "@tvg/sh-lib-my-bets/hooks/useResults";
import buildRaceUrl, {
buildBetSlipUrl,
buildTalentPicksTVG5Url
} from "@tvg/formatter/url";
import {
getFavoriteRunnerByLeg,
stringifySelectionsBetSlip
} from "@tvg/sh-lib-my-bets/utils/pickBets";
import mediator from "@tvg/mediator";
import useScratchNotification from "@tvg/sh-lib-my-bets/hooks/useScratchNotification";
import { getTrackRulesMessage } from "@tvg/sh-lib-my-bets/utils/track";
import { FavoriteRunners, RaceVideoFeedback } from "@tvg/ts-types/Race";
import { ActiveTabEnum, SettledTabEnum } from "@tvg/sh-lib-my-bets/utils/types";
import PromosOnboarding from "@tvg/promos-onboarding";
import { StoryblokPlaceName } from "@tvg/sh-lib-promos-onboarding/types/promoOnboardingComponents";
import { Device } from "@tvg/ts-types/Device";
import { getStoryblokPromoByStep } from "@tvg/sh-lib-promos-onboarding/redux/selectors";
import { matchPlacedWager } from "@tvg/sh-lib-promos-onboarding/utils/matchPlacedWager";
import {
PromoStepType,
WagerStep
} from "@tvg/sh-lib-promos-onboarding/types/promoSteps";
import { useNavigate } from "@tvg/custom-hooks";
import { isTvg5 } from "@tvg/utils/generalUtils";
import { cancelBetGtmEvent } from "@tvg/pp/src/utils/gtm/betCancel";
import { BetSelection } from "@tvg/ts-types/Bet";
import { getBettingInfo } from "@tvg/desktop-bet/src/utils/betUtils";
import BetUtils, { getValidRunnerId } from "@tvg/utils/betSelection";
import { WagerTypeCodesEnum } from "@tvg/ts-types/Wager";
import { useURPProgramPageOnXSell } from "@urp/amplitude-experiments";
import { placeBetGtmEvent } from "./utils/gtm/placeBetGtmEvent";
import MyBetsSelections from "./MyBetsSelections";
import type { MyBetsRowProps } from "./types";
const ACTION_WRAPPER_COL_SIZE = "250px";
export const MyBetsRow = ({
bet,
races,
currentRaceDate,
qaLabel = "mybets-wager-row",
dispatch,
selectedTab = ActiveTabEnum.ACTIVE,
selectedSettledTab = SettledTabEnum.TODAY,
isMTPNewRules = true,
activeBetsCounter = 0,
settledBetsCounter = 0,
useTvgPotReturnToggle = false,
enablePickBetRebet = false,
enablePickBetRepeat = false,
showSeeResultToggle = false,
trackRulesMessages = "",
trackRulesToggle = false,
promosOnboardingStep = null,
handleSelectedRace,
handleSelectedWager,
setIsRepeatBetModalOpen
}: MyBetsRowProps) => {
const [favoriteRunnerByLeg, setFavoriteRunnerByLeg] =
useState<FavoriteRunners>({});
const wager = get(bet, `wagers[0]`, {});
const mainWagerDetails = get(bet, "value", "||0").split("|");
const betRefund = get(wager, "betRefund", 0);
const [raceDate, trackCode] = mainWagerDetails;
const raceNumber = +get(mainWagerDetails, 2, "0");
const racePostTime = get(wager, "racePostTime", "");
const isURPPpOnXSellEnabled = useURPProgramPageOnXSell();
const dateDiff = Math.round(
(new Date(racePostTime).getTime() - new Date().getTime()) /
(1000 * 3600 * 24)
);
const currentRace = races.find(
(race) =>
race.id === `${trackCode}-${raceNumber}` && race.raceDate === raceDate
);
const isMultiRace = isMultiRaceBet(get(wager, "wagerType.code", ""));
const allRacesFromTrack = useAllRacesFromTrack({ races, trackCode });
const wagerSelectionSize = get(wager, "selections.selection.length", 0);
const activeRaces =
allRacesFromTrack &&
allRacesFromTrack.length > 0 &&
getActiveLegs(allRacesFromTrack, raceNumber, wagerSelectionSize);
const currentOpenLeg: any = activeRaces ? first(activeRaces) : null;
const legRaces = getRacesInPickBets(
allRacesFromTrack,
raceNumber,
wagerSelectionSize
);
const isSettledBet = selectedTab === "SETTLED";
const hasRaceLeg = !!(
isMultiRace &&
!isSettledBet &&
currentRace &&
currentOpenLeg
);
const betStatusCode = get(wager, "betStatus.code", "");
const betStatusName = get(wager, "betStatus.name", "");
const betAmount =
betStatusCode !== "C" && betStatusCode !== "R"
? get(wager, "betTotal", 0)
: 0;
const wagerAmount = get(wager, "wagerAmount", 0);
let videoFeedback = RaceVideoFeedback.NOT_AVAILABLE_NO_REPLAY;
if (isMultiRace && currentOpenLeg && !isSettledBet) {
videoFeedback = getVideoFeedback(
currentOpenLeg,
first(allRacesFromTrack),
last(allRacesFromTrack)
);
} else if (currentRace) {
videoFeedback = getVideoFeedback(
currentRace,
first(allRacesFromTrack),
last(allRacesFromTrack)
);
}
const { isCanceled: isCancelled } = getWagerBetStatus(
get(wager, "betStatus", {})
);
const {
mtp,
statusCode,
legStatusCode,
legNumber,
currentRaceNumber,
hasLiveVideo
} = getRaceProps({
isMultiRace,
legRaces,
isCancelled,
currentRace,
currentLeg: currentOpenLeg,
bet,
isSettledBet,
currentRaceDate,
betDate: raceDate,
videoFeedback,
raceNumber
});
const {
isCurrentRaceDate,
isCanceled,
isActive,
currentWagerTypeCode,
currentWagerTypeId,
isWagerCancelable,
isPickBet,
isExotic,
isOptedIn,
isMultiRace: isWagerMultiRace
} = getWagerProps(
wager,
statusCode,
currentRaceDate,
get(mainWagerDetails, 0, ""),
isURPPpOnXSellEnabled,
currentRace
);
const hasReplayVideo = videoFeedback.indexOf("NO_REPLAY") === -1;
const redirectUrl = buildRaceUrl(
trackCode,
get(currentRace, "trackName", ""),
raceNumber,
wager.raceTypeAbbreviation === "G"
);
const shouldRedirect = isActive || dateDiff === 0;
const showReplayVideo =
showSeeResultToggle &&
!isActive &&
statusCode === "RO" &&
wager.betStatus.code !== "R" &&
wager.betStatus.code !== "C" &&
wager.raceTypeAbbreviation !== "G";
const hasPastPerformance = showReplayVideo && hasReplayVideo;
const showSeeResult = showReplayVideo && !hasPastPerformance && !hasLiveVideo;
const finalBettedLeg = currentRace
? +get(currentRace, "number", "0") + wagerSelectionSize - 1
: 0;
const betResults = [];
if (allRacesFromTrack && allRacesFromTrack.length > 0 && raceNumber) {
for (
let j = +raceNumber - 1;
j < +raceNumber + wagerSelectionSize - 1;
j += 1
) {
if (allRacesFromTrack[+j] && allRacesFromTrack[+j].results) {
betResults.push(allRacesFromTrack[+j].results);
}
}
}
const showWillPays =
currentRace && allRacesFromTrack && isMultiRace && betResults && !isCanceled
? shouldShowWillPays(
allRacesFromTrack,
wager.selections.selection,
compact(betResults),
finalBettedLeg
)
: false;
const betProbableValue = get(wager, "probable", "0");
const shouldShowPotentialReturn =
useTvgPotReturnToggle &&
isActive &&
!showWillPays &&
betProbableValue !== "0";
const results = useResults({
allRacesFromTrack
});
const selections = useSelections({
wager,
isMultiRace,
raceNumber,
currentRace,
currentRaceDate,
finalBettedLeg,
showWillPays,
allRacesFromTrack,
currentWagerTypeCode,
isActive,
results,
isExotic
});
const hasAlternates = useMemo(
() => selections.flat().some((selection) => !!selection.alternate),
[selections]
);
const { minWillPays, maxWillPays, showMinMaxWillPays } =
useMinMaxWillPays(selections);
const openBetSlip = useCallback(
(stringifySelections, betWagerTypeId, betWagerAmount, repeatType?) => {
if (window) {
const isGreyhound = get(currentRace, "isGreyhound", false);
const trackName = get(currentRace, "trackName", "");
const url = buildRaceUrl(
trackCode,
trackName,
currentRaceNumber,
isGreyhound
);
onRepeatBetGTM({
gaEventAction: "My Bets CTA Clicked",
gaEventLabel: "repeat bet",
module: "my-bets"
});
mediator.base.dispatch({
type: "TVG4_NAVIGATION",
payload: { route: url }
});
const newUrl = buildBetSlipUrl(
trackCode,
`${currentRaceNumber}`,
stringifySelections,
isGreyhound,
betWagerTypeId,
betWagerAmount,
repeatType ? "repeatBet" : "rebetBet"
);
window.open(newUrl, "", "width=535,height=778");
}
},
[trackCode, currentRaceNumber, currentRace]
);
const [
// eslint-disable-next-line @typescript-eslint/no-unused-vars
UNUSED_handleRebetClickEvent,
rebetWagerTypeName,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
UNUSED_rebetSearch,
shouldShowRebet,
rebetWagerTypeId,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
UNUSED_rebetSelections,
rebetWagerAmount,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
UNUSED_betAmount,
eligibleWagerSelections,
rebetWagerType
] = usePickBetRebet({
allRacesFromTrack,
mainWagerDetails,
currentRace,
currentOpenLeg,
selections,
enablePickBetRebet,
isPickBet,
isCurrentRaceDate,
isSettledBet,
callback: openBetSlip
});
const validSelections = selections.map((selection: BetSelection[]) =>
getValidRunnerId(selection)
);
let totalFilteredAmount = 0;
const typeFromRace =
currentRace &&
BetUtils.getOriginalBetTypeFromRace(
currentRace,
wager.wagerType.id as unknown as WagerTypeCodesEnum
);
if (currentRace) {
const bettingInfo = getBettingInfo(
validSelections,
wager.wagerAmount,
currentRace,
races,
typeFromRace
);
totalFilteredAmount = Number(bettingInfo.totalAmount);
}
const showRepeatButton =
enablePickBetRepeat &&
!shouldShowRebet &&
(wager.cancelable ||
betStatusName === "canceled" ||
betStatusName === "active") &&
raceNumber &&
betAmount !== undefined &&
(statusCode === "O" || statusCode === "IC") &&
selectedTab !== "FUTURES" &&
totalFilteredAmount > 0;
const renderRunnerSelections = useCallback(
() => (
<MyBetsSelections
wager={wager}
raceNumber={raceNumber}
statusCode={statusCode}
currentRaceDate={get(bet, "wagers[0].raceDate", "")}
hasDetails={!isCanceled}
selectedTab={selectedTab}
selectedSettledTab={selectedSettledTab}
allRacesFromTrack={allRacesFromTrack}
currentRace={currentRace}
currentOpenLeg={currentOpenLeg}
showWillPays={showWillPays}
activeBetsCounter={activeBetsCounter}
settledBetsCounter={settledBetsCounter}
favoriteRunnerByLeg={favoriteRunnerByLeg}
selections={selections}
isCurrentRaceDate={isCurrentRaceDate}
isCanceled={isCanceled}
isActive={isActive}
currentWagerTypeCode={currentWagerTypeCode}
isMultiRace={isWagerMultiRace}
isPickBet={isPickBet}
isExotic={isExotic}
betStatusName={betStatusName}
selectionSize={wagerSelectionSize}
/>
),
[
wager,
bet,
raceNumber,
statusCode,
raceNumber,
isCanceled,
legStatusCode,
selectedSettledTab,
races,
currentRace,
allRacesFromTrack,
favoriteRunnerByLeg
]
);
const onRepeatBets = useCallback(() => {
if (isTvg5()) {
setIsRepeatBetModalOpen(true);
handleSelectedRace(currentRace);
handleSelectedWager(wager);
} else {
const newSelectionsWithoutScratch: BetSelection[][] = selections.map(
(selection: BetSelection[]) =>
selection.reduce(
(accSelection: BetSelection[], currSelection: BetSelection) => {
const runners = get(currSelection, "runners") || [];
if (runners.some((runner: any) => !runner.isScratched)) {
accSelection.push(currSelection);
}
return accSelection;
},
[]
)
);
const stringifySelections = stringifySelectionsBetSlip(
newSelectionsWithoutScratch
);
openBetSlip(
stringifySelections,
currentWagerTypeId,
wagerAmount,
isActive ? "Repeat" : "Rebet"
);
}
placeBetGtmEvent({
raceNumber: String(raceNumber),
trackName: currentRace?.trackName,
betType: String(typeFromRace?.type),
betAmount: wagerAmount,
selectionSource: "repeat_bet_mybets",
selectionRaceType: bet.raceType
});
}, [
selections,
currentWagerTypeId,
currentWagerTypeCode,
wagerAmount,
isActive
]);
const onReBet = useCallback(() => {
if (isTvg5()) {
const trackName = get(currentRace, "trackName", "");
const trackURL = buildTalentPicksTVG5Url({
track: trackCode,
trackName,
race: currentRaceNumber,
amount: `${rebetWagerAmount}`,
// @ts-ignore
wagerType: rebetWagerType,
selections: eligibleWagerSelections
});
navigate.push(trackURL);
} else {
const selectionStringify = eligibleWagerSelections
.map((selection: string[]) => selection.join())
.join(";");
openBetSlip(selectionStringify, rebetWagerTypeId, rebetWagerAmount);
}
}, [
eligibleWagerSelections,
rebetWagerTypeId,
rebetWagerAmount,
rebetWagerType
]);
const onWatchReplay = useCallback(() => {
handleRaceHeaderGtm("MYBETS_USER_CLICKS_WATCH_REPLAY", {
selectedTab,
selectedSettledTab,
activeBets: activeBetsCounter,
settledBets: settledBetsCounter,
gaEventLabel: hasReplayVideo ? "Watch Replay" : "See Result"
});
const modalTitle = `${get(
currentRace,
"trackName",
get(bet, "wagers[0].trackName", "")
)} R${raceNumber} - Replay`;
dispatch(
openMybetsPastPerformance(
{
trackCode,
raceNumber,
raceDate
},
modalTitle
)
);
}, [
currentRace,
raceNumber,
raceDate,
bet,
selectedTab,
selectedSettledTab,
activeBetsCounter,
settledBetsCounter,
hasReplayVideo
]);
const navigate = useNavigate();
const onWatchDetails = useCallback(() => {
if (shouldRedirect) {
if (isTvg5()) {
navigate.push(redirectUrl);
} else {
mediator.base.dispatch({
type: "TVG4_NAVIGATION",
payload: { route: redirectUrl }
});
}
onNavigateToTrackGtm(
selectedTab,
selectedSettledTab,
activeBetsCounter,
settledBetsCounter,
redirectUrl
);
}
}, [
shouldRedirect,
redirectUrl,
selectedTab,
selectedSettledTab,
activeBetsCounter,
settledBetsCounter
]);
const onLiveVideo = useCallback(() => {
const liveRedirect = isMultiRace
? buildRaceUrl(
trackCode,
get(currentRace, "trackName", ""),
currentRaceNumber,
wager.raceTypeAbbreviation === "G"
)
: redirectUrl;
const liveRedirectFullUrl = liveRedirect + "&video=true";
if (isTvg5()) {
navigate.push(liveRedirectFullUrl);
} else {
mediator.base.dispatch({
type: "TVG4_NAVIGATION",
payload: { route: liveRedirectFullUrl }
});
}
onNavigateToTrackGtm(
selectedTab,
selectedSettledTab,
activeBetsCounter,
settledBetsCounter,
liveRedirectFullUrl
);
}, [
redirectUrl,
selectedTab,
selectedSettledTab,
activeBetsCounter,
settledBetsCounter,
currentRaceNumber,
isMultiRace
]);
useEffect(() => {
if (allRacesFromTrack) {
setFavoriteRunnerByLeg(
getFavoriteRunnerByLeg(
selections,
allRacesFromTrack,
+raceNumber,
wager.raceDate
)
);
}
}, [allRacesFromTrack, selections]);
const [
showScratchedNotification,
shouldNotHideScratchNotification,
setShouldNotHideScratchNotification,
scratchedTitle,
scratchedLegText
] = useScratchNotification({
selections,
isPickBet,
betStatusCode,
favoriteRunnerByLeg,
currentWagerTypeCode,
isCurrentRaceDate,
betRefund
});
const showPromoOnboarding =
!!promosOnboardingStep && matchPlacedWager(promosOnboardingStep, wager);
const promoOnboardingComponent = (
<PromosOnboarding
placeToRender={StoryblokPlaceName.MYBETS_RACE_DETAILS}
device={Device.DESKTOP}
/>
);
return (
<>
<MyBetsRowOrganism
mtp={mtp}
wager={wager}
raceStatusCode={statusCode}
legStatusCode={legStatusCode}
legNumber={legNumber}
showRaceLeg={hasRaceLeg}
selectedTab={selectedTab}
isMTPNewRules={isMTPNewRules}
raceNumber={raceNumber}
isCanceled={!!isCanceled}
dateDiff={dateDiff}
qaLabel={qaLabel!}
betAmount={betAmount}
isOptedIn={isOptedIn}
showPromoOnboarding={showPromoOnboarding}
promoOnboardingComponent={promoOnboardingComponent}
isWagerCancelable={
isPickBet && currentOpenLeg
? isWagerCancelable && +currentOpenLeg?.number === raceNumber
: isWagerCancelable
}
onCancelWager={() => {
dispatch(cleanBetCancelResult());
dispatch(openBetCancelModal({ bet, wager }));
cancelBetGtmEvent();
}}
renderRunnerSelections={renderRunnerSelections()}
shouldShowPotentialReturn={shouldShowPotentialReturn}
probableValue={betProbableValue}
onApproxPayout={() =>
onApproxPayoutModalGtm(dispatch, {
selectedTab,
selectedSettledTab,
activeBetsCount: +activeBetsCounter,
settledBetsCount: +settledBetsCounter
})
}
shouldShowRebet={shouldShowRebet}
handleRebetClickEvent={onReBet}
onRepeatBets={onRepeatBets}
showRepeatButton={showRepeatButton}
rebetWagerTypeName={rebetWagerTypeName}
isBetActive={isActive}
showMinMaxWillPays={showMinMaxWillPays}
minWillPays={minWillPays}
maxWillPays={maxWillPays}
onRaceDetails={onWatchDetails}
onWatchReplay={onWatchReplay}
hasPastPerformance={hasPastPerformance}
shouldRedirect={shouldRedirect}
showSeeResult={showSeeResult}
hasLiveVideo={hasLiveVideo}
onLiveVideo={onLiveVideo}
showScratchedNotification={
trackRulesToggle && showScratchedNotification
}
shouldNotHideScratchNotification={shouldNotHideScratchNotification}
setShouldNotHideScratchNotification={
setShouldNotHideScratchNotification
}
scratchedTitle={scratchedTitle}
scratchedLegText={scratchedLegText}
isMultiRace={isMultiRace}
currentRaceNumber={currentRaceNumber}
trackRulesMessages={getTrackRulesMessage(
trackRulesMessages,
currentWagerTypeCode,
isWagerMultiRace,
hasAlternates
)}
actionWrapperColSize={ACTION_WRAPPER_COL_SIZE}
/>
</>
);
};
const mapStateToProps = (store: Store) => ({
selectedTab: getSelectedTab(store),
selectedSettledTab: getSelectedSettledTab(store),
isMTPNewRules: getFeatureIsMTPNewRules(store),
useTvgPotReturnToggle: getFeatureUseTvgPotReturn(store),
enablePickBetRebet: getPickBetRebetToggle(store),
enablePickBetRepeat: enableRepeatBetsMyBets(store),
showSeeResultToggle: getShowSeeResult(store),
trackRulesMessages: getMyBetsTrackRulesMessage(store),
trackRulesToggle: getMyBetsTrackRulesToggle(store),
promosOnboardingStep: getStoryblokPromoByStep(
store,
PromoStepType.WAGER
) as WagerStep
});
export default connect(mapStateToProps)(MyBetsRow);
webpack://frontend-mybets/../../packages/tvg-comp-my-bets-desktop/src/utils/gtm/placeBetGtmEvent.ts
import mediator from "@tvg/mediator";
interface PlaceBetGtm {
raceNumber: string;
trackName?: string;
betType: string;
betAmount: string;
selectionSource: string;
selectionRaceType: string;
specialWagerType?: string;
}
export const placeBetGtmEvent = ({
raceNumber,
trackName,
betType,
betAmount,
selectionSource,
selectionRaceType,
specialWagerType
}: PlaceBetGtm) => {
mediator.base.dispatch({
type: "BETSLIP:PLACE_BET",
payload: {
raceNumber,
trackName,
betType,
betAmount,
selectionSource,
selectionRaceType,
specialWagerType
}
});
};
export const repeatBetEvent = ({
raceNumber,
trackName,
betType,
betAmount
}: PlaceBetGtm) => {
mediator.base.dispatch({
type: "BETSLIP:ADD_TO_BETSLIP",
payload: {
raceNumber,
trackName,
betType,
betAmount
}
});
};
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/utils/gtm/betCancel.ts
import mediator from "@tvg/mediator";
import {
betCancelSubmitGtm,
betCancelErrorGtm,
betCancelSuccessGtm
} from "./types";
export const cancelBetGtmEvent = () => {
mediator.base.dispatch({
type: "MYBETS:BET_CANCEL"
});
};
export const cancelBetSubmitGtmEvent = ({
raceNumber,
trackName,
betAmount,
betType
}: betCancelSubmitGtm) => {
mediator.base.dispatch({
type: "BET:BET_CANCEL_SUBMIT",
payload: {
raceNumber,
trackName,
betAmount,
betType
}
});
};
export const cancelBetErrorGtmEvent = ({
gaEventLabel,
raceNumber,
trackName,
betAmount,
betType,
errorType
}: betCancelErrorGtm) => {
mediator.base.dispatch({
type: "BET:BET_CANCEL_ERROR",
payload: {
gaEventLabel,
raceNumber,
trackName,
betAmount,
betType,
errorType
}
});
};
export const cancelBetSuccessGtmEvent = ({
raceNumber,
trackName,
betAmount,
betType
}: betCancelSuccessGtm) => {
mediator.base.dispatch({
type: "BET:BET_CANCEL_SUCCESS",
payload: {
raceNumber,
trackName,
betAmount,
betType
}
});
};
export const keepBetGtmEvent = () => {
mediator.base.dispatch({
type: "MYBETS:BET_CANCEL_KEEP_BET"
});
};
export const closeModalBetGtmEvent = () => {
mediator.base.dispatch({
type: "MYBETS:CANCEL_BET_MODAL_CLOSED"
});
};
webpack://frontend-mybets/../../packages/tvg-comp-my-bets-desktop/src/index.tsx
/* eslint-disable @typescript-eslint/no-explicit-any */
import React, {
FC,
useEffect,
useState,
useLayoutEffect,
useRef,
useMemo,
useCallback
} from "react";
import { connect, batch, useSelector } from "react-redux";
import { Dispatch, Store } from "redux";
import { graphql } from "@apollo/client/react/hoc";
import { get, throttle, flowRight as compose } from "lodash";
import { ToastManager, ToastMessageLink } from "@tvg/design-system";
import { formatDateToMMDDYYYY } from "@tvg/formatter/dates";
import mediator from "@tvg/mediator";
import { isTvg5 } from "@tvg/utils/generalUtils";
import {
buildTabs,
safeJSONParse,
getEmptyStateTitle,
getEmptyStateMessage,
shouldRedirectToSettled
} from "@tvg/sh-lib-my-bets/utils/service";
import {
onMyBetsStartupGtm,
onMyBetsFilterHandling,
handleCancelBetNotificationGtm,
selectedNewCustomDateGtm,
sendTimeframeSelectionGtmEvent,
onTabClickGtm
} from "@tvg/sh-lib-my-bets/utils/gtm";
import {
isLoadingMyBets,
openBetCancelModal,
closeWagerCancellationRulesModal,
setCustomEndDate,
setCustomStartDate,
closeTrackRulesModal,
openWagerCancellationRulesModal
} from "@tvg/sh-lib-my-bets/redux/actions";
import { MyBetsDynamicFilter } from "@tvg/sh-lib-my-bets/redux/types";
import {
RaceInfoMyBets,
RaceProgram,
RaceWagerType,
RaceProgramRaceTrack
} from "@tvg/ts-types/Race";
import {
getSelectedSettledTab,
getSelectedTab,
getDeletedBets,
getIsLoadingMyBets,
getStatusFilters,
getStatusFiltersCount,
getTrackFilters,
getTrackFiltersCount,
getIsWagerCancellationRulesModalOpen,
getBetCancelLimitationsByState,
getBetCancel,
getBetTypeFilters,
getBetTypeFiltersCount,
getMyBetsPaginationConf,
getCustomStartDate,
getCustomEndDate,
getIsCustomTimeFrame,
getRedirectWithoutActiveBetsToggle,
getIsTrackRulesModalOpen,
getMyBetsTrackRulesMessage
} from "@tvg/sh-lib-my-bets/redux/selectors";
import {
shouldRenderWager,
isSuccessBetCancel
} from "@tvg/sh-lib-my-bets/utils/general";
import {
getQueryDynamicOptions,
selectNewStatusFilters,
setDynamicFilters,
resetAllFilters,
selectNewTimeFrame,
updateIsCustomTimeFrame,
reduceDynamicFilters,
clearAllFilters,
clearDrowpdownFilters
} from "@tvg/sh-lib-my-bets/utils/filters";
import groupByWagerType from "@tvg/desktop-bet/src/utils/groupByWagerType";
import useUpdateActiveBetsWithProbables from "@tvg/sh-lib-my-bets/hooks/useUpdateActiveBetsWithProbables";
import useMyBetsCountersSubscription from "@tvg/sh-lib-my-bets/hooks/useMyBetsCountersSubscription";
import useMyBetsSubscription from "@tvg/sh-lib-my-bets/hooks/useMyBetsSubscription";
import useGraphRacesSubscription from "@tvg/sh-lib-my-bets/hooks/useGraphRacesSubscription";
import usePagination from "@tvg/sh-lib-my-bets/hooks/usePagination";
import useMyBetsUpdateRaces from "@tvg/sh-lib-my-bets/hooks/useMyBetsUpdateRaces";
import useClearAllFilters from "@tvg/sh-lib-my-bets/hooks/useClearAllFilters";
import BehgOptions from "@tvg/sh-lib-my-bets/graphql/behgOptions.graph";
import ApolloOptions from "@tvg/sh-lib-my-bets/graphql/options.graph";
import GroupWagersQuery from "@tvg/sh-lib-my-bets/graphql/queries/GroupWagers";
import GroupWagersQueryBehg from "@tvg/sh-lib-my-bets/graphql/queries/GroupWagersBehg";
import AllWagerTypesQuery from "@tvg/sh-lib-my-bets/graphql/queries/AllWagerTypes";
import AllWagerTypesQueryTvg4 from "@tvg/sh-lib-my-bets/graphql/queries/AllWagerTypesMep";
import WagersSubscription from "@tvg/sh-lib-my-bets/graphql/subscriptions/WagersSubscription";
import WagersSubscriptionBehg from "@tvg/sh-lib-my-bets/graphql/subscriptions/WagersSubscriptionBehg";
import RacesSubscription from "@tvg/sh-lib-my-bets/graphql/subscriptions/RacesSubscription";
import { Props, BetCancelResult } from "@tvg/sh-lib-my-bets/utils/types";
import { BetBasicInfo } from "@tvg/ts-types/Bet";
import SettledGraphOptions from "@tvg/sh-lib-my-bets/graphql/optionsSettled.graph";
import ActiveBetsQuery from "@tvg/sh-lib-my-bets/graphql/queries/activeBetsQuery";
import SettledBetsQuery from "@tvg/sh-lib-my-bets/graphql/queries/settledBetsQuery";
import GraphOptions from "@tvg/sh-lib-my-bets/graphql/optionsActive.graph";
import ActiveBetsSubscription from "@tvg/sh-lib-my-bets/graphql/subscriptions/activeBetsSubscription";
import WagerCancellationRulesModal from "@tvg/atomic-ui/_templates/WagerCancellationRulesModal";
import MyBetsHeaderDesktop from "@tvg/atomic-ui/_templates/MyBetsHeaderDesktop";
import MyBetsBodyDesktop from "@tvg/atomic-ui/_templates/MyBetsBodyDesktop";
import { datePreset } from "@tvg/atomic-ui/_molecule/MyBetsDesktopSettledFilters/utils";
import { DatePickerStatus } from "@tvg/atomic-ui/_molecule/MyBetsDesktopSettledFilters/types";
import TrackRulesModal from "@tvg/atomic-ui/_templates/TrackRulesModal";
import { getTrackRulesMessage } from "@tvg/sh-lib-my-bets/utils/track";
import { isMultiRaceBet } from "@tvg/sh-lib-my-bets/utils/raceDetails";
import { WagerTypeCodesEnum } from "@tvg/ts-types/Wager";
import {
getAccountNumber,
getBalance,
getResidenceState
} from "@urp/store-selectors";
import { WroWagerGroup } from "@tvg/ts-types/WroWager";
import formatRaceWagersWithAlternates from "@tvg/pp/src/utils/formatRaceWagersWithAlternates";
import RepeatBetModal from "@tvg/pp/src/components/RepeatBetModal";
import { openResponsibleGamingScreen } from "@urp/unified-modules/src/utils/responsibleGaming/openScreen";
import { UMEventsResponsibleGaming } from "@urp/unified-modules/src/utils/mediator/types";
import MyBetsRow from "./MyBetsRow";
export const buildRace = (race: RaceInfoMyBets | undefined): RaceProgram => {
if (!race) {
return {};
}
const {
bettingInterests,
status,
wagerTypes,
id,
trackName,
trackCode,
postTime,
number,
mtp,
probables,
type,
numRunners
} = race;
const wagerTypesSorted = groupByWagerType(wagerTypes).sort(
(a: RaceWagerType, b: RaceWagerType) => a.type.id - b.type.id
);
return {
bettingInterests,
status,
id,
track: { trackName, trackCode } as RaceProgramRaceTrack,
mtp,
postTime,
raceNumber: number.toString(),
probables,
type,
wagerTypes: wagerTypesSorted,
numRunners,
wagerable: !["SK", "C", "RO"].includes(status.code)
};
};
export const MyBetsDesktopComponent: FC<Props> = ({
queryBets,
races,
dispatch,
wagerProfile,
totalActiveBets = 0,
totalFutureBets = 0,
totalSettledBets,
selectedTab,
selectedSettledTab,
isLoading,
isLoadingGraph,
isLoadingBehg,
isLoadingActiveTotals,
isLoadingSettledTotals,
isLogged,
accountNumber,
activeWageredAmount = 0,
settledWageredAmount = 0,
futureWageredAmount = 0,
subscribeToMore,
subscribeToMoreGraph,
statusFilters = {
Cancelled: false,
Won: false,
Refunded: false,
Lost: false
},
statusFilterCount,
trackFilters,
trackFilterCount,
raceDate: currentRaceDate,
refetchSettled,
wagerCancellationModal,
userLocation,
cancelLimitationsByState,
betCancel,
queryTrackList,
wagerTypeFilter,
betTypeFilters,
betTypeFilterCount,
myBetsPaginationConf,
fetchMore,
customStartDate = new Date(),
customEndDate = new Date(),
isCustomTimeFrame,
redirectWithoutActiveBetsToggle
}) => {
const [hasSentGtm, setHasSentGtm] = useState(false);
const [showDatePicker, setShowDatePicker] = useState(DatePickerStatus.NONE);
const [showPresetDate, setShowPresetDate] = useState(true);
const [isMonthSelector, setIsMonthSelector] = useState(false);
const [lastPresetSelected, setLastPresetSelected] = useState({});
const [selectedMonth, setSelectedMonth] = useState(new Date());
const [isLoadingPaginationScroll, setIsLoadingPaginationScroll] =
useState(false);
const [scrollYPosition, setScrollYPosition] = useState(0);
const [isStatusFilterExpanded, setIsStatusFilterExpanded] = useState(false);
const [isBetTypeFilterExpanded, setIsBetTypeFilterExpanded] = useState(false);
const [isTrackFilterExpanded, setTrackFilterExpanded] = useState(false);
const [selectedFilters, setSelectedFilters] = useState({});
const [isRepeatBetModalOpen, setIsRepeatBetModalOpen] = useState(false);
const [selectedWager, setSelectedWager] = useState<BetBasicInfo>();
const [selectedRace, setSelectedRace] = useState<
RaceInfoMyBets | undefined
>();
const containerRef = useRef(null);
const firstRender = useRef(true);
const firstStatusFilterUpdate = useRef(true);
const firstTracksFilterUpdate = useRef(true);
const firstBetTypeFilterUpdate = useRef(true);
const previouslySelectedTab = useRef(selectedTab);
const userBalance = useSelector(getBalance);
const trackRulesModal = useSelector(getIsTrackRulesModalOpen);
const trackRulesMessages = useSelector(getMyBetsTrackRulesMessage);
const [trackRulesMessagesObject, setTrackRulesMessagesObject] = useState({
subtitle: "",
message: [] as string[]
});
const [cancelledBets, setCancelledBets] = useState<string[]>([]);
useEffect(() => {
if (trackRulesModal?.betType) {
setTrackRulesMessagesObject(
getTrackRulesMessage(
trackRulesMessages,
trackRulesModal.betType,
isMultiRaceBet(trackRulesModal.betType as WagerTypeCodesEnum),
trackRulesModal.alternates
)
);
}
}, [trackRulesModal?.betType]);
useEffect(() => {
dispatch(setCustomEndDate(datePreset.today.to));
setSelectedMonth(datePreset.today.to);
return () => {
batch(() => {
clearAllFilters(dispatch);
setShowDatePicker(DatePickerStatus.NONE);
setShowPresetDate(true);
setIsMonthSelector(false);
setLastPresetSelected({});
});
};
}, [selectedTab]);
useClearAllFilters({
dispatch,
redirectWithoutActiveBetsToggle: !!redirectWithoutActiveBetsToggle
});
useEffect(() => {
if (
typeof refetchSettled === "function" &&
(selectedSettledTab === "TODAY" || selectedTab === "ACTIVE")
)
refetchSettled();
}, [totalActiveBets]);
useEffect(() => {
if (
typeof refetchSettled === "function" &&
selectedSettledTab === "TODAY" &&
!isCustomTimeFrame
)
refetchSettled();
}, [isCustomTimeFrame]);
useEffect(() => {
dispatch(
isLoadingMyBets(
(isLoadingGraph || isLoadingBehg) && !isLoadingPaginationScroll
)
);
}, [isLoadingGraph, isLoadingBehg, isLoadingPaginationScroll]);
useEffect(() => {
setSelectedFilters({ statusFilters, trackFilters, betTypeFilters });
}, [statusFilters, trackFilters, betTypeFilters]);
useLayoutEffect(() => {
if (firstStatusFilterUpdate.current) {
firstStatusFilterUpdate.current = false;
return;
}
onMyBetsFilterHandling(
"Status",
selectedTab,
selectedSettledTab,
totalActiveBets,
totalSettledBets,
isStatusFilterExpanded
);
}, [isStatusFilterExpanded]);
useEffect(() => {
if (
!isLoadingSettledTotals &&
!isLoadingActiveTotals &&
selectedTab !== "ACTIVE" &&
!isCustomTimeFrame
) {
sendTimeframeSelectionGtmEvent(
selectedSettledTab,
selectedTab,
totalActiveBets,
totalSettledBets
);
} else if (
!isLoadingSettledTotals &&
!isLoadingActiveTotals &&
selectedTab !== "ACTIVE" &&
isCustomTimeFrame
) {
selectedNewCustomDateGtm(totalActiveBets, totalSettledBets);
} else if (
!isLoadingSettledTotals &&
!isLoadingActiveTotals &&
selectedTab !== "ACTIVE" &&
isCustomTimeFrame &&
showDatePicker !== DatePickerStatus.NONE
) {
selectedNewCustomDateGtm(totalActiveBets, totalSettledBets);
}
}, [isLoadingActiveTotals, isLoadingSettledTotals]);
useLayoutEffect(() => {
if (firstTracksFilterUpdate.current) {
firstTracksFilterUpdate.current = false;
return;
}
onMyBetsFilterHandling(
"Tracks",
selectedTab,
selectedSettledTab,
totalActiveBets,
totalSettledBets,
isTrackFilterExpanded
);
}, [isTrackFilterExpanded]);
useLayoutEffect(() => {
if (firstBetTypeFilterUpdate.current) {
firstBetTypeFilterUpdate.current = false;
return;
}
onMyBetsFilterHandling(
"Bet Type",
selectedTab,
selectedSettledTab,
totalActiveBets,
totalSettledBets,
isBetTypeFilterExpanded
);
}, [isBetTypeFilterExpanded]);
useMyBetsCountersSubscription(
ActiveBetsSubscription,
!isTvg5() && isLogged,
accountNumber,
subscribeToMore
);
useMyBetsSubscription(
isTvg5() ? WagersSubscription : WagersSubscriptionBehg,
isLogged,
subscribeToMore,
selectedTab,
selectedSettledTab,
selectedFilters,
!!isCustomTimeFrame,
accountNumber
);
useGraphRacesSubscription(
RacesSubscription,
isLogged,
subscribeToMoreGraph,
selectedSettledTab,
wagerProfile,
get(queryBets, "bets", [])
);
useMyBetsUpdateRaces({ dispatch, races });
const activeBetsWithProbables = useUpdateActiveBetsWithProbables(
{
queryBets,
races,
selectedTab
},
true
);
useEffect(() => {
const handleScroll = throttle(
() => {
setScrollYPosition(window.scrollY);
},
100,
{ trailing: true }
);
window.addEventListener("scroll", handleScroll, { passive: true });
return () => {
handleScroll.cancel();
window.removeEventListener("scroll", handleScroll);
};
}, []);
usePagination(
fetchMore,
containerRef,
typeof window !== "undefined" ? document.body : null,
scrollYPosition,
isLoadingPaginationScroll,
setIsLoadingPaginationScroll,
selectedTab,
selectedSettledTab,
get(myBetsPaginationConf, "intersectionWagerPercentage", 0.9),
selectedFilters,
formatDateToMMDDYYYY(customStartDate),
formatDateToMMDDYYYY(customEndDate)
);
useEffect(() => {
if (
onMyBetsStartupGtm(
true,
totalActiveBets,
totalSettledBets,
isLoadingActiveTotals || isLoadingSettledTotals,
hasSentGtm,
setHasSentGtm
)
) {
onTabClickGtm({
selectedTab,
selectedSettledTab,
activeBetsCount: totalActiveBets,
settledBetsCount: totalSettledBets,
futureBetsCount: totalFutureBets,
previousSelectedTab: "None"
});
}
}, [
totalActiveBets,
totalSettledBets,
isLoadingActiveTotals,
isLoadingSettledTotals
]);
useEffect(() => {
if (isSuccessBetCancel(get(betCancel, "result") as BetCancelResult)) {
ToastManager.show({
message: "Bet Cancelled",
variant: "success",
hasDismissButton: true,
actionLink: (
<ToastMessageLink
variant="success"
onPress={() => {
dispatch(openWagerCancellationRulesModal({ hasBack: false }));
handleCancelBetNotificationGtm(
selectedTab,
selectedSettledTab,
totalActiveBets,
totalSettledBets
);
}}
qaLabel="rules-button-notification"
>
See Rules
</ToastMessageLink>
)
});
if (betCancel.wager?.id) {
setCancelledBets([...cancelledBets, betCancel.wager.id]);
}
}
}, [betCancel]);
const setDateRange = useCallback(
(dateRange) => {
if (dateRange.from !== customStartDate) {
clearDrowpdownFilters(dispatch);
}
let showDateType = DatePickerStatus.NONE;
if (!customStartDate && !!dateRange.from) {
showDateType = DatePickerStatus.END_DATE;
} else if (!dateRange.from) {
showDateType = DatePickerStatus.START_DATE;
}
setShowDatePicker(showDateType);
setIsMonthSelector(false);
batch(() => {
dispatch(setCustomStartDate(dateRange.from));
dispatch(setCustomEndDate(dateRange.to));
});
},
[customStartDate, showDatePicker]
);
const cancelRulesMessages = useMemo(
() =>
safeJSONParse({
defaultValue: {},
jsonToParse: `${cancelLimitationsByState}`
}),
[cancelLimitationsByState]
);
const togglePreset = useCallback(
(showPreset) => {
if (showPreset) {
setDateRange(lastPresetSelected);
} else {
setShowDatePicker(DatePickerStatus.START_DATE);
setLastPresetSelected({
from: customStartDate,
to: customEndDate
});
setDateRange({
to: datePreset.today.to
});
}
updateIsCustomTimeFrame(showPreset);
setShowPresetDate(showPreset);
},
[lastPresetSelected, showPresetDate, customStartDate, customEndDate]
);
const mergedBetTypeOptions = getQueryDynamicOptions(
wagerTypeFilter || [],
betTypeFilters || []
);
const mergedTrackOptions = getQueryDynamicOptions(
queryTrackList || [],
trackFilters || []
);
const { keys: trackFilterKeys, values: trackFilterValues } =
reduceDynamicFilters(mergedTrackOptions);
const { keys: betTypeFilterKeys, values: betTypeFilterValues } =
reduceDynamicFilters(mergedBetTypeOptions);
const bets = useMemo(() => {
const filtered = get(activeBetsWithProbables, "bets", []).filter(
(bet: WroWagerGroup) =>
shouldRenderWager(
selectedTab,
currentRaceDate,
get(bet, "wagers[0].raceDate", ""),
mergedTrackOptions
.filter((track: typeof MyBetsDynamicFilter) => track.isActive)
.map((track: typeof MyBetsDynamicFilter) => track.name),
get(bet, "wagers[0].trackName", "")
)
);
if (selectedTab !== "ACTIVE") {
return filtered.sort(
(a: WroWagerGroup, b: WroWagerGroup) =>
new Date(get(b, "wagers[0].transactionDate")).getTime() -
new Date(get(a, "wagers[0].transactionDate")).getTime()
);
}
return filtered.filter((bet: WroWagerGroup) =>
bet.wagers[0].id ? !cancelledBets.includes(bet.wagers[0].id) : true
);
}, [
selectedTab,
activeBetsWithProbables,
currentRaceDate,
trackFilterCount,
cancelledBets
]);
useEffect(() => {
if (
selectedTab === "SETTLED" &&
!isLoadingSettledTotals &&
previouslySelectedTab.current === "ACTIVE"
) {
onTabClickGtm({
selectedTab: "SETTLED",
selectedSettledTab: "TODAY",
activeBetsCount: totalActiveBets,
settledBetsCount: totalSettledBets,
previousSelectedTab: previouslySelectedTab.current
});
previouslySelectedTab.current = selectedTab;
}
if (selectedTab === "ACTIVE" && !isLoadingActiveTotals) {
previouslySelectedTab.current = selectedTab;
}
}, [selectedTab, isLoadingSettledTotals]);
const counters = (() => {
switch (selectedTab) {
case "SETTLED":
return { counter: totalSettledBets, amount: settledWageredAmount };
case "FUTURES":
return { counter: totalFutureBets, amount: futureWageredAmount };
case "ACTIVE":
default:
return { counter: totalActiveBets, amount: activeWageredAmount };
}
})();
const hasBets = bets?.length === 0;
const hasFilters =
betTypeFilterCount !== 0 ||
statusFilterCount !== 0 ||
trackFilterCount !== 0;
const filtersOffsetBottom = 210;
useEffect(() => {
shouldRedirectToSettled(
isLoadingActiveTotals || isLoadingBehg,
totalActiveBets,
totalFutureBets,
firstRender,
dispatch,
selectedTab,
redirectWithoutActiveBetsToggle
);
}, [
isLoadingActiveTotals,
isLoadingBehg,
totalActiveBets,
totalFutureBets,
selectedTab,
redirectWithoutActiveBetsToggle,
firstRender
]);
const handleSelectedRace = (
myBetsSelectedRace: RaceInfoMyBets | undefined
) => {
setSelectedRace(myBetsSelectedRace);
};
const handleSelectedWager = (wager: BetBasicInfo) => {
setSelectedWager(wager);
};
const buildRaces = () => {
let availableRaces: RaceProgram[] = [];
if (races && selectedRace !== undefined) {
availableRaces = Object.values(races).map(buildRace);
}
return availableRaces;
};
const currentRace =
races &&
races.find(
(race) =>
race.id === `${selectedRace?.trackCode}-${selectedRace?.number}` &&
race.raceDate === selectedRace?.raceDate
);
const handleResponsibleGamingError = () => {
setIsRepeatBetModalOpen(false);
openResponsibleGamingScreen(UMEventsResponsibleGaming.ResponsiblePlay);
};
return (
<>
{!isTvg5() && (
<ToastManager
qaLabel="toast-manager"
variant="informational"
message=""
ref={(ref) => ToastManager.setRef(ref)}
/>
)}
<MyBetsHeaderDesktop
title="My Bets"
selectedTab={selectedTab}
selectNewTimeFrame={selectNewTimeFrame(
dispatch,
selectedSettledTab,
selectedTab
)}
tabs={buildTabs(
totalActiveBets,
totalFutureBets,
selectedTab,
dispatch
)}
isStatusFilterExpanded={isStatusFilterExpanded}
setStatusExpanded={setIsStatusFilterExpanded}
isStatusFilterDisabled={hasBets}
isBetTypesFilterDisabled={hasBets}
setStatusFilter={selectNewStatusFilters(
statusFilters,
dispatch,
selectedSettledTab,
totalActiveBets,
totalSettledBets,
setIsStatusFilterExpanded
)}
currentStatusFilters={statusFilters}
statusFilterCount={statusFilterCount}
trackList={trackFilterKeys}
trackListToggles={trackFilterValues}
betTypeList={betTypeFilterKeys}
betTypeListToggles={betTypeFilterValues}
betTypeFilterCount={betTypeFilterCount}
setBetTypeListFilter={setDynamicFilters(
dispatch,
"BetType",
mergedBetTypeOptions,
selectedSettledTab,
totalActiveBets,
totalSettledBets,
setIsBetTypeFilterExpanded
)}
isBetTypeFilterExpanded={isBetTypeFilterExpanded}
setBetTypeFilterExpanded={setIsBetTypeFilterExpanded}
setTrackListFilter={setDynamicFilters(
dispatch,
"Tracks",
mergedTrackOptions,
selectedSettledTab,
totalActiveBets,
totalSettledBets,
setTrackFilterExpanded
)}
isTrackFilterExpanded={isTrackFilterExpanded}
setTrackFilterExpanded={setTrackFilterExpanded}
isTracksFilterDisabled={hasBets}
trackFilterCount={trackFilterCount}
counters={counters}
isClearAllDisabled={
betTypeFilterCount === 0 &&
trackFilterCount === 0 &&
statusFilterCount === 0
}
clearAllFilters={resetAllFilters(
dispatch,
selectedSettledTab,
totalActiveBets,
totalSettledBets
)}
toggleCustom={updateIsCustomTimeFrame(dispatch)}
setShowDatePicker={(showDate: DatePickerStatus) => {
setIsMonthSelector(false);
setShowDatePicker(showDate);
}}
showDatePicker={showDatePicker}
selectedMonth={selectedMonth}
setSelectedMonth={setSelectedMonth}
onDateChange={setDateRange}
dateRange={{
from: customStartDate ? new Date(customStartDate) : undefined,
to: new Date(customEndDate)
}}
showPresetDate={showPresetDate}
onPresetDateChange={togglePreset}
isMonthSelector={isMonthSelector}
setIsMonthSelector={setIsMonthSelector}
filtersOffsetBottom={filtersOffsetBottom}
/>
<MyBetsBodyDesktop
bets={bets}
isLoading={isLoading}
emptyTitle={getEmptyStateTitle(
selectedTab,
selectedSettledTab,
!showPresetDate,
new Date(customStartDate),
new Date(customEndDate),
hasFilters
)}
emptyMessage={getEmptyStateMessage(selectedTab)}
isFetchingPagination={isLoadingPaginationScroll}
selectedTab={selectedTab}
scrollYPosition={scrollYPosition}
containerRef={containerRef}
>
{selectedWager && selectedRace && buildRaces && (
<RepeatBetModal
userBalance={userBalance}
race={buildRace(currentRace)}
races={buildRaces()}
raceWager={formatRaceWagersWithAlternates(selectedWager!)}
isRepeatBetModalOpen={isRepeatBetModalOpen}
setRepeatBetModalOpen={setIsRepeatBetModalOpen}
onResponsibleGamingError={handleResponsibleGamingError}
/>
)}
{bets.map((bet: WroWagerGroup, index: number) => (
<MyBetsRow
key={`myBetsRow-${get(bet, "wagers[0].id")}`}
bet={bet}
races={races || []}
currentRaceDate={currentRaceDate}
qaLabel={`mybets-wager-row-${index}`}
activeBetsCounter={totalActiveBets}
settledBetsCounter={totalSettledBets}
handleSelectedRace={handleSelectedRace}
handleSelectedWager={handleSelectedWager}
setIsRepeatBetModalOpen={setIsRepeatBetModalOpen}
/>
))}
</MyBetsBodyDesktop>
<TrackRulesModal
isOpen={trackRulesModal.isOpen}
onClose={() => {
dispatch(closeTrackRulesModal());
}}
subtitle={get(trackRulesMessagesObject, "subtitle")}
messages={get(trackRulesMessagesObject, "message")}
layerOffset={100}
/>
<WagerCancellationRulesModal
isOpen={wagerCancellationModal.isOpen}
hasBack={wagerCancellationModal.hasBack}
onClose={() => {
dispatch(closeWagerCancellationRulesModal());
}}
userLocation={userLocation}
messages={cancelRulesMessages}
onBack={() => {
dispatch(closeWagerCancellationRulesModal());
setTimeout(() => {
// @ts-ignore
dispatch(openBetCancelModal());
mediator.base.dispatch({ type: "OPEN_BET_CANCEL_MODAL" });
}, 200);
}}
/>
</>
);
};
// @ts-ignore
export default connect(
(store: Store) => ({
accountNumber: getAccountNumber(store),
isLogged: get(store, "userData.logged"),
wagerProfile: get(store, "userData.user.profile", ""),
selectedTab: getSelectedTab(store),
selectedSettledTab: getSelectedSettledTab(store),
deletedBets: getDeletedBets(store),
isLoading: getIsLoadingMyBets(store),
statusFilters: getStatusFilters(store),
statusFilterCount: getStatusFiltersCount(store),
trackFilters: getTrackFilters(store),
trackFilterCount: getTrackFiltersCount(store),
betTypeFilters: getBetTypeFilters(store),
betTypeFilterCount: getBetTypeFiltersCount(store),
wagerCancellationModal: getIsWagerCancellationRulesModalOpen(store),
userLocation: getResidenceState(store),
cancelLimitationsByState: getBetCancelLimitationsByState(store),
betCancel: getBetCancel(store),
myBetsPaginationConf: getMyBetsPaginationConf(store),
customStartDate: getCustomStartDate(store),
customEndDate: getCustomEndDate(store),
isCustomTimeFrame: getIsCustomTimeFrame(store),
redirectWithoutActiveBetsToggle: getRedirectWithoutActiveBetsToggle(store)
}),
// @ts-ignore
(dispatch: Dispatch<any>) => ({ dispatch })
)(
// @ts-ignore
compose(
// @ts-ignore
graphql(ActiveBetsQuery, GraphOptions),
// @ts-ignore
graphql(SettledBetsQuery, SettledGraphOptions),
// @ts-ignore
graphql(isTvg5() ? GroupWagersQuery : GroupWagersQueryBehg, BehgOptions),
// @ts-ignore
graphql(
isTvg5() ? AllWagerTypesQuery : AllWagerTypesQueryTvg4,
ApolloOptions
)
)(MyBetsDesktopComponent)
);
webpack://frontend-mybets/../../packages/sh-lib-my-bets/hooks/useClearAllFilters.ts
import { useEffect } from "react";
import { batch } from "react-redux";
import { Dispatch } from "redux";
import { setSelectedTabMyBetsStandalone } from "../redux/actions";
import { clearAllFilters } from "../utils/filters";
import { ActiveTabEnum } from "../utils/types";
const useTabReset = (props: {
dispatch: Dispatch;
redirectWithoutActiveBetsToggle: boolean;
}) => {
useEffect(() => {
// TODO: remove turned off toggle logic
if (!props.redirectWithoutActiveBetsToggle) {
props.dispatch(setSelectedTabMyBetsStandalone(ActiveTabEnum.ACTIVE));
}
return () => {
batch(() => {
clearAllFilters(props.dispatch);
});
};
}, []);
};
export default useTabReset;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/hooks/useMyBetsCountersSubscription.ts
import { useEffect } from "react";
import { UnaryFn } from "@tvg/ts-types/Functional";
function useMyBetsCountersSubscription(
ActiveBetsSubscription: unknown,
isLogged: boolean,
accountNumber: string,
subscribeToMore: UnaryFn<unknown, void>
) {
useEffect(() => {
let unsubscribe: Function | void | null;
if (
isLogged &&
accountNumber !== undefined &&
accountNumber !== "" &&
typeof subscribeToMore === "function"
) {
unsubscribe = subscribeToMore({
document: ActiveBetsSubscription,
variables: {
accountId: parseInt(accountNumber, 10),
status: ["PENDING"]
}
});
}
// On component will unmount, unsubscribes to websocket
return () => {
if (typeof unsubscribe === "function") {
unsubscribe();
unsubscribe = null;
}
};
}, [subscribeToMore, isLogged, accountNumber]);
return null;
}
export default useMyBetsCountersSubscription;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/hooks/useMyBetsUpdateRaces.ts
import { useEffect } from "react";
import { Dispatch } from "redux";
import { RaceInfoMyBets } from "@tvg/ts-types/Race";
import { updateRacesMyBets } from "../redux/actions";
type Props = {
dispatch: Dispatch;
races: RaceInfoMyBets[];
};
export const useMyBetsUpdateRaces = (props: Props) => {
const { dispatch, races } = props;
useEffect(() => {
if (races && races.length > 0) {
dispatch(updateRacesMyBets(races));
}
}, [JSON.stringify(races)]);
};
export default useMyBetsUpdateRaces;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/hooks/useUpdateActiveBetsWithProbables.ts
import { useEffect, useState } from "react";
import { get } from "lodash";
import { RaceInfoMyBets } from "@tvg/ts-types/Race";
import { Selections, SelectionRunner } from "@tvg/ts-types/Selections";
import { getDisableSpecialWagers } from "@tvg/pp/src/store/selectors";
import { WagerType } from "@tvg/ts-types/Wager";
import { WroWager, WroWagerGroup } from "@tvg/ts-types/WroWager";
import { useSelector } from "react-redux";
import { ActiveTabEnum, ActiveBetsInfoType } from "../utils/types";
import {
doesRaceWagerTypeHasProbables,
getCurrentProbableValue
} from "../utils/potentialReturn";
export type Props = {
queryBets: ActiveBetsInfoType;
races: RaceInfoMyBets[];
selectedTab: ActiveTabEnum;
};
type ChangedBets = Array<{ wagers: WroWager[]; value: string }>;
function useUpdateActiveBetsWithProbables(
{ queryBets, races = [], selectedTab }: Props,
splitWagers: boolean = false
) {
const [activeBetsWithProbables, setActiveBetsWithProbables] =
useState(queryBets);
const disableSpecialWagers = useSelector(getDisableSpecialWagers);
useEffect(() => {
if (queryBets) {
let changedBets: ChangedBets = get(queryBets, "bets", []).map((bet) => {
const raceId = bet.value.split("|");
const currentRace = races.find(
(race) => race.id === `${raceId[1]}-${raceId[2]}`
);
const wagers = get(bet, "wagers", []).map((wager: WroWager) => {
const firstTrack = currentRace?.track;
const specialCardTypes = firstTrack?.specialCardTypes;
let isSpecialWager = false;
isSpecialWager = (specialCardTypes || [])?.some(
(card) => card.specialCardTypeAbbreviation === "NCP"
);
if (
isSpecialWager &&
specialCardTypes?.some(
(card) => card.specialCardTypeAbbreviation === "FUT"
)
) {
isSpecialWager = false;
}
if (disableSpecialWagers) isSpecialWager = false;
let probableValue = "0";
const hasProbables = doesRaceWagerTypeHasProbables(
get(currentRace, "probables", []),
get(wager, "wagerType.id", 0)
);
if (hasProbables) {
const betSelections = get(wager, "selections.selection", []).map(
(selection: Selections) =>
selection.runners.map((runner: SelectionRunner) =>
runner.number.toString()
)
);
probableValue =
getCurrentProbableValue(
get(currentRace, "probables", []),
get(wager, "wagerType", {} as WagerType),
get(wager, "wagerAmount", 0),
betSelections
) || "";
}
return {
...wager,
probable: probableValue,
isSpecialWager
};
});
return {
wagers,
value: bet.value
};
});
if (splitWagers) {
changedBets = changedBets.reduce<ChangedBets>((prev, bet) => {
const split = bet.wagers.map((wager: WroWager) => ({
value: bet.value,
wagers: [wager]
}));
return [...prev, ...split];
}, []);
}
setActiveBetsWithProbables({
...queryBets,
bets: changedBets as WroWagerGroup[]
});
}
}, [selectedTab, JSON.stringify(queryBets), JSON.stringify(races)]);
return activeBetsWithProbables;
}
export default useUpdateActiveBetsWithProbables;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/hooks/usePagination.ts
import { useEffect, useMemo, useState, MutableRefObject } from "react";
import { BinaryFn, UnaryFn } from "@tvg/ts-types/Functional";
import tvgConf from "@tvg/conf";
import { ActiveTabEnum, SettledTabEnum, SelectedFilters } from "../utils/types";
export const usePagination = (
fetchMore: BinaryFn<UnaryFn<boolean, void>, number, void>,
containerRef: MutableRefObject<HTMLDivElement | null>,
scrollableRef: HTMLElement | null,
scrollYPosition: number,
isLoadingPaginationScroll: boolean,
setIsLoadingPaginationScroll: UnaryFn<boolean, void>,
selectedTab: ActiveTabEnum,
selectedSettledTab: SettledTabEnum,
percentage: number,
// Optional desktop properties
customFilters?: SelectedFilters | null,
customStartDate?: string | null,
customEndDate?: string
) => {
const isDesktop = tvgConf().device === "desktop";
const hasPagination = useMemo(
() =>
selectedTab === "SETTLED" &&
(selectedSettledTab !== "TODAY" || !!customStartDate),
[selectedTab, selectedSettledTab, customStartDate]
);
const [page, setPage] = useState(1);
const [hasReachedLastPage, setHasReachedLastPage] = useState(false);
// Calculate bottom remaining area and fetch next page
useEffect(() => {
const containerSize =
containerRef && containerRef.current
? parseInt(`${containerRef.current.offsetHeight}`, 10)
: 0;
const scrollableAreaSize = scrollableRef
? parseInt(`${scrollableRef.offsetHeight}`, 10)
: 0;
if (containerSize > 0 && scrollableAreaSize > 0) {
const remainingArea =
containerSize - (scrollableAreaSize + scrollYPosition);
const triggerArea = Math.round(
containerSize - containerSize * percentage
);
const shouldFetchNextPage =
hasPagination &&
!isLoadingPaginationScroll &&
!hasReachedLastPage &&
remainingArea > 0 &&
triggerArea > 0 &&
remainingArea <= triggerArea;
if (shouldFetchNextPage) {
setIsLoadingPaginationScroll(true);
fetchMore((isDoneLoadingMore) => {
// Callback after fetching the new page
setPage((prevState) => prevState + 1);
setHasReachedLastPage(isDoneLoadingMore);
setIsLoadingPaginationScroll(false);
}, page);
}
}
}, [
page,
hasPagination,
scrollYPosition,
hasReachedLastPage,
isLoadingPaginationScroll
]);
// Reset whole state when changing between settled tabs and custom filters
useEffect(() => {
setTimeout(() => {
setPage(1);
setHasReachedLastPage(false);
setIsLoadingPaginationScroll(false);
if (isDesktop) {
window.scrollTo({ top: 0 });
} else if (scrollableRef) {
scrollableRef.scrollTo({
top: 0
});
}
}, 0);
}, [selectedSettledTab, customFilters, customStartDate, customEndDate]);
};
export default usePagination;
webpack://frontend-mybets/../../packages/tvg-comp-program-page/src/utils/formatRaceWagersWithAlternates.ts
import { BetBasicInfo } from "@tvg/ts-types/Bet";
import { Selections } from "@tvg/ts-types/Selections";
const formatRaceWagersWithAlternates = <
T extends BetBasicInfo | BetBasicInfo[]
>(
wagers: T
): T => {
const wagersArray = Array.isArray(wagers) ? wagers : [wagers];
const formattedWagers = wagersArray.map((wager) => {
if (!wager.selections?.selection) return wager;
return {
...wager,
selections: {
...wager.selections,
selection: wager.selections.selection.map((selection: Selections) => {
if (!selection.bettingInterests) return selection;
const updatedBettingInterests = [...selection.bettingInterests];
const updatedRunners = [...(selection.runners || [])];
if (
selection.alternateBettingInterest &&
selection.alternateBettingInterest.biNumber !== 0 &&
selection.alternateBettingInterest.runners?.length
) {
updatedBettingInterests.push({
...selection.alternateBettingInterest,
isAlternate: true
});
if (selection.alternateBettingInterest.biNumber) {
updatedRunners.push({
// @ts-ignore
number: `${selection.alternateBettingInterest.biNumber}B`
});
}
}
return {
...selection,
bettingInterests: updatedBettingInterests,
runners: updatedRunners
};
})
}
};
});
return (Array.isArray(wagers) ? formattedWagers : formattedWagers[0]) as T;
};
export default formatRaceWagersWithAlternates;
webpack://frontend-mybets/../../packages/tvg-lib-poller/src/index.js
export default class Poller {
pollerInstance;
constructor() {
this.pollerInstance = null;
}
refresh(callBack, interval) {
// Make initial request
if (typeof callBack === "function") {
callBack();
}
// set poller
this.pollerInstance = setInterval(callBack, interval);
}
stop() {
if (this.pollerInstance) {
clearInterval(this.pollerInstance);
this.pollerInstance = null;
}
return this.pollerInstance;
}
start(callBack, interval) {
if (this.pollerInstance) {
clearInterval(this.pollerInstance);
}
this.refresh(callBack, interval);
}
isRunning() {
return !!this.pollerInstance;
}
}
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/redux/actions/index.ts
import {
ResetStoryblokPromosAction,
SetPartialStoryblokPromosAction,
SetStoryblokPromosAction,
SetPromoOnboardingPollerTimeAction
} from "./types";
import { PromoOnboardingFormatted } from "../../types/promoOnboarding";
export const setStoryblokPromos = (
promos: PromoOnboardingFormatted
): SetStoryblokPromosAction => ({
type: "SET_STORYBLOK_PROMOS",
payload: {
...promos
}
});
export const setPartialStoryblokPromos = (
promos: PromoOnboardingFormatted
): SetPartialStoryblokPromosAction => ({
type: "SET_PARTIAL_STORYBLOK_PROMOS",
payload: {
...promos
}
});
export const resetStoryblokPromos = (): ResetStoryblokPromosAction => ({
type: "RESET_STORYBLOK_PROMOS"
});
export const setPromoOnboardingPollerTime = (
pollerTime: number
): SetPromoOnboardingPollerTimeAction => ({
type: "SET_PROMO_ONBOARDING_POLLER_TIME",
payload: pollerTime
});
webpack://frontend-mybets/../../packages/tvg-lib-api/pro/index.ts
import tvgConf from "@tvg/conf";
import { PromosWidgetPROResponse } from "@tvg/ts-types/Promos";
import getProtocol from "../protocolSetter";
import requester from "../requester";
const proService: string = "service.pro";
const fetchTopPromotions = (accountId?: string) =>
requester()({
method: "GET",
url: accountId
? `${getProtocol()}${tvgConf().config(
proService
)}/users/${accountId}/top-promotions`
: `${getProtocol()}${tvgConf().config(proService)}/top-promotions`,
headers: {
"x-tvg-context": tvgConf().context()
},
withCredentials: true
}) as unknown as Promise<PromosWidgetPROResponse>;
const fetchUserPromoOptin = (accountId: string) =>
requester()({
method: "get",
url: `${getProtocol()}${tvgConf().config(
proService
)}/users/${accountId}/promotions/opt-in`,
headers: {
"x-tvg-context": tvgConf().context(),
"Content-Type": "application/json"
},
withCredentials: true
});
const postUserPromoOptin = (accountId: string, promoId: number) =>
requester()({
method: "post",
url: `${getProtocol()}${tvgConf().config(
proService
)}/users/${accountId}/promotions/${promoId}/opt-in`,
headers: {
"x-tvg-context": tvgConf().context(),
"Content-Type": "application/json"
},
data: {
source: "USER"
},
withCredentials: true
});
const fetchUserPromoStatus = (accountId: string, promoId: number) =>
requester()({
method: "get",
url: `${getProtocol()}${tvgConf().config(
proService
)}/users/${accountId}/promotions/${promoId}`,
headers: {
"x-tvg-context": tvgConf().context()
},
withCredentials: true
});
const fetchAllEligiblePromos = (
accountId: string,
params: {
promoType?: string;
overrideContext?: boolean;
} = {}
) =>
requester()({
method: "get",
url: `${getProtocol()}${tvgConf().config(
proService
)}/users/${accountId}/promotions`,
headers: {
"x-tvg-context": tvgConf().context()
},
withCredentials: true,
params
});
const fetchAllRaces = (promoId: number) =>
requester()({
method: "get",
url: `${getProtocol()}${tvgConf().config(
proService
)}/promotions/${promoId}/races`,
headers: {
"x-tvg-context": tvgConf().context()
},
withCredentials: true
});
const fetchUserLeaderBoardStandings = (
accountId: string,
promoId: number,
nearbyUsers: number = 2
) =>
requester()({
method: "get",
url: `${getProtocol()}${tvgConf().config(
proService
)}/leaderboards/${promoId}/${accountId}/nearby-users?nearbyUsers=${nearbyUsers}`,
headers: {
"x-tvg-context": tvgConf().context()
},
withCredentials: true
});
const fetchAllLeaderBoardStandings = (promoId: number, limit: number) =>
requester()({
method: "get",
url: `${getProtocol()}${tvgConf().config(
proService
)}/leaderboards/${promoId}/top-users?limit=${limit}`,
headers: {
"x-tvg-context": tvgConf().context()
}
});
const fetchLeaderBoardStandingsByPagination = (
promoId: number,
round: number,
page: number,
pageSize: number
) =>
requester()({
method: "get",
url: `${getProtocol()}${tvgConf().config(
proService
)}/leaderboards/${promoId}/${round}?page=${page}&pageSize=${pageSize}`,
headers: {
"x-tvg-context": tvgConf().context()
}
});
const fetchReferralStatus = (accountId: string) =>
requester()({
method: "get",
url: `${getProtocol()}${tvgConf().config(
proService
)}/users/${accountId}/referral/status`,
headers: {
"x-tvg-context": tvgConf().context()
},
withCredentials: true
});
const postReferralEmails = (
accountId: string,
referees: string[],
referredBy: string
) =>
requester()({
method: "post",
url: `${getProtocol()}${tvgConf().config(
proService
)}/users/${accountId}/referral`,
headers: {
"x-tvg-context": tvgConf().context(),
"Content-Type": "application/json"
},
data: {
referees,
referredBy
},
withCredentials: true
});
const fetchUserPromoSteps = (accountId: string, promoId: number) =>
requester()({
method: "get",
url: `${getProtocol()}${tvgConf().config(
proService
)}/users/${accountId}/promotions/${promoId}/steps`,
headers: {
"x-tvg-context": tvgConf().context(),
"Content-Type": "application/json"
},
withCredentials: true
});
const PRO_SERVICE = {
fetchTopPromotions,
postUserPromoOptin,
fetchUserPromoOptin,
fetchUserPromoStatus,
fetchAllEligiblePromos,
fetchAllRaces,
fetchUserLeaderBoardStandings,
fetchAllLeaderBoardStandings,
fetchLeaderBoardStandingsByPagination,
fetchReferralStatus,
postReferralEmails,
fetchUserPromoSteps
};
export default PRO_SERVICE;
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/utils/fetchPromoAcquisition.ts
import pro from "@tvg/api/pro";
import { attempt, isError } from "lodash";
import { PromoAcquisition } from "../types/promos";
export const fetchPromoAcquisition = async (
accountId: string,
promoId: number
): Promise<PromoAcquisition | null> => {
const promosAcquisition = await attempt(async () => {
const responseUserPromoSteps = await pro.fetchUserPromoSteps(
accountId,
promoId
);
return responseUserPromoSteps.data as PromoAcquisition;
});
return !isError(promosAcquisition) ? promosAcquisition : null;
};
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/helpers/formatSteps.ts
import { omit } from "lodash";
import {
PromoMappedSteps,
PromoOnboardingStep,
PromoStepType
} from "../types/promoSteps";
export const formatSteps = (
steps: Array<PromoOnboardingStep>
): PromoMappedSteps =>
steps.reduce(
(mappedSteps, promoStep) => ({
...mappedSteps,
[promoStep.stepType || PromoStepType.UNKNOWN]: omit(promoStep, [
"stepType"
])
}),
{} as PromoMappedSteps
);
export default formatSteps;
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/helpers/formatCompletedSteps.ts
import { PromoMappedSteps } from "../types/promoSteps";
import { checkOnboardingPromoAvailable } from "../utils/checkOnboardingPromoAvailable";
export const formatCompletedSteps = (
currentStep: number,
numberSteps: number,
steps: PromoMappedSteps
) => (!checkOnboardingPromoAvailable(steps) ? numberSteps + 1 : currentStep);
export default formatCompletedSteps;
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/utils/getCurrentStep.ts
import { findLast, get } from "lodash";
import {
PromoMappedSteps,
PromoOnboardingStep,
PromoStepType,
PromoStepWagerStatus
} from "../types/promoSteps";
import { checkOnboardingPromoAvailable } from "./checkOnboardingPromoAvailable";
const WAGER_FINISHED_STATUS = [
PromoStepWagerStatus.WIN,
PromoStepWagerStatus.LOST
];
const checkSpecialStepConditions = (formattedSteps: PromoMappedSteps) => {
const wagerStep = get(formattedSteps, PromoStepType.WAGER);
const wagerStatus = get(formattedSteps, `${PromoStepType.WAGER}.wagerStatus`);
const depositDate = get(
formattedSteps,
`${PromoStepType.DEPOSIT}.depositDate`
);
if (!checkOnboardingPromoAvailable(formattedSteps)) {
return true;
}
return wagerStep
? WAGER_FINISHED_STATUS.includes(wagerStatus)
: !!depositDate;
};
export const getCurrentStepType = (
currentStep: number,
steps: Array<PromoOnboardingStep> = [],
formattedSteps: PromoMappedSteps = {}
): PromoStepType => {
let currentStepType = checkSpecialStepConditions(formattedSteps)
? PromoStepType.PAYOUT
: get(steps, `[${currentStep}].stepType`, PromoStepType.UNKNOWN);
// Need to get the last step active when don't recognize the Step
if (!currentStepType || currentStepType === PromoStepType.UNKNOWN) {
const lastStep = findLast(steps, (step) => !!step);
currentStepType = get(lastStep, "stepType", PromoStepType.UNKNOWN);
}
return currentStepType;
};
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/helpers/formatPromoStruct.ts
import { PromoAcquisition } from "../types/promos";
import { PromoOnboardingFormatted } from "../types/promoOnboarding";
import formatSteps from "./formatSteps";
import formatCompletedSteps from "./formatCompletedSteps";
import { getCurrentStepType } from "../utils/getCurrentStep";
export const formatPromoStruct = (
promoAcquisition: PromoAcquisition,
previousRootId?: number
): PromoOnboardingFormatted => {
const {
promotionId,
promoName,
currentStep,
isPromoExpired,
remainingDays,
rebateLimit,
numberSteps,
steps
} = promoAcquisition;
const formattedSteps = formatSteps(steps);
const completedSteps = formatCompletedSteps(
currentStep,
numberSteps,
formattedSteps
);
const currentStepType = getCurrentStepType(
currentStep,
steps,
formattedSteps
);
return {
rootId: previousRootId,
promotionId,
promoName,
completedSteps,
currentStepType,
isPromoExpired,
numberSteps,
remainingDays,
rebateLimit,
steps: formattedSteps
};
};
export default formatPromoStruct;
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/helpers/formatStoryblokComponents.ts
import {
StoryBlokComponentsFormatted,
StoryblokStep
} from "../types/storyblok";
import formatStoryblokMessages from "./formatStoryblokMessages";
export const formatStoryblokComponents = (
storyblokSteps: Array<StoryblokStep>,
addSteps: Array<string>
): StoryBlokComponentsFormatted =>
storyblokSteps.reduce((mappedStep, step) => {
const { step_config, messages } = step;
const {
type,
description,
description_win,
description_lost,
description_processing
} = step_config;
if (!addSteps.includes(type)) {
return mappedStep;
}
const messagesToRender = formatStoryblokMessages(messages);
return {
...mappedStep,
steps: {
...mappedStep.steps,
[type]: {
places: messagesToRender,
description: {
default: description,
loss: description_lost,
win: description_win,
processing: description_processing
}
}
}
};
}, {} as StoryBlokComponentsFormatted);
export default formatStoryblokComponents;
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/helpers/formatStoryblokMessages.ts
import { get } from "lodash";
import {
StoryblokMessages,
StoryblokMessagesFormatted
} from "../types/storyblok";
import {
StoryblokComponentName,
StoryblokComponentProps,
StoryblokPlaceName
} from "../types/promoOnboardingComponents";
import { formatStoryblokProps } from "./formatStoryblokProps";
export const formatStoryblokMessages = (
messages: Array<StoryblokMessages>
): StoryblokMessagesFormatted =>
messages.reduce((mappingRender, message) => {
const componentProps: StoryblokComponentProps = get(
message,
"promo_component[0]"
);
const componentName: StoryblokComponentName = get(
componentProps,
"component",
StoryblokComponentName.UNKNOWN
);
const places: Array<StoryblokPlaceName> = get(
message,
"render_place[0].places",
[]
);
const props = formatStoryblokProps(componentProps);
const placeToRender = places.reduce(
(mappingPlaces, place) => ({
...mappingPlaces,
[place]: {
component: componentName,
props
}
}),
{}
);
return {
...mappingRender,
...placeToRender
};
}, {} as StoryblokMessagesFormatted);
export default formatStoryblokMessages;
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/utils/getPromoOnboarding.ts
import { get, merge } from "lodash";
import { StoryblokDraft, StoryblokStep } from "../types/storyblok";
import { fetchStoryblok } from "./fetchStoryblok";
import formatPromoStruct from "../helpers/formatPromoStruct";
import formatStoryblokComponents from "../helpers/formatStoryblokComponents";
import { PromoAcquisition } from "../types/promos";
import { PromoOnboarding } from "../types/promoOnboarding";
import { PromoStepType } from "../types/promoSteps";
export const getPromoOnboarding = async (
promosAcquisition: PromoAcquisition,
previousRootId?: number,
draft?: StoryblokDraft
): Promise<PromoOnboarding> => {
const { promotionId } = promosAcquisition;
const components = formatPromoStruct(promosAcquisition, previousRootId);
const storyblokResponse = await fetchStoryblok(promotionId, draft);
const storyblokSteps: Array<StoryblokStep> = get(
storyblokResponse,
"data.story.content.steps",
[]
);
const storyblokComponents = formatStoryblokComponents(storyblokSteps, [
...Object.keys(components.steps),
PromoStepType.PAYOUT
]);
return merge(components, storyblokComponents);
};
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/utils/setUserPromosOnboarding.ts
import { Dispatch } from "redux";
import { attempt, throttle } from "lodash";
import { addDays, isAfter } from "date-fns";
import { resetStoryblokPromos, setStoryblokPromos } from "../redux/actions";
import { Actions } from "../redux/actions/types";
import { StoryblokDraftConfig } from "../types/storyblok";
import { fetchPromoAcquisition } from "./fetchPromoAcquisition";
import { getPromoOnboarding } from "./getPromoOnboarding";
import { getPromoFinishedDate } from "./getPromoFinishedDate";
import { PromoEligible } from "../types/promos";
export const setUserPromosOnboarding = throttle(
(
dispatch: Dispatch<Actions>,
accountId: string,
promoEligible: PromoEligible,
draftConfig: StoryblokDraftConfig = {}
) =>
attempt(async () => {
const { draft, draftForceService } = draftConfig;
const { rootId } = promoEligible;
const promosAcquisition =
draftForceService || (await fetchPromoAcquisition(accountId, rootId));
const promoFinishedDate = promosAcquisition
? getPromoFinishedDate(promosAcquisition)
: null;
const todayDate = new Date(Date.now());
const promoExpiredDate = promoFinishedDate
? addDays(new Date(promoFinishedDate), 1)
: null;
if (
!promosAcquisition ||
promosAcquisition.remainingDays <= 0 ||
(promoExpiredDate && isAfter(todayDate, promoExpiredDate))
) {
dispatch(resetStoryblokPromos());
} else {
const storyblokComponents = await getPromoOnboarding(
promosAcquisition,
rootId,
draft
);
dispatch(setStoryblokPromos(storyblokComponents));
}
})
);
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/utils/getPromoFinishedDate.ts
import { get, has, reverse } from "lodash";
import { PromoMappedSteps, PromoStepType } from "../types/promoSteps";
import { PromoAcquisition } from "../types/promos";
import formatSteps from "../helpers/formatSteps";
const getMappedDate = (steps: PromoMappedSteps): string | null => {
let finishedDate: string | null = null;
Object.entries(steps).find(([key, value]) => {
switch (key) {
case PromoStepType.PAYOUT: {
finishedDate = get(value, "timestamp");
break;
}
case PromoStepType.WAGER: {
finishedDate = get(value, "wagerDate");
break;
}
case PromoStepType.DEPOSIT: {
if (!has(steps, PromoStepType.WAGER)) {
finishedDate = get(value, "depositDate");
}
break;
}
default:
return false;
}
return !!finishedDate;
});
return finishedDate || null;
};
export const getPromoFinishedDate = (promoAcquisition: PromoAcquisition) => {
const steps = reverse([...get(promoAcquisition, "steps", [])]);
return steps.length ? getMappedDate(formatSteps(steps)) : null;
};
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/utils/promoOnboardingPoller.ts
import { Dispatch } from "redux";
import Poller from "@tvg/poller";
import { setUserPromosOnboarding } from "@tvg/sh-lib-promos-onboarding/utils/setUserPromosOnboarding";
import { resetStoryblokPromos } from "@tvg/sh-lib-promos-onboarding/redux/actions";
import { PromoEligible } from "../types/promos";
export const PromoOnboardingPoller = new Poller();
export const tryStopPromoOnboardingPoller = () => {
if (PromoOnboardingPoller.isRunning()) {
PromoOnboardingPoller.stop();
}
};
export const startPromoOnboardingPoller = (
dispatch: Dispatch,
pollerTime: number,
isLogged?: boolean,
accountId?: string,
promoEligible?: PromoEligible
) => {
tryStopPromoOnboardingPoller();
if (isLogged && accountId && promoEligible) {
PromoOnboardingPoller.start(() => {
setUserPromosOnboarding(dispatch, accountId, promoEligible);
}, pollerTime * 1000); // to transform pollerTime in seconds
} else {
dispatch(resetStoryblokPromos());
}
};
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/utils/promoOnboardingPollerTime.ts
import { Dispatch } from "redux";
import { get } from "lodash";
import capi from "@tvg/api/capi";
import Poller from "@tvg/poller";
import { setPromoOnboardingPollerTime } from "@tvg/sh-lib-promos-onboarding/redux/actions";
export const PromoOnboardingTimerPoller = new Poller();
const POLLER_TIMER_PERIOD = 300000;
export const tryStopPromoOnboardingTimerPoller = () => {
if (PromoOnboardingTimerPoller.isRunning()) {
PromoOnboardingTimerPoller.stop();
}
};
export const requestPromoOnboardingTime = (dispatch: Dispatch) =>
capi
.fetchPromoOnboardingPollerTime()
.then((response: { data: { value: string } }) =>
dispatch(setPromoOnboardingPollerTime(+get(response, "data.value", "60")))
);
export const startPromoOnboardingTimerPoller = (dispatch: Dispatch) => {
if (!PromoOnboardingTimerPoller.isRunning()) {
PromoOnboardingTimerPoller.start(
() => requestPromoOnboardingTime(dispatch),
POLLER_TIMER_PERIOD
);
}
};
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/utils/fetchPromosEligible.ts
import { get, attempt, first, isError, orderBy } from "lodash";
import { addDays, isBefore } from "date-fns";
import pro from "@tvg/api/pro";
import { PromoEligible } from "../types/promos";
const MAX_OPTION_DATE_TO_FINISH = 35;
const filterValidEligiblePromotions = (eligiblePromotion: PromoEligible) =>
eligiblePromotion.costCategoryGroup === "Acquisition" &&
eligiblePromotion.eligibilityStatusName === "Elgibile" &&
!!eligiblePromotion.optInDate &&
isBefore(
new Date(),
addDays(new Date(eligiblePromotion.optInDate), MAX_OPTION_DATE_TO_FINISH)
) &&
eligiblePromotion.promoActiveStatus === "Active" &&
(!eligiblePromotion.optInEndDate ||
isBefore(new Date(), addDays(new Date(eligiblePromotion.optInEndDate), 1))); // Shifting one day only to get the same day or before.
export const fetchPromosEligible = async (
accountId: string
): Promise<PromoEligible | null> => {
const promosEligible = await attempt(async () => {
const responseAllEligiblePromos = await pro.fetchUserPromoOptin(accountId);
const eligiblePromotions = get(responseAllEligiblePromos, "data", []);
const eligiblePromotionsFiltered = (eligiblePromotions || []).filter(
filterValidEligiblePromotions
);
return orderBy(eligiblePromotionsFiltered, ["optInDate"], ["asc"]);
});
if (isError(promosEligible)) {
return null;
}
return first(promosEligible) || null;
};
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/hooks/usePromoOnboardingPoller.ts
import { useEffect } from "react";
import { Dispatch } from "redux";
import {
startPromoOnboardingPoller,
tryStopPromoOnboardingPoller
} from "../utils/promoOnboardingPoller";
import {
startPromoOnboardingTimerPoller,
tryStopPromoOnboardingTimerPoller
} from "../utils/promoOnboardingPollerTime";
import { resetStoryblokPromos } from "../redux/actions";
import { usePromoEligible } from "./usePromoEligible";
export const usePromoOnboardingPoller = (
dispatch: Dispatch,
promoOnboardingToggle: boolean,
pollerTime: number,
isLogged?: boolean,
accountId?: string
) => {
const promoEligible = usePromoEligible(
isLogged,
accountId,
promoOnboardingToggle
);
useEffect(() => {
if (promoOnboardingToggle) {
startPromoOnboardingTimerPoller(dispatch);
} else {
tryStopPromoOnboardingTimerPoller();
}
return () => {
tryStopPromoOnboardingTimerPoller();
};
}, [promoOnboardingToggle]);
useEffect(() => {
if (promoOnboardingToggle && promoEligible) {
startPromoOnboardingPoller(
dispatch,
pollerTime,
isLogged,
accountId,
promoEligible
);
} else {
tryStopPromoOnboardingPoller();
}
return () => {
tryStopPromoOnboardingPoller();
dispatch(resetStoryblokPromos());
};
}, [pollerTime, isLogged, accountId, promoEligible]);
};
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/hooks/usePromoEligible.ts
import { useEffect, useState } from "react";
import { fetchPromosEligible } from "../utils/fetchPromosEligible";
import { PromoEligible } from "../types/promos";
export const usePromoEligible = (
isLogged?: boolean,
accountId?: string,
promoOnboardingToggle?: boolean
) => {
const [promoEligible, setPromoEligible] = useState<PromoEligible | null>(
null
);
useEffect(() => {
if (isLogged && accountId && promoOnboardingToggle) {
fetchPromosEligible(accountId).then((promo) => {
setPromoEligible(promo);
});
} else {
// To clean the promo eligible state.
setPromoEligible(null);
}
}, [isLogged, accountId, promoOnboardingToggle]);
return promoEligible;
};
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/BetNotification/styled-components.js
/* eslint-disable import/prefer-default-export */
import styled, { css } from "styled-components";
import { fontNormal, fontMedium } from "../../_static/Typography";
import buildColor from "../../_static/ColorPalette";
export const Notification = styled.div`
position: relative;
font-family: ${fontNormal};
display: flex;
justify-content: space-between;
padding: 12px;
background-color: ${({ colorBackground }) => colorBackground};
color: ${({ color }) => color};
width: 100%;
border-bottom: 1px solid ${({ colorBorder }) => colorBorder};
`;
const borderColor = css`
position: absolute;
background: ${({ colorBorder }) => colorBorder};
`;
export const NotificationTopBorder = styled.div`
${borderColor};
top: -1px;
left: 0;
width: 100%;
height: 1px;
`;
export const NotificationLeftBorder = styled.div`
${borderColor};
top: -1px;
left: -1px;
width: 1px;
height: calc(100% + 2px);
`;
export const NotificationRightBorder = styled.div`
${borderColor};
top: -1px;
right: -1px;
width: 1px;
height: calc(100% + 2px);
`;
const paddingLeft = css`
padding-left: 26px;
`;
export const NotificationWrapper = styled.div`
display: flex;
flex-direction: column;
position: relative;
`;
export const NotificationTitle = styled.div`
font-family: ${({ titleIsBold }) => (titleIsBold ? fontMedium : fontNormal)};
font-size: 14px;
line-height: 19px;
display: flex;
align-items: center;
> svg {
position: absolute;
}
> div {
${paddingLeft}
}
`;
const largeTextFont = css`
font-size: 14px;
line-height: 18px;
`;
const smallTextFont = css`
font-size: 12px;
line-height: 17px;
`;
export const NotificationText = styled.div`
font-family: ${fontNormal};
${({ textFontSize }) =>
textFontSize === "small" ? smallTextFont : largeTextFont};
${paddingLeft};
`;
export const CloseNotification = styled.button`
display: flex;
justify-content: center;
align-items: flex-start;
height: 100%;
background-color: ${({ colorBackground }) => colorBackground};
`;
export const RulesButton = styled.button`
display: flex;
outline: none;
text-decoration: underline;
color: ${({ color }) => color || buildColor("orange", "700")};
font-family: ${({ fontFamily }) => fontFamily || fontMedium};
font-size: 12px;
line-height: 17px;
background-color: ${({ colorBackground }) => colorBackground};
${paddingLeft};
cursor: pointer;
`;
export const CancelBetRulesContainer = styled.div`
font-family: ${fontMedium};
font-size: 12px;
line-height: 17px;
margin-top: 2px;
display: flex;
align-items: baseline;
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/BetNotification/index.jsx
import React from "react";
import { noop } from "lodash";
import Icon from "../../_static/Icons";
import { infoOutline } from "../../_static/Icons/icons";
import { close } from "../../_static/Icons/iconsDuotone";
import {
CloseNotification,
Notification,
NotificationText,
NotificationTitle,
NotificationWrapper,
RulesButton,
CancelBetRulesContainer,
NotificationTopBorder,
NotificationLeftBorder,
NotificationRightBorder
} from "./styled-components";
function BetCancelNotification(props) {
const {
qaLabel,
color,
colorBackground,
colorBorder,
colorList,
iconElement,
viewBoxSize,
iconColor,
strokeColor,
title,
text,
textFontSize,
showCloseButton,
showNotificationFn,
showRulesLink,
showRulesFn,
useLargerWidth,
showCancelRulesFn,
showCancelRules,
hasTopBorder,
titleIsBold
} = props;
return (
<Notification
data-qa-label={qaLabel}
color={color}
colorBackground={colorBackground}
colorBorder={colorBorder}
>
{useLargerWidth && <NotificationLeftBorder colorBorder={colorBorder} />}
{useLargerWidth && <NotificationRightBorder colorBorder={colorBorder} />}
{(useLargerWidth || hasTopBorder) && (
<NotificationTopBorder colorBorder={colorBorder} />
)}
<NotificationWrapper data-qa-label={`${qaLabel}-wrapper`}>
<NotificationTitle
data-qa-label={`${qaLabel}-title`}
titleIsBold={titleIsBold}
>
{colorList && colorList.length > 0 ? (
<Icon
icon={iconElement}
colorList={colorList}
size={14}
viewBoxSize={viewBoxSize}
/>
) : (
<Icon
icon={iconElement}
color={iconColor || color}
size={14}
viewBoxSize={viewBoxSize}
stroke={strokeColor}
/>
)}
<div data-qa-label={`${qaLabel}-rules-title-text`}>{title}</div>
</NotificationTitle>
{typeof text === "string" && (
<NotificationText
data-qa-label={`${qaLabel}-text`}
textFontSize={textFontSize}
>
{text}
</NotificationText>
)}
{Array.isArray(text) &&
text.map((elemText, index) => (
<NotificationText
data-qa-label={`${qaLabel + index}-text`}
textFontSize={textFontSize}
>
{elemText}
</NotificationText>
))}
{showRulesLink && showRulesFn && (
<RulesButton
data-qa-label={`${qaLabel}-rules-link`}
onClick={() => showRulesFn(true)}
colorBackground={colorBackground}
>
See track rules
</RulesButton>
)}
{showCancelRules && showCancelRulesFn && (
<CancelBetRulesContainer>
<RulesButton
data-qa-label={`${qaLabel}-rules-link`}
onClick={() => showCancelRulesFn(true)}
colorBackground="transparent"
fontFamily="inherit"
color={color}
>
See rules
</RulesButton>
<span data-qa-label={`${qaLabel}-rules-link-text`}>
for more details
</span>
</CancelBetRulesContainer>
)}
</NotificationWrapper>
{showCloseButton && showNotificationFn && (
<CloseNotification
data-qa-label={`${qaLabel}-close`}
onClick={() => showNotificationFn(false)}
colorBackground={colorBackground}
>
<Icon icon={close} stroke={color} size={16} viewBoxSize={16} />
</CloseNotification>
)}
</Notification>
);
}
BetCancelNotification.defaultProps = {
colorList: [],
viewBoxSize: 1024,
iconElement: infoOutline,
strokeColor: "",
iconColor: "",
qaLabel: "bet-notification",
showNotificationFn: noop,
showCloseButton: false,
showRulesLink: false,
showRulesFn: noop,
textFontSize: "large",
useLargerWidth: false,
hasTopBorder: false,
titleIsBold: true
};
export default BetCancelNotification;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/SpinningWheel/styled-components.js
import styled, { keyframes } from "styled-components";
import Icon from "../../_static/Icons";
const rotate = keyframes`
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
`;
const SpinningWheelIcon = styled(Icon)`
animation: ${rotate} 2s linear infinite;
`;
export default SpinningWheelIcon;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/SpinningWheel/index.jsx
import React from "react";
import SpinningWheelIcon from "./styled-components";
import { spinningWheel } from "../../_static/Icons/icons";
import buildColor from "../../_static/ColorPalette";
const SpinningWheel = (props) => (
<SpinningWheelIcon
qaLabel={props.qaLabel}
icon={spinningWheel}
size={props.size}
color={props.color}
/>
);
SpinningWheel.defaultProps = {
qaLabel: "spinningWheel",
size: 25,
color: buildColor("white", "100")
};
export default SpinningWheel;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/graphql/queries/CancelLimits.ts
import { gql } from "@apollo/client";
export const GET_GROUP_WAGERS_MY_BETS = gql`
query GetGroupWagersMyBets($accountId: Int!) {
wagerHistory(accountId: $accountId) {
cancelLimits {
monthlyCancelCountLimit
dailyCancelCountLimit
currentMonthCancelledCount
currentDayCancelledCount
remainingMonthCancelledAmount
remainingMonthCancelledCount
remainingDayCancelledAmount
remainingDayCancelledCount
}
}
}
`;
export default GET_GROUP_WAGERS_MY_BETS;
webpack://frontend-mybets/../../packages/sh-lib-my-bets/graphql/behgOptionsCancel.graph.ts
import { graphql } from "@apollo/client/react/hoc";
import { get, noop } from "lodash";
import { ExternalProps, GraphResponse } from "../utils/types";
// @ts-ignore
const getProps = (result: graphql<GraphResponse>) => {
const limits = get(result, "data.wagerHistory.cancelLimits", {});
const refetchQuery = get(result, "data.refetch", noop);
return {
limits,
isLoadingLimitsRequest: result.data.loading,
queryError: result.data.error,
refetchQuery
};
};
export default {
skip: (props: ExternalProps) => !props.accountNumber,
options: (props: ExternalProps) => ({
fetchPolicy: "network-only",
client: props.behgClient,
ssr: false,
variables: { accountId: parseInt(props.accountNumber, 10) }
}),
props: getProps
};
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/MyBetsCard/styled-components.js
import styled from "styled-components";
import buildColor from "../../_static/ColorPalette";
export const BetCardWrapper = styled.div`
display: flex;
flex-direction: column;
background-color: ${buildColor("white", "100")};
`;
export const BetCardRaceHeaderContainer = styled.div`
display: flex;
flex: 1 0 auto;
flex-direction: column;
justify-content: center;
text-decoration: none;
color: ${buildColor("grey", "800")};
padding: 12px;
`;
export const WagersList = styled.ul.attrs({
"data-qa-label": "myBets-betTicket-list"
})`
padding: 0 12px 12px;
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/Buttons/buttonLink.jsx
import React, { PureComponent } from "react";
import { noop } from "lodash";
import { StyledLink, StyledRef } from "./styled-components";
import { getSize, getType } from "./styles";
export default class ButtonLink extends PureComponent {
static defaultProps = {
className: "",
children: null,
url: "",
size: "default",
type: "primary",
tag: "link",
isDisabled: false,
hasRoundedCorners: true,
isStretched: false,
qaLabel: "",
onClick: noop,
hasShadow: false
};
render() {
const sizeSpecs = getSize(this.props.size);
const typeSpecs = getType(this.props.type);
const componentProps = {
...(this.props.qaLabel !== ""
? {
"data-qa-label": this.props.qaLabel
}
: {}),
...{
size: this.props.size,
type: this.props.type,
className: this.props.className
},
...(this.props.tag === "link"
? {
to: this.props.url,
state:
typeof this.props.url !== "string"
? this.props.url.state
: undefined
}
: { href: this.props.url, as: this.props.tag }),
onClick: this.props.onClick,
$sizeSpecs: sizeSpecs,
$typeSpecs: typeSpecs,
tag: this.props.tag,
$isStretched: this.props.isStretched,
$isDisabled: this.props.isDisabled,
$hasRoundedCorners: this.props.hasRoundedCorners,
$hasShadow: this.props.hasShadow
};
return this.props.tag === "link" ? (
<StyledLink {...componentProps}>{this.props.children}</StyledLink>
) : (
<StyledRef {...componentProps}>{this.props.children}</StyledRef>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MyBetsCardHeader/styled-components.js
import styled, { css } from "styled-components";
import { Link } from "react-router-dom";
import buildColor from "../../_static/ColorPalette";
import {
fontNormal,
fontMedium,
fontBold,
defaultSize
} from "../../_static/Typography";
import Button from "../../_atom/Buttons/button";
const wrapper = `
display: flex;
justify-content: space-between;
flex: 1;
`;
export const RaceHeaderContainer = styled.div`
display: flex;
flex-direction: column;
`;
export const RaceHeaderWrapper = styled(Link)`
outline: none;
color: inherit;
text-decoration: inherit;
${wrapper}
`;
export const RaceWatchReplayWrapper = styled.div`
margin-top: 12px;
${wrapper}
`;
export const RaceHeaderInfo = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
text-decoration: none;
margin-right: 12px;
overflow: hidden;
`;
export const RaceFeaturedEventName = styled.div`
font-family: ${fontBold};
font-size: 14px;
color: ${buildColor("yellow", "800")};
`;
export const RaceTrackNameWrapper = styled.div`
display: flex;
flex-direction: row;
font-family: ${fontBold};
font-size: 16px;
color: ${buildColor("grey", "900")};
line-height: 22px;
white-space: pre;
`;
export const RaceTrackName = styled.div`
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
`;
export const RaceTrackNumber = styled.div``;
export const RaceBetsInfo = styled.div`
margin-top: 4px;
font-family: ${fontNormal};
font-size: 14px;
color: ${buildColor("grey", "800")};
line-height: 18px;
`;
export const RaceHeaderActions = styled.div`
display: flex;
align-items: center;
> a,
> button {
min-width: 125px;
}
> * {
&:first-child {
margin-left: 0;
}
margin-left: 12px;
}
`;
export const VideoButtonIconWrapper = styled.span`
display: flex;
margin-right: 8px;
`;
export const RepeatBetButton = styled(Button).attrs({
size: "bigger",
isBold: false,
isUppercase: false,
type: "non_styled",
fontFamily: fontMedium
})`
color: ${buildColor("blue_accent", "500")};
font-size: ${defaultSize};
min-width: 0;
padding: 0;
background: "transparent";
> span {
justify-content: flex-end;
}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MyBetsCardHeader/index.jsx
import React from "react";
import { noop } from "lodash";
import { Link } from "react-router-dom";
import { formatPastRaceDate } from "@tvg/formatter/dates";
import formatCurrency from "@tvg/formatter/currency";
import ButtonLink from "../../_atom/Buttons/buttonLink";
import Icon from "../../_static/Icons";
import { play } from "../../_static/Icons/iconsDuotone";
import { hasReplay } from "../../_static/Icons/icons";
import buildColor from "../../_static/ColorPalette";
import {
RaceHeaderContainer,
RaceHeaderWrapper,
RaceWatchReplayWrapper,
RaceHeaderInfo,
RaceTrackNameWrapper,
RaceTrackName,
RaceTrackNumber,
RaceFeaturedEventName,
RaceBetsInfo,
RaceHeaderActions,
VideoButtonIconWrapper,
RepeatBetButton
} from "./styled-components";
import MyBetsMTP from "../MyBetsMTP";
import Button from "../../_atom/Buttons/button";
const getBetsInfo = (betAmount, bets) => {
const betTitle = `Bet${bets > 1 ? "s" : ""}`;
return `${bets} ${betTitle} • ${formatCurrency(betAmount)} staked`;
};
const getButtonProps = (hasReplayVideo) =>
hasReplayVideo
? {
text: "Watch Replay",
type: "primary",
hasIcon: true,
hasShadow: false
}
: {
text: "See Result",
type: "secondary",
hasIcon: false,
hasShadow: true
};
const renderVideoButton = (
raceUrl,
currentRaceNumber,
showRaceNumber,
isRaceNear,
onVideoRedirect
) => {
const [racePathname] = raceUrl.split("?");
const iconColor = isRaceNear
? buildColor("white", "100")
: buildColor("blue_accent", "500");
return (
<ButtonLink
url={{
pathname: racePathname,
search: `?race=${currentRaceNumber}`,
state: {
openVideo: true
}
}}
onClick={onVideoRedirect}
qaLabel="watch-video-button"
size="bigger"
isBold={false}
isUppercase={false}
type={isRaceNear ? "primary" : "secondary"}
hasShadow={!isRaceNear}
>
<VideoButtonIconWrapper>
<Icon
icon={play}
size={14}
viewBoxSize={20}
color={buildColor("white", "0")}
stroke={iconColor}
/>
</VideoButtonIconWrapper>
Watch {showRaceNumber ? `R${currentRaceNumber}` : "Live"}
</ButtonLink>
);
};
const renderRedirectReplayButton = (
raceUrl,
hasReplayVideo,
onWatchReplay,
closeModal
) => {
const [racePathname, raceSearch] = raceUrl.split("?");
const buttonProps = getButtonProps(hasReplayVideo);
return (
<RaceWatchReplayWrapper>
<ButtonLink
isStretched
size="bigger"
isBold={false}
isUppercase={false}
url={{
pathname: racePathname,
search: raceSearch,
state: {
openVideo: true
}
}}
onClick={() => {
onWatchReplay(false);
closeModal();
}}
qaLabel="watch-video-button"
hasRoundedCorners
type={buttonProps.type}
hasShadow={buttonProps.hasShadow}
>
{buttonProps.hasIcon && (
<VideoButtonIconWrapper>
<Icon
icon={hasReplay}
size={15}
color={buildColor("white", "100")}
/>
</VideoButtonIconWrapper>
)}
{buttonProps.text}
</ButtonLink>
</RaceWatchReplayWrapper>
);
};
const renderReplayButton = (
onWatchReplay,
isReplayInsideMyBets,
hasReplayVideo,
raceUrl,
showSeeResult,
closeModal
// eslint-disable-next-line consistent-return
) => {
if (!isReplayInsideMyBets && hasReplayVideo) {
return renderRedirectReplayButton(
raceUrl,
hasReplayVideo,
onWatchReplay,
closeModal
);
}
if (showSeeResult || isReplayInsideMyBets) {
const buttonProps = getButtonProps(hasReplayVideo);
return (
<RaceWatchReplayWrapper>
<Button
isStretched
size="bigger"
isBold={false}
isUppercase={false}
onClick={onWatchReplay}
qaLabel="watch-video-button"
hasRoundedCorners
type={buttonProps.type}
hasShadow={buttonProps.hasShadow}
>
{buttonProps.hasIcon && (
<VideoButtonIconWrapper>
<Icon
icon={hasReplay}
size={15}
color={buildColor("white", "100")}
/>
</VideoButtonIconWrapper>
)}
{buttonProps.text}
</Button>
</RaceWatchReplayWrapper>
);
}
};
const MyBetsCardHeader = (props) => {
const {
racePostTime,
statusCode,
trackName,
eventName,
raceNumber,
currentRaceNumber,
mtp,
bets,
betAmount,
dateDiff,
winningsAmount,
raceUrl,
closeModal,
onWatchReplay,
isFutureBet,
raceDate,
isMTPNewRules,
hasReplayVideo,
hasLiveVideo,
postTime,
showRaceLeg,
legNumber,
onVideoRedirect,
isReplayInsideMyBets,
showBetInfo,
qaLabel,
hasPastPerformance,
isRaceNear,
showSeeResult,
isMyBetsOpen,
hasRepeatBet,
onRepeatBet,
isSpecialWager
} = props;
return (
<RaceHeaderContainer data-qa-label={qaLabel}>
<RaceHeaderWrapper
data-qa-label={`${qaLabel}-details`}
as={dateDiff === 0 && isMyBetsOpen ? Link : "div"}
to={raceUrl}
onClick={closeModal}
>
<RaceHeaderInfo data-qa-label={`${qaLabel}-info`}>
<MyBetsMTP
showRaceLeg={showRaceLeg}
legNumber={legNumber}
isFutureBet={isFutureBet}
raceDate={raceDate}
postTime={postTime}
currentDate={formatPastRaceDate(postTime || "")}
raceMtp={mtp}
racePostTime={racePostTime}
raceStatusCode={statusCode}
raceDateDiff={dateDiff}
isMTPNewRules={isMTPNewRules}
qaLabel={`${qaLabel}-mtp`}
/>
{eventName && (
<RaceFeaturedEventName data-qa-label={`${qaLabel}-event-name`}>
{eventName}
</RaceFeaturedEventName>
)}
<RaceTrackNameWrapper data-qa-label={`${qaLabel}-track-name`}>
<RaceTrackName> {trackName}</RaceTrackName>
{raceNumber && !isSpecialWager && (
<RaceTrackNumber>{` R${raceNumber}`}</RaceTrackNumber>
)}
</RaceTrackNameWrapper>
{showBetInfo && (
<RaceBetsInfo data-qa-label={`${qaLabel}-bets-info`}>
{getBetsInfo(betAmount, bets)}
</RaceBetsInfo>
)}
</RaceHeaderInfo>
<RaceHeaderActions data-qa-label={`${qaLabel}-header-actions`}>
{hasLiveVideo &&
renderVideoButton(
raceUrl,
currentRaceNumber,
!!legNumber,
isRaceNear,
onVideoRedirect
)}
{hasRepeatBet && (
<RepeatBetButton onClick={onRepeatBet} qaLabel="repeat-bet-link">
Repeat bet
</RepeatBetButton>
)}
</RaceHeaderActions>
</RaceHeaderWrapper>
{hasPastPerformance &&
renderReplayButton(
onWatchReplay,
isReplayInsideMyBets,
hasReplayVideo,
raceUrl,
showSeeResult,
closeModal
)}
</RaceHeaderContainer>
);
};
MyBetsCardHeader.defaultProps = {
racePostTime: "2020-11-04T17:00:00Z",
statusCode: "O",
trackName: "",
eventName: "",
raceNumber: 1,
mtp: 60,
bets: 0,
betAmount: 0,
dateDiff: 0,
winningsAmount: 0,
raceUrl: "",
closeModal: noop,
onWatchReplay: noop,
isFutureBet: false,
raceDate: "",
isMTPNewRules: true,
hasReplayVideo: false,
hasLiveVideo: false,
postTime: "",
showRaceLeg: false,
legNumber: 1,
onVideoRedirect: noop,
isReplayInsideMyBets: true,
showBetInfo: false,
qaLabel: "mybets-card-header",
hasPastPerformance: true,
isRaceNear: false,
currentRaceNumber: 1,
showSeeResult: false,
isMyBetsOpen: false,
hasRepeatBet: false,
onRepeatBet: noop
};
export default MyBetsCardHeader;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/MyBetsCard/index.jsx
import React from "react";
import { noop } from "lodash";
import {
BetCardWrapper,
BetCardRaceHeaderContainer,
WagersList
} from "./styled-components";
import MyBetsCardHeader from "../../_molecule/MyBetsCardHeader";
const MyBetsCard = (props) => {
const {
children,
dateDiff,
closeModal,
onWatchReplay,
index,
isReplayInsideMyBets,
isMTPNewRules,
intersectableRef,
itemToRef,
racePostTime,
trackName,
mtp,
statusCode,
legStatusCode,
raceNumber,
raceUrl,
betsNumber,
betAmount,
winningsAmount,
hasReplayVideo,
hasLiveVideo,
onVideoRedirect,
showBetInfoHeader,
isFutureBet,
raceDate,
qaLabel,
showRaceLeg,
legNumber,
hasPastPerformance,
isRaceNear,
currentRaceNumber,
showSeeResult,
isMyBetsOpen,
hasRepeatBet,
onRepeatBet,
isSpecialWager
} = props;
return (
<BetCardWrapper
data-qa-label={qaLabel}
id={`activebet-${index}`}
ref={index === itemToRef ? intersectableRef : null}
>
<BetCardRaceHeaderContainer data-qa-label={`${qaLabel}-header-container`}>
<MyBetsCardHeader
showBetInfo={showBetInfoHeader}
racePostTime={racePostTime}
trackName={trackName}
mtp={mtp}
statusCode={legStatusCode || statusCode}
raceNumber={raceNumber}
bets={betsNumber}
betAmount={betAmount}
dateDiff={dateDiff}
winningsAmount={winningsAmount}
raceUrl={raceUrl}
closeModal={closeModal}
onWatchReplay={onWatchReplay}
isReplayInsideMyBets={isReplayInsideMyBets}
isFutureBet={isFutureBet}
raceDate={raceDate}
isMTPNewRules={isMTPNewRules}
hasReplayVideo={hasReplayVideo}
hasLiveVideo={hasLiveVideo}
onVideoRedirect={onVideoRedirect}
showRaceLeg={showRaceLeg}
legNumber={legNumber}
hasPastPerformance={hasPastPerformance}
isRaceNear={isRaceNear}
currentRaceNumber={currentRaceNumber}
showSeeResult={showSeeResult}
isMyBetsOpen={isMyBetsOpen}
hasRepeatBet={hasRepeatBet}
onRepeatBet={onRepeatBet}
isSpecialWager={isSpecialWager}
/>
</BetCardRaceHeaderContainer>
<WagersList>{children}</WagersList>
</BetCardWrapper>
);
};
MyBetsCard.defaultProps = {
children: null,
dateDiff: 0,
closeModal: noop,
onWatchReplay: noop,
index: -1,
isReplayInsideMyBets: true,
isMTPNewRules: true,
intersectableRef: null,
itemToRef: 0,
racePostTime: "",
trackName: "",
mtp: 60,
statusCode: "O",
raceNumber: 1,
raceUrl: "",
betsNumber: 0,
betAmount: 0,
winningsAmount: 0,
hasReplayVideo: false,
hasLiveVideo: false,
onVideoRedirect: noop,
showBetInfoHeader: false,
isFutureBet: false,
raceDate: "",
qaLabel: "mybets-bets-race-card",
showRaceLeg: false,
legNumber: 0,
hasPastPerformance: false,
isRaceNear: false,
currentRaceNumber: 1,
legStatusCode: null,
showSeeResult: false,
isMyBetsOpen: false,
hasRepeatBet: false,
onRepeatBet: noop
};
export default MyBetsCard;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MyBetsWagerHeader/styled-components.js
import styled, { css } from "styled-components";
import { Link } from "react-router-dom";
import buildColor from "../../_static/ColorPalette";
import Text from "../../_atom/Text";
import {
fontCondensedNormal,
fontMedium,
fontNormal
} from "../../_static/Typography";
/* Use z-index on runnerNumber when (ex: winner) to surpass these styles */
const MutedStyles = (color = "white", variation = "80") => css`
position: relative;
&::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: ${buildColor(color, variation)};
z-index: 1;
}
`;
export const BetCardHeader = styled.div`
display: flex;
justify-content: space-between;
height: ${({ isBigHeader }) => (isBigHeader ? "72px" : "56px")};
padding: 11px 12px;
background-color: ${buildColor("blue_accent", "000")};
border-top-left-radius: 4px;
border-top-right-radius: 4px;
${({ isCenter }) =>
isCenter &&
css`
align-items: center;
`}
${({ hasBorderBottom }) =>
hasBorderBottom &&
css`
border-bottom: 1px solid ${buildColor("blue", "100")};
`}
${({ hasRoundBorderBottom }) =>
hasRoundBorderBottom &&
css`
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
`}
`;
export const HeaderColumn = styled.div`
display: flex;
flex-direction: column;
margin-right: ${({ addMargin }) => (addMargin ? "12px" : "8px")};
&:last-child:not(:first-child) {
margin-right: 0;
align-items: flex-end;
}
${({ betStatus }) =>
betStatus === "canceled" && MutedStyles("blue_accent", "50")}
${({ textRight }) => textRight && "text-align: right"}
`;
export const HeaderText = styled(Text)`
font-size: 14px;
line-height: 18px;
font-family: ${({ isWinner, isRefund }) =>
isWinner || isRefund ? fontMedium : fontNormal};
${({ isCanceled }) =>
isCanceled &&
css`
text-decoration: line-through;
`}
${({ isWinner }) =>
isWinner
? css`
color: ${buildColor("green", "700")};
`
: css`
color: ${buildColor("grey", "900")};
`}
`;
export const HeaderTitle = styled(Text)`
color: ${({ isWinner }) =>
buildColor(isWinner ? "green" : "grey", isWinner ? "700" : "800")};
font-family: ${fontCondensedNormal};
font-size: 12px;
line-height: 16px;
text-transform: uppercase;
${({ isCanceled }) =>
isCanceled &&
css`
text-decoration: line-through;
`}
`;
export const HideShowContainer = styled.button`
background: none;
border: none;
outline: none;
display: flex;
align-items: center;
`;
export const HideShowLabel = styled.span`
color: ${buildColor("blue_accent", "500")};
font-family: ${fontNormal};
font-style: normal;
font-weight: 500;
font-size: 12px;
line-height: 17px;
margin-left: 4px;
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/WagerHeaderStatus/styled-components.js
import styled, { css } from "styled-components";
import { Link } from "react-router-dom";
import Text from "../../_atom/Text";
import {
fontCondensedNormal,
fontMedium,
fontNormal
} from "../../_static/Typography";
import buildColor from "../../_static/ColorPalette";
const IconTextInlineStyles = css`
display: flex;
align-items: center;
svg {
margin-right: 4px;
}
`;
/* Use z-index on runnerNumber when (ex: winner) to surpass these styles */
const MutedStyles = (color = "white", variation = "80") => css`
position: relative;
&::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: ${buildColor(color, variation)};
z-index: 1;
}
`;
export const HeaderCanceledContainer = styled.div`
${IconTextInlineStyles};
`;
export const HeaderColumn = styled.div`
display: flex;
flex-direction: column;
${({ betStatus }) =>
betStatus === "canceled" && MutedStyles("blue_accent", "50")}
${({ textRight }) => textRight && "text-align: right;"}
${({ addMargin }) => addMargin && "margin-right: 8px;"}
`;
export const HeaderContainer = styled.div`
display: flex;
flex-direction: row;
`;
export const HeaderPayoutButton = styled.button`
${IconTextInlineStyles};
background-color: transparent;
outline: none;
border: none;
cursor: pointer;
`;
export const HeaderRefundedLink = styled(Link)`
${IconTextInlineStyles};
text-decoration: none;
${({ smallText }) =>
smallText &&
css`
font-size: 12px;
`}
`;
export const HeaderRow = styled.div`
display: flex;
flex-direction: row;
${({ center }) =>
center &&
css`
justify-content: center;
`}
`;
export const HeaderText = styled(Text)`
font-size: 14px;
line-height: 18px;
font-family: ${({ isWinner, isRefund }) =>
isWinner || isRefund ? fontMedium : fontNormal};
${({ isCanceled }) =>
isCanceled &&
css`
color: ${buildColor("grey", "800")};
`}
${({ isWinner }) =>
isWinner
? css`
color: ${buildColor("green", "700")};
`
: css`
color: ${buildColor("grey", "800")};
`}
`;
export const HeaderRefundText = styled(Text)`
display: flex;
align-items: center;
font-family: ${fontCondensedNormal};
font-size: 12px;
line-height: 14px;
color: ${buildColor("grey", "900")};
margin-right: 1ch;
`;
export const HeaderTitle = styled(Text)`
color: ${({ isWinner }) =>
buildColor(isWinner ? "green" : "grey", isWinner ? "700" : "800")};
font-family: ${fontCondensedNormal};
font-size: 12px;
line-height: 16px;
text-transform: uppercase;
${({ isCanceled }) =>
isCanceled &&
css`
text-decoration: line-through;
`}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/WagerHeaderStatus/index.jsx
import React from "react";
import { noop } from "lodash";
import formatCurrency from "@tvg/formatter/currency";
import {
HeaderCanceledContainer,
HeaderColumn,
HeaderContainer,
HeaderPayoutButton,
HeaderRefundedLink,
HeaderRefundText,
HeaderRow,
HeaderText,
HeaderTitle
} from "./styled-components";
import Icon from "../../_static/Icons";
import { betCanceled, info, question } from "../../_static/Icons/iconsDuotone";
import buildColor from "../../_static/ColorPalette";
import WonIllustration from "../../_atom/WonIllustration";
const renderRefundStatus = (betRefund, qaLabel, addMargin) => (
<HeaderColumn
data-qa-label={`${qaLabel}-status-list`}
textRight
addMargin={addMargin}
>
<HeaderText qaLabel={`${qaLabel}-status-text`} isRefund>
{formatCurrency(betRefund || 0)}
</HeaderText>
{/* There will be a modal explaining this */}
<HeaderRefundedLink data-qa-label={`${qaLabel}-status-link`} to="/">
<Icon
qaLabel={`${qaLabel}-status-icon`}
icon={info}
viewBoxSize={16}
size={16}
color={buildColor("blue_accent", "100")}
stroke={buildColor("blue_accent", "500")}
/>
<HeaderTitle qaLabel={`${qaLabel}-status-title`}>refunded</HeaderTitle>
</HeaderRefundedLink>
</HeaderColumn>
);
export const WagerHeaderStatus = (props) => {
const {
betStatus,
winningsAmount,
probableValue,
onApproxPayout,
betRefund,
isBetWinner,
shouldShowPotentialReturn,
qaLabel,
showMinMaxWillPays,
minWillPays,
maxWillPays,
isFDR
} = props;
const renderPotentialPayout = () => (
<HeaderColumn data-qa-label={`${qaLabel}-status-list`} textRight>
<HeaderText qaLabel={`${qaLabel}-status-text`}>
{probableValue}
</HeaderText>
<HeaderPayoutButton onClick={onApproxPayout}>
<Icon
icon={question}
viewBoxSize={16}
size={16}
color={buildColor("blue_accent", "100")}
stroke={buildColor("blue_accent", "500")}
/>
<HeaderTitle qaLabel={`${qaLabel}-status-title`}>
approx. payout
</HeaderTitle>
</HeaderPayoutButton>
</HeaderColumn>
);
const renderWillPays = () => (
<HeaderColumn>
<HeaderText data-qa-label="my-bets-payout-value">
{`${formatCurrency(minWillPays, "USD")} - ${formatCurrency(
maxWillPays,
"USD"
)}`}
</HeaderText>
<HeaderTitle data-qa-label="my-bets-payout-button-text">
Will Pays
</HeaderTitle>
</HeaderColumn>
);
switch (betStatus) {
case "canceled":
return (
<HeaderColumn data-qa-label={`${qaLabel}-status-list`} textRight>
<HeaderCanceledContainer data-qa-label={`${qaLabel}-status-wrapper`}>
<Icon
qaLabel={`${qaLabel}-status-icon`}
icon={betCanceled}
viewBoxSize={16}
size={16}
color={buildColor("white", "10")}
stroke={buildColor("grey", "800")}
/>
<HeaderText qaLabel={`${qaLabel}-status-text`} isCanceled>
Cancelled
</HeaderText>
</HeaderCanceledContainer>
</HeaderColumn>
);
case "winner":
return isBetWinner ? (
<HeaderRow>
<HeaderContainer>
<HeaderColumn data-qa-label={`${qaLabel}-status-list`}>
<WonIllustration
winAmount={winningsAmount || 0}
hideLogo={isFDR}
/>
{!!betRefund && (
<HeaderRow data-qa-label={`${qaLabel}-status-list`} center>
<HeaderRefundText qaLabel={`${qaLabel}-status-text`}>
+{formatCurrency(betRefund || 0)}
</HeaderRefundText>
{/* There will be a modal explaining this */}
<HeaderRefundedLink
smallText
data-qa-label={`${qaLabel}-status-link`}
to="/"
>
<HeaderTitle qaLabel={`${qaLabel}-status-title`}>
refund
</HeaderTitle>
</HeaderRefundedLink>
</HeaderRow>
)}
</HeaderColumn>
</HeaderContainer>
</HeaderRow>
) : (
<HeaderRow>
{!!betRefund && (
<HeaderColumn data-qa-label={`${qaLabel}-status-list`} textRight>
<HeaderText qaLabel={`${qaLabel}-status-text`}>
{formatCurrency(betRefund || 0)}
</HeaderText>
{/* There will be a modal explaining this */}
<HeaderRefundedLink
data-qa-label={`${qaLabel}-status-link`}
to="/"
>
<HeaderTitle qaLabel={`${qaLabel}-status-title`}>
refund
</HeaderTitle>
</HeaderRefundedLink>
</HeaderColumn>
)}
<HeaderContainer>
<HeaderColumn data-qa-label={`${qaLabel}-status-list`} textRight>
<HeaderText
qaLabel={`${qaLabel}-status-text`}
isWinner={isBetWinner}
>
{formatCurrency(winningsAmount || 0)}
</HeaderText>
<HeaderTitle
qaLabel={`${qaLabel}-status-title`}
isWinner={isBetWinner}
>
return
</HeaderTitle>
</HeaderColumn>
</HeaderContainer>
</HeaderRow>
);
case "loser":
return (
<HeaderContainer>
{betRefund > 0 && renderRefundStatus(betRefund, qaLabel, true)}
<HeaderColumn data-qa-label={`${qaLabel}-status-list`} textRight>
<HeaderText qaLabel={`${qaLabel}-status-text`}>
{formatCurrency(0)}
</HeaderText>
<HeaderTitle qaLabel={`${qaLabel}-status-title`}>
return
</HeaderTitle>
</HeaderColumn>
</HeaderContainer>
);
case "refunded":
return (
<React.Fragment>
{renderRefundStatus(betRefund, qaLabel, false)}
</React.Fragment>
);
default:
return (
<React.Fragment>
{shouldShowPotentialReturn && renderPotentialPayout()}
{showMinMaxWillPays && renderWillPays()}
</React.Fragment>
);
}
};
WagerHeaderStatus.defaultProps = {
betStatus: "active",
winningsAmount: 0,
probableValue: "",
onApproxPayout: noop,
betRefund: 0,
isBetWinner: false,
shouldShowPotentialReturn: false,
qaLabel: "wager-header-status",
showMinMaxWillPays: false,
minWillPays: 0,
maxWillPays: 0,
isFDR: false
};
export default WagerHeaderStatus;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MyBetsWagerHeader/index.jsx
import React from "react";
import { get, noop } from "lodash";
import formatCurrency from "@tvg/formatter/currency";
import Icon from "../../_static/Icons";
import buildColor from "../../_static/ColorPalette";
import { eyeHide, eyeShow } from "../../_static/Icons/icons";
import {
BetCardHeader,
HeaderColumn,
HeaderText,
HeaderTitle,
HideShowContainer,
HideShowLabel
} from "./styled-components";
import WagerHeaderStatus from "../WagerHeaderStatus";
const MyBetsWagerHeader = (props) => {
const {
isOptedIn,
betStatus,
isCanceled,
wager,
probableValue,
onApproxPayout,
onHideShowLegsGTM,
showContent,
setShowContent,
betRefund,
isBetWinner,
shouldShowPotentialReturn,
shouldShowHideLegButton,
shouldShowRebet,
qaLabel,
betsNumber,
showMinMaxWillPays,
minWillPays,
maxWillPays,
isFDR
} = props;
return (
<BetCardHeader
data-qa-label={qaLabel}
hasBorderBottom={showContent && (!isOptedIn || !shouldShowRebet)}
hasRoundBorderBottom={!showContent && !shouldShowRebet}
isBigHeader={!!betRefund && betStatus === "winner"}
isCenter={!betRefund || betStatus !== "winner"}
>
<HeaderColumn data-qa-label={`${qaLabel}-info`} betStatus={betStatus}>
<HeaderText qalabel={`${qaLabel}-text`} isCanceled={isCanceled}>
{formatCurrency(wager.wagerAmount || 0)}{" "}
{get(wager, "wagerType.name", "")}
{betsNumber > 1 && ` (x${betsNumber})`}
</HeaderText>
<HeaderTitle qaLabel={`${qaLabel}-title`} isCanceled={isCanceled}>
{formatCurrency((wager.betTotal || 0) * betsNumber)} ticket
</HeaderTitle>
</HeaderColumn>
<HeaderColumn data-qa-label={`${qaLabel}-status-wrapper`}>
<WagerHeaderStatus
betStatus={get(wager, "betStatus.name", "")}
winningsAmount={get(wager, "winningsAmount", 0)}
probableValue={probableValue}
onApproxPayout={onApproxPayout}
betRefund={betRefund}
isBetWinner={isBetWinner}
shouldShowPotentialReturn={shouldShowPotentialReturn}
showMinMaxWillPays={showMinMaxWillPays}
minWillPays={minWillPays}
maxWillPays={maxWillPays}
isFDR={isFDR}
/>
{shouldShowHideLegButton && (
<HideShowContainer
onClick={() => {
onHideShowLegsGTM(!showContent);
setShowContent(!showContent, get(wager, "id"));
}}
>
<Icon
icon={showContent ? eyeHide : eyeShow}
size={16}
color={buildColor("blue_accent", "100")}
stroke={buildColor("blue_accent", "500")}
/>
<HideShowLabel>{showContent ? "Hide" : "Show"} legs</HideShowLabel>
</HideShowContainer>
)}
</HeaderColumn>
</BetCardHeader>
);
};
MyBetsWagerHeader.defaultProps = {
isOptedIn: false,
betStatus: "active",
isCanceled: false,
wager: {},
probableValue: "",
onApproxPayout: noop,
onHideShowLegsGTM: noop,
showContent: true,
setShowContent: noop,
betRefund: 0,
isBetWinner: false,
shouldShowPotentialReturn: false,
shouldShowHideLegButton: false,
qaLabel: "my-bets-wager-header",
betsNumber: 1,
isFDR: false
};
export default MyBetsWagerHeader;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/MyBetsWager/styled-components.js
import styled, { css } from "styled-components";
import buildColor from "@tvg/atomic-ui/_static/ColorPalette";
import { fontMedium } from "../../_static/Typography";
/* Use z-index on runnerNumber when (ex: winner) to surpass these styles */
const MutedStyles = css`
position: relative;
&::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: ${buildColor("white", "80")};
z-index: 1;
}
`;
export const BetCard = styled.div.attrs({
"data-qa-label": "myBets-betTicket"
})`
border-radius: 4px;
border: 1px solid ${buildColor("blue", "100")};
&:not(:last-child) {
margin-bottom: 12px;
}
`;
export const BetCardBody = styled.div.attrs({
"data-qa-label": "myBets-betTicket-selections"
})`
padding: 12px 10px;
${({ hasContentMaxHeight, isScrollable }) =>
hasContentMaxHeight &&
css`
overflow-y: auto;
max-height: 25vh;
box-shadow: ${isScrollable
? "inset 0px -2px 6px rgba(56, 64, 72, 0.15)"
: "none"};
`}
${({ isBetsDetailedView }) =>
!isBetsDetailedView &&
css`
/* hasMutedStyles in all bets status - (active & winner horses) */
${({ betStatus }) =>
["winner", "canceled", "loser", "refunded"].includes(betStatus) &&
MutedStyles}
`}
`;
export const AlertInlineAction = styled.p`
display: flex;
font-family: ${fontMedium};
font-size: 14px;
line-height: 16px;
cursor: pointer;
text-decoration-line: underline;
color: ${buildColor("blue_accent", "700")};
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/MyBetsWager/index.jsx
import React, { useCallback } from "react";
import { noop, get } from "lodash";
import { AlertInline } from "@tvg/design-system";
import MyBetsWagerHeader from "../../_molecule/MyBetsWagerHeader";
import MyBetsWagerFooter from "../../_molecule/MyBetsWagerFooter";
import PickBetRebet from "../../_molecule/PickBetRebet";
import { infoOutline } from "../../_static/Icons/iconsDuotone";
import buildColor from "../../_static/ColorPalette";
import BetNotificationScratch from "../../_molecule/BetNotification";
import OptedInTag from "../../_atom/OptedInTag";
import { BetCard, BetCardBody, AlertInlineAction } from "./styled-components";
const MyBetsWager = ({
wager,
probableValue,
raceUrl,
closeModal,
onApproxPayout,
showTrackRules,
onHideShowLegsGTM = noop,
showContent,
setShowContent = noop,
betCardRef,
betCardBodyRef,
isOptedIn,
betStatus,
isCanceled,
showBetsDetailedView,
betRefund,
isBetWinner,
shouldShowHideLegButton,
shouldShowPotentialReturn,
hasFooter,
shouldShowRebet,
isDetailsOpened,
handleDetailsButton,
shouldRenderFooter,
isBetActive,
isWagerCancelable,
repeatButtonSearch,
showRepeatButton,
renderRunnerSelection,
showScratchedNotification,
shouldNotHideScratchNotification,
setShouldNotHideScratchNotification,
scratchedTitle,
scratchedLegText,
onCancelWager,
handleRebetClickEvent,
rebetWagerTypeName,
rebetSearch,
qaLabel,
hasContentMaxHeight,
isMyBetsOpen,
betsNumber,
isCardBodyScrollable,
isDesktop,
isScratchInfoDesign,
showMinMaxWillPays,
minWillPays,
maxWillPays,
renderPromoOnboarding,
onShareWager,
socialShareModalToggle,
isFDR
}) => {
if (!wager) {
return null;
}
const wagerId = get(wager, "id", "unk");
const getBetNotificationScratch = useCallback(
() =>
isScratchInfoDesign ? (
<AlertInline
message={scratchedLegText}
title={scratchedTitle}
type="fixed"
variant="informational"
qaLabel={`notification-scratch-${wagerId}`}
marginBottom="space-5"
onDismissPress={setShouldNotHideScratchNotification}
actionLink={
<AlertInlineAction
qaLabel="notification-scratch-modal"
onClick={showTrackRules}
>
See Rules
</AlertInlineAction>
}
/>
) : (
<BetNotificationScratch
qaLabel={`notification-scratch-${wagerId}`}
title={scratchedTitle}
text={scratchedLegText}
textFontSize="small"
color={buildColor("orange", "700")}
colorList={[buildColor("orange", "200"), buildColor("orange", "700")]}
colorBorder={buildColor("orange", "200")}
colorBackground={buildColor("orange", "000")}
iconElement={infoOutline}
showCloseButton
showNotificationFn={setShouldNotHideScratchNotification}
showRulesLink={isMyBetsOpen}
useLargerWidth
showRulesFn={showTrackRules}
/>
),
[
wagerId,
scratchedTitle,
scratchedLegText,
setShouldNotHideScratchNotification,
isMyBetsOpen,
showTrackRules,
isScratchInfoDesign
]
);
return (
<BetCard data-qa-label={qaLabel} ref={betCardRef}>
<MyBetsWagerHeader
isOptedIn={isOptedIn}
betStatus={betStatus}
isCanceled={isCanceled}
wager={wager}
probableValue={probableValue}
onApproxPayout={onApproxPayout}
onHideShowLegsGTM={onHideShowLegsGTM}
showContent={showContent}
setShowContent={setShowContent}
betRefund={betRefund}
isBetWinner={isBetWinner}
shouldShowHideLegButton={shouldShowHideLegButton}
shouldShowPotentialReturn={shouldShowPotentialReturn}
shouldShowRebet={shouldShowRebet}
betsNumber={betsNumber}
showMinMaxWillPays={showMinMaxWillPays}
minWillPays={minWillPays}
maxWillPays={maxWillPays}
isFDR={isFDR}
/>
{isOptedIn && <OptedInTag />}
{showScratchedNotification &&
shouldNotHideScratchNotification &&
getBetNotificationScratch()}
{showContent && (
<BetCardBody
ref={betCardBodyRef}
betStatus={betStatus}
isScrollable={isCardBodyScrollable}
isBetsDetailedView={
showBetsDetailedView &&
showBetsDetailedView.length > 0 &&
showBetsDetailedView.every((value) => value)
}
hasContentMaxHeight={hasContentMaxHeight}
>
{renderRunnerSelection}
</BetCardBody>
)}
{shouldShowRebet && (
<PickBetRebet
raceUrl={raceUrl}
handleRebetClickEvent={handleRebetClickEvent}
rebetWagerTypeName={rebetWagerTypeName}
rebetSearch={rebetSearch}
isContentDisplayed={showContent}
/>
)}
{renderPromoOnboarding}
{hasFooter && (
<MyBetsWagerFooter
closeModal={closeModal}
raceUrl={raceUrl}
isDetailsOpened={isDetailsOpened}
handleDetailsButton={handleDetailsButton}
shouldRenderFooter={shouldRenderFooter && showContent}
isBetActive={isBetActive}
isWagerCancelable={isWagerCancelable}
repeatButtonSearch={repeatButtonSearch}
showRepeatButton={showRepeatButton}
onCancelWager={onCancelWager}
isContentDisplayed={showContent}
isDesktop={isDesktop}
onShareWager={onShareWager}
socialShareModalToggle={socialShareModalToggle}
/>
)}
</BetCard>
);
};
MyBetsWager.defaultProps = {
wager: {},
probableValue: null,
raceUrl: "",
closeModal: noop,
onApproxPayout: noop,
showTrackRules: false,
onHideShowLegsGTM: noop,
showContent: true,
setShowContent: noop,
betCardRef: null,
isOptedIn: false,
betStatus: "O",
isCanceled: false,
showBetsDetailedView: false,
betRefund: 0,
isBetWinner: false,
shouldShowHideLegButton: false,
shouldShowPotentialReturn: false,
hasFooter: true,
shouldShowRebet: false,
isDetailsOpened: false,
handleDetailsButton: noop,
shouldRenderFooter: true,
isBetActive: false,
isWagerCancelable: false,
repeatButtonSearch: "",
showRepeatButton: false,
renderRunnerSelection: null,
showScratchedNotification: false,
shouldNotHideScratchNotification: false,
setShouldNotHideScratchNotification: noop,
scratchedTitle: "",
scratchedLegText: "",
onCancelWager: noop,
handleRebetClickEvent: noop,
rebetWagerTypeName: "",
rebetSearch: "",
qaLabel: "my-bets-wager",
hasContentMaxHeight: false,
isMyBetsOpen: false,
betsNumber: 1,
isCardBodyScrollable: false,
isScratchInfoDesign: false,
showMinMaxWillPays: false,
minWillPays: 0,
maxWillPays: 0,
renderPromoOnboarding: null,
isFDR: false
};
export default MyBetsWager;
webpack://frontend-mybets/../../packages/sh-lib-promos-onboarding/utils/matchWagerPropositions.ts
import { get, find } from "lodash";
import { parseISO, isSameDay } from "date-fns";
import { WagerTypeCodesEnum } from "@tvg/ts-types/Wager";
import { RaceTypeCodeEnum } from "@tvg/ts-types/Race";
import type { PromoOnboardingStep } from "../types/promoSteps";
import type { MyBetsWager } from "../types/wager";
export const validateWagerPlaced = (serialNumber: string) => !!serialNumber;
export const validateTrackCode = (promoTrackCode: string, trackCode: string) =>
promoTrackCode === "ALL" || promoTrackCode === trackCode;
export const validateTypeCode = (
promoWagerTypeCode: WagerTypeCodesEnum,
wagerTypeCode: WagerTypeCodesEnum | null
) => promoWagerTypeCode === wagerTypeCode;
export const validateRaceNumber = (
promoRaceNumber: number,
raceNumber: number
) => promoRaceNumber === 0 || promoRaceNumber === raceNumber;
export const validateBettingInterest = (
promoBettingInterest: number,
bettingInterests: number[]
) => {
if (promoBettingInterest === 0) {
return true;
}
return bettingInterests.includes(promoBettingInterest);
};
export const validateRaceDate = (
promoRaceDate: string | null,
raceDate: string
) =>
promoRaceDate === null ||
isSameDay(parseISO(promoRaceDate), parseISO(raceDate));
export const validateBreedType = (
promoRaceTypeCode: RaceTypeCodeEnum,
raceTypeCode: RaceTypeCodeEnum | null
) =>
promoRaceTypeCode === RaceTypeCodeEnum.ALL ||
promoRaceTypeCode === raceTypeCode;
export const matchWagerPropositions = (
step: PromoOnboardingStep,
wager: Partial<MyBetsWager>
) => {
const isWagerPlaced = validateWagerPlaced(get(step, "serialNumber", ""));
if (isWagerPlaced) {
return false;
}
const propositions = get(step, "wagerPropositions", []);
const matchProposition = find(propositions, (proposition) => {
const {
trackCode,
wagerTypeCode,
raceNumber,
bettingInterest,
raceDate,
breedTypeCode
} = proposition;
const isTrackCodeValid = validateTrackCode(
trackCode,
get(wager, "trackCode", "")
);
const isTypeCodeValid = validateTypeCode(
wagerTypeCode,
get(wager, "wagerTypeCode", null)
);
const isRaceNumberValid = validateRaceNumber(
raceNumber,
get(wager, "raceNumber", 0)
);
const isBettingInterestValid = validateBettingInterest(
bettingInterest,
get(wager, "bettingInterests", [])
);
const isRaceDateValid = validateRaceDate(
raceDate,
get(wager, "raceDate", "")
);
const isBreedTypeCodeValid = validateBreedType(
breedTypeCode,
get(wager, "breedTypeCode", null)
);
return (
isTrackCodeValid &&
isTypeCodeValid &&
isRaceNumberValid &&
isBettingInterestValid &&
isRaceDateValid &&
isBreedTypeCodeValid
);
});
return !!matchProposition;
};
webpack://frontend-mybets/../../node_modules/date-fns/esm/isSameDay/index.js
import startOfDay from '../startOfDay/index.js';
import requiredArgs from '../_lib/requiredArgs/index.js';
/**
* @name isSameDay
* @category Day Helpers
* @summary Are the given dates in the same day?
*
* @description
* Are the given dates in the same day?
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} dateLeft - the first date to check
* @param {Date|Number} dateRight - the second date to check
* @returns {Boolean} the dates are in the same day
* @throws {TypeError} 2 arguments required
*
* @example
* // Are 4 September 06:00:00 and 4 September 18:00:00 in the same day?
* var result = isSameDay(new Date(2014, 8, 4, 6, 0), new Date(2014, 8, 4, 18, 0))
* //=> true
*/
export default function isSameDay(dirtyDateLeft, dirtyDateRight) {
requiredArgs(2, arguments);
var dateLeftStartOfDay = startOfDay(dirtyDateLeft);
var dateRightStartOfDay = startOfDay(dirtyDateRight);
return dateLeftStartOfDay.getTime() === dateRightStartOfDay.getTime();
}
webpack://frontend-mybets/../../packages/tvg-comp-my-bets-standalone/src/MyBetsWager.jsx
import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState
} from "react";
import { get, isEmpty, noop } from "lodash";
import { connect } from "react-redux";
import useScratchNotification from "@tvg/sh-lib-my-bets/hooks/useScratchNotification";
import {
getFeatureUseTvgPotReturn,
getIsMyBetsOpen,
getPickBetRebetToggle,
getSelectedSettledTab,
getSelectedTab,
getTodayActiveCounter,
getTodaySettledCounter,
getMyBetsTrackRulesToggle,
getSocialShareToggle
} from "@tvg/sh-lib-my-bets/redux/selectors";
import { calculateShowBetsDetailedView } from "@tvg/sh-lib-my-bets/utils/betsBetCard";
import {
getRaceStatus,
shouldShowWillPays,
isPickBetSub
} from "@tvg/sh-lib-my-bets/utils/raceDetails";
import {
getFavoriteRunnerByLeg,
getScratchedLegNumbersIndex,
stringifySelections
} from "@tvg/sh-lib-my-bets/utils/pickBets";
import usePickBetRebet from "@tvg/sh-lib-my-bets/hooks/usePickBetRebet";
import {
expandCollapseLegGtm,
onApproxPayoutModalGtm,
onHideShowLegsGTM,
showTrackRulesGtm
} from "@tvg/sh-lib-my-bets/utils/gtm";
import {
checkAllDetailedViewIsOpen,
getSelectionLabel,
getWagerProps,
handleDetailsButton,
setShowContent
} from "@tvg/sh-lib-my-bets/utils/general";
import MyBetsWagerOrganism from "@tvg/atomic-ui/_organism/MyBetsWager";
import {
BetCard,
BetCardBody
} from "@tvg/atomic-ui/_organism/MyBetsWager/styled-components";
import MyBetsRunnerNumberGroup from "@tvg/atomic-ui/_molecule/MybetsRunnerNumberGroup";
import PromosOnboarding from "@tvg/promos-onboarding";
import useSelections from "@tvg/sh-lib-my-bets/hooks/useSelections";
import useMinMaxWillPays from "@tvg/sh-lib-my-bets/hooks/useMinMaxWillPays";
import useResults from "@tvg/sh-lib-my-bets/hooks/useResults";
import {
getStoryblokPromoByStep,
getStoryblokPromos
} from "@tvg/sh-lib-promos-onboarding/redux/selectors";
import { matchWagerPropositions } from "@tvg/sh-lib-promos-onboarding/utils/matchWagerPropositions";
import { matchPlacedWager } from "@tvg/sh-lib-promos-onboarding/utils/matchPlacedWager";
import { isFDR } from "@tvg/utils/generalUtils";
import { PromoStepType } from "@tvg/sh-lib-promos-onboarding/types/promoSteps";
export const MyBetsWager = (props) => {
const {
dispatch,
wager,
mainWagerDetails,
index,
useTvgPotReturnToggle,
selectedTab,
selectedSettledTab,
races,
raceNumber,
statusCode,
betAmount,
bettingInterests,
currentRaceDate,
allRacesFromTrack,
enablePickBetRebet,
modalScrollableRef,
activeBetsCounter,
settledBetsCounter,
closeModal,
raceUrl,
showContentObj,
setShowContentObj,
currentRace,
currentOpenLeg,
hasFooter,
onCancelWager,
hasDetails,
legStatusCode,
hasContentMaxHeight,
isKey,
isBox,
isMyBetsOpen,
isBetPlaced,
isBetConfirmation,
isInsideRaceOfficials,
betsNumber,
isDesktop,
myBetsTrackRulesToggle,
promosOnboardingObject,
promosOnboardingStep,
onShareWager,
socialShareModalToggle
} = props;
const {
wagerBetStatus,
isCurrentRaceDate,
isCanceled,
isActive,
currentWagerTypeCode,
isWagerCancelable,
isMultiRace,
isPickBet,
isExotic,
isBetWinner,
isOptedIn,
isWheel
} = getWagerProps(
wager,
legStatusCode || statusCode,
currentRaceDate,
get(mainWagerDetails, 0, ""),
currentRace
);
const selectionSize = get(wager, "selections.selection.length", 0);
const finalBettedLeg = currentRace
? +get(currentRace, "number", "0") + (selectionSize - 1)
: 0;
const betResults = [];
const betRefund = get(wager, "betRefund", 0);
const betStatusName = wagerBetStatus.name;
const betStatusCode = wagerBetStatus.code;
const betProbableValue = get(wager, "probable", "0");
if (allRacesFromTrack && allRacesFromTrack.length > 0 && raceNumber) {
for (let j = +raceNumber - 1; j < +raceNumber + selectionSize - 1; j += 1) {
if (allRacesFromTrack[j] && allRacesFromTrack[j].results) {
betResults.push(allRacesFromTrack[j].results);
}
}
}
const showWillPays =
currentRace && allRacesFromTrack && isMultiRace && betResults && !isCanceled
? shouldShowWillPays(
allRacesFromTrack,
wager.selections.selection,
betResults,
finalBettedLeg
)
: false;
const results = useResults({
allRacesFromTrack
});
const selections = useSelections({
wager,
isMultiRace,
raceNumber,
currentRace,
currentRaceDate,
finalBettedLeg,
showWillPays,
allRacesFromTrack,
currentWagerTypeCode,
isActive,
results,
isExotic
});
const hasAlternate = useMemo(() => {
return selections.some((selectionGroup) =>
selectionGroup.some((s) => !!s.alternate)
);
}, [selections]);
const { minWillPays, maxWillPays, showMinMaxWillPays } =
useMinMaxWillPays(selections);
const betCardRef = useRef(null);
const betCardBodyRef = useRef(null);
const [showBetsDetailedView, setShowBetsDetailedView] = useState(
calculateShowBetsDetailedView(selections, showWillPays)
);
const isCardBodyScrollable =
betCardBodyRef.current &&
betCardBodyRef.current.scrollHeight > betCardBodyRef.current.clientHeight;
// Scroll betCard inToView
const handleScrollPosition = useCallback(() => {
if (
betCardRef.current &&
modalScrollableRef &&
typeof betCardRef.current.scrollIntoView === "function" &&
typeof betCardRef.current.getBoundingClientRect === "function"
) {
setTimeout(() => {
// this headerOffset is based on modal header height + plus Tab height and or plus the timeframe height
const headerOffset = selectedTab === "SETTLED" ? 164 : 96;
const betCardBoundingClientRect =
betCardRef.current.getBoundingClientRect();
const screenHeight =
get(window, "innerHeight") ||
get(document, "documentElement.clientHeight", 0);
const isBetCardVisible =
betCardBoundingClientRect.top >= headerOffset &&
betCardBoundingClientRect.bottom <= screenHeight;
if (!isBetCardVisible) {
modalScrollableRef.scrollTo({
top: betCardRef.current.offsetTop - headerOffset,
behavior: "smooth"
});
}
}, 0);
}
}, [showBetsDetailedView]);
const [favoriteRunnerByLeg, setFavoriteRunnerByLeg] = useState([]);
const [autoOpenedWillPays, setAutoOpenedWillPays] = useState(false);
const hasLostOneLeg = useCallback(
() =>
selections.some(
(leg) =>
leg.some((sel) => sel.isWinner || sel.isWinner === null) === false
),
[selections]
);
const shouldShowPotentialReturn =
useTvgPotReturnToggle &&
!showWillPays &&
!hasLostOneLeg() &&
betProbableValue !== "0";
const shouldShowHideLegButton =
isMultiRace &&
hasLostOneLeg() &&
selectedTab === "ACTIVE" &&
!shouldShowPotentialReturn &&
!isInsideRaceOfficials;
const isDetailsOpened = checkAllDetailedViewIsOpen(showBetsDetailedView);
const hadScratchedRunner = getScratchedLegNumbersIndex(selections);
const [shouldRenderFooter, setShouldRenderFooter] = useState(true);
const repeatButtonSearch = useCallback(() => {
const newSelectionsWithoutScratch = selections.map((selection) =>
selection.reduce((accSelection, currSelection) => {
const runners = get(currSelection, "runners") || [];
if (runners.some((runner) => !runner.isScratched)) {
accSelection.push(currSelection);
}
return accSelection;
}, [])
);
return `?race=${raceNumber}&wt=${currentWagerTypeCode}&bet=${
wager.wagerAmount
}${stringifySelections(newSelectionsWithoutScratch)}&type=Repeat`;
}, [
currentWagerTypeCode,
raceNumber,
JSON.stringify(selections),
wager.wagerAmount
]);
useEffect(() => {
const willPaysFetched =
currentOpenLeg &&
!!get(
allRacesFromTrack,
`[${+currentOpenLeg.number - 1}].willPays`,
false
);
if (
!showBetsDetailedView.length ||
!get(showBetsDetailedView, "[0].length", true)
) {
setShowBetsDetailedView(
calculateShowBetsDetailedView(selections, showWillPays)
);
} else if (showWillPays && willPaysFetched && !autoOpenedWillPays) {
const newDetailedView = showBetsDetailedView.map(
(leg, legIndex) => legIndex === showBetsDetailedView.length - 1 || leg
);
setAutoOpenedWillPays(true);
setShowBetsDetailedView(newDetailedView);
}
}, [selectedTab, selections, showWillPays]);
useEffect(() => {
if (allRacesFromTrack) {
setFavoriteRunnerByLeg(
getFavoriteRunnerByLeg(
selections,
allRacesFromTrack,
+raceNumber,
wager.raceDate
)
);
}
}, [allRacesFromTrack, selections]);
useEffect(() => {
if (get(wager, "betStatus.code") === "R") {
const isCancelDataOpen = statusCode === "O";
const isCancelDataUpNext = statusCode === "IC";
setShouldRenderFooter(isCancelDataOpen || isCancelDataUpNext);
}
}, []);
useEffect(() => {
setShowBetsDetailedView(Array(selections.length).fill(false));
}, [showContentObj]);
const [
showScratchedNotification,
shouldNotHideScratchNotification,
setShouldNotHideScratchNotification,
scratchedTitle,
scratchedLegText
] = useScratchNotification({
selections,
isPickBet,
betStatusCode,
favoriteRunnerByLeg,
currentWagerTypeCode,
isCurrentRaceDate,
betRefund
});
const defaultScratchedText = "Scratch occurred.";
const [
handleRebetClickEvent,
rebetWagerTypeName,
rebetSearch,
shouldShowRebet
] = usePickBetRebet({
allRacesFromTrack,
mainWagerDetails,
currentRace,
currentOpenLeg,
callback: closeModal,
selections,
enablePickBetRebet,
isPickBet,
isCurrentRaceDate,
isSettledBet: selectedTab === "SETTLED"
});
const showRepeatButton =
!shouldShowRebet &&
!isWheel &&
(wager.cancelable ||
betStatusName === "canceled" ||
betStatusName === "active") &&
raceNumber &&
closeModal &&
raceUrl &&
betAmount !== undefined &&
(statusCode === "O" || statusCode === "IC") &&
selectedTab !== "FUTURES" &&
hadScratchedRunner.length === 0;
const renderedRunnerGroup = useCallback(() => {
return selections.map((selection, indexSelection, { length }) => {
const { key, label, pickBetsLabelLength } = getSelectionLabel({
selectionIndex: indexSelection,
selectionLength: length,
raceNumber: +raceNumber,
selectionsModifier: get(wager, "selections.modifier"),
isMultiRace,
isKey,
isBox,
isDesktop
});
const isAllRunnersScratched = selection.every((runner) =>
runner.runners.every((r) => r.isScratched)
);
const legContainsScratch = selection.some((runner) =>
runner.runners.every((r) => r.isScratched)
);
const betBettingInterests = [];
if (bettingInterests && bettingInterests.length > 0 && raceNumber) {
if (!isMultiRace) {
betBettingInterests.push(
get(
allRacesFromTrack.find((race) => +race.number === +raceNumber),
"bettingInterests",
bettingInterests[+raceNumber - 1]
)
);
} else {
for (
let i = isBetConfirmation ? 0 : +raceNumber;
i < +raceNumber + selectionSize;
i += 1
) {
const raceArrayIterator = isBetConfirmation ? i : i - 1;
if (bettingInterests[raceArrayIterator]) {
betBettingInterests.push(
get(
allRacesFromTrack.find((race) => +race.number === i),
"bettingInterests",
bettingInterests[raceArrayIterator]
)
);
}
}
}
}
const resultsIndex = isMultiRace ? indexSelection : 0;
const currentBettingInterestsLength = get(
betBettingInterests,
`${resultsIndex}.length`,
0
);
const allRunnersSelected =
currentBettingInterestsLength === selection.length;
const favoriteRunner = get(
favoriteRunnerByLeg,
indexSelection,
undefined
);
const allowsPickBetSub =
currentWagerTypeCode && isPickBetSub(currentWagerTypeCode);
const selectionRaceStatus = getRaceStatus({
isAllRunnersScratched,
legContainsScratch,
selection,
selectionIndex: indexSelection,
races: allRacesFromTrack,
raceNumber,
selectionLength: length,
isMultiRace,
isCanceled,
betStatusName,
wagerType: currentWagerTypeCode,
favoriteRunner,
shouldShowReplacement: allowsPickBetSub
});
const isBetRefund =
get(wager, "betRefund", 0) > 0 &&
(betStatusName === "winner" || betStatusName === "refunded");
const sortedSelection = selection.sort(
(a, b) => +a.runnerNumber - +b.runnerNumber
);
return (
<MyBetsRunnerNumberGroup
key={`runner-group${indexSelection.toString()}${get(
wager,
"id",
"unk"
)}`}
runners={sortedSelection}
raceTypeCode={wager.raceTypeAbbreviation}
isMultiRace={isMultiRace}
isExotic={isExotic}
isBetsStandalone
isBetsDetailedView={get(showBetsDetailedView, indexSelection, false)}
isKey={key}
label={label}
showHorizontalRule={length !== indexSelection + 1}
isFirstRowOfRunners={indexSelection === 0}
isLastRowOfRunners={indexSelection === length - 1}
wagerTypeCode={currentWagerTypeCode}
onDetailedView={() => {
const isOpened = get(showBetsDetailedView, indexSelection, false);
expandCollapseLegGtm(
isOpened ? "Closed Leg" : "Opened Leg",
indexSelection + 1,
selectedTab,
selectedSettledTab,
activeBetsCounter,
settledBetsCounter
);
setShowBetsDetailedView((prevShowedBets) => {
const updatedShowedBet = [...prevShowedBets];
updatedShowedBet[indexSelection] =
!prevShowedBets[indexSelection];
return updatedShowedBet;
});
}}
allRunnersSelected={allRunnersSelected}
hasDetails={hasDetails}
raceStatus={selectionRaceStatus}
betStatusName={betStatusName}
isPickBet={isPickBet}
isCanceled={isCanceled}
pickBetsLabelLength={pickBetsLabelLength}
favoriteRunner={favoriteRunner}
isCurrentRaceDate={isCurrentRaceDate}
isBetRefund={isBetRefund}
/>
);
});
}, [
selections,
raceNumber,
wager,
isMultiRace,
races,
raceNumber,
isCanceled,
betStatusName,
favoriteRunnerByLeg,
showBetsDetailedView,
currentWagerTypeCode,
selectedTab,
selectedSettledTab,
activeBetsCounter,
settledBetsCounter,
isPickBet,
isCurrentRaceDate,
isKey,
isBox
]);
const promosOnboardingProps = useMemo(() => {
const biNumbers = bettingInterests.reduce((previous, current) => {
return [...previous, ...(current || []).map((bi) => bi.biNumber)];
}, []);
const wagerData = {
bettingInterests: biNumbers,
raceNumber: currentRace.number,
breedTypeCode: get(wager, "raceTypeAbbreviation", ""),
raceDate: get(currentRace, "raceDate", ""),
trackCode: get(currentRace, "trackCode", ""),
wagerTypeCode: get(wager, "wagerType.code", ""),
serialNumber: get(wager, "serialNumber", "")
};
if (isBetConfirmation) {
const placeToRender = isBetPlaced
? "betslip_placed"
: "betslip_confirmation";
const shouldShowPromoOnboarding = promosOnboardingStep
? matchWagerPropositions(promosOnboardingStep, wagerData)
: false;
return { placeToRender, shouldShowPromoOnboarding };
}
const shouldShowPromoOnboarding = promosOnboardingStep
? matchPlacedWager(promosOnboardingStep, wagerData)
: false;
return { placeToRender: "bet_ticket", shouldShowPromoOnboarding };
}, [
wager,
currentRace,
isBetPlaced,
bettingInterests,
isBetConfirmation,
promosOnboardingStep
]);
const renderPromoOnboarding = useCallback(() => {
const wagerAmount = get(wager, "betTotal", 0);
const rebateLimit = get(promosOnboardingObject, "rebateLimit", 0);
const amountToShow = wagerAmount > rebateLimit ? rebateLimit : wagerAmount;
const customMessage = `$${amountToShow} in wagering credit will be refunded if you don't win.`;
const { placeToRender, shouldShowPromoOnboarding } = promosOnboardingProps;
return (
<PromosOnboarding
placeToRender={placeToRender}
customMessage={customMessage}
isShown={shouldShowPromoOnboarding}
/>
);
}, [promosOnboardingProps]);
return (
<MyBetsWagerOrganism
key={`wager-${get(wager, "id", index)}`}
wager={wager}
raceUrl={raceUrl}
closeModal={closeModal}
onApproxPayout={() =>
onApproxPayoutModalGtm(dispatch, {
selectedTab,
selectedSettledTab,
activeBetsCount: +activeBetsCounter,
settledBetsCount: +settledBetsCounter
})
}
showTrackRules={() =>
showTrackRulesGtm(
dispatch,
selectedTab,
selectedSettledTab,
currentWagerTypeCode,
hasAlternate
)
}
onHideShowLegsGTM={(isOpening) =>
onHideShowLegsGTM({
isOpening,
activeBets: activeBetsCounter,
settledBets: settledBetsCounter
})
}
showContent={get(showContentObj, wager.id, true)}
setShowContent={(value, id) =>
setShowContent(value, id, showContentObj, setShowContentObj)
}
betCardRef={betCardRef}
betCardBodyRef={betCardBodyRef}
isOptedIn={isOptedIn}
isBetActive={isActive}
betStatus={betStatusName}
isCanceled={isCanceled}
showBetsDetailedView={showBetsDetailedView}
betRefund={betRefund}
isBetWinner={isBetWinner}
probableValue={betProbableValue}
shouldShowHideLegButton={shouldShowHideLegButton}
shouldShowPotentialReturn={shouldShowPotentialReturn}
isDetailsOpened={isDetailsOpened}
handleDetailsButton={() =>
handleDetailsButton(
selectedTab,
selectedSettledTab,
isDetailsOpened,
showBetsDetailedView,
setShowBetsDetailedView,
selections,
handleScrollPosition
)
}
shouldRenderFooter={shouldRenderFooter}
isWagerCancelable={
isPickBet && currentOpenLeg
? isWagerCancelable && +currentOpenLeg.number === +raceNumber
: isWagerCancelable
}
repeatButtonSearch={repeatButtonSearch()}
showRepeatButton={!!showRepeatButton}
renderRunnerSelection={renderedRunnerGroup()}
showScratchedNotification={showScratchedNotification}
shouldNotHideScratchNotification={shouldNotHideScratchNotification}
setShouldNotHideScratchNotification={setShouldNotHideScratchNotification}
scratchedTitle={scratchedTitle}
scratchedLegText={
isInsideRaceOfficials ? defaultScratchedText : scratchedLegText
}
hasFooter={hasFooter}
onCancelWager={() => {
onCancelWager(wager);
}}
shouldShowRebet={shouldShowRebet && !isInsideRaceOfficials}
handleRebetClickEvent={handleRebetClickEvent}
rebetWagerTypeName={rebetWagerTypeName}
rebetSearch={rebetSearch}
hasContentMaxHeight={hasContentMaxHeight}
isMyBetsOpen={isMyBetsOpen}
betsNumber={betsNumber}
isCardBodyScrollable={isCardBodyScrollable}
showMinMaxWillPays={showMinMaxWillPays}
minWillPays={minWillPays}
maxWillPays={maxWillPays}
isScratchInfoDesign={myBetsTrackRulesToggle}
renderPromoOnboarding={renderPromoOnboarding()}
onShareWager={onShareWager}
socialShareModalToggle={socialShareModalToggle && !isInsideRaceOfficials}
isFDR={isFDR()}
/>
);
};
MyBetsWager.defaultProps = {
dispatch: noop,
wager: {},
mainWagerDetails: [],
index: -1,
useTvgPotReturnToggle: false,
selectedTab: "ACTIVE",
selectedSettledTab: "TODAY",
races: [],
raceNumber: 1,
statusCode: "O",
betAmount: 0,
bettingInterests: [],
raceDate: "",
currentRaceDate: "",
allRacesFromTrack: [],
enablePickBetRebet: false,
modalScrollableRef: null,
activeBetsCounter: 0,
settledBetsCounter: 0,
closeModal: noop,
raceUrl: "",
showContentObj: {},
setShowContentObj: noop,
currentRace: {},
currentOpenLeg: null,
hasFooter: false,
onCancelWager: noop,
hasDetails: false,
hasContentMaxHeight: false,
isKey: false,
isBox: false,
isMyBetsOpen: false,
isBetPlaced: false,
isBetConfirmation: false,
isInsideRaceOfficials: false,
betsNumber: 1,
promosOnboardingStep: null,
onShareWager: noop
};
export default connect(
(store) => ({
selectedTab: getSelectedTab(store),
isMyBetsOpen: getIsMyBetsOpen(store),
selectedSettledTab: getSelectedSettledTab(store),
activeBetsCounter: getTodayActiveCounter(store),
settledBetsCounter: getTodaySettledCounter(store),
enablePickBetRebet: getPickBetRebetToggle(store),
useTvgPotReturnToggle: getFeatureUseTvgPotReturn(store),
myBetsTrackRulesToggle: getMyBetsTrackRulesToggle(store),
promosOnboardingObject: getStoryblokPromos(store),
promosOnboardingStep: getStoryblokPromoByStep(store, PromoStepType.WAGER),
socialShareModalToggle: getSocialShareToggle(store)
}),
(dispatch) => ({ dispatch })
)(MyBetsWager);
webpack://frontend-mybets/../../packages/tvg-comp-my-bets-standalone/src/MyBetsBody.jsx
import React, { useEffect, useState } from "react";
import { first, get, last, noop, has } from "lodash";
import { connect } from "react-redux";
import MyBetsCard from "@tvg/atomic-ui/_organism/MyBetsCard";
import {
getFeatureIsMTPNewRules,
getSelectedSettledTab,
getSelectedTab,
getShowSeeResult,
getTodayActiveCounter,
getTodaySettledCounter,
getWatchReplayWithinMyBets,
getIsMyBetsOpen
} from "@tvg/sh-lib-my-bets/redux/selectors";
import {
getActiveLegs,
getRacesInPickBets,
isMultiRaceBet,
getRaceProps
} from "@tvg/sh-lib-my-bets/utils/raceDetails";
import {
getWagerToRender,
scrollActiveBetIntoView,
scrollActivePillIntoView,
shouldRenderWager,
useIsomorphicLayoutEffect
} from "@tvg/sh-lib-my-bets/utils/general";
import {
getVideoFeedback,
onVideoRedirect
} from "@tvg/sh-lib-my-bets/utils/video";
import buildRaceUrl from "@tvg/formatter/url";
import {
cleanBetCancelResult,
openMybetsPastPerformance,
openBetSocialShareModal
} from "@tvg/sh-lib-my-bets/redux/actions";
import {
handleRaceHeaderGtm,
onCancelBetModalGtm
} from "@tvg/sh-lib-my-bets/utils/gtm";
import useAllRacesFromTrack from "@tvg/sh-lib-my-bets/hooks/useAllRacesFromTrack";
import MyBetsWager from "./MyBetsWager";
export const MyBetsBody = (props) => {
const {
dispatch,
selectedTab,
isMyBetsOpen,
bet,
index,
races,
closeModal,
activeBetsCounter,
settledBetsCounter,
currentRaceDate,
selectedSettledTab,
isReplayInsideMyBets,
isMTPNewRules,
modalScrollableRef,
hasWagerFooter,
hasPastPerformance,
showLiveVideo,
showRaceLeg,
hasWagerDetails,
selectedWager,
showSeeResult,
isCancelModal,
indexBuffer,
setIndexBuffer,
isInsideRaceOfficials,
isDesktop
} = props;
const wagers = get(bet, "wagers", []);
const [showContentObj, setShowContentObj] = useState(
wagers.reduce((acc, wager) => {
acc[get(wager, "id")] = true;
return acc;
}, {})
);
useIsomorphicLayoutEffect(() => {
if (indexBuffer) {
scrollActiveBetIntoView(indexBuffer);
setIndexBuffer(0);
}
if (
selectedSettledTab === "LAST_MONTH" ||
selectedSettledTab === "LAST_WEEK"
) {
scrollActivePillIntoView();
}
}, []);
useEffect(() => {
let updateInfo = false;
let auxObj = {};
if (wagers.length > 0) {
auxObj = wagers.reduce((acc, wager) => {
const wagerId = get(wager, "id", 0);
if (!has(showContentObj, wagerId)) {
acc[wagerId] = true;
updateInfo = true;
}
return acc;
}, {});
}
if (updateInfo) {
setShowContentObj({ ...showContentObj, ...auxObj });
}
}, [wagers]);
const mainWagerDetails = get(bet, "value", "||0").split("|");
const [raceDate, trackCode] = mainWagerDetails;
const raceNumber = +get(mainWagerDetails, 2, "0");
const biggestSelectionSize = get(
first(
wagers.sort(
(a, b) => b.selections.selection.length - a.selections.selection.length
)
),
"selections.selection.length",
0
);
const currentRace = races.find(
(race) =>
race.id === `${trackCode}-${raceNumber}` && race.raceDate === raceDate
);
const trackName = get(bet, "wagers[0].trackName");
const racePostTime = get(bet, "wagers[0].racePostTime");
const allRacesFromTrack = useAllRacesFromTrack({ races, trackCode });
const activeRaces =
allRacesFromTrack &&
allRacesFromTrack.length > 0 &&
getActiveLegs(allRacesFromTrack, raceNumber, biggestSelectionSize);
const currentOpenLeg = activeRaces ? first(activeRaces) : null;
const legRaces = getRacesInPickBets(
allRacesFromTrack,
raceNumber,
biggestSelectionSize
);
const bettingInterests = allRacesFromTrack.map(
(race) => race.bettingInterests
);
const dateDiff = Math.round(
(new Date(racePostTime).getTime() - new Date().getTime()) /
(1000 * 3600 * 24)
);
// Removed greyhounds variation since its not being used elsewhere (ex. tracks page, talent picks)
const raceUrl = buildRaceUrl(trackCode, trackName, raceNumber);
const betsNumber = wagers.filter(
(cur) => cur.betStatus.code !== "C" && cur.betStatus.code !== "R"
).length;
const betAmount = wagers.reduce((acc, cur) => {
const currentBetTotal =
cur.betStatus.code !== "C" && cur.betStatus.code !== "R"
? cur.betTotal
: 0;
return acc + currentBetTotal;
}, 0);
const winningsAmount = wagers.reduce(
(acc, cur) => acc + cur.winningsAmount,
0
);
// Check if at least one of the bets are Pick/MultiRace Bets
const isMultiRace = !!wagers
.map((b) => isMultiRaceBet(b.wagerType.code))
.findIndex((b) => b === false);
const isAllBetsCancelled =
!!get(wagers, "length", 0) && wagers.every((b) => b.betStatus.code === "C");
const isSettledBet = selectedTab === "SETTLED";
const isFutureBet = selectedTab === "FUTURES";
let videoFeedback = "NOT_AVAILABLE_NO_REPLAY";
if (isMultiRace && currentOpenLeg && !isSettledBet) {
videoFeedback = getVideoFeedback(
currentOpenLeg,
first(allRacesFromTrack),
last(allRacesFromTrack)
);
} else if (currentRace) {
videoFeedback = getVideoFeedback(
currentRace,
first(allRacesFromTrack),
last(allRacesFromTrack)
);
}
const hasRaceLeg =
isMultiRace && !isSettledBet && currentRace && currentOpenLeg;
const {
mtp,
statusCode,
legStatusCode,
legNumber,
hasLiveVideo,
currentRaceNumber,
raceType
} = getRaceProps({
isMultiRace,
legRaces,
isCancelled: isAllBetsCancelled,
currentRace,
currentLeg: currentOpenLeg,
bet,
isSettledBet,
currentRaceDate,
betDate: raceDate,
videoFeedback,
raceNumber
});
const hasReplayVideo = videoFeedback.indexOf("NO_REPLAY") === -1;
return (
<MyBetsCard
hasPastPerformance={
hasPastPerformance &&
isSettledBet &&
statusCode === "RO" &&
raceType !== "G" &&
(hasReplayVideo || showSeeResult)
}
hasReplayVideo={hasReplayVideo}
showSeeResult={showSeeResult}
hasLiveVideo={showLiveVideo && hasLiveVideo}
legNumber={legNumber}
onVideoRedirect={() =>
onVideoRedirect(closeModal, {
selectedTab,
settledBets: settledBetsCounter,
activeBets: activeBetsCounter,
selectedSettledTab
})
}
showBetInfoHeader={betsNumber > 0 && betAmount > 0}
isFutureBet={isFutureBet}
raceDate={get(bet, "wagers[0].raceDate", "")}
showRaceLeg={showRaceLeg && !!hasRaceLeg}
mtp={mtp}
isRaceNear={mtp <= 5}
dateDiff={dateDiff}
betIndex={`activebet-${index}`}
closeModal={closeModal}
index={index}
onWatchReplay={(showIppInsideMybets = true) => {
handleRaceHeaderGtm("MYBETS_USER_CLICKS_WATCH_REPLAY", {
selectedTab,
selectedSettledTab,
activeBets: activeBetsCounter,
settledBets: settledBetsCounter,
gaEventLabel: hasReplayVideo ? "Watch Replay" : "See Result"
});
if (showSeeResult && showIppInsideMybets) {
const modalTitle = `${trackName} R${raceNumber} - Replay`;
setIndexBuffer(index);
dispatch(
openMybetsPastPerformance(
{
trackCode,
raceNumber,
raceDate
},
modalTitle
)
);
}
}}
isReplayInsideMyBets={isReplayInsideMyBets}
isMTPNewRules={isMTPNewRules}
isMyBetsOpen={isMyBetsOpen}
racePostTime={racePostTime}
trackName={trackName}
legStatusCode={legStatusCode}
statusCode={statusCode}
raceNumber={raceNumber}
raceUrl={raceUrl}
betsNumber={betsNumber}
betAmount={betAmount}
winningsAmount={winningsAmount}
currentRaceNumber={currentRaceNumber}
isSpecialWager={get(bet.wagers[0], "isSpecialWager", false)}
>
{/* Render evert single wager for this specific track */}
{getWagerToRender(wagers, selectedWager).map((wager, wagerIndex) => {
const raceStatus = get(currentRace, "status.code");
const isCancelled =
get(wager, "betStatus.code") === "C" &&
raceStatus !== "O" &&
raceStatus !== "IC";
return (
shouldRenderWager(
selectedTab,
currentRaceDate,
get(wager, "raceDate", "")
) && (
<MyBetsWager
key={`wager-${get(wager, "id", "unk")}-${mainWagerDetails.join(
"-"
)}`}
isDesktop={isDesktop}
index={wagerIndex}
wager={wager}
mainWagerDetails={mainWagerDetails}
races={races}
raceNumber={raceNumber}
statusCode={statusCode}
legStatusCode={legStatusCode}
betAmount={betAmount}
bettingInterests={bettingInterests}
currentRaceDate={currentRaceDate}
allRacesFromTrack={allRacesFromTrack}
modalScrollableRef={modalScrollableRef}
closeModal={closeModal}
raceUrl={raceUrl}
showContentObj={showContentObj}
setShowContentObj={setShowContentObj}
currentRace={currentRace}
currentOpenLeg={currentOpenLeg}
hasFooter={hasWagerFooter && !isCancelled}
hasDetails={hasWagerDetails && !isCancelled}
isMyBetsOpen={isMyBetsOpen}
hasContentMaxHeight={isCancelModal}
onCancelWager={() => {
dispatch(cleanBetCancelResult());
onCancelBetModalGtm(
dispatch,
{
bet,
wager
},
selectedTab,
selectedSettledTab
);
}}
isInsideRaceOfficials={isInsideRaceOfficials}
onShareWager={(repeatButtonSearch) => {
dispatch(
openBetSocialShareModal({
bet,
wager,
repeatButtonSearch,
isMyBets: true
})
);
}}
/>
)
);
})}
</MyBetsCard>
);
};
MyBetsBody.defaultProps = {
dispatch: noop,
selectedTab: "",
isMyBetsOpen: false,
bet: {},
index: -1,
races: [],
closeModal: noop,
activeBetsCounter: 0,
settledBetsCounter: 0,
currentRaceDate: "",
selectedSettledTab: "",
isReplayInsideMyBets: true,
isMTPNewRules: true,
modalScrollableRef: null,
hasWagerFooter: true,
selectedWager: undefined,
hasPastPerformance: true,
showLiveVideo: true,
showRaceLeg: true,
hasWagerDetails: true,
showSeeResult: false,
isCancelModal: false,
isInsideRaceOfficials: false,
isDesktop: false
};
const mapStateToProps = (store) => ({
selectedTab: getSelectedTab(store),
isMyBetsOpen: getIsMyBetsOpen(store),
selectedSettledTab: getSelectedSettledTab(store),
activeBetsCounter: getTodayActiveCounter(store),
settledBetsCounter: getTodaySettledCounter(store),
isMTPNewRules: getFeatureIsMTPNewRules(store),
isReplayInsideMyBets: getWatchReplayWithinMyBets(store),
showSeeResult: getShowSeeResult(store)
});
export default connect(mapStateToProps)(MyBetsBody);
webpack://frontend-mybets/../../packages/tvg-lib-ts-types/Bet.ts
import { Selections } from "./Selections";
import { RaceOdds, RaceTypeCodeEnum } from "./Race";
import { WagerType, WagerTypeCodesEnum } from "./Wager";
import { NullaryFn } from "./Functional";
export interface BIPayouts {
amount: number;
wagerType: {
code: string;
};
}
export enum FeedbackTypeEnum {
ERROR = "error",
WARNING = "warning"
}
export interface BetTicketState {
isProcessing?: boolean;
isBetPlaced?: boolean;
isBettingError?: boolean;
errorBetMessage?:
| string
| { title: string; text: string; buttonType: string; code?: number };
betConfirmationTitle?: string | JSX.Element;
randomTalentPhrase?: string;
randomTalentPhraseId?: number;
repeatBetNumber?: number;
hasFeedback?: boolean;
feedbackType?: FeedbackTypeEnum;
partialFailure?: boolean;
partialInfo?: string;
partialInfoDetails?: string;
feedbackTitle?: string;
feedbackMsg?: string;
}
export interface BetType {
type: WagerType;
group: WagerType;
legCount: number;
isKey: boolean;
isWheel: boolean;
isBox: boolean;
positionCount?: number;
columnCount?: number;
}
export interface SuccessReceipt {
price: number;
serialNumber: string;
}
export interface ErrorReceipt {
code: number;
message: string;
exception: string;
}
export interface BetReceipt {
success?: SuccessReceipt;
error?: ErrorReceipt;
statusCode: number;
}
export enum BetStatusCodesEnum {
ACTIVE = "A",
REFUNDED = "R",
LOSER = "L",
WINNER = "W",
CANCELED = "C"
}
export enum BetStatusNameEnum {
Active = "active",
Refunded = "refunded",
Loser = "loser",
Winner = "winner",
Canceled = "canceled"
}
export interface BetStatus {
code: BetStatusCodesEnum;
name: string;
}
export interface runnerSelection {
runnerId: string;
saddleColor: string;
numberColor: string;
}
export interface Selection {
selectionType: string;
runners: runnerSelection[];
}
export enum ExoticBetEnum {
WIN = "WN",
PLACE = "PL",
SHOW = "SH",
WIN_PLACE = "WP",
WIN_SHOW = "WS",
PLACE_SHOW = "PS",
WIN_PLACE_SHOW = "WPS",
QUINELLA = "QN",
QUINELLA_BOX = "QNB",
QUINELLA_WHEEL = "QNW",
EXACTA = "EX",
EXACTA_KEY_BOX = "EKB",
EXACTA_BOX = "EXB",
EXACTA_WHEEL = "EXW",
EXACTA_KEY = "EXK",
TRIFECTA = "TR",
TRIFECTA_BOX = "TRB",
TRIFECTA_WHEEL = "TRW",
TRIFECTA_KEY = "TRK",
TRIFECTA_KEY_BOX = "TKB",
SUPERFECTA = "SU",
SUPERFECTA_BOX = "SUB",
SUPERFECTA_KEY = "SUK",
SUPERFECTA_WHEEL = "SUW",
SUPERFECTA_KEY_BOX = "SKB",
SUPER_HIGH_FIVE = "SH5",
SUPER_HIGH_FIVE_WHEEL = "H5W",
SUPER_HIGH_FIVE_KEY = "H5K",
SUPER_HIGH_FIVE_KEY_BOX = "5KB",
OMNI = "OM",
OMNI_BOX = "OMB",
OMNI_WHEEL = "OMW",
TRIO = "TI",
TRIO_BOX = "TIB"
}
export enum PickBetEnum {
DAILY_DOUBLE = "DB",
GRAND_SLAM = "GS",
PICK_3 = "P3",
PICK_4 = "P4",
PICK_5 = "P5",
PICK_6 = "P6",
PICK_7 = "P7",
PICK_8 = "P8",
PICK_9 = "P9",
PICK_10 = "P10",
PICK_ALL_3 = "A3",
PICK_ALL_4 = "A4",
PICK_ALL_5 = "A5",
PICK_ALL_6 = "A6",
PICK_ALL_7 = "A7",
PICK_ALL_8 = "A8",
PICK_ALL_9 = "A9",
PICK_ALL_10 = "A10",
PLACE_PICK_ALL_3 = "L3",
PLACE_PICK_ALL_4 = "L4",
PLACE_PICK_ALL_5 = "L5",
PLACE_PICK_ALL_6 = "L6",
PLACE_PICK_ALL_7 = "L7",
PLACE_PICK_ALL_8 = "L8",
PLACE_PICK_ALL_9 = "L9",
PLACE_PICK_ALL_10 = "L10",
EXACTA_12 = "E12",
SURVIVOR = "SV"
}
export enum BetTypeTutorialsEnum {
WIN = "WN",
PLACE = "PL",
SHOW = "SH",
WIN_PLACE = "WP",
WIN_SHOW = "WS",
PLACE_SHOW = "PS",
WIN_PLACE_SHOW = "WPS",
QUINELLA = "QN",
EXACTA = "EX",
TRIFECTA = "TR",
SUPERFECTA = "SU",
DAILY_DOUBLE = "DB",
PICK_3 = "P3",
PICK_4 = "P4",
PICK_5 = "P5",
PICK_6 = "P6",
PICK_ALL_3 = "A3",
PICK_ALL_4 = "A4",
PICK_ALL_5 = "A5",
PICK_ALL_6 = "A6",
PLACE_PICK_ALL_3 = "L3",
PLACE_PICK_ALL_4 = "L4",
PLACE_PICK_ALL_5 = "L5",
PLACE_PICK_ALL_6 = "L6"
}
export enum BetTypeSeparatorEnum {
MINUS = "-",
COMMA = ","
}
export interface BetRunnerDetails {
runnerId: string;
runnerName: string;
numberColor?: string;
saddleColor?: string;
isScratched: boolean;
isAlternate?: boolean;
}
export interface AlternateBetSelection {
biNumber: number;
runners: BetRunnerDetails[];
currentOdds?: RaceOdds;
isWinner?: boolean | null;
payouts?: BIPayouts[];
}
export interface BetSelection {
runnerNumber: string;
runners: BetRunnerDetails[];
willPayAmount?: number;
currentOdds?: RaceOdds;
isFavorite?: boolean;
isWinner?: boolean | null;
payouts?: BIPayouts[];
alternate?: AlternateBetSelection;
}
export interface VisualSelection {
number: string;
numberColor?: string;
saddleColor?: string;
runnerName?: string;
winner?: boolean;
scratched?: boolean;
willPay?: number;
currentOdds?: RaceOdds;
isSettled?: boolean;
isAlternate?: boolean;
}
export type VisualSelections = Array<VisualSelection>;
export type ScratchedRunnersByLeg = Record<number, Array<BetRunnerDetails>>;
export type SportTitle = "Horse Racing" | "Greyhounds Racing";
export interface MultiLegCreateBetGTM {
runnerAmount: number;
trackName: string;
betAmount: number;
betType: WagerTypeCodesEnum;
repeatBet: number;
sport: SportTitle;
runnerSelectionList: string;
raceNumber: number;
}
export interface PayloadRepeatBetGTM {
gaEventAction?: string;
gaEventLabel: string;
module: string;
}
export type BIRunner = {
runnerId: number;
scratched: boolean;
horseName: string;
};
export type WinnerBI = boolean | null;
export type BettingInterests = {
biNumber: number;
isWinner: WinnerBI;
runners: BIRunner[] | null;
payouts: BIPayouts[];
currentOdds?: RaceOdds;
};
export interface DeleteBetInformation {
raceTypeCode: RaceTypeCodeEnum;
betTotal: number;
wagerAmount: number;
selectionTypeCode: string;
isKey: boolean;
isLeg: boolean;
isPromoQualifying: boolean;
raceNumber: number;
selections: string[][];
errorMessage: string;
hasError: boolean;
canDelete: boolean;
isLoading: boolean;
onCloseCallback: NullaryFn<unknown>;
onCancelBetCallback: NullaryFn<unknown>;
onKeepCallback: NullaryFn<unknown>;
onGotItCallback: NullaryFn<unknown>;
}
export interface BetGroupDetails {
[key: number]: string[];
allSelections: string[][];
}
export interface BetRepeatInfo {
wagerType: WagerType;
selections: {
selection: Array<{
runners: Array<{ number: number }>;
}>;
};
wagerAmount: number;
}
export interface BetBasicInfo {
id?: string;
trackName: string;
raceNumber: number;
raceTypeCode: RaceTypeCodeEnum;
// needed to retro-compatible with myBets!
raceTypeAbbreviation?: RaceTypeCodeEnum;
raceDate: string;
racePostTime: string;
betStatus: BetStatus;
betTotal: number;
wagerAmount: number;
wagerType: WagerType;
wagerReference: string;
serialNumber: string;
betRefund: number;
selections: {
selection: Selections[];
selectionString: string;
modifier?: string | null;
};
isKey: boolean;
isLeg: boolean;
cancelable: boolean;
isCancelled: boolean;
isLost: boolean;
isRefunded: boolean;
totalWinAmount: number | undefined;
}
webpack://frontend-mybets/../../packages/urp-comp-my-bets/components/card/styled-components.ts
import styled from "styled-components";
import type { Theme } from "@tvg/design-system";
export const BetCardWrapper = styled.div`
margin-top: ${({ theme }) => theme.space["space-3"]};
display: flex;
flex-direction: column;
background-color: ${({ theme }) => theme.colorTokens.background.surface};
`;
export const BetCardRaceHeaderContainer = styled.div<{
theme: Theme;
}>`
display: flex;
flex: 1 0 auto;
flex-direction: column;
justify-content: center;
text-decoration: none;
color: ${({ theme }) => theme.colorTokens.content.subtle};
padding: ${({ theme }) => theme.space["space-4"]};
`;
export const WagersList = styled.ul.attrs({
"data-qa-label": "myBets-betTicket-list"
})<{
theme: Theme;
}>`
padding: 0
${({ theme }) => `${theme.space["space-4"]} ${theme.space["space-4"]}`};
`;
webpack://frontend-mybets/../../packages/fdr-lib-shared-actions/video.ts
import axios from "axios";
import { get } from "lodash";
import tvgConf from "@tvg/conf";
import type { Dispatch } from "redux";
import { UnaryFn } from "@tvg/ts-types/Functional";
const config = tvgConf().config();
// Declare existing actions
type GraphRequestFinnishAction = {
type: "GRAPH_REQUEST_FINISH";
};
type GraphRequestPendingAction = {
type: "GRAPH_REQUEST_PENDING";
};
type VideoRequestAction = {
type: "VIDEO_REQUEST_FETCHING";
payload: {
show: boolean;
};
};
export type VideoCloseAction = {
type: "VIDEO_CLOSE";
};
type VideoRequestErrorAction = {
type: "VIDEO_REQUEST_ERROR";
payload: {
show: boolean;
};
};
type VideoRequestSuccesAction = {
type: "VIDEO_REQUEST_SUCCESS";
payload: {
src: {
sd?: string;
hd?: string;
replay?: string;
};
show: boolean;
};
};
type ShowVideoAction = {
type: "VIDEO_OPEN";
payload?: string;
};
export type Actions =
| VideoRequestAction
| VideoCloseAction
| VideoRequestErrorAction
| VideoRequestSuccesAction
| GraphRequestFinnishAction
| ShowVideoAction
| GraphRequestPendingAction;
/**
* Request for hash
* @param {string} streamName Stream Value (required to build the hash)
* @param {string} streamName Replay File Value (required to build the hash)
* @param {number} timestamp Timestamp (unix)
*/
const generateRCNHash = (
streamName: string,
replayFile: string,
timestamp: number
) => {
const requests = [];
if (streamName) {
requests.push(
axios.get(`${config.service.rcn}/generateHash`, {
params: {
streamname: streamName,
timestamp
},
withCredentials: true
})
);
}
if (replayFile) {
requests.push(
axios.get(`${config.service.rcn}/generateHash`, {
params: {
streamname: replayFile,
timestamp
},
withCredentials: true
})
);
}
return Promise.all(requests);
};
const checkResponseLink = (response: { data: { link: string } }) => {
if (
typeof get(response, "data") === "object" &&
typeof get(response, "data.link") === "string"
) {
return {
type: "success",
payload: response.data.link
};
}
return {
type: "error",
payload: response.data
};
};
const requestStreamHTML5 = (
streamName: string,
isReplay: boolean,
timestamp: number,
hash: string,
hd: boolean
): Promise<{ data: { link: string } }> =>
axios.get(
!isReplay
? "//stream.robertsstream.com/streammobile.php"
: "//replays.robertsstream.com/racereplays/replaysmobile.php",
{
params: {
...{
t: timestamp,
h: hash,
usr: "",
forceformat: "ios",
output: "json",
hd: hd ? "1" : "0"
},
...(!isReplay
? {
stream: streamName,
referer: "TVG"
}
: {
race: streamName,
cust: "TVG"
})
}
}
);
/**
* Request HTML5 Stream Link
* @param {string} streamName Stream Name
*/
export const getHTML5Stream = (
streamName: string,
isReplay: boolean,
hash: string,
timestamp: number,
hd: boolean = true
) =>
requestStreamHTML5(streamName, isReplay, timestamp, hash, hd)
.then(checkResponseLink)
.catch((err) => ({
type: "error",
payload: `${err}`
}));
const getStreamRequests = (
streamName: string,
replayFile: string,
timestamp: number,
hashes: { streamHash: string; replayHash: string }
) => {
const requests = [];
if (hashes.streamHash) {
// SD Stream
requests.push(
getHTML5Stream(streamName, false, hashes.streamHash, timestamp, false)
);
// HD Stream
requests.push(
getHTML5Stream(streamName, false, hashes.streamHash, timestamp, true)
);
}
if (hashes.replayHash) {
// SD Replay
requests.push(
getHTML5Stream(replayFile, true, hashes.replayHash, timestamp, false)
);
}
return requests;
};
export const getStreamSrc =
(
streamName: string,
replayFile: string = "",
openModal: boolean = true,
isLive: boolean = false,
onError?: UnaryFn<{ message: string; code: Number }, void>
) =>
(dispatch: Dispatch<Actions>) => {
dispatch({
type: "VIDEO_REQUEST_FETCHING",
payload: {
show: openModal
}
});
const timestamp = Math.floor(Date.now() / 1000);
return generateRCNHash(streamName, replayFile, timestamp)
.then((response) => {
const streamHash =
!!streamName && typeof response[0] !== "undefined"
? get(response, "[0].data.hash", "")
: "";
const replayIndex = streamName ? 1 : 0;
const replayHash =
typeof response[replayIndex] !== "undefined"
? get(response, `[${replayIndex}].data.hash`, "")
: "";
return {
streamHash,
replayHash
};
})
.then((hashes) =>
Promise.all(
getStreamRequests(streamName, replayFile, timestamp, hashes)
)
.then((streams) => {
const error = streams.reduce(
(final, stream) => (stream.type === "error" ? true : final),
false
);
if (error && typeof onError === "function") {
onError(
get(streams, "[0].type") === "error"
? get(streams, "[0].payload")
: get(streams, "[1].payload")
);
}
let src;
if (streamName) {
src = {
sd: isLive
? get(streams, "[1]payload")
: get(streams, "[0]payload"),
hd: isLive
? get(streams, "[1]payload")
: get(streams, "[0]payload"),
replay: get(streams, "[2]payload", null)
};
} else {
src = {
sd: null,
hd: null,
replay: get(streams, "[0]payload", null)
};
}
dispatch({
type: "VIDEO_REQUEST_SUCCESS",
payload: {
src,
show: openModal
}
});
return src;
})
.catch(() => {
dispatch({
type: "VIDEO_REQUEST_ERROR",
payload: {
show: openModal
}
});
})
)
.catch(() => {
dispatch({
type: "VIDEO_REQUEST_ERROR",
payload: {
show: openModal
}
});
});
};
export const closeVideo = () => ({
type: "VIDEO_CLOSE"
});
export const showVideo = (method?: string) => ({
type: "VIDEO_OPEN",
payload: method || "click"
});
webpack://frontend-mybets/../../packages/urp-comp-my-bets/components/card/header/styled-components.ts
import styled, { css } from "styled-components";
import { Link } from "react-router-dom";
import type { Theme } from "@tvg/design-system";
const wrapper = `
display: flex;
justify-content: space-between;
flex: 1;
`;
export const RaceHeaderContainer = styled.div`
display: flex;
flex-direction: column;
`;
export const RaceHeaderWrapper = styled(Link)`
outline: none;
color: inherit;
text-decoration: inherit;
${wrapper}
`;
export const RaceWatchReplayWrapper = styled.div<{
theme: Theme;
}>`
margin-top: ${({ theme }) => theme.space["space-4"]};
${wrapper}
`;
export const LegMtpWrapper = styled.div`
display: flex;
align-items: center;
`;
export const DateWrapper = styled.div`
display: flex;
align-items: center;
`;
export const RaceHeaderInfo = styled.div<{
theme: Theme;
}>`
display: flex;
flex-direction: column;
justify-content: center;
text-decoration: none;
margin-right: ${({ theme }) => theme.space["space-4"]};
overflow: hidden;
`;
export const RaceFeaturedEventName = styled.div<{
theme: Theme;
}>`
${({ theme }) => css`
font-family: ${theme.fonts.bold};
font-size: ${theme.fontSizes.s};
color: ${theme.colorTokens.button.promo.background.active};
`};
`;
export const RaceTrackNameWrapper = styled.div<{
theme: Theme;
}>`
display: flex;
flex-direction: row;
white-space: pre;
${({ theme }) => css`
font-family: ${theme.fonts.bold};
color: ${theme.colorTokens.content.default};
font-size: ${theme.fontSizes.m};
line-height: ${theme.lineHeights.l};
`};
`;
export const RaceTrackName = styled.div`
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
`;
export const RaceTrackNumber = styled.div``;
export const RaceBetsInfo = styled.div<{
theme: Theme;
}>`
${({ theme }) => css`
font-family: ${theme.fonts.regular};
font-size: ${theme.fontSizes.s};
color: ${theme.colorTokens.content.subtle};
margin-top: ${theme.space["space-1"]};
line-height: ${theme.lineHeights.s};
`};
`;
export const RaceHeaderActions = styled.div<{
theme: Theme;
}>`
display: flex;
align-items: center;
> a,
> button {
min-width: 125px;
}
> * {
&:first-child {
margin-left: 0;
}
margin-left: ${({ theme }) => theme.space["space-4"]};
}
`;
export const VideoButtonIconWrapper = styled.span<{
theme: Theme;
}>`
display: flex;
margin-right: ${({ theme }) => theme.space["space-3"]};
`;
export const ButtonLink = styled(Link)`
text-decoration: none;
`;
webpack://frontend-mybets/../../packages/urp-comp-my-bets/components/card/header/mtp/styled-components.ts
import styled from "styled-components"; export const LegMtpWrapper = styled.div` display: flex; align-items: center; `; export const DateWrapper = styled.div` display: flex; align-items: center; `;
webpack://frontend-mybets/../../packages/urp-comp-my-bets/components/card/header/mtp/index.tsx
import React, { useMemo } from "react";
import { formatPeriod, formatPostTime, formatRaceDate } from "@tvg/formatter";
import { Header, Paragraph } from "@tvg/design-system";
import { Mtp } from "@tvg/design-system/web";
import { RaceStatusEnum } from "@tvg/ts-types/Race";
import { useColorTokens } from "@tvg/design-system/web/hooks";
import { DateWrapper, LegMtpWrapper } from "./styled-components";
import type { Props } from "./types";
const HeaderMTP = (props: Props) => {
const {
qaLabel = "mybets-card-header",
showRaceLeg = false,
legNumber = 1,
isFutureBet = false,
raceDate,
racePostTime,
mtp = 60,
statusCode = RaceStatusEnum.OPEN,
dateDiff = 0
} = props;
const colors = useColorTokens();
const renderFullDate = useMemo(
() =>
dateDiff < 0 && (
<Paragraph
qaLabel={`${qaLabel}-full-date`}
fontFamily="regular"
color={colors.content.subtle}
>
{` - ${formatRaceDate(racePostTime)}`}
</Paragraph>
),
[dateDiff, racePostTime]
);
return (
<LegMtpWrapper>
{showRaceLeg && legNumber > 0 && (
<Header
tag="h3"
fontSize="s"
lineHeight="s"
>{`Leg ${legNumber} -`}</Header>
)}
{isFutureBet ? (
<DateWrapper>
<Paragraph
qaLabel={`${qaLabel}-mtp`}
fontFamily="regular"
color={colors.content.subtle}
>
{`${formatPostTime(racePostTime)} `}
</Paragraph>
<Paragraph
qaLabel={`${qaLabel}-full-date`}
fontFamily="regular"
color={colors.content.subtle}
>
{`${formatPeriod(racePostTime)} - ${formatRaceDate(raceDate)}`}
</Paragraph>
</DateWrapper>
) : (
<>
<Mtp
qaLabel={`${qaLabel}-mtp`}
size="xs"
mtp={mtp}
status={statusCode}
postTime={racePostTime}
ml={showRaceLeg && legNumber > 0 ? "space-1" : undefined}
/>
{renderFullDate}
</>
)}
</LegMtpWrapper>
);
};
export default HeaderMTP;
webpack://frontend-mybets/../../packages/urp-comp-my-bets/components/card/header/index.tsx
import React from "react";
import { noop } from "lodash";
import { useDispatch } from "react-redux";
import { Dispatch } from "redux";
import { Link, useNavigate, NavigateFunction } from "react-router-dom";
import formatCurrency from "@tvg/formatter/currency";
import { useTheme } from "@tvg/design-system";
import { Button } from "@tvg/design-system/web";
import { resetBetting } from "@tvg/desktop-bet/src/store/actions";
import { RaceStatusEnum } from "@tvg/ts-types/Race";
import { isFdr } from "@tvg/pp/src/utils/general";
// @ts-ignore
import { showVideo } from "@fdr/shared-actions/video";
import {
RaceHeaderContainer,
RaceHeaderWrapper,
RaceWatchReplayWrapper,
RaceHeaderInfo,
RaceTrackNameWrapper,
RaceTrackName,
RaceTrackNumber,
RaceFeaturedEventName,
RaceBetsInfo,
RaceHeaderActions
} from "./styled-components";
import { Props, ButtonPropsType } from "./types";
import HeaderMTP from "./mtp";
const getBetsInfo = (betAmount: number, bets: number) => {
const betTitle = `Bet${bets > 1 ? "s" : ""}`;
return `${bets} ${betTitle} • ${formatCurrency(betAmount)} staked`;
};
const getButtonProps = (hasReplayVideo: boolean): ButtonPropsType =>
hasReplayVideo
? {
text: "Watch Replay",
type: "primary",
hasIcon: true,
hasShadow: false
}
: {
text: "See Result",
type: "secondary",
hasIcon: false,
hasShadow: true
};
const renderVideoButton = (
raceUrl: string,
currentRaceNumber: number,
showRaceNumber: boolean,
isRaceNear: boolean,
onVideoRedirect: () => void,
dispatch: Dispatch,
navigate: NavigateFunction
) => (
<Button
qaLabel="watch-video-button"
variant={isRaceNear ? "primary" : "secondary"}
icon="video"
onClick={(e) => {
const [racePathname] = raceUrl.split("?");
navigate(
{
pathname: racePathname,
search: `?race=${currentRaceNumber}`
},
{ state: { showVideo: isFdr() } }
);
onVideoRedirect();
dispatch(resetBetting());
if (isFdr()) {
dispatch(showVideo());
}
e.preventDefault();
e.stopPropagation();
}}
>
{` Watch ${showRaceNumber ? `R${currentRaceNumber}` : "Live"}`}
</Button>
);
const renderRedirectReplayButton = (
raceUrl: string,
hasReplayVideo: boolean,
onWatchReplay: (boolean: boolean) => void,
closeModal: () => void,
dispatch: Dispatch,
navigate: NavigateFunction
) => {
const theme = useTheme();
const buttonProps = getButtonProps(hasReplayVideo);
return (
<RaceWatchReplayWrapper theme={theme}>
<Button
qaLabel="watch-video-button"
variant={buttonProps.type}
icon={buttonProps.hasIcon ? "video" : undefined}
onClick={(e) => {
navigate(raceUrl);
onWatchReplay(false);
closeModal();
dispatch(resetBetting());
if (isFdr()) {
dispatch(showVideo());
}
e.preventDefault();
e.stopPropagation();
}}
isStretched={true}
>
{buttonProps.text}
</Button>
</RaceWatchReplayWrapper>
);
};
const renderReplayButton = (
onWatchReplay: () => void,
isReplayInsideMyBets: boolean,
hasReplayVideo: boolean,
raceUrl: string,
showSeeResult: boolean,
closeModal: () => void,
dispatch: Dispatch,
navigate: NavigateFunction
// eslint-disable-next-line consistent-return
) => {
const theme = useTheme();
if (!isReplayInsideMyBets && hasReplayVideo) {
return renderRedirectReplayButton(
raceUrl,
hasReplayVideo,
onWatchReplay,
closeModal,
dispatch,
navigate
);
}
if (showSeeResult || isReplayInsideMyBets) {
const buttonProps = getButtonProps(hasReplayVideo);
return (
<RaceWatchReplayWrapper theme={theme}>
<Button
variant={buttonProps.type}
icon={buttonProps.hasIcon ? "replay" : undefined}
onClick={onWatchReplay}
qaLabel="watch-video-button"
isStretched={true}
>
{buttonProps.text}
</Button>
</RaceWatchReplayWrapper>
);
}
};
const MyBetsCardHeader = ({
racePostTime = "2020-11-04T17:00:00Z",
raceDate,
statusCode = RaceStatusEnum.OPEN,
trackName = "",
eventName = "",
raceNumber = 1,
mtp = 60,
bets = 0,
betAmount = 0,
dateDiff = 0,
raceUrl = "",
closeModal = noop,
onWatchReplay = noop,
hasReplayVideo = false,
hasLiveVideo = false,
showRaceLeg = false,
legNumber = 1,
onVideoRedirect = noop,
isReplayInsideMyBets = true,
showBetInfo = false,
qaLabel = "mybets-card-header",
hasPastPerformance = true,
isRaceNear = false,
currentRaceNumber = 1,
showSeeResult = false,
isMyBetsOpen = false,
hasRepeatBet = false,
onRepeatBet = noop,
isFutureBet = false,
isLoadingGraphs = false,
isSpecialWager = false
}: Props) => {
const theme = useTheme();
const navigate = useNavigate();
const dispatch = useDispatch();
const roundDiff = Math.round(dateDiff);
const shouldRedirectToProgramPage = () => {
if (roundDiff === 0 && isMyBetsOpen && !isFutureBet) {
return true;
}
return roundDiff === 1 && dateDiff < 1 && isMyBetsOpen && !isFutureBet;
};
return (
<RaceHeaderContainer data-qa-label={qaLabel}>
<RaceHeaderWrapper
data-qa-label={`${qaLabel}-details`}
as={shouldRedirectToProgramPage() ? Link : "div"}
to={raceUrl}
onClick={shouldRedirectToProgramPage() ? closeModal : () => {}}
>
<RaceHeaderInfo data-qa-label={`${qaLabel}-info`} theme={theme}>
{!isLoadingGraphs && (
<HeaderMTP
qaLabel={qaLabel}
racePostTime={racePostTime}
legNumber={legNumber}
raceDate={raceDate}
statusCode={statusCode}
mtp={mtp}
showRaceLeg={showRaceLeg}
isFutureBet={isFutureBet}
dateDiff={roundDiff}
/>
)}
{eventName && (
<RaceFeaturedEventName
data-qa-label={`${qaLabel}-event-name`}
theme={theme}
>
{eventName}
</RaceFeaturedEventName>
)}
<RaceTrackNameWrapper
data-qa-label={`${qaLabel}-track-name`}
theme={theme}
>
<RaceTrackName>{trackName}</RaceTrackName>
{raceNumber && !isSpecialWager && (
<RaceTrackNumber>{` R${raceNumber}`}</RaceTrackNumber>
)}
</RaceTrackNameWrapper>
{showBetInfo && (
<RaceBetsInfo data-qa-label={`${qaLabel}-bets-info`} theme={theme}>
{getBetsInfo(betAmount, bets)}
</RaceBetsInfo>
)}
</RaceHeaderInfo>
<RaceHeaderActions
data-qa-label={`${qaLabel}-header-actions`}
theme={theme}
>
{hasLiveVideo &&
renderVideoButton(
raceUrl,
currentRaceNumber,
!!legNumber,
isRaceNear,
onVideoRedirect,
dispatch,
navigate
)}
{hasRepeatBet && (
<Button
onClick={onRepeatBet}
qaLabel="repeat-bet-link"
variant="tertiary"
size="l"
>
Repeat bet
</Button>
)}
</RaceHeaderActions>
</RaceHeaderWrapper>
{hasPastPerformance &&
renderReplayButton(
onWatchReplay,
isReplayInsideMyBets,
hasReplayVideo,
raceUrl,
showSeeResult,
closeModal,
dispatch,
navigate
)}
</RaceHeaderContainer>
);
};
export default MyBetsCardHeader;
webpack://frontend-mybets/../../packages/urp-comp-my-bets/components/card/index.tsx
import React, { forwardRef } from "react";
import { noop } from "lodash";
import { RaceStatusEnum } from "@tvg/ts-types/Race";
import { useTheme } from "@tvg/design-system";
import type { Props } from "./types";
import {
BetCardWrapper,
BetCardRaceHeaderContainer,
WagersList
} from "./styled-components";
import MyBetsCardHeader from "./header";
const MyBetsCard: React.FC<Props> = forwardRef(
(
{
children = null,
dateDiff = 0,
closeModal = noop,
onWatchReplay = noop,
index = -1,
isReplayInsideMyBets = true,
racePostTime = "",
trackName = "",
mtp = 60,
statusCode = RaceStatusEnum.OPEN,
raceNumber = 1,
raceUrl = "",
betsNumber = 0,
betAmount = 0,
hasReplayVideo = false,
hasLiveVideo = false,
onVideoRedirect = noop,
showBetInfoHeader = false,
qaLabel = "mybets-bets-race-card",
showRaceLeg = false,
legNumber = 0,
hasPastPerformance = false,
isRaceNear = false,
currentRaceNumber = 1,
legStatusCode,
showSeeResult = false,
isMyBetsOpen = false,
hasRepeatBet = false,
onRepeatBet = noop,
isFutureBet = false,
raceDate,
isLoadingGraphs = false,
isSpecialWager = false
},
ref
) => {
const theme = useTheme();
return (
<BetCardWrapper
data-qa-label={`${qaLabel}-${index}`}
theme={theme}
id={`activebet-${index}`}
ref={ref}
>
<BetCardRaceHeaderContainer
data-qa-label={`${qaLabel}-header-container`}
theme={theme}
>
<MyBetsCardHeader
showBetInfo={showBetInfoHeader}
racePostTime={racePostTime}
trackName={trackName}
mtp={mtp}
statusCode={legStatusCode || statusCode}
raceNumber={raceNumber}
bets={betsNumber}
betAmount={betAmount}
dateDiff={dateDiff}
raceUrl={raceUrl}
closeModal={closeModal}
onWatchReplay={onWatchReplay}
isReplayInsideMyBets={isReplayInsideMyBets}
hasReplayVideo={hasReplayVideo}
hasLiveVideo={hasLiveVideo}
onVideoRedirect={onVideoRedirect}
showRaceLeg={showRaceLeg}
legNumber={legNumber}
hasPastPerformance={hasPastPerformance}
isRaceNear={isRaceNear}
currentRaceNumber={currentRaceNumber}
showSeeResult={showSeeResult}
isMyBetsOpen={isMyBetsOpen}
hasRepeatBet={hasRepeatBet}
onRepeatBet={onRepeatBet}
isFutureBet={isFutureBet}
raceDate={raceDate}
isLoadingGraphs={isLoadingGraphs}
isSpecialWager={isSpecialWager}
/>
</BetCardRaceHeaderContainer>
<WagersList theme={theme}>{children}</WagersList>
</BetCardWrapper>
);
}
);
export default MyBetsCard;
webpack://frontend-mybets/../../packages/sh-lib-utils/isSafari.ts
export default (allBrowsers: boolean = false) => {
if (
typeof window !== "undefined" &&
window.navigator &&
window.navigator.userAgent
) {
const ua = window.navigator.userAgent;
const iOS =
(!!ua.match(/iPad/i) || !ua.match(/iPhone/i)) && !!ua.match(/WebKit/i);
return (
iOS &&
!!ua.match(/Safari/i) &&
(allBrowsers || !ua.match(/CriOS/i)) &&
(allBrowsers || !ua.match(/Chrome/i))
);
}
return false;
};
export const getDeviceOS = () => {
if (typeof window === "undefined") return undefined;
const { userAgent } = window.navigator;
if (/android/i.test(userAgent)) {
return "android";
}
if (/iPad|iPhone|iPod/.test(userAgent)) {
return "iOS";
}
return undefined;
};
webpack://frontend-mybets/../../packages/urp-comp-my-bets/components/modals/mybets/index.tsx
import React, {
useEffect,
useState,
useCallback,
memo,
useMemo,
Suspense
} from "react";
import { useDispatch, useSelector, shallowEqual } from "react-redux";
import { Modal } from "@tvg/design-system/web";
import mediator from "@tvg/mediator";
import styled from "styled-components";
import {
closeMybetsPastPerformance,
closeMyBetsStandalone
} from "@tvg/sh-lib-my-bets/redux/actions";
import { getHasMyBetsPastPerformanceBack } from "@tvg/sh-lib-my-bets/redux/selectors";
import { useNavigate } from "@tvg/custom-hooks";
import { getIsLogged } from "@urp/store-selectors";
import { getDeviceOS } from "@tvg/sh-utils/isSafari";
import { breakpoints, useMediaQuery } from "@tvg/design-system/src";
import { store } from "@tvg/sh-lib-my-bets/redux/store";
import { SettledTabEnum } from "@tvg/sh-lib-my-bets/utils/types";
import tvgConf from "@tvg/conf";
import type { Props } from "./types";
type RootState = ReturnType<typeof store.getState>;
const MyBetsModalHeader = React.lazy(() => import("./header"));
const MyBetsTopStickyArea = React.lazy(() => import("./topStickyArea"));
const LoadingContainer = styled.div`
height: 100px;
`;
const LoadingFallback = memo(() => <LoadingContainer />);
LoadingFallback.displayName = "LoadingFallback";
const MyBetsModal = memo(
({
currentPath,
isPastPerformanceOpen,
isVideoShown,
title,
selectedTab,
selectedSettledTab,
qaLabel,
isOpen,
children,
onScroll,
onRender
}: Props) => {
const isMobile = useMediaQuery(breakpoints.tablet.max.sm);
const dispatch = useDispatch();
const [enableRender, setEnableRender] = useState(false);
const { isLogged, hasPastPerformanceBack } = useSelector<
RootState,
{ isLogged: boolean; hasPastPerformanceBack: SettledTabEnum }
>(
(state) => ({
isLogged: getIsLogged(state),
hasPastPerformanceBack: getHasMyBetsPastPerformanceBack(state)
}),
shallowEqual
);
const history = useNavigate();
const closeMyBetsModal = useCallback(
(overlayType: string = "") => {
history.push(currentPath);
dispatch(closeMyBetsStandalone());
if (overlayType !== "none") {
mediator.base.dispatch({
type: "MYBETS_CLICKS_X_BUTTON",
payload: {
selectedTab,
selectedSettledTab
}
});
}
},
[currentPath, dispatch, history, selectedTab, selectedSettledTab]
);
const handleClose = useCallback(() => {
closeMyBetsModal("none");
setEnableRender(false);
}, [closeMyBetsModal]);
const handleBack = useCallback(() => {
dispatch(closeMybetsPastPerformance());
}, [dispatch]);
const Header = useMemo(
() => (
<Suspense fallback={<LoadingFallback />}>
<MyBetsModalHeader
title={title}
{...(hasPastPerformanceBack &&
isPastPerformanceOpen && {
onBack: handleBack
})}
onClose={handleClose}
/>
</Suspense>
),
[
title,
hasPastPerformanceBack,
isPastPerformanceOpen,
handleBack,
handleClose
]
);
const TopStickyArea = useMemo(
() => (
<Suspense fallback={<LoadingFallback />}>
<MyBetsTopStickyArea
isPastPerformanceOpen={isPastPerformanceOpen}
showBannerFeedback={!isVideoShown}
/>
</Suspense>
),
[isPastPerformanceOpen, isVideoShown]
);
const insetValue = useMemo(
() =>
isMobile &&
getDeviceOS() === "iOS" &&
typeof window !== "undefined" &&
tvgConf().product === "fdrmobile"
? 120
: undefined,
[isMobile]
);
useEffect(() => {
if (isOpen && !isLogged) {
closeMyBetsModal();
}
}, [isOpen, isLogged, closeMyBetsModal]);
const handleOpen = useCallback(() => {
const timer = setTimeout(() => setEnableRender(true), 300);
return () => clearTimeout(timer);
}, []);
return (
<Modal
customHeader={Header}
onClose={closeMyBetsModal}
isOpen={isOpen || isPastPerformanceOpen}
qaLabel={qaLabel}
stickyAreaExtraContent={TopStickyArea}
p={0}
maxHeight={isVideoShown ? "68%" : undefined}
onScroll={onScroll}
onRender={onRender}
hasMaxHeight={true}
onOpen={handleOpen}
overrideInset={insetValue}
>
{enableRender ? children : null}
</Modal>
);
}
);
MyBetsModal.displayName = "MyBetsModal";
export default MyBetsModal;
webpack://frontend-mybets/../../packages/urp-comp-my-bets/components/modals/wagerCancellationRules/styled-components.ts
import styled from "styled-components";
export const ContentContainer = styled.div`
&:not(:last-child) {
margin-bottom: 18px;
}
`;
webpack://frontend-mybets/../../packages/urp-comp-my-bets/components/pastPerformanceLoading/styled-components.ts
import styled from "styled-components"; export const LoadingWrapper = styled.div` display: flex; height: 100%; width: 100%; justify-content: center; align-items: center; `;
webpack://frontend-mybets/../../packages/urp-comp-my-bets/components/wonIllustration/illustrations.tsx
import React from "react";
import { buildColor } from "@tvg/design-system";
import { LaurelElement } from "./types";
export const Laurel = ({ direction }: LaurelElement) =>
direction === "left" ? (
<svg
width="20"
height="33"
viewBox="0 0 20 33"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M7.47955 0.617188C0.730745 2.59239 4.74955 8.75319 4.74955 8.75319C4.74955 8.75319 9.52555 7.14159 7.47955 0.617188ZM6.79195 16.7296V16.7272C6.98995 16.6408 11.7071 14.5432 10.0943 9.39399C10.0943 9.39399 5.22355 9.72999 6.15835 14.7988C5.34115 12.9232 3.57835 10.2796 0.016745 9.71079C-0.391255 19.72 6.79195 16.7296 6.79195 16.7296ZM12.2771 15.9856C15.5219 21.0376 11.2043 24.3376 11.1191 24.4012C11.0159 24.4864 5.01115 29.368 2.31235 19.7404C5.63275 19.2868 8.07475 20.9464 9.53515 22.408C7.46755 17.59 12.2771 15.9856 12.2771 15.9856ZM16.4603 21.3244C16.4603 21.3244 12.4691 24.4864 16.2719 28.3492C14.1839 27.6292 10.9463 27.106 7.99075 29.1352C15.2903 36.8344 18.4859 29.3632 18.4859 29.3632L18.4847 29.3608C19.1423 27.9784 20.3723 24.2656 16.4603 21.3244Z"
fill={buildColor("green", "500")}
/>
</svg>
) : (
<svg
width="20"
height="33"
viewBox="0 0 20 33"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M11.9523 0.617188C18.7011 2.59239 14.6811 8.75319 14.6811 8.75319C14.6811 8.75319 9.90629 7.14159 11.9523 0.617188ZM12.6387 16.7296L12.6399 16.7272C12.4419 16.6408 7.72469 14.5432 9.33749 9.39399C9.33749 9.39399 14.2071 9.72999 13.2723 14.7988C14.0895 12.9232 15.8523 10.2796 19.4151 9.71079C19.8231 19.72 12.6387 16.7296 12.6387 16.7296ZM7.15349 15.9844C3.90869 21.0376 8.22749 24.3364 8.31149 24.4012C8.41589 24.4864 14.4207 29.368 17.1183 19.7404C13.7991 19.2868 11.3571 20.9464 9.89669 22.408C11.9631 17.59 7.15349 15.9844 7.15349 15.9844ZM2.97029 21.3244C2.97029 21.3244 6.96269 24.4864 3.15989 28.348C5.24789 27.628 8.48429 27.106 11.4411 29.1352C4.14149 36.8344 0.94469 29.3632 0.94469 29.3632L0.947089 29.3608C0.288289 27.9784 -0.940515 24.2656 2.97029 21.3244Z"
fill={buildColor("green", "500")}
/>
</svg>
);
webpack://frontend-mybets/../../packages/urp-comp-my-bets/components/wonIllustration/styled-components.ts
import styled, { css } from "styled-components";
export const Container = styled.div`
position: relative;
display: flex;
align-items: flex-end;
z-index: 2;
justify-content: flex-end;
`;
export const TextContainer = styled.div<{ shouldWrap: boolean }>`
display: flex;
flex-direction: column;
align-items: center;
margin: 0 4px;
${({ shouldWrap }) =>
shouldWrap &&
css`
max-width: min-content;
`};
`;
export const WinAmountContainer = styled.div<{ shouldWrap: boolean }>`
background-color: ${({ theme }) => theme.colorTokens.content.positive};
transform: skew(-15deg);
padding: 0 4px;
text-align: center;
${({ shouldWrap }) =>
!shouldWrap &&
css`
min-width: 90px;
`};
`;
export const WinAmountValue = styled.span`
display: inline-flex;
transform: skew(15deg);
${({ theme }) => css`
font-family: ${theme.fonts.bold};
font-size: ${theme.fontSizes.s};
color: ${theme.colorTokens.background.surface};
`};
`;
export const WinAmountDescriptionWrapper = styled.div`
display: flex;
margin-top: 2px;
align-items: center;
`;
webpack://frontend-mybets/../../packages/urp-comp-my-bets/components/wonIllustration/index.tsx
import React from "react";
import formatCurrency from "@tvg/formatter/currency";
import { Paragraph } from "@tvg/design-system";
import { useColorTokens } from "@tvg/design-system/web/hooks";
import { Laurel } from "./illustrations";
import { WonIllustrationProps } from "./types";
import {
Container,
TextContainer,
WinAmountContainer,
WinAmountDescriptionWrapper,
WinAmountValue
} from "./styled-components";
const MAX_VALUE_FOR_WRAPPING = 1000;
const WonIllustration = ({ qaLabel, winAmount }: WonIllustrationProps) => {
const shouldWrap = winAmount < MAX_VALUE_FOR_WRAPPING;
const colors = useColorTokens();
return (
<Container data-qa-label={qaLabel}>
<Laurel direction="left" data-qa-label={`${qaLabel}-laurel-left`} />
<TextContainer shouldWrap={shouldWrap}>
<WinAmountContainer
data-qa-label={`${qaLabel}-amount-container`}
shouldWrap={shouldWrap}
>
<WinAmountValue data-qa-label={`${qaLabel}-amount-container`}>
{formatCurrency(winAmount || 0)}
</WinAmountValue>
</WinAmountContainer>
<WinAmountDescriptionWrapper>
<Paragraph
qaLabel={`${qaLabel}-text`}
fontFamily="regular"
fontSize="xs"
lineHeight="xs"
fontWeight={700}
textAlign="center"
color={colors.content.positive}
textTransform="uppercase"
>
Won on fanduel
</Paragraph>
</WinAmountDescriptionWrapper>
</TextContainer>
<Laurel direction="right" data-qa-label={`${qaLabel}-laurel-right`} />
</Container>
);
};
export default WonIllustration;
webpack://frontend-mybets/../../packages/urp-comp-my-bets/components/emptyState/styled-components.ts
import styled from "styled-components";
import type { Theme } from "@tvg/design-system";
export const EmptyCase = styled.div<{
theme: Theme;
}>`
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
width: 100%;
padding: ${({ theme }) => theme.space["space-4"]};
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Tooltip/styled-components.ts
import styled from "styled-components";
import { compose, variant } from "styled-system";
const styles = compose(
variant({
prop: "variant",
variants: {
dark: {
backgroundColor: "var(--fd-colors-brand-secondary-shade)"
},
light: {
backgroundColor: "var(--fd-colors-core-white)"
}
}
})
);
export const Content = styled.div<{ variant: string }>`
${styles};
border-radius: 8px;
padding: 12px;
margin: 4px;
box-shadow: 0 2px 4px 0 rgba(10 10 10 / 10%);
justify-content: center;
white-space: nowrap;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Tooltip/index.tsx
import React, { FC } from "react";
import { Content as StyledContent } from "./styled-components";
import type { TooltipProps, TooltipContentProps } from "./types";
import { Popper } from "../Popper";
import { Paragraph } from "../Typography";
export const Tooltip: FC<TooltipProps> = ({
children,
content,
placement = "top-mid",
isDisabled = false,
isDarkMode = false,
qaLabel,
layer = 1999,
isLeftSideRendered,
...rest
}) => (
<Popper
on="hover"
placement={placement}
isDisabled={isDisabled}
layer={layer}
isLeftSideRendered={isLeftSideRendered}
content={
<StyledContent
data-qa-label={qaLabel}
variant={isDarkMode ? "light" : "dark"}
{...rest}
>
<Paragraph
color={isDarkMode ? "content.default" : "--fd-colors-core-white"}
qaLabel="tooltip-text"
fontSize="xs"
>
{content}
</Paragraph>
</StyledContent>
}
>
{children}
</Popper>
);
export type { TooltipProps, TooltipContentProps };
export default Tooltip;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/IconButton/styled-components.ts
import styled, { css } from "styled-components";
import { compose, space, variant } from "styled-system";
import type { IconButtonProps, OverrideColorsProps } from "./types";
export const iconButtonSizes = {
s: {
width: "32px",
height: "32px",
minWidth: "32px",
minHeight: "32px",
padding: "6px",
borderRadius: "16px"
},
m: {
width: "44px",
minWidth: "44px",
height: "44px",
minHeight: "44px",
padding: "12px",
borderRadius: "22px"
},
l: {
width: "48px",
height: "48px",
minWidth: "48px",
minHeight: "48px",
padding: "14px",
borderRadius: "24px"
}
};
const buttonStyles = compose(
space,
variant({ prop: "size", variants: iconButtonSizes })
);
export const StyledButton = styled.button<
Partial<IconButtonProps> & { colors: OverrideColorsProps }
>`
display: flex;
align-items: center;
justify-content: center;
border-radius: var(--fd-radii-border-radius-010);
background: ${({ colors }) => `var(${colors.default})`};
transition: all 0.15s ease-in-out;
${({ hasBorder }) =>
hasBorder &&
`
border: 1px solid var(--fd-colors---core-white-tint-020);
box-shadow: 0px 1px 3px rgba(17,43,68,0.12);`}
& svg path {
stroke: ${({ colors }) => `var(${colors.iconColor})`};
}
&:hover {
${({ forceActive, colors }) =>
!forceActive &&
css`
background: var(${colors.hover});
& svg path {
stroke: var(${colors.iconHoverColor});
}
`}
}
&:active {
background: ${({ colors }) => `var(${colors.active})`};
& svg path {
stroke: ${({ colors }) => `var(${colors.iconActiveColor})`};
}
}
${({ forceActive, colors }) =>
forceActive &&
css`
background: var(${colors.active});
& svg path {
stroke: var(${colors.iconActiveColor});
}
`}
&:disabled {
background: ${({ colors }) => `var(${colors.disabled})`};
& svg path {
stroke: ${({ colors }) => `var(${colors.iconDisabledColor})`};
}
}
cursor: pointer;
${buttonStyles}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/IconButton/types.ts
import { ButtonHTMLAttributes } from "react";
import { type SpaceProps } from "styled-system";
import { IconSizeVariants } from "../../theme";
import { type IconNames } from "../Icon/types";
import { PopperPlacement } from "../../../src/index";
export type IconButtonSize = "s" | "m" | "l";
export const defaultColors: OverrideColorsDefault = {
light: {
default: "--fd-colors-component-button-transparent-background-base",
hover: "--fd-colors-component-button-transparent-background-hover",
active: "--fd-colors-component-button-transparent-background-active",
disabled: "--fd-colors-component-button-destructive-background-disabled",
iconColor: "--fd-colors-content-strong",
iconActiveColor: "--fd-colors-component-button-transparent-content-base",
iconHoverColor: "--fd-colors-component-button-tertiary-content-hover",
iconDisabledColor:
"--fd-colors-component-button-destructive-content-disabled"
},
dark: {
default: "--fd-colors-component-button-transparent-background-base",
hover: "--fd-colors-component-button-transparent-background-hover",
active: "--fd-colors-core-white-tint-030",
disabled: "--fd-colors-core-white-tint-005",
iconColor: "--fd-colors-component-button-transparent-content-base",
iconDisabledColor: "--fd-colors-core-white-tint-050"
}
};
export interface OverrideColorsDefault {
light: {
default: string;
hover: string;
active: string;
disabled?: string;
iconColor?: string;
iconActiveColor?: string;
iconHoverColor?: string;
iconDisabledColor?: string;
};
dark: {
default: string;
hover: string;
active: string;
disabled?: string;
iconColor?: string;
iconActiveColor?: string;
iconHoverColor?: string;
iconDisabledColor?: string;
};
}
export interface OverrideColorsProps {
default: string;
hover: string;
active: string;
disabled?: string;
iconColor?: string;
iconActiveColor?: string;
iconHoverColor?: string;
iconDisabledColor?: string;
}
export interface IconButtonProps
extends SpaceProps,
ButtonHTMLAttributes<HTMLButtonElement> {
/**
* Button size
* s/m/l
* @default m
*/
size?: IconButtonSize;
/**
* IconButton size
* s/m/l/xl
* @default m
*/
iconSize?: IconSizeVariants;
/**
* Custom icon
*/
iconName?: IconNames;
/**
* Custom tooltip text
*/
textTooltip?: string;
/**
* Custom tooltip placement
* only for textTooltip
*/
placementTooltip?: PopperPlacement;
/**
* Disables the icon button
*/
isDisabled?: boolean;
/**
* Custom data-qa-label attribute applied to element
* */
qaLabel: string;
/**
* light/dark mode
*/
mode?: "light" | "dark";
/**
* Override colors for different variants
*/
overrideColors?: OverrideColorsProps;
/**
* Force to active
*/
forceActive?: boolean;
/**
* Has border
*/
hasBorder?: boolean;
}
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/IconButton/utils.ts
import { defaultColors, type OverrideColorsProps } from "./types";
export const computeColors = (
overrideColors: OverrideColorsProps | undefined,
mode: "light" | "dark"
) =>
overrideColors
? {
...defaultColors[mode as keyof typeof defaultColors],
...overrideColors
}
: defaultColors[mode as keyof typeof defaultColors];
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/IconButton/index.tsx
import React from "react";
import { Tooltip } from "../Tooltip";
import { type IconButtonProps } from "./types";
import { StyledButton } from "./styled-components";
import { Icon } from "../Icon";
import { computeColors } from "./utils";
import {
secondaryDarkOverride,
tertiaryOverride,
secondaryOverride,
bettingOverride,
primaryOverride
} from "./constants";
export const IconButton = ({
size = "l",
iconSize = "m",
iconName = "arrowLeft",
placementTooltip = "bottom-mid",
textTooltip = "",
qaLabel,
isDisabled,
onClick,
mode = "light",
overrideColors,
hasBorder,
...rest
}: IconButtonProps) => {
const colors = computeColors(overrideColors, mode);
const button = (
<StyledButton
size={size}
textTooltip={textTooltip || undefined}
disabled={isDisabled}
onClick={(e) => {
if (onClick) onClick(e);
e.preventDefault();
e.stopPropagation();
}}
data-qa-label={qaLabel}
mode={mode}
colors={colors}
hasBorder={hasBorder}
{...rest}
>
<Icon
name={iconName}
size={iconSize}
lineColor="--fd-colors-content-strong"
backgroundColor="transparent"
qaLabel="button-icon"
/>
</StyledButton>
);
return textTooltip ? (
<Tooltip
qaLabel="tooltip"
content={textTooltip}
placement={placementTooltip}
isDarkMode={mode === "dark"}
isDisabled={isDisabled}
>
{button}
</Tooltip>
) : (
button
);
};
export type { IconButtonProps };
export {
secondaryDarkOverride,
secondaryOverride,
bettingOverride,
tertiaryOverride,
primaryOverride
};
export default IconButton;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Tag/style.themes.ts
export const TAG_THEME_VARIANTS = {
neutral: {
color: "--fd-colors-system-neutral-content-accent",
backgroundColor: "--fd-colors-system-neutral-background-subtle",
iconName: "bets"
},
info: {
color: "--fd-colors-system-info-content-accent",
backgroundColor: "--fd-colors-system-info-background-subtle",
iconName: "info"
},
positive: {
color: "--fd-colors-system-positive-content-accent",
backgroundColor: "--fd-colors-system-positive-background-subtle",
iconName: "optedIn"
},
alert: {
color: "--fd-colors-system-alert-content-accent",
backgroundColor: "--fd-colors-system-alert-background-subtle",
iconName: "promo"
},
warning: {
color: "--fd-colors-system-warning-content-accent",
backgroundColor: "--fd-colors-system-warning-background-subtle",
iconName: "warning"
},
favorite: {
color: "--fd-colors-content-on-light",
backgroundColor: "--fd-colors-brand-tertiary-default",
iconName: undefined
}
} as const;
export const TAG_THEME_SIZES = {
small: {
fontSize: "12px",
padding: "0 6px",
paddingOnlyIcon: undefined,
height: "16px "
},
medium: {
fontSize: "14px",
padding: "0 6px",
paddingOnlyIcon: undefined,
height: "20px"
},
large: {
fontSize: "16px",
padding: "0 6px",
paddingOnlyIcon: "0 4px",
height: "24px"
}
} as const;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Tag/styled-components.ts
import styled, { css } from "styled-components";
import { margin } from "styled-system";
import { TAG_THEME_VARIANTS, TAG_THEME_SIZES } from "./style.themes";
import type { TagProps, TagSize } from "./types";
export const TagContainer = styled.div<
Pick<TagProps, "variant" | "label" | "size">
>`
align-items: center;
align-content: center;
background-color: var(
${({ variant }) =>
TAG_THEME_VARIANTS[variant as TagProps["variant"]].backgroundColor}
);
border-radius: 12px;
display: flex;
gap: 4px;
height: ${({ size }) => TAG_THEME_SIZES[size as TagSize].height};
justify-content: center;
white-space: nowrap;
max-height: ${({ size }) => TAG_THEME_SIZES[size as TagSize].height};
padding: ${({ size, label }) =>
label === undefined && size === "large"
? TAG_THEME_SIZES[size as TagSize].paddingOnlyIcon
: TAG_THEME_SIZES[size as TagSize].padding};
${margin}
`;
export const TagLabel = styled.span<TagProps>`
color: var(
${({ variant }) => TAG_THEME_VARIANTS[variant as TagProps["variant"]].color}
);
font-family: "RobotoCondensed-Regular", sans-serif;
font-size: ${({ size }) => TAG_THEME_SIZES[size as TagSize].fontSize};
font-style: normal;
font-weight: 400;
max-height: max-content;
text-transform: uppercase;
${({ isEllipsed }) =>
isEllipsed &&
css`
overflow: hidden;
text-overflow: ellipsis;
`}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Tag/index.tsx
import React, { type FC } from "react";
import { Icon, type IconNames } from "../Icon";
import { TagContainer, TagLabel } from "./styled-components";
import { TAG_THEME_VARIANTS } from "./style.themes";
import type { TagProps } from "./types";
export const Tag: FC<TagProps> = ({
variant,
size = "medium",
label,
iconName,
qaLabel = "tag",
hideIcon = false,
isEllipsed = false,
...props
}) => (
<TagContainer
data-qa-label={`${qaLabel}`}
variant={variant}
size={size}
label={label}
{...props}
>
{size !== "small" && !hideIcon && variant !== "favorite" && (
<Icon
size="s"
lineColor={TAG_THEME_VARIANTS[variant as TagProps["variant"]].color}
name={
iconName ||
(TAG_THEME_VARIANTS[variant as TagProps["variant"]]
.iconName as IconNames)
}
/>
)}
{label && (
<TagLabel
data-qa-label={`${qaLabel}-label`}
variant={variant}
size={size}
isEllipsed={isEllipsed}
>
{label}
</TagLabel>
)}
</TagContainer>
);
export type { TagProps };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Saddle/styled-components.ts
import styled, { css } from "styled-components";
import { space } from "styled-system";
import { SaddleProps } from "./types";
import { Paragraph } from "../Typography";
const hexToRgba = (hexCode = "#fff", opacity = 1) => {
let hex = hexCode.replace("#", "");
if (hex.length === 3) {
hex = `${hex[0]}${hex[0]}${hex[1]}${hex[1]}${hex[2]}${hex[2]}`;
}
const r = parseInt(hex.substring(0, 2), 16);
const g = parseInt(hex.substring(2, 4), 16);
const b = parseInt(hex.substring(4, 6), 16);
return `rgba(${r},${g},${b},${opacity})`;
};
export const StyledSaddle = styled.div<
Pick<
SaddleProps,
| "all"
| "saddleColor"
| "fullHeight"
| "isScratched"
| "size"
| "raceFinished"
| "enableMyBetsBehavior"
| "isWinner"
| "showAlternateIcon"
>
>`
align-items: center;
background-color: ${({
saddleColor,
isScratched,
isWinner,
raceFinished,
enableMyBetsBehavior
}) =>
isScratched || (enableMyBetsBehavior && raceFinished && !isWinner)
? `${hexToRgba(saddleColor, 0.4)}`
: saddleColor};
border-radius: 2px;
display: flex;
justify-content: center;
position: relative;
${({ isScratched, enableMyBetsBehavior }) =>
isScratched &&
enableMyBetsBehavior &&
css`
box-shadow: inset 0 0 0 2px var(--fd-colors-core-grey-d-2);
`}
${({ showAlternateIcon }) =>
showAlternateIcon &&
css`
& > svg {
position: absolute;
top: -8px;
right: -8px;
z-index: 2;
}
`}
${({ size, fullHeight, all }) => {
if (fullHeight && size !== "s") {
return css`
flex-grow: 1;
height: 100%;
width: 32px;
`;
}
if (all === true && size === "s") {
return css`
width: 44px;
height: 20px;
`;
}
return css`
height: ${size === "s" ? "20px" : "44px"};
width: ${size === "s" ? "20px" : "32px"};
`;
}}
${space};
${({ isWinner }) =>
isWinner &&
css`
&::after {
content: "";
position: absolute;
top: 12px;
left: 12px;
width: 12px;
height: 12px;
z-index: 2;
background-image: url("data:image/svg+xml,%3Csvg width='12' height='12' viewBox='0 0 12 12' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M11.438 6.00219C11.438 9.00537 9.00342 11.4399 6.00024 11.4399C2.99706 11.4399 0.5625 9.00537 0.5625 6.00219C0.5625 2.99901 2.99706 0.564453 6.00024 0.564453C9.00342 0.564453 11.438 2.99901 11.438 6.00219Z' fill='%23128000'/%3E%3Cpath d='M3.37527 6.0001L5.25027 7.8751L9.00027 4.1251M11.438 6.00219C11.438 9.00537 9.00342 11.4399 6.00024 11.4399C2.99706 11.4399 0.5625 9.00537 0.5625 6.00219C0.5625 2.99901 2.99706 0.564453 6.00024 0.564453C9.00342 0.564453 11.438 2.99901 11.438 6.00219Z' stroke='white'/%3E%3C/svg%3E ");
}
`};
`;
export const DiagonalLine = styled.div`
position: absolute;
width: 24px;
height: 2px;
background-color: var(--fd-colors-core-grey-d-2);
top: calc(50% - 1px);
left: -2px;
transform: rotate(135deg);
z-index: 1;
`;
export const StyledParagraph = styled(Paragraph)<
Pick<
SaddleProps,
| "size"
| "isScratched"
| "isWinner"
| "raceFinished"
| "enableMyBetsBehavior"
>
>`
font-family: ${({ size }) =>
size === "s"
? `${'"Roboto-Regular", sans-serif'}`
: `${'"Roboto-Bold", sans-serif'}`};
font-size: ${({ size }) => (size === "s" ? "12px" : "18px")};
text-align: center;
line-height: ${({ size }) => (size === "s" ? "15px" : "22px")};
opacity: ${({ isScratched, isWinner, raceFinished, enableMyBetsBehavior }) =>
isScratched || (enableMyBetsBehavior && raceFinished && !isWinner)
? 0.4
: 1};
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Saddle/consts.ts
import type { SaddleColors } from "./types";
export const SADDLE_COLORS: SaddleColors = {
thoroughbred: {
"1": { numberColor: "#FFFFFF", saddleColor: "#C20E0E" },
"2": { numberColor: "#000000", saddleColor: "#BCC8C8" },
"3": { numberColor: "#FFFFFF", saddleColor: "#3B4E8C" },
"4": { numberColor: "#000000", saddleColor: "#D3B13C" },
"5": { numberColor: "#FFFFFF", saddleColor: "#116410" },
"6": { numberColor: "#FFFFFF", saddleColor: "#303030" },
"7": { numberColor: "#000000", saddleColor: "#D65A2F" },
"8": { numberColor: "#000000", saddleColor: "#E095AA" },
"9": { numberColor: "#000000", saddleColor: "#2AAAA5" },
"10": { numberColor: "#FFFFFF", saddleColor: "#713A98" },
"11": { numberColor: "#FFFFFF", saddleColor: "#6B6B6B" },
"12": { numberColor: "#000000", saddleColor: "#4EA958" },
"13": { numberColor: "#FFFFFF", saddleColor: "#58514D" },
"14": { numberColor: "#FFFFFF", saddleColor: "#94335A" },
"15": { numberColor: "#FFFFFF", saddleColor: "#69522F" },
"16": { numberColor: "#FFFFFF", saddleColor: "#4C6E9F" },
"17": { numberColor: "#FFFFFF", saddleColor: "#373786" },
"18": { numberColor: "#FFFFFF", saddleColor: "#285F23" },
"19": { numberColor: "#FFFFFF", saddleColor: "#32496D" },
"20": { numberColor: "#FFFFFF", saddleColor: "#671334" }
},
harness: {
"1": { numberColor: "#FFFFFF", saddleColor: "#AF0000" },
"2": { numberColor: "#FFFFFF", saddleColor: "#253C85" },
"3": { numberColor: "#000000", saddleColor: "#B2B4B1" },
"4": { numberColor: "#FFFFFF", saddleColor: "#1C5B1B" },
"5": { numberColor: "#FFFFFF", saddleColor: "#252525" },
"6": { numberColor: "#000000", saddleColor: "#B69E00" },
"7": { numberColor: "#000000", saddleColor: "#B27492" },
"8": { numberColor: "#FFFFFF", saddleColor: "#6B6B6B" },
"9": { numberColor: "#FFFFFF", saddleColor: "#610F9A" },
"10": { numberColor: "#FFFFFF", saddleColor: "#263D88" },
"11": { numberColor: "#FFFFFF", saddleColor: "#3B5E90" },
"12": { numberColor: "#FFFFFF", saddleColor: "#A90000" },
"13": { numberColor: "#FFFFFF", saddleColor: "#1D5E1C" },
"14": { numberColor: "#FFFFFF", saddleColor: "#725933" },
"15": { numberColor: "#FFFFFF", saddleColor: "#C0C0C0" }
}
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Saddle/index.tsx
import React, { FC, memo } from "react";
import { get } from "lodash";
import { Icon } from "../Icon";
import {
StyledSaddle,
StyledParagraph,
DiagonalLine
} from "./styled-components";
import {
SaddleProps,
Breed,
HarnessVariation,
ThoroughbredVariation,
SaddleColor
} from "./types";
import { SADDLE_COLORS } from "./consts";
const getRunnerColors = (
runnerNumber: number | string,
breed: Breed = "thoroughbred"
): SaddleColor => {
const runnerNumberInt =
typeof runnerNumber === "string"
? parseInt(runnerNumber, 10)
: runnerNumber;
const breedFilter = get(SADDLE_COLORS, `[${breed}]`) ? breed : "thoroughbred";
const { numberColor, saddleColor } = get(
SADDLE_COLORS,
`[${breedFilter}][${runnerNumberInt}]`,
get(
SADDLE_COLORS,
breedFilter === "harness"
? `[${breedFilter}][15]`
: `[${breedFilter}][20]`
)
);
return {
numberColor,
saddleColor
};
};
export const Saddle: FC<SaddleProps> = memo(
({
all,
number,
qaLabel,
numberColor,
saddleColor,
fullHeight,
size,
isWinner = false,
breed = "thoroughbred",
isScratched = false,
raceFinished = false,
enableMyBetsBehavior = false,
showAlternateIcon = false,
...rest
}) => {
const saddleNumber =
typeof number === "number" ? number.toString() : number;
const defaultColors = getRunnerColors(number, breed);
const runnerColors: SaddleColor = {
numberColor: numberColor || defaultColors.numberColor,
saddleColor: saddleColor || defaultColors.saddleColor
};
return (
<StyledSaddle
data-qa-label={qaLabel || `saddle-container-${number}`}
all={all}
saddleColor={all ? "#C6D3E1" : runnerColors.saddleColor}
fullHeight={fullHeight}
size={size}
isScratched={isScratched}
raceFinished={raceFinished}
enableMyBetsBehavior={enableMyBetsBehavior}
isWinner={isWinner}
showAlternateIcon={showAlternateIcon}
{...rest}
>
{isScratched && size === "s" && enableMyBetsBehavior && (
<DiagonalLine />
)}
{showAlternateIcon && (
<Icon
name="doubleChevronLeftRight"
color="--fd-colors-content-on-dark"
backgroundColor="--fd-colors-content-on-dark"
size="s"
lineColor="--fd-colors-content-on-light"
/>
)}
<StyledParagraph
fontFamily="bold"
fontSize="s"
color={all ? "#0A0A0A" : runnerColors.numberColor}
textTransform={all ? "capitalize" : "none"}
qaLabel="saddle-number"
size={size}
isScratched={isScratched}
isWinner={isWinner}
raceFinished={raceFinished}
enableMyBetsBehavior={enableMyBetsBehavior}
>
{all ? saddleNumber.toLowerCase() : saddleNumber}
</StyledParagraph>
</StyledSaddle>
);
}
);
export default Saddle;
export { SADDLE_COLORS, getRunnerColors };
export type { SaddleProps, Breed, HarnessVariation, ThoroughbredVariation };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/SaddleSelections/utils.ts
import { ParagraphFonts } from "../Typography";
import type { Selection } from "./types";
export const findCoupledRunners = (selections: Selection[], target: string) => {
const match = target.match(/^(\d+)/);
if (!match) return [];
return selections.filter((item) => {
const itemMatch = item.number.match(/^(\d+)([A-Z]*)$/);
return itemMatch && itemMatch[1] === match[1];
});
};
export const groupCoupledRunners = (selections: Selection[]) => {
const getBase = (num: string) => num.replace(/[A-Z]$/, "");
const groups = selections.reduce((acc, sel) => {
if (!sel.isAlternate) {
const base = getBase(sel.number);
if (/^\d+$/.test(base)) {
const group = acc.get(base) ?? [];
group.push(sel.number);
acc.set(base, group);
}
}
return acc;
}, new Map<string, string[]>());
return Array.from(groups.values()).filter((group) => group.length > 1);
};
export const shouldSkipAlternate = (
selections: Selection[],
scratches: string[],
alternateNumber: string,
wagerDetails: boolean,
showReplacedRunners: boolean
) => {
let shouldSkip = false;
const altInfo = selections.reduce(
(acc, s) => {
if (s.isAlternate) {
acc.total += +1;
if (scratches.includes(s.number)) {
acc.scratches += 1;
}
}
return acc;
},
{
total: 0,
scratches: 0
} as Record<string, number>
);
const mainCoupledRunners = groupCoupledRunners(selections);
const mainScratches = selections.filter(
(s) => !s.isAlternate && scratches.includes(s.number)
);
const everyMainCoupledScratched = mainScratches.every((s) => {
const baseNumber = s.number.match(/^(\d+)/)?.[1];
if (!baseNumber) return true;
const coupled = findCoupledRunners(selections, baseNumber);
return coupled.every((c) => scratches.includes(c.number));
});
if (mainCoupledRunners.length === 0 && mainScratches.length > 0) {
shouldSkip = true;
}
if (mainCoupledRunners.length > 0 && mainScratches.length > 0) {
shouldSkip =
everyMainCoupledScratched ||
mainScratches.length !== mainCoupledRunners.length;
}
if (altInfo.total !== altInfo.scratches && wagerDetails) {
shouldSkip =
mainScratches.length > 0 &&
everyMainCoupledScratched &&
!scratches.includes(alternateNumber);
}
if (altInfo.total === altInfo.scratches || !showReplacedRunners) {
shouldSkip = false;
}
return shouldSkip;
};
export const rangeSelections = (
selections: Selection[],
scratches: string[],
wagerDetails: boolean,
enableMyBetsBehavior: boolean,
showReplacedRunners: boolean,
showAllSaddle: boolean
) =>
selections
.reduce((ranges: string[][], curr: Selection) => {
const allSelections =
showAllSaddle &&
!wagerDetails &&
(scratches.length === 0 ||
scratches.every(
(item) => selections.find((sel) => sel.number === item)?.isAlternate
));
if (allSelections && !ranges.flat().includes("all")) {
ranges.push(["all"]);
}
if (curr.isAlternate) {
const shouldSkip = shouldSkipAlternate(
selections,
scratches ?? [],
curr.number,
wagerDetails,
showReplacedRunners
);
if (shouldSkip) {
return ranges;
}
}
const lastSubArray: string[] = ranges[ranges.length - 1];
const prevCurr = (+curr.number - 1).toString();
const nextCurr = +curr.number + 1;
const lastSubArrayChar = lastSubArray?.[lastSubArray?.length - 1]; // 4A or 4
const prevArr = lastSubArrayChar?.match(/[a-zA-Z]+|[0-9]+/g); // ["4","A"] or ["4"]
const isPrevCoupledRunner = prevArr && prevArr?.length > 1;
if (
(curr.winner && enableMyBetsBehavior) ||
!lastSubArray ||
scratches.includes(curr.number) ||
scratches.includes(prevCurr) ||
(isPrevCoupledRunner &&
(+curr.number - 1).toString() !== prevArr?.[0]) ||
(!isPrevCoupledRunner &&
lastSubArray[lastSubArray.length - 1] !== prevCurr &&
!Number.isNaN(+curr.number)) ||
Number.isNaN(nextCurr)
) {
if (!curr.isAlternate && !allSelections) {
ranges.push([]);
}
}
if (curr.isAlternate && !ranges.flat().includes("|")) {
if (!wagerDetails && selections.every((item) => item.isAlternate)) {
ranges.push(["?"]);
}
ranges.push(["|"]);
}
if (!allSelections) {
if (curr.isAlternate) {
ranges.push([curr.number]);
} else {
ranges[ranges.length - 1].push(curr.number);
}
} else if (curr.isAlternate) {
ranges.push([curr.number]);
}
return ranges;
}, [])
.map((range: string[]) => {
if (range.length > 2 && !wagerDetails) {
return [range[0], range[range.length - 1]].join("-");
}
return range;
});
export const saddleRowQaLabel = (
item: string,
isAlternate: boolean | undefined
) => {
if (item === "-" || item === "|" || item === "?") {
return undefined;
}
if (item === "all") {
return "all-saddle-row";
}
return isAlternate ? "alternate-saddle-row" : "main-saddle-row";
};
export const getRunnerNameDetails = ({
item,
scratches = [],
showReplacedRunners = false,
coupledRunners,
replacedRunners,
currentSaddleSelection
}: {
item: string;
scratches?: string[];
showReplacedRunners?: boolean;
coupledRunners: Selection[];
replacedRunners: Selection[];
currentSaddleSelection?: Selection;
}) => {
const isScratched = scratches.includes(item);
const isCoupledScratched =
showReplacedRunners &&
coupledRunners.length > 1 &&
!!currentSaddleSelection &&
coupledRunners.some(
(sel, idx) =>
idx !== 0 &&
sel.number === currentSaddleSelection.number &&
scratches.includes(sel.number)
);
const shouldBeSubtleColor =
currentSaddleSelection?.isSettled ||
(isScratched &&
(!showReplacedRunners ||
currentSaddleSelection?.isAlternate ||
isCoupledScratched));
const shouldBeScratched =
isScratched &&
(!showReplacedRunners ||
currentSaddleSelection?.isAlternate ||
isCoupledScratched);
const showReplacementName =
showReplacedRunners &&
isScratched &&
(coupledRunners.length === 1 ||
(coupledRunners.every((sel) => scratches.includes(sel.number)) &&
/^\d+$/.test(item))) &&
!currentSaddleSelection?.isAlternate;
const isWinner = showReplacementName
? replacedRunners.some((r) => r.winner)
: !currentSaddleSelection?.isAlternate && currentSaddleSelection?.winner;
const replacementNames = replacedRunners
.filter((r) => !scratches.includes(r.number))
.map((r) => r.runnerName)
.join(" / ");
const currentOdds = showReplacementName
? replacedRunners.find((r) => r.winner)?.currentOdds
: currentSaddleSelection?.currentOdds;
return {
showReplacementName,
currentOdds: isWinner ? currentOdds : undefined,
fontFamily: (isWinner ? "medium" : "regular") as ParagraphFonts,
color: shouldBeSubtleColor
? "--fd-colors-content-subtle"
: "--fd-colors-content-default",
scratched: shouldBeScratched,
displayName: showReplacementName
? replacementNames
: currentSaddleSelection?.runnerName ?? ""
};
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/SaddleSelections/styled-components.ts
import styled, { css } from "styled-components";
import { Paragraph } from "../Typography";
export const SelectionsContainer = styled.div`
display: flex;
flex-flow: row;
row-gap: var(--fd-space-space-1);
flex-shrink: 0;
`;
export const SaddleSelectionContainer = styled.div<{
isDetailView: boolean;
}>`
display: flex;
column-gap: var(--fd-space-space-1);
${({ isDetailView }) =>
isDetailView
? "flex-direction: column"
: css`
flex-direction: row;
align-items: center;
flex-wrap: wrap;
`};
row-gap: var(--fd-space-space-3);
width: 100%;
`;
export const ColumnContainer = styled.div`
display: flex;
flex-flow: row;
column-gap: var(--fd-space-space-1);
`;
export const RowContainer = styled.div<{
isDetailView: boolean;
showReplacedRunners?: boolean;
}>`
align-items: center;
${({ isDetailView }) =>
isDetailView
? `display: grid;
column-gap: var(--fd-space-space-1);
row-gap: var(--fd-space-space-3);
grid-template-columns: min-content 1fr min-content;`
: "display: flex; flex-direction: row; column-gap: var(--fd-space-space-1);"}
`;
export const AlternatePlaceholder = styled.div`
display: flex;
align-items: center;
column-gap: var(--fd-space-space-1);
margin-left: var(--fd-space-space-1);
`;
export const AlternateDivider = styled.div<{ isDark: boolean }>`
height: 12px;
width: 1px;
background-color: ${({ isDark }) =>
isDark
? `var(--fd-colors-content-on-dark)`
: `var(--fd-colors-content-subtle)`};
`;
export const IconContainer = styled.div<{
isDetailView?: boolean;
}>`
align-items: center;
flex-direction: row;
height: 20px;
width: 20px;
position: relative;
`;
export const SaddleDetailsParagraph = styled(Paragraph)<{
scratched?: boolean;
}>`
margin-left: var(--fd-space-space-1);
text-decoration: ${({ scratched }) => (scratched ? "line-through" : "none")};
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/SaddleSelections/index.tsx
import React, { useCallback, useMemo } from "react";
import formatCurrency from "@tvg/formatter/currency";
import { get } from "lodash";
import { Saddle } from "../Saddle";
import { Icon } from "../Icon";
import { Paragraph } from "../Typography";
import { Tag } from "../Tag";
import {
findCoupledRunners,
rangeSelections,
saddleRowQaLabel,
getRunnerNameDetails
} from "./utils";
import type { SaddleSelectionsCompProps, Selection } from "./types";
import {
SelectionsContainer,
SaddleSelectionContainer,
RowContainer,
ColumnContainer,
IconContainer,
SaddleDetailsParagraph,
AlternatePlaceholder,
AlternateDivider
} from "./styled-components";
export const SaddleSelections = ({
numWagerableRunners,
selections,
isDark,
scratches,
wagerDetails = false,
shouldShowRefundTag,
breed = "thoroughbred",
qaLabel = "saddle-selections-container",
onHandicaping,
hideWillPaysTag = false,
enableMyBetsBehavior = false,
showOdds,
favoriteRunner,
showReplacedRunners,
raceStatus,
showAlternatePlaceholder = false
}: SaddleSelectionsCompProps) => {
const saddleSelections =
selections?.length > 0
? selections.sort((a, b) => {
if (b.isAlternate !== a.isAlternate) {
return b.isAlternate ? -1 : 1;
}
return (
parseInt(a.number.toString(), 10) -
parseInt(b.number.toString(), 10)
);
})
: [];
const alternateSelections = useMemo(
() =>
saddleSelections
.filter((selection) => selection.isAlternate)
.sort((a, b) => {
const aScratched = scratches?.includes(a.number);
const bScratched = scratches?.includes(b.number);
if (aScratched === bScratched) return 0;
return aScratched ? 1 : -1;
}),
[saddleSelections, scratches]
);
const hasScratches = scratches && scratches.length > 0;
const hasWinner = saddleSelections.some((selection) => selection.winner);
const hasWillPays = saddleSelections.some((selection) => selection.willPay);
const isAlternatesScratched = alternateSelections.every((item) =>
scratches?.includes(item.number)
);
const checkSaddleSelection = useCallback(
(runnerNumber: string) =>
saddleSelections.find(
(saddleSelection) => saddleSelection.number === runnerNumber
),
[saddleSelections, hasWinner, hasScratches, hasWillPays]
);
const replacedRunners = useMemo(() => {
if (alternateSelections.length > 0 && !isAlternatesScratched) {
return alternateSelections;
}
return [
{
...favoriteRunner,
number: get(favoriteRunner, "runnerNumber"),
winner: get(favoriteRunner, "isWinner")
} as Selection
];
}, [alternateSelections, isAlternatesScratched, favoriteRunner]);
const isAllSelections = !!(
numWagerableRunners &&
Number(numWagerableRunners) ===
saddleSelections.length - alternateSelections.length &&
!wagerDetails
);
const isSaddleNumber = !isAllSelections && saddleSelections.length > 0;
const rangedSelections: string[] = useMemo(
() =>
rangeSelections(
saddleSelections,
scratches ?? [],
wagerDetails,
enableMyBetsBehavior,
!!showReplacedRunners,
!!(!hasWinner && !isSaddleNumber && !onHandicaping)
)
.join()
.split(/(-)/)
.join()
.split(",")
.filter((item) =>
wagerDetails ? item !== "|" && item !== "" : item !== ""
),
[
wagerDetails,
saddleSelections,
scratches,
showReplacedRunners,
enableMyBetsBehavior,
hasWinner,
isSaddleNumber,
onHandicaping
]
);
const isSaddleScratched = useCallback(
(currentSelection: Selection) =>
scratches?.includes(currentSelection.number) ||
(!enableMyBetsBehavior &&
hasWinner &&
currentSelection?.winner === false),
[hasWinner, scratches]
);
const isRaceFinished = useCallback(
(currentSelection: Selection) => {
const allScratched = saddleSelections.length === scratches?.length;
const currentNotWinner = hasWinner && !currentSelection.winner;
const myBetsRaceFinished =
enableMyBetsBehavior &&
(["lost", "win"].includes(raceStatus ?? "") ||
(raceStatus === "attention" && !currentSelection.isAlternate));
return allScratched || currentNotWinner || myBetsRaceFinished;
},
[saddleSelections, hasWinner, scratches, raceStatus, enableMyBetsBehavior]
);
return (
<SelectionsContainer data-qa-label={qaLabel}>
<SaddleSelectionContainer isDetailView={wagerDetails}>
{rangedSelections.length === 0 && (
<Saddle
number="?"
size="s"
saddleColor="var(--fd-colors-core-white-tint-020)"
numberColor="var(--fd-colors-core-white)"
enableMyBetsBehavior={enableMyBetsBehavior}
/>
)}
{rangedSelections.map((item, index) => {
const currentSaddleSelection = checkSaddleSelection(item);
const coupledRunners = findCoupledRunners(saddleSelections, item);
const runnerNameDetails = getRunnerNameDetails({
item,
scratches,
showReplacedRunners,
coupledRunners,
replacedRunners,
currentSaddleSelection
});
if (item === "|") {
return <AlternateDivider isDark={isDark} />;
}
return (
<RowContainer
isDetailView={wagerDetails}
showReplacedRunners={
showReplacedRunners && scratches?.includes(item)
}
key={`sanddle-arrow-${index.toString()}`}
data-qa-label={saddleRowQaLabel(
item,
currentSaddleSelection?.isAlternate
)}
>
{item === "all" && (
<Saddle
all={isAllSelections}
number="All"
size="s"
breed={breed}
/>
)}
{item === "-" && (
<IconContainer isDetailView>
<Icon
size="m"
name="arrowRight"
lineColor={
isDark
? "--fd-colors-content-on-dark"
: "--fd-colors-content-default"
}
qaLabel="runner-number-range-arrow"
/>
</IconContainer>
)}
{item === "?" && (
<Saddle
number="?"
size="s"
numberColor="var(--fd-colors-core-white)"
saddleColor="var(--fd-colors-core-white-tint-020)"
/>
)}
{currentSaddleSelection && (
<>
<ColumnContainer>
<Saddle
isScratched={isSaddleScratched(currentSaddleSelection)}
raceFinished={isRaceFinished(currentSaddleSelection)}
key={`Saddle-num-${currentSaddleSelection.number}`}
number={currentSaddleSelection.number}
numberColor={currentSaddleSelection.numberColor}
saddleColor={currentSaddleSelection.saddleColor}
all={currentSaddleSelection.number === "ALL"}
isWinner={
!currentSaddleSelection.isAlternate &&
!currentSaddleSelection.scratched &&
currentSaddleSelection.winner
}
breed={breed}
enableMyBetsBehavior={enableMyBetsBehavior}
size="s"
showAlternateIcon={currentSaddleSelection.isAlternate}
/>
{runnerNameDetails.showReplacementName &&
enableMyBetsBehavior && (
<>
<IconContainer
key={`sanddle-arrow-${index.toString()}`}
isDetailView={wagerDetails}
>
<Icon
size="m"
name="arrowRight"
lineColor="--fd-colors-system-warning-background-default"
qaLabel="runner-number-range-arrow"
/>
</IconContainer>
{replacedRunners
.filter((replaced) =>
!wagerDetails
? true
: !scratches?.includes(replaced.number)
)
.map((replaced) => (
<Saddle
isScratched={isSaddleScratched(replaced)}
raceFinished={isRaceFinished(replaced)}
key={`Saddle-num-${replaced.number}`}
number={replaced.number}
numberColor={replaced.numberColor}
saddleColor={replaced.saddleColor}
enableMyBetsBehavior={enableMyBetsBehavior}
isWinner={replaced.winner}
breed={breed}
size="s"
/>
))}
</>
)}
</ColumnContainer>
{wagerDetails && (
<SaddleDetailsParagraph
qaLabel={`runner-name-${runnerNameDetails.displayName}`}
fontSize="s"
fontFamily={runnerNameDetails.fontFamily}
color={runnerNameDetails.color}
scratched={runnerNameDetails.scratched}
m={0}
>
{runnerNameDetails.displayName}
</SaddleDetailsParagraph>
)}
{wagerDetails && (
<ColumnContainer>
{!!currentSaddleSelection.willPay && !hideWillPaysTag && (
<Paragraph
qaLabel="details-will-pay-amount"
textAlign="center"
fontSize="s"
fontFamily="medium"
color={
currentSaddleSelection.isSettled
? "--fd-colors-content-subtle"
: "--fd-colors-content-default"
}
m={0}
>
{formatCurrency(currentSaddleSelection.willPay)}
</Paragraph>
)}
{!!shouldShowRefundTag &&
!!currentSaddleSelection.scratched && (
<Tag label="REFUND" size="small" variant="warning" />
)}
{showOdds && runnerNameDetails.currentOdds && (
<Paragraph
qaLabel="details-odds"
textAlign="center"
fontSize="s"
fontFamily="bold"
m={0}
>
<>
{get(runnerNameDetails.currentOdds, "numerator")}
{get(runnerNameDetails.currentOdds, "denominator")
? `/${get(
runnerNameDetails.currentOdds,
"denominator"
)}`
: ""}
</>
</Paragraph>
)}
{/* {showReplacedRunners &&
!currentSaddleSelection.isAlternate &&
!!currentSaddleSelection.scratched &&
replacedRunners.find(
(replaced) =>
replaced.number ===
get(favoriteRunner, "runnerNumber") &&
!replaced.isAlternate
) && <Tag label="FAV" size="small" variant="favorite" />} */}
</ColumnContainer>
)}
</>
)}
</RowContainer>
);
})}
</SaddleSelectionContainer>
{!wagerDetails &&
showAlternatePlaceholder &&
alternateSelections.length === 0 && (
<AlternatePlaceholder>
<AlternateDivider isDark={isDark} />
<Saddle
number="?"
size="s"
numberColor="var(--fd-colors-core-white)"
saddleColor="var(--fd-colors-core-white-tint-020)"
qaLabel="saddle-?-alternate"
showAlternateIcon
/>
</AlternatePlaceholder>
)}
</SelectionsContainer>
);
};
export type { SaddleSelectionsCompProps, Selection };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/BetSelections/styled-components.ts
import styled from "styled-components";
export const BetSelectionsContainer = styled.div<{
isDark?: boolean;
}>`
display: flex;
align-items: center;
flex-shrink: 0;
border-radius: 4px;
flex-direction: row;
height: 42px;
width: fit-content;
padding: 0 var(--fd-space-space-3);
background-color: ${({ isDark }) =>
isDark ? "var(--fd-colors-core-navy-d-4)" : "transparent"};
border: 1px solid
${({ isDark }) =>
isDark
? "var(--fd-colors-core-navy-d-4)"
: "var(--fd-colors-border-default)"};
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/BetSelections/index.tsx
import React from "react";
import { SaddleSelections } from "../SaddleSelections";
import { Paragraph } from "../Typography";
import { BetSelectionsContainer } from "./styled-components";
import type { BetSelectionsProps } from "./types";
export const BetSelections = ({
numWagerableRunners,
type,
breed = "thoroughbred",
selections,
isDark = true,
qaLabel = "bet-selection",
showBetType = true,
scratches,
wagerDetails,
shouldShowRefundTag,
onHandicaping,
hideWillPaysTag,
enableMyBetsBehavior = false,
showOdds,
favoriteRunner,
showReplacedRunners,
raceStatus,
showAlternatePlaceholder
}: BetSelectionsProps) =>
showBetType ? (
<BetSelectionsContainer data-qa-label={qaLabel} isDark>
<Paragraph
color={
isDark ? "--fd-colors-content-on-dark" : "--fd-colors-content-default"
}
fontFamily="regular"
fontSize="14px"
paddingRight="6px"
>
{type}
</Paragraph>
<SaddleSelections
selections={selections}
isDark={isDark}
showBetType={showBetType}
scratches={scratches}
breed={breed}
hideWillPaysTag={hideWillPaysTag}
enableMyBetsBehavior={enableMyBetsBehavior}
showOdds={showOdds}
favoriteRunner={favoriteRunner}
showReplacedRunners={showReplacedRunners}
raceStatus={raceStatus}
showAlternatePlaceholder={showAlternatePlaceholder}
/>
</BetSelectionsContainer>
) : (
<SaddleSelections
numWagerableRunners={numWagerableRunners}
selections={selections}
isDark={isDark}
showBetType={showBetType}
scratches={scratches}
breed={breed}
wagerDetails={wagerDetails}
shouldShowRefundTag={shouldShowRefundTag}
onHandicaping={onHandicaping}
hideWillPaysTag={hideWillPaysTag}
enableMyBetsBehavior={enableMyBetsBehavior}
favoriteRunner={favoriteRunner}
showReplacedRunners={showReplacedRunners}
raceStatus={raceStatus}
showOdds={showOdds}
showAlternatePlaceholder={showAlternatePlaceholder}
/>
);
export type { BetSelectionsProps };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/BetTypesCell/styled-components.ts
import styled, { css } from "styled-components";
import { space, layout, compose } from "styled-system";
import { Theme } from "@tvg/design-system";
const styledUtils = compose(space, layout);
export const Container = styled.div<{
showOnlySelections?: boolean;
theme: Theme;
}>`
overflow: hidden;
${styledUtils}
border-radius: 2px;
${({ showOnlySelections }) =>
!showOnlySelections &&
css`
border: 1px solid var(--fd-colors-border-subtle);
`}
&:not(:last-child) {
margin-bottom: 8px;
}
`;
export const Header = styled.div<{
theme: Theme;
}>`
flex-direction: row;
justify-content: space-between;
align-items: center;
border-bottom-width: 1px;
background-color: var(--fd-colors-background-layer);
border-bottom-color: var(--fd-colors-border-subtle);
padding: 6px 12px;
`;
export const ContentActionsWrapper = styled.div`
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: flex-start;
background-color: var(--fd-colors-background-surface);
`;
export const Content = styled.div<{
hasButtons: boolean;
theme: Theme;
isMyBets: boolean;
}>`
padding: 12px;
max-width: ${({ hasButtons }) => (hasButtons ? "calc(100% - 72px)" : "100%")};
${({ isMyBets }) =>
isMyBets &&
css`
width: 100%;
`};
`;
export const Actions = styled.div<{
theme: Theme;
}>`
display: flex;
flex-direction: row;
gap: 8px;
margin: 6px 12px 6px 0;
`;
export const VerticalParagraphLeft = styled.div`
text-align: left;
`;
export const VerticalParagraphRight = styled.div`
text-align: right;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/WagerCardHeader/styled-components.ts
import styled, { css } from "styled-components";
import { space, layout, compose } from "styled-system";
import { Theme } from "@tvg/design-system";
const styledUtils = compose(space, layout);
export const Container = styled.div<{
theme: Theme;
}>`
overflow: hidden;
${styledUtils};
border-top-left-radius: 2px;
border-top-right-radius: 2px;
border-bottom-width: 1px;
border-bottom-style: solid;
${({ theme }) => css`
background-color: ${theme.colorTokens.background.layer};
border-bottom-color: ${theme.colorTokens.border.default};
`};
`;
export const Header = styled.div`
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
padding: ${({ theme }) =>
`${theme.space["space-4"]} ${theme.space["space-4"]}`};
`;
export const VerticalParagraphLeft = styled.div<{ isCanceled?: boolean }>`
display: flex;
flex-direction: column;
text-align: left;
${({ isCanceled }) =>
isCanceled &&
css`
text-decoration: line-through;
text-decoration-color: ${({ theme }) =>
theme.colorTokens.content.disabled};
`}
`;
export const VerticalParagraphRight = styled.div`
text-align: right;
`;
export const HideShowContainer = styled.button`
border: none;
outline: none;
display: flex;
align-items: center;
flex-direction: row;
${({ theme }) => css`
background-color: ${theme.colorTokens.component.button.buttonLink.background
.base};
`};
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/WagerCardHeader/components/WagerHeaderStatus/styled-components.ts
import styled, { css } from "styled-components";
export const Column = styled.div<{ addMargin?: boolean }>`
display: flex;
flex-direction: column;
${({ addMargin }) =>
addMargin &&
css`
margin-right: ${({ theme }) => theme.space["space-3"]};
`}
`;
export const Container = styled.div`
display: flex;
flex-direction: row;
`;
export const LinkContainer = styled.div`
display: flex;
align-items: center;
min-height: 18px;
`;
export const CanceledContainer = styled.div`
display: flex;
flex-direction: row;
align-items: center;
`;
export const WinnerRow = styled.div<{ center?: boolean }>`
display: flex;
flex-direction: row;
width: min-content;
${({ center }) =>
center &&
css`
justify-content: center;
`}
`;
export const Row = styled.div<{ center?: boolean }>`
display: flex;
flex-direction: row;
${({ center }) =>
center &&
css`
justify-content: center;
`}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/WagerCardHeader/components/RefundStatus/styled-components.ts
import styled from "styled-components";
import { compose, space } from "styled-system";
const styledComponentUtils = compose(space);
export const Column = styled.div<{ addMargin?: boolean }>`
display: flex;
flex-direction: column;
${styledComponentUtils};
`;
export const LinkContainer = styled.div`
display: flex;
align-items: center;
min-height: 18px;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/WagerCardHeader/components/RefundStatus/index.tsx
import React, { FC } from "react";
import formatCurrency from "@tvg/formatter/currency";
import { useColorTokens } from "@tvg/design-system/web/hooks";
import { RefundStatusProps } from "./types";
import { Icon } from "../../../Icon";
import { Paragraph } from "../../../../../src";
import { Column, LinkContainer } from "./styled-components";
export const RefundStatus: FC<RefundStatusProps> = ({
betRefund,
qaLabel = "wager-header-status",
...props
}) => {
const colors = useColorTokens();
return (
<Column data-qa-label={qaLabel} {...props}>
<Paragraph
qaLabel={`${qaLabel}-text`}
fontFamily="regular"
fontSize="s"
lineHeight="s"
color={colors.content.subtle}
textAlign="end"
>
{formatCurrency(betRefund || 0)}
</Paragraph>
<LinkContainer>
<Icon
name="betsRefund"
size="s"
qaLabel={`${qaLabel}-icon`}
mr={4}
lineColor={colors.content.subtle}
backgroundColor="transparent"
/>
<Paragraph
qaLabel={`${qaLabel}-title`}
textTransform="uppercase"
fontFamily="regular"
fontSize="xs"
lineHeight="xs"
color={colors.content.subtle}
>
refunded
</Paragraph>
</LinkContainer>
</Column>
);
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/WagerCardHeader/components/PotentialPayoutStatus/styled-components.ts
import styled from "styled-components"; export const Column = styled.div` display: flex; flex-direction: column; `; export const PayoutButton = styled.button` display: flex; flex-direction: row; align-items: center; background-color: transparent; outline: none; border: none; cursor: pointer; `;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/WagerCardHeader/components/PotentialPayoutStatus/index.tsx
import React, { FC } from "react";
import { useColorTokens } from "@tvg/design-system/web/hooks";
import { PotentialPayoutStatusProps } from "./types";
import { Icon } from "../../../Icon";
import { Paragraph } from "../../../../../src";
import { Column, PayoutButton } from "./styled-components";
export const PotentialPayoutStatus: FC<PotentialPayoutStatusProps> = ({
onApproxPayout,
probableValue,
qaLabel = "wager-header-status"
}) => {
const colors = useColorTokens();
return (
<Column data-qa-label={qaLabel}>
<Paragraph
qaLabel={`${qaLabel}-text`}
fontFamily="regular"
fontSize="s"
lineHeight="s"
color={colors.content.defaul}
textAlign="end"
>
{probableValue || ""}
</Paragraph>
<PayoutButton onClick={onApproxPayout}>
<Icon
name="support"
size="s"
lineColor={colors.content.link}
backgroundColor={colors.background.infoSubtle}
qaLabel={`${qaLabel}-payout-icon`}
mr={4}
/>
<Paragraph
qaLabel={`${qaLabel}-title`}
textTransform="uppercase"
fontFamily="condensedRegular"
fontSize="xs"
lineHeight="xs"
color={colors.content.subtle}
>
approx. payout
</Paragraph>
</PayoutButton>
</Column>
);
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/WagerCardHeader/components/WillPaysStatus/styled-components.ts
import styled from "styled-components"; export const Column = styled.div` display: flex; flex-direction: column; `;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/WagerCardHeader/components/WillPaysStatus/index.tsx
import React, { FC } from "react";
import formatCurrency from "@tvg/formatter/currency";
import { useColorTokens } from "@tvg/design-system/web/hooks";
import { WillPaysStatusProps } from "./types";
import { Paragraph } from "../../../../../src";
import { Column } from "./styled-components";
export const WillPaysStatus: FC<WillPaysStatusProps> = ({
minWillPays,
maxWillPays,
qaLabel = "wager-header-status"
}) => {
const colors = useColorTokens();
return (
<Column data-qa-label={qaLabel}>
<Paragraph
qaLabel={`${qaLabel}-payout-value`}
fontFamily="regular"
fontSize="s"
lineHeight="s"
color={colors.content.default}
textAlign="end"
>
{`${formatCurrency(minWillPays, "USD")} - ${formatCurrency(
maxWillPays,
"USD"
)}`}
</Paragraph>
<Paragraph
qaLabel="my-bets-payout-button-text"
textTransform="uppercase"
fontFamily="regular"
fontSize="xs"
lineHeight="xs"
color={colors.content.subtle}
textAlign="end"
>
Will Pays
</Paragraph>
</Column>
);
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/WagerCardHeader/components/WagerHeaderStatus/index.tsx
import React, { FC } from "react";
import formatCurrency from "@tvg/formatter/currency";
import { useColorTokens } from "@tvg/design-system/web/hooks";
import { WagerHeaderStatusProps } from "./types";
import {
Column,
CanceledContainer,
WinnerRow,
Container,
LinkContainer,
Row
} from "./styled-components";
import { Icon } from "../../../Icon";
import { Paragraph, Link } from "../../../../../src";
import { RefundStatus } from "../RefundStatus";
import { PotentialPayoutStatus } from "../PotentialPayoutStatus";
import { WillPaysStatus } from "../WillPaysStatus";
export const WagerHeaderStatus: FC<WagerHeaderStatusProps> = ({
betStatus,
winningsAmount,
probableValue,
onApproxPayout,
betRefund,
isBetWinner,
shouldShowPotentialReturn,
qaLabel = "wager-header-status",
showMinMaxWillPays,
minWillPays,
maxWillPays,
wonIllustration
}) => {
const colors = useColorTokens();
switch (betStatus) {
case "CANCELED":
return (
<Column data-qa-label={qaLabel}>
<CanceledContainer>
<Icon
name="betsCancel"
size="s"
qaLabel={`${qaLabel}-icon`}
lineColor={colors.content.subtle}
backgroundColor="transparent"
mr={4}
/>
<Paragraph
qaLabel={`${qaLabel}-text`}
fontFamily="regular"
fontSize="s"
lineHeight="xs"
color={colors.content.subtle}
>
Cancelled
</Paragraph>
</CanceledContainer>
</Column>
);
case "WINNER":
return isBetWinner ? (
<WinnerRow>
<Container>
<Column data-qa-label={qaLabel}>
{wonIllustration("wager-header-status-winner", winningsAmount)}
{!!betRefund && (
<Row center>
<Paragraph
qaLabel={`${qaLabel}-text`}
fontFamily="condensedRegular"
fontSize="xs"
lineHeight="xs"
color={colors.content.default}
mr={3}
mt={3}
>
{`+${formatCurrency(betRefund || 0)}`}
</Paragraph>
<Link qaLabel={`${qaLabel}-link`} href="/">
<Paragraph
qaLabel={`${qaLabel}-title`}
textTransform="uppercase"
fontFamily="condensedRegular"
fontSize="xs"
lineHeight="xs"
color={colors.content.subtle}
>
refund
</Paragraph>
</Link>
</Row>
)}
</Column>
</Container>
</WinnerRow>
) : (
<WinnerRow>
{!!betRefund && (
<Column data-qa-label={qaLabel} addMargin>
<Paragraph
qaLabel={`${qaLabel}-text`}
fontFamily="regular"
fontSize="s"
lineHeight="s"
color={colors.content.default}
textAlign="end"
>
{`${formatCurrency(betRefund || 0)}`}
</Paragraph>
<LinkContainer>
<Icon
name="betsRefund"
size="s"
qaLabel={`${qaLabel}-icon`}
mr={4}
lineColor={colors.content.link}
backgroundColor="transparent"
/>
<Paragraph
qaLabel={`${qaLabel}-title`}
textTransform="uppercase"
fontFamily="regular"
fontSize="xs"
lineHeight="xs"
color={colors.content.subtle}
>
refund
</Paragraph>
</LinkContainer>
</Column>
)}
<Column data-qa-label={qaLabel}>
<Paragraph
qaLabel={`${qaLabel}-text`}
fontFamily="regular"
fontSize="s"
lineHeight="s"
color={colors.content.default}
textAlign="end"
>
{`${formatCurrency(winningsAmount || 0)}`}
</Paragraph>
<LinkContainer>
<Paragraph
qaLabel={`${qaLabel}-title`}
textTransform="uppercase"
fontFamily="regular"
fontSize="xs"
lineHeight="xs"
color={colors.content.subtle}
>
return
</Paragraph>
</LinkContainer>
</Column>
</WinnerRow>
);
case "LOSER":
return (
<Container>
{!!betRefund && betRefund > 0 && (
<RefundStatus betRefund={betRefund} mr="space-3" />
)}
<Column data-qa-label={qaLabel}>
<Paragraph
qaLabel={`${qaLabel}-text`}
fontFamily="regular"
fontSize="s"
lineHeight="s"
color={colors.content.default}
textAlign="end"
>
{`${formatCurrency(0)}`}
</Paragraph>
<Paragraph
qaLabel={`${qaLabel}-title`}
textTransform="uppercase"
fontFamily="regular"
fontSize="xs"
lineHeight="xs"
color={colors.content.subtle}
>
return
</Paragraph>
</Column>
</Container>
);
case "REFUNDED":
return (
<>
<RefundStatus betRefund={betRefund} />
</>
);
default:
return (
<>
{shouldShowPotentialReturn && (
<PotentialPayoutStatus
onApproxPayout={onApproxPayout}
probableValue={probableValue}
/>
)}
{showMinMaxWillPays && (
<WillPaysStatus
minWillPays={minWillPays}
maxWillPays={maxWillPays}
/>
)}
</>
);
}
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/WagerCardHeader/index.tsx
import React, { FC } from "react";
import { useColorTokens } from "@tvg/design-system/web/hooks";
import { Icon } from "../Icon";
import { WagerCardHeaderProps } from "./types";
import {
Container,
Header,
HideShowContainer,
VerticalParagraphLeft,
VerticalParagraphRight
} from "./styled-components";
import { WagerHeaderStatus } from "./components/WagerHeaderStatus";
import { Paragraph } from "../Typography";
export const WagerCardHeader: FC<WagerCardHeaderProps> = ({
betAmount,
betTypeName,
betTicket,
betStatus,
probableValue,
onApproxPayout,
betRefund,
isBetWinner,
isCanceled,
winningsAmount,
shouldShowPotentialReturn,
showMinMaxWillPays,
minWillPays,
maxWillPays,
shouldShowHideLegButton,
onHideShowLegsGTM,
showContent,
setShowContent,
wagerId,
wonIllustration,
qaLabel = "wager-card-header",
...rest
}) => {
const colors = useColorTokens();
return (
<Container data-qa-label={`${qaLabel}-${wagerId}`} {...rest}>
<Header>
<VerticalParagraphLeft isCanceled={isCanceled}>
<Paragraph
qaLabel="bet-amount"
color={
isCanceled ? colors.content.disabled : colors.content.default
}
>
{`${betAmount} ${betTypeName}`}
</Paragraph>
<Paragraph
qaLabel="ticket-amount"
fontFamily="regular"
color={isCanceled ? colors.content.disabled : colors.content.subtle}
fontSize="xs"
>
{`${betTicket} TICKET`}
</Paragraph>
</VerticalParagraphLeft>
<VerticalParagraphRight>
<WagerHeaderStatus
winningsAmount={winningsAmount}
onApproxPayout={onApproxPayout}
betStatus={betStatus}
probableValue={probableValue}
betRefund={betRefund}
isBetWinner={isBetWinner}
showMinMaxWillPays={showMinMaxWillPays}
minWillPays={minWillPays}
maxWillPays={maxWillPays}
shouldShowPotentialReturn={shouldShowPotentialReturn}
wonIllustration={wonIllustration}
/>
{shouldShowHideLegButton && (
<HideShowContainer
onClick={() => {
onHideShowLegsGTM(!showContent);
setShowContent(!showContent, wagerId);
}}
>
<Icon
name={showContent ? "eyeHide" : "eyeShow"}
size="s"
lineColor={colors.component.button.buttonLink.content.base}
backgroundColor="transparent"
qaLabel="show-hide-leg-button"
/>
<Paragraph
qaLabel="ticket-amount"
fontFamily="regular"
color={colors.component.button.buttonLink.content.base}
fontSize="xs"
ml={4}
>
{showContent ? "Hide legs" : "Show legs"}
</Paragraph>
</HideShowContainer>
)}
</VerticalParagraphRight>
</Header>
</Container>
);
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/BetTypesCell/components/OptedInTag/styled-components.ts
import styled from "styled-components"; export const Wrapper = styled.div` display: flex; height: 30px; padding: 0 8px; border-top: 1px solid var(--fd-colors-system-positive-border-default); border-bottom: 1px solid var(--fd-colors-system-positive-border-default); align-items: center; justify-content: center; background-color: var(--fd-colors-system-positive-background-subtle); `;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/BetTypesCell/components/OptedInTag/index.tsx
import React from "react";
import { useTheme } from "../../../../hooks";
import { Icon } from "../../../Icon";
import { Paragraph } from "../../../Typography";
import { Wrapper } from "./styled-components";
const OptedInTag = () => {
const theme = useTheme();
return (
<Wrapper
data-qa-label="myBets-betTicket-optedInTag-container"
theme={theme}
>
<Icon
name="optedIn"
size="s"
backgroundColor="myBets.win.trackingColor"
lineColor="--fd-colors-system-positive-content-accent"
mr="space-1"
/>
<Paragraph
qaLabel="myBets-betTicket-optedInTag-text"
fontFamily="condensedRegular"
textTransform="uppercase"
color="--fd-colors-system-positive-content-onSubtle"
>
opted in
</Paragraph>
</Wrapper>
);
};
export default OptedInTag;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/RaceCell/utils.ts
import { RaceTrack, TrackLocation } from "@tvg/ts-types/Race";
import { truncate } from "lodash";
import { TRACK_NAME_MAX_LENGTH } from "./constants";
export const buildQALabel = (labels: string[]) =>
labels.filter(Boolean).join("-");
export const getFlagLabel = (location?: TrackLocation) => {
if (location?.country === "USA" && location?.state) return location?.state;
return location?.country ?? "";
};
export const getSpecialPickTrackName = (
track: Pick<RaceTrack, "name" | "shortName">
) => {
if (track.name.length <= TRACK_NAME_MAX_LENGTH) {
return track.name;
}
if (track.shortName && track.shortName.length <= TRACK_NAME_MAX_LENGTH) {
return track.shortName;
}
return truncate(track.shortName || track.name, {
length: TRACK_NAME_MAX_LENGTH
});
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/BetTypesCell/components/Footer/styled-components.ts
import styled, { css } from "styled-components";
import { Theme } from "styled-system";
export const BetCardFooter = styled.div.attrs({
"data-qa-label": "myBets-betTicket-footer"
})<{
theme: Theme;
}>`
display: flex;
align-items: center;
height: 48px;
padding: 0 4px;
border-top: 1px solid var(--fd-colors-border-subtle);
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
`;
export const FooterButton = styled.div<{
theme: Theme;
isCancelButton?: boolean;
isDetailsButton?: boolean;
isRepeatButton?: boolean;
isWagerCancelable?: boolean;
}>`
display: ${({ isDetailsButton, isWagerCancelable }) =>
isDetailsButton && isWagerCancelable ? "unset" : "flex"};
align-items: center;
justify-content: space-between;
text-decoration: none;
${({ isDetailsButton }) =>
isDetailsButton &&
css`
margin-left: auto;
`}
${({ isRepeatButton, isCancelButton }) =>
(isRepeatButton || isCancelButton) &&
css`
padding: 0 8px;
margin-right: 4px;
`};
`;
export const TooltipContainer = styled.div`
margin-left: 4px;
`;
export const ShowHideWrapper = styled.div`
white-space: nowrap;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/BetTypesCell/components/Footer/index.tsx
import React from "react";
import { IconButton } from "../../../IconButton";
import { breakpoints, useMediaQuery } from "../../../../../src";
import { Button } from "../../../Button";
import {
BetCardFooter,
FooterButton,
TooltipContainer,
ShowHideWrapper
} from "./styled-components";
import { Icon } from "../../../Icon";
import type { WagerCardFooterProps } from "./types";
import Tooltip from "../../../Tooltip";
const WagerCardFooter = ({
isBetActive,
hasSocialShare,
hasRepeatButton,
hasCancelButton,
isDetailsOpened,
onRepeatPress,
onDetailsPress,
onCancelWager,
onPressShareWager,
wagerId,
isXsellBlacklistedBet = false
}: WagerCardFooterProps) => {
const isMobile = useMediaQuery(breakpoints.tablet.max.sm);
return (
<BetCardFooter
data-qa-label={`myBets-betTicked-footer${wagerId ? "-" + wagerId : ""}`}
>
{hasSocialShare && (
<FooterButton data-qa-label="myBets-social-share">
<IconButton
size="s"
iconSize="s"
qaLabel="social-share-bet-btn"
onClick={onPressShareWager}
iconName="popout"
color="--fd-colors-content-subtle"
/>
</FooterButton>
)}
{hasRepeatButton && (
<FooterButton isRepeatButton>
{isXsellBlacklistedBet && (
<TooltipContainer>
<Tooltip
content="Repeat bet is currently unavailable for this bet type."
qaLabel="tooltip-repeat-bet-disabled"
placement="top-right"
layer={9999}
isLeftSideRendered={isMobile}
>
<Icon qaLabel="icon-info-repeat-tooltip" name="info" size="s" />
</Tooltip>
</TooltipContainer>
)}
<Button
variant="tertiary"
size="m"
qaLabel="myBets-betTicked-repeatButton"
onClick={onRepeatPress}
icon={!isXsellBlacklistedBet ? "repeat" : undefined}
isDisabled={isXsellBlacklistedBet}
>
{isBetActive ? "Repeat bet" : "Re-Bet"}
</Button>
</FooterButton>
)}
{hasCancelButton && (
<FooterButton isCancelButton>
<Button
variant="tertiaryDestructive"
size="m"
qaLabel="myBets-betTicked-cancelButton"
onClick={onCancelWager}
icon="trash"
>
Cancel
</Button>
</FooterButton>
)}
<FooterButton isDetailsButton isWagerCancelable={hasCancelButton}>
<Button
variant="tertiary"
size="m"
qaLabel="myBets-betTicked-detailsButton"
onClick={onDetailsPress}
icon={!isDetailsOpened ? "chevronDown" : "chevronUp"}
iconPosition="end"
>
<ShowHideWrapper>
{isDetailsOpened ? "Hide details" : "Show details"}{" "}
</ShowHideWrapper>
</Button>
</FooterButton>
</BetCardFooter>
);
};
export default WagerCardFooter;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/BetTypesCell/components/PromoOnboarding/index.tsx
import React from "react";
import PromosOnboarding from "@tvg/promos-onboarding";
import { type PromoOnboardingProps } from "../../types";
const PromoOnboarding = ({
customMessage,
isShown,
placeToRender
}: PromoOnboardingProps) => (
<PromosOnboarding
placeToRender={placeToRender}
customMessage={customMessage}
isShown={isShown}
/>
);
export default PromoOnboarding;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/BetTypesCell/components/PickBetRebet/styled-components.ts
import styled, { css } from "styled-components";
import { Theme } from "styled-system";
export const PickBetsContainer = styled.div<{
hasRoundBottomBorder: boolean;
theme: Theme;
}>`
display: flex;
justify-content: space-between;
align-items: center;
padding: 8px 12px;
border-top: 1px solid var(--fd-colors-border-subtle);
${({ hasRoundBottomBorder }) =>
hasRoundBottomBorder &&
css`
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
`}
`;
export const PickBetsTextWrapper = styled.div`
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: space-between;
`;
export const PickBetsLinkContainer = styled.div`
display: flex;
flex-direction: row;
flex-shrink: 0;
text-decoration: none;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/BetTypesCell/components/PickBetRebet/index.tsx
import React from "react";
import { Button } from "../../../Button";
import {
PickBetsContainer,
PickBetsLinkContainer,
PickBetsTextWrapper
} from "./styled-components";
import { Paragraph } from "../../../Typography";
import { type PickBetRebetProps } from "../../types";
const PickBetRebet = ({
shouldShowRebet,
isContentDisplayed,
rebetWagerTypeName,
onClickBet
}: PickBetRebetProps) =>
shouldShowRebet ? (
<PickBetsContainer
data-qa-label="pick-bets-container"
hasRoundBottomBorder={!isContentDisplayed}
>
<PickBetsTextWrapper>
<Paragraph
fontFamily="medium"
color="--fd-colors-content-default"
qaLabel="pick-bets-rebet-title"
>{`${rebetWagerTypeName} Available`}</Paragraph>
<Paragraph qaLabel="pick-bets-rebet-description" fontSize="xs">
Bet using your remaining selections
</Paragraph>
</PickBetsTextWrapper>
<PickBetsLinkContainer data-qa-label="myBets-pickbets-link">
<Button
variant="betting"
iconPosition="end"
icon="arrowRight"
onClick={onClickBet}
qaLabel="button"
size="m"
isStretched
>
Create Bet
</Button>
</PickBetsLinkContainer>
</PickBetsContainer>
) : null;
export default PickBetRebet;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/BetTypesCell/components/Notification/index.tsx
import React from "react";
import { AlertInLine } from "../../../AlertInLine";
import { type WagerCardNotificationProps } from "../../types";
const WagerCardNotification = ({
scratchedLegText,
scratchedTitle,
shouldNotHideScratchNotification,
showScratchedNotification,
onDismissPress,
wagerId,
onNotificationPress,
enableMyBetsBehavior
}: WagerCardNotificationProps) =>
showScratchedNotification && shouldNotHideScratchNotification ? (
<AlertInLine
message={scratchedLegText}
title={scratchedTitle}
type="fixed"
variant={
scratchedTitle.includes("Scratch") && enableMyBetsBehavior
? "warning"
: "informational"
}
qaLabel={`notification-scratch-${wagerId}`}
marginBottom="space-5"
onDismissPress={() => onDismissPress(false)}
linkLabel="See Rules"
onClick={onNotificationPress}
/>
) : null;
export default WagerCardNotification;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/BetTypesCell/components/CustomBetSelectionsView/styled-components.ts
/* eslint-disable security/detect-object-injection */
import styled, { css, keyframes } from "styled-components";
import { Paragraph } from "../../../Typography";
import type { BetRaceStatusType } from "../../types";
type ColorsMapper = {
[RaceStatus in BetRaceStatusType]: string;
};
const defaultRaceStatusColors: ColorsMapper = {
open: "--fd-colors-system-neutral-background-default",
raceOff: "--fd-colors-system-neutral-background-default",
win: "--fd-colors-system-positive-background-default",
lost: "--fd-colors-system-important-background-default",
attention: "--fd-colors-system-warning-background-default",
unknown: "--fd-colors-system-neutral-background-default"
};
const legTextColors: ColorsMapper = {
open: "--fd-colors-system-neutral-content-default",
raceOff: "--fd-colors-system-neutral-content-subtle",
win: "--fd-colors-system-positive-content-accent",
lost: "--fd-colors-system-important-content-accent",
attention: "--fd-colors-system-warning-content-accent",
unknown: "--fd-colors-system-neutral-content-accent"
};
const fadeIn = keyframes`
0% {
opacity: 0;
}
100% {
opacity: 1;
}
`;
export const Content = styled.div`
justify-content: center;
flex-shrink: 0;
`;
export const PositionsContainer = styled.div<{
raceStatus?: BetRaceStatusType;
isLeg: boolean | undefined;
}>`
&:not(:last-child) {
padding-bottom: 8px;
}
${({ raceStatus, isLeg }) =>
isLeg &&
css`
position: relative;
&:not(:first-child) {
margin-top: 2px;
}
&:not(:last-child) {
&::after {
content: "";
width: 2px;
height: calc(100% - 18px);
${raceStatus &&
css`
background: var(${defaultRaceStatusColors[raceStatus]});
`}
border-radius: 1px;
position: absolute;
top: 20px;
left: 9px;
z-index: 2;
}
}
`}
`;
export const RowWrapper = styled.div<{
isLeg: boolean | undefined;
}>`
${({ isLeg }) =>
isLeg
? css`
display: flex;
position: relative;
`
: css`
display: grid;
grid-template-columns: 25px auto;
gap: 12px 8px;
position: relative;
width: 100%;
`}
`;
export const DetailAction = styled.div`
position: absolute;
width: 100%;
height: 20px;
z-index: 3;
`;
export const PickBetLabelIconContainer = styled.div`
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
height: 20px;
width: 20px;
margin-right: 8px;
position: relative;
z-index: 2;
`;
export const LabelIconWrapper = styled.div<{
raceStatus?: BetRaceStatusType;
}>`
position: relative;
width: 16px;
height: 16px;
${({ raceStatus }) => {
if (raceStatus && ["raceOff"].includes(raceStatus)) {
return css`
border: 2px solid var(--fd-colors-content-subtle);
background: var(--fd-colors-background-surface);
border-radius: 50%;
`;
}
return "";
}}
`;
export const LabelDot = styled.div<{
raceStatus?: BetRaceStatusType;
}>`
position: absolute;
content: "";
width: 4px;
height: 4px;
top: calc(50% - 2px);
left: calc(50% - 2px);
border-radius: 50%;
background: var(--fd-colors-content-subtle);
`;
export const SaddleContainer = styled.div<{
isLeg: boolean | undefined;
hasDetails: boolean;
hasAlternate?: boolean;
}>`
width: ${({ isLeg, hasDetails }) =>
isLeg && !hasDetails ? "fit-content" : "100%"};
${({ hasDetails, isLeg }) =>
isLeg &&
hasDetails &&
css`
margin-top: 8px;
`}
`;
export const LegParagraph = styled(Paragraph)<{
raceStatus?: BetRaceStatusType;
}>`
color: ${({ raceStatus }) =>
raceStatus
? `var(${legTextColors[raceStatus]})`
: "var(--fd-colors-content-subtle)"};
`;
export const DetailsHr = styled.hr.attrs({
"data-qa-label": "myBets-horizontalRule"
})`
height: 1px;
background-color: var(--fd-colors-border-subtle);
width: calc(100% - 4px);
border: none;
position: relative;
left: 2px;
z-index: 2;
margin: 8px 0 0;
animation: ${fadeIn} 0.2s cubic-bezier(0.39, 0.575, 0.565, 1) both;
`;
export const TextAndSelectionContainer = styled.div<{
hasDetails: boolean;
isLeg: boolean | undefined;
}>`
display: flex;
font-family: "Roboto-Regular", sans-serif;
flex-direction: ${({ hasDetails }) => (hasDetails ? "column" : "row")};
${({ isLeg }) =>
isLeg &&
css`
width: 100%;
`};
`;
export const WillPaysInfoContainer = styled.div`
display: flex;
width: 100%;
margin-left: 2px;
margin-top: 6px;
color: var(--fd-colors-system-info-content-accent);
> div {
margin-right: 4px;
}
`;
export const AttentionContainer = styled.div`
display: flex;
width: 100%;
margin-left: 2px;
margin-top: 6px;
color: var(--fd-colors-system-warning-content-accent);
> div {
margin-right: 4px;
}
`;
export const WillPaysLabel = styled.div`
color: var(--fd-colors-content-subtle);
position: absolute;
right: 18px;
font-size: 12px;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/BetTypesCell/types.ts
import type { SpaceProps, LayoutProps } from "styled-system";
import { WagerTypeCodesEnum } from "@tvg/ts-types/Wager";
import { FavoriteRunners } from "@tvg/ts-types/Race";
// TO DO - TO BE REMOVED
import { GestureResponderEvent } from "react-native";
import { StoryblokPlaceName } from "@tvg/sh-lib-promos-onboarding/types/promoOnboardingComponents";
import type { Dispatch, SetStateAction } from "react";
import { Breed, type SaddleSelectionsProps } from "../../../src";
import type {
HeaderBetStatusType,
WagerCardHeaderProps
} from "../WagerCardHeader/types";
type BetStatusType = "NONE" | "PLACED" | "ERROR" | "PROCESSING";
type BetRaceStatusType =
| "open"
| "raceOff"
| "win"
| "lost"
| "attention"
| "unknown";
type BetTypeCellHeaderPickTypes =
| "onApproxPayout"
| "isBetWinner"
| "isCanceled"
| "winningsAmount"
| "shouldShowPotentialReturn"
| "showMinMaxWillPays"
| "minWillPays"
| "maxWillPays"
| "onHideShowLegsGTM"
| "setShowContent"
| "shouldShowHideLegButton"
| "showContent"
| "wagerId"
| "wonIllustration";
enum BetStatusCodesEnum {
ACTIVE = "A",
REFUNDED = "R",
LOSER = "L",
WINNER = "W",
CANCELED = "C"
}
interface BetTypeCellProps extends SpaceProps, LayoutProps {
/** Bet Amount */
betAmount: number;
/** Bet type name */
betTypeName: string;
/** Bet Ticket value */
betTicket: number;
/** Number Wagerable Runners */
numWagerableRunners?: string[] | undefined;
/** Approximated Payout */
approximatedPayout: string;
/** Bet type */
type: WagerTypeCodesEnum;
/** Type of race */
breed?: Breed;
/** Saddle selections */
selections: SaddleSelectionsProps[];
/** Complete Selection Array */
completeSelection?: SaddleSelectionsProps[][];
/** Status of the bet */
betStatus: BetStatusType | HeaderBetStatusType;
/** Repeat bet handler */
onRepeatBetHandler?: (event: GestureResponderEvent) => void;
/** Cancel bet handler */
onCancelBetHandler?: (event: GestureResponderEvent) => void;
/** Custom data-qa-label attribute applied to element */
qaLabel?: string;
/** Is leg bet * */
isLeg: boolean;
/** If include scratch in selections */
scratches?: string[][];
/** Is Key bet */
isKey?: boolean;
/** Is Box bet */
isBox?: boolean;
/** Is Wheel bet */
isWheel?: boolean;
/** Current race number */
raceNumber?: string;
/** No header and no border */
showOnlySelections?: boolean;
betStatusCode?: BetStatusCodesEnum;
racesStatus?: BetRaceStatusType[];
winAmountBet?: number;
/** Is the bet refund amount */
betRefund?: number;
/** Is the component being rendered in the myBets screen */
isMyBets?: boolean;
/** Is the bet repeatable */
isRepeatable?: boolean;
/** If is on handicaping */
onHandicaping?: boolean;
/** if bet is opted in */
isOptedIn?: boolean;
/** if footer should be shown */
isFooterShown?: boolean;
/** Props for my bets header */
headerMyBetsProps?: Pick<WagerCardHeaderProps, BetTypeCellHeaderPickTypes>;
/** Props for notifications */
notificationProps?: WagerCardNotificationProps;
/** Props for pick bet rebet */
pickBetRebetProps?: PickBetRebetProps;
/** Props for promo onboards */
promoOnboardingProps?: PromoOnboardingProps;
/** Props for footer */
wagerCardFooterProps?: WagerCardFooterProps;
/** Details controler */
wagerDetails?: boolean[];
/** Is the bet done on a special wager track */
isSpecialWager?: boolean;
onDetailsView?: (raceSelected: number) => void;
shouldShowRefundTag?: boolean;
enableMyBetsBehavior?: boolean;
favoriteRunnerByLeg?: FavoriteRunners;
showReplacedRunners?: boolean;
showAlternatePlaceholder?: boolean;
}
interface PromoOnboardingProps {
placeToRender?: StoryblokPlaceName;
customMessage?: string;
isShown?: boolean;
}
interface CustomBetSelectionsViewProps {
/** Complete Selection Array */
completeSelection: SaddleSelectionsProps[][] | undefined;
/** Number Wagerable Runners */
numWagerableRunners?: string[] | undefined;
/** Bet type */
type: WagerTypeCodesEnum;
/** Runners Scratches */
scratches?: string[][];
/** Type of race */
breed?: Breed;
/** Key Bet */
isKey?: boolean;
/** Box Bet */
isBox?: boolean;
/** Wheel Bet */
isWheel?: boolean;
/** Leg Bet */
isLeg?: boolean;
/** Exotic Bet */
isExoticBet?: boolean;
/** Current race number */
currentRaceNumber?: string;
/** is the bet done on a special wager */
isSpecialWager?: boolean;
wagerDetails?: boolean[];
racesStatus?: BetRaceStatusType[];
onDetailsView?: (raceSelected: number) => void;
enableMyBetsBehavior?: boolean;
favoriteRunnerByLeg?: FavoriteRunners | null;
showReplacedRunners?: boolean;
showAlternatePlaceholder?: boolean;
}
interface PickBetRebetProps {
shouldShowRebet: boolean;
isContentDisplayed: boolean;
rebetWagerTypeName: string;
onClickBet: () => void;
}
interface WagerCardNotificationProps {
showScratchedNotification: boolean;
shouldNotHideScratchNotification: boolean;
onDismissPress: Dispatch<SetStateAction<boolean>>;
onNotificationPress?: () => void;
scratchedTitle: string;
scratchedLegText: string;
wagerId: string;
enableMyBetsBehavior?: boolean;
}
interface WagerCardFooterProps {
hasSocialShare?: boolean;
hasRepeatButton?: boolean;
hasCancelButton?: boolean;
isDetailsOpened?: boolean;
isBetActive?: boolean;
onPressShareWager: () => void;
onRepeatPress: () => void;
onDetailsPress: () => void;
onCancelWager: () => void;
isXsellBlacklistedBet: boolean;
}
export type {
SaddleSelectionsProps,
WagerCardHeaderProps,
WagerCardNotificationProps,
PickBetRebetProps,
PromoOnboardingProps,
WagerCardFooterProps,
CustomBetSelectionsViewProps,
BetTypeCellProps,
BetRaceStatusType
};
export { BetStatusCodesEnum };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/BetTypesCell/components/CustomBetSelectionsView/index.tsx
import React, { useCallback } from "react";
import formatSequencial from "@tvg/formatter/numeric";
import { get } from "lodash";
import { FavoriteRunners } from "@tvg/ts-types/Race";
import {
AttentionContainer,
Content,
DetailAction,
DetailsHr,
LabelDot,
LabelIconWrapper,
LegParagraph,
PickBetLabelIconContainer,
PositionsContainer,
RowWrapper,
SaddleContainer,
TextAndSelectionContainer,
WillPaysInfoContainer,
WillPaysLabel
} from "./styled-components";
import type { Selection } from "../../../SaddleSelections/types";
import { BetSelections } from "../../../BetSelections";
import { Paragraph } from "../../../Typography";
import { Icon } from "../../../Icon";
import { type CustomBetSelectionsViewProps } from "../../types";
export const CustomBetSelectionsView: React.FC<
CustomBetSelectionsViewProps
> = ({
completeSelection,
numWagerableRunners,
type,
isKey,
isBox,
isWheel,
isLeg,
isExoticBet,
currentRaceNumber,
scratches,
breed,
wagerDetails,
onDetailsView,
racesStatus,
isSpecialWager,
enableMyBetsBehavior = false,
favoriteRunnerByLeg,
showReplacedRunners,
showAlternatePlaceholder
}) => {
const renderKeyOrKeyBox = (index: number) => {
const isKeyBox = isKey && isBox;
const defaultText = isKeyBox ? "Box" : "w/";
return (
<Paragraph
qaLabel={`selection-label-key${isKeyBox ? "-box" : ""}`}
color="--fd-colors-content-subtle"
fontFamily="regular"
>
{index === 0 ? (
<Icon
name="key"
size="s"
qaLabel="key"
lineColor="--fd-colors-content-subtle"
fontFamily="regular"
/>
) : (
defaultText
)}
</Paragraph>
);
};
const renderKeyBoxOrKeyOrBox = (index: number) => {
if (isKey) {
return renderKeyOrKeyBox(index);
}
return (
<Paragraph
color="--fd-colors-content-subtle"
qaLabel="selection-label-box"
fontFamily="regular"
>
Box
</Paragraph>
);
};
const renderExoticOrLegBet = (index: number) => {
const currentRaceStatus = get(racesStatus, index);
return isExoticBet ? (
<Paragraph
qaLabel={`selection-label-${formatSequencial(index + 1)}`}
color="--fd-colors-content-subtle"
fontFamily="regular"
>
{formatSequencial(index + 1)}
</Paragraph>
) : (
<Content>
<LegParagraph
qaLabel={`selection-label-${formatSequencial(index + 1)}`}
fontFamily="condensedRegular"
ml="space-1"
mr="space-3"
raceStatus={currentRaceStatus}
>
{isSpecialWager
? `L${Number(currentRaceNumber) + index}`
: `LEG ${index + 1} - R${Number(currentRaceNumber) + index}`}
</LegParagraph>
</Content>
);
};
const renderWheel = (index: number) => (
<Paragraph
qaLabel="selection-label-wheel"
color="--fd-colors-content-subtle"
fontFamily="regular"
>
{index === 0 ? <></> : "w/"}
</Paragraph>
);
const renderLegLabelIcon = (index: number) => {
const currentRaceStatus = get(racesStatus, index);
switch (currentRaceStatus) {
case "attention":
return (
<PickBetLabelIconContainer>
<LabelIconWrapper raceStatus="attention">
<Icon
qaLabel="attention-leg-icon"
name="changes"
size="s"
lineColor="--fd-colors-system-warning-content-accent"
/>
</LabelIconWrapper>
</PickBetLabelIconContainer>
);
case "lost":
return (
<PickBetLabelIconContainer>
<LabelIconWrapper raceStatus="lost">
<Icon
qaLabel="lost-leg-icon"
name="error"
size="s"
lineColor="--fd-colors-system-important-background-default"
/>
</LabelIconWrapper>
</PickBetLabelIconContainer>
);
case "win":
return (
<PickBetLabelIconContainer>
<LabelIconWrapper raceStatus="win">
<Icon
qaLabel="win-leg-icon"
name="success"
size="s"
lineColor="--fd-colors-system-positive-background-default"
/>
</LabelIconWrapper>
</PickBetLabelIconContainer>
);
default:
return (
<PickBetLabelIconContainer>
<LabelIconWrapper raceStatus={currentRaceStatus}>
<LabelDot raceStatus={currentRaceStatus} />
</LabelIconWrapper>
</PickBetLabelIconContainer>
);
}
};
const replacementMessage = useCallback(
(selections: Selection[], index: number) => {
let message = "Awaiting official result to confirm the bet status.";
if (
scratches?.[index].length &&
selections.some(
(item) =>
item.isAlternate && !scratches?.[index].includes(item.number)
)
) {
message = `Scratch will be replaced with the alternate selection. ${message}`;
} else if (isLeg) {
message = `Scratch will be replaced with the FAV. ${message}`;
}
return message;
},
[isLeg, scratches]
);
const renderLabelAndSelections = (
selection: Selection[],
index: number,
hasWillPaysTag: boolean,
showOdds: boolean,
favRunnersByLeg: FavoriteRunners | null | undefined
) => {
const currentRaceStatus = get(racesStatus, index);
const favoriteRunner = favRunnersByLeg?.[index];
return isLeg ? (
<TextAndSelectionContainer
hasDetails={get(wagerDetails, index, false)}
isLeg={isLeg}
>
{(isKey || isBox) && renderKeyBoxOrKeyOrBox(index)}
{(isExoticBet || isLeg) && renderExoticOrLegBet(index)}
{isWheel && renderWheel(index)}
{hasWillPaysTag && scratches?.[index].length !== selection.length && (
<WillPaysInfoContainer>
<LabelIconWrapper raceStatus="win">
<Icon
qaLabel="info"
name="info"
size="s"
lineColor="--fd-colors-system-info-content-accent"
/>
</LabelIconWrapper>
Will Pays subject to change due to scratches
</WillPaysInfoContainer>
)}
{!hasWillPaysTag &&
currentRaceStatus === "unknown" &&
isLeg &&
get(wagerDetails, index, false) && (
<AttentionContainer>
Result for this leg currently pending.
</AttentionContainer>
)}
{!hasWillPaysTag &&
currentRaceStatus === "attention" &&
isLeg &&
get(wagerDetails, index, false) && (
<AttentionContainer>
{replacementMessage(selection, index)}
</AttentionContainer>
)}
<SaddleContainer
isLeg={isLeg}
hasDetails={get(wagerDetails, index, false)}
>
<BetSelections
scratches={scratches?.[index]}
numWagerableRunners={
isLeg ? numWagerableRunners?.[index] : numWagerableRunners?.[0]
}
selections={selection}
type={type}
showBetType={false}
breed={breed}
wagerDetails={get(wagerDetails, index, false)}
hideWillPaysTag={!hasWillPaysTag}
showOdds={showOdds}
enableMyBetsBehavior={enableMyBetsBehavior}
favoriteRunner={favoriteRunner as unknown as FavoriteRunners}
showReplacedRunners={showReplacedRunners}
raceStatus={currentRaceStatus}
isDark={false}
showAlternatePlaceholder={showAlternatePlaceholder}
/>
{get(wagerDetails, index, false) &&
completeSelection &&
index !== (completeSelection?.length || 0) - 1 &&
completeSelection?.length > 1 && <DetailsHr />}
</SaddleContainer>
</TextAndSelectionContainer>
) : (
<>
{(isKey || isBox) && renderKeyBoxOrKeyOrBox(index)}
{(isExoticBet || isLeg) && renderExoticOrLegBet(index)}
{isWheel && renderWheel(index)}
<SaddleContainer
isLeg={isLeg}
hasDetails={get(wagerDetails, index, false)}
>
<BetSelections
scratches={scratches?.[index]}
numWagerableRunners={
isLeg ? numWagerableRunners?.[index] : numWagerableRunners?.[0]
}
selections={selection}
type={type}
showBetType={false}
breed={breed}
wagerDetails={get(wagerDetails, index, false)}
hideWillPaysTag={!hasWillPaysTag}
enableMyBetsBehavior={enableMyBetsBehavior}
favoriteRunner={favoriteRunner as unknown as FavoriteRunners}
showReplacedRunners={showReplacedRunners}
raceStatus={currentRaceStatus}
isDark={false}
showAlternatePlaceholder={showAlternatePlaceholder}
/>
{get(wagerDetails, index, false) &&
index !== (completeSelection?.length || 0) - 1 &&
completeSelection &&
completeSelection?.length > 1 && <DetailsHr />}
</SaddleContainer>
</>
);
};
return completeSelection?.length ? (
<>
{completeSelection.map((selection, index) => {
const willPaysExist = selection.some(
(sel) => sel.willPay && sel.willPay > 0
);
const hasWillPaysTag =
index === completeSelection.length - 1 &&
willPaysExist &&
scratches?.[index].length !== selection.length &&
get(wagerDetails, index, false);
const showOdds = get(wagerDetails, index, false);
return (
<PositionsContainer
key={`${type}-${index.toString()}`}
isLeg={isLeg}
raceStatus={get(racesStatus, index)}
>
<RowWrapper isLeg={isLeg}>
<DetailAction
onClick={() => onDetailsView && onDetailsView(index)}
/>
{isLeg && renderLegLabelIcon(index)}
{renderLabelAndSelections(
selection,
index,
hasWillPaysTag,
showOdds,
favoriteRunnerByLeg
)}
{hasWillPaysTag && <WillPaysLabel>WILL PAYS</WillPaysLabel>}
{isLeg && wagerDetails && (
<Icon
qaLabel={`${type}-${index}}-details-chevron`}
name={
get(wagerDetails, index, false)
? "chevronUp"
: "chevronDown"
}
size="s"
lineColor="--fd-colors-content-subtle"
/>
)}
</RowWrapper>
</PositionsContainer>
);
})}
</>
) : null;
};
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/BetTypesCell/index.tsx
import React, { useCallback } from "react";
import { WagerTypeCodesEnum } from "@tvg/ts-types/Wager";
import { isZeroLike } from "@tvg/utils/generalUtils";
import formatCurrency from "@tvg/formatter/currency";
import { useColorTokens } from "../../hooks";
import { IconButton } from "../IconButton";
import { Tag } from "../Tag";
import { BetSelections } from "../BetSelections";
import { LoadingSpinner } from "../LoadingSpinner";
import {
Container,
ContentActionsWrapper,
Content,
Actions,
Header,
VerticalParagraphLeft,
VerticalParagraphRight
} from "./styled-components";
import { Paragraph } from "../Typography";
import { WagerCardHeader } from "../WagerCardHeader";
import { HeaderBetStatusType } from "../WagerCardHeader/types";
import OptedInTag from "./components/OptedInTag";
import { buildQALabel } from "../RaceCell/utils";
import WagerCardFooter from "./components/Footer";
import PromoOnboarding from "./components/PromoOnboarding";
import PickBetRebet from "./components/PickBetRebet";
import WagerCardNotification from "./components/Notification";
import { CustomBetSelectionsView } from "./components/CustomBetSelectionsView";
import type {
SaddleSelectionsProps,
WagerCardHeaderProps,
WagerCardNotificationProps,
BetTypeCellProps,
PickBetRebetProps,
PromoOnboardingProps,
WagerCardFooterProps
} from "./types";
import { BetStatusCodesEnum } from "./types";
const exoticBets = [
WagerTypeCodesEnum.EXACTA,
WagerTypeCodesEnum.TRIFECTA,
WagerTypeCodesEnum.SUPERFECTA,
WagerTypeCodesEnum.SUPERHIGHFIVE
];
export const BetTypeCell = ({
numWagerableRunners,
type,
breed = "thoroughbred",
betTypeName,
selections,
completeSelection,
qaLabel = "bet-type-cell",
approximatedPayout,
betAmount,
betStatus,
betTicket,
isLeg,
scratches,
onRepeatBetHandler,
onCancelBetHandler,
isKey,
isBox,
isWheel,
raceNumber,
betStatusCode,
winAmountBet,
showOnlySelections,
betRefund,
headerMyBetsProps,
notificationProps,
pickBetRebetProps,
promoOnboardingProps,
wagerCardFooterProps,
wagerDetails,
shouldShowRefundTag,
racesStatus,
onDetailsView,
isFooterShown = false,
isOptedIn = false,
isMyBets = false,
isRepeatable = true,
isSpecialWager = false,
enableMyBetsBehavior,
favoriteRunnerByLeg,
showReplacedRunners,
showAlternatePlaceholder,
...rest
}: BetTypeCellProps) => {
const colors = useColorTokens();
const isExoticBet = exoticBets.includes(type);
const isCustomSelectionsView =
isKey || isLeg || isBox || isWheel || isExoticBet;
const hasPayout = !isZeroLike(approximatedPayout);
const isWon = betStatusCode === BetStatusCodesEnum.WINNER;
const isRefund = betStatusCode === BetStatusCodesEnum.REFUNDED;
const betStatusCodeMap: Record<
BetStatusCodesEnum,
{ label: string; value?: number | string }
> = {
A: {
label: hasPayout ? "APPROX. PAYOUT" : "",
value: hasPayout ? approximatedPayout : ""
},
R: { label: "REFUND", value: betRefund },
L: { label: "RETURN", value: "$0.00" },
W: { label: "WON", value: winAmountBet },
C: { label: "REFUND", value: betRefund }
};
const onRepeatBet = useCallback(
(e) => {
onRepeatBetHandler?.(e);
},
[onRepeatBetHandler]
);
const onCancel = useCallback(
(e) => {
onCancelBetHandler?.(e);
},
[onCancelBetHandler]
);
const renderRightColumn = () => {
switch (betStatus) {
case "PROCESSING":
return (
<div>
<LoadingSpinner shouldUseColorTokens={true} />
</div>
);
case "ERROR":
return (
<div>
<Tag size="small" variant="warning" label="Failed" hideIcon />
</div>
);
case "PLACED":
return (
<div>
<Tag size="small" variant="positive" label="Placed" hideIcon />
</div>
);
default:
return (
<VerticalParagraphRight
data-qa-label={buildQALabel(["vertical", "paragraph", "right"])}
>
<Paragraph
fontFamily={isWon || isRefund ? "medium" : "regular"}
fontWeight={isWon || isRefund ? 500 : 400}
color={isWon ? colors.content.positive : colors.content.default}
qaLabel={buildQALabel(["approximate", "payout", "value"])}
>
{
betStatusCodeMap[betStatusCode || BetStatusCodesEnum.ACTIVE]
.value
}
</Paragraph>
<Paragraph
qaLabel={buildQALabel(["approximate", "payout"])}
fontFamily="condensedRegular"
color={isWon ? colors.content.positive : colors.content.subtle}
fontSize="xs"
textAlign={isWon ? "end" : "start"}
>
{
betStatusCodeMap[betStatusCode || BetStatusCodesEnum.ACTIVE]
.label
}
</Paragraph>
</VerticalParagraphRight>
);
}
};
const renderSelections = () =>
isCustomSelectionsView ? (
<CustomBetSelectionsView
isKey={isKey}
isBox={isBox}
isLeg={isLeg}
isWheel={isWheel}
isSpecialWager={isSpecialWager}
isExoticBet={isExoticBet}
completeSelection={completeSelection}
numWagerableRunners={numWagerableRunners}
type={type}
currentRaceNumber={raceNumber}
scratches={scratches}
breed={breed}
racesStatus={racesStatus}
wagerDetails={wagerDetails}
onDetailsView={onDetailsView}
enableMyBetsBehavior={enableMyBetsBehavior}
favoriteRunnerByLeg={favoriteRunnerByLeg}
showReplacedRunners={showReplacedRunners}
showAlternatePlaceholder={showAlternatePlaceholder}
/>
) : (
<BetSelections
numWagerableRunners={numWagerableRunners?.[0]}
selections={selections}
type={type}
breed={breed}
showBetType={false}
scratches={Array.from(new Set(scratches?.flat(1)))} // remove duplicates
onHandicaping={rest.onHandicaping}
wagerDetails={!!wagerDetails?.some((detail) => detail)}
shouldShowRefundTag={shouldShowRefundTag}
enableMyBetsBehavior={enableMyBetsBehavior}
favoriteRunner={favoriteRunnerByLeg}
showReplacedRunners={showReplacedRunners}
isDark={false}
showAlternatePlaceholder={showAlternatePlaceholder}
/>
);
const renderHeader = () => {
if (isMyBets && headerMyBetsProps) {
const {
onApproxPayout,
isBetWinner,
isCanceled,
winningsAmount,
shouldShowPotentialReturn,
showMinMaxWillPays,
minWillPays,
maxWillPays,
onHideShowLegsGTM,
setShowContent,
shouldShowHideLegButton,
showContent,
wagerId,
wonIllustration
} = headerMyBetsProps;
return (
<WagerCardHeader
betAmount={formatCurrency(betAmount)}
betTypeName={betTypeName}
betTicket={formatCurrency(betTicket)}
betStatus={betStatus as HeaderBetStatusType}
probableValue={approximatedPayout}
betRefund={betRefund}
onApproxPayout={onApproxPayout}
isBetWinner={isBetWinner}
isCanceled={isCanceled}
winningsAmount={winningsAmount}
shouldShowPotentialReturn={shouldShowPotentialReturn}
showMinMaxWillPays={showMinMaxWillPays}
minWillPays={minWillPays}
maxWillPays={maxWillPays}
onHideShowLegsGTM={onHideShowLegsGTM}
setShowContent={setShowContent}
shouldShowHideLegButton={shouldShowHideLegButton}
showContent={showContent}
wagerId={wagerId}
wonIllustration={wonIllustration}
/>
);
}
if (!showOnlySelections) {
return (
<Header>
<VerticalParagraphLeft>
<Paragraph
qaLabel={buildQALabel(["bet", "amount"])}
>{`${formatCurrency(betAmount)} ${betTypeName}`}</Paragraph>
<Paragraph
qaLabel={buildQALabel(["ticket", "amount"])}
fontFamily="condensedRegular"
color={colors.content.subtle}
fontSize="xs"
>
{`${formatCurrency(betTicket)} TICKET`}
</Paragraph>
</VerticalParagraphLeft>
{renderRightColumn()}
</Header>
);
}
return null;
};
const { showContent } = headerMyBetsProps || { showContent: true };
return (
<Container
showOnlySelections={showOnlySelections}
data-qa-label={`${buildQALabel([qaLabel])}${headerMyBetsProps?.wagerId ? "-" + headerMyBetsProps.wagerId : ""}`}
{...rest}
>
{renderHeader()}
{isMyBets && isOptedIn && <OptedInTag />}
{isMyBets && notificationProps && (
<WagerCardNotification
{...notificationProps}
enableMyBetsBehavior={enableMyBetsBehavior}
/>
)}
{isMyBets && promoOnboardingProps && (
<PromoOnboarding {...promoOnboardingProps} />
)}
<ContentActionsWrapper
data-qa-label={buildQALabel([
qaLabel,
"content",
"actions",
"wrapper",
headerMyBetsProps?.wagerId ? "-" + headerMyBetsProps.wagerId : ""
])}
>
{showContent ? (
<Content
hasButtons={!!onRepeatBetHandler || !!onCancelBetHandler}
isMyBets={isMyBets}
data-qa-label={buildQALabel([
qaLabel,
"content",
"actions",
"content"
])}
>
{selections?.length ? renderSelections() : null}
</Content>
) : (
<></>
)}
{onRepeatBetHandler || onCancelBetHandler ? (
<Actions
data-qa-label={buildQALabel([
qaLabel,
"content",
"actions",
"actions"
])}
>
{onRepeatBetHandler && isRepeatable && (
<IconButton
iconName="repeat"
qaLabel={buildQALabel(["repeat", "bet", "btn"])}
size="s"
color="--fd-colors-content-subtle"
onClick={onRepeatBet}
/>
)}
{onCancelBetHandler && (
<IconButton
iconName="trash"
qaLabel={buildQALabel(["cancel", "bet", "btn"])}
size="s"
color="--fd-colors-content-subtle"
onClick={onCancel}
/>
)}
</Actions>
) : null}
</ContentActionsWrapper>
{isMyBets && pickBetRebetProps && <PickBetRebet {...pickBetRebetProps} />}
{isMyBets && isFooterShown && wagerCardFooterProps && (
<WagerCardFooter
{...wagerCardFooterProps}
wagerId={headerMyBetsProps?.wagerId}
/>
)}
</Container>
);
};
export default BetTypeCell;
export type {
WagerCardFooterProps,
PickBetRebetProps,
PromoOnboardingProps,
WagerCardNotificationProps,
WagerCardHeaderProps,
SaddleSelectionsProps
};
export { BetStatusCodesEnum };
webpack://frontend-mybets/../../packages/urp-comp-my-bets/MyBetsWager.tsx
import React, { useCallback, useEffect, useRef, useState } from "react";
import { first, get, isEmpty } from "lodash";
import { useDispatch, useSelector } from "react-redux";
import { FavoriteRunners, RaceInfoMyBetsResults } from "@tvg/ts-types/Race";
import {
BetRunnerDetails,
BetSelection,
BetStatusCodesEnum
} from "@tvg/ts-types/Bet";
import {
getPickBetRebetToggle,
getSelectedSettledTab,
getSelectedTab,
getTodayActiveCounter,
getTodaySettledCounter,
getSocialShareToggle,
getFeatureUseTvgPotReturn
} from "@tvg/sh-lib-my-bets/redux/selectors";
import { calculateShowBetsDetailedView } from "@tvg/sh-lib-my-bets/utils/betsBetCard";
import { getBettingInfo } from "@tvg/desktop-bet/src/utils/betUtils";
import {
getRaceStatus,
isPickBetSub,
shouldShowWillPays
} from "@tvg/sh-lib-my-bets/utils/raceDetails";
import {
getFavoriteRunnerByLeg,
stringifySelections
} from "@tvg/sh-lib-my-bets/utils/pickBets";
import usePickBetRebet from "@tvg/sh-lib-my-bets/hooks/usePickBetRebet";
import {
onHideShowLegsGTM,
onApproxPayoutModalGtm,
showTrackRulesGtm,
expandCollapseLegGtm
} from "@tvg/sh-lib-my-bets/utils/gtm";
import { isXSell } from "@tvg/sh-utils/mobileUtils";
import {
checkAllDetailedViewIsOpen,
getWagerProps,
handleDetailsButton,
setShowContent
} from "@tvg/sh-lib-my-bets/utils/general";
import BetUtils from "@tvg/utils/betSelection";
import { useNavigate } from "react-router-dom";
import useSelections from "@tvg/sh-lib-my-bets/hooks/useSelections";
import useResults from "@tvg/sh-lib-my-bets/hooks/useResults";
import useMinMaxWillPays from "@tvg/sh-lib-my-bets/hooks/useMinMaxWillPays";
import { resetBetting } from "@tvg/desktop-bet/src/store/actions";
import { BetTypeCell } from "@tvg/design-system/web";
import { Breed } from "@tvg/design-system";
import { ActiveTabEnum } from "@tvg/sh-lib-my-bets/utils/types";
import { HeaderBetStatusType } from "@tvg/design-system/web/components/WagerCardHeader/types";
import useScratchNotification from "@tvg/sh-lib-my-bets/hooks/useScratchNotification";
import { replaceCAPIVariables } from "@tvg/utils/capiUtils";
import {
getPromosOnboardingWalletSteps,
getStoryblokPromos
} from "@tvg/sh-lib-promos-onboarding/redux/selectors";
import { useURPProgramPageOnXSell } from "@urp/amplitude-experiments";
import { MyBetsWagerProps } from "./types";
import { MyBetsWonIllustration } from "./components";
import {
getSelectionsRunnerNumber,
getVisualSelectionsFromWager,
parseSelectionsUrl
} from "./utils/selections";
import { useMyBetsPromosOnboarding } from "./components/promosOnboarding/hooks";
import repeatBetEvent from "./utils/gtm/repeatBetEvent";
export const MyBetsWager = (props: MyBetsWagerProps) => {
const {
wager,
mainWagerDetails,
index,
wagerIndex,
races,
raceNumber,
statusCode,
betAmount,
bettingInterests,
currentRaceDate,
allRacesFromTrack,
modalScrollableRef,
closeModal,
raceUrl,
showContentObj,
setShowContentObj,
currentRace,
currentOpenLeg,
hasFooter,
onCancelWager,
isBetPlaced,
isBetConfirmation,
isInsideRaceOfficials,
onShareWager,
openedDetailedViews,
setOpenedDetailedViews
} = props;
const navigate = useNavigate();
const dispatch = useDispatch();
const selectedTab = useSelector(getSelectedTab);
const selectedSettledTab = useSelector(getSelectedSettledTab);
const activeBetsCounter = useSelector(getTodayActiveCounter);
const settledBetsCounter = useSelector(getTodaySettledCounter);
const enablePickBetRebet = useSelector(getPickBetRebetToggle);
const promosOnboardingObject = useSelector(getStoryblokPromos);
const customMessageCapi = useSelector(getPromosOnboardingWalletSteps);
const socialShareModalToggle = useSelector(getSocialShareToggle);
const useTvgPotReturnToggle = useSelector(getFeatureUseTvgPotReturn);
const isURPPpOnXSellEnabled = useURPProgramPageOnXSell();
const {
isBetWinner,
isOptedIn,
wagerBetStatus,
isCurrentRaceDate,
isCanceled,
isActive,
currentWagerTypeCode,
isWagerCancelable,
isMultiRace,
isWheel,
isKey,
isBox,
isPickBet,
isExotic,
isXsellBlacklisted
} = getWagerProps(
wager,
statusCode,
currentRaceDate,
get(mainWagerDetails, 0, ""),
isURPPpOnXSellEnabled,
currentRace
);
const selectionSize = get(wager, "selections.selection.length", 0);
const finalBettedLeg = currentRace
? +get(currentRace, "number", "0") + (selectionSize - 1)
: 0;
const betResults: RaceInfoMyBetsResults[] = [];
const betStatusName =
wagerBetStatus.name.toUpperCase() as HeaderBetStatusType;
const isSpecialWager = get(wager, "isSpecialWager", false);
if (allRacesFromTrack && allRacesFromTrack.length > 0 && raceNumber) {
for (let j = +raceNumber - 1; j < +raceNumber + selectionSize - 1; j += 1) {
if (
allRacesFromTrack[j as number] &&
allRacesFromTrack[j as number].results
) {
betResults.push(
allRacesFromTrack[j as number].results as RaceInfoMyBetsResults
);
}
}
}
const showWillPays =
currentRace && allRacesFromTrack && isMultiRace && betResults && !isCanceled
? shouldShowWillPays(
allRacesFromTrack,
wager.selections.selection,
betResults,
finalBettedLeg
)
: false;
const results = useResults({
allRacesFromTrack
});
const selections = useSelections({
wager,
isMultiRace,
raceNumber,
currentRace,
currentRaceDate,
finalBettedLeg,
showWillPays,
allRacesFromTrack,
currentWagerTypeCode,
isActive,
results,
isExotic
});
const betCardRef = useRef<HTMLDivElement>(null);
const showBetsDetailedView = get(openedDetailedViews, index, {});
const currentBetDetailedView = get(showBetsDetailedView, wagerIndex, []);
// Scroll betCard inToView
const handleScrollPosition = useCallback(() => {
if (
betCardRef.current &&
modalScrollableRef &&
typeof betCardRef.current.scrollIntoView === "function" &&
typeof betCardRef.current.getBoundingClientRect === "function"
) {
setTimeout(() => {
// this headerOffset is based on modal header height + plus Tab height and or plus the timeframe height
const headerOffset = selectedTab === "SETTLED" ? 164 : 96;
const betCardBoundingClientRect: DOMRect | null =
betCardRef.current && betCardRef.current.getBoundingClientRect();
const screenHeight =
get(window, "innerHeight") ||
get(document, "documentElement.clientHeight", 0);
const isBetCardVisible =
betCardBoundingClientRect &&
betCardBoundingClientRect.top >= headerOffset &&
betCardBoundingClientRect.bottom <= screenHeight;
if (!isBetCardVisible && modalScrollableRef) {
modalScrollableRef.scrollTo({
y: betCardRef.current
? betCardRef.current.offsetTop - headerOffset
: undefined,
animated: true
});
}
}, 0);
}
}, [currentBetDetailedView]);
const [favoriteRunnerByLeg, setFavoriteRunnerByLeg] =
useState<FavoriteRunners>([]);
const [autoOpenedWillPays, setAutoOpenedWillPays] = useState(false);
const isDetailsOpened = checkAllDetailedViewIsOpen(currentBetDetailedView);
const validRunners = selections.map((bet) =>
bet.reduce((accSelection: BetRunnerDetails[], selection) => {
selection.runners.filter((runner) => {
if (!runner.isScratched) {
accSelection.push(runner);
}
return accSelection;
});
return accSelection;
}, [])
);
const isBetValid = validRunners.every((bet) => bet.length > 0);
const [shouldRenderFooter, setShouldRenderFooter] = useState(true);
const repeatButtonSearch = useCallback(() => {
const newSelectionsWithoutScratch = selections.map((selection) =>
selection.reduce((accSelection: BetSelection[], currSelection) => {
const runners = get(currSelection, "runners") || [];
if (runners.some((runner) => !runner.isScratched)) {
accSelection.push(currSelection);
}
return accSelection;
}, [])
);
return `?race=${raceNumber}&wt=${currentWagerTypeCode}&bet=${
wager.wagerAmount
}${stringifySelections(newSelectionsWithoutScratch)}&type=Repeat`;
}, [
currentWagerTypeCode,
raceNumber,
JSON.stringify(selections),
wager.wagerAmount
]);
useEffect(() => {
const willPaysFetched =
currentOpenLeg &&
!!get(
allRacesFromTrack,
`[${+currentOpenLeg.number - 1}].willPays`,
false
);
if (
(!currentBetDetailedView.length ||
!get(currentBetDetailedView, "[0].length", true)) &&
typeof setOpenedDetailedViews === "function"
) {
setOpenedDetailedViews((prevShowedBets) =>
prevShowedBets.map((showedBet, betIndex) =>
betIndex === index
? {
...showedBet,
[wagerIndex]: calculateShowBetsDetailedView(
selections,
showWillPays
)
}
: showedBet
)
);
} else if (
showWillPays &&
willPaysFetched &&
!autoOpenedWillPays &&
typeof setOpenedDetailedViews === "function"
) {
const newDetailedView = currentBetDetailedView.map(
(leg, legIndex) => legIndex === currentBetDetailedView.length - 1 || leg
);
setAutoOpenedWillPays(true);
setOpenedDetailedViews((prevShowedBets) =>
prevShowedBets.map((showedBet, betIndex) =>
betIndex === index
? {
...showedBet,
[wagerIndex]: newDetailedView
}
: showedBet
)
);
}
}, [
selectedTab,
JSON.stringify(selections),
showWillPays,
setOpenedDetailedViews
]);
useEffect(() => {
if (allRacesFromTrack) {
setFavoriteRunnerByLeg(
getFavoriteRunnerByLeg(
selections,
allRacesFromTrack,
+raceNumber,
wager.raceDate
)
);
}
}, [allRacesFromTrack, JSON.stringify(selections)]);
useEffect(() => {
if (typeof setOpenedDetailedViews === "function") {
setOpenedDetailedViews((prevShowedBets) =>
prevShowedBets.map((showedBets, betIndex) => {
if (betIndex === index) {
if (get(showedBets, wagerIndex, []).length) {
return showedBets;
}
return {
...showedBets,
[wagerIndex]: calculateShowBetsDetailedView(
selections,
showWillPays
)
};
}
return showedBets;
})
);
}
if (get(wager, "betStatus.code") === "R") {
const isCancelDataOpen = statusCode === "O";
const isCancelDataUpNext = statusCode === "IC";
setShouldRenderFooter(isCancelDataOpen || isCancelDataUpNext);
}
}, [setOpenedDetailedViews]);
const betStatusCode = wagerBetStatus.code as BetStatusCodesEnum;
const betRefund = get(wager, "betRefund", 0);
const wagerType = get(wager, "wagerType");
const wagerId = get(wager, "wagerType.id");
const wagerAmount = get(wager, "betTotal", 0);
const rebateLimit = get(promosOnboardingObject, "rebateLimit", 0);
const amountToShow = wagerAmount > rebateLimit ? rebateLimit : wagerAmount;
const customPromoOnboardingMessage = replaceCAPIVariables(customMessageCapi, {
amountToShow
});
const isSettledBet = selectedTab === ActiveTabEnum.SETTLED;
const fullSelections = getVisualSelectionsFromWager(selections, isSettledBet);
let numberOfWagerableRunnersResult: string[] | undefined;
if (currentRace) {
const typeFromRace = BetUtils.getOriginalBetTypeFromRace(
currentRace,
wagerId
);
const selectionsRunnerNumber = getSelectionsRunnerNumber(wager);
const { numberOfWagerableRunners } = getBettingInfo(
selectionsRunnerNumber,
wager.wagerAmount,
currentRace,
races,
typeFromRace
);
numberOfWagerableRunnersResult = numberOfWagerableRunners;
}
const scratches = BetUtils.getSelectionsRunnerNbrScratched(fullSelections);
const { minWillPays, maxWillPays, showMinMaxWillPays } =
useMinMaxWillPays(selections);
const [
showScratchedNotification,
shouldNotHideScratchNotification,
setShouldNotHideScratchNotification,
scratchedTitle,
scratchedLegText,
hasAlternates
] = useScratchNotification({
selections,
isPickBet,
betStatusCode,
favoriteRunnerByLeg,
currentWagerTypeCode,
isCurrentRaceDate,
betRefund
});
const [
handleRebetClickEvent,
rebetWagerTypeName,
rebetSearch,
shouldShowRebet
] = usePickBetRebet({
allRacesFromTrack,
mainWagerDetails,
currentRace,
currentOpenLeg,
callback: closeModal,
selections,
enablePickBetRebet,
isPickBet,
isCurrentRaceDate,
isSettledBet
});
const showRepeatButton =
!shouldShowRebet &&
(wager.cancelable ||
betStatusName === "CANCELED" ||
betStatusName === "ACTIVE") &&
raceNumber &&
raceUrl &&
betAmount !== undefined &&
(statusCode === "O" || statusCode === "IC") &&
selectedTab !== "FUTURES" &&
isBetValid;
const { placeToRender, shouldShowPromoOnboarding } =
useMyBetsPromosOnboarding({
bettingInterests,
currentRace,
isBetConfirmation: !!isBetConfirmation,
isBetPlaced: !!isBetPlaced,
wager
});
const hasLostOneLeg = useCallback(
() =>
selections.some(
(leg) => !leg.some((sel) => sel.isWinner || sel.isWinner === null)
),
[selections]
);
const betProbableValue = get(wager, "probable", "0");
const showContent = get(showContentObj, wager?.id || "", true);
const isBetRefund =
get(wager, "betRefund", 0) > 0 &&
(betStatusName === "WINNER" || betStatusName === "REFUNDED");
const shouldShowPotentialReturn =
useTvgPotReturnToggle &&
!showWillPays &&
!hasLostOneLeg() &&
betProbableValue !== "0";
const shouldShowHideLegButton =
isMultiRace &&
hasLostOneLeg() &&
selectedTab === ActiveTabEnum.ACTIVE &&
!shouldShowPotentialReturn &&
!isInsideRaceOfficials;
const currentRaceNumber = currentRace
? currentRace?.number.toString()
: raceNumber.toString();
const renderWonIllustration = (qaLabelWon: string, winAmount: number) => (
<MyBetsWonIllustration qaLabel={qaLabelWon} winAmount={winAmount} />
);
const statusRaces = selections.map((selection, indexSelection, { length }) =>
getRaceStatus({
isAllRunnersScratched: selection.every((runner) =>
runner.runners.every((r) => r.isScratched)
),
legContainsScratch: selection.some((runner) =>
runner.runners.every((r) => r.isScratched)
),
selection,
selectionIndex: indexSelection,
races: allRacesFromTrack,
raceNumber,
selectionLength: length,
isMultiRace,
isCanceled,
betStatusName,
wagerType: currentWagerTypeCode,
favoriteRunner: !isEmpty(favoriteRunnerByLeg)
? favoriteRunnerByLeg[indexSelection as number]
: undefined,
shouldShowReplacement:
hasAlternates ||
(currentWagerTypeCode && isPickBetSub(currentWagerTypeCode))
})
);
return (
<BetTypeCell
enableMyBetsBehavior
key={`wager-${get(wager, "id", index)}`}
approximatedPayout={betProbableValue}
betAmount={get(wager, "wagerAmount", 0)}
betStatus={betStatusName}
betTicket={get(wager, "betTotal", 0)}
betTypeName={get(wager, "wagerType.name", "")}
isKey={isKey}
isBox={isBox}
isLeg={isMultiRace}
isWheel={isWheel}
numWagerableRunners={numberOfWagerableRunnersResult}
raceNumber={currentRaceNumber}
completeSelection={fullSelections}
selections={fullSelections[0]}
favoriteRunnerByLeg={favoriteRunnerByLeg}
type={wagerType.code}
scratches={scratches}
isOptedIn={isOptedIn}
racesStatus={statusRaces}
isFooterShown={shouldRenderFooter && hasFooter && showContent}
wagerDetails={currentBetDetailedView}
shouldShowRefundTag={isBetRefund}
betRefund={betRefund}
isSpecialWager={isSpecialWager}
showReplacedRunners={
!isActive &&
(hasAlternates ||
(currentWagerTypeCode && isPickBetSub(currentWagerTypeCode)))
}
onDetailsView={(raceIndexSelection) => {
const isOpened = get(currentBetDetailedView, raceIndexSelection, false);
expandCollapseLegGtm(
isOpened ? "Closed Leg" : "Opened Leg",
raceIndexSelection + 1,
selectedTab,
selectedSettledTab,
activeBetsCounter,
settledBetsCounter
);
setOpenedDetailedViews((prevShowedBets) => {
const showedBet = prevShowedBets[index] || {};
const wagerArray = showedBet[wagerIndex] || [];
const updatedShowedBet = [...wagerArray];
const currentValue = updatedShowedBet[raceIndexSelection];
updatedShowedBet[raceIndexSelection] = !currentValue;
return prevShowedBets.map((mappedShowedBet, betIndex) =>
betIndex === index
? {
...mappedShowedBet,
[wagerIndex]: updatedShowedBet
}
: mappedShowedBet
);
});
}}
breed={
`${get(
currentRace,
"type.name",
"Thoroughbred"
)}`.toLowerCase() as Breed
}
headerMyBetsProps={{
isBetWinner,
isCanceled,
maxWillPays,
minWillPays,
onApproxPayout: () =>
onApproxPayoutModalGtm(dispatch, {
selectedTab,
selectedSettledTab,
activeBetsCount: +activeBetsCounter,
settledBetsCount: +settledBetsCounter
}),
onHideShowLegsGTM: (isOpening: boolean) =>
onHideShowLegsGTM({
isOpening,
activeBets: activeBetsCounter,
settledBets: settledBetsCounter
}),
setShowContent: (value: boolean, id: string) =>
setShowContent(value, id, showContentObj, setShowContentObj),
shouldShowHideLegButton,
shouldShowPotentialReturn,
showContent,
showMinMaxWillPays,
wagerId: get(wager, "id", ""),
winningsAmount: get(wager, "winningsAmount", 0),
wonIllustration: renderWonIllustration
}}
notificationProps={{
scratchedLegText,
scratchedTitle,
shouldNotHideScratchNotification,
showScratchedNotification,
wagerId: get(wager, "id", ""),
onDismissPress: setShouldNotHideScratchNotification,
onNotificationPress: () => {
showTrackRulesGtm(
dispatch,
selectedTab,
selectedSettledTab,
currentWagerTypeCode,
hasAlternates
);
}
}}
pickBetRebetProps={{
isContentDisplayed: showContent,
onClickBet: () => {
navigate({
pathname: raceUrl && first(raceUrl.split("?")),
search: rebetSearch
});
handleRebetClickEvent();
dispatch(resetBetting());
},
rebetWagerTypeName,
shouldShowRebet
}}
promoOnboardingProps={{
placeToRender,
isShown: shouldShowPromoOnboarding,
customMessage: customPromoOnboardingMessage
}}
wagerCardFooterProps={{
hasSocialShare: socialShareModalToggle,
onPressShareWager: () =>
onShareWager(parseSelectionsUrl(repeatButtonSearch())),
hasRepeatButton: !!showRepeatButton,
isBetActive: isActive,
isXsellBlacklistedBet: isXSell() && isXsellBlacklisted,
onRepeatPress: () => {
navigate({
pathname: first(raceUrl.split("?")),
search: repeatButtonSearch().substring(1)
});
closeModal();
repeatBetEvent({
raceNumber,
trackName: currentRace?.trackName ?? "",
betType: wager.wagerType.name,
betAmount: String(wagerAmount),
selectionSource: "repeat_bet_mybets",
raceType: currentRace?.type?.name ?? ""
});
dispatch(resetBetting());
},
hasCancelButton: isWagerCancelable,
onCancelWager: () => {
onCancelWager(wager);
},
onDetailsPress: () =>
handleDetailsButton(
selectedTab,
selectedSettledTab,
isDetailsOpened,
currentBetDetailedView,
(detailedViews) => {
setOpenedDetailedViews((prevShowedBets) =>
prevShowedBets.map((showedBet, betIndex) =>
betIndex === index
? {
...showedBet,
[wagerIndex]: detailedViews
}
: showedBet
)
);
},
selections,
handleScrollPosition
),
isDetailsOpened
}}
isMyBets
/>
);
};
export default MyBetsWager;
webpack://frontend-mybets/../../packages/urp-comp-my-bets/utils/selections.ts
import type { BetSelection, VisualSelections } from "@tvg/ts-types/Bet";
import type { WroWager } from "@tvg/ts-types/WroWager";
export const getSelectionsRunnerNumber = (
wager: WroWager
): Array<Array<string>> =>
(wager.selections?.selection || []).map((selection) =>
selection.runners.map((runner) => runner.number.toString())
);
export const getVisualSelectionsFromWager = (
selections: BetSelection[][],
isSettled?: boolean
) =>
selections.reduce(
(visualSelectionsAcc: VisualSelections[], runnersWagerGroup) => {
const groupSelections: VisualSelections = [];
runnersWagerGroup.forEach((wagerGroup) => {
const { currentOdds, isWinner, willPayAmount, alternate } = wagerGroup;
wagerGroup.runners.forEach((runner) =>
groupSelections.push({
currentOdds,
number: runner.runnerId,
runnerName: runner.runnerName,
scratched: runner.isScratched,
saddleColor: runner.saddleColor,
numberColor: runner.numberColor,
winner: !!isWinner,
willPay: willPayAmount,
isAlternate: false,
isSettled
})
);
if (alternate) {
alternate.runners.forEach((runner) => {
if (
groupSelections.findIndex(
(sel) => sel.number === runner.runnerId
) === -1
) {
groupSelections.push({
currentOdds: alternate?.currentOdds,
number: runner.runnerId,
runnerName: runner.runnerName,
scratched: runner.isScratched,
saddleColor: runner.saddleColor,
numberColor: runner.numberColor,
winner: !!alternate.isWinner,
willPay: 0,
isAlternate: true,
isSettled
});
}
});
}
});
visualSelectionsAcc.push(groupSelections);
return visualSelectionsAcc;
},
[]
);
export const parseSelectionsUrl = (url: string): string => {
if (!url) return "";
const urlParsed = url.split("&");
if (urlParsed.length) {
urlParsed.shift();
urlParsed.pop();
return urlParsed.join("&");
}
return "";
};
webpack://frontend-mybets/../../packages/urp-comp-my-bets/components/promosOnboarding/hooks.ts
import { useMemo } from "react";
import { Store } from "redux";
import { useSelector } from "react-redux";
import { get } from "lodash";
import { BettingInterest, RaceTypeCodeEnum } from "@tvg/ts-types/Race";
import { matchWagerPropositions } from "@tvg/sh-lib-promos-onboarding/utils/matchWagerPropositions";
import { matchPlacedWager } from "@tvg/sh-lib-promos-onboarding/utils/matchPlacedWager";
import { getStoryblokPromoByStep } from "@tvg/sh-lib-promos-onboarding/redux/selectors";
import {
PromoStepType,
WagerStep
} from "@tvg/sh-lib-promos-onboarding/types/promoSteps";
import { StoryblokPlaceName } from "@tvg/sh-lib-promos-onboarding/types/promoOnboardingComponents";
import { MyBetsWager } from "@tvg/sh-lib-promos-onboarding/types/wager";
import { MyBetsPromosOnboarding } from "./types";
export const useMyBetsPromosOnboarding = ({
wager,
currentRace,
isBetPlaced,
bettingInterests,
isBetConfirmation
}: MyBetsPromosOnboarding) => {
const promosOnboardingStep = useSelector((store: Store) =>
getStoryblokPromoByStep(store, PromoStepType.WAGER)
);
return useMemo(() => {
const biNumbers = bettingInterests.reduce(
(previous: number[], current: BettingInterest[]) => [
...previous,
...(current || []).map((bi) => bi.biNumber)
],
[]
);
const wagerData: Partial<MyBetsWager> = {
bettingInterests: biNumbers,
raceNumber: get(currentRace, "number"),
breedTypeCode: get(wager, "raceTypeAbbreviation", "") as RaceTypeCodeEnum,
raceDate: get(currentRace, "raceDate", ""),
trackCode: get(currentRace, "trackCode", ""),
wagerTypeCode: get(wager, "wagerType.code", ""),
serialNumber: get(wager, "serialNumber", "")
};
if (isBetConfirmation) {
const placeToRender = isBetPlaced
? StoryblokPlaceName.BETSLIP_PLACED
: StoryblokPlaceName.BETSLIP_CONFIRMATION;
const shouldShowPromoOnboarding = promosOnboardingStep
? matchWagerPropositions(promosOnboardingStep, wagerData)
: false;
return { placeToRender, shouldShowPromoOnboarding };
}
const shouldShowPromoOnboarding = promosOnboardingStep
? matchPlacedWager(promosOnboardingStep as WagerStep, wagerData)
: false;
return {
placeToRender: StoryblokPlaceName.MYBETS_WAGER_FOOTER,
shouldShowPromoOnboarding
};
}, [
wager,
currentRace,
isBetPlaced,
bettingInterests,
isBetConfirmation,
promosOnboardingStep
]);
};
webpack://frontend-mybets/../../packages/urp-comp-my-bets/utils/gtm/repeatBetEvent.ts
import mediator from "@tvg/mediator";
interface PlaceBetGtm {
raceNumber: number;
trackName: string;
betType: string;
betAmount: string;
selectionSource: string;
raceType: string;
specialWagerType?: string;
}
const repeatBetEvent = ({
raceNumber,
trackName,
betType,
betAmount,
selectionSource,
raceType,
specialWagerType
}: PlaceBetGtm) => {
mediator.base.dispatch({
type: "MYBETS_ADD_TO_BETSLIP",
payload: {
module: "my_bets",
raceNumber,
trackName,
betType,
betAmount,
selectionSource,
raceType,
specialWagerType
}
});
};
export default repeatBetEvent;
webpack://frontend-mybets/../../packages/urp-comp-my-bets/MyBetsBody.tsx
import React, { memo, useEffect, useRef, useState } from "react";
import { first, get, has, last, noop } from "lodash";
import { Store } from "redux";
import { useDispatch, useSelector } from "react-redux";
import {
getIsMyBetsOpen,
getSelectedSettledTab,
getSelectedTab,
getShowSeeResult,
getTodayActiveCounter,
getTodaySettledCounter,
getWatchReplayWithinMyBets
} from "@tvg/sh-lib-my-bets/redux/selectors";
import {
getActiveLegs,
getRaceProps,
getRacesInPickBets,
isMultiRaceBet
} from "@tvg/sh-lib-my-bets/utils/raceDetails";
import {
getWagerToRender,
scrollActiveBetIntoView,
scrollActivePillIntoView,
shouldRenderWager,
useIsomorphicLayoutEffect
} from "@tvg/sh-lib-my-bets/utils/general";
import {
getVideoFeedback,
onVideoRedirect
} from "@tvg/sh-lib-my-bets/utils/video";
import buildRaceUrl from "@tvg/formatter/url";
import {
cleanBetCancelResult,
openBetSocialShareModal,
openMybetsPastPerformance
} from "@tvg/sh-lib-my-bets/redux/actions";
import {
handleRaceHeaderGtm,
onCancelBetModalGtm
} from "@tvg/sh-lib-my-bets/utils/gtm";
import {
RaceStatusEnum,
RaceTypeCodeEnum,
RaceVideoFeedback
} from "@tvg/ts-types/Race";
import useAllRacesFromTrack from "@tvg/sh-lib-my-bets/hooks/useAllRacesFromTrack";
import { ActiveTabEnum, SettledTabEnum } from "@tvg/sh-lib-my-bets/utils/types";
import { WroWager, WroWagerGroup } from "@tvg/ts-types/WroWager";
import { BetStatusCodesEnum } from "@tvg/ts-types/Bet";
import type { MyBetsBodyProps, ShowContent } from "./types";
import { MyBetsCard } from "./components";
import MyBetsWager from "./MyBetsWager";
const MyBetsBody = ({
bet = {} as WroWagerGroup,
index = -1,
races = [],
closeModal = noop,
currentRaceDate = "",
modalScrollableRef = null,
hasWagerFooter = true,
selectedWager = undefined,
hasPastPerformance = true,
showLiveVideo = true,
showRaceLeg = true,
hasWagerDetails = true,
isCancelModal = false,
isInsideRaceOfficials = false,
isDesktop = false,
indexBuffer,
openedDetailedViews,
setOpenedDetailedViews,
setIndexBuffer,
isLoadingGraphs = false
}: MyBetsBodyProps) => {
const myBetsCardRef = useRef<HTMLDivElement>(null);
const MILISECONDS_IN_A_DAY = 1000 * 3600 * 24;
const selectedTab = useSelector((store: Store) => getSelectedTab(store));
const isMyBetsOpen = useSelector((store: Store) => getIsMyBetsOpen(store));
const selectedSettledTab = useSelector((store: Store) =>
getSelectedSettledTab(store)
);
const activeBetsCounter = useSelector((store: Store) =>
getTodayActiveCounter(store)
);
const settledBetsCounter = useSelector((store: Store) =>
getTodaySettledCounter(store)
);
const isReplayInsideMyBets = useSelector((store: Store) =>
getWatchReplayWithinMyBets(store)
);
const showSeeResult = useSelector((store: Store) => getShowSeeResult(store));
const dispatch = useDispatch();
const wagers: Array<WroWager> = get(bet, "wagers", []);
const [showContentObj, setShowContentObj] = useState(
wagers.reduce((acc, wager) => {
const wagerId = get(wager, "id");
if (wagerId) {
acc[wagerId] = true;
}
return acc;
}, {} as ShowContent)
);
useIsomorphicLayoutEffect(() => {
if (indexBuffer) {
scrollActiveBetIntoView(indexBuffer);
setIndexBuffer(0);
}
if (
selectedSettledTab === SettledTabEnum.LAST_MONTH ||
selectedSettledTab === SettledTabEnum.LAST_WEEK
) {
scrollActivePillIntoView();
}
}, []);
useEffect(() => {
let updateInfo = false;
let auxObj = {};
if (wagers.length > 0) {
auxObj = wagers.reduce((acc, wager) => {
const wagerId = get(wager, "id", "0");
if (!has(showContentObj, wagerId)) {
acc[wagerId] = true;
updateInfo = true;
}
return acc;
}, {} as ShowContent);
}
if (updateInfo) {
setShowContentObj({ ...showContentObj, ...auxObj });
}
}, [wagers]);
const mainWagerDetails: Array<string> = get(bet, "value", "||0").split("|");
const [raceDate, trackCode] = mainWagerDetails;
const raceNumber = +get(mainWagerDetails, 2, "0");
const biggestSelectionSize: number = get(
first(
wagers.sort(
(a, b) => b.selections.selection.length - a.selections.selection.length
)
),
"selections.selection.length",
0
);
const currentRace = races.find(
(race) =>
race.id === `${trackCode}-${raceNumber}` && race.raceDate === raceDate
);
const trackName: string = get(bet, "wagers[0].trackName");
const racePostTime: string = get(bet, "wagers[0].racePostTime");
const isBetStatusNotCanceledOrRefunded: boolean = wagers.some(
(wager) =>
wager.betStatus.code !== BetStatusCodesEnum.REFUNDED &&
wager.betStatus.code !== BetStatusCodesEnum.CANCELED
);
const allRacesFromTrack = useAllRacesFromTrack({ races, trackCode });
const activeRaces =
allRacesFromTrack &&
allRacesFromTrack.length > 0 &&
getActiveLegs(allRacesFromTrack, raceNumber, biggestSelectionSize);
const currentOpenLeg = activeRaces ? first(activeRaces) : undefined;
const legRaces = getRacesInPickBets(
allRacesFromTrack,
raceNumber,
biggestSelectionSize
);
const bettingInterests = allRacesFromTrack.map(
(race) => race.bettingInterests
);
const dateDiff =
(new Date(racePostTime).getTime() - new Date().getTime()) /
MILISECONDS_IN_A_DAY;
// Removed greyhounds variation since its not being used elsewhere (ex. tracks page, talent picks)
const raceUrl: string = buildRaceUrl(trackCode, trackName, raceNumber);
const betsNumber = wagers.filter(
(cur) =>
cur.betStatus.code !== BetStatusCodesEnum.CANCELED &&
cur.betStatus.code !== BetStatusCodesEnum.REFUNDED
).length;
const betAmount = wagers.reduce((acc, cur) => {
const currentBetTotal =
cur.betStatus.code !== BetStatusCodesEnum.CANCELED &&
cur.betStatus.code !== BetStatusCodesEnum.REFUNDED
? cur.betTotal
: 0;
return acc + currentBetTotal;
}, 0);
// Check if at least one of the bets are Pick/MultiRace Bets
const isMultiRace = !!wagers
.map((b) => isMultiRaceBet(b.wagerType.code))
.findIndex((b) => b === false);
const isAllBetsCancelled =
!!get(wagers, "length", 0) &&
wagers.every((b) => b.betStatus.code === BetStatusCodesEnum.CANCELED);
const isSettledBet = selectedTab === ActiveTabEnum.SETTLED;
const isFutureBet = selectedTab === ActiveTabEnum.FUTURES;
let videoFeedback = RaceVideoFeedback.NOT_AVAILABLE_NO_REPLAY;
if (isMultiRace && currentOpenLeg && !isSettledBet) {
videoFeedback = getVideoFeedback(
currentOpenLeg,
first(allRacesFromTrack),
last(allRacesFromTrack)
);
} else if (currentRace) {
videoFeedback = getVideoFeedback(
currentRace,
first(allRacesFromTrack),
last(allRacesFromTrack)
);
}
const hasRaceLeg =
isMultiRace && !isSettledBet && currentRace && currentOpenLeg;
const {
mtp,
statusCode,
legStatusCode,
legNumber,
hasLiveVideo,
currentRaceNumber,
raceType
} = getRaceProps({
isMultiRace,
legRaces,
isCancelled: isAllBetsCancelled,
currentRace,
currentLeg: currentOpenLeg,
bet,
isSettledBet,
currentRaceDate,
betDate: raceDate,
videoFeedback,
raceNumber
});
const hasReplayVideo = videoFeedback.indexOf("NO_REPLAY") === -1;
return (
<MyBetsCard
ref={myBetsCardRef}
hasPastPerformance={
hasPastPerformance &&
isSettledBet &&
isBetStatusNotCanceledOrRefunded &&
statusCode === RaceStatusEnum.RACE_OFFICIAL &&
raceType !== RaceTypeCodeEnum.GREYHOUNDS &&
(hasReplayVideo || showSeeResult)
}
hasReplayVideo={hasReplayVideo}
showSeeResult={showSeeResult}
hasLiveVideo={showLiveVideo && hasLiveVideo}
legNumber={legNumber}
onVideoRedirect={() =>
onVideoRedirect(closeModal, {
selectedTab,
settledBets: settledBetsCounter,
activeBets: activeBetsCounter,
selectedSettledTab
})
}
showBetInfoHeader={betsNumber > 0 && betAmount > 0}
showRaceLeg={showRaceLeg && !!hasRaceLeg}
mtp={mtp}
isRaceNear={mtp <= 5}
dateDiff={dateDiff}
closeModal={closeModal}
index={index}
onWatchReplay={(showIppInsideMybets = true) => {
handleRaceHeaderGtm("MYBETS_USER_CLICKS_WATCH_REPLAY", {
selectedTab,
selectedSettledTab,
activeBets: activeBetsCounter,
settledBets: settledBetsCounter,
gaEventLabel: hasReplayVideo ? "watch_replay" : "see_result"
});
if (showSeeResult && showIppInsideMybets) {
const modalTitle = `${trackName} R${raceNumber} - Replay`;
setIndexBuffer(index);
dispatch(
openMybetsPastPerformance(
{
trackCode,
raceNumber,
raceDate
},
modalTitle
)
);
}
}}
isReplayInsideMyBets={isReplayInsideMyBets}
isMyBetsOpen={isMyBetsOpen}
racePostTime={racePostTime}
trackName={trackName}
legStatusCode={legStatusCode}
statusCode={statusCode}
raceNumber={raceNumber}
raceUrl={raceUrl}
betsNumber={betsNumber}
betAmount={betAmount}
currentRaceNumber={currentRaceNumber}
isFutureBet={isFutureBet}
raceDate={raceDate}
isLoadingGraphs={isLoadingGraphs}
isSpecialWager={get(wagers[0], "isSpecialWager", false)}
>
{/* Render evert single wager for this specific track */}
{getWagerToRender(wagers, selectedWager).map((wager, wagerIndex) => {
const raceStatus: RaceStatusEnum = get(currentRace, "status.code");
const isCancelled =
get(wager, "betStatus.code") === BetStatusCodesEnum.CANCELED &&
raceStatus !== RaceStatusEnum.OPEN &&
raceStatus !== RaceStatusEnum.UP_NEXT;
return shouldRenderWager(
selectedTab,
currentRaceDate,
get(wager, "raceDate", "")
) ? (
<MyBetsWager
key={`wager-${get(wager, "id", "unk")}-${mainWagerDetails.join(
"-"
)}`}
isDesktop={isDesktop}
wagerIndex={wagerIndex}
index={index}
wager={wager}
mainWagerDetails={mainWagerDetails}
races={races}
raceNumber={raceNumber}
statusCode={statusCode}
legStatusCode={legStatusCode}
betAmount={betAmount}
bettingInterests={bettingInterests}
currentRaceDate={currentRaceDate}
allRacesFromTrack={allRacesFromTrack}
modalScrollableRef={modalScrollableRef}
closeModal={closeModal}
raceUrl={raceUrl}
showContentObj={showContentObj}
setShowContentObj={setShowContentObj}
currentRace={currentRace}
currentOpenLeg={currentOpenLeg}
hasFooter={hasWagerFooter && !isCancelled}
hasDetails={hasWagerDetails && !isCancelled}
hasContentMaxHeight={isCancelModal}
openedDetailedViews={openedDetailedViews}
setOpenedDetailedViews={setOpenedDetailedViews}
onCancelWager={() => {
dispatch(cleanBetCancelResult());
onCancelBetModalGtm(
dispatch,
{
bet,
wager,
hasBackgroundModal: true
},
selectedTab,
selectedSettledTab
);
}}
isInsideRaceOfficials={isInsideRaceOfficials}
onShareWager={(repeatButtonSearch: string) => {
dispatch(
openBetSocialShareModal({
bet,
wager,
repeatButtonSearch,
isMyBets: true
})
);
}}
/>
) : null;
})}
</MyBetsCard>
);
};
export default memo(MyBetsBody);
webpack://frontend-mybets/../../packages/tvg-comp-bet-cancel/utils/service.js
import wtx from "@tvg/api/wtx";
import performanceUtils from "@tvg/utils/performanceUtils";
const cancelBet = ({ wager, accountNumber }) => {
performanceUtils.register("cancel_bet");
return wtx
.cancelBet(wager.serialNumber, wager.wagerReference, accountNumber)
.then((res) => {
performanceUtils.measure("cancel_bet");
return res;
});
};
export default cancelBet;
webpack://frontend-mybets/../../packages/tvg-lib-utils/performanceUtils.js
export default {
register: (mark, timing = null) => {
if (typeof window === "object" && window.perf) {
window.perf.register(mark, timing);
}
},
measure: (mark, tags) => {
if (typeof window === "object" && window.perf) {
window.perf.measure(mark, tags);
}
}
};
webpack://frontend-mybets/../../packages/tvg-comp-bet-cancel/styled-components.js
/* eslint-disable import/prefer-default-export */
import styled from "styled-components";
import buildColor from "@tvg/atomic-ui/_static/ColorPalette";
import { fontMedium } from "@tvg/atomic-ui/_static/Typography";
import { Link } from "react-router-dom";
export const BetItemWrapperBetCancel = styled.div`
display: flex;
flex-direction: column;
background-color: ${buildColor("white", "100")};
position: relative;
margin-top: 0;
`;
export const ButtonsContainer = styled.div`
font-family: ${fontMedium};
font-size: 14px;
display: flex;
flex-direction: column;
padding: 0 12px 12px 12px;
button:not(:last-child) {
margin-bottom: 8px;
}
background-color: ${buildColor("white", "100")};
min-height: 100px;
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
`;
export const BetCancelBetItemLinkContainer = styled(Link)`
display: flex;
flex: 1;
flex-direction: column;
justify-content: center;
text-decoration: none;
color: ${buildColor("grey", "800")};
padding: 12px;
&:active {
background-color: ${buildColor("blue_accent", "100")};
}
`;
export const BetCancelLoadingMask = styled.div`
position: absolute;
left: 0;
top: 0;
z-index: 5;
width: 100%;
height: 100%;
background-color: ${buildColor("white", "50")};
`;
webpack://frontend-mybets/../../packages/tvg-comp-bet-cancel/index.jsx
import React, { useMemo, useEffect } from "react";
import { get, noop } from "lodash";
import { connect } from "react-redux";
import buildColor from "@tvg/atomic-ui/_static/ColorPalette";
import BetCancelNotification from "@tvg/atomic-ui/_molecule/BetNotification";
import formatCurrency from "@tvg/formatter/currency";
import SpinningWheel from "@tvg/atomic-ui/_atom/SpinningWheel";
import Button from "@tvg/atomic-ui/_atom/Buttons/button";
import {
errorOutline,
warningOutline
} from "@tvg/atomic-ui/_static/Icons/icons";
import { infoOutline } from "@tvg/atomic-ui/_static/Icons/iconsDuotone";
import {
closeBetCancelModal,
loadingBetCancelModalOn,
betCancelRequestError,
cleanBetCancelResult,
openWagerCancellationRulesModal
} from "@tvg/sh-lib-my-bets/redux/actions";
import CancelLimitsQuery from "@tvg/sh-lib-my-bets/graphql/queries/CancelLimits";
import BehgOptionsCancel from "@tvg/sh-lib-my-bets/graphql/behgOptionsCancel.graph";
import { graphql } from "@apollo/client/react/hoc";
import { getAccountNumber } from "@urp/store-selectors";
import {
getBetCancelWager,
getBetCancelRaceNumber,
getBetCancelIsLoadingRequest,
getBetCancelRequestError,
getMyBetBettingInterests,
getFeatureUseTvgPotReturn,
getFeatureIsMTPNewRules,
getBetCancelRaces,
getTotalActiveBets,
getTotalSettledBets,
getBetCancelBet
} from "@tvg/sh-lib-my-bets/redux/selectors";
import { updateBalance } from "@tvg/shared-actions/UserActions";
import mediator from "@tvg/mediator";
import tvgConf from "@tvg/conf";
import sendAppMetrics, { getApp } from "@tvg/metrics-collector";
import MyBetsBodyStandalone from "@tvg/my-bets-standalone/src/MyBetsBody";
import { fontMedium } from "@tvg/atomic-ui/_static/Typography";
import PromosOnboarding from "@tvg/promos-onboarding";
import { getStoryblokPromoByStep } from "@tvg/sh-lib-promos-onboarding/redux/selectors";
import { matchPlacedWager } from "@tvg/sh-lib-promos-onboarding/utils/matchPlacedWager";
import {
cancelBetSubmitGtmEvent,
cancelBetErrorGtmEvent,
cancelBetSuccessGtmEvent,
keepBetGtmEvent
} from "@tvg/pp/src/utils/gtm/betCancel";
import MyBetsBody from "@urp/my-bets/MyBetsBody";
import { isFdr } from "@tvg/pp/src/utils/general";
import cancelBet from "./utils/service";
import {
BetItemWrapperBetCancel,
ButtonsContainer,
BetCancelLoadingMask
} from "./styled-components";
export const handleCancelBet = ({
wager,
raceNumber,
accountNumber,
dispatch
}) => {
cancelBetSubmitGtmEvent({
raceNumber,
trackName: wager.trackName,
betAmount: wager.betTotal,
betType: get(wager, "wagerType.code", "")
});
dispatch(loadingBetCancelModalOn());
return cancelBet({ wager, accountNumber })
.then(({ data = {} }) => {
sendAppMetrics(getApp(), accountNumber, ["cancel_bets_number"]);
dispatch(
closeBetCancelModal({
result: { status: "success" }
})
);
// wait until toast animation finishes
setTimeout(() => {
dispatch(cleanBetCancelResult());
}, 3500);
const newBalance = get(data, "userBalance", undefined);
if (newBalance) {
dispatch(updateBalance(newBalance));
if (tvgConf().device === "desktop") {
mediator.base.dispatch({
type: "ACCOUNT_BALANCE_CHANGED",
payload: { balance: newBalance }
});
}
}
cancelBetSuccessGtmEvent({
raceNumber,
trackName: wager.trackName,
betAmount: wager.betTotal,
betType: get(wager, "wagerType.code", "")
});
})
.catch((err) => {
const errorCode = get(err, "response.data.code", "default");
cancelBetErrorGtmEvent({
gaEventLabel: get(err, "message", ""),
raceNumber,
trackName: wager.trackName,
betAmount: wager.betTotal,
betType: get(wager, "wagerType.code", ""),
errorType: get(err, "message", "")
});
dispatch(betCancelRequestError({ payload: err }));
throw errorCode;
});
};
export const handleKeepBet = ({ dispatch }) => {
dispatch(closeBetCancelModal({ result: { status: "aborted" } }));
dispatch(cleanBetCancelResult());
keepBetGtmEvent();
};
const infoIconProperties = () => {
const iconElement = infoOutline;
const color = buildColor("blue_accent", "600");
const colorList = [
buildColor("blue_accent", "200"),
buildColor("blue_accent", "600")
];
const colorBackground = buildColor("blue_accent", "000");
const colorBorder = buildColor("blue_accent", "200");
return { color, colorBackground, iconElement, colorBorder, colorList };
};
const errorIconProperties = () => {
const iconElement = errorOutline;
const color = buildColor("red", "500");
const colorBackground = buildColor("red", "000");
const colorBorder = buildColor("red", "100");
return { color, colorBackground, iconElement, colorBorder };
};
// Disabling ESLint for next line: 'warningIconProperties' is assigned a value but never used
// eslint-disable-next-line
const warningIconProperties = () => {
const iconElement = warningOutline;
const color = buildColor("orange", "500");
const colorBackground = buildColor("orange", "000");
const colorBorder = buildColor("orange", "100");
return { color, colorBackground, iconElement, colorBorder };
};
export const getNotificationArguments = ({ limits, serviceError }) => {
let notificationArguments = {
title: "Please confirm that you want to cancel this bet.",
text: `You can only cancel ${limits.remainingDayCancelledCount} bets per day`,
...infoIconProperties(),
showCancelRules: true
};
if (!serviceError) {
if (
limits.remainingDayCancelledCount === 0 ||
limits.remainingDayCancelledAmount === 0
) {
notificationArguments = {
title: "Unable to cancel bet",
text: "You have reached your cancelation limit",
...errorIconProperties()
};
} else if (limits.currentDayCancelledCount > 0) {
notificationArguments = {
title: `You can cancel ${limits.remainingDayCancelledCount} more bets today`,
text: `You can currently cancel bets up to ${formatCurrency(
limits.remainingDayCancelledAmount
)}`,
...infoIconProperties(),
showCancelRules: true
};
}
} else {
notificationArguments = {
title: "Something went wrong...",
text: "Close and try again later",
...errorIconProperties()
};
}
return notificationArguments;
};
export const formatWager = (wager) => [{ wagers: [wager] }];
export const BetCancel = (props) => {
const {
bet,
wager,
raceNumber,
accountNumber,
isLoadingLimitsRequest, // from bet cancel request
isLoadingBetCancelRequest, // from graph limits request
dispatch,
limits,
queryError,
betCancelRequestErrorMessage,
selectedTab,
selectedSettledTab,
races,
totalActiveBets,
totalSettledBets,
activeBets,
settledBets,
isDesktop,
promosOnboardingStep,
myBetsStandaloneToggle
} = props;
const isLoading = isLoadingLimitsRequest || isLoadingBetCancelRequest;
const notificationArguments = getNotificationArguments({
limits,
serviceError: queryError || betCancelRequestErrorMessage
});
const hasError =
betCancelRequestErrorMessage ||
queryError ||
limits.remainingDayCancelledAmount <= 0 ||
limits.remainingDayCancelledCount <= 0;
useEffect(() => {
if (!isLoading) {
mediator.base.dispatch({
type: "MYBETS_USER_SAW_WARNING_MESSAGE",
payload: {
selectedTab,
selectedSettledTab,
message: notificationArguments.title,
activeBets: isDesktop ? activeBets : totalActiveBets,
settledBets: isDesktop ? settledBets : totalSettledBets
}
});
}
}, [isLoading]);
const onShowCancelRules = () => {
mediator.base.dispatch({
type: "MYBETS_USER_CLICKS_SEE_RULES_ON_CANCELLED_BET",
payload: {
selectedTab,
selectedSettledTab,
activeBets: isDesktop ? activeBets : totalActiveBets,
settledBets: isDesktop ? settledBets : totalSettledBets
}
});
dispatch(closeBetCancelModal());
setTimeout(() => {
dispatch(openWagerCancellationRulesModal({ hasBack: true }));
}, 200);
};
const promoOnboardingComponent = useMemo(() => {
const renderPlace = "cancel_bet";
const isValidWager = matchPlacedWager(promosOnboardingStep, wager);
if (!isValidWager) {
return null;
}
return (
<PromosOnboarding placeToRender={renderPlace} isShown={isValidWager} />
);
}, [wager, raceNumber, accountNumber, promosOnboardingStep]);
return (
<React.Fragment>
<BetItemWrapperBetCancel data-qa-label="bet-cancel-item-wrapper">
{promoOnboardingComponent ||
(!isLoading && (
<BetCancelNotification
{...notificationArguments}
showCancelRulesFn={onShowCancelRules}
/>
))}
{myBetsStandaloneToggle || isFdr() ? (
<MyBetsBody
bet={bet}
races={races}
hasWagerFooter={false}
currentRaceDate={get(wager, "raceDate", "")}
isCancelModal
selectedWager={wager}
hasPastPerformance={false}
showLiveVideo={false}
showRaceLeg={false}
hasWagerDetails={false}
/>
) : (
<MyBetsBodyStandalone
bet={bet}
races={races}
hasWagerFooter={false}
currentRaceDate={get(wager, "raceDate", "")}
isCancelModal
selectedWager={wager}
hasPastPerformance={false}
showLiveVideo={false}
showRaceLeg={false}
hasWagerDetails={false}
/>
)}
</BetItemWrapperBetCancel>
<ButtonsContainer>
{hasError ? null : (
<Button
qaLabel="betCancelButtonConfirm"
type="delete"
size="bigger"
fontFamily={fontMedium}
onClick={
isLoading
? noop
: () =>
handleCancelBet({
wager,
raceNumber,
accountNumber,
dispatch
})
}
isStretched
isUppercase={false}
isBold={false}
className="betCancelButtonConfirm"
>
{isLoading ? (
<SpinningWheel qaLabel="betCancelLoading" />
) : (
"Cancel Bet"
)}
</Button>
)}
<Button
qaLabel="betCancelButtonKeep"
type="secondary"
size="bigger"
onClick={() => handleKeepBet({ dispatch })}
isStretched
isUppercase={false}
isBold={false}
fontFamily={fontMedium}
className="betCancelButtonKeep"
>
{hasError ? "Close" : "Keep Bet"}
</Button>
</ButtonsContainer>
{isLoading && (
<BetCancelLoadingMask data-qa-label="betCancelLoadingOverlay" />
)}
</React.Fragment>
);
};
BetCancel.defaultProps = {
wager: {},
raceNumber: 1,
accountNumber: "",
isLoadingLimitsRequest: false,
isLoadingBetCancelRequest: false,
useTvgPotReturnToggle: false,
dispatch: noop,
limits: {},
queryError: null,
betCancelRequestErrorMessage: "",
selectedTab: "ACTIVE",
selectedSettledTab: "TODAY",
races: [],
totalActiveBets: 0,
totalSettledBets: 0,
promosOnboardingStep: null
};
export default connect(
(store) => ({
bet: getBetCancelBet(store),
races: getBetCancelRaces(store),
wager: getBetCancelWager(store),
raceNumber: getBetCancelRaceNumber(store),
accountNumber: getAccountNumber(store),
isLoadingBetCancelRequest: getBetCancelIsLoadingRequest(store),
betCancelRequestErrorMessage: getBetCancelRequestError(store),
bettingInterests: getMyBetBettingInterests(store),
useTvgPotReturnToggle: getFeatureUseTvgPotReturn(store),
selectedTab: get(store, "myBetsStandalone.selectedTab"),
selectedSettledTab: get(store, "myBetsStandalone.selectedSettledTab"),
isMTPNewRules: getFeatureIsMTPNewRules(store),
totalActiveBets: getTotalActiveBets(store),
totalSettledBets: getTotalSettledBets(store),
promosOnboardingStep: getStoryblokPromoByStep(store, "WAGER_STEP")
}),
(dispatch) => ({ dispatch })
)(graphql(CancelLimitsQuery, BehgOptionsCancel)(BetCancel));
webpack://frontend-mybets/./src/pages/components/Modals/BetCancel.tsx
import React from "react";
import type { Dispatch } from "redux";
import { ApolloClient, NormalizedCacheObject } from "@apollo/client";
import ModalV2 from "@tvg/atomic-ui/_templates/ModalV2";
import BetCancel from "@tvg/bet-cancel";
import tvgConf from "@tvg/conf";
import { closeBetCancelModal } from "@tvg/sh-lib-my-bets/redux/actions";
import { TransitionState } from "../../../types";
const isDesktop = tvgConf().device === "desktop";
const BetCancelModal = ({
isOpen,
isLoading,
behgClient,
dispatch,
activeBets,
settledBets
}: {
isOpen: boolean;
isLoading: boolean;
behgClient: ApolloClient<NormalizedCacheObject>;
dispatch: Dispatch;
activeBets: number;
settledBets: number;
}) => {
const onClose = () => {
dispatch(closeBetCancelModal({ result: { status: "aborted" } }));
};
const props = {
title: isLoading ? "Processing Cancellation..." : "Confirm Cancellation",
titleType: "ipp",
isOpen,
onClose,
qaLabel: "bet-cancel",
hasShadow: true,
hasOverlay: true,
isFullWidth: false,
isContentTransparent: false,
isFullHeight: false,
layerOffset: 1,
hasContentMaxHeight: false,
animation: "fade",
offsetTop: 40,
offsetBottom: 0,
offsetLeft: 40,
offsetRight: 40,
isTitleCenter: true
};
return (
<ModalV2 {...props}>
{(transitionState: TransitionState) => (
<BetCancel
transitionState={transitionState}
behgClient={behgClient}
activeBets={activeBets}
settledBets={settledBets}
isDesktop={isDesktop}
/>
)}
</ModalV2>
);
};
export default BetCancelModal;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/SvgImages/ApproximatePayout.jsx
import React from "react";
const ApproximatePayout = () => (
<svg width="270" height="119" viewBox="0 0 270 119" fill="none">
<path
opacity="0.4"
fillRule="evenodd"
clipRule="evenodd"
d="M204.766 93.1304L203.412 103.478H217.076L218.43 93.1304H204.766ZM203.256 91.4058L201.451 105.203H218.587L220.391 91.4058H203.256ZM65.2994 1.72464L63.9478 12.0725H77.6103L78.962 1.72464H65.2994ZM63.7894 0L61.985 13.7971H79.1204L80.9248 0H63.7894ZM71.3499 96.5797L70.8574 100.029H76.7253L77.2178 96.5797H71.3499ZM69.8553 94.8551L68.8722 101.754H78.2199L79.203 94.8551H69.8553ZM111.487 98.3043L107.187 117.275H151.948L156.249 98.3043H111.489H111.487ZM110.113 96.5797L105.03 119H153.323L158.406 96.5797H110.113ZM154.532 12.0725L150.233 31.0435H194.993L199.294 12.0725H154.534H154.532ZM153.158 10.3478L148.075 32.7681H196.368L201.451 10.3478H153.158Z"
fill="#38AB4F"
/>
<path
opacity="0.2"
fillRule="evenodd"
clipRule="evenodd"
d="M188.873 56.913L186.413 67.2609H214.029L216.489 56.913H188.873ZM187.513 55.1884L184.233 68.9855H215.389L218.669 55.1884H187.513Z"
fill="#FFB80C"
/>
<path
opacity="0.6"
d="M187.513 5.17391H218.669L215.389 18.971H184.233L187.513 5.17391Z"
fill="url(#paint0_linear)"
fillOpacity="0.4"
/>
<path
opacity="0.6"
fillRule="evenodd"
clipRule="evenodd"
d="M188.873 6.89855L186.413 17.2464H214.029L216.489 6.89855H188.873ZM187.513 5.17391L184.233 18.971H215.389L218.669 5.17391H187.513Z"
fill="#FFB80C"
/>
<path
opacity="0.2"
fillRule="evenodd"
clipRule="evenodd"
d="M147.741 72.4348L146.648 79.3333H158.74L159.833 72.4348H147.741ZM146.271 70.7101L144.632 81.058H160.21L161.85 70.7101H146.271Z"
fill="#38AB4F"
/>
<path
d="M12.4486 71.4121H31.3747L29.3826 84.5073H10.4582L12.4504 71.4121H12.4486Z"
fill="url(#paint1_linear)"
/>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M13.9294 73.1367L12.4624 82.7826H27.9036L29.3705 73.1367H13.9294ZM12.4486 71.4121L10.46 84.5073H29.3843L31.3764 71.4121H12.4504H12.4486Z"
fill="#FFB80C"
/>
<path
d="M2.48973 21.6545H26.1473L23.6559 37.366H0L2.48973 21.6545Z"
fill="url(#paint2_linear)"
/>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M3.96015 23.3792L2.01623 35.6414H22.1855L24.1294 23.3792H3.96015ZM2.48973 21.6545L0 37.366H23.6559L26.1456 21.6545H2.48973Z"
fill="#FFB80C"
/>
<path
d="M58.7652 34.748H70.594L69.3491 42.6055H57.5203L58.7652 34.748Z"
fill="url(#paint3_linear)"
/>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M60.2356 36.4726L59.5366 40.8808H67.8787L68.576 36.4726H60.2356ZM58.7652 34.748L57.5203 42.6055H69.3491L70.594 34.748H58.7652Z"
fill="#FFB80C"
/>
<path
d="M73.6366 27.5942H201.023L192.386 63.8116H65L73.6366 27.5942Z"
fill="#329A47"
/>
<path
opacity="0.5"
d="M151.519 75.3098C151.519 75.9197 151.761 76.5047 152.191 76.936C152.622 77.3673 153.206 77.6096 153.815 77.6096C154.424 77.6096 155.008 77.3673 155.438 76.936C155.869 76.5047 156.111 75.9197 156.111 75.3098C156.111 74.6998 155.869 74.1148 155.438 73.6835C155.008 73.2522 154.424 73.0099 153.815 73.0099C153.206 73.0099 152.622 73.2522 152.191 73.6835C151.761 74.1148 151.519 74.6998 151.519 75.3098Z"
fill="#F8EAC8"
/>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M218.268 29.3188C227.951 32.1576 222.183 41.0119 222.183 41.0119C222.183 41.0119 215.332 38.6957 218.268 29.3188ZM219.253 52.4756L219.255 52.4721C218.97 52.3479 212.202 49.3333 214.516 41.9328C214.516 41.9328 221.503 42.4157 220.162 49.7006C221.335 47.005 223.864 43.2056 228.976 42.3881C229.561 56.7733 219.253 52.4756 219.253 52.4756ZM211.382 51.4046C206.727 58.667 212.924 63.408 213.044 63.5012C213.194 63.6236 221.81 70.6394 225.68 56.8027C220.918 56.1508 217.414 58.5359 215.319 60.6365C218.283 53.7121 211.382 51.4046 211.382 51.4046ZM205.38 59.0792C205.38 59.0792 211.109 63.6236 205.652 69.1735C208.648 68.1387 213.292 67.3885 217.535 70.3049C207.061 81.3701 202.474 70.6325 202.474 70.6325L202.477 70.6291C201.532 68.6423 199.769 63.3063 205.38 59.0792ZM41.7245 29.3188C32.0411 32.1576 37.8074 41.0119 37.8074 41.0119C37.8074 41.0119 44.6602 38.6957 41.7245 29.3188ZM40.7379 52.4756V52.4721C41.022 52.3479 47.7904 49.3333 45.4763 41.9328C45.4763 41.9328 38.4875 42.4157 39.8288 49.7006C38.6562 47.005 36.1269 43.2056 31.0166 42.3881C30.4312 56.7733 40.7379 52.4773 40.7379 52.4773V52.4756ZM48.6083 51.4063C53.264 58.667 47.069 63.4098 46.9467 63.5012C46.7986 63.6236 38.1827 70.6394 34.3104 56.8027C39.0746 56.1508 42.5785 58.5359 44.6739 60.6365C41.7073 53.7121 48.6083 51.4046 48.6083 51.4046V51.4063ZM54.6105 59.0792C54.6105 59.0792 48.8837 63.6236 54.3401 69.1752C51.3442 68.1404 46.6988 67.3885 42.458 70.3049C52.9317 81.3701 57.5169 70.6325 57.5169 70.6325L57.5152 70.6291C58.4587 68.6423 60.2236 63.3063 54.6105 59.0792Z"
fill="#38AB4F"
/>
<path
d="M237.449 71.4121H256.375L254.383 84.5073H235.458L237.45 71.4121H237.449Z"
fill="url(#paint4_linear)"
/>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M238.929 73.1367L237.462 82.7826H252.904L254.371 73.1367H238.929ZM237.449 71.4121L235.46 84.5073H254.384L256.376 71.4121H237.45H237.449Z"
fill="#FFB80C"
/>
<path
d="M245.49 21.6545H269.147L266.656 37.366H243L245.49 21.6545Z"
fill="url(#paint5_linear)"
/>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M246.96 23.3792L245.016 35.6414H265.185L267.129 23.3792H246.96ZM245.49 21.6545L243 37.366H266.656L269.146 21.6545H245.49Z"
fill="#FFB80C"
/>
<path
d="M106.211 51.7637C106.211 51.0163 106.001 50.4238 105.582 49.9863C105.172 49.5397 104.47 49.1296 103.477 48.7559C102.483 48.3822 101.626 48.013 100.906 47.6484C100.186 47.2747 99.5664 46.8509 99.0469 46.377C98.5365 45.8939 98.1354 45.3288 97.8438 44.6816C97.5612 44.0345 97.4199 43.2643 97.4199 42.3711C97.4199 40.8307 97.9121 39.5684 98.8965 38.584C99.8809 37.5996 101.189 37.0254 102.82 36.8613V33.9355H105.008V36.9023C106.621 37.1302 107.883 37.8047 108.795 38.9258C109.706 40.0378 110.162 41.4824 110.162 43.2598H106.211C106.211 42.166 105.983 41.3503 105.527 40.8125C105.081 40.2656 104.479 39.9922 103.723 39.9922C102.975 39.9922 102.396 40.2064 101.986 40.6348C101.576 41.054 101.371 41.6374 101.371 42.3848C101.371 43.0775 101.572 43.6335 101.973 44.0527C102.374 44.472 103.117 44.9004 104.201 45.3379C105.295 45.7754 106.193 46.1901 106.895 46.582C107.596 46.9648 108.189 47.4023 108.672 47.8945C109.155 48.3776 109.524 48.9336 109.779 49.5625C110.035 50.1823 110.162 50.9069 110.162 51.7363C110.162 53.2858 109.679 54.5436 108.713 55.5098C107.747 56.4759 106.416 57.0456 104.721 57.2188V59.9395H102.547V57.2324C100.678 57.0319 99.2292 56.3711 98.1992 55.25C97.1784 54.1198 96.668 52.6204 96.668 50.752H100.619C100.619 51.8366 100.874 52.6706 101.385 53.2539C101.904 53.8281 102.647 54.1152 103.613 54.1152C104.415 54.1152 105.049 53.9056 105.514 53.4863C105.979 53.0579 106.211 52.4837 106.211 51.7637ZM137.262 51.7637C137.262 51.0163 137.052 50.4238 136.633 49.9863C136.223 49.5397 135.521 49.1296 134.527 48.7559C133.534 48.3822 132.677 48.013 131.957 47.6484C131.237 47.2747 130.617 46.8509 130.098 46.377C129.587 45.8939 129.186 45.3288 128.895 44.6816C128.612 44.0345 128.471 43.2643 128.471 42.3711C128.471 40.8307 128.963 39.5684 129.947 38.584C130.932 37.5996 132.24 37.0254 133.871 36.8613V33.9355H136.059V36.9023C137.672 37.1302 138.934 37.8047 139.846 38.9258C140.757 40.0378 141.213 41.4824 141.213 43.2598H137.262C137.262 42.166 137.034 41.3503 136.578 40.8125C136.132 40.2656 135.53 39.9922 134.773 39.9922C134.026 39.9922 133.447 40.2064 133.037 40.6348C132.627 41.054 132.422 41.6374 132.422 42.3848C132.422 43.0775 132.622 43.6335 133.023 44.0527C133.424 44.472 134.167 44.9004 135.252 45.3379C136.346 45.7754 137.243 46.1901 137.945 46.582C138.647 46.9648 139.24 47.4023 139.723 47.8945C140.206 48.3776 140.575 48.9336 140.83 49.5625C141.085 50.1823 141.213 50.9069 141.213 51.7363C141.213 53.2858 140.73 54.5436 139.764 55.5098C138.798 56.4759 137.467 57.0456 135.771 57.2188V59.9395H133.598V57.2324C131.729 57.0319 130.28 56.3711 129.25 55.25C128.229 54.1198 127.719 52.6204 127.719 50.752H131.67C131.67 51.8366 131.925 52.6706 132.436 53.2539C132.955 53.8281 133.698 54.1152 134.664 54.1152C135.466 54.1152 136.1 53.9056 136.564 53.4863C137.029 53.0579 137.262 52.4837 137.262 51.7637ZM168.312 51.7637C168.312 51.0163 168.103 50.4238 167.684 49.9863C167.273 49.5397 166.572 49.1296 165.578 48.7559C164.585 48.3822 163.728 48.013 163.008 47.6484C162.288 47.2747 161.668 46.8509 161.148 46.377C160.638 45.8939 160.237 45.3288 159.945 44.6816C159.663 44.0345 159.521 43.2643 159.521 42.3711C159.521 40.8307 160.014 39.5684 160.998 38.584C161.982 37.5996 163.29 37.0254 164.922 36.8613V33.9355H167.109V36.9023C168.723 37.1302 169.985 37.8047 170.896 38.9258C171.808 40.0378 172.264 41.4824 172.264 43.2598H168.312C168.312 42.166 168.085 41.3503 167.629 40.8125C167.182 40.2656 166.581 39.9922 165.824 39.9922C165.077 39.9922 164.498 40.2064 164.088 40.6348C163.678 41.054 163.473 41.6374 163.473 42.3848C163.473 43.0775 163.673 43.6335 164.074 44.0527C164.475 44.472 165.218 44.9004 166.303 45.3379C167.396 45.7754 168.294 46.1901 168.996 46.582C169.698 46.9648 170.29 47.4023 170.773 47.8945C171.257 48.3776 171.626 48.9336 171.881 49.5625C172.136 50.1823 172.264 50.9069 172.264 51.7363C172.264 53.2858 171.781 54.5436 170.814 55.5098C169.848 56.4759 168.518 57.0456 166.822 57.2188V59.9395H164.648V57.2324C162.78 57.0319 161.331 56.3711 160.301 55.25C159.28 54.1198 158.77 52.6204 158.77 50.752H162.721C162.721 51.8366 162.976 52.6706 163.486 53.2539C164.006 53.8281 164.749 54.1152 165.715 54.1152C166.517 54.1152 167.15 53.9056 167.615 53.4863C168.08 53.0579 168.312 52.4837 168.312 51.7637Z"
fill="white"
/>
<path
d="M75.4375 83.6562H71.3281L70.5469 86H68.0547L72.2891 74.625H74.4609L78.7188 86H76.2266L75.4375 83.6562ZM71.9609 81.7578H74.8047L73.375 77.5L71.9609 81.7578ZM82.125 81.9922V86H79.7812V74.625H84.2188C85.0729 74.625 85.8229 74.7812 86.4688 75.0938C87.1198 75.4062 87.6198 75.8516 87.9688 76.4297C88.3177 77.0026 88.4922 77.6562 88.4922 78.3906C88.4922 79.5052 88.1094 80.3854 87.3438 81.0312C86.5833 81.6719 85.5286 81.9922 84.1797 81.9922H82.125ZM82.125 80.0938H84.2188C84.8385 80.0938 85.3099 79.9479 85.6328 79.6562C85.9609 79.3646 86.125 78.9479 86.125 78.4062C86.125 77.849 85.9609 77.3984 85.6328 77.0547C85.3047 76.7109 84.8516 76.5339 84.2734 76.5234H82.125V80.0938ZM92.4531 81.9922V86H90.1094V74.625H94.5469C95.401 74.625 96.151 74.7812 96.7969 75.0938C97.4479 75.4062 97.9479 75.8516 98.2969 76.4297C98.6458 77.0026 98.8203 77.6562 98.8203 78.3906C98.8203 79.5052 98.4375 80.3854 97.6719 81.0312C96.9115 81.6719 95.8568 81.9922 94.5078 81.9922H92.4531ZM92.4531 80.0938H94.5469C95.1667 80.0938 95.638 79.9479 95.9609 79.6562C96.2891 79.3646 96.4531 78.9479 96.4531 78.4062C96.4531 77.849 96.2891 77.3984 95.9609 77.0547C95.6328 76.7109 95.1797 76.5339 94.6016 76.5234H92.4531V80.0938ZM104.648 81.8359H102.781V86H100.438V74.625H104.664C106.008 74.625 107.044 74.9245 107.773 75.5234C108.503 76.1224 108.867 76.9688 108.867 78.0625C108.867 78.8385 108.698 79.487 108.359 80.0078C108.026 80.5234 107.518 80.9349 106.836 81.2422L109.297 85.8906V86H106.781L104.648 81.8359ZM102.781 79.9375H104.672C105.26 79.9375 105.716 79.7891 106.039 79.4922C106.362 79.1901 106.523 78.776 106.523 78.25C106.523 77.7135 106.37 77.2917 106.062 76.9844C105.76 76.6771 105.294 76.5234 104.664 76.5234H102.781V79.9375ZM120 80.5703C120 81.6901 119.802 82.6719 119.406 83.5156C119.01 84.3594 118.443 85.0104 117.703 85.4688C116.969 85.9271 116.125 86.1562 115.172 86.1562C114.229 86.1562 113.388 85.9297 112.648 85.4766C111.909 85.0234 111.336 84.3776 110.93 83.5391C110.523 82.6953 110.318 81.7266 110.312 80.6328V80.0703C110.312 78.9505 110.513 77.9661 110.914 77.1172C111.32 76.263 111.891 75.6094 112.625 75.1562C113.365 74.6979 114.208 74.4688 115.156 74.4688C116.104 74.4688 116.945 74.6979 117.68 75.1562C118.419 75.6094 118.99 76.263 119.391 77.1172C119.797 77.9661 120 78.9479 120 80.0625V80.5703ZM117.625 80.0547C117.625 78.862 117.411 77.9557 116.984 77.3359C116.557 76.7161 115.948 76.4062 115.156 76.4062C114.37 76.4062 113.763 76.7135 113.336 77.3281C112.909 77.9375 112.693 78.8333 112.688 80.0156V80.5703C112.688 81.7318 112.901 82.6328 113.328 83.2734C113.755 83.9141 114.37 84.2344 115.172 84.2344C115.958 84.2344 116.562 83.9271 116.984 83.3125C117.406 82.6927 117.62 81.7917 117.625 80.6094V80.0547ZM125.602 78.5469L127.734 74.625H130.43L127.117 80.2656L130.516 86H127.789L125.602 82.0156L123.414 86H120.688L124.086 80.2656L120.773 74.625H123.469L125.602 78.5469ZM131.672 84.8906C131.672 84.5312 131.792 84.2396 132.031 84.0156C132.276 83.7917 132.581 83.6797 132.945 83.6797C133.315 83.6797 133.62 83.7917 133.859 84.0156C134.104 84.2396 134.227 84.5312 134.227 84.8906C134.227 85.2448 134.107 85.5339 133.867 85.7578C133.628 85.9766 133.32 86.0859 132.945 86.0859C132.576 86.0859 132.271 85.9766 132.031 85.7578C131.792 85.5339 131.672 85.2448 131.672 84.8906ZM142.688 81.9922V86H140.344V74.625H144.781C145.635 74.625 146.385 74.7812 147.031 75.0938C147.682 75.4062 148.182 75.8516 148.531 76.4297C148.88 77.0026 149.055 77.6562 149.055 78.3906C149.055 79.5052 148.672 80.3854 147.906 81.0312C147.146 81.6719 146.091 81.9922 144.742 81.9922H142.688ZM142.688 80.0938H144.781C145.401 80.0938 145.872 79.9479 146.195 79.6562C146.523 79.3646 146.688 78.9479 146.688 78.4062C146.688 77.849 146.523 77.3984 146.195 77.0547C145.867 76.7109 145.414 76.5339 144.836 76.5234H142.688V80.0938ZM155.703 83.6562H151.594L150.812 86H148.32L152.555 74.625H154.727L158.984 86H156.492L155.703 83.6562ZM152.227 81.7578H155.07L153.641 77.5L152.227 81.7578ZM162.797 79.75L165.164 74.625H167.727L163.992 81.875V86H161.609V81.875L157.875 74.625H160.445L162.797 79.75ZM177.875 80.5703C177.875 81.6901 177.677 82.6719 177.281 83.5156C176.885 84.3594 176.318 85.0104 175.578 85.4688C174.844 85.9271 174 86.1562 173.047 86.1562C172.104 86.1562 171.263 85.9297 170.523 85.4766C169.784 85.0234 169.211 84.3776 168.805 83.5391C168.398 82.6953 168.193 81.7266 168.188 80.6328V80.0703C168.188 78.9505 168.388 77.9661 168.789 77.1172C169.195 76.263 169.766 75.6094 170.5 75.1562C171.24 74.6979 172.083 74.4688 173.031 74.4688C173.979 74.4688 174.82 74.6979 175.555 75.1562C176.294 75.6094 176.865 76.263 177.266 77.1172C177.672 77.9661 177.875 78.9479 177.875 80.0625V80.5703ZM175.5 80.0547C175.5 78.862 175.286 77.9557 174.859 77.3359C174.432 76.7161 173.823 76.4062 173.031 76.4062C172.245 76.4062 171.638 76.7135 171.211 77.3281C170.784 77.9375 170.568 78.8333 170.562 80.0156V80.5703C170.562 81.7318 170.776 82.6328 171.203 83.2734C171.63 83.9141 172.245 84.2344 173.047 84.2344C173.833 84.2344 174.438 83.9271 174.859 83.3125C175.281 82.6927 175.495 81.7917 175.5 80.6094V80.0547ZM188.188 74.625V82.1172C188.188 83.362 187.797 84.3464 187.016 85.0703C186.24 85.7943 185.177 86.1562 183.828 86.1562C182.5 86.1562 181.445 85.8047 180.664 85.1016C179.883 84.3984 179.484 83.4323 179.469 82.2031V74.625H181.812V82.1328C181.812 82.8776 181.99 83.4219 182.344 83.7656C182.703 84.1042 183.198 84.2734 183.828 84.2734C185.146 84.2734 185.815 83.5807 185.836 82.1953V74.625H188.188ZM198.672 76.5234H195.188V86H192.844V76.5234H189.406V74.625H198.672V76.5234Z"
fill="#329A47"
/>
<defs>
<linearGradient
id="paint0_linear"
x1="186.816"
y1="12.0725"
x2="201.451"
y2="12.0725"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#FFB80C" />
<stop offset="1" stopColor="#FFB80C" stopOpacity="0" />
</linearGradient>
<linearGradient
id="paint1_linear"
x1="10.4582"
y1="79.2695"
x2="20.9165"
y2="79.2695"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#FFB80C" />
<stop offset="1" stopColor="#FFB80C" stopOpacity="0" />
</linearGradient>
<linearGradient
id="paint2_linear"
x1="2.61542"
y1="29.5103"
x2="13.0737"
y2="29.5103"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#FFB80C" />
<stop offset="1" stopColor="#FFB80C" stopOpacity="0" />
</linearGradient>
<linearGradient
id="paint3_linear"
x1="64.0563"
y1="34.748"
x2="64.0563"
y2="42.6055"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#FFB80C" />
<stop offset="1" stopColor="#FFB80C" stopOpacity="0" />
</linearGradient>
<linearGradient
id="paint4_linear"
x1="235.458"
y1="79.2695"
x2="245.916"
y2="79.2695"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#FFB80C" />
<stop offset="1" stopColor="#FFB80C" stopOpacity="0" />
</linearGradient>
<linearGradient
id="paint5_linear"
x1="245.615"
y1="29.5103"
x2="256.074"
y2="29.5103"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#FFB80C" />
<stop offset="1" stopColor="#FFB80C" stopOpacity="0" />
</linearGradient>
</defs>
</svg>
);
export default ApproximatePayout;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_templates/ApproxPayoutHelp/styled-components.js
import styled from "styled-components";
import buildColor from "../../_static/ColorPalette";
import { fontNormal } from "../../_static/Typography";
export const IllustrationContainer = styled.div`
background-color: ${buildColor("blue_accent", "000")};
padding: 16px;
display: flex;
align-items: center;
justify-content: center;
`;
export const DescriptionContainer = styled.div`
font-family: ${fontNormal};
font-size: 14px;
line-height: 18px;
padding: 16px 12px;
color: ${buildColor("grey", "800")};
background-color: ${buildColor("white", "100")};
p:not(:last-child) {
margin-bottom: 18px;
}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_templates/ApproxPayoutHelp/index.jsx
import React, { Fragment } from "react";
import ApproximatePayout from "../../_static/SvgImages/ApproximatePayout";
import ApproxPayoutNotification from "../../_molecule/BetNotification";
import { info } from "../../_static/Icons/iconsDuotone";
import {
IllustrationContainer,
DescriptionContainer
} from "./styled-components";
import buildColor from "../../_static/ColorPalette";
const ApproxPayoutHelp = (props) => {
const { description } = props;
return (
<Fragment>
<IllustrationContainer>
<ApproximatePayout />
</IllustrationContainer>
<ApproxPayoutNotification
qaLabels={{
main: "approxPayout-notification-container",
title: "approxPayout-notification-title",
text: "approxPayout-notification-text"
}}
viewBoxSize={16}
iconElement={info}
iconColor={buildColor("blue_accent", "200")}
strokeColor={buildColor("blue_accent", "600")}
color={buildColor("blue_accent", "600")}
colorBackground={buildColor("blue_accent", "000")}
colorBorder={buildColor("blue_accent", "200")}
title="Approximate Payout is only available for:"
text="Win, Place, Show, Exacta and Daily Double."
hasTopBorder
/>
<DescriptionContainer>
{description.map((paragraph, index) => (
<p key={index.toString()}>{paragraph}</p>
))}
</DescriptionContainer>
</Fragment>
);
};
ApproxPayoutHelp.defaultProps = {
description: ["", ""]
};
export default ApproxPayoutHelp;
webpack://frontend-mybets/../../packages/tvg-comp-approx-payout-help/index.jsx
import React from "react";
import { connect } from "react-redux";
import ApproxPayoutHelp from "@tvg/atomic-ui/_templates/ApproxPayoutHelp";
import parseJSONCapiMessage from "@tvg/utils/capiUtils";
export const ApproxPayoutHelpComp = ({ description }) => (
<ApproxPayoutHelp description={description} />
);
ApproxPayoutHelpComp.defaultProps = {
description: ["", "", ""]
};
export default connect((store) => ({
description: parseJSONCapiMessage(store, "capi.messages.approxPayoutHelp", [])
}))(ApproxPayoutHelpComp);
webpack://frontend-mybets/./src/pages/components/Modals/ApproxPayoutHelp.tsx
import React from "react";
import type { Dispatch } from "redux";
import ModalV2 from "@tvg/atomic-ui/_templates/ModalV2";
import ApproxPayoutHelp from "@tvg/approx-payout-help";
import { closeApproxPayoutModal } from "@tvg/sh-lib-my-bets/redux/actions";
import { TransitionState } from "../../../types";
const ApproxPayoutHelpModal = ({
isOpen,
dispatch
}: {
isOpen: boolean;
dispatch: Dispatch;
}) => {
const onClose = () => {
dispatch(closeApproxPayoutModal());
};
const props = {
title: "Approximate Payout",
titleType: "ipp",
isOpen,
onClose,
qaLabel: "approximate-payout-help-modal",
hasShadow: true,
hasOverlay: true,
isFullWidth: false,
isContentTransparent: false,
isFullHeight: false,
layerOffset: 2,
animation: "fade",
offsetTop: 40,
offsetBottom: 0,
offsetLeft: 40,
offsetRight: 40
};
return (
<ModalV2 {...props}>
{(transitionState: TransitionState) => (
<ApproxPayoutHelp transitionState={transitionState} />
)}
</ModalV2>
);
};
export default ApproxPayoutHelpModal;
webpack://frontend-mybets/../../packages/tvg-lib-api/wro/index.ts
import tvgConf from "@tvg/conf";
import getProtocol from "../protocolSetter";
import requester from "../requester";
import type { RequestOptions, WroResponse } from "./types";
const wroService: string = "service.wro";
const getWroServiceUrl = (accountNumber: string): string =>
`${getProtocol()}${tvgConf().config(
wroService
)}/users/${accountNumber}/wagers`;
const formatWroRequestOptions = (options: RequestOptions): RequestOptions => {
let wroPreferences: RequestOptions = {
startDate: options.startDate,
endDate: options.endDate,
page: options.page || 1,
recordsPerPage: options.recordsPerPage || 25,
sort: options.sort || "transactiondate",
ascendingOrder: options.ascendingOrder || false,
status: options.status || "all",
tvgRaceId: options.tvgRaceId
};
if (options.track) {
wroPreferences = { ...wroPreferences, track: options.track };
}
if (options.race) {
wroPreferences = { ...wroPreferences, race: options.race };
}
if (options.group) {
wroPreferences = { ...wroPreferences, group: options.group };
}
if (options.groupSort) {
wroPreferences = { ...wroPreferences, groupSort: options.groupSort };
}
if (options.groupSortAscendingOrder) {
wroPreferences = {
...wroPreferences,
groupSortAscendingOrder: options.groupSortAscendingOrder
};
}
return wroPreferences;
};
const getMyBets = (
options: RequestOptions,
accountNumber: string
): Promise<{
data: WroResponse;
config: Record<string, string>;
status: number;
}> =>
requester()({
url: getWroServiceUrl(accountNumber),
method: "get",
withCredentials: true,
params: formatWroRequestOptions(options),
headers: { "x-tvg-context": tvgConf().context() }
}) as unknown as Promise<{
data: WroResponse;
config: Record<string, string>;
status: number;
}>;
const WRO_SERVICE = {
getMyBets
};
export default WRO_SERVICE;
webpack://frontend-mybets/../../packages/tvg-lib-utils/pastPerformanceUtils.js
import tvgConf from "@tvg/conf";
import axios from "axios";
import { get, filter } from "lodash";
const config = tvgConf().config();
export const convertBettingInterests = (bettingInterests) => {
const scratchedRunners = [];
const bettingInterestsFormated = bettingInterests.map((betInterest) => ({
biNumber: betInterest.biNumber,
currentOdds: betInterest.currentOdds || {
numerator: 0,
denominator: 0
},
morningLineOdds: betInterest.morningLineOdds || {
numerator: 0,
denominator: 0
},
isFavorite: betInterest.favorite,
runners: betInterest.runners.map((runner) => {
if (runner.scratched) {
scratchedRunners.push(runner.runnerId);
}
return {
horseName: runner.horseName,
dob: get(runner, "dob"),
runnerId: runner.runnerId,
scratched: runner.scratched,
handicapping: [runner.jockey, runner.trainer],
masterPickNumber: -1
};
})
}));
return {
bettingInterests: bettingInterestsFormated,
scratchedRunners
};
};
export const findRunnerInRace = (runnerName, bettingInterests) => {
const bettingInterestsLength = bettingInterests.length;
if (bettingInterestsLength) {
for (let i = 0; i < bettingInterestsLength; i += 1) {
const bi = bettingInterests[i];
const foundRunner = bi.runners.find(
(r) =>
get(r, "horseName", "").toLowerCase() === runnerName.toLowerCase()
);
if (foundRunner) {
const raceCardRunner = {
horseName: get(foundRunner, "horseName"),
dob: get(foundRunner, "dob"),
runnerId: get(foundRunner, "runnerId"),
scratched: get(foundRunner, "scratched", false),
handicapping: [
get(foundRunner, "jockey"),
get(foundRunner, "trainer")
],
masterPickNumber: -1
};
return raceCardRunner;
}
}
}
return null;
};
export const getFilteredRaces = (races, conditionsToMatch) => {
const ids = [];
return {
races: filter(races, (race) => {
if (
race.distance === conditionsToMatch.distance &&
race.surface.shortName === conditionsToMatch.surface
) {
ids.push(race.id);
return true;
}
return false;
}),
ids
};
};
export const formatBets = (wagers) =>
wagers.map((wager) => {
const raceWagerType = {
isKey: false,
legCount: 1,
type: wager.wagerType
};
return {
id: wager.serialNumber,
raceTypeCode: wager.raceTypeAbbreviation,
betTotal: wager.betTotal,
wagerAmount: wager.wagerAmount,
wagerType: raceWagerType.type,
isKey: raceWagerType.isKey,
isLeg: raceWagerType.legCount > 1,
selections: wager.selections.selection.map((selection) =>
selection.runners.map((runner) => runner.number.toString())
),
isCancelled: wager.betStatus.code === "C",
isLost: wager.betStatus.code === "L",
isRefunded: wager.betStatus.code === "R",
totalWinAmount:
wager.betStatus.code === "W" ? wager.winningsAmount : undefined
};
});
export const formatWroBets = (response) =>
formatBets(get(response, "data.wagers", []));
/**
* Request for hash
* @param {string} streamName Stream Value (required to build the hash)
* @param {string} streamName Replay File Value (required to build the hash)
* @param {number} timestamp Timestamp (unix)
*/
const generateRCNHash = (replayFile, timestamp) =>
axios.get(`${config.service_host}/rcn/v1/generateHash`, {
params: {
streamname: replayFile,
timestamp
},
withCredentials: true
});
const checkResponseLink = (response) => {
if (
typeof get(response, "data") === "object" &&
typeof get(response, "data.link") === "string" &&
get(response, "data", "") !== "There was an error: invalidparam"
) {
return {
type: "success",
payload: response.data.link
};
}
return {
type: "error",
payload: response.data
};
};
const requestStreamHTML5 = (race, timestamp, hash, isFlash) => {
return axios.get(
`//replays.robertsstream.com/racereplays/replaysmobile.php`,
{
params: {
t: timestamp,
h: hash,
output: "json",
forceformat: "ios",
hd: "0",
race,
cust: "TVG"
}
}
);
};
export const getHTML5Stream = (stream, hash, timestamp, isFlash) =>
requestStreamHTML5(stream, timestamp, hash, isFlash)
.then(checkResponseLink)
.catch((err) => ({
type: "error",
payload: err.message
}));
const getStreamRequests = (replayFile, timestamp, replayHash, isFlash) =>
getHTML5Stream(replayFile, replayHash, timestamp, isFlash);
export const getStreamSrc = (replayFile = "", isFlash) => {
if (!replayFile || replayFile === "") {
return Promise.resolve({
type: "error",
payload: "no given replayFile"
});
}
const timestamp = Math.floor(Date.now() / 1000);
return generateRCNHash(replayFile, timestamp)
.then((response) =>
typeof response !== "undefined" && !!get(response, `data.hash`, "")
? get(response, `data.hash`, "")
: ""
)
.then((replayHash) =>
getStreamRequests(replayFile, timestamp, replayHash, isFlash)
);
};
webpack://frontend-mybets/../../packages/sh-lib-my-bets/utils/bettingInterests.ts
import { get } from "lodash";
import {
BettingInterest,
FullResultRunner,
Results,
RaceInfoMyBetsResults,
Runner,
Payoffs,
ResultRunner
} from "@tvg/ts-types/Race";
import { formatSecondsToDuration } from "@tvg/formatter/dates";
const payoffBets = ["WN", "PL", "SH"];
type ResultsTemplateProps = {
label: string;
show: boolean;
};
type ResultsTemplate = {
winningTime: ResultsTemplateProps;
};
export const RESULTS_TEMPLATE = {
emptyWinningTime: {
winningTime: {
label: "n/d",
show: true
}
}
};
export const mapRunnersToFullResults = (
bettingInterests: BettingInterest[],
runners: Runner[]
): FullResultRunner[] =>
(runners || []).map((runner) => {
const bi = bettingInterests[get(runner, "biNumber", 1) - 1];
const runnerBI = bettingInterests[
get(runner, "biNumber", 1) - 1
].runners.find((r) => +r.runnerId === runner.runnerNumber);
const runnerResult = {
runnerId: `${get(runner, "runnerNumber", "")}`,
runnerName: get(runner, "runnerName", ""),
jockey: get(runnerBI, "jockey", ""),
trainer: get(runnerBI, "trainer", ""),
scratched: get(runnerBI, "scratched", false),
finishPosition: get(runner, "finishPosition", 0)
};
return get(runner, "timeform")
? {
...runnerResult,
odds: get(bi, "currentOdds"),
accBeatenDistance: get(runner, "timeform.accBeatenDistance", ""),
accBeatenDistanceStatus: get(
runner,
"timeform.accBeatenDistanceStatus",
""
),
postRaceReport: get(runner, "timeform.postRaceReport", "")
}
: runnerResult;
});
export const checkTimeformData = (
results: Results | RaceInfoMyBetsResults
): boolean => !!get(results, "runners[0].timeform", false);
export const buildResults = (
results?: Results,
defaultValues: ResultsTemplate = {
winningTime: {
label: "",
show: false
}
}
) => {
const formattedResult: {
payoffs: Array<Payoffs>;
runners: Array<ResultRunner>;
winningTime: string | undefined;
} = {
payoffs: (get(results, "payoffs") || []).filter(
(payoff) => payoffBets.indexOf(payoff.wagerType.code) === -1
),
runners: get(results, "runners") || [],
winningTime: undefined
};
const { winningTime } = defaultValues;
const resultsWinningTime = +get(results, "winningTime", "0");
if (winningTime.show) {
formattedResult.winningTime =
resultsWinningTime > 0
? formatSecondsToDuration(resultsWinningTime)
: winningTime.label;
}
return formattedResult;
};
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/graphql/options.graph.ts
import { get, upperFirst, isNumber } from "lodash";
import type { WagerProfile } from "@tvg/ts-types/User";
import { mapRunnersToFullResults } from "@tvg/sh-lib-my-bets/utils/bettingInterests";
import { getPortByBrand } from "@tvg/utils/generalUtils";
import { ApolloClient, WatchQueryFetchPolicy } from "@apollo/client";
import { PastRace } from "@tvg/ts-types/Race";
import { type Props } from "../types";
type GraphFcpProps = {
runnerName?: string;
runnerDob?: number;
entityRunnerId?: string;
trackCode?: string;
raceNumber?: string | number;
raceDate?: string;
wagerProfile: WagerProfile;
fcpClient: ApolloClient<unknown>;
racesCounter?: number;
};
type GraphBehgProps = {
trackCode?: string;
raceNumber?: string | number;
raceDate?: string;
behgClient: ApolloClient<unknown>;
accountNumber?: number | string;
behgToggle: boolean;
myBetsResultedBetTicket: boolean;
isAccountCompliant?: boolean;
};
const QUERY_VARIABLES_IPP = {
runnerName: "",
sortBy: { byPostTime: "DESC" }
};
const QUERY_VARIABLES_RUNNER_STATS = {
runnerName: "",
runnerDob: 0
};
const QUERY_VARIABLES_PP = {
trackCode: "",
raceNumber: "",
date: ""
};
export const getFinishPosition = (
finishPosition: number | undefined | null,
scratched: false
) => {
if (scratched) {
return 0;
}
return finishPosition;
};
const handleRunnerStats = (result: {}) => {
const runnerStats = get(result, "data.runnerStats", {});
const startsValue = get(runnerStats, "numberRaces", 0);
const winsValue = get(runnerStats, "numberRacesWon", 0);
const top3Value = get(runnerStats, "numberRacesTop3", 0);
const wins =
startsValue > 0 ? Math.floor((winsValue * 100) / startsValue) : undefined;
const top3 =
startsValue > 0 ? Math.floor((top3Value * 100) / startsValue) : undefined;
return {
runnerStats: {
starts: startsValue,
wins,
top3
},
refetchStats: get(result, "data.refetch"),
isLoadingStats: get(result, "data.loading", false)
};
};
const handleResultsIPP = (result: {}) => {
const raceIds: unknown[] = [];
return {
races: get(result, "data.pastRaces", []).map((race: PastRace) => {
const runner = get(race, "results.runners[0]");
const tempRace = {
...race,
id: race.raceId,
runnerNumber: get(runner, "runnerNumber", ""),
hasReplays: !!get(race, "video.replayFileName", ""),
replayFileName: get(race, "video.replayFileName", ""),
raceTypeCode: get(race, "type.code"),
distance: `${get(race, "distance.value", "")}${get(
race,
"distance.code",
""
)}`.toLowerCase(),
finishPosition: getFinishPosition(
get(runner, "finishPosition"),
get(runner, "scratched", false)
),
finishStatus: get(runner, "finishStatus", ""),
favorite: get(runner, "favorite"),
scratched: get(runner, "scratched", false),
odds: get(runner, "currentOdds"),
postRaceReport: upperFirst(get(runner, "timeform.postRaceReport", "")),
accBeatenDistance: upperFirst(
get(runner, "timeform.accBeatenDistance", "")
),
accBeatenDistanceStatus: upperFirst(
get(runner, "timeform.accBeatenDistanceStatus", "")
),
accBeatenDistanceStatusAbrev: upperFirst(
get(runner, "timeform.accBeatenDistanceStatusAbrev", "")
),
winningDistance: upperFirst(
get(runner, "timeform.winningDistance", "")
),
winningDistanceStatus: upperFirst(
get(runner, "timeform.winningDistanceStatus", "")
)
};
raceIds.push(race.raceId);
delete tempRace.raceId;
delete tempRace.results;
// @ts-ignore
delete tempRace.type;
// @ts-ignore
delete tempRace.video;
return tempRace;
}),
raceIds,
isLoading: get(result, "data.loading", false),
runnerName: get(result, "data.variables.runnerName"),
runnerDob: get(result, "data.variables.runnerDob"),
refetch: get(result, "data.refetch")
};
};
// Used on MyBets, and converted to use useQuery
export const apolloOptionRacePP = ({
wagerProfile,
trackCode,
raceNumber,
raceDate,
fcpClient,
racesCounter
}: GraphFcpProps) => {
const variables = {
...QUERY_VARIABLES_PP,
wagerProfile,
trackCode,
raceNumber: `${raceNumber || ""}`,
date: raceDate
};
return {
client: fcpClient,
fetchPolicy: "cache-and-network" as WatchQueryFetchPolicy,
pollInterval: 0,
ssr: false,
variables,
skip: !trackCode || !raceNumber || !raceDate || !!racesCounter
};
};
export const ApolloOptionsRacePP = {
skip: (props: Props) =>
!props.trackCode ||
!props.raceNumber ||
!props.raceDate ||
get(props, "races.length", 0) !== 0,
options: (props: GraphFcpProps) => {
const variables = {
...QUERY_VARIABLES_PP,
wagerProfile: props.wagerProfile,
trackCode: props.trackCode,
raceNumber: `${props.raceNumber || ""}`,
date: props.raceDate
};
return {
client: props.fcpClient,
fetchPolicy: "cache-and-network",
pollInterval: 0,
ssr: false,
variables
};
},
props: (data: {}) => {
let resultsIpp = handleResultsIPP(data);
if (resultsIpp) {
resultsIpp = {
...resultsIpp,
// @ts-ignore
race: get(resultsIpp, "races[0]"),
races: undefined
};
}
return resultsIpp;
}
};
// Used on MyBets, and converted to use useQuery
export const apolloOptionsGroupWagerPP = ({
trackCode,
raceNumber,
raceDate,
accountNumber,
behgClient,
behgToggle,
myBetsResultedBetTicket
}: GraphBehgProps) => {
const trackCodeFormatted =
typeof trackCode === "string" ? trackCode.trim() : trackCode;
const variables = {
trackCode: trackCodeFormatted,
raceNumber: raceNumber && isNumber(+raceNumber) ? +raceNumber : undefined,
startDate: raceDate,
endDate: raceDate,
accountId: parseInt(`${accountNumber}`, 10)
};
return {
client: behgClient,
fetchPolicy: "cache-and-network" as WatchQueryFetchPolicy,
pollInterval: 0,
ssr: false,
variables,
skip:
!accountNumber || !trackCode || !behgToggle || !myBetsResultedBetTicket
};
};
export const ApolloOptionsWagerPP = {
skip: (props: GraphBehgProps) =>
!props.accountNumber ||
!props.trackCode ||
!props.behgToggle ||
!props.myBetsResultedBetTicket ||
!props.isAccountCompliant,
options: (props: GraphBehgProps) => {
const trackCode =
typeof props.trackCode === "string"
? props.trackCode.trim()
: props.trackCode;
const variables = {
trackCode,
raceNumber:
props.raceNumber && isNumber(+props.raceNumber)
? +props.raceNumber
: undefined,
startDate: props.raceDate,
endDate: props.raceDate,
accountId: parseInt(`${props.accountNumber}`, 10)
};
return {
client: props.behgClient,
fetchPolicy: "cache-and-network",
pollInterval: 0,
ssr: false,
variables
};
},
props: (result: {}) => ({
isPPLoading: get(result, "data.loading", false),
queryGroupWagers: get(result, "data.wagerHistory.groupWagers", []).map(
(groupWager: { value: string; wagers: string[] }) => ({
value: groupWager.value.replace(/#/gi, "|"),
wagers: (groupWager.wagers || []).filter(
(wager: unknown) =>
get(wager, "betStatus.code") !== "C" &&
get(wager, "raceDate") === get(result, "ownProps.raceDate")
)
})
)
})
};
export const ApolloOptionsIPP = {
options: (props: GraphFcpProps) => {
const variables = {
...QUERY_VARIABLES_IPP,
wagerProfile: props.wagerProfile || getPortByBrand(),
runnerName: props.runnerName,
runnerDob: props.runnerDob,
entityRunnerId: props.entityRunnerId
};
return {
client: props.fcpClient,
fetchPolicy: "cache-and-network",
pollInterval: 0,
ssr: false,
variables
};
},
props: handleResultsIPP
};
export const ApolloOptionsRunnerStats = {
options: (props: GraphFcpProps) => {
const variables = {
...QUERY_VARIABLES_RUNNER_STATS,
wagerProfile: props.wagerProfile || getPortByBrand(),
runnerName: props.runnerName,
runnerDob: props.runnerDob,
entityRunnerId: props.entityRunnerId
};
return {
client: props.fcpClient,
fetchPolicy: "cache-and-network",
pollInterval: 0,
ssr: false,
variables
};
},
props: handleRunnerStats
};
const handleResultsPP = (result: {}) => ({
pastRace: get(result, "data.pastRaces[0]", null),
fullResults: mapRunnersToFullResults(
get(result, "data.pastRaces[0].bettingInterests", []),
get(result, "data.pastRaces[0].results.runners", [])
),
isLoading: get(result, "data.loading", false),
hasTimeformData: !!get(
result,
"data.pastRaces[0].results.runners[0].timeform",
false
)
});
export const ApolloOptionsPP = {
options: (props: GraphFcpProps) => {
const variables = {
...QUERY_VARIABLES_PP,
wagerProfile: props.wagerProfile || getPortByBrand(),
trackCode: props.trackCode,
raceNumber: `${props.raceNumber || ""}`,
date: props.raceDate
};
return {
client: props.fcpClient,
fetchPolicy: "cache-and-network",
pollInterval: 0,
ssr: false,
variables
};
},
props: handleResultsPP
};
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/graphql/queries/racePastPerformance.ts
import { gql } from "@apollo/client";
export const GET_PAST_RACE = gql`
query getPastRace(
$wagerProfile: String!
$trackCode: String
$raceNumber: String
$date: String
) {
pastRaces(
trackCode: $trackCode
raceNumber: $raceNumber
date: $date
profile: $wagerProfile
) {
raceId: id
raceDate: date
date: postTime
number
track {
id
name
code
}
video {
replayFileName
}
distance {
value
code
}
surface {
shortName
defaultCondition
}
raceClass {
shortName
}
type {
code
}
purse
results {
runners {
entityRunnerId
biNumber
runnerNumber
finishPosition
scratched
currentOdds {
numerator
denominator
}
timeform {
postRaceReport
accBeatenDistance
accBeatenDistanceStatus
accBeatenDistanceStatusAbrev
}
favorite
}
}
numRunners
}
}
`;
export default GET_PAST_RACE;
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/graphql/queries/wagerGroupQuery.ts
import { gql } from "@apollo/client";
export const GET_RACE_WAGERS = gql`
query getRaceWagers(
$accountId: Int!
$trackCode: String
$raceNumber: Int
$startDate: String
$endDate: String
) {
wagerHistory(
accountId: $accountId
trackCode: $trackCode
raceNumber: $raceNumber
beginDate: $startDate
endDate: $endDate
) {
id
groupWagers(group: { group: RACE, order: DESC }) {
value: key
wagers: value {
id
serialNumber
wagerAmount
betTotal: cost
betRefund
winningsAmount: winnings
betStatus {
code
name
}
transactionDate
wageringPlatform
wagerType {
id
code
name
}
promoQualifying
cancelableStatus {
code
name
}
cancelable
selections {
selectionString
modifier
selection {
bettingInterests {
currentOdds {
numerator
denominator
}
biNumber
isWinner
runners {
runnerId
scratched
horseName
}
payouts {
amount
wagerType {
code
}
}
}
alternateBettingInterest {
currentOdds {
numerator
denominator
}
biNumber
isWinner
runners {
runnerId
scratched
horseName
}
payouts {
amount
wagerType {
code
}
}
}
selectionType {
code
name
}
runners {
number
}
}
}
raceDate
racePostTime: postTime
raceTypeAbbreviation: raceType
tvgRaceId
trackName
wagerReference
}
}
}
}
`;
export default GET_RACE_WAGERS;
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/graphql/queries/wagerGroupQueryBehg.ts
import { gql } from "@apollo/client";
export const GET_RACE_WAGERS = gql`
query getRaceWagers(
$accountId: Int!
$trackCode: String
$raceNumber: Int
$startDate: String
$endDate: String
) {
wagerHistory(
accountId: $accountId
trackCode: $trackCode
raceNumber: $raceNumber
beginDate: $startDate
endDate: $endDate
) {
id
groupWagers(group: { group: RACE, order: DESC }) {
value: key
wagers: value {
id
serialNumber
wagerAmount
betTotal: cost
betRefund
winningsAmount: winnings
betStatus {
code
name
}
transactionDate
wageringPlatform
wagerType {
id
code
name
}
promoQualifying
cancelableStatus {
code
name
}
cancelable
selections {
selectionString
modifier
selection {
bettingInterests {
currentOdds {
numerator
denominator
}
biNumber
isWinner
runners {
runnerId
scratched
horseName
}
payouts {
amount
wagerType {
code
}
}
}
selectionType {
code
name
}
runners {
number
}
}
}
raceDate
racePostTime: postTime
raceTypeAbbreviation: raceType
tvgRaceId
trackName
wagerReference
}
}
}
}
`;
export default GET_RACE_WAGERS;
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/components/SimpleInlineInfo/index.tsx
import React, { FC } from "react";
import { get } from "lodash";
import { HandicapOptions } from "@tvg/ts-types/Race";
import { Icon } from "@tvg/design-system";
import {
Description,
OptionItem,
InfoItems,
InfoItem,
InfoContainer,
FavoriteTag,
Separator,
IconContainer
} from "./styled-components";
interface Props {
/**
* Description of the race
*/
title?: string;
/**
* Inline data to displayed
*/
info: Array<HandicapOptions | string>;
/**
* Handicap options keys to highlight (only available if info typeof HandicapOptions)
*/
highlighted?: Array<string>;
/**
* Handicap options keys to mark has changed (only available if info typeof HandicapOptions)
*/
changed?: Array<string>;
/**
* Handicap options keys with favorite tag (only available if info typeof HandicapOptions)
*/
favorite?: Array<string>;
/**
* Handicap info separator
*/
separator?: string;
/**
* Style class name
*/
className?: string;
/*
use updated icon to not break anywhere the icon
*/
useUpdatedIcon?: boolean;
}
const SimpleInlineInfo: FC<Props> = ({
title = "",
info = [],
highlighted = [],
changed = [],
favorite = [],
separator = " |",
className = "",
useUpdatedIcon = false
}) => {
const isInfoArrayOfStrings = () =>
info.reduce(
(result, infoItem) => result && typeof infoItem === "string",
true
);
const renderInfoItems = () => (
<InfoItems data-qa-label="handicapItems">
{info.map((infoItem, infoIndex) => {
const hasSeparator = infoIndex !== 0;
if (typeof infoItem === "string")
return hasSeparator ? `${separator} ${infoItem}` : infoItem;
const infoItemKey = get(infoItem, "key", `keyDefault_${infoIndex}`);
const hasChanges = changed && changed.includes(infoItemKey);
return (
<InfoItem
key={infoItemKey}
data-qa-label={`handicapItem-${infoItemKey}`}
isHighlighted={highlighted && highlighted.includes(infoItemKey)}
hasChanges={hasChanges}
>
{hasSeparator && <Separator>{`${separator} `}</Separator>}
{hasChanges && (
<IconContainer>
<Icon
name="changes"
size="s"
backgroundColor={
useUpdatedIcon ? "orange.400" : "transparent"
}
lineColor={useUpdatedIcon ? "grey.900" : "orange.400"}
/>
</IconContainer>
)}
{infoItem.value}
{favorite && favorite.includes(infoItemKey) && (
<FavoriteTag>FAV</FavoriteTag>
)}
</InfoItem>
);
})}
</InfoItems>
);
return (
<InfoContainer className={className}>
{!!title && (
<Description data-qa-label="handicapDescription">{title}</Description>
)}
{isInfoArrayOfStrings() ? (
<OptionItem data-qa-label="handicapItem">
{info.join(`${separator} `)}
</OptionItem>
) : (
renderInfoItems()
)}
</InfoContainer>
);
};
export default SimpleInlineInfo;
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/components/RunnerInfoPastPerformance/styled-components.ts
import styled from "styled-components";
import { Button } from "@tvg/design-system/web";
export const RaceSection = styled.div`
display: flex;
align-items: center;
justify-content: flex-start;
width: 100%;
padding: 12px 6px 12px 12px;
background-color: ${({ theme }) => theme.colorTokens.content.onDark};
& > * {
flex-shrink: 0;
}
`;
export const RaceInfo = styled.div`
flex: 1 1 auto;
align-items: flex-start;
flex-direction: column;
justify-content: center;
& li {
font-size: 14px;
}
`;
export const TrackRace = styled.h3`
display: flex;
text-align: left;
font-family: ${({ theme }) => theme.fonts.bold};
font-size: 16px;
line-height: 22px;
color: ${({ theme }) => theme.colorTokens.content.default};
`;
export const TrackDate = styled.time`
font-family: ${({ theme }) => theme.fonts.regular};
display: flex;
text-align: left;
font-size: 14px;
color: ${({ theme }) => theme.colorTokens.background.neutral};
line-height: 18px;
`;
export const RaceDataList = styled.ul`
list-style: none;
text-align: left;
`;
export const RaceArrowLink = styled(Button)<{ isDisabled?: boolean }>`
background: ${({ theme }) =>
theme.colorTokens.component.button.secondaryDark.background.base};
&:active {
background-color: ${({ theme }) =>
theme.colorTokens.component.button.secondaryDark.background.hover};
}
${({ isDisabled }) =>
isDisabled &&
`
svg {
color: var(--fd-colors-component-button-secondary-content-disabled) !important;
stroke: var(--fd-colors-component-button-secondary-content-disabled) !important;
path {
stroke: var(--fd-colors-component-button-secondary-content-disabled) !important;
}
}
`}
`;
export const RaceArrowContent = styled.span`
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
`;
export const RaceArrowNavigation = styled.div`
display: flex;
flex: 0 0 72px;
flex-direction: row;
align-items: stretch;
margin-left: 8px;
`;
export const NavigationTip = styled.span<{ hasCallback?: boolean }>`
font-family: ${({ theme }) => theme.fonts.medium};
font-size: 12px;
color: ${({ hasCallback, theme }) =>
hasCallback
? theme.colorTokens.content.default
: theme.colorTokens.background.neutral};
`;
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/components/RunnerInfoPastPerformance/index.tsx
import React, { PureComponent } from "react";
import { get, noop } from "lodash";
import { formatDateWithTextDayFirst } from "@tvg/formatter/dates";
import { formatPurse } from "@tvg/formatter/currency";
import { PastPerformanceRace as PastPerformanceRaceType } from "@tvg/ts-types/Race";
import { NullaryFn } from "@tvg/ts-types/Functional";
import SimpleInlineInfo from "@tvg/ipp/src/components/SimpleInlineInfo";
import { Icon } from "@tvg/design-system";
import {
NavigationTip,
RaceInfo,
TrackRace,
TrackDate,
RaceSection,
RaceArrowLink,
RaceArrowNavigation,
RaceArrowContent
} from "./styled-components";
interface Props {
race: PastPerformanceRaceType;
hasNextRace: boolean;
hasPreviousRace: boolean;
onPreviousRaceNavigation: NullaryFn<void>;
onNextRaceNavigation: NullaryFn<void>;
}
export default class RunnerInfoPastPerformance extends PureComponent<Props> {
static defaultProps = {
onClick: noop,
hasNextRace: false,
hasPreviousRace: false,
onPreviousRaceNavigation: noop,
onNextRaceNavigation: noop
};
renderInfo = () => {
const { race } = this.props;
return (
<RaceInfo>
<TrackDate
key="race-date"
data-qa-label="race-info-date"
dateTime={race.date}
>
{formatDateWithTextDayFirst(race.date).replace("'", "")}
</TrackDate>
<TrackRace data-qa-label="race-track-number">{`${race.track.name} R${race.number}`}</TrackRace>
<SimpleInlineInfo
info={[
{
key: "numRunners",
value: `${get(this.props.race, "numRunners")} runners`
},
{
key: "distance",
value: `${get(this.props.race, "distance") || "-"}`
},
{
key: "course",
value: `${get(this.props.race, "surface.shortName") || "-"}`
},
{
key: "condition",
value: `${
get(this.props.race, "surface.defaultCondition") || "-"
}`
},
{
key: "raceClass",
value: `${get(this.props.race, "raceClass.shortName") || "-"}`
},
{
key: "purse",
value: formatPurse(get(this.props.race, "purse"))
}
]}
highlighted={["distance", "course"]}
separator=","
/>
</RaceInfo>
);
};
renderNavigation = () => {
if (!this.props.hasNextRace && !this.props.hasPreviousRace) {
return null;
}
const renderButton = (
type: "back" | "forward",
callback: NullaryFn<void>,
isDisabled?: boolean
) => {
const buttonContent = (
<RaceArrowContent>
<Icon name={type === "back" ? "arrowLeft" : "arrowRight"} size="s" />
<NavigationTip hasCallback={!!callback}>
{type === "back" ? "Prev." : "Next"}
</NavigationTip>
</RaceArrowContent>
);
return (
<RaceArrowLink
qaLabel={
isDisabled
? `ipp-navigation-${type}-disable`
: `ipp-navigation-${type}`
}
onClick={callback}
isDisabled={isDisabled}
variant="tertiary"
size="m"
>
{buttonContent}
</RaceArrowLink>
);
};
return (
<RaceArrowNavigation>
{renderButton(
"back",
this.props.onPreviousRaceNavigation,
!this.props.hasPreviousRace
)}
{renderButton(
"forward",
this.props.onNextRaceNavigation,
!this.props.hasNextRace
)}
</RaceArrowNavigation>
);
};
renderSimpleLayout = () => (
<RaceSection data-qa-label="ipp-past-race">
{this.renderInfo()}
{this.renderNavigation()}
</RaceSection>
);
render() {
return this.renderSimpleLayout();
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/PositionLabel/styled-components.js
import styled, { css } from "styled-components";
import buildColor from "../../_static/ColorPalette";
export default styled.strong`
border-radius: 2px;
display: inline-flex;
height: 15px;
font-size: 12px;
line-height: 14px;
align-items: center;
padding: 0 2px;
margin: 0 4px;
${({ nonNumeric }) =>
nonNumeric
? css`
color: ${buildColor("grey", "700")};
border: 1px solid ${buildColor("grey", "700")};
`
: css`
color: ${buildColor("grey", "900")};
background-color: ${buildColor("blue", "100")};
`}
& > sup {
display: inline-block;
font-size: 8px;
transform: translate(0, -2px);
margin-right: 4px;
vertical-align: inherit;
}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/PositionLabel/index.jsx
import React, { PureComponent } from "react";
import { toString, isFinite } from "lodash";
import formatSequencial from "@tvg/formatter/numeric";
import Position from "./styled-components";
export default class PositionLabel extends PureComponent {
getNonNumericPosition() {
let position;
const { race } = this.props;
if (isFinite(race.finishPosition)) {
if (race.finishPosition <= 0) {
position = <Position nonNumeric>SCR</Position>;
} else {
position = <Position nonNumeric>DNF</Position>;
}
} else {
position = <Position>- {`/ ${race.numRunners}`}</Position>;
}
return position;
}
getPosition() {
const { race } = this.props;
return (
isFinite(race.finishPosition) && (
<Position>
{race.finishPosition}
<sup>
{formatSequencial(race.finishPosition).replace(
toString(race.finishPosition),
""
)}
</sup>
{`/ ${race.numRunners}`}
</Position>
)
);
}
render() {
const { race } = this.props;
return typeof race.finishPosition === "number" &&
!!race.finishPosition &&
race.finishPosition > 0 &&
race.finishPosition <= +race.numRunners
? this.getPosition()
: this.getNonNumericPosition();
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/PastPerformanceRace/styled-components.js
import styled, { css } from "styled-components";
import Button from "../../_atom/Buttons/default";
import { titleFont } from "../../_static/Typography";
import buildColor from "../../_static/ColorPalette";
export const RaceButton = styled.button`
display: flex;
align-items: center;
justify-content: flex-start;
width: 100%;
padding: 8px 8px 8px 6px;
outline: none;
${(props) =>
props.isSelected
? css`
background-color: ${buildColor("blue", "000")};
position: relative;
&::before {
content: "";
position: absolute;
width: 2px;
top: 0;
left: 0;
bottom: 0;
background-color: ${buildColor("blue_accent", "500")};
}
`
: css`
background-color: ${buildColor("white", "0")};
`};
& > * {
flex-shrink: 0;
}
`;
export const RaceSection = styled.div`
display: flex;
align-items: center;
justify-content: flex-start;
width: 100%;
padding: 8px 0;
background-color: ${buildColor("white", "100")};
& > * {
flex-shrink: 0;
}
`;
export const Date = styled.time`
width: 42px;
min-height: 32px;
display: flex;
flex: 0 0 auto;
align-items: flex-start;
justify-content: center;
flex-direction: column;
color: ${buildColor("grey", "800")};
text-transform: uppercase;
font-size: 10px;
line-height: 1.4;
border-right: 1px solid ${buildColor("blue", "100")};
strong {
color: ${buildColor("grey", "900")};
}
`;
export const RaceInfo = styled.div`
flex: 1 1 auto;
align-items: flex-start;
flex-direction: column;
justify-content: center;
padding-left: 8px;
`;
export const TrackRace = styled.h3`
display: flex;
text-align: left;
font-family: ${titleFont};
text-transform: uppercase;
color: ${buildColor("grey", "900")};
`;
export const TrackDate = styled.time`
display: flex;
text-align: left;
height: 12px;
width: 55px;
font-size: 11px;
color: ${buildColor("grey", "800")};
font-weight: bold;
margin-bottom: 2px;
`;
export const RaceDataList = styled.ul`
list-style: none;
text-align: left;
`;
export const RaceDataListItem = styled.li`
font-size: 12px;
color: ${buildColor("grey", "800")};
display: inline;
text-align: left;
&:not(:last-child) {
&::after {
content: "";
border-right: 1px solid ${buildColor("grey", "600")};
padding-right: 4px;
margin-right: 4px;
}
}
`;
export const Position = styled.strong`
border-radius: 2px;
display: flex;
height: 15px;
align-items: center;
padding: 0 2px;
margin: 0 4px;
color: ${buildColor("grey", "900")};
background-color: ${buildColor("blue", "100")};
& > sup {
display: inline-block;
font-size: 8px;
transform: translate(0, -2px);
margin-right: 4px;
vertical-align: inherit;
}
`;
export const RaceArrowLink = styled(Button)`
background: ${buildColor("white", "0")};
width: 40px;
&:active {
background-color: ${buildColor("white", "50")};
}
`;
export const RaceArrowContent = styled.span`
display: flex;
align-items: center;
justify-content: center;
width: 40px;
`;
export const RaceArrowNavigation = styled.div`
display: flex;
flex: 0 0 72px;
flex-direction: row;
align-items: stretch;
margin-left: 8px;
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/PastPerformanceRace/index.jsx
import React, { PureComponent } from "react";
import { noop } from "lodash";
import { formatRaceDate, formatDateWithText } from "@tvg/formatter/dates";
import { formatPurse } from "@tvg/formatter/currency";
import PositionLabel from "../../_atom/PositionLabel";
import Icon from "../../_static/Icons";
import {
arrowBack,
arrowForward,
videoReplay,
noVideoReplay
} from "../../_static/Icons/icons";
import buildColor from "../../_static/ColorPalette";
import {
RaceButton,
Date,
RaceInfo,
TrackRace,
TrackDate,
RaceDataList,
RaceDataListItem,
RaceSection,
RaceArrowLink,
RaceArrowNavigation,
RaceArrowContent
} from "./styled-components";
export default class PastPerformanceRace extends PureComponent {
static defaultProps = {
onClick: noop,
isSelected: false,
hasNextRace: false,
hasPreviousRace: false,
useSimpleLayout: false,
onPreviousRaceNavigation: noop,
onNextRaceNavigation: noop,
hasNumberOfRunners: undefined
};
renderDate = () => {
const date = formatRaceDate(this.props.race.date).split(" ");
return (
<Date data-qa-label="race-info-date">
<strong>{`${date[1]} ${date[0]}`}</strong>
{date[2]}
</Date>
);
};
renderInfo = (withDate = false) => {
const { race, useSimpleLayout, hasNumberOfRunners } = this.props;
return (
<RaceInfo>
<TrackRace data-qa-label="race-track-number">{`${race.track.name} R${race.number}`}</TrackRace>
{withDate && (
<TrackDate
key="race-date"
data-qa-label="race-info-date"
dateTime={race.date}
>
{formatDateWithText(race.date)}
</TrackDate>
)}
<RaceDataList>
{(typeof hasNumberOfRunners === "boolean"
? hasNumberOfRunners
: useSimpleLayout) && (
<RaceDataListItem
key="race-numRunners"
data-qa-label="race-info-numRunners"
>
{race.numRunners} runners
</RaceDataListItem>
)}
<RaceDataListItem
key="race-distance"
data-qa-label="race-info-distance"
>
{race.distance}
</RaceDataListItem>
<RaceDataListItem
key="race-surface"
data-qa-label="race-info-surface"
>
{race.surface.shortName}
</RaceDataListItem>
<RaceDataListItem
key="race-condition"
data-qa-label="race-info-condition"
>
{race.surface.defaultCondition}
</RaceDataListItem>
<RaceDataListItem key="race-class" data-qa-label="race-info-class">
{race.raceClass.shortName}
</RaceDataListItem>
<RaceDataListItem key="race-purse" data-qa-label="race-info-purse">
{formatPurse(race.purse)}
</RaceDataListItem>
</RaceDataList>
</RaceInfo>
);
};
renderPosition = () => {
const { race } = this.props;
return <PositionLabel race={race} />;
};
renderReplay = () => {
const hasReplay = this.props.race.hasReplays;
return (
<Icon
data-qa-label={hasReplay ? "video-replay" : "no-video-replay"}
color={
hasReplay ? buildColor("grey", "900") : buildColor("grey", "700")
}
icon={hasReplay ? videoReplay : noVideoReplay}
/>
);
};
renderNavigation = () => {
if (!this.props.hasNextRace && !this.props.hasPreviousRace) {
return null;
}
const renderButton = (icon, callback, type) => {
const buttonContent = (
<RaceArrowContent
{...(!callback
? { "data-qa-label": `ipp-navigation-${type}-disable` }
: {})}
>
<Icon
icon={icon}
size={16}
color={
callback ? buildColor("grey", "900") : buildColor("grey", "600")
}
/>
</RaceArrowContent>
);
return callback ? (
<RaceArrowLink onClick={callback} qaLabel={`ipp-navigation-${type}`}>
{buttonContent}
</RaceArrowLink>
) : (
buttonContent
);
};
return (
<RaceArrowNavigation>
{renderButton(
arrowBack,
this.props.hasPreviousRace
? this.props.onPreviousRaceNavigation
: null,
"back"
)}
{renderButton(
arrowForward,
this.props.hasNextRace ? this.props.onNextRaceNavigation : null,
"forward"
)}
</RaceArrowNavigation>
);
};
renderSimpleLayout = () => (
<RaceSection data-qa-label="ipp-past-race">
{this.renderInfo(true)}
{this.renderNavigation()}
</RaceSection>
);
renderFullLayout = () => (
<RaceButton
onClick={!this.props.isSelected ? this.props.onClick : noop}
isSelected={this.props.isSelected}
>
{this.renderDate()}
{this.renderInfo()}
{this.renderPosition()}
{this.renderReplay()}
</RaceButton>
);
render() {
if (this.props.useSimpleLayout) {
return this.renderSimpleLayout();
}
return this.renderFullLayout();
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/__mocks__/ipp-pastRaces.mock.js
export const horsePastRaces = [
{
id: "GP-12",
raceDate: "2017-01-28T00:00:00",
date: "2017-01-28T00:00:00",
number: "12",
raceTypeCode: "T",
track: {
name: "Gulfstream Park",
code: "GP"
},
hasReplays: true,
replayFileName: "movie",
distance: "21f",
surface: {
shortName: "Dirt",
defaultCondition: "Fast"
},
raceClass: {
shortName: "Stakes"
},
purse: 12000000,
numRunners: 17,
finishPosition: 1,
scratched: false,
odds: { numerator: 4, denominator: 5 }
},
{
id: "LRC-9",
raceDate: "2016-12-17T00:00:00",
date: "2016-12-17T00:00:00",
number: "9",
raceTypeCode: "T",
replayFileName: "movie",
track: {
name: "Los Alamitos TBred",
code: "LRC"
},
hasReplays: false,
distance: "8.5f",
surface: {
shortName: "Dirt",
defaultCondition: "Fast"
},
raceClass: {
shortName: "Stakes"
},
purse: 180000,
numRunners: 17,
finishPosition: 0,
scratched: false,
odds: { numerator: 4, denominator: null },
postRaceReport:
"Dueled, short lead backstr, hustled hard late turn, clr top str, heldDueled, short lead backstr."
},
{
id: "SA-12",
raceDate: "2016-11-05T00:00:00",
date: "2016-11-05T00:00:00",
number: "12",
raceTypeCode: "T",
replayFileName: "movie",
track: {
name: "Breeders Cup Santa Anita",
code: "SA"
},
hasReplays: true,
distance: "10f",
surface: {
shortName: "Dirt",
defaultCondition: "Fast"
},
raceClass: {
shortName: "Stakes"
},
purse: 6000000,
numRunners: 20,
finishPosition: null,
scratched: true
},
{
id: "SA-7",
raceDate: "2016-10-01T00:00:00",
date: "2016-10-01T00:00:00",
number: "7",
raceTypeCode: "T",
track: {
name: "Santa Anita",
code: "SA"
},
hasReplays: true,
distance: "9f",
surface: {
shortName: "Dirt",
defaultCondition: "Fast"
},
raceClass: {
shortName: "Stakes"
},
purse: 300000,
numRunners: 17,
finishPosition: 99,
scratched: false,
odds: { numerator: 4, denominator: null },
postRaceReport:
"Dueled, short lead backstr, hustled hard late turn, clr top str, heldDueled, short lead backstr."
},
{
id: "DUB-9",
raceDate: "2016-03-26T00:00:00",
date: "2016-03-26T00:00:00",
number: "9",
raceTypeCode: "T",
track: {
name: "Dubai",
code: "DUB"
},
hasReplays: true,
distance: "10f",
surface: {
shortName: "Dirt",
defaultCondition: "Fast"
},
raceClass: {
shortName: "Stakes"
},
purse: 10000000,
numRunners: 17,
finishPosition: 4,
scratched: false,
odds: { numerator: 4, denominator: 5 },
postRaceReport:
"Dueled, short lead backstr, hustled hard late turn, clr top str, heldDueled, short lead backstr."
},
{
id: "SA-8",
raceDate: "2016-01-09T00:00:00",
date: "2016-01-09T00:00:00",
number: "8",
raceTypeCode: "T",
track: {
name: "Santa Anita",
code: "SA"
},
hasReplays: true,
distance: "8.5f",
surface: {
shortName: "Dirt",
defaultCondition: "Fast"
},
raceClass: {
shortName: "Stakes"
},
purse: 200000,
numRunners: 17,
finishPosition: 3,
scratched: false,
odds: { numerator: 4, denominator: 5 },
postRaceReport:
"Dueled, short lead backstr, hustled hard late turn, clr top str, heldDueled, short lead backstr."
},
{
id: "DUB-9",
raceDate: "2015-03-28T00:00:00",
date: "2015-03-28T00:00:00",
number: "9",
raceTypeCode: "T",
track: {
name: "Dubai",
code: "DUB"
},
hasReplays: true,
distance: "10f",
surface: {
shortName: "Dirt",
defaultCondition: "Fast"
},
raceClass: {
shortName: "Stakes"
},
purse: 10000000,
numRunners: 17,
finishPosition: 2,
scratched: false,
odds: { numerator: 4, denominator: 5 },
postRaceReport:
"Dueled, short lead backstr, hustled hard late turn, clr top str, heldDueled, short lead backstr."
},
{
id: "SA-8",
raceDate: "2015-02-07T00:00:00",
date: "2015-02-07T00:00:00",
number: "8",
raceTypeCode: "T",
track: {
name: "Santa Anita",
code: "SA"
},
hasReplays: true,
distance: "9f",
surface: {
shortName: "Dirt",
defaultCondition: "Fast"
},
raceClass: {
shortName: "Stakes"
},
purse: 500000,
numRunners: 17,
finishPosition: 1,
scratched: false,
odds: { numerator: 4, denominator: 5 },
postRaceReport:
"Dueled, short lead backstr, hustled hard late turn, clr top str, heldDueled, short lead backstr."
},
{
id: "SXC-4",
raceDate: "2015-02-07T00:00:00",
date: "2015-02-07T00:00:00",
number: "4",
raceTypeCode: "T",
track: {
name: "Cross Country Pick 4",
code: "SXC"
},
hasReplays: true,
distance: "9f",
surface: {
shortName: "Dirt",
defaultCondition: "Fast"
},
raceClass: {
shortName: "Stakes"
},
purse: 500000,
numRunners: 17,
finishPosition: 1,
scratched: false,
odds: { numerator: 4, denominator: 5 },
postRaceReport:
"Dueled, short lead backstr, hustled hard late turn, clr top str, heldDueled, short lead backstr."
},
{
id: "DMR-8",
raceDate: "2014-11-29T00:00:00",
date: "2014-11-29T00:00:00",
number: "8",
raceTypeCode: "T",
track: {
name: "Del Mar",
code: "DMR"
},
hasReplays: true,
distance: "9f",
surface: {
shortName: "Turf",
defaultCondition: "Good"
},
raceClass: {
shortName: "Stakes"
},
purse: 300000,
numRunners: 17,
finishPosition: 1,
scratched: false,
odds: { numerator: 4, denominator: 5 },
postRaceReport:
"Dueled, short lead backstr, hustled hard late turn, clr top str, heldDueled, short lead backstr."
},
{
id: "SA-12",
raceDate: "2014-11-01T00:00:00",
date: "2014-11-01T00:00:00",
number: "12",
raceTypeCode: "T",
track: {
name: "Breeders Cup Santa Anita",
code: "SA"
},
hasReplays: true,
distance: "10f",
surface: {
shortName: "Dirt",
defaultCondition: "Fast"
},
raceClass: {
shortName: "Stakes"
},
purse: 5000000,
numRunners: 17,
finishPosition: 10,
scratched: false,
odds: { numerator: 4, denominator: 5 },
postRaceReport:
"Dueled, short lead backstr, hustled hard late turn, clr top str, heldDueled, short lead backstr."
},
{
id: "PHI-12",
raceDate: "2014-09-20T00:00:00",
date: "2014-09-20T00:00:00",
number: "12",
raceTypeCode: "T",
track: {
name: "Parx Racing",
code: "PHI"
},
hasReplays: true,
distance: "9f",
surface: {
shortName: "Dirt",
defaultCondition: "Fast"
},
raceClass: {
shortName: "Stakes"
},
purse: 1000000,
numRunners: 17,
finishPosition: 1,
scratched: false,
odds: { numerator: 4, denominator: 5 },
postRaceReport:
"Dueled, short lead backstr, hustled hard late turn, clr top str, heldDueled, short lead backstr."
},
{
id: "BEL-11",
raceDate: "2014-06-07T00:00:00",
date: "2014-06-07T00:00:00",
number: "11",
raceTypeCode: "T",
track: {
name: "Belmont",
code: "BEL"
},
hasReplays: true,
distance: "12f",
surface: {
shortName: "Dirt",
defaultCondition: "Fast"
},
raceClass: {
shortName: "Stakes"
},
purse: 1500000,
numRunners: 17,
finishPosition: 1,
scratched: false,
odds: { numerator: 4, denominator: 5 },
postRaceReport:
"Dueled, short lead backstr, hustled hard late turn, clr top str, heldDueled, short lead backstr."
},
{
id: "PIM-12",
raceDate: "2014-05-17T00:00:00",
date: "2014-05-17T00:00:00",
number: "12",
raceTypeCode: "T",
track: {
name: "Pimlico",
code: "PIM"
},
hasReplays: true,
distance: "9.5f",
surface: {
shortName: "Dirt",
defaultCondition: "Fast"
},
raceClass: {
shortName: "Stakes"
},
purse: 1500000,
numRunners: 17,
finishPosition: 1,
scratched: false,
odds: { numerator: 4, denominator: 5 },
postRaceReport:
"Dueled, short lead backstr, hustled hard late turn, clr top str, heldDueled, short lead backstr."
},
{
id: "CD-11",
raceDate: "2014-05-03T00:00:00",
date: "2014-05-03T00:00:00",
number: "11",
raceTypeCode: "T",
track: {
name: "Churchill Downs KY Derby",
code: "CD"
},
hasReplays: true,
distance: "10f",
surface: {
shortName: "Dirt",
defaultCondition: "Fast"
},
raceClass: {
shortName: "Stakes"
},
purse: 2000000,
numRunners: 17,
finishPosition: 1,
scratched: false,
odds: { numerator: 4, denominator: 5 },
postRaceReport:
"Dueled, short lead backstr, hustled hard late turn, clr top str, heldDueled, short lead backstr."
},
{
id: "SA-8",
raceDate: "2014-04-05T00:00:00",
date: "2014-04-05T00:00:00",
number: "8",
raceTypeCode: "T",
track: {
name: "Santa Anita",
code: "SA"
},
hasReplays: true,
distance: "9f",
surface: {
shortName: "Dirt",
defaultCondition: "Fast"
},
raceClass: {
shortName: "Stakes"
},
purse: 1000000,
numRunners: 17,
finishPosition: 1,
scratched: false,
odds: { numerator: 4, denominator: 5 },
postRaceReport:
"Dueled, short lead backstr, hustled hard late turn, clr top str, heldDueled, short lead backstr."
},
{
id: "SA-5",
raceDate: "2014-03-08T00:00:00",
date: "2014-03-08T00:00:00",
number: "5",
raceTypeCode: "T",
track: {
name: "Santa Anita",
code: "SA"
},
hasReplays: true,
distance: "8.5f",
surface: {
shortName: "Dirt",
defaultCondition: "Fast"
},
raceClass: {
shortName: "Stakes"
},
purse: 300000,
numRunners: 17,
finishPosition: 1,
scratched: false,
odds: { numerator: 4, denominator: 5 },
postRaceReport:
"Dueled, short lead backstr, hustled hard late turn, clr top str, heldDueled, short lead backstr."
},
{
id: "SA-10",
raceDate: "2014-01-25T00:00:00",
date: "2014-01-25T00:00:00",
number: "10",
raceTypeCode: "T",
track: {
name: "Santa Anita",
code: "SA"
},
hasReplays: true,
distance: "8.5f",
surface: {
shortName: "Dirt",
defaultCondition: "Fast"
},
raceClass: {
shortName: "Stakes"
},
purse: 250000,
numRunners: 17,
finishPosition: 1,
scratched: false,
odds: { numerator: 4, denominator: 5 },
postRaceReport:
"Dueled, short lead backstr, hustled hard late turn, clr top str, heldDueled, short lead backstr."
},
{
id: "SA-3",
raceDate: "2013-11-01T00:00:00",
date: "2013-11-01T00:00:00",
number: "3",
raceTypeCode: "T",
track: {
name: "Santa Anita",
code: "SA"
},
hasReplays: true,
distance: "8f",
surface: {
shortName: "Dirt",
defaultCondition: "Fast"
},
raceClass: {
shortName: "Stakes"
},
purse: 200000,
numRunners: 17,
finishPosition: 1,
scratched: false,
odds: { numerator: 4, denominator: 5 },
postRaceReport:
"Dueled, short lead backstr, hustled hard late turn, clr top str, heldDueled, short lead backstr."
},
{
id: "DMR-8",
raceDate: "2013-09-04T00:00:00",
date: "2013-09-04T00:00:00",
number: "8",
raceTypeCode: "T",
track: {
name: "Del Mar",
code: "DMR"
},
hasReplays: true,
distance: "7f",
surface: {
shortName: "Synth",
defaultCondition: "Fast"
},
raceClass: {
shortName: "Stakes"
},
purse: 300000,
numRunners: 17,
finishPosition: 1,
scratched: false,
odds: { numerator: 4, denominator: 5 },
postRaceReport:
"Dueled, short lead backstr, hustled hard late turn, clr top str, heldDueled, short lead backstr."
},
{
id: "DMR-7",
raceDate: "2013-07-31T00:00:00",
date: "2013-07-31T00:00:00",
number: "7",
raceTypeCode: "T",
track: {
name: "Del Mar",
code: "DMR"
},
hasReplays: true,
distance: "5.5f",
surface: {
shortName: "Synth",
defaultCondition: "Fast"
},
raceClass: {
shortName: "Stakes"
},
purse: 100000,
numRunners: 17,
finishPosition: 1,
scratched: false,
odds: { numerator: 4, denominator: 5 },
postRaceReport:
"Dueled, short lead backstr, hustled hard late turn, clr top str, heldDueled, short lead backstr."
}
];
export const runnerResults = [
{
runnerId: "1",
runnerName: "Arrogate",
trainer: "Baffert Bob",
jockey: "Smith Mike E",
scratched: false,
finishPosition: 1,
accBeatenDistance: "",
accBeatenDistanceStatus: "",
postRaceReport:
"rail position, 3w, turn, mild pressure late, geared down 1/16",
odds: { numerator: 4, denominator: 5 }
},
{
runnerId: "7",
runnerName: "Shaman Ghost",
trainer: "Jerkens James A",
jockey: "Ortiz Jose L",
scratched: false,
finishPosition: 2,
accBeatenDistance: "4.75",
accBeatenDistanceStatus: "4¾",
postRaceReport:
"allowed to settle, 2-3w rally, lug in 1/16, clearly 2nd best",
odds: { numerator: 19, denominator: null }
},
{
runnerId: "3",
runnerName: "Neolithic",
trainer: "Pletcher Todd A",
jockey: "Velazquez John R",
scratched: false,
finishPosition: 3,
accBeatenDistance: "3.50",
accBeatenDistanceStatus: "3½",
postRaceReport: "pressed pace two wide, led between calls turn, no match",
odds: { numerator: 23, denominator: null }
},
{
runnerId: "9",
runnerName: "Keen Ice",
trainer: "Pletcher Todd A",
jockey: "Castellano Javier",
scratched: false,
finishPosition: 4,
accBeatenDistance: "2.75",
accBeatenDistanceStatus: "2¾",
postRaceReport:
"outrun for 6F three wide, four wide into stretch, late interest",
odds: { numerator: 16, denominator: null }
},
{
runnerId: "5",
runnerName: "War Story",
trainer: "Navarro Jorge",
jockey: "Gallardo Antonio A",
scratched: false,
finishPosition: 5,
accBeatenDistance: "2.50",
accBeatenDistanceStatus: "2¼",
postRaceReport:
"rail both turns, clear down backstretch behind 1st flight, evenly",
odds: { numerator: 45, denominator: null }
},
{
runnerId: "4",
runnerName: "Noble Bird",
trainer: "Casse Mark E",
jockey: "Leparoux Julien R",
scratched: false,
finishPosition: 6,
accBeatenDistance: "1",
accBeatenDistanceStatus: "1",
postRaceReport:
"slight bobble start, alert to lead inside, weakened far turn rail",
odds: { numerator: 30, denominator: null }
},
{
runnerId: "8",
runnerName: "Semper Fortis",
trainer: "O'neill Doug F",
jockey: "Gaffalione Tyler",
scratched: true,
finishPosition: 7,
accBeatenDistance: "9",
accBeatenDistanceStatus: "9",
postRaceReport: "two wide first turn, two to three wide far turn, tired",
odds: { numerator: 99, denominator: null }
},
{
runnerId: "10",
runnerName: "Breaking Lucky",
trainer: "Baker Reade",
jockey: "Contreras Luis",
scratched: false,
finishPosition: 8,
accBeatenDistance: "3.25",
accBeatenDistanceStatus: "3¼",
postRaceReport: "four wide first turn, three wide far turn, no factor",
odds: { numerator: 70, denominator: null }
},
{
runnerId: "12",
runnerName: "California Chrome",
trainer: "Sherman Art",
jockey: "Espinoza Victor",
scratched: false,
finishPosition: 9,
accBeatenDistance: "3",
accBeatenDistanceStatus: "3",
postRaceReport:
"five wide to first turn, asked 4 wide near far turn, no response",
odds: { numerator: 6, denominator: 5 }
},
{
runnerId: "2",
runnerName: "Prayer For Relief",
trainer: "Romans Dale L",
jockey: "Geroux Florent",
scratched: false,
finishPosition: 10,
accBeatenDistance: "4.25",
accBeatenDistanceStatus: "4¼",
postRaceReport: "rail first turn, two wide far turn, never prominent",
odds: { numerator: 99, denominator: null }
},
{
runnerId: "6",
runnerName: "War Envoy",
trainer: "Ruis Mick",
jockey: "Saez Luis",
scratched: false,
finishPosition: 11,
accBeatenDistance: "10",
accBeatenDistanceStatus: "10",
postRaceReport: "bobbled start, rail turns, finished early",
odds: { numerator: 99, denominator: null }
},
{
runnerId: "11",
runnerName: "Eragon (Arg)",
trainer: "Wohlers Laura",
jockey: "Prado Edgar S",
scratched: false,
finishPosition: 12,
accBeatenDistance: "18",
accBeatenDistanceStatus: "18",
postRaceReport: "trailed throughout, eased in stretch",
odds: { numerator: 80, denominator: null }
},
{
runnerId: "41",
runnerName: "California Hello",
trainer: "Sherman Art 2",
jockey: "Espinoza Victor 2",
scratched: true,
finishPosition: 99,
accBeatenDistance: "8",
accBeatenDistanceStatus: "8",
postRaceReport:
"five wide to first turn, asked 4 wide near far turn, no response",
odds: { numerator: 6, denominator: 5 }
}
];
export const runnerResultsBasic = [
{
runnerId: "1",
runnerName: "Arrogate",
trainer: "Baffert Bob",
jockey: "Smith Mike E",
scratched: false,
finishPosition: 1,
odds: { numerator: 4, denominator: 5 }
},
{
runnerId: "7",
runnerName: "Shaman Ghost",
trainer: "Jerkens James A",
jockey: "Ortiz Jose L",
scratched: false,
finishPosition: 2,
odds: { numerator: 19, denominator: null }
},
{
runnerId: "3",
runnerName: "Neolithic",
trainer: "Pletcher Todd A",
jockey: "Velazquez John R",
scratched: false,
finishPosition: 3,
odds: { numerator: 23, denominator: null }
},
{
runnerId: "9",
runnerName: "Keen Ice",
trainer: "Pletcher Todd A",
jockey: "Castellano Javier",
scratched: false,
finishPosition: 4,
odds: { numerator: 16, denominator: null }
},
{
runnerId: "5",
runnerName: "War Story",
trainer: "Navarro Jorge",
jockey: "Gallardo Antonio A",
scratched: false,
finishPosition: 5,
odds: { numerator: 45, denominator: null }
}
];
export const pastRaceFullResults = [
{
runnerId: "1",
runnerName: "Arrogate",
trainer: "Baffert Bob",
jockey: "Smith Mike E",
scratched: false,
finishPosition: 1,
odds: {
numerator: 4,
denominator: 5
},
postRaceReport:
"rail position, 3w, turn, mild pressure late, geared down 1/16",
accBeatenDistance: ""
},
{
runnerId: "7",
runnerName: "Shaman Ghost",
trainer: "Jerkens James A",
jockey: "Ortiz Jose L",
scratched: false,
finishPosition: 2,
odds: {
numerator: 19,
denominator: null
},
postRaceReport:
"allowed to settle, 2-3w rally, lug in 1/16, clearly 2nd best",
accBeatenDistance: "4¾"
},
{
runnerId: "3",
runnerName: "Neolithic",
trainer: "Pletcher Todd A",
jockey: "Velazquez John R",
scratched: false,
finishPosition: 3,
odds: {
numerator: 23,
denominator: null
},
postRaceReport: "pressed pace two wide, led between calls turn, no match",
accBeatenDistance: "3½"
},
{
runnerId: "9",
runnerName: "Keen Ice",
trainer: "Pletcher Todd A",
jockey: "Castellano Javier",
scratched: false,
finishPosition: 4,
odds: {
numerator: 16,
denominator: null
},
postRaceReport:
"outrun for 6F three wide, four wide into stretch, late interest",
accBeatenDistance: "2¾"
},
{
runnerId: "5",
runnerName: "War Story",
trainer: "Navarro Jorge",
jockey: "Gallardo Antonio A",
scratched: false,
finishPosition: 5,
odds: {
numerator: 45,
denominator: null
},
postRaceReport:
"rail both turns, clear down backstretch behind 1st flight, evenly",
accBeatenDistance: "2¼"
},
{
runnerId: "4",
runnerName: "Noble Bird",
trainer: "Casse Mark E",
jockey: "Leparoux Julien R",
scratched: false,
finishPosition: 6,
odds: {
numerator: 30,
denominator: null
},
postRaceReport:
"slight bobble start, alert to lead inside, weakened far turn rail",
accBeatenDistance: "1"
},
{
runnerId: "8",
runnerName: "Semper Fortis",
trainer: "O'neill Doug F",
jockey: "Gaffalione Tyler",
scratched: false,
finishPosition: 7,
odds: {
numerator: 99,
denominator: null
},
postRaceReport: "two wide first turn, two to three wide far turn, tired",
accBeatenDistance: "9"
},
{
runnerId: "10",
runnerName: "Breaking Lucky",
trainer: "Baker Reade",
jockey: "Contreras Luis",
scratched: false,
finishPosition: 8,
odds: {
numerator: 70,
denominator: null
},
postRaceReport: "four wide first turn, three wide far turn, no factor",
accBeatenDistance: "3¼"
},
{
runnerId: "12",
runnerName: "California Chrome",
trainer: "Sherman Art",
jockey: "Espinoza Victor",
scratched: false,
finishPosition: 9,
odds: {
numerator: 6,
denominator: 5
},
postRaceReport:
"five wide to first turn, asked 4 wide near far turn, no response",
accBeatenDistance: "3"
},
{
runnerId: "2",
runnerName: "Prayer For Relief",
trainer: "Romans Dale L",
jockey: "Geroux Florent",
scratched: false,
finishPosition: 10,
odds: {
numerator: 99,
denominator: null
},
postRaceReport: "rail first turn, two wide far turn, never prominent",
accBeatenDistance: "4¼"
},
{
runnerId: "6",
runnerName: "War Envoy",
trainer: "Ruis Mick",
jockey: "Saez Luis",
scratched: false,
finishPosition: 11,
odds: {
numerator: 99,
denominator: null
},
postRaceReport: "bobbled start, rail turns, finished early",
accBeatenDistance: "10"
},
{
runnerId: "11",
runnerName: "Eragon (Arg)",
trainer: "Wohlers Laura",
jockey: "Prado Edgar S",
scratched: false,
finishPosition: 12,
odds: {
numerator: 80,
denominator: null
},
postRaceReport: "trailed throughout, eased in stretch",
accBeatenDistance: "18"
}
];
export const pastRaceBasicResults = [
{
runnerId: "1",
runnerName: "Arrogate",
trainer: "Baffert Bob",
jockey: "Smith Mike E",
scratched: false,
finishPosition: 1
},
{
runnerId: "7",
runnerName: "Shaman Ghost",
trainer: "Jerkens James A",
jockey: "Ortiz Jose L",
scratched: false,
finishPosition: 2
},
{
runnerId: "3",
runnerName: "Neolithic",
trainer: "Pletcher Todd A",
jockey: "Velazquez John R",
scratched: false,
finishPosition: 3
},
{
runnerId: "9",
runnerName: "Keen Ice",
trainer: "Pletcher Todd A",
jockey: "Castellano Javier",
scratched: false,
finishPosition: 4
}
];
export const ipprunners = [
{
biNumber: 1,
currentOdds: { numerator: 5, denominator: 2 },
morningLineOdds: { numerator: 7, denominator: 2 },
isFavorite: true,
runners: [
{
horseName: "Bonnin Margaret",
runnerId: "1",
scratched: false,
hasJockeyChanges: false,
timeform: {
analystsComments: "Craze horse runne fast, bet now",
silkUrlSvg: "silk.svg"
},
handicapping: [
{ key: "jockey", value: "David Allan" },
{ key: "trainer", value: "Tim Easterby" }
],
masterPickNumber: 3,
dob: 2017
},
{
horseName: "Horsey Horsing",
runnerId: "1A",
scratched: true,
hasJockeyChanges: false,
handicapping: [
{ key: "jockey", value: "David Allan" },
{ key: "trainer", value: "Tim Easterby" }
],
masterPickNumber: 3,
dob: 2017
}
]
},
{
biNumber: 2,
currentOdds: { numerator: 33, denominator: null },
morningLineOdds: { numerator: 33, denominator: null },
isFavorite: false,
runners: [
{
horseName: "Ravenscar (Ire)",
runnerId: "2",
scratched: true,
hasJockeyChanges: false,
handicapping: [
{ key: "jockey", value: "Ben Curtis" },
{ key: "trainer", value: "Philip Kirby" }
],
dob: 2016
}
]
},
{
biNumber: 3,
currentOdds: { numerator: 7, denominator: 2 },
morningLineOdds: { numerator: 5, denominator: null },
isFavorite: false,
runners: [
{
horseName: "Golden Hind",
runnerId: "3",
scratched: false,
hasJockeyChanges: false,
handicapping: [
{ key: "jockey", value: "Daniel Tudhope" },
{ key: "trainer", value: "David O'meara" }
],
dob: 2017
}
]
},
{
biNumber: 4,
currentOdds: { numerator: 7, denominator: 2 },
morningLineOdds: { numerator: 10, denominator: null },
isFavorite: false,
runners: [
{
horseName: "Rainbow Jet (Ire)",
runnerId: "4",
scratched: false,
hasJockeyChanges: false,
handicapping: [
{ key: "jockey", value: "Graham Lee" },
{ key: "trainer", value: "John Mackie" }
],
dob: 2017
}
]
},
{
biNumber: 5,
currentOdds: { numerator: 7, denominator: 2 },
morningLineOdds: { numerator: 9, denominator: 2 },
isFavorite: false,
runners: [
{
horseName: "Bellatrixsa (Ire)",
runnerId: "5",
scratched: false,
hasJockeyChanges: false,
handicapping: [
{ key: "jockey", value: "Connor Beasley" },
{ key: "trainer", value: "Michael Dods" }
],
masterPickNumber: 1,
dob: 2017
}
]
}
];
export const ippRunnersSorted = [
{
biNumber: 1,
currentOdds: { numerator: 5, denominator: 2 },
morningLineOdds: { numerator: 7, denominator: 2 },
isFavorite: true,
runners: [
{
horseName: "Bonnin Margaret",
runnerId: "1",
scratched: false,
hasJockeyChanges: false,
timeform: {
analystsComments: "Craze horse runne fast, bet now",
silkUrlSvg: "silk.svg"
},
handicapping: [
{ key: "jockey", value: "David Allan" },
{ key: "trainer", value: "Tim Easterby" }
],
masterPickNumber: 3,
dob: 2017
}
]
},
{
biNumber: 3,
currentOdds: { numerator: 7, denominator: 2 },
morningLineOdds: { numerator: 5, denominator: null },
isFavorite: false,
runners: [
{
horseName: "Golden Hind",
runnerId: "3",
scratched: false,
hasJockeyChanges: false,
handicapping: [
{ key: "jockey", value: "Daniel Tudhope" },
{ key: "trainer", value: "David O'meara" }
],
dob: 2017
}
]
},
{
biNumber: 4,
currentOdds: { numerator: 7, denominator: 2 },
morningLineOdds: { numerator: 10, denominator: null },
isFavorite: false,
runners: [
{
horseName: "Rainbow Jet (Ire)",
runnerId: "4",
scratched: false,
hasJockeyChanges: false,
handicapping: [
{ key: "jockey", value: "Graham Lee" },
{ key: "trainer", value: "John Mackie" }
],
dob: 2017
}
]
},
{
biNumber: 5,
currentOdds: { numerator: 7, denominator: 2 },
morningLineOdds: { numerator: 9, denominator: 2 },
isFavorite: false,
runners: [
{
horseName: "Bellatrixsa (Ire)",
runnerId: "5",
scratched: false,
hasJockeyChanges: false,
handicapping: [
{ key: "jockey", value: "Connor Beasley" },
{ key: "trainer", value: "Michael Dods" }
],
masterPickNumber: 1,
dob: 2017
}
]
},
{
biNumber: 1,
currentOdds: { numerator: 5, denominator: 2 },
morningLineOdds: { numerator: 7, denominator: 2 },
isFavorite: true,
runners: [
{
horseName: "Horsey Horsing",
runnerId: "1A",
scratched: true,
hasJockeyChanges: false,
handicapping: [
{ key: "jockey", value: "David Allan" },
{ key: "trainer", value: "Tim Easterby" }
],
masterPickNumber: 3,
dob: 2017
}
]
},
{
biNumber: 2,
currentOdds: { numerator: 33, denominator: null },
morningLineOdds: { numerator: 33, denominator: null },
isFavorite: false,
runners: [
{
horseName: "Ravenscar (Ire)",
runnerId: "2",
scratched: true,
hasJockeyChanges: false,
handicapping: [
{ key: "jockey", value: "Ben Curtis" },
{ key: "trainer", value: "Philip Kirby" }
],
dob: 2016
}
]
}
];
export const activeHorse = {
biNumber: 1,
currentOdds: { numerator: 5, denominator: 2 },
morningLineOdds: { numerator: 7, denominator: 2 },
isFavorite: true,
runners: [
{
horseName: "Horsey Horsing",
runnerId: "1A",
scratched: true,
hasJockeyChanges: false,
handicapping: [
{ key: "jockey", value: "David Allan" },
{ key: "trainer", value: "Tim Easterby" }
],
masterPickNumber: 3,
dob: 2017
}
]
};
export const emptyMessagesDefault = {
emptyMessageTitle: "",
emptyMessageNone: "",
emptyMessageWithFilterMultiple: "",
emptyMessageWithFilterSingle: ""
};
export const mtpNotificationConfigDefault = {
mtpBelowThresholdText: "",
raceOffText: "",
mtpThreshold: 3,
showNotificationDelay: 5,
hideNotificationDelay: 20
};
export const handicappingRunnerFlagsDefault = {
title: "",
subtitle: "",
subtitleRunnerFlags: "",
flags: []
};
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MTPNotification/styled-compontents.js
import styled, { css } from "styled-components";
import buildColor from "../../_static/ColorPalette";
import { fontMedium } from "../../_static/Typography";
export const MTPNotificationContainer = styled.div`
display: flex;
color: ${buildColor("white", "100")};
background-color: ${buildColor("orange", "500")};
transition: transform 1s ease-in
${({ showNotificationDelay }) =>
showNotificationDelay ? `${showNotificationDelay}s` : "0s"};
transform: translate(-50%, 150%);
position: absolute;
bottom: 16px;
left: 50%;
align-items: center;
padding: 14px 16px;
box-shadow:
0 2px 4px rgba(17, 43, 68, 0.06),
0 1px 2px rgba(17, 43, 68, 0.08);
border-radius: 2px;
&.slide-up {
transform: translate(-50%, 0%);
}
&.slide-down {
transition-delay: ${({ hideNotificationDelay }) =>
hideNotificationDelay ? `${hideNotificationDelay}s` : "0s"};
}
${({ isRaceOff }) =>
isRaceOff &&
css`
background-color: ${buildColor("blue", "500")};
`}
`;
export const MTPNotificationDetailText = styled.span`
margin-right: 5px;
white-space: nowrap;
font-family: ${fontMedium};
font-size: 14px;
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MTPNotification/index.jsx
import React, { useState, useEffect, memo } from "react";
import { noop } from "lodash";
import { replaceCAPIVariables } from "@tvg/utils/capiUtils";
import { mtpNotificationConfigDefault } from "../../__mocks__/ipp-pastRaces.mock";
import { arrowForward } from "../../_static/Icons/icons";
import buildColor from "../../_static/ColorPalette";
import Icon from "../../_static/Icons";
import {
MTPNotificationContainer,
MTPNotificationDetailText
} from "./styled-compontents";
const idleIncrementUntilAnimationFinish = 2;
const statusAllowed = ["IC"];
const MTPNotification = (props) => {
const {
currentRace: { mtp = 0, track: { trackCode } = {}, raceNumber, status },
onModalClose,
mtpNotificationConfig: {
mtpBelowThresholdText,
raceOffText,
mtpThreshold,
showNotificationDelay,
hideNotificationDelay
}
} = props;
const clickHandler = () => onModalClose();
const [showNotification, setShowNotification] = useState(false);
const [animation, setAnimation] = useState("");
const [isRaceOff, setIsRaceOff] = useState(false);
useEffect(() => {
if (status && status.code === "SK") {
setIsRaceOff(true);
}
let timerShowId;
if (
!showNotification &&
((status && statusAllowed.includes(status.code) && mtp <= mtpThreshold) ||
isRaceOff)
) {
setShowNotification(true);
timerShowId = setTimeout(() => setAnimation("slide-up"), 0);
}
let timerHideId;
if (isRaceOff) {
timerHideId = setTimeout(
() => {
clearTimeout(timerShowId);
setAnimation("slide-down");
setTimeout(
() => setShowNotification(false),
(hideNotificationDelay + idleIncrementUntilAnimationFinish) * 1000
);
},
(showNotificationDelay + idleIncrementUntilAnimationFinish) * 1000
);
}
return () => {
clearTimeout(timerShowId);
clearTimeout(timerHideId);
};
}, [mtp, status, isRaceOff]);
return (
showNotification && (
<MTPNotificationContainer
onClick={clickHandler}
className={animation}
showNotificationDelay={showNotificationDelay}
hideNotificationDelay={hideNotificationDelay}
isRaceOff={isRaceOff}
>
<MTPNotificationDetailText data-qa-label="notificiation-mtpText">
{isRaceOff
? replaceCAPIVariables(raceOffText, {
mtp,
trackCode,
raceNumber: raceNumber || ""
})
: replaceCAPIVariables(mtpBelowThresholdText, {
mtp,
trackCode,
raceNumber: raceNumber || ""
})}
</MTPNotificationDetailText>
<Icon
icon={arrowForward}
color={buildColor("white", "100")}
size={16}
/>
</MTPNotificationContainer>
)
);
};
MTPNotification.defaultProps = {
currentRace: {},
onModalClose: noop,
mtpNotificationConfig: mtpNotificationConfigDefault
};
export default memo(MTPNotification);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Tabs/styled-components.ts
import styled, { css } from "styled-components";
import { margin } from "styled-system";
export const StyledContainer = styled.div<{ isFullHeight: boolean }>`
position: relative;
${({ isFullHeight }) =>
isFullHeight &&
css`
flex-grow: 1;
`};
${margin}
`;
export const ContentContainer = styled.div<{ isFullHeight: boolean }>`
${({ isFullHeight }) =>
isFullHeight &&
css`
flex-grow: 1;
`};
`;
export const TabHeaderContainer = styled.div<{
headerPadding?: string;
headerWidth?: string;
}>`
border-bottom: 1px solid var(--fd-colors-border-subtle);
width: ${({ headerWidth }) => headerWidth || `100%`};
background-color: var(--fd-colors-background-surface);
z-index: 1;
${({ headerPadding }) =>
headerPadding &&
css`
padding: ${headerPadding};
`}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Tabs/Tabs.tsx
import React, { createContext, useMemo, useState } from "react";
import type { TabsContextProps, TabsLayout, TabsProps } from "./types";
import {
ContentContainer,
StyledContainer,
TabHeaderContainer
} from "./styled-components";
const initialState: TabsContextProps = {
selectedValue: "",
onChange: () => {},
isStretched: false,
tabsLayout: {},
setTabsLayout: () => {},
isFullHeight: false
};
export const TabsContext = createContext<TabsContextProps>(initialState);
TabsContext.displayName = "TabsContext";
export const Tabs = ({
qaLabel,
children,
selectedValue,
onChange,
isFullHeight = false,
headerPadding,
headerWidth,
...rest
}: TabsProps) => {
const content = useMemo(() => {
const childrenElements = React.Children.toArray(children);
return childrenElements.filter((val) => {
if (React.isValidElement<{ value: string }>(val)) {
return val.props.value === selectedValue;
}
return val;
});
}, [selectedValue, children]);
const [tabsLayout, setTabsLayout] = useState<TabsLayout>({});
let tabList;
if (children[0]?.props.qaLabel === "tabList") {
tabList = children[0];
} else {
throw new Error(
"TabList child element is required to be used at first place"
);
}
return (
<StyledContainer
isFullHeight={isFullHeight}
{...rest}
data-qa-label={qaLabel}
>
<TabsContext.Provider
value={{
selectedValue,
onChange,
tabsLayout,
setTabsLayout,
isFullHeight
}}
>
<TabHeaderContainer
headerPadding={headerPadding}
headerWidth={headerWidth}
>
{tabList}
</TabHeaderContainer>
<ContentContainer isFullHeight={isFullHeight}>
{content}
</ContentContainer>
</TabsContext.Provider>
</StyledContainer>
);
};
export type { TabsContextProps, TabsLayout, TabsProps };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Tabs/components/TabSelectionIndicator/styled-components.ts
import styled from "styled-components"; export const SelectionIndicatorDiv = styled.div` background-color: var(--fd-colors-border-active) !important; height: 2px; position: absolute; top: 46px; transition: left 0.15s ease-in-out; `;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Tabs/components/TabSelectionIndicator/index.tsx
import React from "react";
import { SelectionIndicatorDiv } from "./styled-components";
export const TabSelectionIndicator = () => (
<SelectionIndicatorDiv className="glider" />
);
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Tabs/components/TabList/styled-components.ts
import styled, { css } from "styled-components";
import type { TabsLayout } from "../../types";
export const StyledContainer = styled.div<{
tabsLayout: TabsLayout;
}>`
display: flex;
flex-direction: row;
height: 48px;
border: none;
position: relative;
${({ tabsLayout }) =>
tabsLayout &&
Object.entries(tabsLayout).map(
([key, value]) => css`
#${key}.selected ~ .glider {
width: ${value.width}px;
left: ${value.x}px;
}
`
)}
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Tabs/components/TabList/index.tsx
import React, { useContext, Children, cloneElement } from "react";
import { TabsContext } from "../../Tabs";
import { TabSelectionIndicator } from "../TabSelectionIndicator";
import type { TabListProps } from "./types";
import { StyledContainer } from "./styled-components";
export const TabList = ({ children, isStretched }: TabListProps) => {
const { tabsLayout } = useContext(TabsContext);
return isStretched ? (
<div>
<StyledContainer tabsLayout={tabsLayout} data-qa-label="tablist-wrapper">
{Children.map(children, (child) =>
cloneElement(child, { isStretched })
)}
<TabSelectionIndicator />
</StyledContainer>
</div>
) : (
<>
<StyledContainer tabsLayout={tabsLayout} data-qa-label="tablist-wrapper">
{Children.map(children, (child) =>
cloneElement(child, { isStretched })
)}
<TabSelectionIndicator />
</StyledContainer>
</>
);
};
export type { TabListProps };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Tabs/components/Tab/styled-components.ts
import styled, { css } from "styled-components";
import type { StrechedProps, StyledProps, DisabledProps } from "./types";
export const StyledButton = styled.div<
StyledProps & StrechedProps & DisabledProps
>`
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
white-space: nowrap;
height: 48px;
background-color: var(--fd-colors-background-surface);
border-bottom: ${({ noBorder }) => (noBorder ? "0" : "1px")}
--fd-border-styles-border-style-solid-style var(--fd-colors-border-default) !important;
padding: 0 var(--fd-space-space-2);
${({ isStretched }) =>
isStretched &&
css`
flex-grow: 1;
`}
&:hover {
background-color: var(--fd-colors-background-hover);
cursor: ${({ isDisabled }) => (isDisabled ? "default" : "pointer")};
}
${({ isSelected }) =>
isSelected &&
css`
&:hover {
p: {
color: var(--fd-colors-link-default-hover);
}
}
`}
&:active {
background-color: var(--fd-colors-border-active);
p {
color: var(--fd-colors-content-on-dark);
}
}
`;
export const StyledTitle = styled.p<StyledProps & DisabledProps>`
color: var(--fd-colors-content-default);
font-family: Roboto-Medium, sans-serif;
font-size: 14px;
font-style: normal;
line-height: 125%;
${({ isSelected }) =>
isSelected &&
css`
color: var(--fd-colors-link-default-hover);
`}
&:active {
color: var(--fd-colors-content-on-dark);
}
${({ isDisabled }) =>
isDisabled &&
css`
color: var(--fd-colors-content-disabled);
`}
`;
export const StyledViewIconContainer = styled.div`
margin-left: ${({ theme }) => theme.space["space-1"]};
`;
export const StyledDescription = styled.p<StyledProps & DisabledProps>`
color: var(--fd-colors-content-subtle);
margin-top: var(--fd-space-space-05);
font-family: Roboto-Regular, sans-serif;
font-size: 12px;
font-style: normal;
line-height: 125%;
${({ isSelected }) =>
isSelected &&
css`
color: var(--fd-colors-link-default-hover);
`}
&:active {
color: var(--fd-colors-content-on-dark);
}
${({ isDisabled }) =>
isDisabled &&
css`
color: var(--fd-colors-content-disabled);
`}
`;
export const StyledViewTitleContainer = styled.div`
display: flex;
flex-direction: row;
margin-bottom: 2px;
background-color: transparent !important;
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Tabs/components/Tab/index.tsx
import React, { useContext, useEffect, useRef } from "react";
import { TabsContext } from "../../Tabs";
import {
StyledViewIconContainer,
StyledViewTitleContainer,
StyledTitle,
StyledDescription,
StyledButton
} from "./styled-components";
import type { TabProps } from "./types";
export const Tab = ({
value,
title,
description,
counter,
isSelected = false,
isDisabled = false,
noBorder = false,
isStretched,
qaLabel = value
}: TabProps) => {
const { onChange, selectedValue, setTabsLayout } = useContext(TabsContext);
const ref = useRef<HTMLDivElement>(null);
const isCurrentTabSelected = isSelected || selectedValue === value;
useEffect(() => {
const resizeObserver = new ResizeObserver(() => {
if (ref.current && ref.current.offsetWidth) {
const newState = {
[value]: {
width: ref.current.offsetWidth,
x: ref.current.offsetLeft
}
};
setTabsLayout((state: {}) => ({ ...state, ...newState }));
}
});
if (ref.current) {
resizeObserver.observe(ref.current);
}
return () => resizeObserver.disconnect();
}, [ref, isCurrentTabSelected]);
return (
<StyledButton
onClick={() => onChange(value)}
isStretched={isStretched}
isDisabled={isDisabled}
noBorder={noBorder}
isSelected={isCurrentTabSelected}
className={isCurrentTabSelected ? "selected" : ""}
data-qa-label={qaLabel}
id={value}
ref={ref}
>
<>
<StyledViewTitleContainer>
<StyledTitle
isDisabled={isDisabled}
isSelected={isCurrentTabSelected}
data-qa-label={`tab-title-${title}`}
>
{title}
</StyledTitle>
{!isDisabled && counter && (
<StyledViewIconContainer>{counter}</StyledViewIconContainer>
)}
</StyledViewTitleContainer>
{description && (
<StyledDescription
isDisabled={isDisabled}
isSelected={isCurrentTabSelected}
data-qa-label={`tab-description-${description}`}
>
{description}
</StyledDescription>
)}
</>
</StyledButton>
);
};
export type { TabProps };
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Tabs/components/TabPanel/styled-components.ts
import styled, { css } from "styled-components";
import { padding } from "styled-system";
export const StyledContainer = styled.div<{ isFullHeight?: boolean }>`
${({ isFullHeight }) =>
isFullHeight &&
css`
flex-grow: 1;
`};
${padding};
`;
webpack://frontend-mybets/../../packages/tvg-lib-design-system/web/components/Tabs/components/TabPanel/index.tsx
import React from "react";
import type { TabPanelProps } from "./types";
import { StyledContainer } from "./styled-components";
export const TabPanel = ({
children,
qaLabel = "tabPanel",
isFullHeight,
...rest
}: TabPanelProps) => (
<StyledContainer
isFullHeight={isFullHeight}
data-qa-label={qaLabel}
{...rest}
>
{children}
</StyledContainer>
);
export type { TabPanelProps };
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/InlineInfo/styled-components.js
import styled, { css } from "styled-components";
import buildColor from "../../_static/ColorPalette";
import { buildText } from "../Text";
import { fontMedium, fontNormal } from "../../_static/Typography";
export const InfoContainer = styled.span`
display: flex;
flex-wrap: wrap;
text-align: left;
word-wrap: break-word;
align-items: center;
font-family: ${({ isFirstFontMedium }) =>
isFirstFontMedium ? fontMedium : fontNormal};
span {
font-family: ${fontNormal};
}
span:first-child {
font-family: ${({ isFirstFontMedium }) =>
isFirstFontMedium ? fontMedium : fontNormal};
}
`;
export const InlineInfoWrapper = styled.div`
${(props) =>
props.showInfoInline &&
css`
display: inline-flex;
`}
`;
export const IconWrapper = styled.span`
display: inline-flex;
align-items: center;
line-height: 1.3;
& > svg {
margin-right: 2px;
}
`;
export const Description = styled(
buildText({
tag: "span",
fontSize: 14,
color: buildColor("grey", "900"),
capitalize: true
})
)`
${({ showInfoInline }) =>
showInfoInline
? css`
margin-right: 5px;
`
: css`
display: block;
`};
font-weight: ${({ isDescriptionBold }) =>
isDescriptionBold ? "bold" : "normal"};
text-align: left;
padding-bottom: ${({ showInfoInline }) => (showInfoInline ? "0" : "2px")};
font-family: ${fontMedium};
`;
export const OptionItem = styled(
buildText({
tag: "span",
color: buildColor("grey", "800")
})
)`
${({ showInfoInline }) =>
showInfoInline
? css`
font-size: 14px;
color: ${buildColor("grey", "700")};
`
: css`
font-size: 12px;
`};
position: relative;
&:not(:last-child) {
margin-right: 4px;
padding-right: 5px;
&::after {
position: absolute;
right: 0;
top: 1px;
bottom: 1px;
content: "";
border-right: 1px solid ${buildColor("grey", "300")};
}
}
`;
export const SortActive = styled.strong`
position: relative;
display: inline-flex;
align-items: flex-end;
background-color: ${buildColor("grey", "200")};
color: ${buildColor("grey", "900")};
padding: 1px 2px;
border-radius: 1px;
${({ hasArrow }) =>
hasArrow &&
css`
padding: 1px 13px 1px 2px;
`}
& > svg {
transform: translate(1px, 0);
position: absolute;
top: calc(50% - 6px);
right: 2px;
}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/InlineInfo/index.jsx
import React, { PureComponent } from "react";
import { endsWith, get } from "lodash";
import {
Description,
OptionItem,
InfoContainer,
IconWrapper,
InlineInfoWrapper,
SortActive
} from "./styled-components";
import Icon from "../../_static/Icons";
import { changes, arrowUpward, arrowDownward } from "../../_static/Icons/icons";
import buildColor from "../../_static/ColorPalette";
export default class InlineInfo extends PureComponent {
static defaultProps = {
title: "",
info: [],
isDescriptionBold: true,
isFirstBold: false,
hasJockeyChanges: false,
showInfoInline: false,
handicappingSort: true,
showHandicappingSortMode: false,
handicappingSortMode: "saddlecloth",
isFirstFontMedium: true
};
render() {
const noArrowExceptions = ["med"];
return (
<InlineInfoWrapper showInfoInline={this.props.showInfoInline}>
{!!this.props.title && (
<Description
showInfoInline={this.props.showInfoInline}
data-qa-label="handicapDescription"
>
{this.props.title}
</Description>
)}
<InfoContainer>
{this.props.info.map((handicapping, index) => {
let icon = null;
if (
handicapping.sorting &&
typeof handicapping !== "string" &&
!noArrowExceptions.includes(
get(handicapping, "key", "saddlecloth")
)
) {
switch (handicapping.sorting) {
case "asc":
icon = arrowUpward;
break;
case "desc":
icon = arrowDownward;
break;
default:
icon = null;
}
}
return (
<OptionItem
key={`inlineinfo-item-${index.toString()}`}
isFirstBold={this.props.isFirstBold}
showInfoInline={this.props.showInfoInline}
data-qa-label="handicapItem"
isFirstFontMedium={this.props.isFirstFontMedium}
>
{typeof handicapping === "object" ? (
<IconWrapper>
{this.props.hasJockeyChanges &&
(handicapping.key === "jockey" ||
handicapping.key ===
"handicapping.jockeyTrainer.jockeyName") && (
<Icon
icon={changes}
color={buildColor("yellow", "500")}
/>
)}
{this.props.handicappingSort &&
this.props.showHandicappingSortMode &&
(handicapping.key === this.props.handicappingSortMode ||
endsWith(
handicapping.key,
this.props.handicappingSortMode
)) ? (
<SortActive hasArrow={!!icon}>
{handicapping.value}
{icon && (
<Icon
icon={icon}
size={11}
color={buildColor("grey", "900")}
/>
)}
</SortActive>
) : (
handicapping.value
)}
</IconWrapper>
) : (
handicapping
)}
</OptionItem>
);
})}
</InfoContainer>
</InlineInfoWrapper>
);
}
}
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/components/RunnerListHeader/styled-components.ts
import styled, { css } from "styled-components";
import { themeGet } from "@tvg/design-system/src/theming";
interface Props {
iconBefore?: boolean;
qaLabel: string;
}
export const RLHeader = styled.tr<{
isLeg: boolean;
}>`
width: 100%;
border-style: solid;
border-width: ${(props) => (props.isLeg ? "0 1px 1px 1px" : "0 0 1px 0")};
border-color: ${({ theme }) => theme.colorTokens.component.input.base};
border-bottom: 0;
height: 40px;
background-color: ${({ theme }) =>
theme.colorTokens.component.button.primary.background.disabled};
`;
export const RLHandicap = styled.tr<{
isLeg: boolean;
}>`
height: 24px;
background-color: ${({ theme }) =>
theme.colorTokens.component.button.primary.background.disabled};
border-style: solid;
border-color: ${({ theme }) =>
theme.colorTokens.component.notification.input};
border-width: ${(props) => (props.isLeg ? "0 1px 0 1px" : "0")};
border-top: 0;
`;
export const HandicapWrapper = styled.td`
padding: 0 8px;
text-align: left;
position: relative;
`;
export const InlineContainer = styled.span`
display: flex;
padding: 4px 0;
border-top: 1px solid ${({ theme }) => theme.colorTokens.border.default};
`;
export const RunnerInfoWrapper = styled.th`
max-width: 0;
padding: 0 0 0 4px;
text-align: left;
`;
export const BetAllWrapper = styled.th<{
isLeg: boolean;
numColumns: number;
}>`
width: ${(props) => (props.isLeg ? "30px" : "70px")};
padding: ${(props) => (props.numColumns < 3 ? "0" : "0 4px 0 0")};
& > div {
display: flex;
justify-content: flex-end;
}
`;
export const BetAllButton = styled.button.attrs<{
qaLabel?: string;
}>((props) => ({
"data-qa-label": props.qaLabel
}))<Props>`
outline: none;
opacity: 1;
width: 48px;
height: 40px;
background: none;
font-family: ${themeGet("fonts.medium")};
font-size: 14px;
cursor: pointer;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
span {
height: auto;
margin: 0;
}
`;
export const CloseButton = styled.button`
outline: none;
opacity: 1;
width: 48px;
height: 40px;
background: none;
cursor: pointer;
display: flex;
flex-direction: row-reverse;
justify-content: center;
& > svg {
float: right;
}
`;
export const HandicappTypeWrapper = styled.button.attrs<{
iconBefore?: boolean;
qaLabel?: string;
}>((props) => ({
"data-qa-label": props.qaLabel
}))<Props>`
position: relative;
display: inline-flex;
align-items: center;
justify-content: space-between;
background: none;
padding: 4px;
margin: 0;
font-size: 14px;
${({ iconBefore }) =>
iconBefore &&
css`
padding: 4px 4px 4px 19px;
`}
&:active {
background-color: ${({ theme }) =>
theme.colorTokens.component.button.tertiary.border.base};
}
& > svg {
position: absolute;
top: calc(50% - 6px);
left: 4px;
}
`;
export const SeparatorLine = styled.div`
border-left: 1px solid ${({ theme }) => theme.colorTokens.background.neutral};
width: 0;
height: 16px;
display: inline-block;
margin: 0 4px;
`;
export const Text = styled.span<{
verticalSpacer?: boolean;
}>`
font-size: 14px;
text-transform: uppercase;
color: ${({ theme }) => theme.colorTokens.content.link};
${({ verticalSpacer }) =>
verticalSpacer &&
css`
margin-bottom: 4px;
`}
height: 11px;
font-family: ${themeGet("fonts.medium")};
`;
export const TitleBoldEllipsis = styled.strong.attrs({
"data-qa-label": "handicapTitle"
})`
color: ${({ theme }) =>
theme.colorTokens.component.button.promo.content.base};
font-weight: bold;
padding-right: 9px;
font-family: ${themeGet("fonts.condensedRegular")};
font-size: 10px;
display: block;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
`;
export const FixedHandicapContainer = styled.div<{
isLeg: boolean;
isHandicapFixed: boolean;
fixedOffset: number;
}>`
min-height: 24px;
display: flex;
align-items: center;
padding: 4px 8px;
background-color: ${({ theme }) =>
theme.colorTokens.component.button.primary.background.disabled};
position: fixed;
${(props) =>
props.isLeg
? css`
left: 17px;
right: 17px;
`
: css`
left: 0;
right: 0;
margin: 0 4px;
border-left: 1px solid
${({ theme }) => theme.colorTokens.component.input.base};
border-right: 1px solid
${({ theme }) => theme.colorTokens.component.notification.input};
`};
top: ${(props) => props.isHandicapFixed && `${props.fixedOffset}px`};
box-shadow:
0 -1px 0 0 ${({ theme }) => theme.colorTokens.component.notification.input},
inset 0 -1px 0 0 ${({ theme }) => theme.colorTokens.component.notification.input};
`;
export const OptionTitle = styled.span`
font-size: 14px;
color: ${({ theme }) => theme.colorTokens.groupedfiltercell.content.default};
text-transform: capitalize;
padding: 0;
font-family: ${themeGet("fonts.medium")};
`;
export const BetAllOption = styled.span`
font-size: 14px;
text-transform: uppercase;
color: ${({ theme }) =>
theme.colorTokens.component.button.promo.content.base};
position: relative;
display: flex;
align-items: center;
justify-content: center;
padding-right: 14px;
font-family: ${themeGet("fonts.medium")};
&:active {
background-color: ${({ theme }) =>
theme.colorTokens.component.button.tertiary.border.base};
}
& > svg {
position: absolute;
top: calc(50% - 6px);
right: 0;
}
`;
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/components/RunnerListHeader/index.tsx
import React, { PureComponent, Fragment } from "react";
import { noop, times, isFunction } from "lodash";
import { createPortal } from "react-dom";
import type {
RaceTypeCodeEnum,
HandicapOptions,
HandicapSortOptionsType
} from "@tvg/types/Race";
import formatSequencial from "@tvg/formatter/numeric";
import DSIcon from "@tvg/design-system/src/components/icon";
import Icon from "@tvg/atomic-ui/_static/Icons";
import InlineInfo from "@tvg/atomic-ui/_atom/InlineInfo";
import { HandicapSelectiontype } from "./types";
import { SelectionType } from "../SelectionButton";
import {
RLHeader,
RunnerInfoWrapper,
BetAllWrapper,
BetAllButton,
Text,
TitleBoldEllipsis,
HandicappTypeWrapper,
SeparatorLine,
RLHandicap,
HandicapWrapper,
InlineContainer,
FixedHandicapContainer,
OptionTitle,
BetAllOption
} from "./styled-components";
const getSelectionText = (
selectionType: SelectionType,
column: number,
selected: boolean
) => {
const text = [];
switch (selectionType) {
case "key":
if (column === 0) {
text.push(
<DSIcon
key="key-icon"
name="key"
size="s"
lineColor="lhnHeader.selectedcell.background"
shouldUseColorTokens
/>
);
} else {
text.push(<Text key="line1">{!selected ? "W/" : "RESET"}</Text>);
text.push(<Text key="line2">ALL</Text>);
}
break;
case "number":
text.push(
<Text key="line1">
{!selected ? formatSequencial(column + 1) : "RESET"}
</Text>
);
text.push(<Text key="line2">ALL</Text>);
break;
case "default":
default:
text.push(
<Text verticalSpacer={!selected} key="line1">
{!selected ? "BET" : "RESET"}
</Text>
);
text.push(<Text key="line2">ALL</Text>);
break;
}
return text;
};
type HeaderRef = { current: null | HTMLTableSectionElement };
interface Props {
/**
* Leg number for the race
*/
leg: number;
/**
* Boolean to change the button state
*/
isWagerable: boolean;
/**
* Flag to activate the leg layout
*/
isLeg: boolean;
/**
* Flag to activate a key column
*/
isKey: boolean;
/**
* Number of selection columns
*/
numColumns: number;
/**
* Race type code
*/
raceTypeCode: typeof RaceTypeCodeEnum;
/**
* Boolean to change the button state.
*/
isAllSelected: Array<boolean>;
/**
* Function to select all runners
*/
onAllRunnersSelect: (a: number) => unknown;
/**
* Title for handicapping selector
*/
handicapTitle?: string;
/**
* Handicap format to be displayed in row
*/
handicapInfo: Array<string | typeof HandicapOptions>;
/**
* Should handicap section be fixed
*/
isHandicapFixed: boolean;
/**
* Position of fixing handicap section
*/
fixedHandicapOffset: number;
/**
* has handicapping dropdown
*/
hasHandicappingSelection: boolean;
/**
* List of Handicap options to show
*/
handicapOptions: HandicapSelectiontype[];
/**
* Header reference
*/
refHeader: HeaderRef;
toggleBetAll: () => unknown;
/**
* Handicapping Sort Mode
*/
handicappingSortMode: typeof HandicapSortOptionsType;
shouldRenderPromoOnboarding: boolean;
/**
* Function to render promo onboarding message
*/
renderPromoOnboarding: () => Element;
}
export default class RunnerListHeader extends PureComponent<Props> {
static defaultProps = {
leg: 0,
isWagerable: true,
raceTypeCode: "T",
numColumns: 1,
fixedHandicapOffset: 0,
isHandicapFixed: false,
isKey: false,
isLeg: false,
isAllSelected: [false],
handicapInfo: [],
onAllRunnersSelect: noop,
hasHandicappingSelection: false,
handicapOptions: [],
handicapTitle: "",
refHeader: { current: null },
toggleBetAll: noop,
handicappingSortMode: "saddlecloth",
shouldRenderPromoOnboarding: false,
renderPromoOnboarding: noop
};
el: Element | undefined;
buildHandicapFormat = () => {
/* istanbul ignore next */
if (typeof window !== "undefined") {
this.el = document.querySelector("#app > section > div") || document.body;
}
return (
!!this.props.handicapInfo.length &&
(this.props.isHandicapFixed && this.el ? (
createPortal(
<FixedHandicapContainer
isHandicapFixed
fixedOffset={this.props.fixedHandicapOffset}
isLeg={this.props.isLeg}
>
<InlineInfo
info={this.props.handicapInfo}
showHandicappingSortMode={this.props.raceTypeCode !== "G"}
handicappingSortMode={this.props.handicappingSortMode}
/>
</FixedHandicapContainer>,
this.el
)
) : (
<RLHandicap isLeg={this.props.isLeg}>
<HandicapWrapper colSpan={4}>
<InlineContainer>
<InlineInfo
info={this.props.handicapInfo}
showHandicappingSortMode={this.props.raceTypeCode !== "G"}
handicappingSortMode={this.props.handicappingSortMode}
/>
</InlineContainer>
</HandicapWrapper>
</RLHandicap>
))
);
};
renderSelectAll = () => {
const selectionType = (() => {
if (!this.props.isKey) {
return this.props.numColumns === 1 ? "default" : "number";
}
return "key";
})();
const buildQALabel = (column: number) => {
if (this.props.isKey) {
return column === 0
? "runnerListHeader-selectKeyButton"
: "runnerListHeader-selectWithButton";
}
return this.props.numColumns === 1
? "runnerListHeader-selectAllButton"
: `runnerListHeader-select-${column + 1}-button`;
};
return this.props.numColumns < 3 ? (
times(this.props.numColumns, (column) => (
<BetAllButton
key={`button-${column}`}
onClick={() =>
this.props.onAllRunnersSelect(
this.props.leg > 0 ? this.props.leg : column
)
}
qaLabel={buildQALabel(column)}
>
{getSelectionText(
selectionType,
column,
this.props.isAllSelected[column]
)}
</BetAllButton>
))
) : (
<HandicappTypeWrapper
onTouchStart={noop}
qaLabel="runnerListHeader-BetAllSelector"
onClick={this.props.toggleBetAll}
>
<BetAllOption>
BET ALL <DSIcon name="arrowBottom" size="xs" shouldUseColorTokens />
</BetAllOption>
</HandicappTypeWrapper>
);
};
renderSelectOptions = () =>
this.props.handicapOptions
.filter((option) => option.visible)
.map((option, index, options) => (
<Fragment key={`select-option-${index.toString()}`}>
<HandicappTypeWrapper
onTouchStart={noop}
qaLabel={option.qaLabel}
onClick={option.callback}
iconBefore
>
{!!option.icon && <Icon icon={option.icon} size={11} />}
<OptionTitle>{option.title.toLowerCase()}</OptionTitle>
</HandicappTypeWrapper>
{index < options.length - 1 && <SeparatorLine />}
</Fragment>
));
render() {
const promoOnboardingComponent = isFunction(
this.props.renderPromoOnboarding
)
? this.props.renderPromoOnboarding()
: null;
return (
<thead data-qa-label="runnerListHeader" ref={this.props.refHeader}>
<RLHeader isLeg={this.props.isLeg}>
<RunnerInfoWrapper colSpan={this.props.isWagerable ? 3 : 4}>
{this.props.hasHandicappingSelection ? (
this.renderSelectOptions()
) : (
<TitleBoldEllipsis>{this.props.handicapTitle}</TitleBoldEllipsis>
)}
</RunnerInfoWrapper>
{this.props.isWagerable && (
<BetAllWrapper
isLeg={this.props.isLeg}
numColumns={this.props.numColumns}
>
<div>{this.renderSelectAll()}</div>
</BetAllWrapper>
)}
</RLHeader>
{this.buildHandicapFormat()}
{this.props.shouldRenderPromoOnboarding &&
!!promoOnboardingComponent && (
<tr>
<td colSpan={4}>{promoOnboardingComponent}</td>
</tr>
)}
</thead>
);
}
}
webpack://frontend-mybets/../../packages/urp-lib-alchemer/types.ts
export enum AlchemerFeedbackWidget {
OPEN = "BETA-PROGRAM:OPEN_FEEDBACK_WIDGET",
SUBMIT = "BETA-PROGRAM:SUBMIT_FEEDBACK_WIDGET"
}
webpack://frontend-mybets/../../packages/urp-lib-alchemer/amplitude.ts
import mediator from "@tvg/mediator";
import { AlchemerFeedbackWidget } from "./types";
export const sendOpenFeedbackWidgetEvent = () =>
mediator.base.dispatch({
type: AlchemerFeedbackWidget.OPEN
});
export const sendSubmitFeedbackWidgetEvent = () =>
mediator.base.dispatch({
type: AlchemerFeedbackWidget.SUBMIT
});
webpack://frontend-mybets/../../packages/urp-lib-alchemer/utils.ts
import mediator from "@tvg/mediator";
import { isMobile } from "@tvg/sh-utils/mobileUtils";
import { UserInfo } from "@tvg/ts-types/User";
import {
sendOpenFeedbackWidgetEvent,
sendSubmitFeedbackWidgetEvent
} from "./amplitude";
export const createConversation = ({
accountNumber,
firstName,
lastName,
emailAddress,
profile,
homeAddress,
primaryPhone
}: UserInfo) => {
if (typeof window !== "undefined" && window.ApptentiveSDK) {
const payload = {
app_release: {
version: "1.0.0"
},
person: {
custom_data: {
account_id: accountNumber,
first_name: firstName,
last_name: lastName,
email: emailAddress,
day_of_birthday: "",
home_city: homeAddress ? homeAddress.state : "",
gender: "",
country: homeAddress ? homeAddress.country : "",
phone: primaryPhone,
full_home_address: "",
key_account_yn: false,
value_band: profile
}
},
device: {
custom_data: {
flash: true,
es6: false
}
}
};
window.ApptentiveSDK.createConversation(payload);
}
};
export const engageApptentiveEvent = (eventName: string) => {
if (isMobile()) {
mediator.ios.dispatch({
type: "ALCHEMER_EVENTS",
payload: { alchemerEvent: eventName }
});
} else if (typeof window !== "undefined" && window.ApptentiveSDK) {
window.ApptentiveSDK.engage(eventName);
}
};
export const dispatchSubmited = () => {
sendSubmitFeedbackWidgetEvent();
document.removeEventListener("apptentive:survey:submit", dispatchSubmited);
};
export const trackBetaFeatureFeedback = () => {
sendOpenFeedbackWidgetEvent();
document.addEventListener("apptentive:survey:submit", dispatchSubmited);
};
export const closeSurveyAfterSubmit = () => {
const closeButton = document.getElementsByClassName(
"apptentive-button--primary"
);
const closeSurvey = () => {
closeButton[0]?.removeEventListener("click", closeSurvey);
};
closeButton[0]?.addEventListener("click", closeSurvey);
};
export const hideMinimizeSurveyButton = () => {
const alchemerMinimizeBtn = document?.getElementsByClassName(
"apptentive-appbar__action--minimize"
);
if (document?.body && alchemerMinimizeBtn.length) {
// @ts-ignore
alchemerMinimizeBtn[0].style = "display:none";
}
};
webpack://frontend-mybets/../../packages/urp-lib-alchemer/events/accountWallet.ts
import { engageApptentiveEvent } from "../utils";
// when a user logs in to TVG
export const login = () => engageApptentiveEvent("Login");
// when user close the success deposit modal
export const closeDeposit = () => engageApptentiveEvent("Deposit");
// when user close the success withdrawal modal
export const closeWithdrawal = () => engageApptentiveEvent("Withdrawal");
// when user select Responsible Gaming
export const selectResponsibleGaming = () =>
engageApptentiveEvent("Responsible Gaming");
// when user select Wallet
export const selectWallet = () => engageApptentiveEvent("Wallet is tapped");
// when user navigate to Home
export const navigateHome = () => engageApptentiveEvent("Home tapped");
webpack://frontend-mybets/../../packages/urp-lib-alchemer/events/betActivities.ts
import { engageApptentiveEvent } from "../utils";
// when a user logs in to TVG
export const placeABet = () => engageApptentiveEvent("Places bet");
// when a user select handicap option
export const selectHandicapOptions = () =>
engageApptentiveEvent("Handicapping options tapped");
// when a user select the TVG Logo
export const selectTVGLogo = () => engageApptentiveEvent("TVG Logo tapped");
// when a user set a track as favorite
export const setTrackAsFavorite = () =>
engageApptentiveEvent("Race track is favorited");
// when a user selects/uses inline pps in raace page
export const selectInlinePastPerformance = () =>
engageApptentiveEvent("Inline past performance tapped");
// when a user selects 'More' in the race page to view pps
export const selectMoreButton = () =>
engageApptentiveEvent(`User taps "more" in race page to view PPs`);
// when a user selects a bet type tooltip in the race page
export const selectBetTypeTooltip = () =>
engageApptentiveEvent("Bet Type tooltip is tapped");
webpack://frontend-mybets/../../packages/urp-lib-alchemer/events/interactions.ts
import { engageApptentiveEvent, hideMinimizeSurveyButton } from "../utils";
// when a user wants to give feedback on the New Program Page beta feature
export const showNewProgramPageFeedbackSurvey = () =>
engageApptentiveEvent("Beta Program Page Feedback");
export const showExitNewFeedbackBetaProgramSurvey = () =>
engageApptentiveEvent("New Feature Exit Beta");
// when a user wants to give feedback for the whole app
// ("Send Feedback" buttons on the Account Panel)
export const showSendFeedbackSurvey = () => {
engageApptentiveEvent("Send Feedback");
hideMinimizeSurveyButton();
};
webpack://frontend-mybets/../../packages/urp-lib-alchemer/events/featureActivities.ts
import { engageApptentiveEvent } from "../utils";
// when a user receives referral bonus inbox/email
export const refferalBonusDeposited = () =>
engageApptentiveEvent("Refferal bonus is deposited to user account");
// when a user selects any video
export const selectEducationVideo = () =>
engageApptentiveEvent("Education videos is tapped");
// when a user selects 'Watch Live'
export const selectWatchLiveButton = () =>
engageApptentiveEvent("Watch Live is tapped");
webpack://frontend-mybets/../../packages/urp-lib-alchemer/events/raceActivities.ts
import { engageApptentiveEvent } from "../utils";
// when a user selects on Races Starting Soon
export const selectStartsSoonRace = () =>
engageApptentiveEvent("Races Starting Soon is tapped");
// when a user selects on Today's Popular Races
export const selectPopularRace = () =>
engageApptentiveEvent("Today's Popular Races is tapped");
webpack://frontend-mybets/../../packages/urp-lib-alchemer/events/navigationActivities.ts
import { engageApptentiveEvent } from "../utils";
// when a user selects back to return to the home screen
export const backTapped = () =>
engageApptentiveEvent("Back button/icon is tapped");
// when a user selects the FDR logo to go to home screen
export const fdrLogoTapped = () => engageApptentiveEvent("FDR Logo tapped");
// when a user selects home button
export const homeTapped = () => engageApptentiveEvent("Home tapped");
// when a users favorites a track
export const selectFavouriteTrack = () =>
engageApptentiveEvent("Race track is favorited");
// when a user selects Earn $20 (RAF)
export const earnBonusTapped = () =>
engageApptentiveEvent("Earn $20 (RAF) tapped");
// when a user selects "Tutorials" tab
export const selectTutorialsTab = () =>
engageApptentiveEvent(`"Tutorials" is tapped`);
// when a user select "Learn horse racing"
export const selectLearnHorseRacing = () =>
engageApptentiveEvent(`"Learn horse racing" is tapped`);
webpack://frontend-mybets/../../packages/urp-lib-alchemer/events/index.ts
import * as accountWallet from "./accountWallet";
import * as betActivities from "./betActivities";
import * as interactions from "./interactions";
import * as featureActivities from "./featureActivities";
import * as raceActivities from "./raceActivities";
import * as navigationActivities from "./navigationActivities";
export const events = {
...accountWallet,
...betActivities,
...interactions,
...featureActivities,
...raceActivities,
...navigationActivities
};
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/TrackMasterPickTag/styled-components.js
import styled, { css } from "styled-components";
import { fontCondensedNormal } from "../../_static/Typography";
import buildColor from "../../_static/ColorPalette";
const TagWrapper = styled.span`
display: flex;
flex-direction: row;
font-weight: 500;
align-items: center;
justify-content: flex-start;
font-size: 12px;
font-family: ${fontCondensedNormal};
${(props) =>
props.labelDarker
? css`
margin-bottom: 4px;
color: ${buildColor("grey", "800")};
`
: css`
margin-top: 4px;
margin-bottom: 4px;
color: ${buildColor("grey", "800")};
`}
${(props) =>
props.isScratched
? css`
opacity: 0.5;
`
: css`
opacity: 1;
`}
& svg {
margin-right: 4px;
fill: ${buildColor("grey", "800")};
}
`;
export default TagWrapper;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/TrackMasterPickTag/RacingAndSportsIcon.jsx
import React from "react";
const RacingAndSportsIcon = () => (
<svg
height="16"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 226.3 119.87"
data-qa-label="racingAndSportsIcon"
>
<path
fill="#b1b235"
d="M197.05,42.89c-.22-1.54-.66-2.64-1.54-3.74-.66-.88-1.54-1.76-2.64-2.2-1.98-1.1-4.4-1.54-7.26-1.54-3.08,0-5.5,.44-6.82,1.32s-2.2,1.98-2.2,3.74c0,1.54,.66,2.86,2.2,3.96s3.3,1.98,5.72,2.86c2.42,.88,5.06,1.54,7.92,2.2,2.86,.66,5.94,1.54,9.02,2.42s6.16,1.98,9.02,3.08c2.86,1.32,5.5,2.86,7.92,4.84,2.42,1.98,4.18,4.4,5.72,7.04,1.54,2.86,2.2,6.16,2.2,10.12,0,5.06-1.1,9.46-3.08,13.2-1.98,3.74-4.84,6.82-8.36,9.24-3.52,2.42-7.92,4.18-12.76,5.5-5.06,1.32-10.34,1.76-16.28,1.76s-10.78-.88-15.4-2.42c-4.62-1.54-8.58-3.74-11.88-6.38-3.3-2.64-5.94-5.72-7.7-9.24-1.98-3.52-2.86-7.26-3.08-11h27.05c.66,3.08,2.2,5.28,4.62,6.82,1.1,.66,2.42,1.32,3.74,1.54,1.54,.44,2.86,.44,4.18,.44,3.52,0,6.38-.44,8.58-1.54s3.08-2.64,3.08-4.84-1.32-3.74-3.74-5.06c-2.42-1.1-5.5-2.2-9.24-3.08-3.74-.88-7.7-1.98-12.1-3.08-4.4-1.1-8.36-2.64-12.1-4.62-3.74-1.98-6.82-4.62-9.24-8.14-2.42-3.3-3.74-7.7-3.74-13.42,0-4.62,.88-8.58,2.86-12.1s4.4-6.38,7.7-8.58c3.3-2.2,7.26-3.96,11.88-5.06s9.46-1.76,14.96-1.76c5.94,0,11.22,.66,15.62,2.2,4.4,1.54,8.14,3.3,11,5.94,3.08,2.42,5.28,5.28,7.04,8.8,1.76,3.3,2.86,6.82,3.3,10.56h-26.17v.22Z"
/>
<g>
<polygon
fill="#b1b235"
points="96.93 45.53 96.93 56.3 112.77 56.3 96.93 69.06 96.93 80.5 131.68 80.5 131.68 69.06 116.06 69.06 131.68 56.52 131.68 45.53 96.93 45.53"
/>
<path
fill="#b1b235"
d="M96.93,86v18.25s.88,15.62,17.38,15.62,17.38-15.62,17.38-15.62v-18.25h-34.75Zm24.85,16.06s-.66,6.82-7.48,6.82-7.48-6.82-7.48-6.82v-4.62h14.96v4.62h0Z"
/>
<path
fill="#b1b235"
d="M96.93,0V13.2l3.96,1.76v13.2l-3.96,1.98v12.32l34.75-14.52V15.62L96.93,0Zm12.76,24.41v-6.6l9.9,3.3-9.9,3.3Z"
/>
</g>
<path
fill="#004693"
d="M83.14,44.87c.44-18.69-18.91-24.19-27.71-24.19H13.64L0,106.23H23.53l5.28-31.23h7.48l13.2,31.23h26.17l-15.62-32.77s22.65-8.36,23.09-28.59Zm-28.37,10.34c-2.2,1.98-3.96,2.86-6.82,2.86H31.45l3.08-18.91h11.44c2.86,0,6.16-.66,8.8,1.1,2.42,1.54,3.52,4.62,3.52,7.26,0,3.3-1.32,5.94-3.52,7.7Z"
/>
</svg>
);
export default RacingAndSportsIcon;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/TrackMasterPickTag/index.jsx
import React, { PureComponent } from "react";
import {
TRACK_DATA_SOURCE_GSA,
TRACK_DATA_SOURCE_RAS,
TRACK_DATA_SOURCE_SRW
} from "@tvg/utils/trackMasterPicksUtils";
import buildColor from "../../_static/ColorPalette";
import Icon from "../../_static/Icons";
import {
trackMasterPick,
timeformPick,
srwPick,
numberFirePick
} from "../../_static/Icons/icons";
import TagWrapper from "./styled-components";
import RacingAndSportsIcon from "./RacingAndSportsIcon";
export default class TrackMasterPickTag extends PureComponent {
static defaultProps = {
pickNumber: -1,
labelDarker: false,
isScratched: false,
trackDataSource: "",
isNumberFirePick: false
};
getIcon = (trackDataSource, isNumberFirePick) => {
if (isNumberFirePick) return numberFirePick;
switch (trackDataSource) {
case TRACK_DATA_SOURCE_GSA:
return timeformPick;
case TRACK_DATA_SOURCE_SRW:
return srwPick;
default:
return trackMasterPick;
}
};
render() {
const {
pickNumber,
labelDarker,
isScratched,
trackDataSource,
isNumberFirePick
} = this.props;
let message = "";
const color = labelDarker
? buildColor("grey", "900")
: buildColor("grey", "800");
const svgIcon = this.getIcon(trackDataSource, isNumberFirePick);
switch (pickNumber) {
case 1:
message = "1ST PICK";
break;
case 2:
message = "2ND PICK";
break;
case 3:
message = "3RD PICK";
break;
default:
return "";
}
return (
<TagWrapper labelDarker={labelDarker} isScratched={isScratched}>
{trackDataSource === TRACK_DATA_SOURCE_RAS && <RacingAndSportsIcon />}
{trackDataSource !== TRACK_DATA_SOURCE_RAS && (
<Icon size={16} icon={svgIcon} color={color} />
)}
{message}
</TagWrapper>
);
}
}
webpack://frontend-mybets/../../packages/tvg-lib-utils/trackMasterPicksUtils.js
import { isNull, get, sortBy, flatMap } from "lodash";
export const TALENT_PICKS = "talentpicks";
export const TRACKMASTER_PICKS = "trackmasterpicks";
export const TIMEFORM_PICKS = "timeformpicks";
export const HANDICAPPING_STORE = "handicappingStore";
export const RACING_AND_SPORTS = "racingAndSports";
export const TRACK_DATA_SOURCE_USGSA = "USGSA";
export const TRACK_DATA_SOURCE_GSA = "GSA";
export const TRACK_DATA_SOURCE_SRW = "SRW";
export const TRACK_DATA_SOURCE_EQB = "EQB";
export const TRACK_DATA_SOURCE_RAS = "RAS";
const getOddsInfo = (bettingInterestRunnerInfo) => {
const currentOddsNumerator =
get(bettingInterestRunnerInfo, "currentOdds.numerator") || "";
const currentOddsDenominator =
get(bettingInterestRunnerInfo, "currentOdds.denominator") || "";
const mlOddsNumerator =
get(bettingInterestRunnerInfo, "morningLineOdds.numerator") || "";
const mlOddsDenominator =
get(bettingInterestRunnerInfo, "morningLineOdds.denominator") || "";
const isMorningLine =
currentOddsNumerator === "" && currentOddsDenominator === "";
return {
currentOddsNumerator: isMorningLine
? mlOddsNumerator
: currentOddsNumerator,
currentOddsDenominator: isMorningLine
? mlOddsDenominator
: currentOddsDenominator,
isMorningLine
};
};
const hasInfo = (freePicks) =>
!!freePicks && !isNull(freePicks.number) && !isNull(freePicks.info);
const getPickInfo = (bettingInterestData, picksType = TRACKMASTER_PICKS) => {
const returnPicksInfo = [];
bettingInterestData.runners.forEach((runner) => {
const pickInfo =
picksType === TIMEFORM_PICKS
? get(runner, "timeform.freePick")
: get(runner, "handicapping.freePick");
if (hasInfo(pickInfo)) {
returnPicksInfo.push({
runnerInfo: runner,
pickInfo
});
}
});
return returnPicksInfo;
};
const hasPicksInfo = (bettingInterestData, picksType = TRACKMASTER_PICKS) =>
bettingInterestData.runners &&
bettingInterestData.runners.some((runner) =>
hasInfo(
picksType === TIMEFORM_PICKS
? get(runner, "timeform.freePick")
: get(runner, "handicapping.freePick")
)
);
const processBettingInterests = (
raceData = [],
raceTypeCode = "T",
picksType = TRACKMASTER_PICKS
) =>
raceData
.filter((bettingInterestData) =>
hasPicksInfo(bettingInterestData, picksType)
)
.map((bettingInterestData) => {
const runnerAndPicksInfoStruct =
getPickInfo(bettingInterestData, picksType) || [];
const runnerOddsInfo = getOddsInfo(bettingInterestData);
return runnerAndPicksInfoStruct.map((runnerAndPicksInfo) => ({
info: runnerAndPicksInfo.pickInfo.info,
number: runnerAndPicksInfo.pickInfo.number,
horseName: runnerAndPicksInfo.runnerInfo.horseName,
runnerId: runnerAndPicksInfo.runnerInfo.runnerId,
raceTypeCode,
scratched: runnerAndPicksInfo.runnerInfo.scratched,
isMorningLine: runnerOddsInfo.isMorningLine,
currentOddsNumerator: runnerOddsInfo.currentOddsNumerator,
currentOddsDenominator: runnerOddsInfo.currentOddsDenominator
}));
});
const prepDataForPicks = (
bettingInsterestData,
raceTypeCode,
picksType = TRACKMASTER_PICKS
) =>
sortBy(
flatMap(
processBettingInterests(bettingInsterestData, raceTypeCode, picksType)
),
["number"]
);
export const filterPicksBettingInterests = (
raceData,
picksType = TRACKMASTER_PICKS
) => {
const biWithPicks = [];
if (!!raceData && raceData.length > 0) {
raceData
.filter((bettingInterestData) =>
hasPicksInfo(bettingInterestData, picksType)
)
.forEach((bi) => {
bi.runners.forEach((runner) => {
const freePick =
picksType === TIMEFORM_PICKS
? get(runner, "timeform.freePick")
: get(runner, "handicapping.freePick");
if (hasInfo(freePick)) {
biWithPicks[get(freePick, "number", 0) - 1] = {
biNumber: bi.biNumber,
currentOdds: bi.currentOdds,
morningLineOdds: bi.morningLineOdds,
isFavorite: bi.isFavorite,
runners: [
{
horseName: get(runner, "horseName"),
runnerId: get(runner, "runnerId"),
scratched: get(runner, "scratched"),
masterPickNumber: get(freePick, "number"),
masterPickInfo: get(freePick, "info", "") || ""
}
]
};
}
});
});
}
return biWithPicks;
};
export const getTrackDataSourceTitle = (trackDataFromTimeform, withPicks) => {
let title = "Trackmaster";
if (trackDataFromTimeform === TRACK_DATA_SOURCE_GSA) {
title = "Timeform 1-2-3";
} else if (trackDataFromTimeform === TRACK_DATA_SOURCE_SRW) {
title = "Free";
}
return `${title}${withPicks ? " Picks" : ""}`;
};
export default prepDataForPicks;
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/components/TagList/styled-components.ts
import styled from "styled-components";
export const Container = styled.div`
display: flex;
flex-direction: column;
`;
export const TitleElement = styled.h4`
color: ${({ theme }) => theme.colorTokens.content.default};
font-family: ${({ theme }) => theme.fonts.medium};
font-style: normal;
font-weight: 500;
line-height: 19px;
display: block;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
margin: 0;
`;
export const Separator = styled.div`
&::before {
margin: 12px -12px 16px 0;
content: " ";
display: block;
border-bottom: 1px solid ${({ theme }) => theme.colorTokens.border.default};
}
`;
export const Description = styled.div`
color: ${({ theme }) => theme.colorTokens.content.subtle};
font-size: 14px;
margin-top: 6px;
& * {
font-family: ${({ theme }) => theme.fonts.regular};
line-height: 18px;
}
& ol,
ul {
margin-top: 8px;
}
& li {
margin-left: 16px;
list-style-type: disc;
}
`;
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/components/TagList/index.tsx
import React, { Fragment, ReactNode } from "react";
import { Tag } from "@tvg/design-system/src/components/tag";
import { TagProps as TagFlowType } from "@tvg/design-system/src/components/tag/types";
import {
Container,
TitleElement,
Description,
Separator
} from "./styled-components";
type Props = {
title?: string | ReactNode;
tags: TagFlowType[];
qaLabel: string;
};
const TagList = (props: Props) => (
<Container data-qa-label={props.qaLabel}>
{props.title && <TitleElement>{props.title}</TitleElement>}
{props.tags.map((tag: TagFlowType) => {
const key = `tag-${tag.label.replace(/ /g, "-")}`;
return (
<Fragment key={key}>
<Separator />
<Tag qaLabel={key} {...tag} />
<Description
data-qa-label={`${key}-description`}
dangerouslySetInnerHTML={{ __html: tag.description || "" }}
/>
</Fragment>
);
})}
</Container>
);
TagList.defaultProps = {
title: "",
tags: [],
qaLabel: "tagList"
};
export default TagList;
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/components/RunnerFlags/styled-components.ts
import styled, { css } from "styled-components";
export const RunnerFlagsWrapper = styled.ul`
display: flex;
justify-content: flex-start;
flex-wrap: wrap;
& .runner-flag {
margin-right: 8px;
&:last-of-type {
margin-right: 0;
}
}
`;
export const ContentWrapper = styled.div<{ hasSeparator: boolean }>`
background-color: ${({ theme }) => theme.colorTokens.content.onDark};
padding: 12px;
${({ hasSeparator, theme }) =>
hasSeparator
? css`
border-top: 10px solid ${theme.colorTokens.border.default};
`
: css`
border-bottom: 1px solid ${theme.colorTokens.border.default};
`}
`;
export const IconWrapper = styled.span`
margin-left: 4px;
height: 24px;
width: 24px;
display: flex;
justify-content: center;
align-items: center;
`;
export const RunnerNumberContainer = styled.div`
display: inline-block;
min-width: 20px;
height: 20px;
margin-right: 4px;
`;
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/components/RunnerFlags/index.tsx
import React, { ReactNode, useEffect, useState } from "react";
import { get, uniqWith } from "lodash";
import { UnaryFn } from "@tvg/ts-types/Functional";
import { RunnerFlags as RunnerFlagsType } from "@tvg/ts-types/Race";
import { replaceCAPIVariables } from "@tvg/utils/capiUtils";
import { useColorTokens, Icon, Tag, TagProps } from "@tvg/design-system";
import { Modal, Saddle } from "@tvg/design-system/web";
import TagList from "../TagList";
import {
RunnerFlagsWrapper,
ContentWrapper,
IconWrapper,
RunnerNumberContainer
} from "./styled-components";
type FlagConfig = {
id: string;
name: string;
description: string;
isCondensed: boolean;
};
export type HandicappingRunnerFlags = {
title: string;
subtitle: string;
subtitleRunnerFlags: string;
flags: Array<FlagConfig>;
};
type Props = {
runnerId: string;
runnerName: string;
flags: RunnerFlagsType;
maxFlags?: number;
handicappingRunnerFlags: HandicappingRunnerFlags;
helpShown: boolean;
};
const mapToTag = (flag: FlagConfig): TagProps => ({
label: flag.name,
description: flag.description,
icon: undefined,
qaLabel: `flag-${flag.id}`,
variant: "warning",
size: "l"
});
const renderContentWrapper = (
title: string | ReactNode,
flags: Array<FlagConfig>,
hasSeparator = false
) => (
<ContentWrapper hasSeparator={hasSeparator}>
<TagList title={title} tags={flags.map((flag) => mapToTag(flag))} />
</ContentWrapper>
);
const getRunnerTitle = (
titleTemplate: string,
runnerId: string,
runnerName: string
) => (
<>
{replaceCAPIVariables(titleTemplate, {
runnerName: ""
})}
<RunnerNumberContainer>
<Saddle
size="s"
number={runnerId}
qaLabel={`saddle-container-${runnerId}`}
/>
</RunnerNumberContainer>
{runnerName}
</>
);
const renderFlagsHelpContent = (
runnerId: string,
runnerName: string,
handicappingRunnerFlags: HandicappingRunnerFlags,
runnerFlags: string[] = []
) => {
const flagsUniq = uniqWith(
handicappingRunnerFlags.flags,
(flagCfgA, flagCfgB) => flagCfgA.name === flagCfgB.name
);
// runner flags config
const RunnerFlagsTitle = getRunnerTitle(
handicappingRunnerFlags.subtitleRunnerFlags,
runnerId,
runnerName
);
const runnerFlagsConfig =
runnerFlags && runnerFlags.length > 0
? flagsUniq.filter((handicappingFlag) =>
runnerFlags.includes(handicappingFlag.id)
)
: [];
// other flags config
const hasSeparator = true;
const otherFlagsTitle = handicappingRunnerFlags.subtitle;
const otherFlagsConfig = flagsUniq.filter(
(handicappingFlag) => !runnerFlags.includes(handicappingFlag.id)
);
return (
<>
{runnerFlagsConfig.length > 0 &&
renderContentWrapper(RunnerFlagsTitle, runnerFlagsConfig)}
{renderContentWrapper(otherFlagsTitle, otherFlagsConfig, hasSeparator)}
</>
);
};
const renderFlagsHelpModal = (
runnerId: string,
runnerName: string,
handicappingRunnerFlags: HandicappingRunnerFlags,
flagsList: string[],
isModalOpen: boolean,
setIsModalOpen: UnaryFn<boolean, void>
) => {
const modalProps = {
isOpen: isModalOpen,
headerProps: {
title: handicappingRunnerFlags.title,
showCloseButton: true,
showBackButton: true,
onBack: () => {
setIsModalOpen(false);
}
},
onClose: () => {
setIsModalOpen(false);
},
padding: "0px",
hasMaxHeight: true
};
return (
<Modal {...modalProps}>
{renderFlagsHelpContent(
runnerId,
runnerName,
handicappingRunnerFlags,
flagsList
)}
</Modal>
);
};
const RunnerFlags = (props: Props) => {
const {
runnerId,
runnerName,
flags,
maxFlags,
handicappingRunnerFlags,
helpShown
} = props;
const [isModalOpen, setIsModalOpen] = useState(false);
const [flagsList, setFlagsList] = useState<string[]>([]);
const colorTokens = useColorTokens();
useEffect(() => {
setFlagsList(
Object.keys(flags).filter(
(flag) => flags[flag as keyof RunnerFlagsType] && flag !== "__typename"
)
);
}, [runnerName, flags]);
const getFlagConfig = (flag: string) =>
get(handicappingRunnerFlags, "flags", []).find(
(flagConfig) => flagConfig.id === flag
) || { id: flag, name: flag, description: flag, isCondensed: true };
return flagsList.length > 0 ? (
<>
<RunnerFlagsWrapper>
{flagsList.slice(0, maxFlags || flagsList.length).map((flag) => (
<Tag key={flag} {...mapToTag(getFlagConfig(flag))} />
))}
{helpShown && !!handicappingRunnerFlags && (
<IconWrapper onClick={() => setIsModalOpen(true)}>
<Icon
name="support"
lineColor={colorTokens.content.link}
size="m"
backgroundColor={colorTokens.background.infoSubtle}
/>
</IconWrapper>
)}
</RunnerFlagsWrapper>
{renderFlagsHelpModal(
runnerId,
runnerName,
handicappingRunnerFlags,
flagsList,
isModalOpen,
setIsModalOpen
)}
</>
) : null;
};
RunnerFlags.defaultProps = {
runnerId: "",
runnerName: "",
flags: {
horseInFocus: false,
warningHorse: false,
jockeyUplift: false,
trainerUplift: false,
horsesForCoursePos: false,
horsesForCourseNeg: false,
hotTrainer: false,
coldTrainer: false,
highestLastSpeedRating: false,
sectionalFlag: false,
significantImprover: false,
jockeyInForm: false,
clearTopRated: false,
interestingJockeyBooking: false,
firstTimeBlinkers: false
},
maxFlags: null,
handicappingRunnerFlags: {
title: "",
subtitle: "",
subtitleRunnerFlags: "",
flags: []
},
helpShown: false
};
export default RunnerFlags;
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/components/RunnerBio/styled-components.ts
import styled from "styled-components";
import { ellipsis } from "polished";
import { themeGet } from "@tvg/design-system/src/theming";
interface Props {
runnerName: string;
isScratched: boolean;
}
export const BioWrapper = styled.dl`
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: center;
padding: 8px 8px 4px;
margin: 0;
position: relative;
`;
export const BioTitle = styled.dt.attrs<{
runnerName: string;
}>((props) => ({
title: props.runnerName,
"data-qa-label": "runnerBio-title"
}))<Props>`
text-transform: uppercase;
font-size: 14px;
font-family: ${themeGet("fonts.bold")};
font-weight: 500;
min-height: 16px;
margin-bottom: 2px;
letter-spacing: 0;
${ellipsis()};
color: ${({ theme }) => theme.colorTokens.content.strong};
text-decoration: ${(props) => (props.isScratched ? "line-through" : "")};
opacity: ${(props) => (props.isScratched ? 0.5 : 1)};
& svg {
padding-right: 4px;
}
`;
export const BioDescription = styled.dd<{
isScratched: boolean;
}>`
font-size: 12px;
color: ${({ theme }) => theme.colorTokens.content.subtle};
margin: 0;
max-width: 100%;
min-height: 14px;
letter-spacing: 0;
opacity: ${(props) => props.isScratched && 0.5};
& > :not(:last-child) {
margin-right: 8px;
padding-right: 8px;
}
`;
export const Results = styled.dt`
position: absolute;
top: 8px;
right: 0;
display: flex;
font-size: 12px;
line-height: 1.6;
`;
export const ResultsDistance = styled.strong`
width: 70px;
text-align: right;
`;
export const ResultsOdds = styled.span`
width: 44px;
text-align: right;
padding-left: 16px;
`;
export const FlagsAndPick = styled.div`
display: flex;
flex-wrap: wrap;
width: 100%;
margin-top: 4px;
> span {
margin-right: 8px;
}
`;
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/components/RunnerBio/index.tsx
import React, { PureComponent } from "react";
import { get } from "lodash";
import type {
RaceTypeCodeEnum,
RaceOdds,
HandicapOptions,
HandicapSortOptionsType,
RaceCardRunner
} from "@tvg/types/Race";
import InlineInfo from "@tvg/atomic-ui/_atom/InlineInfo";
import Icon from "@tvg/design-system/src/components/icon";
import TrackMasterPickTag from "@tvg/atomic-ui/_molecule/TrackMasterPickTag";
import SimpleInlineInfo from "../SimpleInlineInfo";
import RunnerFlags, { HandicappingRunnerFlags } from "../RunnerFlags";
import {
BioWrapper,
BioTitle,
BioDescription,
Results,
ResultsDistance,
ResultsOdds,
FlagsAndPick
} from "./styled-components";
interface Props {
/**
* Race type code
*/
raceTypeCode: typeof RaceTypeCodeEnum;
/**
* Runner name to be displayed
*/
runnerName: string;
/**
* Runner track master pick position
*/
runnerMasterPickNumber: number;
/**
* Is Runner track master pick
*/
isRunnerTrackMasterPick: boolean;
/**
Is Runner numberFire pick
*/
isRunnerNumberFirePick: boolean;
/**
* Inline handicapping data
*/
handicappingData: Array<typeof HandicapOptions | string>;
/**
* Scratches the runner
*/
isScratched: boolean;
/**
* For the first element of inline handicapping be bold
*/
firstHandicapBold: boolean;
/**
* show favorite
*/
showFavorite: boolean;
/**
* For the first element of inline handicapping be bold
*/
isFavorite: boolean;
/**
* For the past performance results, there might have a past race report to be displayed
*/
resultsData: {
accBeatenDistance: string;
odds: typeof RaceOdds | null | void;
} | null | void;
/**
* If jockey has changed show icon
*/
hasJockeyChanges: boolean;
/**
* Handicapping Sort Mode
*/
handicappingSortMode: typeof HandicapSortOptionsType;
/**
* Runner has track master info
*/
hasTrackMasterInfo: boolean;
/**
* Track data source
*/
trackDataSource: string;
runnerData: typeof RaceCardRunner | null | void;
showFlags: boolean;
handicappingRunnerFlags: HandicappingRunnerFlags;
}
export default class RunnerBio extends PureComponent<Props> {
static defaultProps = {
raceTypeCode: "T",
runnerName: "",
handicappingData: [],
isScratched: false,
firstHandicapBold: false,
showFavorite: false,
isFavorite: false,
runnerMasterPickNumber: -1,
isRunnerTrackMasterPick: false,
isRunnerNumberFirePick: false,
resultsData: null,
hasJockeyChanges: false,
handicappingSortMode: "saddlecloth",
hasTrackMasterInfo: true,
trackDataSource: "",
runnerData: null,
showFlags: true,
handicappingRunnerFlags: {
title: "",
subtitle: "",
subtitleRunnerFlags: "",
flags: []
}
};
renderOdds = () => {
const odds = get(this.props.resultsData, "odds");
if (!!odds && !!odds.numerator) {
return `${odds.numerator}${
odds.denominator ? `/${odds.denominator}` : ""
}`;
}
return "n/a";
};
renderRunnerFlags = () => {
const flagsObg = get(this.props.runnerData, "timeform.flags", {});
const hasFlags = Object.keys(flagsObg).some((flag) => flagsObg[flag]);
return (
hasFlags &&
this.props.showFlags && (
<RunnerFlags
flags={flagsObg}
maxFlags={2}
handicappingRunnerFlags={this.props.handicappingRunnerFlags}
/>
)
);
};
render() {
const flagsObg = get(this.props.runnerData, "timeform.flags", {});
const hasFlags = Object.keys(flagsObg).some((flag) => flagsObg[flag]);
const hasPicksOrFlags =
(hasFlags && this.props.showFlags) || this.props.hasTrackMasterInfo;
return (
<BioWrapper>
{(this.props.isRunnerTrackMasterPick ||
this.props.isRunnerNumberFirePick) && (
<TrackMasterPickTag
pickNumber={this.props.runnerMasterPickNumber}
labelDarker={this.props.isRunnerTrackMasterPick}
isScratched={this.props.isScratched}
trackDataSource={this.props.trackDataSource}
isNumberFirePick={this.props.isRunnerNumberFirePick}
/>
)}
<BioTitle
runnerName={this.props.runnerName}
isScratched={this.props.isScratched}
>
{this.props.showFavorite && (
<Icon
name="star"
size="s"
shouldUseColorTokens
lineColor={
this.props.isFavorite
? "background.alert"
: "background.neutralSubtle"
}
/>
)}
{this.props.runnerName}
</BioTitle>
{!!this.props.resultsData && (
<Results>
<ResultsDistance>
{this.props.resultsData.accBeatenDistance}
</ResultsDistance>
<ResultsOdds>{this.renderOdds()}</ResultsOdds>
</Results>
)}
<BioDescription isScratched={this.props.isScratched}>
{this.props.handicappingData.length > 0 &&
(this.props.hasTrackMasterInfo ? (
<InlineInfo
isFirstBold={this.props.firstHandicapBold}
info={this.props.handicappingData}
hasJockeyChanges={this.props.hasJockeyChanges}
isScratched={this.props.isScratched}
showHandicappingSortMode={this.props.raceTypeCode !== "G"}
handicappingSortMode={this.props.handicappingSortMode}
/>
) : (
<SimpleInlineInfo info={this.props.handicappingData} />
))}
</BioDescription>
{hasPicksOrFlags && (
<FlagsAndPick>
{!this.props.isRunnerTrackMasterPick &&
!this.props.isRunnerNumberFirePick &&
this.props.hasTrackMasterInfo && (
<TrackMasterPickTag
pickNumber={this.props.runnerMasterPickNumber}
labelDarker={this.props.isRunnerTrackMasterPick}
trackDataSource={this.props.trackDataSource}
/>
)}
{hasFlags && this.props.showFlags && (
<RunnerFlags
flags={flagsObg}
maxFlags={2}
handicappingRunnerFlags={this.props.handicappingRunnerFlags}
/>
)}
</FlagsAndPick>
)}
</BioWrapper>
);
}
}
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/components/helpers.ts
type Transition = {
function: string;
value: number;
time: "ms" | "s";
};
export const easeInOut: Transition = {
function: "ease-in-out",
value: 200,
time: "ms"
};
export const cubic: Transition = {
function: "cubic-bezier(0.03, 0.59, 0.1, 0.97)",
value: 250,
time: "ms"
};
export const generateTransition = (
transition: Transition,
cssProp: string = "all",
delay?: string
): string =>
`${cssProp} ${transition.value}${transition.time} ${transition.function}${
delay ? ` ${delay}` : ""
}`;
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/components/RunnerOdds/styled-components.ts
import { useQaLabel } from "@tvg/design-system/src/hooks/useQaLabel";
import { themeGet } from "@tvg/design-system/src/theming";
import styled from "styled-components";
import { easeInOut, generateTransition } from "../helpers";
export const RunnerOddsAtom = styled.div<{
scratched?: boolean;
favorite?: boolean;
}>`
position: absolute;
top: 0;
left: 0;
display: flex;
flex-direction: column;
justify-content: center;
width: 100%;
height: 100%;
align-items: center;
text-align: center;
font-size: 12px;
line-height: 14px;
opacity: ${(props) => props.scratched && 0.4};
background-color: ${({ favorite, theme }) =>
favorite && theme.colorTokens.component.tag.offer_subtle.background};
will-change: background-color;
transition: ${generateTransition(easeInOut, "background-color")};
& > strong {
margin-bottom: 2px;
}
`;
export const Strong = styled.span.attrs<{
qaLabel: string;
}>((props) => ({
...useQaLabel(props.qaLabel)
}))<{
qaLabel?: string;
}>`
display: block;
font-size: 14px;
font-family: ${themeGet("fonts.medium")};
height: 16px;
letter-spacing: 0;
text-align: center;
margin: 0 0 2px;
color: ${({ theme }) => theme.colorTokens.content.brandSecondary};
`;
export const Span = styled.span.attrs<{
qaLabel: string;
}>((props) => ({
...useQaLabel(props.qaLabel)
}))<{
qaLabel?: string;
}>`
display: block;
font-size: 12px;
font-family: ${themeGet("fonts.regular")};
font-weight: 500;
height: 14px;
letter-spacing: 0;
text-align: center;
color: ${({ theme }) => theme.colorTokens.content.subtle};
`;
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/components/RunnerOdds/index.tsx
import React, { PureComponent } from "react";
import { isNumber, toString, toNumber } from "lodash";
import { RunnerOddsAtom, Strong, Span } from "./styled-components";
const getRunnerOddQALabelSuffix = (
isFavorite: boolean,
isScratched: boolean
): string => {
if (isScratched) {
return "-scratched";
}
if (isFavorite) {
return "-favorite";
}
return "";
};
interface Props {
/**
* Does the runner is isScratched
*/
isScratched: boolean;
/**
* Does the runner is favorite
*/
isFavorite: boolean;
/**
* Current odds value
*/
currentOddsNumerator: number | null | void;
/**
* Current odds value
*/
currentOddsDenominator: number | null | void;
/**
* Morning line odds value
*/
morningLineOddsNumerator: number | null | void;
/**
* Current odds value
*/
morningLineOddsDenominator: number | null | void;
}
export default class RunnerOdds extends PureComponent<Props> {
static defaultProps = {
isScratched: false,
isSelected: false,
isFavorite: false,
currentOddsNumerator: null,
currentOddsDenominator: null,
morningLineOddsNumerator: null,
morningLineOddsDenominator: null
};
renderOddDenominator() {
return (
(isNumber(this.props.currentOddsDenominator) &&
`/${toString(this.props.currentOddsDenominator)}`) ||
""
);
}
renderOdd() {
if (!this.props.isScratched) {
if (!isNumber(this.props.currentOddsNumerator)) {
return "n/a";
}
return `${toString(
this.props.currentOddsNumerator
)}${this.renderOddDenominator()}`;
}
return "scr";
}
renderMorningLineDenominator() {
return (
(toNumber(this.props.morningLineOddsDenominator) > 1 &&
`/${toString(this.props.morningLineOddsDenominator)}`) ||
""
);
}
renderMorningLine() {
if (isNumber(this.props.morningLineOddsNumerator)) {
return `${
this.props.morningLineOddsNumerator
}${this.renderMorningLineDenominator()}`;
}
return "n/a";
}
render() {
return (
<RunnerOddsAtom
data-qa-label={`runnerOdds${getRunnerOddQALabelSuffix(
this.props.isFavorite,
this.props.isScratched
)}`}
scratched={this.props.isScratched}
favorite={this.props.isFavorite && !this.props.isScratched}
>
<Strong qaLabel="runnerOdds-odd">{this.renderOdd()}</Strong>
<Span qaLabel="runnerOdds-morningLineOdd">
{this.renderMorningLine()}
</Span>
</RunnerOddsAtom>
);
}
}
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/components/SelectionButton/styled-components.ts
import styled, { css } from "styled-components";
import Icon from "@tvg/design-system/src/components/icon";
import { generateTransition, cubic } from "../helpers";
interface SelectionProps {
qaLabel?: string;
width: string;
height: string;
}
export const Selection = styled.button.attrs<{
qaLabel?: string;
}>((props) => ({
"data-qa-label": props.qaLabel
}))<SelectionProps>`
outline: none;
opacity: 1;
width: ${(props) => props.width};
height: ${(props) => props.height};
position: relative;
background-color: ${({ theme }) =>
theme.colorTokens.component.button.transparent.background.disabled};
cursor: pointer;
`;
export const IconsWrapper = styled.span`
position: relative;
display: inline-flex;
align-items: center;
justify-content: center;
`;
export const Circle = styled.span<{
isChecked: boolean;
hasHover?: boolean;
}>`
display: inline-flex;
width: 24px;
height: 24px;
border: 2px solid ${({ theme }) => theme.colorTokens.background.positive};
border-radius: 50%;
align-items: center;
justify-content: center;
background-color: ${({ theme }) =>
theme.colorTokens.component.button.secondaryDark.background.hover};
will-change: transform;
transition: ${generateTransition(cubic, "transform")};
transform: ${({ isChecked }) => (isChecked ? "scale(0)" : "scale(1)")};
position: relative;
line-height: 24px;
font-size: 12px;
font-weight: bold;
color: ${({ isChecked, theme }) =>
isChecked
? theme.colorTokens.component.button.secondaryDark.background.hover
: theme.colorTokens.notification.positive.background};
${({ hasHover }) =>
hasHover &&
css`
&:hover {
background-color: ${({ theme }) =>
theme.colorTokens.background.positiveSubtle};
}
`}
`;
export const CircleChecked = styled(Circle)`
position: absolute;
background-color: ${({ theme }) =>
theme.colorTokens.notification.positive.background};
transform: ${(props) => (props.isChecked ? "scale(1)" : "scale(0)")};
`;
export const NumberIcon = styled(Icon)<{
isChecked: boolean;
}>`
position: absolute;
border: 1px solid
${({ isChecked, theme }) =>
isChecked
? theme.colorTokens.core.whiteTint020
: theme.colorTokens.notification.positive.background};
border-radius: 50%;
top: -2px;
right: -7px;
background: ${({ isChecked, theme }) =>
isChecked
? theme.colorTokens.notification.positive.background
: theme.colorTokens.component.button.secondaryDark.background.hover};
`;
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/components/SelectionButton/index.tsx
import React, { PureComponent, SyntheticEvent } from "react";
import { noop } from "lodash";
import Icon from "@tvg/design-system/src/components/icon";
import {
Selection,
Circle,
CircleChecked,
NumberIcon,
IconsWrapper
} from "./styled-components";
export type SelectionType = "default" | "key" | "number";
interface Props {
/**
* Width of SelectionButton
*/
width: string;
/**
* Height of SelectionButton
*/
height: string;
/**
* Selection's Type
*/
selectionType: SelectionType;
/**
* Selection's number
*/
number: number;
/**
* isChecked state of SelectionButton
*/
isChecked: boolean;
/**
* Scratched state of SelectionButton
*/
isScratched: boolean;
/**
* Callback function after click on SelectionButton
*/
onChange: () => unknown;
/**
* has Hover on button
*/
hasHover: boolean;
/**
* Redirect to racecard, means it is on top races
*/
redirectToRacecard: boolean;
}
const onChangeFunc = (
e: SyntheticEvent,
isScratched: boolean,
onChange: () => unknown,
redirectToRacecard: boolean
): void => {
if (!redirectToRacecard) {
e.preventDefault();
e.stopPropagation();
}
if (!isScratched) {
onChange();
}
};
const getIcon = (
selectionType: SelectionType,
isChecked: boolean,
color: string
) => {
switch (selectionType) {
case "number":
return (
<NumberIcon
name={!isChecked ? "add" : "tick"}
lineColor={color}
size="s"
isChecked={isChecked}
shouldUseColorTokens
/>
);
case "key":
return (
<Icon name="key" lineColor={color} size="s" shouldUseColorTokens />
);
default:
return (
<Icon
name={!isChecked ? "add" : "tick"}
lineColor={color}
size="s"
shouldUseColorTokens
/>
);
}
};
const getSelectionButtonQAPrefix = (
isChecked: boolean,
isScratched: boolean,
selectionType: string
): string | null | void => {
if (isScratched) {
return "scratched";
}
if (selectionType === "key") {
if (isChecked) {
return "key-checked";
}
return "key";
}
if (isChecked) {
return "checked";
}
return null;
};
export default class SelectionButton extends PureComponent<Props> {
static defaultProps = {
selectionKey: "",
width: "48px",
height: "100%",
selectionType: "default",
number: 0,
isChecked: false,
isScratched: false,
onChange: noop,
hasHover: false,
redirectToRacecard: false
};
render() {
return (
<Selection
width={this.props.width}
height={this.props.height}
onClick={(e: SyntheticEvent): void =>
onChangeFunc(
e,
this.props.isScratched,
this.props.onChange,
this.props.redirectToRacecard
)
}
qaLabel="selectionButton"
>
<IconsWrapper
data-qa-label={getSelectionButtonQAPrefix(
this.props.isChecked,
this.props.isScratched,
this.props.selectionType
)}
>
{!this.props.isScratched && [
<CircleChecked key="selected" isChecked={this.props.isChecked}>
{this.props.selectionType === "number" && this.props.number}
{getIcon(
this.props.selectionType,
this.props.isChecked,
"core.whiteTint020"
)}
</CircleChecked>,
<Circle
key="unselected"
isChecked={this.props.isChecked}
hasHover={this.props.hasHover}
>
{this.props.selectionType === "number" && this.props.number}
{getIcon(
this.props.selectionType,
this.props.isChecked,
"background.positive"
)}
</Circle>
]}
</IconsWrapper>
</Selection>
);
}
}
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/components/RunnerLine/styled-components.ts
import styled, { css } from "styled-components";
import { generateTransition, easeInOut } from "../helpers";
export const RunnerWrapper = styled.tr<{
isLeg: boolean;
showActiveState: boolean;
hasHover: boolean;
}>`
background-color: ${({ theme }) =>
theme.colorTokens.component.button.transparent.background.hover};
${(props) =>
props.isLeg
? css`
border-top: ${({ theme }) =>
`1px solid ${theme.colorTokens.groupedfiltercell.border.hover}`};
border-bottom: ${({ theme }) =>
`1px solid ${theme.colorTokens.groupedfiltercell.border.hover}`};
border-left: ${({ theme }) =>
`1px solid ${theme.colorTokens.component.input.base}`};
border-right: ${({ theme }) =>
`1px solid ${theme.colorTokens.component.input.base}`};
`
: css`
border-top: ${({ theme }) =>
`1px solid ${theme.colorTokens.groupedfiltercell.border.hover}`};
border-bottom: ${({ theme }) =>
`1px solid ${theme.colorTokens.groupedfiltercell.border.hover}`};
`};
&:active {
background-color: ${({ theme, showActiveState }) =>
showActiveState && theme.colorTokens.background.base};
}
`;
export const AnimateContainer = styled.div`
max-height: 0;
overflow: hidden;
transition: ${generateTransition(easeInOut, "max-height")};
`;
export const SecondRow = styled.tr`
& .animated-container {
max-height: 1000px;
}
&.expand-enter .animated-container {
max-height: 0;
}
&.expand-enter-active .animated-container {
max-height: 1000px;
}
&.expand-enter-done .animated-container {
max-height: 1000px;
}
&.expand-exit-active .animated-container {
max-height: 0;
}
&.expand-exit-done .animated-container {
max-height: 0;
}
`;
export const RunnerCell = styled.td`
height: 0;
`;
export const RunnerNumberWrapper = styled(RunnerCell)`
width: 24px;
position: relative;
`;
export const RunnerNumberContainer = styled.div`
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
`;
export const RunnerOddWrapper = styled(RunnerCell)`
width: 40px;
position: relative;
`;
export const RunnerBioWrapper = styled(RunnerCell)<{
removeVerticalPadding?: boolean;
hasHover?: boolean;
}>`
padding: ${(props) => !props.removeVerticalPadding && "4px 0"};
max-width: 225px;
border-left: ${({ theme }) =>
`1px solid ${theme.colorTokens.groupedfiltercell.border.hover}`};
${({ hasHover }) =>
hasHover &&
css`
&:hover {
background-color: ${({ theme }) => theme.colorTokens.background.accent};
}
`}
`;
export const RunnerSelectionWrapped = styled.div<{
vertical?: boolean;
}>`
display: flex;
align-items: center;
justify-content: flex-end;
${({ vertical }) =>
vertical
? css`
min-height: 0;
padding-bottom: 12px;
`
: css`
min-height: 40px;
`}
`;
export const RunnerTrackMasterInfo = styled.p<{
vertical?: boolean;
}>`
font-size: 12px;
color: ${({ theme }) => theme.colorTokens.content.subtle};
margin-top: -4px;
${({ vertical }) =>
vertical
? css`
padding: 0 8px 8px;
`
: css`
padding: 0 8px 4px;
`};
`;
export const BioSelectionsWrapper = styled.div<{
vertical?: boolean;
}>`
display: flex;
${({ vertical }) =>
vertical
? css`
flex-direction: column;
`
: css`
align-items: center;
`};
& > :first-child {
flex: 1;
min-width: 0;
}
& > :not(:first-child):last-child {
flex: 0 0 auto;
}
`;
export const SilkContainer = styled(RunnerCell)`
margin: 12px 0;
padding-right: 8px;
width: 31px;
height: 100%;
position: relative;
`;
export const Silk = styled.img`
height: 31px;
width: 31px;
`;
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/components/RunnerLine/index.tsx
import React, { Component, MouseEvent, RefObject } from "react";
import type {
ExpandLineArgs,
HandicapSortOptionsType,
RaceCardBettingInterest,
RaceCardRunner,
RacePanelLink,
RaceProgram,
RaceTypeCodeEnum,
Timeform
} from "@tvg/types/Race";
import { TernaryFn, QuadFn, UnaryFn } from "@tvg/ts-types/Functional";
import { events as AlchemerEvents } from "@urp/alchemer";
import RunnerNumber from "@tvg/atomic-ui/_atom/RunnerNumber";
import { get, isEqual, noop, times } from "lodash";
import { Link } from "react-router-dom";
import { CSSTransition } from "react-transition-group";
import RunnerBio from "../RunnerBio";
import type { HandicappingRunnerFlags } from "../RunnerFlags";
import RunnerOdds from "../RunnerOdds";
import SelectionButton from "../SelectionButton";
import {
AnimateContainer,
BioSelectionsWrapper,
RunnerBioWrapper,
RunnerNumberContainer,
RunnerNumberWrapper,
RunnerOddWrapper,
RunnerSelectionWrapped,
RunnerTrackMasterInfo,
RunnerWrapper,
SecondRow,
Silk,
SilkContainer
} from "./styled-components";
type ArrowDirectionEnum = "none" | "up" | "down";
interface Props {
/**
* Display the betting interest number
*/
biNumber: number;
/**
* Leg number for the race
*/
leg: number;
/**
* Race type code
*/
raceTypeCode: typeof RaceTypeCodeEnum;
/**
* Current odds value
*/
currentOddsNumerator: number | null | void;
/**
* Current odds value
*/
currentOddsDenominator: number | null | void;
/**
* Morning line odds value
*/
morningLineOddsNumerator: number | null | void;
/**
* Current odds value
*/
morningLineOddsDenominator: number | null | void;
/**
* Runner full object
*/
runnerData: typeof RaceCardRunner;
/**
* Does the runner is isFavorite
*/
isFavorite: boolean;
/**
* Selects the runner
*/
selections: boolean[];
/**
* Race is isWagerable
*/
isWagerable: boolean;
/**
* Number of selection columns
*/
numColumns: number;
/**
* Flag to activate a key column
*/
isKey: boolean;
/**
* Flag to activate the leg layout
*/
isLeg: boolean;
/**
* Callback function after click on SelectionButton
*/
onRunnerSelect: TernaryFn<string, number, boolean, unknown>;
/**
* For the first element of inline handicapping be bold
*/
firstHandicapBold: boolean;
/**
**************** talent pick tool props *******************
*/
/**
* Activate favorite selection
*/
isFavoriteSelectionActive: boolean;
/**
* Selected the favorite
* Selected the favorite
*/
favoriteSelection: boolean;
/**
* Runner Line expanded
*/
expandedRunner: string;
/**
* Runner Line expand callBack
*/
expandLine: UnaryFn<typeof ExpandLineArgs, void>;
/**
* Render Expanded info
*/
expandInfo: QuadFn<
string,
number,
(typeof RaceCardBettingInterest)[],
string,
Element | void
>;
/**
Use arrow icon on inline past performances
*/
inLinePastPerformance: boolean;
/**
Is Runner track master pick
*/
isRunnerTrackMasterPick: boolean;
/**
Is Runner numberFire pick
*/
isRunnerNumberFirePick: boolean;
/**
Is Runner Racing And Sports
*/
isRunnerRacingAndSports: boolean;
/**
Handicapping Sort Mode
*/
handicappingSortMode: typeof HandicapSortOptionsType;
/**
Reveals if the user may see the inLinePastPerformance or be redirected to the race card
*/
redirectToRaceCard: boolean;
/**
The race url to be redirected to
*/
raceUrl: string;
/**
* Has track master info
*/
hasTrackMasterInfo: boolean;
/**
* On runner selection callback for top races
*/
onRunnerSelection: (
a: typeof RacePanelLink,
b: number,
c: string,
d?: MouseEvent
) => void;
/**
* Race the runner line is on
*/
race: typeof RacePanelLink | null | void;
/**
* Has hover effect
*/
hasHover: boolean;
/**
* Show runner line active state
*/
showActiveState: boolean;
/**
* Track data source
*/
trackDataSource: string;
/**
* List of all the runners
*/
runners: (typeof RaceCardBettingInterest)[];
/**
* Current race
*/
currentRace: typeof RaceProgram;
handicappingRunnerFlags: HandicappingRunnerFlags;
scrollRunnerPP: boolean;
scrollOffset: number;
/**
* Indicates if runner silk loads
*/
doesSilkLoads?: boolean;
}
export default class RunnerLine extends Component<Props> {
static defaultProps = {
biNumber: 0,
leg: 0,
raceTypeCode: "T",
currentOddsNumerator: 0,
currentOddsDenominator: 0,
morningLineOddsNumerator: 0,
morningLineOddsDenominator: 0,
jockeyKannelName: "",
trainerName: "",
isFavorite: false,
selections: [false],
isWagerable: true,
onRunnerSelect: noop,
numColumns: 1,
isKey: false,
isLeg: false,
firstHandicapBold: false,
isFavoriteSelectionActive: false,
favoriteSelection: false,
expandedRunner: "",
expandLine: noop,
expandInfo: noop,
inLinePastPerformance: false,
isRunnerTrackMasterPick: false,
isRunnerNumberFirePick: false,
isRunnerRacingAndSports: false,
handicappingSortMode: "saddlecloth",
redirectToRaceCard: false,
raceUrl: "/",
hasTrackMasterInfo: true,
onRunnerSelection: noop,
race: null,
hasHover: false,
showActiveState: true,
trackDataSource: "",
runners: [],
currentRace: {},
handicappingRunnerFlags: {
title: "",
subtitle: "",
subtitleRunnerFlags: "",
flags: []
},
scrollRunnerPP: false,
scrollOffset: 0,
doesSilkLoads: true
};
constructor(props: Props) {
super(props);
this.ref = React.createRef();
}
shouldComponentUpdate(nextProps: Props) {
const { expandedRunner: expandedRunnerNext, ...restNext } = nextProps;
const { expandedRunner: expandedRunnerProps, ...restProps } = this.props;
const expandedRunnerChange =
expandedRunnerNext !== expandedRunnerProps &&
(expandedRunnerNext === restProps.runnerData.runnerId ||
expandedRunnerProps === restProps.runnerData.runnerId);
return (
!isEqual(restNext, restProps) ||
expandedRunnerChange ||
!isEqual(this.props.currentRace, nextProps.currentRace)
);
}
handleLineSelection = (direction: ArrowDirectionEnum) => {
if (direction === "down") {
AlchemerEvents.selectHandicapOptions();
}
this.props.expandLine({
runnerId: this.props.runnerData.runnerId,
selection: this.props.biNumber.toString(),
column: this.props.leg,
fromIcon: false,
direction: direction.toString(),
isScratched: this.props.runnerData.scratched
});
};
handleSelectionButtonClick = (column: number, event?: MouseEvent) =>
this.props.redirectToRaceCard && this.props.race
? this.props.onRunnerSelection(
this.props.race,
this.props.biNumber,
this.props.raceUrl,
event
)
: this.props.onRunnerSelect(
this.props.biNumber.toString(),
this.props.leg > 0 ? this.props.leg : column,
true
);
handleLineClick = (direction: ArrowDirectionEnum) =>
!this.props.redirectToRaceCard && this.handleLineSelection(direction);
ref: RefObject<unknown> | HTMLTableRowElement;
showRunnerSilk = (isWagerable: boolean, runnerTimeform: typeof Timeform) =>
this.props.doesSilkLoads &&
!isWagerable &&
runnerTimeform &&
runnerTimeform.silkUrlSvg;
scrollIntoView = () => {
const element = this.ref as HTMLElement;
const tabletColumn = document.querySelector(
"#programpage-dualColumn-right"
);
const containerOffset = tabletColumn
? tabletColumn.scrollTop
: window.pageYOffset;
const scrollPosition =
element.getBoundingClientRect().top +
containerOffset -
this.props.scrollOffset;
if (tabletColumn) {
const header = document.querySelector("#raceCardHeader") as HTMLElement;
const headerHeight = header ? header.offsetHeight : 0;
// this is because of the auto height from magnet scroll that is breaking scroll
setTimeout(() => {
tabletColumn.scrollTo({
top: scrollPosition - headerHeight,
behavior: "smooth"
});
}, 200);
} else {
window.scrollTo({
top: scrollPosition,
behavior: "smooth"
});
}
};
renderSelectionButtons = () => {
const selectionType = (() => {
if (!this.props.isKey) {
return this.props.numColumns === 1 ? "default" : "number";
}
return "key";
})();
const columns = times(this.props.numColumns, (column) =>
!this.props.redirectToRaceCard ? (
<SelectionButton
key={`selection-${column + 1}`}
selectionType={
this.props.isKey && column > 0 ? "default" : selectionType
}
number={column + 1}
isChecked={!!this.props.selections[column]}
isScratched={this.props.runnerData.scratched}
onChange={() => this.handleSelectionButtonClick(column)}
hasHover={this.props.hasHover}
/>
) : (
<Link
key={`selection-${column + 1}`}
to={`${this.props.raceUrl}&selectedRunner=${get(
this.props,
"biNumber"
)}&betType=10`}
onClick={(event) => this.handleSelectionButtonClick(column, event)}
>
<SelectionButton
selectionType={
this.props.isKey && column > 0 ? "default" : selectionType
}
redirectToRacecard
number={column + 1}
isChecked={!!this.props.selections[column]}
isScratched={this.props.runnerData.scratched}
hasHover={this.props.hasHover}
/>
</Link>
)
);
return (
<RunnerSelectionWrapped
vertical={this.props.numColumns >= 3}
data-qa-label="runnerLine-selectionButtons"
>
{columns}
</RunnerSelectionWrapped>
);
};
renderSingleRow = (direction: ArrowDirectionEnum) => {
const runner = this.props.runners.find(
(runnerBI) => get(runnerBI, "biNumber") === get(this.props, "biNumber")
);
const runnerTimeform = get(runner, "runners[0].timeform", {});
const isSilkShown = this.showRunnerSilk(
this.props.isWagerable,
runnerTimeform
);
return (
<RunnerWrapper
// @ts-ignore
// eslint-disable-next-line
ref={(comp) => (this.ref = comp)}
onTouchStart={noop}
key={`runner-${this.props.runnerData.runnerId}`}
data-qa-label={`${this.props.runnerData.runnerId}-runnerLine${
this.props.runnerData.runnerId.match(/[a-zA-Z]/i) ? "-coupled" : ""
}${this.props.runnerData.scratched ? "-scratched" : ""}`}
isLeg={this.props.isLeg}
hasHover={this.props.hasHover}
showActiveState={this.props.showActiveState}
>
<RunnerNumberWrapper onClick={() => this.handleLineClick(direction)}>
<RunnerNumberContainer>
<RunnerNumber
raceTypeCode={this.props.raceTypeCode}
runnerId={this.props.runnerData.runnerId}
arrowDirection={direction}
/>
</RunnerNumberContainer>
</RunnerNumberWrapper>
<RunnerOddWrapper onClick={() => this.handleLineClick(direction)}>
<RunnerOdds
currentOddsNumerator={this.props.currentOddsNumerator}
currentOddsDenominator={this.props.currentOddsDenominator}
morningLineOddsNumerator={this.props.morningLineOddsNumerator}
morningLineOddsDenominator={this.props.morningLineOddsDenominator}
isScratched={this.props.runnerData.scratched}
isFavorite={this.props.isFavorite}
/>
</RunnerOddWrapper>
<RunnerBioWrapper
removeVerticalPadding={
this.props.numColumns >= 3 && this.props.isWagerable
}
onClick={() => this.handleLineClick(direction)}
colSpan={this.props.isWagerable ? 2 : 1}
>
<BioSelectionsWrapper vertical={this.props.numColumns >= 3}>
<RunnerBio
raceTypeCode={this.props.raceTypeCode}
firstHandicapBold={this.props.firstHandicapBold}
runnerName={this.props.runnerData.horseName}
handicappingData={
this.props.isRunnerTrackMasterPick
? []
: this.props.runnerData.handicapping
}
isScratched={this.props.runnerData.scratched}
showFavorite={
this.props.isWagerable && this.props.isFavoriteSelectionActive
}
isFavorite={this.props.favoriteSelection}
runnerMasterPickNumber={this.props.runnerData.masterPickNumber}
isRunnerTrackMasterPick={this.props.isRunnerTrackMasterPick}
isRunnerNumberFirePick={this.props.isRunnerNumberFirePick}
hasJockeyChanges={this.props.runnerData.hasJockeyChanges}
handicappingSortMode={this.props.handicappingSortMode}
hasTrackMasterInfo={this.props.hasTrackMasterInfo}
trackDataSource={this.props.trackDataSource}
runnerData={this.props.runnerData}
showFlags={
(this.props.expandedRunner === "" ||
this.props.expandedRunner !==
this.props.runnerData.runnerId) &&
this.props.expandInfo !== noop
}
handicappingRunnerFlags={this.props.handicappingRunnerFlags}
/>
{this.props.isWagerable &&
!this.props.runnerData.scratched &&
this.renderSelectionButtons()}
</BioSelectionsWrapper>
{(this.props.isRunnerTrackMasterPick ||
this.props.isRunnerNumberFirePick ||
this.props.isRunnerRacingAndSports) && (
<RunnerTrackMasterInfo vertical={this.props.numColumns >= 3}>
{this.props.runnerData.masterPickInfo}
</RunnerTrackMasterInfo>
)}
</RunnerBioWrapper>
{isSilkShown && (
<SilkContainer>
<Silk src={runnerTimeform.silkUrlSvg} />
</SilkContainer>
)}
</RunnerWrapper>
);
};
renderExpandedRow = () => {
const info = this.props.expandInfo(
this.props.runnerData.horseName,
get(this.props.runnerData, "dob", 0),
this.props.runners,
get(this.props.runnerData, "entityRunnerId", "")
);
return (
!!info && (
<td colSpan={4}>
<AnimateContainer className="animated-container">
{info}
</AnimateContainer>
</td>
)
);
};
render() {
const showSecondRow =
this.props.expandedRunner === this.props.runnerData.runnerId &&
this.props.expandedRunner !== "" &&
this.props.expandInfo !== noop;
const direction = showSecondRow ? "up" : "down";
return (
<>
{this.renderSingleRow(
this.props.inLinePastPerformance ? direction : "none"
)}
<CSSTransition
in={showSecondRow}
classNames="expand"
timeout={200}
unmountOnExit
onEntered={() => {
if (
this.ref instanceof Element &&
typeof window !== "undefined" &&
this.props.scrollRunnerPP
) {
this.scrollIntoView();
}
}}
>
<SecondRow>{this.renderExpandedRow()}</SecondRow>
</CSSTransition>
</>
);
}
}
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/components/RunnerList/index.tsx
import React, { Component } from "react";
import { noop, isEqual, indexOf, toString, get } from "lodash";
import { doesSilkLoads } from "@tvg/utils/handicappingUtils";
import type {
BinaryFn,
UnaryFn,
TernaryFn,
QuadFn
} from "@tvg/ts-types/Functional";
import type {
RaceCardBettingInterest,
RaceTypeCodeEnum,
RaceCardRunner,
ExpandLineArgs,
HandicapSortOptionsType,
RacePanelLink,
RaceProgram
} from "@tvg/types/Race";
import RunnerLine from "../RunnerLine";
import type { HandicappingRunnerFlags } from "../RunnerFlags";
export type Selections = string[][];
interface Props {
runners: (typeof RaceCardBettingInterest)[];
/**
* Leg number for the race
*/
leg: number;
/**
* Flag to activate the leg layout
*/
isLeg: boolean;
/**
* Flag that controls if the race is wagerable or not
*/
isWagerable: boolean;
/**
* Race type code
*/
raceTypeCode: typeof RaceTypeCodeEnum;
/**
* Array with the current selections of the RaceCard
*/
selections: Selections;
/**
* Flag to activate a key column
*/
isKey: boolean;
/**
* Number of selection columns
*/
numColumns: number;
/**
* Calback to run when user selects a runner
*/
onRunnerSelect: BinaryFn<string, number, unknown>;
/**
* For the first element of inline handicapping be bold
*/
firstHandicapBold?: boolean;
/**
**************** talent pick tool props *******************
*/
/**
* Activate favorite selection
*/
isFavoriteSelectionActive: boolean;
/**
* Selected the favorite
*/
favoriteSelections: string[][];
/**
* Runner Line expanded
*/
expandedRunner: string;
/**
* Runner Line expand callBack
*/
expandLine: UnaryFn<typeof ExpandLineArgs, void>;
/**
* Render Expanded info
*/
expandInfo: QuadFn<
string,
number,
(typeof RaceCardBettingInterest)[],
string,
Element | void
>;
/**
Arrow direction to use on inline pp
*/
inLinePastPerformance: boolean;
/**
is track master pick
*/
isTrackMasterPick: boolean;
/**
is numberFire pick
*/
isNumberFirePick: boolean;
/**
is Racing And Sports
*/
isRacingAndSports: boolean;
/**
Handicapping Sort Mode
*/
handicappingSortMode: typeof HandicapSortOptionsType;
/**
Reveals if the user may see the inLinePastPerformance or be redirected to the race card on the respective runnerLines
*/
redirectToRaceCard: boolean;
/**
The race url to be redirected to
*/
raceUrl: string;
/**
* Has TrackMaster information
*/
hasTrackMasterInfo: boolean;
/**
* On runner selection for top races
*/
onRunnerSelection: TernaryFn<typeof RacePanelLink, number, string, void>;
/**
* The Race this runner list is on
*/
race: typeof RacePanelLink | null | void;
/**
* hover effect on runner bio
*
*/
hasHover: boolean;
/**
* Show runner line active state
*/
showRunnerLineActiveState: boolean;
/**
* Track data source
*/
trackDataSource: string;
/**
* Current Race info
*/
currentRace: typeof RaceProgram;
handicappingRunnerFlags: HandicappingRunnerFlags;
scrollRunnerPP: boolean;
scrollOffset: number;
}
type State = {
doesSilkLoads: boolean;
};
const getRunnerSelections = (biNumber: number, selections: Selections) =>
selections.map((column) => indexOf(column, toString(biNumber)) >= 0);
const getFavoriteSelections = (biNumber: number, leg: string[]) =>
leg.indexOf(`${biNumber}`) >= 0;
export default class RunnerList extends Component<Props, State> {
static defaultProps = {
runners: [],
leg: 0,
isLeg: false,
isWagerable: true,
onRunnerSelect: noop,
raceTypeCode: "T",
selections: [[]],
numColumns: 1,
isKey: false,
firstHandicapBold: false,
isFavoriteSelectionActive: false,
favoriteSelections: [[]],
expandedRunner: "",
expandLine: noop,
expandInfo: noop,
inLinePastPerformance: false,
isTrackMasterPick: false,
isNumberFirePick: false,
isRacingAndSports: false,
handicappingSortMode: "saddlecloth",
redirectToRaceCard: false,
raceUrl: "/",
hasTrackMasterInfo: true,
onRunnerSelection: noop,
race: null,
hasHover: false,
showRunnerLineActiveState: true,
trackDataSource: "",
currentRace: {},
handicappingRunnerFlags: {
title: "",
subtitle: "",
subtitleRunnerFlags: "",
flags: []
},
scrollRunnerPP: false,
scrollOffset: 0
};
state: State = {
doesSilkLoads: true
};
componentDidMount() {
this.setDoesSilkLoads();
}
shouldComponentUpdate(nextProps: Props, nextState: State) {
return (
this.state.doesSilkLoads !== nextState.doesSilkLoads ||
!isEqual(nextProps, this.props)
);
}
componentDidUpdate(prevProps: Props) {
if (!isEqual(this.props.currentRace, prevProps.currentRace)) {
this.setDoesSilkLoads();
}
}
setDoesSilkLoads() {
doesSilkLoads(this.props.runners).then((silkLoads: boolean) => {
if (this.state.doesSilkLoads !== silkLoads) {
// eslint-disable-next-line react/no-did-update-set-state
this.setState({
doesSilkLoads: silkLoads
});
}
});
}
renderRunners() {
return (
this.props.runners &&
this.props.runners.map((bi: typeof RaceCardBettingInterest) =>
bi.runners.map((runner: typeof RaceCardRunner) => (
<RunnerLine
race={this.props.race}
runners={this.props.runners}
key={`runner-${runner.runnerId}`}
selections={getRunnerSelections(bi.biNumber, this.props.selections)}
runnerData={runner}
isFavorite={bi.isFavorite}
biNumber={bi.biNumber}
leg={this.props.leg}
raceTypeCode={this.props.raceTypeCode}
currentOddsNumerator={get(bi, "currentOdds.numerator")}
currentOddsDenominator={get(bi, "currentOdds.denominator")}
morningLineOddsNumerator={get(bi, "morningLineOdds.numerator")}
morningLineOddsDenominator={get(bi, "morningLineOdds.denominator")}
isWagerable={this.props.isWagerable}
onRunnerSelect={this.props.onRunnerSelect}
numColumns={this.props.numColumns}
isKey={this.props.isKey}
isLeg={this.props.isLeg}
expandedRunner={this.props.expandedRunner}
expandLine={this.props.expandLine}
expandInfo={this.props.expandInfo}
firstHandicapBold={this.props.firstHandicapBold}
isFavoriteSelectionActive={this.props.isFavoriteSelectionActive}
onRunnerSelection={this.props.onRunnerSelection}
favoriteSelection={
this.props.isFavoriteSelectionActive &&
getFavoriteSelections(
bi.biNumber,
this.props.favoriteSelections[this.props.leg]
)
}
inLinePastPerformance={this.props.inLinePastPerformance}
isRunnerTrackMasterPick={this.props.isTrackMasterPick}
isRunnerNumberFirePick={this.props.isNumberFirePick}
isRunnerRacingAndSports={this.props.isRacingAndSports}
handicappingSortMode={this.props.handicappingSortMode}
redirectToRaceCard={this.props.redirectToRaceCard}
raceUrl={this.props.raceUrl}
hasTrackMasterInfo={this.props.hasTrackMasterInfo}
hasHover={this.props.hasHover}
showActiveState={this.props.showRunnerLineActiveState}
trackDataSource={this.props.trackDataSource}
currentRace={this.props.currentRace}
handicappingRunnerFlags={this.props.handicappingRunnerFlags}
scrollRunnerPP={this.props.scrollRunnerPP}
scrollOffset={this.props.scrollOffset}
doesSilkLoads={this.state.doesSilkLoads}
/>
))
)
);
}
render() {
return !!this.props.runners.length && <tbody>{this.renderRunners()}</tbody>;
}
}
webpack://frontend-mybets/../../packages/tvg-lib-utils/handicappingUtils.js
import { get } from "lodash";
import sortRunnerList from "./handicappingSort";
export const getHandicappingMode = (logged, mode, isGreyhound) => {
if (logged) {
if (isGreyhound && mode !== "basic") {
return "advanced";
}
return mode;
}
return "basic";
};
const getSnapShotHandicapping = (runner) => {
const handicapping = [];
// power
const power = get(runner, "handicapping.snapshot.powerRating");
if (power !== undefined && power !== null && power !== "") {
handicapping.push({ key: "power", value: power.toString() });
} else {
handicapping.push({ key: "power", value: "-" });
}
// horse wins and horse starts
const horseWins = get(runner, "handicapping.snapshot.horseWins");
const horseStarts = get(runner, "handicapping.snapshot.horseStarts");
let winStarts = "";
if (horseWins !== undefined && horseWins !== null && horseWins !== "") {
winStarts += horseWins;
} else {
winStarts += "-";
}
winStarts += "/";
if (horseStarts !== undefined && horseStarts !== null && horseStarts !== "") {
winStarts += horseStarts;
} else {
winStarts += "-";
}
handicapping.push({ key: "winStarts", value: winStarts });
// Days off
const daysOff = get(runner, "handicapping.snapshot.daysOff");
if (daysOff !== undefined && daysOff !== null && daysOff !== "") {
handicapping.push({ key: "daysOff", value: `${daysOff}` });
} else {
handicapping.push({ key: "daysOff", value: "-" });
}
return handicapping;
};
export const addOptions = (keys, mappingObject) => {
const handicapping = [];
keys.forEach((option) => {
const defaultValue = "-";
const value = get(mappingObject, `${option}`, defaultValue);
handicapping.push({
key: option,
value: value === "" ? defaultValue : value
});
});
return handicapping;
};
const buildHandicapping = (key, runner, isGreyhound = false) => {
let optionsArray;
switch (key) {
case "advanced":
optionsArray = isGreyhound
? ["jockey", "trainer", "weight", "age", "sex", "sire", "dam"]
: [
"age",
"sex",
"jockey",
"trainer",
"med",
"weight",
"sire",
"dam",
"damSire",
"ownerName"
];
return addOptions(optionsArray, runner);
case "snapshot":
return getSnapShotHandicapping(runner);
case "speed":
optionsArray = [
"handicapping.speedAndClass.avgSpeed",
"handicapping.speedAndClass.avgDistance",
"handicapping.speedAndClass.highSpeed",
"handicapping.speedAndClass.avgClassRating",
"handicapping.speedAndClass.lastClassRating"
];
return addOptions(optionsArray, runner);
case "pace":
optionsArray = [
"handicapping.averagePace.numRaces",
"handicapping.averagePace.early",
"handicapping.averagePace.middle",
"handicapping.averagePace.finish"
];
return addOptions(optionsArray, runner);
case "stats":
optionsArray = [
"handicapping.jockeyTrainer.jockeyName",
"handicapping.jockeyTrainer.trainerName",
"handicapping.jockeyTrainer.starts",
"handicapping.jockeyTrainer.wins",
"handicapping.jockeyTrainer.places",
"handicapping.jockeyTrainer.shows"
];
return addOptions(optionsArray, runner);
default:
optionsArray = ["jockey", "trainer"];
return addOptions(optionsArray, runner);
}
};
export const buildRunners = (
key,
runners,
isGreyhound = false,
trackCode = "",
showPickNumber = false,
isJockeyChangeShown = false
) => {
if (!trackCode.includes("HKS") && !trackCode.includes("HKH")) {
return (
runners &&
runners.map((runner) => ({
...runner,
hasJockeyChanges: isJockeyChangeShown
? !!runner.hasJockeyChanges
: false,
handicapping: buildHandicapping(key, runner, isGreyhound),
masterPickNumber: showPickNumber
? get(runner, "handicapping.freePick.number")
: -1
}))
);
}
const newRunners = [];
runners.forEach((runner) => {
if (!get(runner, "runnerId", "").includes("S")) {
newRunners.push({
...runner,
hasJockeyChanges: isJockeyChangeShown
? !!runner.hasJockeyChanges
: false,
handicapping: buildHandicapping(key, runner, isGreyhound),
masterPickNumber: showPickNumber
? get(runner, "handicapping.freePick.number")
: -1
});
}
});
return newRunners;
};
export const getRunnersInfoForRace = (
bettingInterests = [],
key = "basic",
isGreyhound = false,
trackCode = "",
showPickNumber = false,
isJockeyChangeShown = false,
handicappingMode = "basic",
handicappingSortMode = "saddlecloth"
) => {
const mappedBettingInterests = bettingInterests.map((bettingInterest) => ({
biNumber: bettingInterest.biNumber,
currentOdds: bettingInterest.currentOdds,
morningLineOdds: bettingInterest.morningLineOdds,
recentOdds: bettingInterest.recentOdds,
isFavorite: bettingInterest.isFavorite,
runners: buildRunners(
key,
bettingInterest.runners,
isGreyhound,
trackCode,
showPickNumber,
isJockeyChangeShown
)
}));
return handicappingSortMode &&
handicappingSortMode !== "saddlecloth" &&
!isGreyhound
? sortRunnerList(
mappedBettingInterests,
handicappingMode,
handicappingSortMode
)
: mappedBettingInterests;
};
const getRunnersInfoForRaceCard = (
bettingInterestsMatrix = [],
key = "basic",
isGreyhound = false,
trackCode = "",
showPickNumber = false,
isJockeyChangeShown = false,
handicappingMode = "basic",
handicappingSortMode = "saddlecloth"
) =>
bettingInterestsMatrix.map((bettingInterests) =>
getRunnersInfoForRace(
bettingInterests,
key,
isGreyhound,
trackCode,
showPickNumber,
isJockeyChangeShown,
handicappingMode,
handicappingSortMode
)
);
export const isFirstElementBold = (key) => ["basic", "stats"].includes(key);
export const doesSilkLoads = (bettingInterests, isRacecard = false) => {
if (!!bettingInterests && bettingInterests.length > 0) {
const runnerList = isRacecard
? get(bettingInterests, "[0].[0].runners", {})
: get(bettingInterests, "[0].runners", {});
const silkUrl = get(runnerList, "[0].timeform.silkUrlSvg");
if (silkUrl) {
return new Promise((resolve) => {
const img = new Image();
// eslint-disable-next-line
img.onerror = img.onabort = () => {
resolve(false);
};
img.onload = () => {
resolve(true);
};
img.src = silkUrl;
});
}
}
return Promise.resolve(false);
};
export default getRunnersInfoForRaceCard;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MessageBox/styles.js
import tvgConf from "@tvg/conf";
import buildColor from "../../_static/ColorPalette";
import {
info,
infoOutline,
exclamation,
warningOutline,
success,
successOutline,
error,
glassyError,
checkPromo,
personRightArrow
} from "../../_static/Icons/icons";
import { infoOutline as infoOutlineDuotone } from "../../_static/Icons/iconsDuotone";
const styleMap = {
default: {
icon: info,
fill: buildColor("blue_accent", "500"),
background: buildColor("white", "0")
},
infoWhiteBackground: {
icon: info,
fill: buildColor("blue_accent", "500"),
background: buildColor("white", "100")
},
info: {
icon: info,
fill: buildColor("blue_accent", "500"),
background: buildColor("blue_accent", "100")
},
infoNoBackground: {
icon: info,
fill: buildColor("blue_accent", "500"),
background: buildColor("white", "0")
},
warning: {
icon: exclamation,
fill: buildColor("yellow", "500"),
background: buildColor("yellow", "100")
},
success: {
icon: success,
fill: buildColor("green", "600"),
background: buildColor("green", "100")
},
error: {
icon: error,
fill: buildColor("red", "500"),
background: buildColor("red", "100")
},
promos: {
icon: checkPromo,
fill: buildColor("green", "100"),
background: buildColor("green", "000"),
borderColor: buildColor("green", "200"),
onlyBorderBottom: tvgConf().device === "desktop",
borderRadius: tvgConf().device === "desktop" ? "4px 4px 0 0" : "4px",
viewBoxSize: 16
},
referral: {
icon: personRightArrow,
strokeColorList: [null, null, buildColor("green", "600")],
fill: buildColor("green", "100"),
background: buildColor("green", "000"),
viewBoxSize: 16,
onlyBorderBottom: tvgConf().device === "desktop",
borderColor: buildColor("green", "200"),
borderRadius: tvgConf().device === "desktop" ? "4px 4px 0 0" : "4px"
},
promosInvalid: {
icon: infoOutlineDuotone,
background: buildColor("blue_accent", "000"),
onlyBorderBottom: tvgConf().device === "desktop",
borderColor: buildColor("blue_accent", "200"),
borderRadius: tvgConf().device === "desktop" ? "4px 4px 0 0" : "0",
colorList: [
buildColor("blue_accent", "200"),
buildColor("blue_accent", "600")
]
},
preferencesInfo: {
icon: infoOutlineDuotone,
background: buildColor("blue_accent", "000"),
borderColor: buildColor("blue_accent", "200"),
borderRadius: "4px",
colorList: [
buildColor("blue_accent", "200"),
buildColor("blue_accent", "600")
],
color: buildColor("blue_accent", "600")
}
};
// todo: for now only info, warning and success have the alt style props
export const styleMapAlt = {
default: {
icon: info,
fill: buildColor("blue_accent", "500"),
background: buildColor("white", "0")
},
infoWhiteBackground: {
icon: info,
fill: buildColor("blue_accent", "500"),
background: buildColor("white", "100")
},
info: {
icon: infoOutline,
fill: buildColor("blue_accent", "600"),
iconBackground: buildColor("blue_accent", "200"),
borderColor: buildColor("blue_accent", "200"),
background: buildColor("blue_accent", "000")
},
infoNoBackground: {
icon: info,
fill: buildColor("blue_accent", "500"),
background: buildColor("white", "0")
},
warning: {
icon: warningOutline,
fill: buildColor("orange", "700"),
borderColor: buildColor("orange", "200"),
background: buildColor("orange", "000")
},
success: {
icon: successOutline,
fill: buildColor("green", "600"),
iconBackground: buildColor("green", "100"),
borderColor: buildColor("green", "200"),
background: buildColor("green", "000")
},
error: {
icon: glassyError,
fill: buildColor("red", "600"),
borderColor: buildColor("red", "200"),
background: buildColor("red", "000")
},
promos: {
icon: checkPromo,
fill: buildColor("green", "100"),
background: buildColor("green", "100"),
viewBoxSize: 16
},
referral: {
icon: personRightArrow,
strokeColorList: [null, null, buildColor("green", "600")],
fill: buildColor("green", "100"),
background: buildColor("green", "100"),
viewBoxSize: 16
},
promosInvalid: {
icon: infoOutlineDuotone,
background: buildColor("blue_accent", "000"),
colorList: [
buildColor("blue_accent", "200"),
buildColor("blue_accent", "600")
]
},
preferencesInfo: {
icon: infoOutlineDuotone,
background: buildColor("blue_accent", "000"),
borderColor: buildColor("blue_accent", "200"),
borderRadius: "4px",
colorList: [
buildColor("blue_accent", "200"),
buildColor("blue_accent", "600")
],
color: buildColor("blue_accent", "600")
}
};
export default styleMap;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MessageBox/styled-components.js
import styled, { css } from "styled-components";
import { Link } from "react-router-dom";
import Button from "../../_atom/Buttons/button";
import Icon from "../../_static/Icons";
import { fontNormal, fontMedium } from "../../_static/Typography";
import buildColor from "../../_static/ColorPalette";
export const HorizontalMessageBox = styled(Link)`
${({ customStyle }) =>
customStyle.addonStyle
? `
background-color: ${customStyle.addonStyle.backgroundColor};
color: ${customStyle.addonStyle.color};
`
: `
background-color: ${customStyle.background};
color: ${buildColor("grey", "900")};
`}
padding: ${(props) => {
if (props.isAlt) return "12px";
if (
props.type === "promos" ||
props.type === "referral" ||
props.type === "promosInvalid"
)
return "12px";
return props.hasIcon && !props.hasTitle ? "12px" : "8px";
}};
border-radius: ${({ customStyle }) =>
customStyle.borderRadius ? `${customStyle.borderRadius}` : "2px"};
display: flex;
text-decoration: none;
flex-direction: column;
${(props) =>
props.hasBorderTop &&
css`
border-top: 1px solid
${props.isAlt && props.customStyle.borderColor
? props.customStyle.borderColor
: buildColor("grey", "300")};
`};
${(props) =>
props.hasBorderBottom &&
css`
border-bottom: 1px solid
${props.isAlt && props.customStyle.borderColor
? props.customStyle.borderColor
: buildColor("grey", "300")};
`};
${(props) =>
props.hasMarginTop &&
css`
margin-top: ${(props.hasMarginsLarge && "20") || "8"}px;
`};
${(props) =>
props.hasMarginBottom &&
css`
margin-bottom: ${(props.hasMarginsLarge && "20") || "8"}px;
`};
${(props) => css`
border: ${props.customStyle.borderColor
? `1px solid ${props.customStyle.borderColor}`
: "none"};
`}
${(props) =>
props.customStyle.onlyBorderBottom
? css`
border: none;
border-bottom: ${props.customStyle.borderColor
? `1px solid ${props.customStyle.borderColor}`
: "none"};
`
: ""}
${(props) =>
props.isAlt &&
css`
border: ${props.customStyle.borderColor
? `1px solid ${props.customStyle.borderColor}`
: "none"};
${!props.hasBorderLeft && "border-left: none;"};
${!props.hasBorderRight && "border-right: none;"};
${!props.hasBorderTop && "border-top: none;"};
${!props.hasBorderBottom && "border-bottom: none;"};
border-radius: ${props.hasRoundCorners ? "4px" : "0"};
${props.hasDropShadow &&
css`
box-shadow:
0 4px 4px rgb(0 0 0 / 10%),
0 4px 6px rgb(0 0 0 / 5%);
`};
color: ${props.customStyle.fill || "none"};
font-family: ${fontNormal};
span {
font-family: ${fontNormal};
}
`};
${(props) =>
props.customStyle &&
props.customStyle.iconBackground &&
css`
svg {
border-radius: 50%;
background-color: ${({ customStyle }) =>
customStyle && customStyle.iconBackground
? customStyle.iconBackground
: "transparent"};
}
`};
`;
export const IconTextWrapper = styled.div`
display: flex;
${({ horizontalPadding }) =>
horizontalPadding ? `padding: 0 ${horizontalPadding}px;` : ""}
${({ alignCenter }) => alignCenter && `align-items: center;`}
`;
export const MessageIcon = styled(Icon).attrs({
"data-qa-label": "messageBox-icon"
})`
flex-shrink: 0;
`;
export const VerticalMessageBox = styled(Link)`
display: flex;
flex-direction: column;
align-items: center;
flex: 1 0 0;
justify-content: center;
text-decoration: none;
`;
export const TextWrapper = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
flex-grow: 1;
font-size: 14px;
color: ${(props) => (props.isAlt ? "inherit" : buildColor("grey", "900"))};
text-align: left;
margin-left: ${(props) => props.hasIcon && "12px"};
line-height: 17px;
min-height: ${(props) => props.hasIcon && "16"};
font-family: ${fontNormal};
a {
text-decoration: underline;
color: initial;
}
b {
vertical-align: bottom;
}
`;
export const VerticalTextWrapper = styled.div`
font-size: 12px;
line-height: 16px;
color: ${buildColor("grey", "900")};
text-align: center;
margin-top: 8px;
`;
export const MessageTitle = styled.div`
${({ isAlt }) =>
isAlt
? css`
font-weight: 500;
font-weight: normal;
text-transform: none;
font-family: ${fontMedium};
margin-bottom: 4px;
`
: css`
text-transform: uppercase;
font-weight: bold;
`};
${({ isPromo }) =>
isPromo &&
css`
font-family: ${fontNormal};
font-weight: 400;
font-size: 14px;
text-transform: none;
color: ${buildColor("green", "600")};
`};
${({ promosInvalid }) =>
promosInvalid &&
css`
font-family: ${fontNormal};
font-weight: 400;
font-size: 14px;
text-transform: none;
color: ${buildColor("blue_accent", "600")};
`};
${({ color }) =>
color &&
css`
color: ${color};
`};
`;
export const MessageContent = styled.span`
${({ color }) =>
color &&
css`
color: ${color};
`};
`;
export const CloseBtn = styled.button`
cursor: pointer;
width: 16px;
height: 16px;
margin-left: 12px;
background: none;
`;
export const EditBtn = styled.button`
cursor: pointer;
background: none;
outline: none;
${({ typeButton }) =>
(typeButton === "promos" && `color: ${buildColor("green", "900")}`) ||
(typeButton === "referral" && `color: ${buildColor("green", "900")}`) ||
typeButton === "promosInvalid"
? css`
color: ${buildColor("blue_accent", "500")};
font-family: ${fontMedium};
font-weight: 500;
font-size: 14px;
`
: ""}
`;
export const ArrowIconContainer = styled.div`
width: 16px;
height: 100%;
display: flex;
align-items: center;
`;
export const LogSignupButtonWrapper = styled.div`
margin-top: 12px;
display: flex;
justify-content: flex-start;
padding-left: 16px;
`;
export const LogSignupButton = styled(Button)`
margin-left: 8px;
font-size: 14px;
text-transform: capitalize;
font-family: ${fontMedium};
`;
export const LogSignupButtonInner = styled.span`
line-height: 14px;
height: 12px;
`;
export const LockIcon = styled(Icon)`
margin-right: 4px;
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/MessageBox/index.jsx
import React, { PureComponent } from "react";
import { has, noop } from "lodash";
import buildColor from "../../_static/ColorPalette";
import Icon from "../../_static/Icons";
import { arrowRight, close, lock } from "../../_static/Icons/icons";
import messageBoxStylesDefault, {
styleMapAlt as messageBoxStylesAlt
} from "./styles";
import {
HorizontalMessageBox,
VerticalMessageBox,
IconTextWrapper,
MessageIcon,
TextWrapper,
MessageTitle,
MessageContent,
CloseBtn,
EditBtn,
VerticalTextWrapper,
LogSignupButtonWrapper,
LogSignupButton,
LogSignupButtonInner,
LockIcon,
ArrowIconContainer
} from "./styled-components";
export default class MessageBox extends PureComponent {
renderLoginSignupButton() {
const { onLoginCallback, onSignupCallback } = this.props;
const LoginBtn = has(this.props, "onLoginCallback") &&
typeof onLoginCallback === "function" && (
<LogSignupButton
qaLabel="messageBox-loginBtn"
type="secondary"
onClick={onLoginCallback}
isBold={false}
>
<LockIcon size={16} icon={lock} color={buildColor("grey", "900")} />
<LogSignupButtonInner>log in</LogSignupButtonInner>
</LogSignupButton>
);
const SignupBtn = has(this.props, "onSignupCallback") &&
typeof onSignupCallback === "function" && (
<LogSignupButton
qaLabel="messageBox-signUpBtn"
onClick={onSignupCallback}
isBold={false}
>
sign up
</LogSignupButton>
);
return (
(LoginBtn || SignupBtn) && (
<LogSignupButtonWrapper>
{LoginBtn}
{SignupBtn}
</LogSignupButtonWrapper>
)
);
}
renderMessage(style) {
const { message: PropsMessage } = this.props;
const message = React.isValidElement(PropsMessage) ? (
<MessageContent color={style.color}>{PropsMessage}</MessageContent>
) : (
// eslint-disable-next-line react/no-danger
<MessageContent
color={style.color}
dangerouslySetInnerHTML={{ __html: PropsMessage }}
/>
);
return message;
}
getMsgSubtypeProps() {
const msgSubtypePropsDefault = {
hasBorderLeft: false,
hasBorderRight: false,
hasBorderBottom: false,
hasBorderTop: false,
hasRoundCorners: false,
hasDropShadow: false
};
const msgSubtypeProps = {
contextual: msgSubtypePropsDefault,
fullWith: {
hasBorderTop: true,
hasBorderBottom: true
},
floating: {
hasBorderLeft: true,
hasBorderRight: true,
hasBorderTop: true,
hasBorderBottom: true,
hasRoundCorners: true
},
scratchcard: {
hasBorderLeft: true,
hasBorderRight: true,
hasBorderTop: true,
hasBorderBottom: true,
hasRoundCorners: true,
hasDropShadow: true
}
};
return this.props.subtype &&
this.props.subtype !== "custom" &&
msgSubtypeProps[this.props.subtype]
? { ...msgSubtypePropsDefault, ...msgSubtypeProps[this.props.subtype] }
: {};
}
renderHorizontalMessage(style, hasIcon, hasTitle) {
const {
children,
title,
url,
className,
type,
subtype,
onClick,
hasBorderBottom,
hasBorderTop,
hasMarginBottom,
hasMarginTop,
hasMarginsLarge,
horizontalPadding,
isAlt,
onClose,
hasEdit,
editHandleClick,
alignCenter,
fullBoxOnClick
} = this.props;
const Message = url
? HorizontalMessageBox
: HorizontalMessageBox.withComponent("div");
const messageProps = url
? { ...this.getMsgSubtypeProps(), to: url, onClick }
: { ...this.getMsgSubtypeProps() };
return (
<Message
customStyle={style}
hasIcon={hasIcon}
hasTitle={hasTitle}
type={type}
className={className}
data-qa-label={`messageBox-${type}`}
hasBorderBottom={hasBorderBottom}
hasBorderTop={hasBorderTop}
hasMarginTop={hasMarginTop}
hasMarginBottom={hasMarginBottom}
hasMarginsLarge={hasMarginsLarge}
onClick={fullBoxOnClick}
isAlt={isAlt}
{...messageProps}
>
<IconTextWrapper
alignCenter={alignCenter}
horizontalPadding={horizontalPadding}
>
{hasIcon && (
<MessageIcon
icon={style.icon}
strokeColorList={style.strokeColorList || []}
size={16}
color={style.fill}
colorList={style.colorList || []}
qaLabel="messageBox-icon"
viewBoxSize={style.viewBoxSize || 1024}
/>
)}
<TextWrapper
hasIcon={hasIcon}
data-qa-label="messageBox-text"
isAlt={isAlt}
>
{title && (
<MessageTitle
data-qa-label="messageBox-title"
isAlt={isAlt}
isPromo={type === "promos" || type === "referral"}
promosInvalid={type === "promosInvalid"}
color={style.color}
>
{title}
</MessageTitle>
)}
{this.renderMessage(style)}
</TextWrapper>
{onClose && (
<CloseBtn onClick={onClose} data-qa-label="messageBox-closeBtn">
<Icon icon={close} size={16} color={buildColor("blue", "800")} />
</CloseBtn>
)}
{hasEdit && (
<EditBtn
type="button"
onClick={editHandleClick}
data-qa-label="messageBox-editBtn"
typeButton={type}
>
{type === "promosInvalid" ? "Change" : "Edit"}
</EditBtn>
)}
{url && (
<ArrowIconContainer>
<Icon
icon={arrowRight}
size={16}
color={buildColor("blue", "800")}
/>
</ArrowIconContainer>
)}
</IconTextWrapper>
{this.renderLoginSignupButton()}
{children}
</Message>
);
}
renderVerticalMessage(style) {
const { children, title, url, className, type, hasIcon } = this.props;
const Message = url
? VerticalMessageBox
: VerticalMessageBox.withComponent("div");
const messageProps = url ? { to: url } : {};
return (
<Message
className={className}
data-qa-label={`messageBox-${type}`}
{...messageProps}
>
{hasIcon && (
<MessageIcon
icon={style.icon}
size={16}
color={style.fill}
qaLabel="messageBox-icon"
/>
)}
<VerticalTextWrapper data-qa-label="messageBox-text">
{title && (
<MessageTitle
isVertical
data-qa-label="messageBox-title"
color={style.color}
>
{title}
</MessageTitle>
)}
{this.renderMessage(style)}
</VerticalTextWrapper>
{this.renderLoginSignupButton()}
{children}
</Message>
);
}
render() {
const { isAlt, addonStyle, type, isVertical, hasIcon, title } = this.props;
const messageBoxStyles = isAlt
? messageBoxStylesAlt
: messageBoxStylesDefault;
const style = addonStyle
? {
...messageBoxStyles[type],
addonStyle
}
: messageBoxStyles[type];
if (isVertical) {
return this.renderVerticalMessage(style);
}
return this.renderHorizontalMessage(style, hasIcon, !!title);
}
}
MessageBox.defaultProps = {
type: "default",
subtype: "custom",
message: "",
className: "",
hasIcon: true,
hasBorderBottom: false,
hasBorderTop: false,
isVertical: false,
title: null,
children: null,
onClick: noop,
onClose: null,
onLoginCallback: null,
onSignupCallback: null,
url: null,
hasMarginTop: false,
hasMarginBottom: false,
hasEdit: false,
addonStyle: null,
isAlt: false
};
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/components/RaceMessageRedirect/styled-components.ts
import styled from "styled-components";
import Icon from "@tvg/design-system/src/components/icon";
export const RaceButtonsContainer = styled.div<{
isWarning?: boolean;
hasBorderBottom?: boolean;
}>`
margin: 0;
background: ${({ isWarning, theme }) =>
isWarning
? theme.colorTokens.component.tag.offer_subtle.background
: theme.colorTokens.component.button.tertiary.background.active};
padding: 0 8px 12px 32px;
border-bottom: ${({ hasBorderBottom, theme }) =>
hasBorderBottom && `1px solid ${theme.colorTokens.component.input.base}`};
& > :first-child {
margin-right: 8px;
}
`;
export const ArrowIcon = styled(Icon)`
margin-left: 4px;
`;
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/components/RaceMessageRedirect/index.tsx
import React, { PureComponent } from "react";
import { noop } from "lodash";
import ButtonLink from "@tvg/atomic-ui/_atom/Buttons/buttonLink";
import MessageBox from "@tvg/atomic-ui/_molecule/MessageBox";
import { NullaryFn } from "@tvg/ts-types/Functional";
import { RaceButtonsContainer, ArrowIcon } from "./styled-components";
interface Props {
keyLabel: string;
title: string;
message: string;
isWarning: boolean;
nextRaceUrl: string;
homeUrl: string;
tracksUrl: string;
hasBorderBottom: boolean;
onNextRaceClick: NullaryFn<unknown>;
onChangeTrackClick: NullaryFn<unknown>;
}
export default class RaceMessageRedirect extends PureComponent<Props> {
static defaultProps = {
keyLabel: "race-message-redirect",
title: "",
message: "",
isWarning: false,
homeUrl: "/",
tracksUrl: "",
nextRaceUrl: "",
hasBorderBottom: false,
onNextRaceClick: noop,
onChangeTrackClick: noop
};
renderButtons = () => (
<RaceButtonsContainer
isWarning={this.props.isWarning}
hasBorderBottom={this.props.hasBorderBottom}
>
{!this.props.tracksUrl && !this.props.nextRaceUrl && (
<ButtonLink type="secondary" url={this.props.homeUrl}>
Return to Homepage
</ButtonLink>
)}
{this.props.tracksUrl && (
<ButtonLink
type="secondary"
url={this.props.tracksUrl}
onClick={this.props.onChangeTrackClick}
>
Change Track
</ButtonLink>
)}
{this.props.nextRaceUrl && (
<ButtonLink
type="secondary"
url={this.props.homeUrl}
onClick={this.props.onNextRaceClick}
>
<span>Next Race</span>
<ArrowIcon
name="arrowRight"
lineColor="content.onLight"
size="s"
shouldUseColorTokens
/>
</ButtonLink>
)}
</RaceButtonsContainer>
);
render() {
return (
<>
<MessageBox
key={this.props.keyLabel}
type={this.props.isWarning ? "warning" : "info"}
message={this.props.message}
title={this.props.title}
/>
{this.renderButtons()}
</>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/RaceResultsTop/styled-components.js
import styled, { css } from "styled-components";
import buildColor from "../../_static/ColorPalette";
import { buildText } from "../../_atom/Text";
import { fontMedium } from "../../_static/Typography";
const HeaderText = buildText({
tag: "div",
fontSize: 14,
color: buildColor("grey", "900")
});
export const HeaderContainer = styled(HeaderText)`
background-color: ${buildColor("blue", "000")};
padding: 12px;
font-weight: 500;
font-family: ${fontMedium};
display: grid;
grid-template-columns: 1fr repeat(3, 55px);
grid-column-gap: 20px;
`;
export const HeaderColumn = styled.div`
text-align: right;
${({ gridPosition }) =>
gridPosition &&
css`
grid-column-start: ${gridPosition};
`}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/RaceResultsTop/index.jsx
// todo: replace RaceResultsHeader with this
// legacy component: RaceResultsHeader
// feature toggle: enableRaceResultsReDesign
import React from "react";
import { HeaderContainer, HeaderColumn } from "./styled-components";
const getGridPosition = (hasPlace, hasShow) => {
if (!hasPlace && !hasShow) {
return 4;
}
if ((!hasShow && hasPlace) || (!hasPlace && hasShow)) {
return 3;
}
return false;
};
const DEFAULT_GRID_POSITION = 2;
const RaceResultsTop = ({
betAmount,
hasWin,
hasPlace,
hasShow,
racePayoffsShift
}) => (
<HeaderContainer data-qa-label="RaceResultsTop">
<div>Position</div>
{hasWin && betAmount && (
<HeaderColumn
gridPosition={
racePayoffsShift
? getGridPosition(hasPlace, hasShow)
: DEFAULT_GRID_POSITION
}
>
${betAmount} Win
</HeaderColumn>
)}
{hasPlace && betAmount && <HeaderColumn>${betAmount} Place </HeaderColumn>}
{hasShow && betAmount && <HeaderColumn>${betAmount} Show</HeaderColumn>}
</HeaderContainer>
);
RaceResultsTop.defaultProps = {
betAmount: 2,
hasWin: true,
hasPlace: true,
hasShow: true,
racePayoffsShift: false
};
export default RaceResultsTop;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/BeatenDistance/styled-components.js
import styled from "styled-components";
import { fontNormal } from "../../_static/Typography";
import buildColor from "../../_static/ColorPalette";
export default styled.span`
margin-left: 5px;
font-family: ${fontNormal};
font-weight: normal;
color: ${buildColor("grey", "600")};
text-transform: lowercase;
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/BeatenDistance/index.jsx
import React, { useMemo } from "react";
import { pluralize } from "@tvg/utils/generalUtils";
import BeatenDistanceText from "./styled-components";
const computeBeatenDistance = (
shouldComputeBeatenDistanceStatus,
beatenDistance,
beatenDistanceStatus
) => {
if (shouldComputeBeatenDistanceStatus) {
if (beatenDistance < 0.5) return beatenDistanceStatus;
return `${beatenDistanceStatus} ${pluralize(
beatenDistance,
"length",
false
)}`;
}
return beatenDistanceStatus;
};
const BeatenDistance = (props) => {
const {
isWinner,
beatenDistance,
beatenDistanceStatus,
shouldComputeBeatenDistanceStatus
} = props;
return useMemo(() => {
if (!beatenDistance || !beatenDistanceStatus) return null;
let beatenDistancePre = parseFloat(beatenDistance) < 0.5 ? "by a " : "by ";
if (isWinner) {
beatenDistancePre = `won ${beatenDistancePre}`;
}
const computedBeatenDistanceAfter = computeBeatenDistance(
shouldComputeBeatenDistanceStatus,
parseFloat(beatenDistance),
beatenDistanceStatus
);
return (
<BeatenDistanceText>
{beatenDistancePre + computedBeatenDistanceAfter.toLowerCase()}
</BeatenDistanceText>
);
}, [beatenDistance, beatenDistanceStatus, shouldComputeBeatenDistanceStatus]);
};
BeatenDistance.defaultProps = {
isWinner: false,
beatenDistance: "",
beatenDistanceStatus: "",
shouldComputeBeatenDistanceStatus: false
};
export default BeatenDistance;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/RacePayoffRunnerItem/styled-components.js
import styled, { css } from "styled-components";
import buildColor from "../../_static/ColorPalette";
import { fontNormal, fontMedium, fontBold } from "../../_static/Typography";
import { buildText } from "../../_atom/Text";
export const RunnerRow = styled.article`
background-color: ${(props) =>
props.isActive
? buildColor("blue_accent", "000")
: buildColor("white", "100")};
font-size: 14px;
padding: 12px;
border-top: 1px ${(props) => (props.hasDashedBorder ? "dashed" : "solid")}
${buildColor("blue", "100")};
font-family: ${fontMedium};
border-left: ${(props) =>
props.isActive ? `2px solid ${buildColor("blue_accent", "500")}` : "0px"};
`;
export const ResultRow = styled.div`
display: grid;
grid-template-columns: 1fr repeat(3, 55px);
grid-column-gap: 20px;
`;
export const Position = styled(
buildText({
tag: "div",
fontSize: 14,
color: buildColor("grey", "900")
})
)`
font-family: ${fontBold};
color: ${(props) =>
props.isFirst ? buildColor("green", "600") : buildColor("grey", "900")};
display: inline-flex;
`;
export const MoneyWon = styled.div`
font-family: ${fontMedium};
font-size: 14px;
color: ${buildColor("grey", "800")};
text-align: right;
${({ gridPosition }) =>
gridPosition &&
css`
grid-column-start: ${gridPosition};
`}
`;
export const RunnerInfo = styled.div`
padding-top: 8px;
display: flex;
align-items: center;
`;
export const Number = styled.div`
min-width: 16px;
height: 16px;
margin-right: 8px;
`;
export const RunnerName = styled.div`
color: ${buildColor("grey", "900")};
font-size: 16px;
font-family: ${fontBold};
`;
export const Comment = styled.p`
font-family: ${fontNormal};
font-size: 14px;
color: ${buildColor("grey", "800")};
line-height: 18px;
margin-top: 4px;
&::first-letter {
text-transform: uppercase;
}
&::before {
content: '"';
}
&::after {
content: '"';
}
`;
export const Info = styled.div`
display: flex;
align-items: center;
margin-top: 8px;
font-family: ${fontNormal};
font-size: 14px;
color: ${buildColor("grey", "800")};
`;
export const InfoItem = styled.div`
&:not(:last-child) {
&::after {
content: "|";
margin: 0 4px;
}
}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/RacePayoffRunnerItem/index.jsx
// todo: replace RaceResultsRunner with this
// legacy component: RaceResultsRunner
// feature toggle: enableRaceResultsReDesign
import React, { useMemo } from "react";
import { formatCurrency, formatSequencial } from "@tvg/formatter";
import { get } from "lodash";
import RunnerNumber from "../../_atom/RunnerNumber";
import BeatenDistance from "../../_atom/BeatenDistance";
import {
RunnerRow,
ResultRow,
RunnerInfo,
Number,
RunnerName,
Position,
MoneyWon,
Comment,
Info,
InfoItem
} from "./styled-components";
const computeMoneyWon = (runner, betType) => {
const moneyWon = get(runner, betType, "");
return moneyWon > 0 ? formatCurrency(moneyWon) : "";
};
const RacePayoffRunner = (props) => {
const {
runner,
bettingInterest,
raceTypeCode,
isActive,
hasDashedBorder,
gridStartPosition,
racePayoffsShift
} = props;
return useMemo(() => {
const moneyWon = {
winPayoff: computeMoneyWon(runner, "winPayoff"),
placePayoff: computeMoneyWon(runner, "placePayoff"),
showPayoff: computeMoneyWon(runner, "showPayoff")
};
const runnerComment = get(runner, "timeform.postRaceReport");
const jockey =
get(bettingInterest, "jockey") ||
get(bettingInterest, "handicapping[0].value", "") ||
get(bettingInterest, "handicapping[0]", "");
const hasJockey =
typeof jockey === "string" && jockey !== "-" && jockey !== "";
const trainer =
get(bettingInterest, "trainer") ||
get(bettingInterest, "handicapping[1].value", "") ||
get(bettingInterest, "handicapping[1]", "");
const hasTrainer =
typeof trainer === "string" && trainer !== "-" && trainer !== "";
const isDnf = runner.finishStatus && runner.finishStatus !== null;
const isWinner = runner.finishPosition === 1;
return (
<RunnerRow
key={`position-runner-${runner.finishPosition}`}
data-qa-label="raceResultsRunner-runner"
isActive={isActive}
hasDashedBorder={hasDashedBorder}
>
<ResultRow>
<Position isFirst={runner.finishPosition === 1}>
{isDnf
? runner.finishStatus?.toUpperCase() || ""
: formatSequencial(runner.finishPosition)}
<BeatenDistance
isWinner={isWinner}
beatenDistance={
isWinner
? get(runner, "timeform.winningDistance", "")
: get(runner, "timeform.accBeatenDistance", "")
}
beatenDistanceStatus={
isWinner
? get(runner, "timeform.winningDistanceStatus", "")
: get(runner, "timeform.accBeatenDistanceStatus")
}
/>
</Position>
<MoneyWon gridPosition={gridStartPosition}>
{moneyWon.winPayoff}
</MoneyWon>
{(moneyWon.placePayoff || !racePayoffsShift) && (
<MoneyWon>{moneyWon.placePayoff}</MoneyWon>
)}
{moneyWon.showPayoff && <MoneyWon>{moneyWon.showPayoff}</MoneyWon>}
</ResultRow>
<RunnerInfo>
<Number>
<RunnerNumber
runnerId={runner.runnerNumber}
raceTypeCode={raceTypeCode}
/>
</Number>
<RunnerName>{get(runner, "runnerName", "")}</RunnerName>
</RunnerInfo>
{(hasJockey || hasTrainer) && (
<Info>
{hasJockey && <InfoItem>{jockey}</InfoItem>}
{hasTrainer && <InfoItem> {trainer}</InfoItem>}
</Info>
)}
{runnerComment && <Comment>{runnerComment}</Comment>}
</RunnerRow>
);
}, [
JSON.stringify(runner),
JSON.stringify(bettingInterest),
raceTypeCode,
isActive,
hasDashedBorder
]);
};
RacePayoffRunner.defaultProps = {
runner: {
biNumber: 0,
runnerNumber: "",
betAmount: 0,
finishPosition: 0,
placePayoff: 0,
runnerName: "",
showPayoff: 0,
winPayoff: 0,
timeform: null
},
raceTypeCode: "T",
isActive: false,
hasDashedBorder: false,
gridStartPosition: false,
racePayoffsShift: false
};
export default RacePayoffRunner;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/RaceRunners/styled-components.js
import styled from "styled-components";
import buildColor from "../../_static/ColorPalette";
import { fontMedium, fontNormal } from "../../_static/Typography";
import { buildText } from "../../_atom/Text";
import { generateTransition, easeInOut } from "../../_static/Transitions";
import Button from "../../_atom/Buttons/button";
const computeMaxHeight = (runnersNumber) => {
const averageHeight = 225;
const height = runnersNumber * averageHeight;
if (height < 1000) return "max-height: 1000px";
return `max-height: ${height}px`;
};
export const InfoContainer = styled.div`
display: flex;
flex-direction: column;
padding: 0 12px;
padding-bottom: 12px;
background-color: ${buildColor("white", "100")};
border-top: 1px solid ${buildColor("blue", "100")};
`;
export const InfoItem = styled.div`
padding-top: 12px;
display: inline-flex;
`;
export const InfoLabel = styled(
buildText({
tag: "span",
fontSize: 14,
color: buildColor("grey", "900")
})
)`
font-family: ${fontMedium};
margin-right: ${(props) => (props.isScratched ? "32px" : "8px")};
`;
export const InfoMessage = styled(
buildText({
tag: "span",
fontSize: 14,
color: buildColor("grey", "800")
})
)`
font-family: ${fontNormal};
`;
export const RunnerNumberContainer = styled.div`
margin-right: 4px;
min-width: 16px;
height: 16px;
`;
export const AnimateContainer = styled.div`
max-height: 0;
overflow: hidden;
transition: ${generateTransition(easeInOut, "max-height")};
`;
export const RunnersRestContainer = styled.div`
width: 100%;
& .animatedContainer {
${({ runnersNumber }) => computeMaxHeight(runnersNumber)}
}
&.expand-enter .animatedContainer {
max-height: 0;
}
&.expand-enter-active .animatedContainer {
${({ runnersNumber }) => computeMaxHeight(runnersNumber)}
}
&.expand-enter-done .animatedContainer {
${({ runnersNumber }) => computeMaxHeight(runnersNumber)}
}
&.expand-exit-active .animatedContainer {
max-height: 0;
}
&.expand-exit-done .animatedContainer {
max-height: 0;
}
`;
export const ShowMoreRunnersButton = styled(Button)`
height: 44px;
background-color: ${buildColor("white", "100")};
border-top: 1px solid ${buildColor("blue", "100")};
&& > span {
font-size: 14px;
color: ${buildColor("blue_accent", "500")};
font-family: ${fontMedium};
text-transform: capitalize;
font-weight: normal;
}
`;
export const ShowMoreRunnersArrow = styled.div`
display: flex;
align-items: center;
padding-left: 10px;
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/RaceRunners/index.jsx
// todo: replace RaceRunnersPayoffs with this
// legacy component: RaceRunnersPayoffs
// feature toggle: enableRaceResultsReDesign
import React, { useMemo, useState, useEffect } from "react";
import { some, get } from "lodash";
import { pluralize } from "@tvg/utils/generalUtils";
import { CSSTransition } from "react-transition-group";
import { formatSecondsToDuration } from "@tvg/formatter/dates";
import RaceResultsHeader from "../../_molecule/RaceResultsTop";
import RacePayoffRunner from "../../_molecule/RacePayoffRunnerItem";
import RunnerNumber from "../../_atom/RunnerNumber";
import { arrowDown } from "../../_static/Icons/icons";
import buildColor from "../../_static/ColorPalette";
import Icon from "../../_static/Icons";
import {
InfoContainer,
InfoItem,
InfoLabel,
InfoMessage,
RunnerNumberContainer,
AnimateContainer,
RunnersRestContainer,
ShowMoreRunnersButton,
ShowMoreRunnersArrow
} from "./styled-components";
const RESULTS_SHOWN_MAX = 4;
// some finish positions for scratched runners show up as "0"
// meaning they would show up before the actual results
// this makes the 0 finish positions show up at the end
const pushScratchedRunnersToEnd = (runners) => {
const runnersWithZeroPosition = runners
.filter((runnerBi) => runnerBi.runner.finishPosition === 0)
.sort((a, b) => a.runner.runnerNumber - b.runner.runnerNumber);
const runnersWithoutZeroPosition = runners.filter(
(runnerBi) => runnerBi.runner.finishPosition !== 0
);
return [...runnersWithoutZeroPosition, ...runnersWithZeroPosition];
};
const getWagerTypesDisplay = (results) => ({
hasWin: some(results, (r) => r.winPayoff > 0),
hasPlace: some(results, (r) => r.placePayoff > 0),
hasShow: some(results, (r) => r.showPayoff > 0)
});
// the jocker and trainer information for a runner were in the bettingInterests data
// to find the horses bettingInterest data we must use the combination of the runnerNumber and biNumber
const getRunnersWithBettingInterest = (runners, bettingInterests) => {
const runnersWithMoreInfo = runners.map((runner) => {
const { biNumber, runnerNumber } = runner;
const biRunnerObject = bettingInterests.find(
(runnerBettingInterests) => runnerBettingInterests.biNumber === biNumber
);
const biRunnersList = get(biRunnerObject, "runners", []);
const biRunner = biRunnersList.find(
(biRunnerItem) => biRunnerItem.runnerId === runnerNumber
);
return {
runner,
biRunner
};
});
return pushScratchedRunnersToEnd(runnersWithMoreInfo);
};
const getScratchedRunners = (bettingInterests) => {
let scratchedArray = [];
bettingInterests.forEach((runnerBettingInterests) => {
const runnersList = get(runnerBettingInterests, "runners", []);
const scratched = runnersList.filter((runner) => runner.scratched);
if (scratched.length > 0) scratchedArray = scratchedArray.concat(scratched);
});
return scratchedArray;
};
const getGridPosition = (hasPlace, hasShow) => {
if (!hasPlace && !hasShow) {
return 4;
}
if ((!hasShow && hasPlace) || (!hasPlace && hasShow)) {
return 3;
}
return false;
};
const RaceRunners = ({
runners,
bettingInterests,
raceTypeCode,
winningTime,
shouldExpandMoreRunners,
runnerNameHighlighted,
raceId,
racePayoffsShift
}) => {
const [showAllRunners, setShowAllRunners] = useState(false);
// when the race changes collapse expand
useEffect(() => {
setShowAllRunners(false);
}, [raceId]);
const runnersComputed = getRunnersWithBettingInterest(
runners,
bettingInterests
);
const wagerTypesDisplay = getWagerTypesDisplay(runners);
const runnersScratched = getScratchedRunners(bettingInterests);
const runnerHighlighted = runnersComputed.find(
(runner) => runner.runner.runnerName === runnerNameHighlighted
);
const renderRunnerHighlighted = () => {
if (
!runnerHighlighted ||
!runnerHighlighted.runner ||
!runnerHighlighted.biRunner
)
return null;
const { runner, biRunner } = runnerHighlighted;
return (
<RacePayoffRunner
key={`${runner.biNumber}-${runner.runnerNumber}-${runner.runnerName}`}
runner={runner}
bettingInterest={biRunner}
raceTypeCode={raceTypeCode}
isActive
hasDashedBorder
/>
);
};
const renderShowAllRunners = () => (
<ShowMoreRunnersButton
onClick={() => setShowAllRunners(!showAllRunners)}
type="secondary_alt"
hasRoundedCorners={false}
isUppercase={false}
isStretched
>
<span>See {pluralize(runnersComputed.length, "runner")}</span>
<ShowMoreRunnersArrow>
<Icon
size={13}
icon={arrowDown}
color={buildColor("blue_accent", "500")}
/>
</ShowMoreRunnersArrow>
</ShowMoreRunnersButton>
);
const renderRestRunnersWithExpand = (runnersArr) => (
<React.Fragment>
<CSSTransition
in={showAllRunners}
classNames="expand"
timeout={200}
unmountOnExit
>
<RunnersRestContainer runnersNumber={runnersArr.length}>
<AnimateContainer className="animatedContainer">
{runnersArr.map(({ runner, biRunner }) => (
<RacePayoffRunner
key={`${runner.biNumber}-${runner.runnerNumber}-${runner.runnerName}`}
runner={runner}
bettingInterest={biRunner}
raceTypeCode={raceTypeCode}
isActive={runner.runnerName === runnerNameHighlighted}
/>
))}
</AnimateContainer>
</RunnersRestContainer>
</CSSTransition>
{!showAllRunners && runnersArr.length > 0 && renderShowAllRunners()}
</React.Fragment>
);
const renderRestRunners = (runnersArr) =>
runnersArr.map(({ runner, biRunner }) => (
<RacePayoffRunner
key={`${runner.biNumber}-${runner.runnerNumber}-${runner.runnerName}`}
runner={runner}
bettingInterest={biRunner}
raceTypeCode={raceTypeCode}
isActive={runner.runnerName === runnerNameHighlighted}
/>
));
const renderRunners = () => {
const resultsTop = runnersComputed.slice(0, RESULTS_SHOWN_MAX);
const resultsAfter = runnersComputed.slice(RESULTS_SHOWN_MAX);
const shouldRenderHighlightedRunner =
shouldExpandMoreRunners &&
runnerHighlighted &&
runnerHighlighted.runner.finishPosition > RESULTS_SHOWN_MAX &&
!showAllRunners;
const DEFAULT_GRID_POSITION = 2;
return (
<section data-qa-label="raceResults">
<RaceResultsHeader
hasWin={wagerTypesDisplay.hasWin}
hasPlace={wagerTypesDisplay.hasPlace}
hasShow={wagerTypesDisplay.hasShow}
data-qa-label="raceResults-header"
racePayoffsShift={racePayoffsShift}
/>
{resultsTop.map(({ runner, biRunner }) => (
<RacePayoffRunner
key={`${runner.biNumber}-${runner.runnerNumber}-${runner.runnerName}`}
gridStartPosition={
racePayoffsShift
? getGridPosition(runner.placePayoff, runner.showPayoff)
: DEFAULT_GRID_POSITION
}
racePayoffsShift={racePayoffsShift}
runner={runner}
bettingInterest={biRunner}
raceTypeCode={raceTypeCode}
isActive={runner.runnerName === runnerNameHighlighted}
/>
))}
{shouldRenderHighlightedRunner && renderRunnerHighlighted()}
{shouldExpandMoreRunners
? renderRestRunnersWithExpand(resultsAfter)
: renderRestRunners(resultsAfter)}
</section>
);
};
const renderScratched = () => (
<InfoItem>
<InfoLabel isScratched>Scratched</InfoLabel>
{runnersScratched.map((bi) => (
<RunnerNumberContainer key={`runner-${bi.runnerId}`}>
<RunnerNumber raceTypeCode={raceTypeCode} runnerId={bi.runnerId} />
</RunnerNumberContainer>
))}
</InfoItem>
);
const renderWinningTime = () => (
<InfoItem>
<InfoLabel>Winning Time</InfoLabel>
<InfoMessage>
{winningTime &&
(typeof winningTime === "number"
? formatSecondsToDuration(winningTime)
: winningTime)}
</InfoMessage>
</InfoItem>
);
return useMemo(
() => (
<React.Fragment>
{renderRunners()}
{(runnersScratched.length > 0 || Boolean(winningTime)) && (
<InfoContainer>
{runnersScratched.length > 0 && renderScratched()}
{Boolean(winningTime) && renderWinningTime()}
</InfoContainer>
)}
</React.Fragment>
),
[
JSON.stringify(runners),
JSON.stringify(bettingInterests),
winningTime,
showAllRunners,
raceTypeCode,
shouldExpandMoreRunners,
runnerNameHighlighted,
raceId
]
);
};
RaceRunners.defaultProps = {
runners: [],
bettingInterests: [],
raceTypeCode: "T",
winningTime: 0,
shouldExpandMoreRunners: false,
runnerNameHighlighted: "",
raceId: "0",
racePayoffsShift: false
};
export default RaceRunners;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/RaceRunnersPayoffs/styled-components.js
import styled, { css } from "styled-components";
import buildColor from "../../_static/ColorPalette";
const ResultsTable = styled.table`
width: 100%;
${(props) =>
props.border &&
css`
border-bottom: 1px solid ${buildColor("grey", "300")};
`};
`;
export default ResultsTable;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/RaceResultsHeader/styled-components.js
import styled from "styled-components";
import buildColor from "../../_static/ColorPalette";
import { titleFont } from "../../_static/Typography";
export const HeaderRow = styled.tr`
background-color: ${buildColor("blue", "100")};
border-bottom: 1px solid ${buildColor("grey", "300")};
`;
export const HeaderCell = styled.th`
font-family: ${titleFont};
height: 32px;
font-size: 12px;
text-transform: uppercase;
`;
export const Position = styled(HeaderCell)`
width: 36px;
padding-left: 8px;
text-align: left;
`;
export const Number = styled(HeaderCell)`
width: 24px;
text-align: center;
`;
export const Runner = styled(HeaderCell)`
text-align: left;
padding: 0 8px;
`;
export const WagerType = styled(HeaderCell)`
width: 68px;
text-align: right;
padding-right: 8px;
`;
export const Odds = styled(HeaderCell)`
width: 44px;
padding-left: 16px;
padding-right: 8px;
`;
export const BeatenDistance = styled(HeaderCell)`
width: 70px;
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/RaceResultsHeader/index.jsx
import React, { PureComponent } from "react";
import {
HeaderRow,
Position,
Number,
Runner,
WagerType,
BeatenDistance,
Odds
} from "./styled-components";
export default class RaceResultsHeader extends PureComponent {
static defaultProps = {
hasRunner: true,
hasWin: true,
hasPlace: true,
hasShow: true,
hasDistance: false,
hasOdds: false,
isGreyhound: false
};
render() {
return (
<thead data-qa-label="raceResultsHeader">
<HeaderRow>
<Position>POS</Position>
<Number>#</Number>
<Runner data-qa-label="raceResultsHeader-runner">
{this.props.hasRunner && (this.props.isGreyhound ? "DOG" : "HORSE")}
</Runner>
{this.props.hasWin && (
<WagerType data-qa-label="raceResultsHeader-betType">WIN</WagerType>
)}
{this.props.hasPlace && (
<WagerType data-qa-label="raceResultsHeader-betType">
PLACE
</WagerType>
)}
{this.props.hasShow && (
<WagerType data-qa-label="raceResultsHeader-betType">
SHOW
</WagerType>
)}
{this.props.hasDistance && (
<BeatenDistance data-qa-label="raceResultsHeader-beatenDistance">
Beaten Dist.
</BeatenDistance>
)}
{this.props.hasOdds && (
<Odds data-qa-label="raceResultsHeader-Odds">Odds</Odds>
)}
</HeaderRow>
</thead>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/RacePayoffRunner/styled-components.js
import styled, { css } from "styled-components";
import { buildText } from "../../_atom/Text";
import buildColor from "../../_static/ColorPalette";
import { titleFont } from "../../_static/Typography";
export const RunnerRow = styled.tr`
background-color: ${buildColor("white", "100")};
height: 40px;
font-size: 12px;
`;
export const PayoffRow = styled.tr`
background-color: ${buildColor("white", "100")};
font-size: 12px;
${({ hasBorder }) =>
hasBorder
? css`
border-bottom: 1px solid ${buildColor("grey", "300")};
height: 24px;
`
: css`
height: 32px;
`};
`;
export const RunnerCell = styled.td`
text-transform: uppercase;
`;
export const Position = styled(RunnerCell)`
font-family: ${titleFont};
width: 36px;
padding-left: 8px;
text-align: left;
`;
export const Number = styled(RunnerCell)`
padding: 0 4px;
text-align: center;
min-width: 16px;
height: 16px;
`;
export const Runner = styled(RunnerCell)`
font-family: ${titleFont};
text-align: left;
padding: 0 8px;
max-width: 0;
`;
export const Payoff = styled(RunnerCell)`
width: 68px;
padding-right: 8px;
text-align: right;
font-weight: bold;
color: ${buildColor("grey", "800")};
`;
export const RunnerName = styled(
buildText({
tag: "strong",
fontSize: 15,
color: buildColor("grey", "900"),
ellipsis: true,
qaLabel: "raceResultsRunner-runner-name"
})
)`
font-family: ${titleFont};
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/RacePayoffRunner/index.jsx
import React, { Fragment, PureComponent } from "react";
import { formatCurrency, formatSequencial } from "@tvg/formatter";
import { get } from "lodash";
import RunnerNumber from "../../_atom/RunnerNumber";
import {
RunnerRow,
PayoffRow,
RunnerCell,
Position,
Number,
Runner,
RunnerName,
Payoff
} from "./styled-components";
export default class RacePayoffRunner extends PureComponent {
static defaultProps = {
result: {
biNumber: 0,
runnerNumber: "string",
betAmount: 0,
finishPosition: 0,
placePayoff: 0,
runnerName: "",
showPayoff: 0,
winPayoff: 0
},
raceTypeCode: "T",
hasRunner: true,
hasWin: true,
hasPlace: true,
hasShow: true
};
renderRunner() {
return (
<RunnerRow
key={`position-runner-${this.props.runner.finishPosition}`}
data-qa-label="raceResultsRunner-runner"
>
<Position data-qa-label="raceResultsRunner-runner-position">
{formatSequencial(this.props.runner.finishPosition)}
</Position>
<Number>
<RunnerNumber
runnerId={this.props.runner.runnerNumber}
raceTypeCode={this.props.raceTypeCode}
/>
</Number>
<Runner colSpan={4}>
<RunnerName>{get(this.props.runner, "runnerName", "")}</RunnerName>
</Runner>
</RunnerRow>
);
}
renderPayoff(simpleVersion) {
return (
<PayoffRow
key={`payoff-runner-${this.props.runner.finishPosition}`}
data-qa-label="raceResultsRunner-payoff"
hasBorder={!simpleVersion}
>
{simpleVersion ? (
<Fragment>
<Position data-qa-label="raceResultsRunner-runner-position">
{formatSequencial(this.props.runner.finishPosition)}
</Position>
<Number>
<RunnerNumber
runnerId={this.props.runner.runnerNumber}
raceTypeCode={this.props.raceTypeCode}
/>
</Number>
<td />
</Fragment>
) : (
<RunnerCell colSpan={3} />
)}
{this.props.hasWin && (
<Payoff data-qa-label="raceResultsRunner-payoff-value">
{this.props.runner.winPayoff > 0 &&
formatCurrency(this.props.runner.winPayoff)}
</Payoff>
)}
{this.props.hasPlace && (
<Payoff data-qa-label="raceResultsRunner-payoff-value">
{this.props.runner.placePayoff > 0 &&
formatCurrency(this.props.runner.placePayoff)}
</Payoff>
)}
{this.props.hasShow && (
<Payoff data-qa-label="raceResultsRunner-payoff-value">
{this.props.runner.showPayoff > 0 &&
formatCurrency(this.props.runner.showPayoff)}
</Payoff>
)}
</PayoffRow>
);
}
render() {
return (
<Fragment>
{this.props.hasRunner && this.renderRunner()}
{this.renderPayoff(!this.props.hasRunner)}
</Fragment>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/RaceRunnersPayoffs/index.jsx
import React, { PureComponent } from "react";
import { some, map } from "lodash";
import ResultsTable from "./styled-components";
import RaceResultsHeader from "../../_molecule/RaceResultsHeader";
import RacePayoffRunner from "../../_molecule/RacePayoffRunner";
const getWagerTypesDisplay = (results) => ({
hasWin: some(results, (r) => r.winPayoff > 0),
hasPlace: some(results, (r) => r.placePayoff > 0),
hasShow: some(results, (r) => r.showPayoff > 0)
});
export default class RaceRunnersPayoffs extends PureComponent {
static defaultProps = {
runners: [],
raceTypeCode: "T",
displayRunner: true
};
render() {
const wagerTypesDisplay = getWagerTypesDisplay(this.props.runners);
return (
this.props.runners.length > 0 && (
<section data-qa-label="raceResults">
<ResultsTable border={!this.props.displayRunner}>
<RaceResultsHeader
hasRunner={this.props.displayRunner}
hasWin={wagerTypesDisplay.hasWin}
hasPlace={wagerTypesDisplay.hasPlace}
hasShow={wagerTypesDisplay.hasShow}
data-qa-label="raceResults-header"
isGreyhound={this.props.raceTypeCode === "G"}
/>
<tbody>
{map(this.props.runners, (runner) => (
<RacePayoffRunner
key={`${runner.biNumber}-${runner.placePayoff}-results-position-${runner.finishPosition}`}
hasRunner={this.props.displayRunner}
hasWin={wagerTypesDisplay.hasWin}
hasPlace={wagerTypesDisplay.hasPlace}
hasShow={wagerTypesDisplay.hasShow}
runner={runner}
raceTypeCode={this.props.raceTypeCode}
/>
))}
</tbody>
</ResultsTable>
</section>
)
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/RaceResultsPayoff/styled-components.js
import styled, { css } from "styled-components";
import { buildText } from "../../_atom/Text";
import buildColor from "../../_static/ColorPalette";
import { fontMedium, fontNormal } from "../../_static/Typography";
export const PayoffRow = styled.tr`
background-color: ${buildColor("white", "100")};
border-bottom: 1px solid
${({ hasNewDesign }) =>
hasNewDesign ? buildColor("blue", "100") : buildColor("grey", "300")};
height: 40px;
font-size: 12px;
`;
export const PayoffCell = styled.td`
padding: ${({ hasNewDesign }) => (hasNewDesign ? "10px 12px" : "10px 8px")};
${({ hasNewDesign }) =>
hasNewDesign &&
css`
& > span > span:last-child {
text-transform: capitalize;
}
`};
&:last-child {
width: 1%;
text-align: right;
vertical-align: baseline;
}
`;
export const RacePayoffsDesc = styled(
buildText({
color: buildColor("grey", "900")
})
)`
font-size: 14px;
`;
export const RacePayoffsPickDetail = styled(
buildText({
color: buildColor("grey", "700")
})
)`
padding-left: 5px;
`;
export const PayoffsPerSaddleContainer = styled.div`
display: flex;
margin-top: 5px;
${({ isVertical }) =>
isVertical &&
css`
flex-direction: column;
`}
`;
export const Selections = styled.section`
display: flex;
align-items: baseline;
margin-right: 5px;
${({ isVertical }) =>
isVertical &&
css`
flex-direction: column;
`}
`;
export const Payoff = buildText({
tag: "strong",
color: buildColor("grey", "800")
});
export const NewPayoff = styled.span`
font-family: ${fontMedium};
color: ${buildColor("grey", "800")};
font-size: 14px;
`;
export const PayoffsPerSaddleList = styled.ul`
display: flex;
flex-wrap: wrap;
margin-top: 5px;
list-style: none;
`;
export const PayoffsPerSaddleItem = styled.li`
text-align: center;
margin-right: 5px;
margin-bottom: 5px;
`;
export const PayoutText = styled.span`
margin-right: 5px;
${({ hasNewDesign }) =>
hasNewDesign &&
css`
font-family: ${fontNormal};
font-size: 12px;
color: ${buildColor("grey", "800")};
`}
`;
export const RunnerText = styled.span`
background-color: ${buildColor("blue", "100")};
border-radius: 1px;
width: 33px;
height: 16px;
display: inline-flex;
justify-content: center;
align-items: center;
color: ${buildColor("black", "100")};
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/RaceResultsPayoff/index.jsx
import React, { PureComponent } from "react";
import { get, capitalize } from "lodash";
import { formatCurrency, formatSequencial } from "@tvg/formatter";
import RunnerNumber from "../../_atom/RunnerNumber";
import {
PayoffRow,
PayoffCell,
RacePayoffsDesc,
RacePayoffsPickDetail,
Selections,
Payoff,
PayoffsPerSaddleContainer,
PayoffsPerSaddleList,
PayoffsPerSaddleItem,
PayoutText,
RunnerText,
NewPayoff
} from "./styled-components";
const exoticSeparator = "-";
const pickSeparator = "-";
const positionSeparator = ",";
export const exoticsBet = [
"WN",
"PL",
"SH",
"WP",
"WS",
"PS",
"WPS",
"QN",
"QNB",
"QNW",
"EX",
"EKB",
"EXB",
"EXW",
"EXK",
"TR",
"TRB",
"TRW",
"TRK",
"TKB",
"SU",
"SUB",
"SUK",
"SUW",
"SKB",
"SH5",
"H5W",
"S5K",
"5KB",
"OM",
"OMB",
"OMW",
"TI",
"TIB",
"TIW"
];
export const picksBet = [
"DB",
"GS",
"P3",
"P4",
"P5",
"P6",
"P7",
"P8",
"P9",
"P10",
"A3",
"A4",
"A5",
"A6",
"A7",
"A8",
"A9",
"A10",
"L3",
"L4",
"L5",
"L6",
"L7",
"L8",
"L9",
"L10",
"E12",
"SV"
];
export const formatPickResults = (raceNumberBase) => (pickNumber) =>
`R${raceNumberBase + pickNumber}`;
const hasRacesSeparators = (selection, raceSeparator) =>
RegExp(`[${raceSeparator}${positionSeparator}]`).test(selection);
export const parseResults = (selections, typeSeparator) =>
selections
.split(typeSeparator)
.map((winners) => winners.split(positionSeparator));
export default class RaceResultsPayoff extends PureComponent {
static defaultProps = {
payoff: {
wagerAmount: 0,
wagerType: { code: "", name: "" },
selections: [{ payoutAmount: 0, selection: "" }]
},
raceNumber: "1",
raceTypeCode: "T",
enableRaceResultsReDesign: false
};
renderSelections = (selections, wagerTypeCode) => {
if (
exoticsBet.includes(wagerTypeCode) &&
hasRacesSeparators(selections, exoticSeparator)
) {
const payoffsArr = parseResults(selections, exoticSeparator);
return this.renderPayoffsList(payoffsArr, formatSequencial);
}
if (
picksBet.includes(wagerTypeCode) &&
hasRacesSeparators(selections, pickSeparator)
) {
const payoffsArr = parseResults(selections, pickSeparator);
return this.renderPayoffsList(
payoffsArr,
formatPickResults(+this.props.raceNumber - payoffsArr.length),
true
);
}
return this.renderPlainPayoffs(selections);
};
renderPayoffsList = (winners, cbText, isColRowLayout = false) => (
<PayoffsPerSaddleContainer
isVertical={isColRowLayout}
data-qa-label="racePayoffs-row-selections"
>
{winners.map((winner, index) => (
// eslint-disable-next-line react/no-array-index-key
<Selections isVertical={!isColRowLayout} key={`winner_${index}`}>
{cbText && (
<PayoutText hasNewDesign={this.props.enableRaceResultsReDesign}>
{cbText(index + 1)}
</PayoutText>
)}
<PayoffsPerSaddleList>
{winner.map((horse, position) => (
// eslint-disable-next-line react/no-array-index-key
<PayoffsPerSaddleItem key={`winner_${index}_${position}`}>
{isNaN(horse) ? (
<RunnerText>{horse}</RunnerText>
) : (
<RunnerNumber
runnerId={horse}
raceTypeCode={this.props.raceTypeCode}
/>
)}
</PayoffsPerSaddleItem>
))}
</PayoffsPerSaddleList>
</Selections>
))}
</PayoffsPerSaddleContainer>
);
renderPlainPayoffs = (text) => (
<PayoffsPerSaddleContainer data-qa-label="racePayoffs-row-selections">
{text}
</PayoffsPerSaddleContainer>
);
renderWithHorseSaddlecloth() {
const selectionsRaw = get(this.props.payoff, "selections[0].selection");
const wagerTypeCode = get(this.props.payoff, "wagerType.code");
const pickRegex = /^\s*(\d+)\s*of\s*(\d+)\s+/i;
const match = selectionsRaw.match(pickRegex);
const pickStr = match ? match[0].trim().toUpperCase() : null;
const selections = match
? selectionsRaw.slice(match[0].length)
: selectionsRaw;
return (
<PayoffRow
hasNewDesign={this.props.enableRaceResultsReDesign}
data-qa-label="racePayoffs-row"
>
<PayoffCell hasNewDesign={this.props.enableRaceResultsReDesign}>
<span>
<RacePayoffsDesc data-qa-label="racePayoffs-row-betAmount">
{`${formatCurrency(get(this.props.payoff, "wagerAmount"))} `}
</RacePayoffsDesc>
<RacePayoffsDesc data-qa-label="racePayoffs-row-wagerType">
{`${capitalize(get(this.props.payoff, "wagerType.name", ""))}`}
</RacePayoffsDesc>
{pickStr && (
<RacePayoffsPickDetail>({pickStr})</RacePayoffsPickDetail>
)}
</span>
{selections !== "Refund" &&
this.renderSelections(selections, wagerTypeCode, pickStr)}
</PayoffCell>
<PayoffCell hasNewDesign={this.props.enableRaceResultsReDesign}>
<NewPayoff data-qa-label="racePayoffs-row-payoutAmount">
{selections !== "Refund"
? formatCurrency(
get(this.props.payoff, "selections[0].payoutAmount")
)
: "Refund"}
</NewPayoff>
</PayoffCell>
</PayoffRow>
);
}
renderPlainResults() {
const selections = get(this.props.payoff, "selections[0].selection");
return (
<PayoffRow data-qa-label="racePayoffs-row">
<PayoffCell>
<span>
<span data-qa-label="racePayoffs-row-betAmount">
{`${formatCurrency(get(this.props.payoff, "wagerAmount"))} `}
</span>
<span data-qa-label="racePayoffs-row-wagerType">
{get(this.props.payoff, "wagerType.name")}
</span>
</span>
{selections !== "Refund" && (
<Selections data-qa-label="racePayoffs-row-selections">
{selections}
</Selections>
)}
</PayoffCell>
<PayoffCell>
<Payoff data-qa-label="racePayoffs-row-payoutAmount">
{selections !== "Refund"
? formatCurrency(
get(this.props.payoff, "selections[0].payoutAmount")
)
: "Refund"}
</Payoff>
</PayoffCell>
</PayoffRow>
);
}
render() {
return this.props.enableRaceResultsReDesign
? this.renderWithHorseSaddlecloth()
: this.renderPlainResults();
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/RacePayoffs/styled-components.js
import styled from "styled-components"; const PayoffsTable = styled.table` width: 100%; `; export default PayoffsTable;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/RaceResultsPayoffHeader/styled-components.js
import styled from "styled-components";
import buildColor from "../../_static/ColorPalette";
import { fontMedium } from "../../_static/Typography";
export const PayoffHeaderRow = styled.tr`
height: 43px;
color: ${buildColor("grey", "900")};
background-color: ${buildColor("blue", "000")};
border-bottom: 1px solid ${buildColor("blue", "100")};
border-top: 1px solid ${buildColor("blue", "100")};
`;
export const PayoffHeaderCell = styled.th`
font-size: 14px;
font-family: ${fontMedium};
font-weight: normal;
&:first-child {
padding-left: 12px;
text-align: left;
}
&:last-child {
padding-right: 12px;
text-align: right;
}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/RaceResultsPayoffHeader/index.jsx
import React from "react";
import { PayoffHeaderRow, PayoffHeaderCell } from "./styled-components";
function RaceResultsPayoffHeader() {
return (
<thead>
<PayoffHeaderRow data-qa-label="payoffHeader-row">
<PayoffHeaderCell>Wager</PayoffHeaderCell>
<PayoffHeaderCell>Payout</PayoffHeaderCell>
</PayoffHeaderRow>
</thead>
);
}
export default RaceResultsPayoffHeader;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/RacePayoffs/index.jsx
import React, { PureComponent } from "react";
import { map } from "lodash";
import RaceResultsPayoff from "../../_molecule/RaceResultsPayoff";
import PayoffsTable from "./styled-components";
import RaceResultsPayoffHeader from "../../_molecule/RaceResultsPayoffHeader";
export default class RacePayoffs extends PureComponent {
static defaultProps = {
payoffs: [],
raceNumber: "1",
raceTypeCode: "T",
enableRaceResultsReDesign: false
};
render() {
const { payoffs, raceNumber, raceTypeCode, enableRaceResultsReDesign } =
this.props;
return (
<PayoffsTable data-qa-label="racePayoffs">
{enableRaceResultsReDesign && payoffs.length > 0 && (
<RaceResultsPayoffHeader />
)}
<tbody>
{map(payoffs, (payoff, index) => (
<RaceResultsPayoff
key={`${index}-${payoff.wagerType.code}-${payoff.selections[0].payoutAmount}-${payoff.selections[0].selection}-payoff`}
payoff={payoff}
raceNumber={raceNumber}
raceTypeCode={raceTypeCode}
enableRaceResultsReDesign={enableRaceResultsReDesign}
/>
))}
</tbody>
</PayoffsTable>
);
}
}
webpack://frontend-mybets/../../node_modules/react-transition-group/esm/utils/ChildMapping.js
import { Children, cloneElement, isValidElement } from 'react';
/**
* Given `this.props.children`, return an object mapping key to child.
*
* @param {*} children `this.props.children`
* @return {object} Mapping of key to child
*/
export function getChildMapping(children, mapFn) {
var mapper = function mapper(child) {
return mapFn && isValidElement(child) ? mapFn(child) : child;
};
var result = Object.create(null);
if (children) Children.map(children, function (c) {
return c;
}).forEach(function (child) {
// run the map function here instead so that the key is the computed one
result[child.key] = mapper(child);
});
return result;
}
/**
* When you're adding or removing children some may be added or removed in the
* same render pass. We want to show *both* since we want to simultaneously
* animate elements in and out. This function takes a previous set of keys
* and a new set of keys and merges them with its best guess of the correct
* ordering. In the future we may expose some of the utilities in
* ReactMultiChild to make this easy, but for now React itself does not
* directly have this concept of the union of prevChildren and nextChildren
* so we implement it here.
*
* @param {object} prev prev children as returned from
* `ReactTransitionChildMapping.getChildMapping()`.
* @param {object} next next children as returned from
* `ReactTransitionChildMapping.getChildMapping()`.
* @return {object} a key set that contains all keys in `prev` and all keys
* in `next` in a reasonable order.
*/
export function mergeChildMappings(prev, next) {
prev = prev || {};
next = next || {};
function getValueForKey(key) {
return key in next ? next[key] : prev[key];
} // For each key of `next`, the list of keys to insert before that key in
// the combined list
var nextKeysPending = Object.create(null);
var pendingKeys = [];
for (var prevKey in prev) {
if (prevKey in next) {
if (pendingKeys.length) {
nextKeysPending[prevKey] = pendingKeys;
pendingKeys = [];
}
} else {
pendingKeys.push(prevKey);
}
}
var i;
var childMapping = {};
for (var nextKey in next) {
if (nextKeysPending[nextKey]) {
for (i = 0; i < nextKeysPending[nextKey].length; i++) {
var pendingNextKey = nextKeysPending[nextKey][i];
childMapping[nextKeysPending[nextKey][i]] = getValueForKey(pendingNextKey);
}
}
childMapping[nextKey] = getValueForKey(nextKey);
} // Finally, add the keys which didn't appear before any key in `next`
for (i = 0; i < pendingKeys.length; i++) {
childMapping[pendingKeys[i]] = getValueForKey(pendingKeys[i]);
}
return childMapping;
}
function getProp(child, prop, props) {
return props[prop] != null ? props[prop] : child.props[prop];
}
export function getInitialChildMapping(props, onExited) {
return getChildMapping(props.children, function (child) {
return cloneElement(child, {
onExited: onExited.bind(null, child),
in: true,
appear: getProp(child, 'appear', props),
enter: getProp(child, 'enter', props),
exit: getProp(child, 'exit', props)
});
});
}
export function getNextChildMapping(nextProps, prevChildMapping, onExited) {
var nextChildMapping = getChildMapping(nextProps.children);
var children = mergeChildMappings(prevChildMapping, nextChildMapping);
Object.keys(children).forEach(function (key) {
var child = children[key];
if (!isValidElement(child)) return;
var hasPrev = (key in prevChildMapping);
var hasNext = (key in nextChildMapping);
var prevChild = prevChildMapping[key];
var isLeaving = isValidElement(prevChild) && !prevChild.props.in; // item is new (entering)
if (hasNext && (!hasPrev || isLeaving)) {
// console.log('entering', key)
children[key] = cloneElement(child, {
onExited: onExited.bind(null, child),
in: true,
exit: getProp(child, 'exit', nextProps),
enter: getProp(child, 'enter', nextProps)
});
} else if (!hasNext && hasPrev && !isLeaving) {
// item is old (exiting)
// console.log('leaving', key)
children[key] = cloneElement(child, {
in: false
});
} else if (hasNext && hasPrev && isValidElement(prevChild)) {
// item hasn't changed transition states
// copy over the last transition props;
// console.log('unchanged', key)
children[key] = cloneElement(child, {
onExited: onExited.bind(null, child),
in: prevChild.props.in,
exit: getProp(child, 'exit', nextProps),
enter: getProp(child, 'enter', nextProps)
});
}
});
return children;
}
webpack://frontend-mybets/../../node_modules/react-transition-group/esm/TransitionGroup.js
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _extends from "@babel/runtime/helpers/esm/extends";
import _assertThisInitialized from "@babel/runtime/helpers/esm/assertThisInitialized";
import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose";
import PropTypes from 'prop-types';
import React from 'react';
import TransitionGroupContext from './TransitionGroupContext';
import { getChildMapping, getInitialChildMapping, getNextChildMapping } from './utils/ChildMapping';
var values = Object.values || function (obj) {
return Object.keys(obj).map(function (k) {
return obj[k];
});
};
var defaultProps = {
component: 'div',
childFactory: function childFactory(child) {
return child;
}
};
/**
* The `<TransitionGroup>` component manages a set of transition components
* (`<Transition>` and `<CSSTransition>`) in a list. Like with the transition
* components, `<TransitionGroup>` is a state machine for managing the mounting
* and unmounting of components over time.
*
* Consider the example below. As items are removed or added to the TodoList the
* `in` prop is toggled automatically by the `<TransitionGroup>`.
*
* Note that `<TransitionGroup>` does not define any animation behavior!
* Exactly _how_ a list item animates is up to the individual transition
* component. This means you can mix and match animations across different list
* items.
*/
var TransitionGroup = /*#__PURE__*/function (_React$Component) {
_inheritsLoose(TransitionGroup, _React$Component);
function TransitionGroup(props, context) {
var _this;
_this = _React$Component.call(this, props, context) || this;
var handleExited = _this.handleExited.bind(_assertThisInitialized(_this)); // Initial children should all be entering, dependent on appear
_this.state = {
contextValue: {
isMounting: true
},
handleExited: handleExited,
firstRender: true
};
return _this;
}
var _proto = TransitionGroup.prototype;
_proto.componentDidMount = function componentDidMount() {
this.mounted = true;
this.setState({
contextValue: {
isMounting: false
}
});
};
_proto.componentWillUnmount = function componentWillUnmount() {
this.mounted = false;
};
TransitionGroup.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, _ref) {
var prevChildMapping = _ref.children,
handleExited = _ref.handleExited,
firstRender = _ref.firstRender;
return {
children: firstRender ? getInitialChildMapping(nextProps, handleExited) : getNextChildMapping(nextProps, prevChildMapping, handleExited),
firstRender: false
};
} // node is `undefined` when user provided `nodeRef` prop
;
_proto.handleExited = function handleExited(child, node) {
var currentChildMapping = getChildMapping(this.props.children);
if (child.key in currentChildMapping) return;
if (child.props.onExited) {
child.props.onExited(node);
}
if (this.mounted) {
this.setState(function (state) {
var children = _extends({}, state.children);
delete children[child.key];
return {
children: children
};
});
}
};
_proto.render = function render() {
var _this$props = this.props,
Component = _this$props.component,
childFactory = _this$props.childFactory,
props = _objectWithoutPropertiesLoose(_this$props, ["component", "childFactory"]);
var contextValue = this.state.contextValue;
var children = values(this.state.children).map(childFactory);
delete props.appear;
delete props.enter;
delete props.exit;
if (Component === null) {
return /*#__PURE__*/React.createElement(TransitionGroupContext.Provider, {
value: contextValue
}, children);
}
return /*#__PURE__*/React.createElement(TransitionGroupContext.Provider, {
value: contextValue
}, /*#__PURE__*/React.createElement(Component, props, children));
};
return TransitionGroup;
}(React.Component);
TransitionGroup.propTypes = process.env.NODE_ENV !== "production" ? {
/**
* `<TransitionGroup>` renders a `<div>` by default. You can change this
* behavior by providing a `component` prop.
* If you use React v16+ and would like to avoid a wrapping `<div>` element
* you can pass in `component={null}`. This is useful if the wrapping div
* borks your css styles.
*/
component: PropTypes.any,
/**
* A set of `<Transition>` components, that are toggled `in` and out as they
* leave. the `<TransitionGroup>` will inject specific transition props, so
* remember to spread them through if you are wrapping the `<Transition>` as
* with our `<Fade>` example.
*
* While this component is meant for multiple `Transition` or `CSSTransition`
* children, sometimes you may want to have a single transition child with
* content that you want to be transitioned out and in when you change it
* (e.g. routes, images etc.) In that case you can change the `key` prop of
* the transition child as you change its content, this will cause
* `TransitionGroup` to transition the child out and back in.
*/
children: PropTypes.node,
/**
* A convenience prop that enables or disables appear animations
* for all children. Note that specifying this will override any defaults set
* on individual children Transitions.
*/
appear: PropTypes.bool,
/**
* A convenience prop that enables or disables enter animations
* for all children. Note that specifying this will override any defaults set
* on individual children Transitions.
*/
enter: PropTypes.bool,
/**
* A convenience prop that enables or disables exit animations
* for all children. Note that specifying this will override any defaults set
* on individual children Transitions.
*/
exit: PropTypes.bool,
/**
* You may need to apply reactive updates to a child as it is exiting.
* This is generally done by using `cloneElement` however in the case of an exiting
* child the element has already been removed and not accessible to the consumer.
*
* If you do need to update a child as it leaves you can provide a `childFactory`
* to wrap every child, even the ones that are leaving.
*
* @type Function(child: ReactElement) -> ReactElement
*/
childFactory: PropTypes.func
} : {};
TransitionGroup.defaultProps = defaultProps;
export default TransitionGroup;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/SequentialLabel/styled-components.js
import styled from "styled-components";
import { fontMedium } from "../../_static/Typography";
import buildColor from "../../_static/ColorPalette";
const Label = styled.span`
font-weight: 500;
font-size: 14px;
font-family: ${fontMedium};
color: ${buildColor("grey", "900")};
& > sup {
font-size: 10px;
vertical-align: super;
}
`;
export default Label;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/SequentialLabel/index.jsx
import React, { PureComponent } from "react";
import Label from "./styled-components";
export default class SequentialLabel extends PureComponent {
static defaultProps = {
label: ""
};
processLabel = () => {
const isLeg = this.props.label.charAt(0) === "R";
const number = !isLeg ? this.props.label.slice(0, -2) : this.props.label;
const letters = !isLeg ? this.props.label.slice(-2).toLowerCase() : "";
return {
number,
letters
};
};
render() {
const { number, letters } = this.processLabel();
return (
<Label>
{number}
{letters && <sup>{letters}</sup>}
</Label>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/RunnerNumberGroup/styled-components.js
import styled from "styled-components";
import { titleFont } from "../../_static/Typography";
import { buildText } from "../../_atom/Text";
import buildColor from "../../_static/ColorPalette";
import Icon from "../../_static/Icons";
export const RunnerNumberGroupMolecule = styled.ol`
list-style-type: none;
display: flex;
width: 100%;
align-items: center;
`;
export const ListItem = styled.li`
min-width: 20px;
height: 20px;
display: flex;
justify-content: center;
align-items: center;
&:not(:first-child) {
margin-left: 1px;
}
`;
export const LabelItem = styled.li`
height: 16px;
width: 21px;
margin-right: 7px;
display: inline-flex;
align-items: center;
`;
export const Label = styled(
buildText({
tag: "strong",
fontSize: 12,
bold: true,
color: buildColor("grey", "900"),
uppercase: true
})
)`
font-family: ${titleFont};
`;
export const ArrowIcon = styled(Icon)`
margin: 2px;
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/RunnerNumberGroup/index.jsx
import React, { Component, Fragment } from "react";
import { isEqual, includes } from "lodash";
import RunnerNumber from "../../_atom/RunnerNumber";
import SequentialLabel from "../../_atom/SequentialLabel";
import Icon from "../../_static/Icons";
import { key, arrowForward } from "../../_static/Icons/icons";
import buildColor from "../../_static/ColorPalette";
import {
RunnerNumberGroupMolecule,
ListItem,
LabelItem,
ArrowIcon
} from "./styled-components";
const doubleEntryRegex = /^[0-9]+[a-zA-Z]+$/; // Double Entry validation regex
const getListItem = (runner, isFavorite, isArrow, raceTypeCode) => (
<ListItem
data-qa-label={`runnerNumberGroup-${isArrow ? runner : "saddleItem"}`}
key={`runnerNumberGroup-${runner}-${isFavorite ? "Fav" : "Nfav"}`}
>
{isArrow ? (
<ArrowIcon
size={12}
icon={arrowForward}
color={buildColor("blue", "800")}
/>
) : (
<RunnerNumber
runnerId={runner}
raceTypeCode={raceTypeCode}
isFavorite={isFavorite}
/>
)}
</ListItem>
);
const getEmptyList = () => (
<Fragment>
<ListItem key="empty">
<RunnerNumber />
</ListItem>
</Fragment>
);
const getFullList = (runners, favorites, raceTypeCode) => (
<Fragment>
{runners.map((runner) =>
getListItem(runner, includes(favorites, runner), false, raceTypeCode)
)}
</Fragment>
);
export const checkFavoriteSequence = (runner, favorites, lastFavoriteAdded) =>
lastFavoriteAdded &&
!includes(favorites, runner) &&
((doubleEntryRegex.test(runner) &&
(lastFavoriteAdded === runner ||
parseInt(lastFavoriteAdded, 10) === parseInt(runner, 10))) ||
parseInt(lastFavoriteAdded, 10) + 1 === parseInt(runner, 10));
export const getShortedSelectionsList = (runners, favorites, raceTypeCode) => {
let isFavorite;
let lastFavoriteAdded = "";
let startWithFavorite;
let count;
let countDE; // Double Entry count.
let i = 0;
const shortedSelections = [];
while (i < runners.length) {
count = 1;
countDE = 0;
while (
doubleEntryRegex.test(runners[i + count]) ||
parseInt(runners[i], 10) + (count - countDE) ===
parseInt(runners[i + count], 10)
) {
if (doubleEntryRegex.test(runners[i + count])) {
countDE += 1;
}
count += 1;
if (includes(favorites, runners[i + count - 1])) {
break;
}
}
startWithFavorite = 0; // new runners sequence starts with a favorite (0 -> false, 1 -> true)
if (
count === 2 &&
checkFavoriteSequence(runners[i], favorites, lastFavoriteAdded)
) {
// check if the last runner added to the array was a favorite and if the next one is sequencial to the favorite
startWithFavorite = 1;
}
if (count + startWithFavorite >= 3) {
// Sequence
if (!checkFavoriteSequence(runners[i], favorites, lastFavoriteAdded)) {
// if sequence not start after a favorite then add new runner.
isFavorite = includes(favorites, runners[i]);
shortedSelections.push(
getListItem(
isFavorite ? runners[i] : parseInt(runners[i], 10).toString(),
isFavorite,
false,
raceTypeCode
)
);
}
shortedSelections.push(
getListItem(`arrow${i}`, false, true, raceTypeCode)
);
isFavorite = includes(favorites, runners[i + count - 1]);
shortedSelections.push(
getListItem(
isFavorite
? runners[i + count - 1]
: parseInt(runners[i + count - 1], 10).toString(),
isFavorite,
false,
raceTypeCode
)
);
lastFavoriteAdded = isFavorite ? runners[i + count - 1] : "";
i += count;
} else {
// Single entry
isFavorite = includes(favorites, runners[i]);
lastFavoriteAdded = isFavorite ? runners[i] : "";
shortedSelections.push(
getListItem(runners[i], isFavorite, false, raceTypeCode)
);
i += 1;
}
}
return <Fragment>{shortedSelections}</Fragment>;
};
export default class RunnerNumberGroup extends Component {
static defaultProps = {
runners: [],
raceTypeCode: "T",
label: "",
isKey: false,
isShort: true,
favoriteRunners: []
};
shouldComponentUpdate(nextProps) {
return (
nextProps.runners.length !== this.props.runners.length ||
nextProps.favoriteRunners.length !== this.props.favoriteRunners.length ||
!isEqual(nextProps, this.props)
);
}
buildSaddleList = () => {
if (!this.props.runners.length) {
return getEmptyList();
}
if (this.props.isShort && this.props.runners.length > 2) {
return getShortedSelectionsList(
this.props.runners,
this.props.favoriteRunners,
this.props.raceTypeCode
);
}
return getFullList(
this.props.runners,
this.props.favoriteRunners,
this.props.raceTypeCode
);
};
render() {
return (
<RunnerNumberGroupMolecule data-qa-label="runnerNumberGroup">
{(this.props.isKey || this.props.label) && (
<LabelItem>
{!this.props.isKey ? (
<SequentialLabel label={this.props.label} />
) : (
<Icon icon={key} size={16} color={buildColor("grey", "900")} />
)}
</LabelItem>
)}
{this.buildSaddleList()}
</RunnerNumberGroupMolecule>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/BetSummary/styled-components.js
import styled, { css } from "styled-components";
import { buildText } from "../../_atom/Text";
import ButtonDefault from "../../_atom/Buttons/default";
import buildColor from "../../_static/ColorPalette";
import { fontMedium } from "../../_static/Typography";
export const BetDetailsContainer = styled.div`
display: flex;
height: 40px;
align-items: center;
background-color: ${buildColor("blue", "000")};
padding-right: ${(props) => (props.isCancelable ? "0" : "8px")};
`;
export const BetDetails = styled.div`
display: flex;
flex-direction: column;
flex-grow: 1;
place-items: flex-start center;
padding-left: 8px;
span:not(:first-child) {
margin-left: 4px;
}
`;
export const TrashButton = styled(ButtonDefault)`
width: 48px;
height: 40px;
background: transparent;
border: 0;
border-radius: 0;
`;
export const TrashContainer = styled.div`
display: flex;
align-items: center;
justify-content: center;
`;
export const PromoOptedInWrapper = styled.div`
display: flex;
align-items: center;
margin-top: 2px;
`;
export const PromoOptedInLabel = styled.small`
font-size: 10px;
display: inline-block;
margin-left: 2px;
text-transform: uppercase;
color: ${buildColor("grey", "800")};
`;
export const SelectionsContainer = styled.div`
display: flex;
align-items: center;
min-height: 40px;
${(props) =>
props.layout === "full" &&
css`
background: ${buildColor("white", "100")};
border-top: 1px solid ${buildColor("blue", "100")};
padding: 8px;
`};
${(props) =>
props.layout === "simple" &&
css`
padding: 12px 0;
`};
${(props) =>
props.isVertical
? css`
flex-direction: column;
justify-content: center;
& > ol {
flex-basis: auto;
&:not(:first-child) {
margin: 8px 0 0;
}
}
`
: css`
flex-flow: row nowrap;
justify-content: flex-start;
overflow: auto;
& > ol {
flex-basis: 0;
&:not(:first-child) {
margin: 0 0 0 8px;
}
}
`};
`;
export const BetSummaryContainer = styled.div`
position: relative;
border: 1px solid ${buildColor("grey", "300")};
border-radius: 2px;
`;
export const BetAmount = styled(
buildText({
tag: "span",
fontSize: 12,
bold: false,
color: buildColor("grey", "900"),
qaLabel: "betSummary-betAmount"
})
)`
letter-spacing: normal;
font-family: ${fontMedium};
`;
export const TicketAmount = buildText({
fontSize: 12,
color: buildColor("grey", "800"),
qaLabel: "betSummary-ticketAmount"
});
export const BetLabel = styled.span`
background-color: ${(props) => props.bgColor};
color: ${(props) => props.color};
padding: 0 3px;
height: 16px;
line-height: 16px;
font-size: 11px;
border-radius: 1px;
text-transform: uppercase;
font-weight: bold;
`;
export const RepeatableLabel = styled.span`
margin-left: 3px;
`;
export const RepeatButton = styled.span`
> button {
padding: 0;
}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/BetSummary/index.jsx
import React, { Component, Fragment } from "react";
import { noop, isEqual, isString } from "lodash";
import formatCurrency from "@tvg/formatter/currency";
import formatSequencial from "@tvg/formatter/numeric";
import buildColor from "../../_static/ColorPalette";
import Icon from "../../_static/Icons";
import { trash, promosolid } from "../../_static/Icons/icons";
import RunnerNumberGroup from "../RunnerNumberGroup";
import Button from "../../_atom/Buttons/button";
import {
BetDetailsContainer,
BetDetails,
TrashButton,
TrashContainer,
SelectionsContainer,
BetSummaryContainer,
BetAmount,
TicketAmount,
BetLabel,
RepeatableLabel,
RepeatButton,
PromoOptedInWrapper,
PromoOptedInLabel
} from "./styled-components";
export const getListRunnerNumberGroup = (
selectionsList = [],
raceTypeCode = "T",
isKey = false,
isLeg = false,
raceNumber = 1,
favoriteRunners = [],
showAllSelections = true
) => {
const multipleColumns = selectionsList.length > 1;
return (
<Fragment>
{(!showAllSelections && selectionsList.length > 5
? selectionsList.slice(0, 5)
: selectionsList
).map((selection, index) => {
if (isKey && index > 1) {
return false;
}
const favoritesColumn = isLeg ? index : 0;
const favorites = favoriteRunners[favoritesColumn] || [];
const favoritesAsStrings = favorites.every((fav) => isString(fav));
const normalizedFavs = favoritesAsStrings
? favorites
: favorites.map((fav) => `${fav}`);
let key = false;
let label = "";
if (multipleColumns) {
key = index === 0 && isKey;
if (isKey && index !== 0) {
label = "W/";
} else {
label = !isLeg
? formatSequencial(index + 1)
: `R${raceNumber + index}`;
}
}
return (
<RunnerNumberGroup
key={`runner-group${label}`}
runners={selection}
raceTypeCode={raceTypeCode}
isKey={key}
label={label}
favoriteRunners={normalizedFavs}
/>
);
})}
</Fragment>
);
};
class BetSummary extends Component {
static defaultProps = {
onDelete: noop,
onRepeatClick: noop,
isCancelable: false,
betTotal: 0,
wagerAmount: 0,
selectionTypeCode: "",
selections: [],
favoriteRunners: [],
raceTypeCode: "T",
isKey: false,
isLeg: false,
isVertical: true,
isLost: false,
isRepeatable: false,
isPromoQualifying: false,
repetitionsNr: 1,
isCancelled: false,
isRefunded: false,
totalWinAmount: null,
className: "",
raceNumber: "1",
layout: "full",
hasRepeaterEnabled: false,
hideRepeatButton: false,
hasPromosOptedIn: false,
showAllSelections: true
};
shouldComponentUpdate(nextProps) {
return (
this.props.selections.length !== nextProps.selections.length ||
this.props.repetitionsNr !== nextProps.repetitionsNr ||
!isEqual(this.props, nextProps)
);
}
renderBetDetails() {
return (
<BetDetails>
<div>
<BetAmount>
<span data-qa-label="betSummary-betAmount-amount">
{formatCurrency(this.props.wagerAmount || 0)}
</span>
<span data-qa-label="betSummary-betAmount-betType">
{this.props.selectionTypeCode}
</span>
{this.props.repetitionsNr > 1 && (
<RepeatableLabel data-qa-label="betSummary-betAmount-repetitionsNr">
[x{this.props.repetitionsNr}]
</RepeatableLabel>
)}
</BetAmount>
<TicketAmount>
<span data-qa-label="betSummary-betAmount-betTotal">
{this.props.repetitionsNr > 1
? formatCurrency(this.props.betTotal * this.props.repetitionsNr)
: formatCurrency(this.props.betTotal || 0)}
</span>
<span>Ticket</span>
</TicketAmount>
</div>
{this.props.hasPromosOptedIn && this.props.isPromoQualifying && (
<PromoOptedInWrapper>
<Icon icon={promosolid} color={buildColor("yellow", "500")} />
<PromoOptedInLabel>Opted-In</PromoOptedInLabel>
</PromoOptedInWrapper>
)}
</BetDetails>
);
}
renderTrashButton() {
return (
<TrashButton
onClick={this.props.onDelete}
qaLabel="betSummary-cancelBetBtn"
>
<TrashContainer>
<Icon size={16} icon={trash} color={buildColor("grey", "900")} />
</TrashContainer>
</TrashButton>
);
}
renderSelections() {
return getListRunnerNumberGroup(
this.props.selections,
this.props.raceTypeCode,
this.props.isKey,
this.props.isLeg,
+this.props.raceNumber,
this.props.favoriteRunners,
this.props.showAllSelections
);
}
renderFullBetSummary() {
return (
<BetSummaryContainer
data-qa-label="betSummary"
className={this.props.className}
>
<BetDetailsContainer
isRepeatable={
this.props.isRepeatable &&
this.props.hasRepeaterEnabled &&
!this.props.hideRepeatButton
}
isCancelable={this.props.isCancelable}
>
{this.renderBetDetails()}
{this.props.isRepeatable &&
this.props.hasRepeaterEnabled &&
!this.props.hideRepeatButton &&
!this.props.isCancelled &&
!this.props.isLost &&
!this.props.isRefunded &&
!this.props.totalWinAmount && (
<RepeatButton>
<Button
type="tertiary"
qaLabel="betSummary-repeatLink"
onClick={this.props.onRepeatClick}
>
Repeat
</Button>
</RepeatButton>
)}
{this.props.isCancelable && this.renderTrashButton()}
{this.props.isCancelled && (
<BetLabel
bgColor={buildColor("white", "100")}
color={buildColor("grey", "900")}
data-qa-label="betSummary-cancelledLabel"
>
Cancelled
</BetLabel>
)}
{this.props.isRefunded && (
<BetLabel
bgColor={buildColor("white", "100")}
color={buildColor("grey", "900")}
data-qa-label="betSummary-refundedLabel"
>
Refunded
</BetLabel>
)}
{this.props.isLost && (
<BetLabel
bgColor={buildColor("blue", "100")}
color={buildColor("grey", "900")}
data-qa-label="betSummary-lostLabel"
>
Lost
</BetLabel>
)}
{this.props.totalWinAmount && (
<BetLabel
bgColor={buildColor("green", "600")}
color={buildColor("white", "100")}
data-qa-label="betSummary-winlabel"
>
Won {formatCurrency(this.props.totalWinAmount)}
</BetLabel>
)}
</BetDetailsContainer>
<SelectionsContainer
data-qa-label="runnerSelections"
isVertical={this.props.isVertical}
layout={this.props.layout}
isMyBets={!this.props.isRepeatable && !this.props.hasRepeaterEnabled}
>
{this.renderSelections()}
</SelectionsContainer>
</BetSummaryContainer>
);
}
renderSimpleBetSummary() {
return (
<div className={`simpleBetSummaryWrapper ${this.props.className}`}>
{this.renderBetDetails()}
<SelectionsContainer
data-qa-label="runnerSelections"
isVertical={this.props.isVertical}
layout={this.props.layout}
>
{this.renderSelections()}
</SelectionsContainer>
</div>
);
}
render() {
switch (this.props.layout) {
case "simple":
return this.renderSimpleBetSummary();
case "full":
default:
return this.renderFullBetSummary();
}
}
}
export default BetSummary;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/RaceBets/styled-components.js
import styled from "styled-components";
import {
generateTransition,
easeInOut,
delayAction
} from "../../_static/Transitions";
export const BetList = styled.div`
margin: 0;
padding: 0;
& ul {
list-style: none;
}
`;
export const BetListItem = styled.li`
transition: ${generateTransition(easeInOut, "opacity", "2.7s")},
${generateTransition(easeInOut, "min-height", "2.9s")},
${generateTransition(easeInOut, "max-height", "2.9s")},
${generateTransition(easeInOut, "margin", "2.9s")},
${generateTransition(easeInOut, "padding", "2.9s")},
${generateTransition(easeInOut, "border", "2.9s")};
&:not(:last-child) {
padding-bottom: 8px;
}
& .betSummaryMessage {
padding: 0;
max-height: 0;
margin: 0;
opacity: 0;
transition: ${generateTransition(delayAction, "max-height", "0.9s")},
${generateTransition(delayAction, "padding", "0.9s")},
${generateTransition(delayAction, "margin", "0.9s")},
${generateTransition(easeInOut, "opacity", "1s")};
}
& .betSummary {
transition: ${generateTransition(easeInOut, "opacity", "0.5s")},
${generateTransition(easeInOut, "max-height", "0.7s")},
${generateTransition(easeInOut, "padding", "0.7s")},
${generateTransition(easeInOut, "margin", "0.7s")};
}
&.bet-list-item-exit {
opacity: 1;
max-height: 250px;
min-height: 50px;
& .betSummary {
opacity: 1;
max-height: 250px;
}
& .betSummaryMessage {
opacity: 1;
margin: 0;
max-height: 40px;
padding: 12px 8px;
}
}
&.bet-list-item-exit-active {
padding: 0;
border: 0;
opacity: 0;
margin: 0;
max-height: 0;
min-height: 0;
overflow: hidden;
& .betSummary {
opacity: 0;
max-height: 0;
padding: 0;
margin: 0;
}
}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/RaceBets/index.jsx
import React, { PureComponent } from "react";
import { map } from "lodash";
import { TransitionGroup, CSSTransition } from "react-transition-group";
import BetSummary from "../../_molecule/BetSummary";
import { BetList, BetListItem } from "./styled-components";
import MessageBox from "../../_molecule/MessageBox";
export default class RaceBets extends PureComponent {
static defaultProps = {
bets: [],
raceNumber: "1",
hasPromosOptedIn: false
};
render() {
return (
<BetList>
<TransitionGroup component="ul" data-qa-label="betlist">
{map(this.props.bets, (bet) => (
<CSSTransition
timeout={4000}
key={`bet-${bet.id}`}
classNames="bet-list-item"
>
<BetListItem>
{bet.isCancelable && (
<MessageBox
type="info"
hasIcon
message="Bet successfully deleted"
className="betSummaryMessage"
/>
)}
<BetSummary
className="betSummary"
isCancelable={bet.isCancelable}
betTotal={bet.betTotal}
selectionTypeCode={bet.wagerType.code}
wagerAmount={bet.wagerAmount}
selections={bet.selections}
raceTypeCode={bet.raceTypeCode}
isKey={bet.isKey}
isLeg={bet.isLeg}
isVertical
onDelete={bet.onDelete}
isLost={bet.isLost}
isRepeatable={bet.isRepeatable}
isPromoQualifying={bet.isPromoQualifying}
hasRepeatButton={bet.hasRepeatButton}
hasRepeaterEnabled={bet.hasRepeaterEnabled}
onRepeatClick={bet.onRepeatClick}
repetitionsNr={bet.repetitionsNr}
isCancelled={bet.isCancelled}
isRefunded={bet.isRefunded}
totalWinAmount={bet.totalWinAmount}
raceNumber={this.props.raceNumber}
hasPromosOptedIn={this.props.hasPromosOptedIn}
/>
</BetListItem>
</CSSTransition>
))}
</TransitionGroup>
</BetList>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/RaceResults/styled-components.js
import styled from "styled-components";
import Button from "../../_atom/Buttons/button";
import buildColor from "../../_static/ColorPalette";
export const ResultsTable = styled.table`
width: 100%;
`;
export const SeeAllRunnersSection = styled.div`
background-color: ${buildColor("blue", "000")};
border-bottom: 1px solid ${buildColor("grey", "300")};
`;
export const AllRunnersButton = styled(Button)`
width: 100%;
`;
export const IconContainer = styled.div`
padding-left: 3px;
height: 16px;
`;
export const OtherInfo = styled.div`
display: flex;
flex-direction: column;
background: ${buildColor("white", "100")};
font-size: 12px;
padding: 16px 8px;
border-bottom: 1px solid ${buildColor("grey", "300")};
& > :nth-child(2) {
margin-top: 8px;
}
`;
export const WinningTimeLabel = styled.strong`
padding-right: 16px;
padding-left: 3px;
color: ${buildColor("grey", "900")};
`;
export const WinningTime = styled.div`
display: flex;
color: ${buildColor("grey", "800")};
`;
export const ScratchesLabel = styled.strong`
padding-right: 34px;
padding-left: 3px;
color: ${buildColor("grey", "900")};
`;
export const Scratches = styled.div`
display: flex;
color: ${buildColor("grey", "800")};
`;
export const Number = styled.div`
width: 16px;
text-align: center;
margin-right: 2px;
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/RunnerBio/styled-components.js
import styled from "styled-components";
import { ellipsis } from "polished";
import { fontBold } from "../../_static/Typography";
import buildColor from "../../_static/ColorPalette";
export const BioWrapper = styled.dl`
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: center;
padding: 8px 8px 4px;
margin: 0;
position: relative;
`;
export const BioTitle = styled.dt.attrs((props) => ({
title: props.runnerName,
"data-qa-label": "runnerBio-title"
}))`
text-transform: uppercase;
font-size: 14px;
font-family: ${fontBold};
font-weight: 500;
min-height: 16px;
margin-bottom: 2px;
letter-spacing: 0;
${ellipsis()};
color: ${buildColor("grey", "900")};
text-decoration: ${(props) => (props.isScratched ? "line-through" : "")};
opacity: ${(props) => (props.isScratched ? 0.5 : 1)};
& svg {
padding-right: 4px;
}
`;
export const BioDescription = styled.dd`
font-size: 12px;
color: ${buildColor("grey", "800")};
margin: 0;
max-width: 100%;
min-height: 14px;
letter-spacing: 0;
opacity: ${(props) => props.isScratched && 0.5};
& > :not(:last-child) {
margin-right: 8px;
padding-right: 8px;
}
`;
export const Results = styled.dt`
position: absolute;
top: 8px;
right: 0;
display: flex;
font-size: 12px;
line-height: 1.6;
`;
export const ResultsDistance = styled.strong`
width: 70px;
text-align: right;
`;
export const ResultsOdds = styled.span`
width: 44px;
text-align: right;
padding-left: 16px;
`;
export const FlagsAndPick = styled.div`
display: flex;
flex-wrap: wrap;
width: 100%;
margin-top: 4px;
> span {
margin-right: 8px;
}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/RunnerBio/index.jsx
import React, { PureComponent } from "react";
import { get } from "lodash";
import SimpleInlineInfo from "@tvg/ipp/src/components/SimpleInlineInfo";
import RunnerFlags from "@tvg/ipp/src/components/RunnerFlags";
import InlineInfo from "../../_atom/InlineInfo";
import Icon from "../../_static/Icons";
import { star } from "../../_static/Icons/icons";
import buildColor from "../../_static/ColorPalette";
import TrackMasterPickTag from "../TrackMasterPickTag";
import {
BioWrapper,
BioTitle,
BioDescription,
Results,
ResultsDistance,
ResultsOdds,
FlagsAndPick
} from "./styled-components";
export default class RunnerBio extends PureComponent {
static defaultProps = {
raceTypeCode: "T",
runnerName: "",
handicappingData: [],
isScratched: false,
firstHandicapBold: false,
showFavorite: false,
isFavorite: false,
runnerMasterPickNumber: -1,
isRunnerTrackMasterPick: false,
isRunnerNumberFirePick: false,
resultsData: null,
hasJockeyChanges: false,
handicappingSortMode: "saddlecloth",
hasTrackMasterInfo: true,
trackDataSource: "",
runnerData: null,
showFlags: true,
handicappingRunnerFlags: {
title: "",
subtitle: "",
subtitleRunnerFlags: "",
flags: []
}
};
renderOdds = () => {
const odds = get(this.props.resultsData, "odds");
if (!!odds && !!odds.numerator) {
return `${odds.numerator}${
odds.denominator ? `/${odds.denominator}` : ""
}`;
}
return "n/a";
};
renderRunnerFlags = () => {
const flagsObg = get(this.props.runnerData, "timeform.flags", {});
const hasFlags = Object.keys(flagsObg).some((flag) => flagsObg[flag]);
return (
hasFlags &&
this.props.showFlags && (
<RunnerFlags
flags={flagsObg}
maxFlags={2}
handicappingRunnerFlags={this.props.handicappingRunnerFlags}
/>
)
);
};
render() {
const flagsObg = get(this.props.runnerData, "timeform.flags", {});
const hasFlags = Object.keys(flagsObg).some((flag) => flagsObg[flag]);
const hasPicksOrFlags =
(hasFlags && this.props.showFlags) || this.props.hasTrackMasterInfo;
return (
<BioWrapper>
{(this.props.isRunnerTrackMasterPick ||
this.props.isRunnerNumberFirePick) && (
<TrackMasterPickTag
pickNumber={this.props.runnerMasterPickNumber}
labelDarker={this.props.isRunnerTrackMasterPick}
isScratched={this.props.isScratched}
trackDataSource={this.props.trackDataSource}
isNumberFirePick={this.props.isRunnerNumberFirePick}
/>
)}
<BioTitle
runnerName={this.props.runnerName}
isScratched={this.props.isScratched}
>
{this.props.showFavorite && (
<Icon
icon={star}
size={14}
color={
!this.props.isFavorite
? buildColor("grey", "100")
: buildColor("yellow", "500")
}
/>
)}
{this.props.runnerName}
</BioTitle>
{!!this.props.resultsData && (
<Results>
<ResultsDistance>
{this.props.resultsData.accBeatenDistance}
</ResultsDistance>
<ResultsOdds>{this.renderOdds()}</ResultsOdds>
</Results>
)}
<BioDescription isScratched={this.props.isScratched}>
{this.props.handicappingData.length > 0 &&
(this.props.hasTrackMasterInfo ? (
<InlineInfo
isFirstBold={this.props.firstHandicapBold}
info={this.props.handicappingData}
hasJockeyChanges={this.props.hasJockeyChanges}
isScratched={this.props.isScratched}
showHandicappingSortMode={this.props.raceTypeCode !== "G"}
handicappingSortMode={this.props.handicappingSortMode}
/>
) : (
<SimpleInlineInfo info={this.props.handicappingData} />
))}
</BioDescription>
{hasPicksOrFlags && (
<FlagsAndPick>
{!this.props.isRunnerTrackMasterPick &&
!this.props.isRunnerNumberFirePick &&
this.props.hasTrackMasterInfo && (
<TrackMasterPickTag
pickNumber={this.props.runnerMasterPickNumber}
labelDarker={this.props.isRunnerTrackMasterPick}
trackDataSource={this.props.trackDataSource}
/>
)}
{hasFlags && this.props.showFlags && (
<RunnerFlags
flags={flagsObg}
maxFlags={2}
handicappingRunnerFlags={this.props.handicappingRunnerFlags}
/>
)}
</FlagsAndPick>
)}
</BioWrapper>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/RaceResultsRunner/styled-components.js
import styled, { css } from "styled-components";
import buildColor from "../../_static/ColorPalette";
import { titleFont } from "../../_static/Typography";
export const RunnerRow = styled.tr`
background-color: ${buildColor("white", "100")};
font-size: 12px;
border-bottom: 1px solid ${buildColor("blue", "100")};
vertical-align: top;
`;
export const PositionCell = styled.td`
height: 0;
vertical-align: top;
`;
export const Position = styled.strong`
font-family: ${titleFont};
padding: 16px 0 0 8px;
width: 100%;
height: 100%;
font-size: 12px;
display: flex;
line-height: 16px;
box-sizing: content-box;
${({ isHighlighted }) =>
isHighlighted &&
css`
color: ${buildColor("blue_accent", "500")};
position: relative;
&::before {
content: "";
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 4px;
background-color: ${buildColor("blue_accent", "500")};
}
`};
& > sup {
font-size: 8px;
transform: translate(0, -2px);
}
`;
export const DNF = styled.span`
width: 30px;
height: 16px;
display: flex;
align-items: center;
justify-content: center;
padding: 0 2px;
border-radius: 2px;
border: 1px solid ${buildColor("grey", "700")};
color: ${buildColor("grey", "700")};
&::before {
content: "DNF";
}
`;
export const Number = styled.td`
width: 24px;
vertical-align: top;
padding-top: 16px;
${({ isDnf }) =>
isDnf
? css`
padding-left: 8px;
`
: css`
padding-right: 8px;
`};
`;
export const Runner = styled.td`
font-family: ${titleFont};
text-align: left;
${({ isBasic }) =>
isBasic
? css`
padding: 8px 8px 8px 0;
`
: css`
padding: 8px 8px 12px 0;
`};
max-width: 0;
${({ isDnf }) =>
isDnf &&
css`
padding-left: 8px;
`};
`;
export const OtherInfo = styled.p`
padding: 0 8px;
transform: translate(0, -4px);
${({ isDnf }) =>
isDnf
? css`
color: ${buildColor("grey", "700")};
`
: css`
color: ${buildColor("grey", "800")};
`};
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_molecule/RaceResultsRunner/index.jsx
import React, { Fragment, PureComponent } from "react";
import { get } from "lodash";
import { formatSequencial } from "@tvg/formatter";
import RunnerNumber from "../../_atom/RunnerNumber";
import RunnerBio from "../RunnerBio";
import {
RunnerRow,
PositionCell,
Position,
Number,
Runner,
OtherInfo,
DNF
} from "./styled-components";
export default class RaceResultsRunner extends PureComponent {
static defaultProps = {
runnerId: "0",
runnerName: "",
trainer: "",
jockey: "",
scratched: false,
finishPosition: 0,
accBeatenDistance: "",
postRaceReport: "",
odds: null,
isHighlighted: false,
hasTimeformData: true,
raceTypeCode: "T"
};
renderRunner() {
const {
runnerId,
runnerName,
finishPosition,
odds,
isHighlighted,
raceTypeCode,
hasTimeformData
} = this.props;
const postRaceReport = get(this.props, "postRaceReport");
const accBeatenDistance = get(this.props, "accBeatenDistance");
const jockey = get(this.props, "jockey");
const trainer = get(this.props, "trainer");
const isDnf = finishPosition === 99;
return (
<RunnerRow
key={`position-runner-${+runnerId}`}
data-qa-label="raceResultsRunner-runner"
>
<PositionCell data-qa-label="raceResultsRunner-runner-position">
<Position isHighlighted={isHighlighted}>
{isDnf ? (
<DNF />
) : (
<Fragment>
{finishPosition}
<sup>
{formatSequencial(+finishPosition).replace(
(+finishPosition).toString(),
""
)}
</sup>
</Fragment>
)}
</Position>
</PositionCell>
<Number isDnf={isDnf}>
<RunnerNumber runnerId={runnerId} raceTypeCode={raceTypeCode} />
</Number>
<Runner
{...(hasTimeformData ? { colSpan: 3 } : {})}
isBasic={!hasTimeformData}
isDnf={isDnf}
>
<RunnerBio
runnerName={runnerName}
handicappingData={[jockey, trainer]}
removeVerticalPadding
firstHandicapBold
resultsData={
hasTimeformData && !isDnf
? {
accBeatenDistance,
odds
}
: null
}
isScratched={isDnf}
/>
{hasTimeformData && !!postRaceReport && (
<OtherInfo isDnf={isDnf}>{`"${postRaceReport}"`}</OtherInfo>
)}
</Runner>
</RunnerRow>
);
}
render() {
return <Fragment>{this.renderRunner()}</Fragment>;
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_organism/RaceResults/index.jsx
import React, { Component } from "react";
import { isEqual, noop } from "lodash";
import {
ResultsTable,
AllRunnersButton,
IconContainer,
SeeAllRunnersSection,
OtherInfo,
WinningTime,
WinningTimeLabel,
Scratches,
ScratchesLabel,
Number
} from "./styled-components";
import RunnerNumber from "../../_atom/RunnerNumber";
import RaceResultsHeader from "../../_molecule/RaceResultsHeader";
import RaceResultsRunner from "../../_molecule/RaceResultsRunner";
import Icon from "../../_static/Icons";
import { arrowDown } from "../../_static/Icons/icons";
import buildColor from "../../_static/ColorPalette";
export default class RaceResults extends Component {
static defaultProps = {
runnerName: "",
runners: [],
scratchedRunners: [],
raceTypeCode: "T",
resultsType: "full",
winningTime: "",
seeAllHorsesGTM: noop
};
constructor(props) {
super(props);
this.state = {
isExpanded: false
};
}
getSnapshotBeforeUpdate(prevProps) {
if (!isEqual(this.props, prevProps) && this.state.isExpanded === true) {
this.setState({ isExpanded: false });
}
}
getRunnersForFullResults = (runners, runnerName) =>
runners.reduce((resultRunner, runner, index) => {
if (
index < 3 ||
runner.runnerName.toLowerCase() === runnerName.toLowerCase()
) {
resultRunner.push(runner);
}
return resultRunner;
}, []);
render() {
const {
runners,
runnerName,
raceTypeCode,
resultsType,
winningTime,
scratchedRunners
} = this.props;
const hasRunners = runners.length > 0;
const hasTimeformData = resultsType === "full";
const runnersToDisplay =
this.state.isExpanded || !hasTimeformData
? runners
: this.getRunnersForFullResults([...runners], runnerName);
return (
hasRunners && (
<section data-qa-label="raceResults">
<ResultsTable>
<RaceResultsHeader
data-qa-label="raceResults-header"
isGreyhound={raceTypeCode === "G"}
hasWin={false}
hasPlace={false}
hasShow={false}
hasDistance={hasTimeformData}
hasOdds={hasTimeformData}
/>
<tbody>
{runnersToDisplay.map((runner) => (
<RaceResultsRunner
key={`${runner.runnerId}-results-position-${runner.finishPosition}`}
{...runner}
accBeatenDistance={runner.accBeatenDistanceStatus}
hasTimeformData={hasTimeformData}
isHighlighted={runner.runnerName === runnerName}
raceTypeCode={raceTypeCode}
/>
))}
</tbody>
</ResultsTable>
{!this.state.isExpanded && hasTimeformData && (
<SeeAllRunnersSection>
<AllRunnersButton
size="big"
type="tertiary"
onClick={() => {
this.props.seeAllHorsesGTM();
this.setState({ isExpanded: true });
}}
qaLabel="hpp-all-runners"
>
See all runners
<IconContainer>
<Icon
icon={arrowDown}
color={buildColor("blue_accent", "600")}
/>
</IconContainer>
</AllRunnersButton>
</SeeAllRunnersSection>
)}
<OtherInfo>
{hasTimeformData && (
<WinningTime>
<WinningTimeLabel>Winning time</WinningTimeLabel>
{winningTime}
</WinningTime>
)}
<Scratches>
<ScratchesLabel>Scratches</ScratchesLabel>
{scratchedRunners.length === 0
? "No Changes"
: scratchedRunners.map((runner) => (
<Number key={runner}>
<RunnerNumber
key={`${runner}-number`}
runnerId={runner}
raceTypeCode={this.props.raceTypeCode}
/>
</Number>
))}
</Scratches>
</OtherInfo>
</section>
)
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_templates/RaceCard/styled-components.js
import styled, { css, keyframes } from "styled-components";
import buildColor from "../../_static/ColorPalette";
import ButtonDefault from "../../_atom/Buttons/default";
import { buildText } from "../../_atom/Text";
const fadeIn = keyframes`
from {
opacity: 0;
}
to {
opacity: 1;
}
`;
const fadeOut = keyframes`
from {
opacity: 1;
}
to {
opacity: 0;
}
`;
const slideIn = keyframes`
from {
opacity: 0;
left: 200px;
}
to {
opacity: 1;
left: 0;
}
`;
const slideOut = keyframes`
from {
opacity: 1;
left: 0;
}
to {
opacity: 0;
left: 200px;
}
`;
export const RaceCardSection = styled.section`
width: 100%;
flex: 1 1 0;
background-color: ${buildColor("white", "0")};
padding-top: ${(props) =>
props.isHandicapFixed && `${props.handicapFormatHeight}px`};
`;
export const RaceCardTableWrapper = styled.div`
${(props) =>
props.device === "mobile" &&
!props.isLeg &&
css`
border: 1px solid ${buildColor("grey", "300")};
border-radius: 2px;
overflow: hidden;
${({ removeMargin }) =>
!removeMargin &&
css`
margin: 4px;
`};
`}
`;
export const RaceCardTable = styled.table`
width: 100%;
background-color: ${buildColor("white", "100")};
${(props) =>
props.device === "tablet" &&
css`
border-right: 1px solid ${buildColor("grey", "300")};
border-left: 1px solid ${buildColor("grey", "300")};
`};
${(props) =>
props.noBorderOnFirstChild &&
css`
& tr:first-child {
border-top: 0;
}
`};
`;
export const RaceDataContainer = styled.div`
padding: 4px 8px;
background-color: ${buildColor("white", "100")};
border: 1px solid ${buildColor("grey", "300")};
border-top-left-radius: 2px;
border-top-right-radius: 2px;
`;
export const RaceCardLegWrapper = styled.div`
width: calc(100% - 16px);
padding: 12px 0 12px 8px;
&:first-child {
padding-left: 12px;
}
&:last-child {
width: 100%;
margin-right: 1px;
}
`;
export const Text = styled(
buildText({
tag: "span",
fontSize: 10,
color: buildColor("blue_accent", "500"),
uppercase: true,
bold: true
})
)`
height: 11px;
`;
export const BetAllModalWrapper = styled.div`
visibility: ${({ isBetAllOpened }) =>
isBetAllOpened ? "visible" : "hidden"};
height: 0;
position: relative;
z-index: 1;
${({ isBetAllOpened }) =>
isBetAllOpened
? css`
animation: ${fadeIn} 0.8s linear;
transition: visibility 0.8s linear;
`
: css`
animation: ${fadeOut} 0.8s ease-out;
animation-delay: ${({ numColumns }) => 0.09 * numColumns}s;
transition: visibility 0.8s ease-out;
`}
`;
export const BetAllModal = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
height: ${(props) => props.headerHeight}px;
background-color: ${buildColor("white", "100")};
overflow: hidden;
${(props) =>
props.device === "tablet" &&
css`
border-right: 1px solid ${buildColor("grey", "300")};
border-left: 1px solid ${buildColor("grey", "300")};
`};
`;
export const CloseButton = styled.div`
width: 48px;
height: 40px;
position: relative;
display: flex;
justify-content: center;
align-items: center;
background-color: ${buildColor("white", "0")};
${({ isBetAllOpened }) =>
isBetAllOpened
? css`
animation: ${slideIn} 0.5s ease-in;
`
: css`
animation: ${slideOut} 0.5s ease-in;
animation-delay: ${({ numColumns }) => 0.09 * numColumns}s;
`}
`;
export const BetAllButtons = styled.div`
display: flex;
justify-content: flex-end;
`;
export const BetAllButton = styled(ButtonDefault)`
width: 48px;
height: 40px;
position: relative;
background-color: ${buildColor("white", "0")};
${({ isBetAllOpened }) =>
isBetAllOpened
? css`
animation: ${slideIn} 0.5s ease-in;
animation-delay: ${({ column }) => 0.09 * column}s;
animation-fill-mode: backwards;
`
: css`
animation: ${slideOut} 0.5s ease-in;
animation-delay: ${(props) =>
0.09 * (props.numColumns - props.column)}s;
animation-fill-mode: forwards;
`}
& > span {
display: block;
}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/TextHighlighted/styled-components.js
import styled from "styled-components";
import { buildText } from "../Text";
const createTextHighlightComponent = (
type,
fontSize,
bold,
uppercase,
qaLabel
) => styled(
buildText({ fontSize, color: type.textColor, bold, uppercase, qaLabel })
)`
background-color: ${type.bgColor};
padding: 0 2px;
border-radius: 30px;
display: inline-flex;
@media (pointer: coarse) {
padding: 0 6px;
}
`;
export default createTextHighlightComponent;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_atom/TextHighlighted/index.jsx
import React, { PureComponent } from "react";
import createTextHighlightComponent from "./styled-components";
import buildColor from "../../_static/ColorPalette";
export const TYPES = {
primary: {
bgColor: buildColor("blue_accent", "500"),
textColor: buildColor("white", "100")
},
secondary: {
bgColor: buildColor("blue", "100"),
textColor: buildColor("grey", "900")
},
bet: {
bgColor: buildColor("green", "600"),
textColor: buildColor("white", "100")
},
marketing: {
bgColor: buildColor("yellow", "500"),
textColor: buildColor("grey", "900")
},
pending: {
bgColor: buildColor("grey", "100"),
textColor: buildColor("grey", "800")
}
};
export const getType = (type) => TYPES[type];
export const buildTextHighlighted = createTextHighlightComponent;
export default class TextHighlighted extends PureComponent {
static defaultProps = {
children: null,
fontSize: 11,
type: "primary",
uppercase: true,
bold: false,
className: "",
qaLabel: ""
};
render() {
const ExtendedText = createTextHighlightComponent(
getType(this.props.type),
this.props.fontSize,
this.props.bold,
this.props.uppercase,
this.props.qaLabel
);
return (
<ExtendedText className={this.props.className}>
{this.props.children}
</ExtendedText>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_templates/RaceOfficials/styled-components.js
import styled, { css } from "styled-components";
import { fontNormal } from "../../_static/Typography";
import { buildTextHighlighted, TYPES } from "../../_atom/TextHighlighted";
import MessageBox from "../../_molecule/MessageBox";
import buildColor from "../../_static/ColorPalette";
export const ResultsContainer = styled.section`
background-color: ${buildColor("blue", "100")};
`;
export const NoBetsContainer = styled.section`
display: flex;
justify-content: center;
flex-direction: column;
flex-grow: 1;
background-color: ${buildColor("white", "100")};
`;
export const RaceBetsContainer = styled.section`
${(props) => css`
background-color: ${props.myBetsBody
? buildColor("blue", "000")
: buildColor("white", "100")};
padding: ${props.myBetsBody ? "0px" : "8px"};
> div {
margin-top: ${props.myBetsBody ? "8px" : "0px"};
}
`};
`;
export const Alerts = styled(MessageBox)`
border-radius: 2px;
min-height: 64px;
`;
export const TextHighlighted = styled(
buildTextHighlighted(TYPES.pending, 11, true, true)
)`
padding: 1px 2px;
line-height: 1;
`;
export const ROWrapper = styled.div`
display: flex;
flex: 1 0 auto;
flex-direction: column;
ul.tab-group {
box-shadow: inset 0 -1px 0 0 ${buildColor("blue", "100")} !important;
}
`;
export const Message = styled(MessageBox)`
border-bottom: 1px solid ${buildColor("grey", "300")};
${(props) =>
props.enableRaceResultsReDesign &&
css`
border-radius: 0 !important;
border-bottom: 1px solid ${buildColor("blue", "100")};
padding: 15px 12px !important;
span {
color: ${buildColor("blue_accent", "500")};
font-family: ${fontNormal};
font-size: 14px;
}
`};
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_templates/RaceOfficials/index.jsx
import React, { Component, Fragment } from "react";
import { bindAll, isEqual, get, noop, first } from "lodash";
import { Tabs, Tab, TabList, TabPanel, Counter } from "@tvg/design-system/web";
import handicappingOptions, {
handicappingGreyhoundOptions,
handicappingHarnessOptions
} from "@tvg/utils/handicapping-conf/handicappingOptions";
import { checkTimeformData } from "@tvg/sh-lib-my-bets/utils/bettingInterests";
import MyBetsBody from "@tvg/my-bets-standalone/src/MyBetsBody";
import RunnerListHeader from "@tvg/ipp/src/components/RunnerListHeader";
import RunnerList from "@tvg/ipp/src/components/RunnerList";
import RaceMessageRedirect from "@tvg/ipp/src/components/RaceMessageRedirect";
import RaceRunnersPayoffsReDesign from "../../_organism/RaceRunners";
import RaceRunnersPayoffs from "../../_organism/RaceRunnersPayoffs";
import RacePayoffs from "../../_organism/RacePayoffs";
import RaceBets from "../../_organism/RaceBets";
import { ResultsMask } from "../../_static/Masks";
import RaceResults from "../../_organism/RaceResults";
import {
RaceCardTableWrapper,
RaceCardTable
} from "../RaceCard/styled-components";
import {
ResultsContainer,
RaceBetsContainer,
Alerts,
NoBetsContainer,
TextHighlighted,
ROWrapper,
Message
} from "./styled-components";
import { handicapping } from "../../_static/Icons/icons";
export default class RaceOfficials extends Component {
static defaultProps = {
resultsType: "official",
bettingInterests: [],
scratchedRunners: [],
results: null,
fullResults: [],
runnerName: "",
raceTypeCode: "T",
isResultsPending: true,
bets: [],
races: [],
wagerGroup: null,
myBetsResultedBetTicket: false,
defaultTab: "racecard",
onTabClick: () => false,
legExpandedRunner: "",
runnerExpandLine: noop,
runnerExpandInfo: noop,
inLinePastPerformance: false,
handicapType: "basic",
openHandicapCallback: noop,
raceNumber: "1",
firstHandicapBold: false,
nextRaceUrl: "",
tracksUrl: "",
onNextRaceClick: noop,
onChangeTrackClick: noop,
hasNoHandicappingSelection: false,
hasTimeformData: false,
winningTime: "",
isGreyhound: false,
device: "mobile",
trackDataSource: "",
enableRaceResultsReDesign: false,
seeAllHorsesGTM: noop,
scrollRunnerPP: false,
scrollOffset: 0,
handicappingRunnerFlags: {
title: "",
subtitle: "",
subtitleRunnerFlags: "",
flags: []
},
raceId: "0",
racePayoffsShift: false
};
constructor(props) {
super(props);
this.state = {
selectedtab:
this.props.defaultTab === "none" ? "racecard" : this.props.defaultTab
};
bindAll(this, "handleTabClick", "renderResultTab", "getHandicappingFormat");
}
// eslint-disable-next-line camelcase
UNSAFE_componentWillReceiveProps(nextProps) {
if (this.state.selectedtab !== nextProps.defaultTab) {
this.setState({
selectedtab:
nextProps.defaultTab === "none" ? "racecard" : nextProps.defaultTab
});
}
}
shouldComponentUpdate(nextProps, nextState) {
return (
nextState.selectedtab !== this.state.selectedtab ||
nextProps.defaultTab !== this.props.defaultTab ||
nextProps.bettingInterests.length !==
this.props.bettingInterests.length ||
get(nextProps, "results.runners", []).length !==
get(this.props, "results.runners", []).length ||
get(nextProps.results, "payoffs", []).length !==
get(this.props.results, "payoffs", []).length ||
!isEqual(nextProps, this.props)
);
}
handleTabClick(newTab) {
if (this.state.selectedtab !== newTab && this.props.onTabClick(newTab)) {
this.setState({ selectedtab: newTab });
}
}
getHandicappingFormat(handicapKey) {
let option = [];
if (this.props.raceTypeCode === "G") {
option = handicappingGreyhoundOptions;
} else if (this.props.raceTypeCode === "H") {
option = handicappingHarnessOptions;
} else {
option = handicappingOptions;
}
const findRes =
option.find((handicapItem) => handicapItem.key === handicapKey) ||
option[0];
return handicapKey === "basic"
? {
title: findRes.title
}
: findRes;
}
renderMyBets() {
return this.props.bets.length > 0 ? (
<RaceBetsContainer key="bets-tab">
<RaceBets bets={this.props.bets} raceNumber={this.props.raceNumber} />
</RaceBetsContainer>
) : (
<NoBetsContainer>
<Alerts isVertical type="info" message="You've no bets on this race" />
</NoBetsContainer>
);
}
renderNewMyBets() {
const { wagerGroup, races } = this.props;
return wagerGroup && wagerGroup.wagers.length > 0 ? (
<RaceBetsContainer key="bets-tab" myBetsBody>
<MyBetsBody
bet={wagerGroup}
races={races || []}
currentRaceDate={first(wagerGroup.value.split("|"))}
hasPastPerformance={false}
showLiveVideo={false}
isInsideRaceOfficials
/>
</RaceBetsContainer>
) : (
<NoBetsContainer>
<Alerts isVertical type="info" message="You've no bets on this race" />
</NoBetsContainer>
);
}
renderResultTab() {
return (
<ResultsContainer>
{!this.props.isResultsPending && (
<Fragment>
{this.props.enableRaceResultsReDesign ? (
<RaceRunnersPayoffsReDesign
shouldExpandMoreRunners={checkTimeformData(
get(this.props, "results")
)}
raceTypeCode={this.props.raceTypeCode}
runners={get(this.props.results, "runners", [])}
bettingInterests={this.props.bettingInterests}
winningTime={this.props.winningTime}
runnerNameHighlighted={this.props.runnerName}
raceId={this.props.raceId}
racePayoffsShift={this.props.racePayoffsShift}
/>
) : (
<RaceRunnersPayoffs
raceTypeCode={this.props.raceTypeCode}
runners={get(this.props.results, "runners", [])}
/>
)}
<RacePayoffs
raceNumber={this.props.raceNumber}
raceTypeCode={this.props.raceTypeCode}
enableRaceResultsReDesign={this.props.enableRaceResultsReDesign}
payoffs={get(this.props.results, "payoffs", [])}
/>
</Fragment>
)}
{this.props.isResultsPending && (
<Fragment>
<RaceMessageRedirect
title="Result pending"
message="Full result will be posted once they are official"
nextRaceUrl={this.props.nextRaceUrl}
tracksUrl={this.props.tracksUrl}
onNextRaceClick={this.props.onNextRaceClick}
onChangeTrackClick={this.props.onChangeTrackClick}
/>
<ResultsMask />
</Fragment>
)}
</ResultsContainer>
);
}
renderFullResultTab = () => {
const {
hasTimeformData,
raceTypeCode,
results,
runnerName,
fullResults,
scratchedRunners,
winningTime,
enableRaceResultsReDesign,
seeAllHorsesGTM
} = this.props;
return (
<Fragment>
{!hasTimeformData && (
<Message
enableRaceResultsReDesign={enableRaceResultsReDesign}
type="info"
message="Full result unavailable at this time"
/>
)}
{enableRaceResultsReDesign ? (
<RaceRunnersPayoffsReDesign
raceTypeCode={raceTypeCode}
runners={get(results, "runners", [])}
bettingInterests={this.props.bettingInterests}
winningTime={winningTime}
runnerNameHighlighted={runnerName}
shouldExpandMoreRunners={this.props.hasTimeformData}
raceId={this.props.raceId}
/>
) : (
<React.Fragment>
<RaceResults
resultsType={hasTimeformData ? "full" : "basic"}
runnerName={runnerName}
runners={fullResults}
scratchedRunners={scratchedRunners}
raceTypeCode={raceTypeCode}
winningTime={winningTime}
seeAllHorsesGTM={seeAllHorsesGTM}
/>
<RaceRunnersPayoffs
raceTypeCode={raceTypeCode}
runners={get(results, "runners", [])}
displayRunner={false}
/>
</React.Fragment>
)}
<RacePayoffs
raceNumber={this.props.raceNumber}
raceTypeCode={raceTypeCode}
payoffs={get(results, "payoffs", [])}
enableRaceResultsReDesign={enableRaceResultsReDesign}
/>
</Fragment>
);
};
renderRaceCardtab() {
const handicappingFormat = this.getHandicappingFormat(
this.props.handicapType
);
const handicapOptions = [
{
title: handicappingFormat.title,
callback: this.props.openHandicapCallback,
icon: handicapping,
visible: true,
qaLabel: "runnerListHeader-handicapInfoBtn"
}
];
return (
<Fragment>
{this.props.isResultsPending && (
<RaceMessageRedirect
isWarning
hasBorderBottom
message="Betting has now closed on this race"
nextRaceUrl={this.props.nextRaceUrl}
tracksUrl={this.props.tracksUrl}
onNextRaceClick={this.props.onNextRaceClick}
onChangeTrackClick={this.props.onChangeTrackClick}
/>
)}
<RaceCardTableWrapper
removeMargin={this.props.enableRaceResultsReDesign}
device={this.props.device}
>
<RaceCardTable
device={this.props.device}
noBorderOnFirstChild={this.props.hasNoHandicappingSelection}
>
{!this.props.hasNoHandicappingSelection && (
<RunnerListHeader
isWagerable={false}
handicapOptions={handicapOptions}
handicapInfo={get(handicappingFormat, "handicapData")}
raceTypeCode={this.props.raceTypeCode}
hasHandicappingSelection
/>
)}
<RunnerList
runners={this.props.bettingInterests}
raceTypeCode={this.props.raceTypeCode}
isWagerable={false}
numColumns={1}
firstHandicapBold={this.props.firstHandicapBold}
trackDataSource={this.props.trackDataSource}
expandedRunner={this.props.legExpandedRunner}
expandLine={this.props.runnerExpandLine}
expandInfo={this.props.runnerExpandInfo}
inLinePastPerformance={this.props.inLinePastPerformance}
scrollRunnerPP={this.props.scrollRunnerPP}
scrollOffset={this.props.scrollOffset}
handicappingRunnerFlags={this.props.handicappingRunnerFlags}
/>
</RaceCardTable>
</RaceCardTableWrapper>
</Fragment>
);
}
getTitle = () => {
return this.props.hasTimeformData ? "Full Result" : "Basic Result";
};
getTotalBets = () => {
const { bets, myBetsResultedBetTicket, wagerGroup } = this.props;
return myBetsResultedBetTicket
? wagerGroup?.wagers.length || 0
: bets.length;
};
render() {
const isDesktop = this.props.device !== "mobile";
const sharedTabProps = {
isTitleUppercase: !this.props.enableRaceResultsReDesign,
...(isDesktop && {
hoverColor: "var(--fd-colors-background-base)",
textTitleColor: "var(--fd-colors-content-default)",
textTitleSelectedColor: "var(--fd-colors-content-default)",
hasPressedColor: false
})
};
return (
<Fragment>
<ROWrapper data-qa-label="raceOfficials">
<Tabs
selectedValue={this.state.selectedtab}
onChange={this.handleTabClick}
isStretched
qaLabel="tabs"
>
<TabList
qaLabel="tabList"
isStretched
tabSelectionIndicatorColor="var(--fd-colors-border-default)"
>
{this.props.resultsType === "full" ? (
<Tab
value="fullresult"
title={
this.props.enableRaceResultsReDesign
? "Result"
: this.getTitle()
}
qaLabel={
this.props.hasTimeformData
? "raceofficials-fullresult"
: "raceofficials-basicresult"
}
{...sharedTabProps}
/>
) : (
<Tab
value="result"
title="Result"
description={
this.props.isResultsPending ? (
<TextHighlighted>PENDING</TextHighlighted>
) : (
""
)
}
qaLabel="raceofficials-result"
{...sharedTabProps}
/>
)}
{this.getTotalBets() === 0 ? (
<React.Fragment> </React.Fragment>
) : (
<Tab
value="bets"
title="Bets"
isDisabled={this.getTotalBets() === 0}
counter={<Counter value={this.getTotalBets()} />}
qaLabel="raceofficials-bets"
{...sharedTabProps}
/>
)}
<Tab
value="racecard"
title="Racecard"
qaLabel="raceofficials-racecard"
isTitleUppercase={!this.props.enableRaceResultsReDesign}
{...sharedTabProps}
/>
</TabList>
<TabPanel id="result" value="result">
{this.renderResultTab()}
</TabPanel>
<TabPanel id="fullresult" value="fullresult">
{this.renderFullResultTab()}
</TabPanel>
<TabPanel id="bets" value="bets">
{this.props.myBetsResultedBetTicket
? this.renderNewMyBets()
: this.renderMyBets()}
</TabPanel>
<TabPanel id="racecard" value="racecard">
{this.renderRaceCardtab()}
</TabPanel>
</Tabs>
</ROWrapper>
</Fragment>
);
}
}
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_static/images/hr-video-placeholder.jpg
export default __webpack_public_path__ + "d9cf865359c7501f92d5ccbb0b2b91b4.jpg";
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_templates/HorsePastPerformances/styled-components.js
import styled, { css } from "styled-components";
import { breakpoints } from "@tvg/design-system";
import horseImage from "../../_static/images/hr-video-placeholder.jpg";
import buildColor from "../../_static/ColorPalette";
export const InfoContainer = styled.div`
display: flex;
border-bottom: 1px solid ${buildColor("blue", "100")};
`;
export const HandicapInfoContainer = styled.div`
width: 100%;
`;
export const RunnerCell = styled.td`
height: 100%;
padding-top: 0;
padding-bottom: 0;
`;
export const RaceOfficialsWrapper = styled.div`
border-top: 1px solid ${buildColor("blue", "100")};
`;
export const LoadingState = styled.div`
width: 100%;
height: 100%;
${({ hasBackground }) =>
hasBackground &&
css`
background-color: ${buildColor("white", "100")};
`}
`;
export const ContentWrapper = styled.div`
width: 100%;
height: 100%;
background-color: ${buildColor("white", "100")};
${(props) =>
props.withBorders &&
css`
border-radius: 2px;
border: 1px solid ${buildColor("grey", "300")};
`};
`;
export const ModalWrapper = styled.div`
background-color: ${buildColor("white", "100")};
`;
export const VideoContainer = styled.div`
position: relative;
background-color: ${(props) =>
props.isVideoAvailable
? buildColor("white", "100")
: buildColor("black", "100")};
${({ isTvg5, isMobile }) =>
isTvg5 && !isMobile
? css`
height: 600px;
`
: css`
/* forces video to be 4:3 aspect ratio */
height: 0;
padding-top: 75%;
`}
& > div {
${({ isTvg5, isMobile }) =>
isTvg5 && !isMobile
? css`
height: 600px;
`
: css`
position: absolute;
inset: 0;
`}
}
`;
export const NoReplayContainer = styled.div`
min-height: inherit;
display: flex;
align-items: center;
justify-content: center;
background-image: url("${horseImage}");
background-position: 0 0;
background-size: cover;
background-repeat: no-repeat;
flex-direction: column;
text-align: center;
opacity: 0.7;
`;
export const NoReplayContainerMessage = styled.div`
min-height: inherit;
display: flex;
align-items: center;
justify-content: center;
background: transparent;
flex-direction: column;
text-align: center;
z-index: 10;
`;
export const IconContainer = styled.span`
width: 100%;
`;
export const MessageContainer = styled.span`
margin-top: 8px;
font-size: 12px;
color: ${buildColor("white", "100")};
`;
export const UnavailableVideoContainer = styled.div`
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
background-color: var(--fd-colors-core-blue-d-4);
padding: 0 56px;
& > :first-child svg {
width: 96px;
height: 96px;
}
@media screen and ${breakpoints.tablet.min.sm} {
flex-grow: 1;
}
`;
webpack://frontend-mybets/../../packages/tvg-atomic-ui/_templates/HorsePastPerformances/index.jsx
import React, { Component, Fragment } from "react";
import { noop, get, isEqual } from "lodash";
import RunnerInfoPastPerformance from "@tvg/ipp/src/components/RunnerInfoPastPerformance";
import { MyBetsPastPerformanceTab } from "@tvg/sh-lib-my-bets/utils/types";
import { Icon as DSIcon, Paragraph } from "@tvg/design-system/web";
import FeedbackOverlay from "../../_atom/FeedbackOverlay";
import InlinePastPerformanceInfo from "../../_molecule/PastPerformanceRace";
import MTPNotification from "../../_molecule/MTPNotification";
import { mtpNotificationConfigDefault } from "../../__mocks__/ipp-pastRaces.mock";
import RaceOfficials from "../RaceOfficials";
import Video from "../../_organism/Video";
import { info } from "../../_static/Icons/icons";
import Icon from "../../_static/Icons";
import buildColor from "../../_static/ColorPalette";
import {
InfoContainer,
LoadingState,
ContentWrapper,
ModalWrapper,
VideoContainer,
NoReplayContainer,
NoReplayContainerMessage,
IconContainer,
MessageContainer,
UnavailableVideoContainer
} from "./styled-components";
export default class HorsePastPerformances extends Component {
static defaultProps = {
runner: null,
hasNextRace: false,
hasPreviousRace: false,
onPreviousRaceNavigation: noop,
onNextRaceNavigation: noop,
results: null,
onTabClick: noop,
onModalClose: noop,
withBorders: false,
videoFullscreenTilt: false,
isLoading: true,
bettingInterests: [],
scratchedRunners: [],
raceBets: [],
wagerGroup: null,
myBetsResultedBetTicket: false,
replaySrc: null,
sendVideoGtmEvent: noop,
fullResults: [],
hasTimeformData: false,
deviceLockRotationToggle: noop,
device: "mobile",
enableRaceResultsReDesign: false,
seeAllHorsesGTM: noop,
handicappingRunnerFlags: {
title: "",
subtitle: "",
subtitleRunnerFlags: "",
flags: []
},
racePayoffsShift: false,
currentRace: {},
mtpNotificationConfig: mtpNotificationConfigDefault,
handicappingMTPNotification: false,
isVideoIframe: false,
disableFullscreen: false,
isAutoPlay: false,
isTvg5: false,
defaultTab: MyBetsPastPerformanceTab.FULL_RESULT,
races: []
};
shouldComponentUpdate(nextProps) {
const { race, runner, results, bettingInterests, raceBets } = this.props;
return (
!isEqual(results, nextProps.results) ||
!isEqual(race, nextProps.race) ||
!isEqual(runner, nextProps.runner) ||
!isEqual(bettingInterests, nextProps.bettingInterests) ||
!isEqual(raceBets, nextProps.raceBets) ||
!isEqual(this.props, nextProps)
);
}
renderResults = () => {
return (
<RaceOfficials
isResultsPending={false}
results={{
payoffs: get(this.props.results, "payoffs") || [],
runners: get(this.props.results, "runners") || []
}}
firstHandicapBold
defaultTab={this.props.defaultTab}
raceTypeCode={get(this.props.race, "raceTypeCode", "")}
raceNumber={get(this.props.race, "number", "")}
onTabClick={this.props.onTabClick}
handicapType="basic"
bettingInterests={this.props.bettingInterests}
hasNoHandicappingSelection
bets={this.props.raceBets}
wagerGroup={this.props.wagerGroup}
myBetsResultedBetTicket={this.props.myBetsResultedBetTicket}
fullResults={this.props.fullResults}
scratchedRunners={this.props.scratchedRunners}
runnerName={get(this.props.runner, "horseName")}
resultsType="full"
hasTimeformData={this.props.hasTimeformData}
winningTime={get(this.props.results, "winningTime")}
enableRaceResultsReDesign={this.props.enableRaceResultsReDesign}
seeAllHorsesGTM={this.props.seeAllHorsesGTM}
handicappingRunnerFlags={this.props.handicappingRunnerFlags}
raceId={get(this.props.race, "id")}
racePayoffsShift={this.props.racePayoffsShift}
device={this.props.device}
races={this.props.races}
/>
);
};
renderVideo = () =>
this.props.replaySrc && this.props.isVideoIframe ? (
<div>
<iframe
title="rcn-player-replay-video"
src={`${this.props.replaySrc}&autoplay=1`}
allowFullScreen="true"
width="100%"
height="100%"
allow={`fullscreen${this.props.isAutoPlay ? ";autoplay" : ""}`}
scrolling="no"
id="rcn-player-replay-video"
/>
</div>
) : (
<Video
raceId={get(this.props.race, "id")}
src={{ hd: null, sd: null, replay: this.props.replaySrc }}
isReplay
inlineVideo
onVideoPlay={this.props.sendVideoGtmEvent}
videoFullscreenTilt={this.props.videoFullscreenTilt}
deviceLockRotationToggle={this.props.deviceLockRotationToggle}
isAutoPlay={this.props.isAutoPlay}
disableFullscreen={this.props.disableFullscreen}
/>
);
renderVideoFallback = () =>
get(this.props, "isAccountCompliant", true) ? (
<Fragment>
<NoReplayContainer />
<NoReplayContainerMessage>
<IconContainer>
<Icon icon={info} color={buildColor("white", "100")} size={16} />
</IconContainer>
<MessageContainer>No replay available</MessageContainer>
</NoReplayContainerMessage>
</Fragment>
) : (
<UnavailableVideoContainer data-qa-label="unavailable-video-container">
<DSIcon
name="liveVideo"
size="xl"
qaLabel="live_video_icon"
lineColor="--fd-colors-component-button-transparent-content-base"
backgroundColor="transparent"
/>
<Paragraph
fontFamily="regular"
qaLabel="unavailable-message"
color="--fd-colors-component-button-transparent-content-base"
my="space-5"
textAlign="center"
>
{get(
this.props.watchFDTVMessages,
"unavailableVideo.notVerified",
"Verify your account to watch FanDuel TV"
)}
</Paragraph>
</UnavailableVideoContainer>
);
renderMTPNotification = () =>
this.props.handicappingMTPNotification && (
<MTPNotification
onModalClose={this.props.onModalClose}
currentRace={this.props.currentRace}
mtpNotificationConfig={this.props.mtpNotificationConfig}
/>
);
render() {
if (this.props.isLoading) {
<ModalWrapper>
<ContentWrapper withBorders={this.props.withBorders}>
<LoadingState>
<FeedbackOverlay
loadingIconColor={buildColor("grey", "900")}
overlayBgColor={buildColor("white", "70")}
/>
</LoadingState>
</ContentWrapper>
</ModalWrapper>;
}
return (
<ModalWrapper>
<ContentWrapper withBorders={this.props.withBorders}>
<InfoContainer borderless={this.props.withBorders}>
{this.props.enableRaceResultsReDesign ? (
<RunnerInfoPastPerformance
race={this.props.race}
hasNextRace={this.props.hasNextRace}
hasPreviousRace={this.props.hasPreviousRace}
onPreviousRaceNavigation={this.props.onPreviousRaceNavigation}
onNextRaceNavigation={this.props.onNextRaceNavigation}
hasNumberOfRunners={this.props.device !== "desktop"}
/>
) : (
<InlinePastPerformanceInfo
race={this.props.race}
hasNextRace={this.props.hasNextRace}
hasPreviousRace={this.props.hasPreviousRace}
useSimpleLayout
onPreviousRaceNavigation={this.props.onPreviousRaceNavigation}
onNextRaceNavigation={this.props.onNextRaceNavigation}
hasNumberOfRunners={this.props.device !== "desktop"}
/>
)}
</InfoContainer>
<VideoContainer
isVideoAvailable={
get(this.props, "race.hasReplays") && this.props.replaySrc
}
isPlaying={!!this.props.replaySrc}
isTvg5={this.props.isTvg5}
isMobile={this.props.device === "mobile"}
>
{get(this.props, "race.hasReplays") &&
get(this.props, "isAccountCompliant", true)
? this.renderVideo()
: this.renderVideoFallback()}
</VideoContainer>
{this.renderResults()}
{this.renderMTPNotification()}
</ContentWrapper>
</ModalWrapper>
);
}
}
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/graphql/queries/horsePastPerformance.ts
import { gql } from "@apollo/client";
export const GET_PAST_RACE = gql`
query getPastRace(
$wagerProfile: String!
$trackCode: String
$raceNumber: String
$date: String
) {
pastRaces(
trackCode: $trackCode
raceNumber: $raceNumber
date: $date
profile: $wagerProfile
) {
id
results {
winningTime
runners {
entityRunnerId
betAmount
biNumber
runnerNumber
finishPosition
finishStatus
placePayoff
runnerName
showPayoff
winPayoff
timeform {
postRaceReport
accBeatenDistance
accBeatenDistanceStatus
winningDistance
winningDistanceStatus
}
}
payoffs {
selections {
payoutAmount
selection
}
wagerAmount
wagerType {
code
name
}
}
}
bettingInterests {
biNumber
numberColor
saddleColor
favorite
currentOdds {
numerator
denominator
}
morningLineOdds {
numerator
denominator
}
runners {
handicapping {
speedAndClass {
avgClassRating
highSpeed
avgSpeed
lastClassRating
avgDistance
}
averagePace {
finish
numRaces
middle
early
}
jockeyTrainer {
places
jockeyName
trainerName
shows
wins
starts
}
snapshot {
powerRating
daysOff
horseWins
horseStarts
}
freePick {
number
info
}
}
horseName
runnerId
trainer
jockey
scratched
}
}
}
}
`;
export default GET_PAST_RACE;
webpack://frontend-mybets/../../packages/tvg-comp-inline-past-performance/src/PastPerformance/index.tsx
import React, { Component } from "react";
import { isEqual, noop, get } from "lodash";
import { connect } from "react-redux";
import { graphql } from "@apollo/client/react/hoc";
import mediator from "@tvg/mediator";
import type {
PastPerformanceRace,
RaceCardRunner,
PastRace,
RaceProgram,
FullResultRunner,
RaceCardBettingInterest,
RaceTypeCodeEnum,
MTPNotificationConfigType,
RaceBet
} from "@tvg/ts-types/Race";
import type { WroWagerGroup } from "@tvg/api/wro/types";
import type { WagerProfile } from "@tvg/ts-types/User";
import type { NullaryFn, UnaryFn } from "@tvg/ts-types/Functional";
import type { Device } from "@tvg/ts-types/Device";
import {
findRunnerInRace,
convertBettingInterests,
getStreamSrc
} from "@tvg/utils/pastPerformanceUtils";
import parseCapiMessage from "@tvg/utils/capiUtils";
import type { HandicappingRunnerFlags } from "@tvg/ipp/src/components/RunnerFlags";
import HorsePastPerformances from "@tvg/atomic-ui/_templates/HorsePastPerformances";
import type { TabKey } from "@tvg/ts-types/Generic";
import { mtpNotificationConfigDefault } from "@tvg/atomic-ui/__mocks__/ipp-pastRaces.mock";
import {
buildResults,
RESULTS_TEMPLATE
} from "@tvg/sh-lib-my-bets/utils/bettingInterests";
import { getAccountNumber } from "@urp/store-selectors";
import { isAccountCompliantSelector } from "@tvg/sh-utils/sessionUtils";
import { MyBetsPastPerformanceTab } from "@tvg/sh-lib-my-bets/utils/types";
import { Dispatch } from "redux";
import HorsePerformanceQuery from "../graphql/queries/horsePastPerformance";
import { ApolloOptionsPP } from "../graphql/options.graph";
type WatchFDTVMessages = {
unavailableVideo: {
notVerified: string;
};
};
type Props = {
device: Device;
runnerName: string;
trackCode: string;
raceNumber: string;
raceDate: string;
wagerProfile: WagerProfile;
selectedRace: PastPerformanceRace;
selectedRaceIndex: number;
races: PastPerformanceRace[];
wagerGroup: WroWagerGroup | null | undefined;
myBetsResultedBetTicket: boolean;
pastRace: PastRace | null | undefined;
fullResults: FullResultRunner[];
hasTimeformData: boolean;
hasNextRace: boolean;
hasPreviousRace: boolean;
onPreviousRaceNavigation: NullaryFn<void>;
onNextRaceNavigation: NullaryFn<void>;
onRaceFromList: UnaryFn<number, void>;
hasNavigation: boolean;
videoFullscreenTilt: boolean;
isRaceListView: boolean;
onClickGTMEvent: UnaryFn<RaceCardRunner, void>;
isLoading: boolean;
updateRunner: UnaryFn<RaceCardRunner, void>;
accountNumber: string;
raceBets: RaceBet[] | null | undefined;
onMatchConditions: NullaryFn<void>;
isMatchConditionsOn: boolean;
originRace: string;
raceTypeCode: RaceTypeCodeEnum;
activeRunner: string;
activeRunnerBI: RaceCardBettingInterest | null | undefined;
isLoadingRunner: boolean;
enableRaceResultsReDesign: boolean;
handicappingRunnerFlags: HandicappingRunnerFlags;
racePayoffsShift: boolean;
mtpNotificationConfig: MTPNotificationConfigType;
handicappingMTPNotification: boolean;
currentRace: RaceProgram;
onModalClose: NullaryFn<void>;
isVideoIframe: boolean;
disableFullscreen: boolean;
isFlash?: boolean;
isTvg5?: boolean;
isAutoPlay?: boolean;
pastPerformanceDefaultTab?: MyBetsPastPerformanceTab;
isAccountCompliant?: boolean;
watchFDTVDesktopMessages?: WatchFDTVMessages;
watchFDTVMobileMessages?: WatchFDTVMessages;
};
type State = {
replaySrc: string | undefined | null | {};
};
export class PastPerformanceComponent extends Component<Props, State> {
static defaultProps = {
dispatch: noop,
device: "mobile",
races: [],
wagerGroup: null,
myBetsResultedBetTicket: false,
fullResults: [],
runnerName: "",
wagerProfile: "PORT-Generic",
selectedRaceIndex: -1,
pastRace: null,
hasTimeformData: false,
hasPreviousRace: false,
hasNextRace: false,
onPreviousRaceNavigation: noop,
onNextRaceNavigation: noop,
onRaceFromList: noop,
hasNavigation: false,
videoFullscreenTilt: false,
isRaceListView: false,
onClickGTMEvent: noop,
isLoading: true,
updateRunner: noop,
accountNumber: "",
raceBets: null,
onMatchConditions: noop,
isMatchConditionsOn: false,
originRace: "",
raceTypeCode: "T",
activeRunner: "",
activeRunnerBI: null,
isLoadingRunner: false,
enableRaceResultsReDesign: false,
handicappingRunnerFlags: {
title: "",
subtitle: "",
subtitleRunnerFlags: "",
flags: []
},
racePayoffsShift: false,
mtpNotificationConfig: mtpNotificationConfigDefault,
handicappingMTPNotification: false,
currentRace: {},
onModalClose: noop,
isVideoIframe: false,
disableFullscreen: false,
isFlash: false,
isTvg5: false,
isAutoPlay: false,
watchFDTVDesktopMessages: {},
watchFDTVMobileMessages: {}
};
constructor(props: Props) {
super(props);
this.state = {
replaySrc: null
};
}
shouldComponentUpdate(nextProps: Props, nextState: State) {
const {
runnerName,
selectedRace,
selectedRaceIndex,
pastRace,
hasPreviousRace,
hasNextRace,
isLoading,
isMatchConditionsOn,
raceBets,
activeRunner,
isLoadingRunner
} = this.props;
return (
isMatchConditionsOn !== nextProps.isMatchConditionsOn ||
runnerName.toLowerCase() !== nextProps.runnerName.toLowerCase() ||
hasPreviousRace !== nextProps.hasPreviousRace ||
activeRunner !== nextProps.activeRunner ||
isLoadingRunner !== nextProps.isLoadingRunner ||
hasNextRace !== nextProps.hasNextRace ||
isLoading !== nextProps.isLoading ||
selectedRaceIndex !== nextProps.selectedRaceIndex ||
(nextState && nextState.replaySrc !== this.state.replaySrc) ||
!isEqual(nextProps.raceBets, raceBets) ||
!isEqual(selectedRace, nextProps.selectedRace) ||
!isEqual(pastRace, nextProps.pastRace)
);
}
componentDidUpdate(prevProps: Props) {
const runner = this.getRunner();
if (runner) {
this.props.updateRunner(runner);
}
if (this.props.pastRace && !prevProps.pastRace) {
// CLICKED ON A PP
if (runner) {
this.props.onClickGTMEvent(runner);
}
}
if (
this.props.selectedRace &&
this.props.selectedRace.hasReplays &&
(!this.state.replaySrc ||
!isEqual(this.props.selectedRace, prevProps.selectedRace))
) {
const replayFileName = get(this.props.selectedRace, "replayFileName");
getStreamSrc(replayFileName).then(
(data: { payload: {}; type: string }) => {
if (data.payload && data.type === "success") {
const replaySrc = get(data, "payload");
const finalReplaySrc =
this.props.isVideoIframe &&
replaySrc &&
typeof replaySrc === "string"
? replaySrc
.replace("replaysmobile.m3u8", "replaysflash.php")
.replace("race=", "stream=")
.concat(
this.props.isTvg5
? "&width=100%&height=100%"
: "&width=548&height=411"
)
: replaySrc;
this.setState({
replaySrc: finalReplaySrc
});
}
}
);
}
}
getRunner = (): RaceCardRunner | null => {
const { runnerName, pastRace } = this.props;
return pastRace
? findRunnerInRace(runnerName, pastRace?.bettingInterests || [])
: null;
};
changeRaceOfficialsTab = (tab: TabKey) => {
const actionType = {
result: "PAST_PERFORMANCES:VIEW_RESULTS",
racecard: "PAST_PERFORMANCES:VIEW_RACECARD",
bets: "PAST_PERFORMANCES:VIEW_BETS",
fullresult: "",
none: ""
};
if (actionType[tab]) {
mediator.base.dispatch({
type: actionType[tab],
payload: {
trackName: get(this.props.selectedRace, "track.name", ""),
runnerName: get(this.props, "runnerName", ""),
raceNumber: get(this.props.selectedRace, "number", "")
}
});
}
return true;
};
sendVideoGtmEvent = () => {
mediator.base.dispatch({
type: "PAST_PERFORMANCES:VIEW_REPLAY",
payload: {
trackName: get(this.props, "selectedRace.track.name"),
runnerName: this.props.runnerName,
raceNumber: get(this.props, "selectedRace.number")
}
});
};
deviceLockRotationToggle = (lock: boolean = true) => {
if (this.props.videoFullscreenTilt) {
mediator.ios.dispatch({
type: "IPHONE_LOCK_SCREEN_ROTATION",
payload: { lockScreenRotation: lock ? 0 : 2 }
});
}
};
seeAllHorsesGTM = () => {
mediator.base.dispatch({
type: "PAST_PERFORMANCES:SEE_ALL_RUNNERS"
});
};
render() {
const biData = convertBettingInterests(
get(this.props.pastRace, "bettingInterests") || []
);
return (
<HorsePastPerformances
results={buildResults(
get(this.props.pastRace, "results"),
RESULTS_TEMPLATE.emptyWinningTime
)}
races={this.props.races}
race={this.props.selectedRace}
runner={this.getRunner()}
hasPreviousRace={this.props.hasNavigation && this.props.hasPreviousRace}
hasNextRace={this.props.hasNavigation && this.props.hasNextRace}
onPreviousRaceNavigation={this.props.onPreviousRaceNavigation}
onNextRaceNavigation={this.props.onNextRaceNavigation}
isLoading={this.props.isLoading}
onTabClick={this.changeRaceOfficialsTab}
withBorders={this.props.device !== "mobile"}
bettingInterests={biData.bettingInterests}
scratchedRunners={biData.scratchedRunners}
raceBets={this.props.raceBets || []}
wagerGroup={this.props.wagerGroup}
myBetsResultedBetTicket={this.props.myBetsResultedBetTicket}
defaultTab={this.props.pastPerformanceDefaultTab}
replaySrc={this.state.replaySrc}
sendVideoGtmEvent={this.sendVideoGtmEvent}
fullResults={this.props.fullResults}
hasTimeformData={this.props.hasTimeformData}
videoFullscreenTilt={this.props.videoFullscreenTilt}
deviceLockRotationToggle={this.deviceLockRotationToggle}
device={this.props.device}
enableRaceResultsReDesign={this.props.enableRaceResultsReDesign}
seeAllHorsesGTM={this.seeAllHorsesGTM}
handicappingRunnerFlags={this.props.handicappingRunnerFlags}
racePayoffsShift={this.props.racePayoffsShift}
currentRace={this.props.currentRace}
mtpNotificationConfig={this.props.mtpNotificationConfig}
handicappingMTPNotification={
this.props.device === "mobile" &&
this.props.handicappingMTPNotification
}
onModalClose={this.props.onModalClose}
isVideoIframe={this.props.isVideoIframe}
disableFullscreen={this.props.disableFullscreen}
isAutoPlay={this.props.isAutoPlay}
isTvg5={this.props.isTvg5}
isAccountCompliant={this.props.isAccountCompliant}
watchFDTVMessages={
this.props.device === "mobile"
? this.props.watchFDTVMobileMessages
: this.props.watchFDTVDesktopMessages
}
/>
);
}
}
export default connect(
/* istanbul ignore next */
(store) => ({
// @ts-ignore
accountNumber: getAccountNumber(store),
hasNavigation: get(
store,
"capi.featureToggles.inLinePastPerformanceNavigation",
false
),
videoFullscreenTilt: get(
store,
"capi.featureToggles.videoFullscreenTilt",
false
),
enableRaceResultsReDesign: get(
store,
"capi.featureToggles.enableRaceResultsReDesign",
false
),
racePayoffsShift: get(store, "capi.featureToggles.RacePayoffsShift", false),
mtpNotificationConfig: parseCapiMessage(
store,
"capi.messages.mtpNotification"
),
handicappingMTPNotification: get(
store,
"capi.featureToggles.handicappingMTPNotification",
false
),
myBetsResultedBetTicket: get(
store,
"capi.featureToggles.myBetsResultedBetTicket",
false
),
pastPerformanceDefaultTab: get(
store,
"myBetsStandalone.pastPerformance.selectedTab"
),
// @ts-ignore
isAccountCompliant: isAccountCompliantSelector(store),
watchFDTVDesktopMessages: parseCapiMessage(
store,
"capi.messages.watchFDTVDesktop"
),
watchFDTVMobileMessages: parseCapiMessage(
store,
"capi.messages.watchFDTVMobile"
)
}),
/* istanbul ignore next */
(dispatch: Dispatch) => ({
dispatch
})
// @ts-ignore
)(graphql(HorsePerformanceQuery, ApolloOptionsPP)(PastPerformanceComponent));
webpack://frontend-mybets/../../packages/tvg-comp-pgm/actions/video.js
import axios from "axios";
import { get } from "lodash";
import tvgConf from "@tvg/conf";
const config = tvgConf().config();
// Declare existing actions
/**
* Request for hash
* @param {string} streamName Stream Value (required to build the hash)
* @param {string} streamName Replay File Value (required to build the hash)
* @param {number} timestamp Timestamp (unix)
*/
const generateRCNHash = (streamName, replayFile, timestamp) => {
const requests = [];
if (streamName) {
requests.push(
axios.get(`${config.service.rcn}/generateHash`, {
params: {
streamname: streamName,
timestamp
},
withCredentials: true
})
);
}
if (replayFile) {
requests.push(
axios.get(`${config.service.rcn}/generateHash`, {
params: {
streamname: replayFile,
timestamp
},
withCredentials: true
})
);
}
return Promise.all(requests);
};
const checkResponseLink = (response) => {
if (
typeof get(response, "data") === "object" &&
typeof get(response, "data.link") === "string"
) {
return {
type: "success",
payload: response.data.link
};
}
return {
type: "error",
payload: response.data
};
};
const requestStreamHTML5 = (streamName, isReplay, timestamp, hash, hd) =>
axios.get(
!isReplay
? "//stream.robertsstream.com/streammobile.php"
: "//replays.robertsstream.com/racereplays/replaysmobile.php",
{
params: {
...{
t: timestamp,
h: hash,
usr: "",
forceformat: "ios",
output: "json",
hd: hd ? "1" : "0"
},
...(!isReplay
? {
stream: streamName,
referer: "TVG"
}
: {
race: streamName,
cust: "TVG"
})
}
}
);
/**
* Request HTML5 Stream Link
* @param {string} streamName Stream Name
*/
export const getHTML5Stream = (
streamName,
isReplay,
hash,
timestamp,
hd = true
) =>
requestStreamHTML5(streamName, isReplay, timestamp, hash, hd)
.then(checkResponseLink)
.catch((err) => ({
type: "error",
payload: err.message
}));
const getStreamRequests = (streamName, replayFile, timestamp, hashes) => {
const requests = [];
if (hashes.streamHash) {
// SD Stream
requests.push(
getHTML5Stream(streamName, false, hashes.streamHash, timestamp, false)
);
// HD Stream
requests.push(
getHTML5Stream(streamName, false, hashes.streamHash, timestamp, true)
);
}
if (hashes.replayHash) {
// SD Replay
requests.push(
getHTML5Stream(replayFile, true, hashes.replayHash, timestamp, false)
);
}
return requests;
};
export const getStreamSrc =
(
streamName,
replayFile,
openModal = true,
isStreamHighDefinition = false,
onError
) =>
(dispatch) => {
dispatch({
type: "VIDEO_REQUEST_FETCHING",
payload: {
show: openModal
}
});
const timestamp = Math.floor(Date.now() / 1000);
return generateRCNHash(streamName, replayFile, timestamp)
.then((response) => {
const streamHash =
!!streamName && typeof response[0] !== "undefined"
? get(response, "[0].data.hash", "")
: "";
const replayIndex = streamName ? 1 : 0;
const replayHash =
typeof response[replayIndex] !== "undefined"
? get(response, `[${replayIndex}].data.hash`, "")
: "";
return {
streamHash,
replayHash
};
})
.then((hashes) =>
Promise.all(
getStreamRequests(streamName, replayFile, timestamp, hashes)
)
.then((streams) => {
const error = streams.reduce(
(final, stream) => (stream.type === "error" ? true : final),
false
);
if (error && typeof onError === "function") {
onError(
get(streams, "[0].type") === "error"
? get(streams, "[0].payload")
: get(streams, "[1].payload")
);
}
let src;
if (streamName) {
src = {
sd: isStreamHighDefinition
? get(streams, "[1]payload")
: get(streams, "[0]payload"),
hd: isStreamHighDefinition
? get(streams, "[1]payload")
: get(streams, "[0]payload"),
replay: get(streams, "[2]payload", null)
};
} else {
src = {
sd: null,
hd: null,
replay: get(streams, "[0]payload", null)
};
}
dispatch({
type: "VIDEO_REQUEST_SUCCESS",
payload: {
src,
show: openModal
}
});
})
.catch(() => {
dispatch({
type: "VIDEO_REQUEST_ERROR",
payload: {
show: openModal
}
});
})
)
.catch(() => {
dispatch({
type: "VIDEO_REQUEST_ERROR",
payload: {
show: openModal
}
});
});
};
export const closeVideo = () => ({
type: "VIDEO_CLOSE"
});
export const showVideo = () => ({
type: "VIDEO_OPEN"
});
webpack://frontend-mybets/../../packages/tvg-comp-my-bets-standalone/src/MyBetsPastPerformance.jsx
import React, { useState, useEffect } from "react";
import { connect } from "react-redux";
import { graphql } from "@apollo/client/react/hoc";
import { get, noop, first, flowRight as compose } from "lodash";
import { formatPastRaceDate } from "@tvg/formatter/dates";
import parseCAPIMessage from "@tvg/utils/capiUtils";
import { isTvg5 } from "@tvg/utils/generalUtils";
import {
getMyBetsPastPerformanceTrackCode,
getMyBetsPastPerformanceRaceNumber,
getMyBetsPastPerformanceDate,
getMyBetsPastPerformanceRaces
} from "@tvg/sh-lib-my-bets/redux/selectors";
import wro from "@tvg/api/wro";
import { formatWroBets } from "@tvg/utils/pastPerformanceUtils";
import {
ApolloOptionsRacePP,
ApolloOptionsWagerPP
} from "@tvg/ipp/src/graphql/options.graph";
import RacePerformanceQuery from "@tvg/ipp/src/graphql/queries/racePastPerformance";
import WagerGroupQuery from "@tvg/ipp/src/graphql/queries/wagerGroupQuery";
import WagerGroupQueryBehg from "@tvg/ipp/src/graphql/queries/wagerGroupQueryBehg";
import PastPerformance from "@tvg/ipp/src/PastPerformance";
import { LoadingState } from "@tvg/atomic-ui/_templates/HorsePastPerformances/styled-components";
import FeedbackOverlay from "@tvg/atomic-ui/_atom/FeedbackOverlay";
import buildColor from "@tvg/atomic-ui/_static/ColorPalette";
import { closeVideo } from "@tvg/program-page/actions/video";
import { getAccountNumber } from "@urp/store-selectors";
import { isAccountCompliantSelector } from "@tvg/sh-utils/sessionUtils";
const getRaceBets = (accountNumber, race) => {
const date = formatPastRaceDate(get(race, "date", ""));
return wro
.getMyBets(
{
startDate: date,
endDate: date,
track: get(race, "track.code"),
race: +get(race, "number")
},
accountNumber
)
.then((res) => (res.status === 200 ? formatWroBets(res) : []))
.catch(() => []);
};
export const MyBetsPastPerformance = (props) => {
const {
device,
handicappingRunnerFlags,
wagerProfile,
fcpClient,
raceTypeCode,
race,
queryGroupWagers,
accountNumber,
programPageVideoIsOpen,
dispatch,
trackCode,
raceNumber,
raceDate,
isVideoIframe,
disableFullscreen,
isFlash,
behgToggle,
storedRaces
} = props;
const [selectedRace, setSelectedRace] = useState(null);
const [raceBets, setRaceBets] = useState(null);
useEffect(() => {
if (!selectedRace && race) {
setSelectedRace(race);
}
}, [race]);
useEffect(() => {
if (!behgToggle && selectedRace) {
getRaceBets(accountNumber, selectedRace).then((wagerRaceBets) => {
setRaceBets(wagerRaceBets);
});
}
}, [selectedRace]);
useEffect(() => {
if (programPageVideoIsOpen) {
dispatch(closeVideo());
}
}, [programPageVideoIsOpen]);
if (!selectedRace) {
return (
<LoadingState hasBackground>
<FeedbackOverlay
loadingIconColor={buildColor("grey", "900")}
overlayBgColor={buildColor("white", "70")}
/>
</LoadingState>
);
}
return (
<PastPerformance
device={device}
selectedRace={selectedRace}
trackCode={trackCode}
raceNumber={raceNumber}
raceDate={formatPastRaceDate(raceDate)}
wagerProfile={wagerProfile}
fcpClient={fcpClient}
raceTypeCode={raceTypeCode}
handicappingRunnerFlags={handicappingRunnerFlags}
currentRace={selectedRace}
raceBets={raceBets}
wagerGroup={first(queryGroupWagers)}
isVideoIframe={isVideoIframe}
disableFullscreen={disableFullscreen}
isFlash={isFlash}
races={storedRaces}
/>
);
};
MyBetsPastPerformance.defaultProps = {
accountNumber: "",
device: "mobile",
wagerProfile: "PORT-Generic",
fcpClient: noop,
behgClient: noop,
queryGroupWagers: null,
raceTypeCode: "T",
handicappingRunnerFlags: {
title: "",
subtitle: "",
subtitleRunnerFlags: "",
flags: []
},
onModalClose: noop,
trackCode: "",
raceNumber: 1,
raceDate: "",
race: null,
storedRaces: [],
isVideoIframe: false,
disableFullscreen: false,
isFlash: false
};
export default connect(
(store, props) => ({
accountNumber: getAccountNumber(store),
behgToggle: get(store, "capi.featureToggles.tvgenablebehg", false),
myBetsResultedBetTicket: get(
store,
"capi.featureToggles.myBetsResultedBetTicket",
false
),
behgClient: props.behgClient,
wagerProfile: get(store, "userData.user.profile", ""),
handicappingRunnerFlags: parseCAPIMessage(
store,
"capi.messages.handicappingRunnerFlags"
),
storedRaces: getMyBetsPastPerformanceRaces(store),
trackCode: getMyBetsPastPerformanceTrackCode(store),
raceNumber: getMyBetsPastPerformanceRaceNumber(store),
raceDate: getMyBetsPastPerformanceDate(store),
programPageVideoIsOpen: get(store, "RaceProgramVideo.show", false),
isAccountCompliant: isAccountCompliantSelector(store)
}),
(dispatch) => ({ dispatch })
)(
compose(
graphql(RacePerformanceQuery, ApolloOptionsRacePP),
graphql(
isTvg5() ? WagerGroupQuery : WagerGroupQueryBehg,
ApolloOptionsWagerPP
)
)(MyBetsPastPerformance)
);
webpack://frontend-mybets/./src/pages/components/Modals/styled-components.ts
import styled from "styled-components"; export const Container = styled.div` padding: 12px; `;
webpack://frontend-mybets/./src/pages/components/Modals/WatchReplay.tsx
import React from "react";
import type { Dispatch } from "redux";
import { ApolloClient, NormalizedCacheObject } from "@apollo/client";
import ModalV2 from "@tvg/atomic-ui/_templates/ModalV2";
import PastPerformance from "@tvg/my-bets-standalone/src/MyBetsPastPerformance";
import { closeMybetsPastPerformance } from "@tvg/sh-lib-my-bets/redux/actions";
import { isSafari } from "@tvg/utils/mobileUtils";
import { TransitionState } from "../../../types";
import { Container } from "./styled-components";
const isSafariBrowser = isSafari();
const WatchReplayModal = ({
isOpen,
behgClient,
dispatch,
fcpClient,
modalTitle
}: {
isOpen: boolean;
dispatch: Dispatch;
behgClient: ApolloClient<NormalizedCacheObject>;
fcpClient: ApolloClient<NormalizedCacheObject>;
modalTitle: string;
}) => {
const onClose = () => {
dispatch(closeMybetsPastPerformance());
};
const props = {
title: modalTitle,
titleType: "default",
isOpen,
onClose,
qaLabel: "watch-replay",
hasShadow: true,
hasOverlay: true,
isFullWidth: false,
isContentTransparent: false,
isFullHeight: true,
layerOffset: 1,
hasContentMaxHeight: true,
contentMaxHeight: "100vh",
marginsForMaxHeight: "60px",
animation: "bottomFloating",
fixedWidth: "572px"
};
return (
<ModalV2 {...props}>
{(transitionState: TransitionState) => (
<Container>
<PastPerformance
device="mobile"
fcpClient={fcpClient}
behgClient={behgClient}
transitionState={transitionState}
disableFullscreen={isSafariBrowser}
isVideoIframe
isFlash
/>
</Container>
)}
</ModalV2>
);
};
export default WatchReplayModal;
webpack://frontend-mybets/../../packages/tvg-lib-utils/mobileUtils.js
import { includes } from "lodash";
import mediator from "@tvg/mediator";
import TvgConfig from "@tvg/conf";
export const isMobile = (product) =>
includes(
[
"ios2",
"androidwrapper",
"iosnative",
"androidnative",
"tvgandroid",
"fdrios",
"fdrandroid",
"fdrandroidgps"
],
product
);
export const isAndroid = (product) =>
includes(
["androidwrapper", "fdrandroid", "tvgandroid", "fdrandroidgps"],
product
);
/* eslint-disable consistent-return */
export const openExternalLink = (link, callback) => {
if (isMobile(TvgConfig().product)) {
mediator.ios.dispatch({
type: "OPEN_EXTERNAL_APP",
payload: { openExternalApp: link }
});
} else if (window) {
// eslint-disable-next-line security/detect-non-literal-fs-filename
const tab = window.open(link, "_blank");
if (tab) {
tab.focus();
}
if (callback) {
callback(tab);
}
}
};
export const isSafari = (allBrowsers = false) => {
if (
typeof window !== "undefined" &&
window.navigator &&
window.navigator.userAgent
) {
const ua = window.navigator.userAgent;
const iOS =
(!!ua.match(/iPad/i) || !ua.match(/iPhone/i)) && !!ua.match(/WebKit/i);
return (
iOS &&
!!ua.match(/Safari/i) &&
(allBrowsers || !ua.match(/CriOS/i)) &&
(allBrowsers || !ua.match(/Chrome/i))
);
}
return false;
};
export const isSafariBrowser = () => {
if (
typeof window !== "undefined" &&
window.navigator &&
window.navigator.userAgent
) {
const ua = window.navigator.userAgent;
// TODO: revisit this!!!
return (
ua.match(/WebKit/i) ||
(ua.match(/Safari/i) && !ua.match(/CriOS/i) && !ua.match(/Chrome/i))
);
}
return false;
};
export default isMobile;
webpack://frontend-mybets/./src/pages/components/MicroApp/index.tsx
/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { FC, useRef, useMemo, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { History } from "history";
import ApolloContext from "@tvg/utils/apolloContext";
import {
getBetCancelIsLoadingBetCancelRequest,
getBetCancelIsOpen,
getIsApproxPayoutModalOpen,
getIsMyBetsPastPerformanceOpen,
getPastPerformanceModaLTitle,
getTotalActiveBets,
getTotalSettledBets
} from "@tvg/sh-lib-my-bets/redux/selectors";
import MtpStatus from "@tvg/mtp-update/src";
import MyBetsDesktopComponent from "@tvg/my-bets-desktop";
import { usePromoOnboardingPoller } from "@tvg/sh-lib-promos-onboarding/hooks/usePromoOnboardingPoller";
import {
getPromoOnboardingPollerTime,
getPromosOnboardingToggle
} from "@tvg/sh-lib-promos-onboarding/redux/selectors";
import { getAccountNumber } from "@urp/store-selectors";
import BetCancelModal from "../Modals/BetCancel";
import ApproxPayoutHelpModal from "../Modals/ApproxPayoutHelp";
import WatchReplayModal from "../Modals/WatchReplay";
interface Props {
history: History;
isLogged: boolean;
product: string;
isCheckingLoginState: boolean;
}
const MicroApp: FC<Props> = ({ history, isLogged, isCheckingLoginState }) => {
const dispatch = useDispatch();
const isFirstRender = useRef(true);
const isLoadingBetCancelRequest = useSelector(
getBetCancelIsLoadingBetCancelRequest
);
const betCancelModalOpen = useSelector(getBetCancelIsOpen);
const pastPerformancesOpen = useSelector(getIsMyBetsPastPerformanceOpen);
const pastPerformancesModalTitle = useSelector(getPastPerformanceModaLTitle);
const approxPayoutModalOpen = useSelector(getIsApproxPayoutModalOpen);
const promoOnboardingPollerTime = useSelector(getPromoOnboardingPollerTime);
const activeBets = useSelector(getTotalActiveBets);
const settledBets = useSelector(getTotalSettledBets);
const accountId = useSelector(getAccountNumber);
const promoOnboardingToggle = useSelector(getPromosOnboardingToggle);
useEffect(() => {
if (!isLogged && !isFirstRender) {
history.push("/");
}
isFirstRender.current = false;
}, [isLogged]);
usePromoOnboardingPoller(
dispatch,
promoOnboardingToggle,
promoOnboardingPollerTime,
isLogged,
accountId
);
return useMemo(
() =>
!isCheckingLoginState && isLogged ? (
<ApolloContext.Consumer>
{(value: any) => (
<>
<MtpStatus>
<MyBetsDesktopComponent {...value} history={history} />
</MtpStatus>
<BetCancelModal
isOpen={!!betCancelModalOpen}
isLoading={!!isLoadingBetCancelRequest}
behgClient={value.behgClient}
dispatch={dispatch}
activeBets={activeBets}
settledBets={settledBets}
/>
<ApproxPayoutHelpModal
isOpen={approxPayoutModalOpen}
dispatch={dispatch}
/>
<WatchReplayModal
modalTitle={pastPerformancesModalTitle}
isOpen={!!pastPerformancesOpen}
dispatch={dispatch}
behgClient={value.behgClient}
fcpClient={value.fcpClient}
/>
</>
)}
</ApolloContext.Consumer>
) : (
<></>
),
[
isCheckingLoginState,
betCancelModalOpen,
approxPayoutModalOpen,
activeBets,
settledBets,
isLoadingBetCancelRequest,
pastPerformancesOpen,
pastPerformancesModalTitle
]
);
};
MicroApp.defaultProps = {
isLogged: false
};
export default MicroApp;
webpack://frontend-mybets/./src/pages/index.tsx
/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { PureComponent } from "react";
import { Route, Routes, HistoryRouterProps } from "react-router-dom";
import withRouter from "@tvg/utils/withCustomRouter";
import { connect } from "react-redux";
import { TvgSafeAreaProvider } from "@tvg/design-system/src/utils/tvgSafeAreaProvider";
import type { Dispatch } from "redux";
import { attempt, get, isEmpty } from "lodash";
import tvgConf from "@tvg/conf";
import LoginService from "@tvg/login-service";
import calculateFeatureOverride from "@tvg/utils/featuresUtils";
import * as mediatorClassic from "@tvg/mediator-classic/src";
import mediator from "@tvg/mediator";
import useMyBetsGtmSubscribers from "@tvg/gtm/src/modules/MyBets";
import {
Messages,
Feature,
MapFeatureToggles,
FeatureToggles,
UserData
} from "../actions/types";
import {
failFeaturesRequest,
failMessagesRequest,
successFeaturesRequest,
successMessagesRequest
} from "../actions/capi";
import {
getUserData,
setUserAccountNumber,
setUserLoggedState
} from "../actions/user";
import MicroApp from "./components/MicroApp";
type Props = {
dispatch: Dispatch<any>;
isLogged: boolean;
hasRequestedLogin: boolean;
features: Feature[];
featureToggles: MapFeatureToggles;
messages: Messages;
location: HistoryRouterProps;
history: HistoryRouterProps;
isBeta: boolean;
};
export class Main extends PureComponent<Props> {
tvg = tvgConf();
product = get(this.tvg, "product");
componentDidMount() {
if (typeof window !== "undefined") {
LoginService.validateSession().then(
(response: { success: { data: any } }) => {
if (response.success) {
// @ts-ignore
this.props.dispatch(getUserData(response.success.data));
this.props.dispatch(setUserLoggedState(true));
} else {
this.props.dispatch(setUserLoggedState(false));
}
}
);
if (!isEmpty(this.props.features)) {
const featureToggles = {};
let featureOverrides = this.getFeaturesOverrides() || {};
const hasFeaturesOverrides = !!this.getFeaturesOverrides();
this.props.features.forEach((toggle: Feature) => {
let { enabled } = toggle;
featureOverrides = calculateFeatureOverride(
hasFeaturesOverrides,
featureOverrides,
toggle
);
if (get(featureOverrides, toggle.name)) {
// @ts-ignore
enabled = featureOverrides[toggle.name].enabled; // eslint-disable-line
}
// @ts-ignore
featureToggles[toggle.name] = enabled;
});
if (typeof window !== "undefined" && !isEmpty(featureOverrides)) {
this.setFeaturesOverrides(featureOverrides);
}
this.props.dispatch(successFeaturesRequest(featureToggles));
} else {
this.getFeatures();
}
this.getMessages();
// tries to get the user id (accountNumber) from localStorage and dispatch it to user data
// this is useful because every component initialized by tvg-mobile will know if the user is logged, plus it's
// account number beforehand
attempt(() => {
if (window.sessionStorage.getItem("userId")) {
this.props.dispatch(
setUserAccountNumber(
window.sessionStorage.getItem("userId") as string
)
);
}
});
mediatorClassic.subscribe("UPDATE_ROUTER", this.updateRouter);
mediator.base.subscribe("TVG4_NAVIGATION", this.updateTVG4Navigation);
mediatorClassic.subscribeWithPast(
"TVG_LOGIN:USER_SESSION_UPDATE",
this.updateUserSession
);
mediator.base.subscribe(
"ACCOUNT_BALANCE_CHANGED",
this.updateAccountBalance
);
useMyBetsGtmSubscribers();
}
}
componentWillUnmount() {
mediatorClassic.unsubscribe("UPDATE_ROUTER", this.updateRouter);
mediator.base.unsubscribe("TVG4_NAVIGATION", this.updateTVG4Navigation);
mediatorClassic.unsubscribe(
"TVG_LOGIN:USER_SESSION_UPDATE",
this.updateUserSession
);
mediator.base.unsubscribe(
"ACCOUNT_BALANCE_CHANGED",
this.updateAccountBalance
);
}
updateRouter = () => {
const pathWithParameters = window.location.href.replace(
window.location.origin,
""
);
// @ts-ignore
if (this.props.location.pathname !== pathWithParameters) {
// @ts-ignore
this.props.history.replace(pathWithParameters);
}
};
updateTVG4Navigation = (data: any) => {
mediatorClassic.dispatch("TVG4_NAVIGATION", data.payload);
};
updateUserSession = (data: UserData) => {
this.props.dispatch(getUserData(data));
};
updateAccountBalance = (data: any) => {
mediatorClassic.dispatch(
"ACCOUNT_BALANCE_CHANGED",
data && data.payload ? data.payload : {}
);
};
getFeaturesOverrides = () =>
attempt(
() =>
JSON.parse(window.localStorage.getItem("featureOverrides") as string),
false
);
setFeaturesOverrides = (features: Feature) =>
attempt(() =>
window.localStorage.setItem("featureOverrides", JSON.stringify(features))
);
getFeatures = () =>
typeof window !== "undefined" &&
this.tvg
.getFeatures()
.then((response: FeatureToggles | false) => {
const featureToggles = {};
let featureOverrides = this.getFeaturesOverrides() || {};
const hasFeaturesOverrides = !!this.getFeaturesOverrides();
if (response && Array.isArray(response.featureToggles)) {
response.featureToggles.forEach((toggle: Feature) => {
let { enabled } = toggle;
featureOverrides = calculateFeatureOverride(
hasFeaturesOverrides,
featureOverrides,
toggle
);
if (get(featureOverrides, toggle.name)) {
// @ts-ignore
enabled = featureOverrides[toggle.name].enabled; // eslint-disable-line
}
// @ts-ignore
featureToggles[toggle.name] = enabled;
});
}
if (!isEmpty(featureOverrides)) {
this.setFeaturesOverrides(featureOverrides);
}
this.props.dispatch(successFeaturesRequest(featureToggles));
})
.catch((err: Error) => this.props.dispatch(failFeaturesRequest(err)));
getMessages = () => {
const messageNamespaces = ["Global", "Homepage"];
return this.tvg
.getMessages(messageNamespaces, true)
.then((response: any) =>
this.props.dispatch(successMessagesRequest(response))
)
.catch((err: Error) => this.props.dispatch(failMessagesRequest(err)));
};
render = () => (
<main>
<TvgSafeAreaProvider>
<Routes>
<Route
path="/my-bets"
element={
get(this.props.featureToggles, "myBetsDesktopMicroApp", false) ? (
<MicroApp
// @ts-ignore
history={this.props.history}
isLogged={this.props.isLogged}
product={this.product}
isCheckingLoginState={!this.props.hasRequestedLogin}
/>
) : null
}
/>
</Routes>
</TvgSafeAreaProvider>
</main>
);
}
export default connect(
(store) => ({
isLogged: get(store, "userData.logged"),
hasRequestedLogin: get(store, "userData.hasRequested"),
featureToggles: get(store, "capi.featureToggles"),
features: get(store, "capi.features"),
// @ts-ignore
messages: store.capi.messages
})
// @ts-ignore
)(withRouter(Main));
webpack://frontend-mybets/../../packages/tvg-lib-gtm/src/modules/MyBets.js
import mediatorChannels from "@tvg/mediator";
import { get } from "lodash";
import { formatDateToMMDDYYYY } from "@tvg/formatter/dates";
import pushToDataLayer, {
setFirstLetterCapital,
convertMyBetsFilterActive
} from "../gtmUtils";
export default () => {
mediatorChannels.base.subscribe("MYBETS_TAB_SELECT", (data) => {
pushToDataLayer({
event: "siteClick",
gaEventCategory: "Site Click",
gaEventAction: "Open",
tag: undefined,
gaEventLabel: get(data, "payload.tab"),
module: "Bets Modal",
microApp: "non-Microapp"
});
});
mediatorChannels.base.subscribe("MYBETS_STARTUP", (data) => {
pushToDataLayer({
pageData: {
activeBets: get(data, "payload.activeBetsCounter", 0),
settledBets: get(data, "payload.settledBetsCounter", 0)
}
});
});
mediatorChannels.base.subscribe("MYBETS_FILTERS_HANDLING", (data) => {
pushToDataLayer({
event: "myBets",
gaEventCategory: "My Bets",
gaEventAction: `${
get(data, "payload.isOpening") ? "Opened" : "Closed"
} Filter`,
gaEventLabel: get(data, "payload.filter"),
module: get(data, "payload.tab"),
filterActive: get(data, "payload.settledTab", "None"),
activeBets: get(data, "payload.activeBets", 0),
settledBets: get(data, "payload.settledBets", 0)
});
});
mediatorChannels.base.subscribe("CLEAR_MYBETS_FILTER_DROPDOWN", (data) => {
pushToDataLayer({
event: "myBets",
gaEventCategory: "My Bets",
gaEventAction: "Cleared Filter List",
gaEventLabel: get(data, "payload.name"),
module: "Settled",
filterActive: get(data, "payload.activeFilter", "None"),
activeBets: get(data, "payload.activeBets", 0),
settledBets: get(data, "payload.settledBets", 0)
});
});
mediatorChannels.base.subscribe("SELECT_MYBETS_FILTER_TYPE", (data) => {
pushToDataLayer({
event: "myBets",
gaEventCategory: "My Bets",
gaEventAction: "Selected Filter",
gaEventLabel: get(data, "payload.name"),
module: "Settled",
filterActive: get(data, "payload.activeFilter", "None"),
activeBets: get(data, "payload.activeBets", 0),
settledBets: get(data, "payload.settledBets", 0)
});
});
mediatorChannels.base.subscribe("SELECT_MYBETS_CUSTOM_DATE", (data) => {
pushToDataLayer({
event: "myBets",
gaEventCategory: "My Bets",
gaEventAction: "Selected Filter",
gaEventLabel: "Custom Date",
module: "Settled",
filterActive: "Custom Date",
activeBets: get(data, "payload.activeBets", 0),
settledBets: get(data, "payload.settledBets", 0)
});
});
mediatorChannels.base.subscribe("CLEAR_ALL_MYBETS_FILTERS", (data) => {
pushToDataLayer({
event: "myBets",
gaEventCategory: "My Bets",
gaEventAction: "Cleared All Filters",
gaEventLabel: undefined,
module: "Settled",
filterActive: get(data, "payload.activeFilter", "None"),
activeBets: get(data, "payload.activeBets", 0),
settledBets: get(data, "payload.settledBets", 0)
});
});
mediatorChannels.base.subscribe("MYBETS_GO_TO_TRACK", (data) => {
pushToDataLayer({
event: "Navigation",
gaEventCategory: "Navigation",
gaEventAction: "Navigated to",
menu: undefined,
gaEventLabel: `${get(data, "payload.trackName")} - ${get(
data,
"payload.number"
)} - ${get(data, "payload.mtp")}`,
module: "Bets Modal",
microApp: "non-Microapp",
sport: get(data, "payload.sport"),
tag: undefined,
destinationUrl: get(data, "payload.url")
});
});
mediatorChannels.base.subscribe("MYBETS_TIMEFRAME_SELECTED", (data) => {
const selectedTab =
get(data, "payload.tab", "") === "ACTIVE" ? "Active" : "Settled";
const timeframe =
selectedTab === "Active" ? "None" : get(data, "payload.timeframe", "");
pushToDataLayer({
event: "myBets",
gaEventCategory: "My Bets",
gaEventAction: "Selected Filter",
gaEventLabel: timeframe,
module: selectedTab,
filterActive: timeframe,
activeBets: get(data, "payload.activeBets", 0),
settledBets: get(data, "payload.settledBets", 0)
});
});
mediatorChannels.base.subscribe("MYBETS_OPEN_FROM_FOOTER", () => {
pushToDataLayer({
event: "siteClick",
gaEventCategory: "Site Click",
gaEventAction: "Open",
tag: undefined,
gaEventLabel: "Bets",
module: "Mobile Footer",
microApp: "non-Microapp"
});
});
mediatorChannels.base.subscribe("MYBETS_MODAL_CLOSE", () => {
pushToDataLayer({
event: "siteClick",
gaEventCategory: "Site Click",
gaEventAction: "Close",
tag: undefined,
gaEventLabel: "Bets",
module: "Bets Modal",
microApp: "non-Microapp"
});
});
mediatorChannels.base.subscribe("MYBETS_KEEP_BET", () => {
pushToDataLayer({
event: "siteClick",
gaEventCategory: "Site Click",
gaEventAction: "Keep Bet",
gaEventLabel: undefined,
module: "Delete Bet Modal",
tag: undefined,
microApp: "non-Microapp"
});
});
mediatorChannels.base.subscribe("MYBETS_CONFIRM_DELETE_BET", (data) => {
pushToDataLayer({
event: "bet",
gaEventCategory: "Bet",
gaEventAction: "Cancel Bet Success",
gaEventLabel: get(data, "payload.wagerSerialNumber"),
runnerAmount: get(data, "payload.runnerAmount"),
trackName: get(data, "payload.trackName"),
betAmount: get(data, "payload.betAmount"),
betType: get(data, "payload.betType"),
repeatBet: get(data, "payload.repeatBet"),
tag: undefined,
sport: `${get(data, "payload.runnerType")} Racing`,
runnerSelectionList: get(data, "payload.selections"),
raceNumber: get(data, "payload.raceNumber"),
module: get(data, "payload.module")
});
});
mediatorChannels.base.subscribe("MYBETS_ERROR_DELETE_BET", (data) => {
pushToDataLayer({
event: "bet",
gaEventCategory: "Bet",
gaEventAction: "Cancel Bet Error",
gaEventLabel: get(data, "payload.errorMessage"),
runnerAmount: get(data, "payload.runnerAmount"),
trackName: get(data, "payload.trackName"),
betAmount: get(data, "payload.betAmount"),
betType: get(data, "payload.betType"),
repeatBet: get(data, "payload.repeatBet"),
tag: undefined,
sport: `${get(data, "payload.runnerType")} Racing`,
runnerSelectionList: get(data, "payload.selections"),
raceNumber: get(data, "payload.raceNumber"),
module: "My Bets My Account"
});
});
mediatorChannels.base.subscribe("MYBETS_DELETE_BET", () => {
pushToDataLayer({
event: "siteClick",
gaEventCategory: "Site Click",
gaEventAction: "Open",
gaEventLabel: "Delete Bet",
module: "Bets Modal",
tag: undefined,
microApp: "non-Microapp"
});
});
mediatorChannels.base.subscribe("MYBETS_DELETE_BET_ERROR", (data) => {
pushToDataLayer({
event: "bet",
gaEventCategory: "Bet",
gaEventAction: "Delete Bet Error",
gaEventLabel: data.payload.errorId,
module: "My Bets My Account",
runnerSelectionList: data.payload.runnerSelection,
trackName: data.payload.trackName,
raceNumber: data.payload.raceNumber,
betId: data.payload.betId,
betAmount: data.payload.betAmount,
betType: data.payload.betType,
sport: data.payload.sport,
repeatBet: data.payload.repeatBet
});
});
mediatorChannels.base.subscribe("MYBETS_SHOW_DETAILS", (data) => {
pushToDataLayer({
event: "myBets",
gaEventCategory: "My Bets",
gaEventAction: get(data, "payload.show", false) ? "Opened Show" : "Hide",
gaEventLabel: "Show Details",
module: setFirstLetterCapital(get(data, "payload.selectedTab")),
filterActive: convertMyBetsFilterActive(
get(data, "payload.selectedTab", ""),
get(data, "payload.selectedSettledTab", "")
),
activeBets: get(data, "payload.totalActiveBets", 0),
settledBets: get(data, "payload.totalSettledBets", 0)
});
});
mediatorChannels.base.subscribe("HIDE-SHOW-LEGS-GTM", (data) => {
pushToDataLayer({
event: "myBets",
gaEventCategory: "My Bets",
gaEventAction: data.payload.isOpening
? "Opened Show/Hide"
: "Closed Show/Hide",
gaEventLabel: "All Legs",
module: "Active",
filterActive: "None",
activeBets: data.payload.activeBets,
settledBets: data.payload.settledBets
});
});
mediatorChannels.base.subscribe("MYBETS_CANCEL_BET", (data) => {
pushToDataLayer({
event: "myBets",
gaEventCategory: "My Bets",
gaEventAction: "Opened Modal",
gaEventLabel: "Cancel Bet Confirmation",
module: get(data, "payload.selectedTab"),
filterActive: convertMyBetsFilterActive(
get(data, "payload.selectedTab", ""),
get(data, "payload.selectedSettledTab", "")
),
activeBets: get(data, "payload.activeBets", 0),
settledBets: get(data, "payload.settledBets", 0)
});
});
mediatorChannels.base.subscribe("MYBETS_RETURN_TO_BETTING", (data) => {
pushToDataLayer({
event: "myBets",
gaEventCategory: "My Bets",
gaEventAction: "Navigated To",
gaEventLabel: "Return to Betting",
module: get(data, "payload.selectedTab"),
filterActive: convertMyBetsFilterActive(
get(data, "payload.selectedTab", ""),
get(data, "payload.selectedSettledTab", "")
)
});
});
mediatorChannels.base.subscribe("MYBETS_CLICKS_X_BUTTON", (data) => {
pushToDataLayer({
event: "myBets",
gaEventCategory: "My Bets",
gaEventAction: "Closed Screen",
gaEventLabel: "My Bets",
module: setFirstLetterCapital(get(data, "payload.selectedTab")),
filterActive: convertMyBetsFilterActive(
get(data, "payload.selectedTab", ""),
get(data, "payload.selectedSettledTab", "")
)
});
});
mediatorChannels.base.subscribe("MYBETS_OPEN_TRACK_RULES", (data) => {
pushToDataLayer({
event: "myBets",
gaEventCategory: "My Bets",
gaEventAction: "Opened Modal",
gaEventLabel: "See Track Rules",
module: get(data, "payload.selectedTab"),
filterActive: convertMyBetsFilterActive(
get(data, "payload.selectedTab", ""),
get(data, "payload.selectedSettledTab", "")
)
});
});
mediatorChannels.base.subscribe("MYBETS_USER_SAW_WARNING_MESSAGE", (data) => {
pushToDataLayer({
event: "myBets",
gaEventCategory: "My Bets",
gaEventAction: "Saw Message",
gaEventLabel: get(data, "payload.message", ""),
module: setFirstLetterCapital(get(data, "payload.selectedTab")),
filterActive: convertMyBetsFilterActive(
get(data, "payload.selectedTab", ""),
get(data, "payload.selectedSettledTab", "")
),
activeBets: get(data, "payload.activeBets", 0),
settledBets: get(data, "payload.settledBets", 0)
});
});
mediatorChannels.base.subscribe("MYBETS_USER_CLICKS_WATCH_REPLAY", (data) => {
pushToDataLayer({
event: "myBets",
gaEventCategory: "My Bets",
gaEventAction: "Navigated To",
gaEventLabel: get(data, "payload.gaEventLabel", "Watch Replay"),
module: setFirstLetterCapital(get(data, "payload.selectedTab")),
filterActive: convertMyBetsFilterActive(
get(data, "payload.selectedTab", ""),
get(data, "payload.selectedSettledTab", "")
),
activeBets: get(data, "payload.activeBets", 0),
settledBets: get(data, "payload.settledBets", 0)
});
});
mediatorChannels.base.subscribe(
"MYBETS_USER_CLICKS_VIDEO_LIVE_BUTTON",
(data) => {
pushToDataLayer({
event: "myBets",
gaEventCategory: "My Bets",
gaEventAction: "Navigated To",
gaEventLabel: "Race Card",
module: setFirstLetterCapital(get(data, "payload.selectedTab")),
filterActive: convertMyBetsFilterActive(
get(data, "payload.selectedTab", ""),
get(data, "payload.selectedSettledTab", "")
),
activeBets: get(data, "payload.activeBets", 0),
settledBets: get(data, "payload.settledBets", 0)
});
}
);
mediatorChannels.base.subscribe(
"MYBETS_USER_CLICKS_SEE_RULES_ON_CANCELLED_BET",
(data) => {
pushToDataLayer({
event: "myBets",
gaEventCategory: "My Bets",
gaEventAction: "Opened Modal",
gaEventLabel: "See Rules",
module: setFirstLetterCapital(get(data, "payload.selectedTab")),
filterActive: convertMyBetsFilterActive(
get(data, "payload.selectedTab", ""),
get(data, "payload.selectedSettledTab", "")
),
activeBets: get(data, "payload.activeBets", 0),
settledBets: get(data, "payload.settledBets", 0)
});
}
);
mediatorChannels.base.subscribe("MYBETS_TAB_CLICK", (data) => {
const myBetsBaseGtm = {
event: "myBets",
gaEventCategory: "My Bets",
gaEventAction: "Open Tab",
gaEventLabel: setFirstLetterCapital(get(data, "payload.selectedTab", "")),
module: setFirstLetterCapital(get(data, "payload.previousSelectedTab")),
filterActive: convertMyBetsFilterActive(
get(data, "payload.selectedTab", ""),
"TODAY"
),
activeBets: get(data, "payload.activeBets", 0),
settledBets: get(data, "payload.settledBets", 0)
};
const dataLayer =
get(data, "payload.selectedTab", "").toUpperCase() === "FUTURES"
? { ...myBetsBaseGtm, futureBets: get(data, "payload.futureBets", 0) }
: myBetsBaseGtm;
pushToDataLayer(dataLayer);
});
mediatorChannels.base.subscribe(
"MYBETS_EXPAND_COLLAPSE_INDIVIDUAL_LEG",
(data) => {
pushToDataLayer({
event: "myBets",
gaEventCategory: "My Bets",
gaEventAction: get(data, "payload.gaEventAction"),
gaEventLabel: get(data, "payload.legNumber"),
module: setFirstLetterCapital(get(data, "payload.selectedTab")),
filterActive: convertMyBetsFilterActive(
get(data, "payload.selectedTab", ""),
get(data, "payload.selectedSettledTab", "")
),
activeBets: get(data, "payload.activeBets", 0),
settledBets: get(data, "payload.settledBets", 0)
});
}
);
mediatorChannels.base.subscribe("MYBETS_PICKBET_CREATE_BET", (data) => {
pushToDataLayer({
event: "bet",
gaEventCategory: "Bet",
gaEventAction: "Create Bet",
gaEventLabel: undefined,
runnerAmount: get(data, "payload.runnerAmount"),
trackName: get(data, "payload.trackName"),
betAmount: get(data, "payload.betAmount"),
betType: get(data, "payload.betType"),
repeatBet: get(data, "payload.repeatBet"),
tag: undefined,
sport: get(data, "payload.sport"),
runnerSelectionList: get(data, "payload.runnerSelectionList"),
raceNumber: get(data, "payload.raceNumber"),
module: "My Bets My Account"
});
});
mediatorChannels.base.subscribe("MYBETS_POTENTIAL_PAYOUT_CLICK", (data) => {
pushToDataLayer({
event: "myBets",
gaEventCategory: "My Bets",
gaEventAction: "Opened Modal",
gaEventLabel: "Potential Payout",
module: setFirstLetterCapital(get(data, "payload.selectedTab")),
filterActive: convertMyBetsFilterActive(
get(data, "payload.selectedTab", ""),
get(data, "payload.selectedSettledTab", "")
),
activeBets: get(data, "payload.activeBets", 0),
settledBets: get(data, "payload.settledBets", 0)
});
});
mediatorChannels.base.subscribe("MYBETS_REPEAT_BET", (data) =>
pushToDataLayer({
event: "myBets",
gaEventCategory: "My Bets",
gaEventAction: get(data, "payload.gaEventAction", "Bet Success"),
gaEventLabel: get(data, "payload.gaEventLabel"),
module: get(data, "payload.module"),
linkText: get(data, "payload.gaEventLabel"),
linkUrl: undefined
})
);
mediatorChannels.base.subscribe("MYBETS_NAVIGATE_TO_TRACK", (data) => {
pushToDataLayer({
event: "myBets",
gaEventCategory: "My Bets",
gaEventAction: "Navigated to",
gaEventLabel: "Program Page",
module: setFirstLetterCapital(get(data, "payload.selectedTab")),
filterActive: convertMyBetsFilterActive(
get(data, "payload.selectedTab", ""),
get(data, "payload.selectedSettledTab", "")
),
activeBets: get(data, "payload.activeBets", 0),
settledBets: get(data, "payload.settledBets", 0)
});
});
};
webpack://frontend-mybets/../../packages/tvg-lib-utils/withCustomRouter.jsx
import React from "react";
import { useLocation, useNavigate, useParams } from "react-router-dom";
export const withRouter = (Component) => {
return (props) => {
const location = useLocation();
const history = useNavigate();
const match = { params: useParams() };
const customProps = {
history: {
back: () => history(-1),
goBack: () => history(-1),
location,
push: (url, state) => history(url, { state }),
replace: (url, state) =>
history(url, {
replace: true,
state
})
},
location,
match
};
return <Component {...customProps} {...props} />;
};
};
export default withRouter;
webpack://frontend-mybets/./src/entry-client.tsx
import React from "react";
// @ts-ignore
import { AppRegistry } from "react-native-web";
import { ApolloProvider } from "@apollo/client";
import { Provider } from "react-redux";
import { BrowserRouter } from "react-router-dom";
import tvgConf from "@tvg/conf";
import ApolloContext from "@tvg/utils/apolloContext";
// TODO: add gtm for this microapp
// import Registration from "@tvg/gtm/src/modules/Registration";
import { recoverQueriesFromBackground } from "@tvg/utils/generalUtils";
import { TVGThemeProviderWeb, TvgConfProvider } from "@tvg/design-system";
import { FormationTokens } from "@tvg/design-system/web";
import ApolloClient from "./apolloClient/ApolloClient";
import configureStore from "./configureStore";
import App from "./pages";
// @ts-ignore
const preloadedState = window.__MYBETS_PRELOADED_STATE__; // eslint-disable-line no-underscore-dangle
// @ts-ignore
window.handleNativeMessages = (type, body) => {
const message = {};
const postMessage =
window &&
// @ts-ignore
window.ReactNativeWebView &&
// @ts-ignore
window.ReactNativeWebView.postMessage;
if (postMessage) {
// @ts-ignore
message.type = type;
if (body) {
// @ts-ignore
message.body = body;
}
postMessage(JSON.stringify(message));
}
};
// random gui from the net...
const guid = () => {
const s4 = () =>
Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
return `${s4() + s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`;
};
// @ts-ignore
window.promiseChain = Promise.resolve();
// @ts-ignore
window.callbacks = {};
// @ts-ignore
window.nativeBridge = (type, data, success, error) => {
const msgObj = {
type,
body: data || {},
msgId: ""
};
if (success || error) {
msgObj.msgId = guid();
}
const msg = JSON.stringify(msgObj);
// @ts-ignore
window.promiseChain = window.promiseChain
.then(
() =>
new Promise((resolve) => {
console.log(`sending message ${msgObj.type}`);
if (msgObj.msgId !== "") {
// @ts-ignore
window.callbacks[msgObj.msgId] = {
onsuccess: success,
onerror: error
};
}
// @ts-ignore
window.ReactNativeWebView.postMessage(msg);
// @ts-ignore
resolve();
})
)
// @ts-ignore
.catch((e) => {
console.error(`nativeBridge promise failed ${e.message}`);
});
};
// @TODO GTM subscribers event init
// Registration();
const store = configureStore(preloadedState);
// gets conf for specific host / device
tvgConf(window.location.hostname, window.navigator.userAgent);
const defaultClient = ApolloClient.createClient(false);
if (typeof window !== "undefined") {
recoverQueriesFromBackground([defaultClient]);
}
const Main = () => (
<TvgConfProvider>
<TVGThemeProviderWeb isFanduelTheme={false}>
<FormationTokens />
<ApolloProvider client={defaultClient}>
<ApolloContext.Provider
value={{ behgClient: defaultClient, fcpClient: defaultClient }}
>
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
</ApolloContext.Provider>
</ApolloProvider>
</TVGThemeProviderWeb>
</TvgConfProvider>
);
const Render = () => {
AppRegistry.registerComponent("App", () => Main);
AppRegistry.runApplication("App", {
initialProps: {},
// @TODO check if we can improve the hydration
// hydrate: true,
rootTag: document.getElementById("mybets")
});
};
export default Render();