glass-app-manager
Version:
Informatica's Glass Framework CLI for bootstrapping
41,671 lines • 1.49 MB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('react-dom')) :
typeof define === 'function' && define.amd ? define(['exports', 'react', 'react-dom'], factory) :
(factory((global.Droplets = {}),global.React,global.ReactDOM));
}(this, (function (exports,React,_reactDom) { 'use strict';
var React__default = 'default' in React ? React['default'] : React;
_reactDom = _reactDom && _reactDom.hasOwnProperty('default') ? _reactDom['default'] : _reactDom;
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function commonjsRequire () {
throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
}
function unwrapExports (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var _extends_1 = createCommonjsModule(function (module) {
function _extends() {
module.exports = _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);
}
module.exports = _extends;
});
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
var defineProperty = _defineProperty;
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
var arrayWithHoles = _arrayWithHoles;
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
var iterableToArrayLimit = _iterableToArrayLimit;
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
var nonIterableRest = _nonIterableRest;
function _slicedToArray(arr, i) {
return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || nonIterableRest();
}
var slicedToArray = _slicedToArray;
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 objectWithoutPropertiesLoose = _objectWithoutPropertiesLoose;
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
var objectWithoutProperties = _objectWithoutProperties;
function _taggedTemplateLiteral(strings, raw) {
if (!raw) {
raw = strings.slice(0);
}
return Object.freeze(Object.defineProperties(strings, {
raw: {
value: Object.freeze(raw)
}
}));
}
var taggedTemplateLiteral = _taggedTemplateLiteral;
var classnames = createCommonjsModule(function (module) {
/*!
Copyright (c) 2017 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!arg) continue;
var argType = typeof arg;
if (argType === 'string' || argType === 'number') {
classes.push(arg);
} else if (Array.isArray(arg) && arg.length) {
var inner = classNames.apply(null, arg);
if (inner) {
classes.push(inner);
}
} else if (argType === 'object') {
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes.push(key);
}
}
}
}
return classes.join(' ');
}
if (module.exports) {
classNames.default = classNames;
module.exports = classNames;
} else {
window.classNames = classNames;
}
}());
});
/*
Based off glamor's StyleSheet, thanks Sunil ❤️
high performance StyleSheet for css-in-js systems
- uses multiple style tags behind the scenes for millions of rules
- uses `insertRule` for appending in production for *much* faster performance
// usage
import { StyleSheet } from '@emotion/sheet'
let styleSheet = new StyleSheet({ key: '', container: document.head })
styleSheet.insert('#box { border: 1px solid red; }')
- appends a css rule into the stylesheet
styleSheet.flush()
- empties the stylesheet of all its contents
*/
// $FlowFixMe
function sheetForTag(tag) {
if (tag.sheet) {
// $FlowFixMe
return tag.sheet;
} // this weirdness brought to you by firefox
/* istanbul ignore next */
for (var i = 0; i < document.styleSheets.length; i++) {
if (document.styleSheets[i].ownerNode === tag) {
// $FlowFixMe
return document.styleSheets[i];
}
}
}
function createStyleElement(options) {
var tag = document.createElement('style');
tag.setAttribute('data-emotion', options.key);
if (options.nonce !== undefined) {
tag.setAttribute('nonce', options.nonce);
}
tag.appendChild(document.createTextNode(''));
return tag;
}
var StyleSheet =
/*#__PURE__*/
function () {
function StyleSheet(options) {
this.isSpeedy = options.speedy === undefined ? 'production' === 'production' : options.speedy;
this.tags = [];
this.ctr = 0;
this.nonce = options.nonce; // key is the value of the data-emotion attribute, it's used to identify different sheets
this.key = options.key;
this.container = options.container;
this.before = null;
}
var _proto = StyleSheet.prototype;
_proto.insert = function insert(rule) {
// the max length is how many rules we have per style tag, it's 65000 in speedy mode
// it's 1 in dev because we insert source maps that map a single rule to a location
// and you can only have one source map per style tag
if (this.ctr % (this.isSpeedy ? 65000 : 1) === 0) {
var _tag = createStyleElement(this);
var before;
if (this.tags.length === 0) {
before = this.before;
} else {
before = this.tags[this.tags.length - 1].nextSibling;
}
this.container.insertBefore(_tag, before);
this.tags.push(_tag);
}
var tag = this.tags[this.tags.length - 1];
if (this.isSpeedy) {
var sheet = sheetForTag(tag);
try {
// this is a really hot path
// we check the second character first because having "i"
// as the second character will happen less often than
// having "@" as the first character
var isImportRule = rule.charCodeAt(1) === 105 && rule.charCodeAt(0) === 64; // this is the ultrafast version, works across browsers
// the big drawback is that the css won't be editable in devtools
sheet.insertRule(rule, // we need to insert @import rules before anything else
// otherwise there will be an error
// technically this means that the @import rules will
// _usually_(not always since there could be multiple style tags)
// be the first ones in prod and generally later in dev
// this shouldn't really matter in the real world though
// @import is generally only used for font faces from google fonts and etc.
// so while this could be technically correct then it would be slower and larger
// for a tiny bit of correctness that won't matter in the real world
isImportRule ? 0 : sheet.cssRules.length);
} catch (e) {
}
} else {
tag.appendChild(document.createTextNode(rule));
}
this.ctr++;
};
_proto.flush = function flush() {
// $FlowFixMe
this.tags.forEach(function (tag) {
return tag.parentNode.removeChild(tag);
});
this.tags = [];
this.ctr = 0;
};
return StyleSheet;
}();
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, m).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, m).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;
}
var weakMemoize = function weakMemoize(func) {
// $FlowFixMe flow doesn't include all non-primitive types as allowed for weakmaps
var cache = new WeakMap();
return function (arg) {
if (cache.has(arg)) {
// $FlowFixMe
return cache.get(arg);
}
var ret = func(arg);
cache.set(arg, ret);
return ret;
};
};
// https://github.com/thysultan/stylis.js/tree/master/plugins/rule-sheet
// inlined to avoid umd wrapper and peerDep warnings/installing stylis
// since we use stylis after closure compiler
var delimiter = '/*|*/';
var needle = delimiter + '}';
function toSheet(block) {
if (block) {
Sheet.current.insert(block + '}');
}
}
var Sheet = {
current: null
};
var ruleSheet = function ruleSheet(context, content, selectors, parents, line, column, length, ns, depth, at) {
switch (context) {
// property
case 1:
{
switch (content.charCodeAt(0)) {
case 64:
{
// @import
Sheet.current.insert(content + ';');
return '';
}
// charcode for l
case 108:
{
// charcode for b
// this ignores label
if (content.charCodeAt(2) === 98) {
return '';
}
}
}
break;
}
// selector
case 2:
{
if (ns === 0) return content + delimiter;
break;
}
// at-rule
case 3:
{
switch (ns) {
// @font-face, @page
case 102:
case 112:
{
Sheet.current.insert(selectors[0] + content);
return '';
}
default:
{
return content + (at === 0 ? delimiter : '');
}
}
}
case -2:
{
content.split(needle).forEach(toSheet);
}
}
};
var removeLabel = function removeLabel(context, content) {
if (context === 1 && // charcode for l
content.charCodeAt(0) === 108 && // charcode for b
content.charCodeAt(2) === 98 // this ignores label
) {
return '';
}
};
var isBrowser = typeof document !== 'undefined';
var rootServerStylisCache = {};
var getServerStylisCache = isBrowser ? undefined : weakMemoize(function () {
var getCache = weakMemoize(function () {
return {};
});
var prefixTrueCache = {};
var prefixFalseCache = {};
return function (prefix) {
if (prefix === undefined || prefix === true) {
return prefixTrueCache;
}
if (prefix === false) {
return prefixFalseCache;
}
return getCache(prefix);
};
});
var createCache = function createCache(options) {
if (options === undefined) options = {};
var key = options.key || 'css';
var stylisOptions;
if (options.prefix !== undefined) {
stylisOptions = {
prefix: options.prefix
};
}
var stylis = new stylis_min(stylisOptions);
var inserted = {}; // $FlowFixMe
var container;
if (isBrowser) {
container = options.container || document.head;
var nodes = document.querySelectorAll("style[data-emotion-" + key + "]");
Array.prototype.forEach.call(nodes, function (node) {
var attrib = node.getAttribute("data-emotion-" + key); // $FlowFixMe
attrib.split(' ').forEach(function (id) {
inserted[id] = true;
});
if (node.parentNode !== container) {
container.appendChild(node);
}
});
}
var _insert;
if (isBrowser) {
stylis.use(options.stylisPlugins)(ruleSheet);
_insert = function insert(selector, serialized, sheet, shouldCache) {
var name = serialized.name;
Sheet.current = sheet;
stylis(selector, serialized.styles);
if (shouldCache) {
cache.inserted[name] = true;
}
};
} else {
stylis.use(removeLabel);
var serverStylisCache = rootServerStylisCache;
if (options.stylisPlugins || options.prefix !== undefined) {
stylis.use(options.stylisPlugins); // $FlowFixMe
serverStylisCache = getServerStylisCache(options.stylisPlugins || rootServerStylisCache)(options.prefix);
}
var getRules = function getRules(selector, serialized) {
var name = serialized.name;
if (serverStylisCache[name] === undefined) {
serverStylisCache[name] = stylis(selector, serialized.styles);
}
return serverStylisCache[name];
};
_insert = function _insert(selector, serialized, sheet, shouldCache) {
var name = serialized.name;
var rules = getRules(selector, serialized);
{
// in regular mode, we don't set the styles on the inserted cache
// since we don't need to and that would be wasting memory
// we return them so that they are rendered in a style tag
if (shouldCache) {
cache.inserted[name] = true;
}
return rules;
}
};
}
var cache = {
key: key,
sheet: new StyleSheet({
key: key,
container: container,
nonce: options.nonce,
speedy: options.speedy
}),
nonce: options.nonce,
inserted: inserted,
registered: {},
insert: _insert
};
return cache;
};
/* eslint-disable */
// murmurhash2 via https://github.com/garycourt/murmurhash-js/blob/master/murmurhash2_gc.js
function murmurhash2_32_gc(str) {
var l = str.length,
h = l ^ 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).toString(36);
}
var unitlessKeys = {
animationIterationCount: 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,
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
};
function memoize(fn) {
var cache = {};
return function (arg) {
if (cache[arg] === undefined) cache[arg] = fn(arg);
return cache[arg];
};
}
var hyphenateRegex = /[A-Z]|^ms/g;
var animationRegex = /_EMO_([^_]+?)_([^]*?)_EMO_/g;
var processStyleName = memoize(function (styleName) {
return styleName.replace(hyphenateRegex, '-$&').toLowerCase();
});
var processStyleValue = function processStyleValue(key, value) {
if (value == null || typeof value === 'boolean') {
return '';
}
switch (key) {
case 'animation':
case 'animationName':
{
if (typeof value === 'string') {
value = value.replace(animationRegex, function (match, p1, p2) {
cursor = {
name: p1,
styles: p2,
next: cursor
};
return p1;
});
}
}
}
if (unitlessKeys[key] !== 1 && key.charCodeAt(1) !== 45 && // custom properties
typeof value === 'number' && value !== 0) {
return value + 'px';
}
return value;
};
function handleInterpolation(mergedProps, registered, interpolation, couldBeSelectorInterpolation) {
if (interpolation == null) {
return '';
}
if (interpolation.__emotion_styles !== undefined) {
return interpolation;
}
switch (typeof interpolation) {
case 'boolean':
{
return '';
}
case 'object':
{
if (interpolation.anim === 1) {
cursor = {
name: interpolation.name,
styles: interpolation.styles,
next: cursor
};
return interpolation.name;
}
if (interpolation.styles !== undefined) {
var next = interpolation.next;
if (next !== undefined) {
// not the most efficient thing ever but this is a pretty rare case
// and there will be very few iterations of this generally
while (next !== undefined) {
cursor = {
name: next.name,
styles: next.styles,
next: cursor
};
next = next.next;
}
}
var styles = interpolation.styles;
return styles;
}
return createStringFromObject(mergedProps, registered, interpolation);
}
case 'function':
{
if (mergedProps !== undefined) {
var previousCursor = cursor;
var result = interpolation(mergedProps);
cursor = previousCursor;
return handleInterpolation(mergedProps, registered, result, couldBeSelectorInterpolation);
}
}
// eslint-disable-next-line no-fallthrough
default:
{
if (registered == null) {
return interpolation;
}
var cached = registered[interpolation];
return cached !== undefined && !couldBeSelectorInterpolation ? cached : interpolation;
}
}
}
function createStringFromObject(mergedProps, registered, obj) {
var string = '';
if (Array.isArray(obj)) {
for (var i = 0; i < obj.length; i++) {
string += handleInterpolation(mergedProps, registered, obj[i], false);
}
} else {
for (var _key in obj) {
var value = obj[_key];
if (typeof value !== 'object') {
if (registered != null && registered[value] !== undefined) {
string += _key + "{" + registered[value] + "}";
} else {
string += processStyleName(_key) + ":" + processStyleValue(_key, value) + ";";
}
} else {
if (_key === 'NO_COMPONENT_SELECTOR' && 'production' !== 'production') {
throw new Error('Component selectors can only be used in conjunction with babel-plugin-emotion.');
}
if (Array.isArray(value) && typeof value[0] === 'string' && (registered == null || registered[value[0]] === undefined)) {
for (var _i = 0; _i < value.length; _i++) {
string += processStyleName(_key) + ":" + processStyleValue(_key, value[_i]) + ";";
}
} else {
string += _key + "{" + handleInterpolation(mergedProps, registered, value, false) + "}";
}
}
}
}
return string;
}
var labelPattern = /label:\s*([^\s;\n{]+)\s*;/g;
// keyframes are stored on the SerializedStyles object as a linked list
var cursor;
var serializeStyles = function serializeStyles(args, registered, mergedProps) {
if (args.length === 1 && typeof args[0] === 'object' && args[0] !== null && args[0].styles !== undefined) {
return args[0];
}
var stringMode = true;
var styles = '';
cursor = undefined;
var strings = args[0];
if (strings == null || strings.raw === undefined) {
stringMode = false;
styles += handleInterpolation(mergedProps, registered, strings, false);
} else {
styles += strings[0];
} // we start at 1 since we've already handled the first arg
for (var i = 1; i < args.length; i++) {
styles += handleInterpolation(mergedProps, registered, args[i], styles.charCodeAt(styles.length - 1) === 46);
if (stringMode) {
styles += strings[i];
}
}
labelPattern.lastIndex = 0;
var identifierName = '';
var match; // https://esbench.com/bench/5b809c2cf2949800a0f61fb5
while ((match = labelPattern.exec(styles)) !== null) {
identifierName += '-' + // $FlowFixMe we know it's not null
match[1];
}
var name = murmurhash2_32_gc(styles) + identifierName;
return {
name: name,
styles: styles,
next: cursor
};
};
var isBrowser$1 = typeof document !== 'undefined';
function getRegisteredStyles(registered, registeredStyles, classNames) {
var rawClassName = '';
classNames.split(' ').forEach(function (className) {
if (registered[className] !== undefined) {
registeredStyles.push(registered[className]);
} else {
rawClassName += className + " ";
}
});
return rawClassName;
}
var insertStyles = function insertStyles(cache, serialized, isStringTag) {
var className = cache.key + "-" + serialized.name;
if ( // we only need to add the styles to the registered cache if the
// class name could be used further down
// the tree but if it's a string tag, we know it won't
// so we don't have to add it to registered cache.
// this improves memory usage since we can avoid storing the whole style string
(isStringTag === false || // we need to always store it if we're in compat mode and
// in node since emotion-server relies on whether a style is in
// the registered cache to know whether a style is global or not
// also, note that this check will be dead code eliminated in the browser
isBrowser$1 === false && cache.compat !== undefined) && cache.registered[className] === undefined) {
cache.registered[className] = serialized.styles;
}
if (cache.inserted[serialized.name] === undefined) {
var stylesForSSR = '';
var current = serialized;
do {
var maybeStyles = cache.insert("." + className, current, cache.sheet, true);
if (!isBrowser$1 && maybeStyles !== undefined) {
stylesForSSR += maybeStyles;
}
current = current.next;
} while (current !== undefined);
if (!isBrowser$1 && stylesForSSR.length !== 0) {
return stylesForSSR;
}
}
};
function insertWithoutScoping(cache, serialized) {
if (cache.inserted[serialized.name] === undefined) {
return cache.insert('', serialized, cache.sheet, true);
}
}
function merge(registered, css, className) {
var registeredStyles = [];
var rawClassName = getRegisteredStyles(registered, registeredStyles, className);
if (registeredStyles.length < 2) {
return className;
}
return rawClassName + css(registeredStyles);
}
var createEmotion = function createEmotion(options) {
var cache = createCache(options); // $FlowFixMe
cache.sheet.speedy = function (value) {
this.isSpeedy = value;
};
cache.compat = true;
var css = function css() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var serialized = serializeStyles(args, cache.registered, this !== undefined ? this.mergedProps : undefined);
insertStyles(cache, serialized, false);
return cache.key + "-" + serialized.name;
};
var keyframes = function keyframes() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
var serialized = serializeStyles(args, cache.registered);
var animation = "animation-" + serialized.name;
insertWithoutScoping(cache, {
name: serialized.name,
styles: "@keyframes " + animation + "{" + serialized.styles + "}"
});
return animation;
};
var injectGlobal = function injectGlobal() {
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
var serialized = serializeStyles(args, cache.registered);
insertWithoutScoping(cache, serialized);
};
var cx = function cx() {
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
return merge(cache.registered, css, classnames$1(args));
};
return {
css: css,
cx: cx,
injectGlobal: injectGlobal,
keyframes: keyframes,
hydrate: function hydrate(ids) {
ids.forEach(function (key) {
cache.inserted[key] = true;
});
},
flush: function flush() {
cache.registered = {};
cache.inserted = {};
cache.sheet.flush();
},
// $FlowFixMe
sheet: cache.sheet,
cache: cache,
getRegisteredStyles: getRegisteredStyles.bind(null, cache.registered),
merge: merge.bind(null, cache.registered, css)
};
};
var classnames$1 = function classnames(args) {
var cls = '';
for (var i = 0; i < args.length; i++) {
var arg = args[i];
if (arg == null) continue;
var toAdd = void 0;
switch (typeof arg) {
case 'boolean':
break;
case 'object':
{
if (Array.isArray(arg)) {
toAdd = classnames(arg);
} else {
toAdd = '';
for (var k in arg) {
if (arg[k] && k) {
toAdd && (toAdd += ' ');
toAdd += k;
}
}
}
break;
}
default:
{
toAdd = arg;
}
}
if (toAdd) {
cls && (cls += ' ');
cls += toAdd;
}
}
return cls;
};
var _createEmotion = createEmotion(),
flush = _createEmotion.flush,
hydrate = _createEmotion.hydrate,
cx = _createEmotion.cx,
merge$1 = _createEmotion.merge,
getRegisteredStyles$1 = _createEmotion.getRegisteredStyles,
injectGlobal = _createEmotion.injectGlobal,
keyframes = _createEmotion.keyframes,
css = _createEmotion.css,
sheet = _createEmotion.sheet,
cache = _createEmotion.cache;
function _templateObject2() {
var data = taggedTemplateLiteral(["\n ::after {\n left: ", ";\n transform: translateX(", ");\n }\n "]);
_templateObject2 = function _templateObject2() {
return data;
};
return data;
}
function _templateObject() {
var data = taggedTemplateLiteral(["\n ::after {\n top: ", ";\n transform: translateY(", ");\n }\n "]);
_templateObject = function _templateObject() {
return data;
};
return data;
}
var getOffsetCss = function getOffsetCss(location, offset, distance) {
switch (location) {
case "left":
case "right":
return css(_templateObject(), offset === "top" ? "".concat(distance, "px") : "calc(100% - ".concat(distance, "px)"), offset === "top" ? "0" : "-100%");
case "top":
case "bottom":
return css(_templateObject2(), offset === "left" ? "".concat(distance, "px") : "calc(100% - ".concat(distance, "px)"), offset === "left" ? "0" : "-100%");
default:
return "";
}
};
var Bubble = React.forwardRef(function (_ref, ref) {
var children = _ref.children,
className = _ref.className,
_ref$distance = _ref.distance,
distance = _ref$distance === void 0 ? 10 : _ref$distance,
_ref$position = _ref.position,
position = _ref$position === void 0 ? "bottom" : _ref$position,
_ref$variant = _ref.variant,
variant = _ref$variant === void 0 ? "light" : _ref$variant,
rest = objectWithoutProperties(_ref, ["children", "className", "distance", "position", "variant"]);
var _position$split = position.split("-"),
_position$split2 = slicedToArray(_position$split, 2),
location = _position$split2[0],
offset = _position$split2[1]; //TODO: refine location and offset type so getOffsetCss can be more explicit about its types
return React.createElement("div", _extends_1({
className: classnames("d-bubble", "d-bubble--".concat(variant), "d-bubble--".concat(location), className, defineProperty({}, getOffsetCss(location, offset, distance), !!offset)),
ref: ref
}, rest), children);
});
var wrapTextNode = function wrapTextNode(node) {
if (typeof node === "string") {
return React__default.createElement("span", null, node);
}
return node;
};
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === 'function') {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function (key) {
defineProperty(target, key, source[key]);
});
}
return target;
}
var objectSpread = _objectSpread;
var BaseButton = React.forwardRef(function (_ref, ref) {
var _ref$className = _ref.className,
className = _ref$className === void 0 ? "" : _ref$className,
children = _ref.children,
_ref$component = _ref.component,
component = _ref$component === void 0 ? "button" : _ref$component,
_ref$disabled = _ref.disabled,
disabled = _ref$disabled === void 0 ? false : _ref$disabled,
rest = objectWithoutProperties(_ref, ["className", "children", "component", "disabled"]);
return React.createElement(component, objectSpread({
ref: ref,
className: className,
tabIndex: "0"
}, disabled ? {
"aria-disabled": true
} : {}, component === "button" ? {
type: "button"
} : {
role: "button"
}, {
disabled: disabled
}, rest), children);
});
BaseButton.displayName = "BaseButton";
var Button = React.forwardRef(function (_ref, ref) {
var className = _ref.className,
children = _ref.children,
_ref$variant = _ref.variant,
variant = _ref$variant === void 0 ? "secondary" : _ref$variant,
rest = objectWithoutProperties(_ref, ["className", "children", "variant"]);
return React.createElement(BaseButton, _extends_1({
className: classnames("button", "button--".concat(variant), className)
}, rest, {
ref: ref
}), React.Children.map(children, wrapTextNode));
});
Button.displayName = "Button";
var IconButton = React.forwardRef(function (_ref, ref) {
var className = _ref.className,
children = _ref.children,
variant = _ref.variant,
rest = objectWithoutProperties(_ref, ["className", "children", "variant"]);
return React.createElement(BaseButton, _extends_1({
className: classnames("icon-button", defineProperty({}, "icon-button--".concat(variant), !!variant), className)
}, rest, {
ref: ref
}), children);
});
IconButton.displayName = "IconButton";
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var classCallCheck = _classCallCheck;
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;
}
var createClass = _createClass;
var _typeof_1 = createCommonjsModule(function (module) {
function _typeof2(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof2 = function _typeof2(obj) { return typeof obj; }; } else { _typeof2 = function _typeof2(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof2(obj); }
function _typeof(obj) {
if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") {
module.exports = _typeof = function _typeof(obj) {
return _typeof2(obj);
};
} else {
module.exports = _typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2(obj);
};
}
return _typeof(obj);
}
module.exports = _typeof;
});
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
var assertThisInitialized = _assertThisInitialized;
function _possibleConstructorReturn(self, call) {
if (call && (_typeof_1(call) === "object" || typeof call === "function")) {
return call;
}
return assertThisInitialized(self);
}
var possibleConstructorReturn = _possibleConstructorReturn;
var getPrototypeOf = createCommonjsModule(function (module) {
function _getPrototypeOf(o) {
module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
module.exports = _getPrototypeOf;
});
var setPrototypeOf = createCommonjsModule(function (module) {
function _setPrototypeOf(o, p) {
module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
module.exports = _setPrototypeOf;
});
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) setPrototypeOf(subClass, superClass);
}
var inherits = _inherits;
var CardBody =
/*#__PURE__*/
function (_PureComponent) {
inherits(CardBody, _PureComponent);
function CardBody() {
classCallCheck(this, CardBody);
return possibleConstructorReturn(this, getPrototypeOf(CardBody).apply(this, arguments));
}
createClass(CardBody, [{
key: "render",
value: function render() {
return React__default.createElement("div", {
className: "d-card__body"
}, this.props.children);
}
}]);
return CardBody;
}(React.PureComponent);
var CardHeader =
/*#__PURE__*/
function (_PureComponent) {
inherits(CardHeader, _PureComponent);
function CardHeader() {
classCallCheck(this, CardHeader);
return possibleConstructorReturn(this, getPrototypeOf(CardHeader).apply(this, arguments));
}
createClass(CardHeader, [{
key: "render",
value: function render() {
return React__default.createElement("div", {
className: "d-card__header"
}, React__default.createElement("span", {
className: "d-card__header__title"
}, typeof this.props.title === "function" ? this.props.title() : this.props.title), this.props.children);
}
}]);
return CardHeader;
}(React.PureComponent);
var Card =
/*#__PURE__*/
function (_PureComponent) {
inherits(Card, _PureComponent);
function Card() {
var _getPrototypeOf2;
var _this;
classCallCheck(this, Card);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = possibleConstructorReturn(this, (_getPrototypeOf2 = getPrototypeOf(Card)).call.apply(_getPrototypeOf2, [this].concat(args)));
defineProperty(assertThisInitialized(_this), "getClassNames", function () {
var base = "d-card";
if (_this.props.className) {
base += " ";
base += _this.props.className;
}
return base;
});
return _this;
}
createClass(Card, [{
key: "render",
value: function render() {
return React__default.createElement("div", {
className: this.getClassNames()
}, this.props.children);
}
}]);
return Card;
}(React.PureComponent);
defineProperty(Card, "Body", CardBody);
defineProperty(Card, "Header", CardHeader);
var classCallCheck$1 = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass$1 = 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$1 = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var possibleConstructorReturn$1 = 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 styles = {
base: {
position: 'absolute',
userSelect: 'none',
MsUserSelect: 'none'
},
top: {
width: '100%',
height: '10px',
top: '-5px',
left: '0px',
cursor: 'row-resize'
},
right: {
width: '10px',
height: '100%',
top: '0px',
right: '-5px',
cursor: 'col-resize'
},
bottom: {
width: '100%',
height: '10px',
bottom: '-5px',
left: '0px',
cursor: 'row-resize'
},
left: {
width: '10px',
height: '100%',
top: '0px',
left: '-5px',
cursor: 'col-resize'
},
topRight: {
width: '20px',
height: '20px',
position: 'absolute',
right: '-10px',
top: '-10px',
cursor: 'ne-resize'
},
bottomRight: {
width: '20px',
height: '20px',
position: 'absolute',
right: '-10px',
bottom: '-10px',
cursor: 'se-resize'
},
bottomLeft: {
width: '20px',
height: '20px',
position: 'absolute',
left: '-10px',
bottom: '-10px',
cursor: 'sw-resize'
},
topLeft: {
width: '20px',
height: '20px',
position: 'absolute',
left: '-10px',
top: '-10px',
cursor: 'nw-resize'
}
};
var Resizer = (function (props) {
return React.createElement(
'div',
{
className: props.className,
style: _extends({}, styles.base, styles[props.direction], props.replaceStyles || {}),
onMouseDown: function onMouseDown(e) {
props.onResizeStart(e, props.direction);
},
onTouchStart: function onTouchStart(e) {
props.onResizeStart(e, props.direction);
}
},
props.children
);
});
var userSelectNone = {
userSelect: 'none',
MozUserSelect: 'none',
WebkitUserSelect: 'none',
MsUserSelect: 'none'
};
var userSelectAuto = {
userSelect: 'auto',
MozUserSelect: 'auto',
WebkitUserSelect: 'auto',
MsUserSelect: 'auto'
};
var clamp = function clamp(n, min, max) {
return Math.max(Math.min(n, max), min);
};
var snap = function snap(n, size) {
return Math.round(n / size) * size;
};
var findClosestSnap = function findClosestSnap(n, snapArray) {
return snapArray.reduce(function (prev, curr) {
return Math.abs(curr - n) < Math.abs(prev - n) ? curr : prev;
});
};
var endsWith = function endsWith(str, searchStr) {
return str.substr(str.length - searchStr.length, searchStr.length) === searchStr;
};
var getStringSize = function getStringSize(n) {
if (n.toString() === 'auto') return n.toString();
if (endsWith(n.toString(), 'px')) return n.toString();
if (endsWith(n.toString(), '%')) return n.toString();
if (endsWith(n.toString(), 'vh')) return n.toString();
if (endsWith(n.toString(), 'vw')) return n.toString();
if (endsWith(n.toString(), 'vmax')) return n.toString();
if (endsWith(n.toString(), 'vmin')) return n.toString();
return n + 'px';
};
var definedProps = ['style', 'className', 'grid', 'snap', 'bounds', 'size', 'defaultSize', 'minWidth', 'minHeight', 'maxWidth', 'maxHeight', 'lockAspectRatio', 'lockAspectRatioExtraWidth', 'lockAspectRatioExtraHeight', 'enable', 'handleStyles', 'handleClasses', 'handleWrapperStyle', 'handleWrapperClass', 'children', 'onResizeStart', 'onResize', 'onResizeStop', 'handleComponent', 'scale', 'resizeRatio'];
var baseClassName = '__resizable_base__';
var Resizable = function (_React$Component) {
inherits$1(Resizable, _React$Component);
function Resizable(props) {
classCallCheck$1(this, Resizable);
var _this = possibleConstructorReturn$1(this, (Resizable.__proto__ || Object.getPrototypeOf(Resizable)).call(this, props));
_this.state = {
isResizing: false,
resizeCursor: 'auto',
width: typeof (_this.propsSize && _this.propsSize.width) === 'undefined' ? 'auto' : _this.propsSize && _this.propsSize.width,
height: typeof (_this.propsSize && _this.propsSize.height) === 'undefined' ? 'auto' : _this.propsSize && _this.propsSize.height,
direction: 'right',
original: {
x: 0,
y: 0,
width: 0,
height: 0
}
};
_this.updateExtendsProps(props);
_this.onResizeStart = _this.onResizeStart.bind(_this);
_this.onMouseMove = _this.onMouseMove.bind(_this);
_this.onMouseUp = _this.onMouseUp.bind(_this);
if (typeof window !== 'undefined') {
window.addEventListener('mouseup', _this.onMouseUp);
window.addEventListener('mousemove', _this.onMouseMove);
window.addEventListener('mouseleave', _this.onMouseUp);
window.addEventListener('touchmove', _this.onMouseMove);
window.addEventListener('touchend', _this.onMouseUp);
}
return _this;
}
createClass$1(Resizable, [{
key: 'updateExtendsProps',
value: function updateExtendsProps(props) {
this.extendsProps = Object.keys(props).reduce(function (acc, key) {
if (definedProps.indexOf(key) !== -1) return acc;
acc[key] = props[key];
return acc;
}, {});
}
}, {
key: 'getParentSize',
value: function getParentSize() {
var base = this.base;
if (!base) return { width: window.innerWidth, height: window.innerHeight };
// INFO: To calculate parent width with flex layout
var wrapChanged = false;
var wrap = this.parentNode.style.flexWrap;
var minWidth = base.style.minWidth;
if (wrap !== 'wrap') {
wrapChanged = true;
this.parentNode.style.flexWrap = 'wrap';
// HACK: Use relative to get parent padding size
}
base.style.position = 'relative';
base.style.minWidth = '100%';
var size = {
width: base.offsetWidth,
height: base.offsetHeight
};
base.style.position = 'absolute';
if (wrapChanged) this.parentNode.style.flexWrap = wrap;
base.style.minWidth = minWidth;
return size;
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var size = this.size;
this.setState({
width: this.state.width || size.width,
height: this.state.height || size.height
});
var parent = this.parentNode;
if (!(parent instanceof HTMLElement)) return;
if (this.base) return;
var element = document.createElement('div');
element.style.width = '100%';
element.style.height = '100%';
element.style.position = 'absolute';
element.style.transform = 'scale(0, 0)';
element.style.left = '0';
element.style.flex = '0';
if (element.classList) {
element.classList.add(baseClassName);
} else {
element.className += baseClassName;
}
parent.appendChild(element);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(next) {
this.updateExtendsProps(next);
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
if (typeof window !== 'undefined') {
window.removeEventListener('mouseup', this.onMouseUp);
window.removeEventListener('mousemove', this.onMouseMove);
window.removeEventListener('mouseleave', this.onMouseUp);
window.removeEventListener('touchmove', this.onMouseMove);
window.removeEventListener('touchend', this.onMouseUp);
var parent = this.parentNode;
var base = this.base;
if (!base || !parent) return;
if (!(parent instanceof HTMLElement) || !(base instanceof Node)) return;
parent.removeChild(base);
}
}
}, {
key: 'calculateNewSize',
value: function calculateNewSize(newSize, kind) {
var propsSize = this.propsSize && this.propsSize[kind];
return this.state[kind] === 'auto' && this.state.original[kind] === newSize && (typeof propsSize === 'undefined' || propsSize === 'auto') ? 'auto' : newSize;
}
}, {
key: 'onResizeStart',
value: function onResizeStart(event, direction) {
var clientX = 0;
var clientY = 0;
if (event.nativeEvent instanceof MouseEvent) {
clientX = event.nativeEvent.clientX;
clientY = event.nativeEvent.clientY;
// When user click with right button the resize is stuck in resizing mode
// until users clicks again, dont continue if right click is used.
// HACK: MouseEvent does not have `which` from flow-bin v0.68.
if (event.nativeEvent.which === 3) {
return;
}
} else if (event.nativeEvent instanceof TouchEvent) {
clientX = event.nativeEvent.touches[0].clientX;
clientY = event.nativeEvent.touches[0].clientY;
}
if (this.props.onResizeStart) {
this.props.onResizeStart(event, direction, this.resizable);
}
// Fix #168
if (this.props.size) {
if (typeof this.props.size.height !== 'undefined' && this.props.size.height !== this.state.height) {
this.setState({ height: this.props.size.height });
}
if (typeof this.props.size.width !== 'undefined' && this.props.size.width !== this.state.width) {
this.setState({ width: this.props.size.width });
}
}
this.setState({
original: {
x: clientX,
y: clientY,
width: this.size.width,
height: this.size.height
},
isResizing: true,
resizeCursor: window.getComputedStyle(event.target).cursor,
direction: direction
});
}
}, {
key: 'onMouseMove',
value: function onMouseMove(event) {
if (!this.state.isResizing) return;
var clientX = event instanceof MouseEvent ? event.clientX : event.touches[0].clientX;
var clientY = event instanceof MouseEvent ? event.clientY : event.touches[0].clientY;
var _state = this.state,
direction = _state.direction,
original = _state.original,
width = _state.width,
height = _state.height;
var _props = this.props,
lockAspectRatio = _props.lockAspectRatio,
lockAspectRatioExtraHeight = _props.lockAspectRatioExtraHeight,
lockAspectRatioExtraWidth = _props.lockAspectRatioExtraWidth;
var scale = this.props.scale || 1;
var _props2 = this.props,
maxWidth = _props2.maxWidth,
maxHeight = _props2.maxHeight,
minWidth = _props2.minWidth,
minHeight = _props2.minHeight;
var resizeRatio = this.props.resizeRatio || 1;
// TODO: refactor
var parentSize = this.getParentSize();
if (maxWidth && typeof maxWidth === 'string' && endsWith(maxWidth, '%')) {
var _ratio = Number(maxWidth.replace('%', '')) / 100;
maxWidth = parentSize.width * _ratio;
}
if (maxHeight && typeof maxHeight === 'string' && endsWith(maxHeight, '%')) {
var _ratio2 = Number(maxHeight.replace('%', '')) / 100;
maxHeight = parentSize.height * _ratio2;
}
if (minWidth && typeof minWidth === 'string' && endsWith(minWidth, '%')) {
var _ratio3 = Number(minWidth.replace('%', '')) / 100;
minWidth = parentSize.width * _ratio3;
}
if (minHeight && typeof minHeight === 'string' && endsWith(minHeight, '%')) {
var _ratio4 = Number(minHeight.replace('%', '')) / 100;
minHeight = parentSize.height * _ratio4;
}
maxWidth = typeof maxWidth === 'undefined' ? undefined : Number(maxWidth);
maxHeight = typeof maxHeight === 'undefined' ? undefined : Number(maxHeight);
minWidth = typeof minWidth === 'undefined' ? undefined : Number(minWidth);
minHeight = typeof minHeight === 'undefined' ? undefined : Number(minHeight);
var ratio = typeof lockAspectRatio === 'number' ? lockAspectRatio : original.width / original.height;
var newWidth = original.width;
var newHeight = original.height;
if (/right/i.test(direction)) {
newWidth = original.width + (clientX - original.x) * resizeRatio / scale;
if (lockAspectRatio) newHeight = (newWidth - lockAspectRatioExtraWidth) / ratio + lockAspectRatioExtraHeight;
}
if (/left/i.test(direction)) {
newWidth = original.width - (clientX - original.x) * resizeRatio / scale;
if (lockAspectRatio) newHeight = (newWidth - lockAspectRatioExtraWidth) / ratio + lockAspectRatioExtraHeight;
}
if (/bottom/i.test(direction)) {
newHeight = original.height + (clientY - original.y) * resizeRatio / scale;
if (lockAspectRatio) newWidth = (newHeight - lockAspectRatioExtraHeight) * ratio + lockAspectRatioExtraWidth;
}
if (/top/i.test(direction)) {
newHeight = original.height - (clientY - original.y) * resizeRatio / scale;
if (lockAspectRatio) newWidth = (newHeight - lockAspectRatioExtraHeight) * ratio + lockAspectRatioExtraWidth;
}
if (this.props.bounds === 'parent') {
var parent = this.parentNode;
if (parent instanceof HTMLElement) {
var parentRect = parent.getBoundingClientRect();
var parentLeft = parentRect.left;
var parentTop = parentRect.top;
var _resizable$getBoundin = this.resizable.getBoundingClientRect(),
_left = _resizable$getBoundin.left,
_top = _resizable$getBoundin.top;
var boundWidth = parent.offsetWidth + (parentLeft - _left);
var boundHeight = parent.offsetHeight + (parentTop - _top);
maxWidth = maxWidth && maxWidth < boundWidth ? maxWidth : boundWidth;
maxHeight = maxHeight && maxHeight < boundHeight ? maxHeight : boundHeight;
}
} else if (this.props.bounds === 'window') {
if (typeof window !== 'undefined') {
var _resizable$getBoundin2 = this.resizable.getBoundingClientRect(),
_left2 = _resizable$getBoundin2.left,
_top2 = _resizable$getBoundin2.top;
var _boundWidth = window.innerWidth - _left2;
var _boundHeight = window.innerHeight - _top2;
maxWidth = maxWidth && maxWidth < _boundWidth ? maxWidth : _boundWidth;
maxHeight = maxHeight && maxHeight < _boundHeight ? maxHeight : _boundHeight;
}
} else if (this.props.bounds instanceof HTMLElement) {
var targetRect = this.props.bounds.getBoundingClientRect();
var targetLeft = targetRect.left;
var targetTop = targetRect.top;
var _resizable$getBoundin3 = this.resizable.getBoundingClientRect(),
_left3 = _resizable$getBoundin3.left,
_top3 = _resizable$getBoundin3.top;
if (!(this.props.bounds instanceof HTMLElement)) return;
var _boundWidth2 = this.props.bounds.offsetWidth + (targetLeft - _left3);
var _boundHeight2 = this.props.bounds.offsetHeight + (targetTop - _top3);
maxWidth = maxWidth && maxWidth < _boundWidth2 ? maxWidth : _boundWidth2;
maxHeight = maxHeight && maxHeight < _boundHeight2 ? maxHeight : _boundHeight2;
}
var computedMinWidth = typeof minWidth === 'undefined' ? 10 : minWidth;
var computedMaxWidth = typeof maxWidth === 'undefined' || maxWidth < 0 ? newWidth : maxWidth;
var computedMinHeight = typeof minHeight === 'undefined' ? 10 : minHeight;
var computedMaxHeight = typeof maxHeight === 'undefined' || maxHeight < 0 ? newHeight : maxHeight;
if (lockAspectRatio) {
var extraMinWidth = (computedMinHeight - lockAspectRatioExtraHeight) * ratio + lockAspectRatioExtraWidth;
var extraMaxWidth = (computedMaxHeight - lockAspectRatioExtraHeight) * ratio + lockAspectRatioExtraWidth;
var extraMinHeight = (computedMinWidth - lockAspectRatioExtraWidth) / ratio + lockAspectRatioExtraHeight;
var extraMaxHeight = (computedMaxWidth - lockAspectRatioExtraWidth) / ratio + lockAspectRatioExtraHeight;
var lockedMinWidth = Math.max(computedMinWidth, extraMinWidth);
var lockedMaxWidth = Math.min(computedMaxWidth, extraMaxWidth);
var lockedMinHeight = Math.max(computedMinHeight, extraMinHeight);
var lockedMaxHeight = Math.min(computedMaxHeight, extraMaxHeight);
newWidth = clamp(newWidth, lockedMinWidth, lockedMaxWidth);
newHeight = clamp(newHeight, lockedMinHeight, lockedMaxHeight);
} else {
newWidth = clamp(newWidth, computedMinWidth, computedMaxWidth);
newHeight = clamp(newHeight, computedMinHeight, computedMaxHeight);
}
if (this.props.grid) {
newWidth = snap(newWidth, this.props.grid[0]);
}
if (this.props.grid) {
newHeight = snap(newHeight, this.props.grid[1]);
}
if (this.props.snap && this.props.snap.x) {
newWidth = findClosestSnap(newWidth, this.props.snap.x);
}
if (this.props.snap && this.props.snap.y) {
newHeight = findClosestSnap(newHeight, this.props.snap.y);
}
var delta = {
width: newWidth - original.width,
height: newHeight - original.height
};
if (width && typeof width === 'string' && endsWith(width, '%')) {
var percent = newWidth / parentSize.width * 100;
newWidth = percent + '%';
}
if (height && typeof height === 'string' && endsWith(height, '%')) {
var _percent = newHeight / parentSize.height * 100;
newHeight = _percent + '%';
}
this.setState({
width: this.calculateNewSize(newWidth, 'width'),
height: this.calculateNewSize(newHeight, 'height')
});
if (this.props.onResize) {
this.props.onResize(event, direction, this.resizable, delta);
}
}
}, {
key: 'onMouseUp',
value: function onMouseUp(event) {
var _state2 = this.state,
isResizing = _state2.isResizing,
direction = _state2.direction,
original = _state2.original;
if (!isResizing) return;
var delta = {
width: this.size.width - original.width,
height: this.size.height - original.height
};
if (this.props.onResizeStop) {
this.props.onResizeStop(event, direction, this.resizable, delta);
}
if (this.props.size) {
this.setState(this.props.size);
}
this.setState({ isResizing: false, resizeCursor: 'auto' });
}
}, {
key: 'updateSize',
value: function updateSize(size) {
this.setState({ width: size.width, height: size.height });
}
}, {
key: 'renderResizer',
value: function renderResizer() {
var _this2 = this;
var _props3 = this.props,
enable = _props3.enable,
handleStyles = _props3.handleStyles,
handleClasses = _props3.handleClasses,
handleWrapperStyle = _props3.handleWrapperStyle,
handleWrapperClass = _props3.handleWrapperClass,
handleComponent = _props3.handleComponent;
if (!enable) return null;
var resizers = Object.keys(enable).map(function (dir) {
if (enable[dir] !== false) {
return React.createElement(
Resizer,
{
key: dir,
direction: dir,
onResizeStart: _this2.onResizeStart,
replaceStyles: handleStyles && handleStyles[dir],
className: handleClasses && handleClasses[dir]
},
handleComponent && handleComponent[dir] ? React.createElement(handleComponent[dir]) : null
);
}
return null;
});
// #93 Wrap the resize box in span (will not break 100% width/height)
return React.createElement(
'span',
{ className: handleWrapperClass, style: handleWrapperStyle },
resizers
);
}
}, {
key: 'render',
value: function render() {
var _this3 = this;
var userSelect = this.state.isResizing ? userSelectNone : userSelectAuto;
return React.createElement(
'div',
_extends({
ref: function ref(c) {
if (c) {
_this3.resizable = c;
}
},
style: _extends({
position: 'relative'
}, userSelect, this.props.style, this.sizeStyle, {
maxWidth: this.props.maxWidth,
maxHeight: this.props.maxHeight,
minWidth: this.props.minWidth,
minHeight: this.props.minHeight,
boxSizing: 'border-box'
}),
className: this.props.className
}, this.extendsProps),
this.state.isResizing && React.createElement('div', {
style: {
height: '100%',
width: '100%',
backgroundColor: 'rgba(0,0,0,0)',
cursor: '' + (this.state.resizeCursor || 'auto'),
opacity: '0',
position: 'fixed',
zIndex: '9999',
top: '0',
left: '0',
bottom: '0',
right: '0'
}
}),
this.props.children,
this.renderResizer()
);
}
}, {
key: 'parentNode',
get: function get$$1() {
return this.resizable.parentNode;
}
}, {
key: 'propsSize',
get: function get$$1() {
return this.props.size || this.props.defaultSize;
}
}, {
key: 'base',
get: function get$$1() {
var parent = this.parentNode;
if (!parent) return undefined;
var children = [].slice.call(parent.children);
for (var i = 0; i < children.length; i += 1) {
var n = children[i];
if (n instanceof HTMLElement) {
if (n.classList.contains(baseClassName)) {
return n;
}
}
}
return undefined;
}
}, {
key: 'size',
get: function get$$1() {
var width = 0;
var height = 0;
if (typeof window !== 'undefined') {
var orgWidth = this.resizable.offsetWidth;
var orgHeight = this.resizable.offsetHeight;
// HACK: Set position `relative` to get parent size.
// This is because when re-resizable set `absolute`, I can not get base width correctly.
var orgPosition = this.resizable.style.position;
if (orgPosition !== 'relative') {
this.resizable.style.position = 'relative';
}
// INFO: Use original width or height if set auto.
width = this.resizable.style.width !== 'auto' ? this.resizable.offsetWidth : orgWidth;
height = this.resizable.style.height !== 'auto' ? this.resizable.offsetHeight : orgHeight;
// Restore original position
this.resizable.style.position = orgPosition;
}
return { width: width, height: height };
}
}, {
key: 'sizeStyle',
get: function get$$1() {
var _this4 = this;
var size = this.props.size;
var getSize = function getSize(key) {
if (typeof _this4.state[key] === 'undefined' || _this4.state[key] === 'auto') return 'auto';
if (_this4.propsSize && _this4.propsSize[key] && endsWith(_this4.propsSize[key].toString(), '%')) {
if (endsWith(_this4.state[key].toString(), '%')) return _this4.state[key].toString();
var parentSize = _this4.getParentSize();
var value = Number(_this4.state[key].toString().replace('px', ''));
var percent = value / parentSize[key] * 100;
return percent + '%';
}
return getStringSize(_this4.state[key]);
};
var width = size && typeof size.width !== 'undefined' && !this.state.isResizing ? getStringSize(size.width) : getSize('width');
var height = size && typeof size.height !== 'undefined' && !this.state.isResizing ? getStringSize(size.height) : getSize('height');
return { width: width, height: height };
}
}]);
return Resizable;
}(React.Component);
Resizable.defaultProps = {
onResizeStart: function onResizeStart() {},
onResize: function onResize() {},
onResizeStop: function onResizeStop() {},
enable: {
top: true,
right: true,
bottom: true,
left: true,
topRight: true,
bottomRight: true,
bottomLeft: true,
topLeft: true
},
style: {},
grid: [1, 1],
lockAspectRatio: false,
lockAspectRatioExtraWidth: 0,
lockAspectRatioExtraHeight: 0,
scale: 1,
resizeRatio: 1
};
var reactDraggable = createCommonjsModule(function (module, exports) {
(function (global, factory) {
module.exports = factory(_reactDom, React__default);
}(commonjsGlobal, (function (ReactDOM,React$$1) {
ReactDOM = ReactDOM && ReactDOM.hasOwnProperty('default') ? ReactDOM['default'] : ReactDOM;
React$$1 = React$$1 && React$$1.hasOwnProperty('default') ? React$$1['default'] : React$$1;
function createCommonjsModule$$1(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
function makeEmptyFunction(arg) {
return function () {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
var emptyFunction = function emptyFunction() {};
emptyFunction.thatReturns = makeEmptyFunction;
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction.thatReturnsNull = makeEmptyFunction(null);
emptyFunction.thatReturnsThis = function () {
return this;
};
emptyFunction.thatReturnsArgument = function (arg) {
return arg;
};
var emptyFunction_1 = emptyFunction;
/**
* 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 invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
var validateFormat = function validateFormat(format) {};
{
validateFormat = function validateFormat(format) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
};
}
function invariant(condition, format, a, b, c, d, e, f) {
validateFormat(format);
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
var invariant_1 = invariant;
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var warning = emptyFunction_1;
{
var printWarning = function printWarning(format) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.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) {}
};
warning = function warning(condition, format) {
if (format === undefined) {
throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (format.indexOf('Failed Composite propType: ') === 0) {
return; // Ignore CompositeComponent proptype check.
}
if (!condition) {
for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
printWarning.apply(undefined, [format].concat(args));
}
};
}
var warning_1 = warning;
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
var ReactPropTypesSecret_1 = ReactPropTypesSecret;
{
var invariant$1 = invariant_1;
var warning$1 = warning_1;
var ReactPropTypesSecret$1 = ReactPropTypesSecret_1;
var loggedTypeFailures = {};
}
/**
* Assert that the values match with the type specs.
* Error messages are memorized and will only be shown once.
*
* @param {object} typeSpecs Map of name to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @param {string} componentName Name of the component for error messages.
* @param {?Function} getStack Returns the component stack.
* @private
*/
function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
{
for (var typeSpecName in typeSpecs) {
if (typeSpecs.hasOwnProperty(typeSpecName)) {
var error;
// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
invariant$1(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'the `prop-types` package, but received `%s`.', componentName || 'React class', location, typeSpecName, typeof typeSpecs[typeSpecName]);
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret$1);
} catch (ex) {
error = ex;
}
warning$1(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error);
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var stack = getStack ? getStack() : '';
warning$1(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : '');
}
}
}
}
}
var checkPropTypes_1 = checkPropTypes;
var factoryWithTypeCheckers = function(isValidElement, throwOnDirectAccess) {
/* global Symbol */
var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
/**
* Returns the iterator method function contained on the iterable object.
*
* Be sure to invoke the function with the iterable as context:
*
* var iteratorFn = getIteratorFn(myIterable);
* if (iteratorFn) {
* var iterator = iteratorFn.call(myIterable);
* ...
* }
*
* @param {?object} maybeIterable
* @return {?function}
*/
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
}
/**
* Collection of methods that allow declaration and validation of props that are
* supplied to React components. Example usage:
*
* var Props = require('ReactPropTypes');
* var MyArticle = React.createClass({
* propTypes: {
* // An optional string prop named "description".
* description: Props.string,
*
* // A required enum prop named "category".
* category: Props.oneOf(['News','Photos']).isRequired,
*
* // A prop named "dialog" that requires an instance of Dialog.
* dialog: Props.instanceOf(Dialog).isRequired
* },
* render: function() { ... }
* });
*
* A more formal specification of how these methods are used:
*
* type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
* decl := ReactPropTypes.{type}(.isRequired)?
*
* Each and every declaration produces a function with the same signature. This
* allows the creation of custom validation functions. For example:
*
* var MyLink = React.createClass({
* propTypes: {
* // An optional string or URI prop named "href".
* href: function(props, propName, componentName) {
* var propValue = props[propName];
* if (propValue != null && typeof propValue !== 'string' &&
* !(propValue instanceof URI)) {
* return new Error(
* 'Expected a string or an URI for ' + propName + ' in ' +
* componentName
* );
* }
* }
* },
* render: function() {...}
* });
*
* @internal
*/
var ANONYMOUS = '<<anonymous>>';
// Important!
// Keep this list in sync with production version in `./factoryWithThrowingShims.js`.
var ReactPropTypes = {
array: createPrimitiveTypeChecker('array'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
symbol: createPrimitiveTypeChecker('symbol'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker,
exact: createStrictShapeTypeChecker,
};
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
/*eslint-disable no-self-compare*/
function is(x, y) {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/*eslint-enable no-self-compare*/
/**
* We use an Error-like object for backward compatibility as people may call
* PropTypes directly and inspect their output. However, we don't use real
* Errors anymore. We don't inspect their stack anyway, and creating them
* is prohibitively expensive if they are created too often, such as what
* happens in oneOfType() for any type before the one that matched.
*/
function PropTypeError(message) {
this.message = message;
this.stack = '';
}
// Make `instanceof Error` still work for returned errors.
PropTypeError.prototype = Error.prototype;
function createChainableTypeChecker(validate) {
{
var manualPropTypeCallCache = {};
var manualPropTypeWarningCount = 0;
}
function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (secret !== ReactPropTypesSecret_1) {
if (throwOnDirectAccess) {
// New behavior only for users of `prop-types` package
invariant_1(
false,
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use `PropTypes.checkPropTypes()` to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
} else if (typeof console !== 'undefined') {
// Old behavior for people using React.PropTypes
var cacheKey = componentName + ':' + propName;
if (
!manualPropTypeCallCache[cacheKey] &&
// Avoid spamming the console because they are often not actionable except for lib authors
manualPropTypeWarningCount < 3
) {
warning_1(
false,
'You are manually calling a React.PropTypes validation ' +
'function for the `%s` prop on `%s`. This is deprecated ' +
'and will throw in the standalone `prop-types` package. ' +
'You may be seeing this warning due to a third-party PropTypes ' +
'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.',
propFullName,
componentName
);
manualPropTypeCallCache[cacheKey] = true;
manualPropTypeWarningCount++;
}
}
}
if (props[propName] == null) {
if (isRequired) {
if (props[propName] === null) {
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));
}
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));
}
return null;
} else {
return validate(props, propName, componentName, location, propFullName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location, propFullName, secret) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== expectedType) {
// `propValue` being instance of, say, date/regexp, pass the 'object'
// check, but we can offer a more precise error message here rather than
// 'of type `object`'.
var preciseType = getPreciseType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunction_1.thatReturnsNull);
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
}
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
}
for (var i = 0; i < propValue.length; i++) {
var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret_1);
if (error instanceof Error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!isValidElement(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location, propFullName) {
if (!(props[propName] instanceof expectedClass)) {
var expectedClassName = expectedClass.name || ANONYMOUS;
var actualClassName = getClassName(props[propName]);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
if (!Array.isArray(expectedValues)) {
warning_1(false, 'Invalid argument supplied to oneOf, expected an instance of array.');
return emptyFunction_1.thatReturnsNull;
}
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
for (var i = 0; i < expectedValues.length; i++) {
if (is(propValue, expectedValues[i])) {
return null;
}
}
var valuesString = JSON.stringify(expectedValues);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
}
return createChainableTypeChecker(validate);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
}
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
}
for (var key in propValue) {
if (propValue.hasOwnProperty(key)) {
var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
if (error instanceof Error) {
return error;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
if (!Array.isArray(arrayOfTypeCheckers)) {
warning_1(false, 'Invalid argument supplied to oneOfType, expected an instance of array.');
return emptyFunction_1.thatReturnsNull;
}
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (typeof checker !== 'function') {
warning_1(
false,
'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' +
'received %s at index %s.',
getPostfixForTypeWarning(checker),
i
);
return emptyFunction_1.thatReturnsNull;
}
}
function validate(props, propName, componentName, location, propFullName) {
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret_1) == null) {
return null;
}
}
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
}
return createChainableTypeChecker(validate);
}
function createNodeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!isNode(props[propName])) {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
for (var key in shapeTypes) {
var checker = shapeTypes[key];
if (!checker) {
continue;
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createStrictShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
// We need to check all keys in case some are required but missing from
// props.
var allKeys = objectAssign({}, props[propName], shapeTypes);
for (var key in allKeys) {
var checker = shapeTypes[key];
if (!checker) {
return new PropTypeError(
'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' +
'\nBad object: ' + JSON.stringify(props[propName], null, ' ') +
'\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ')
);
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode(propValue) {
switch (typeof propValue) {
case 'number':
case 'string':
case 'undefined':
return true;
case 'boolean':
return !propValue;
case 'object':
if (Array.isArray(propValue)) {
return propValue.every(isNode);
}
if (propValue === null || isValidElement(propValue)) {
return true;
}
var iteratorFn = getIteratorFn(propValue);
if (iteratorFn) {
var iterator = iteratorFn.call(propValue);
var step;
if (iteratorFn !== propValue.entries) {
while (!(step = iterator.next()).done) {
if (!isNode(step.value)) {
return false;
}
}
} else {
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
if (!isNode(entry[1])) {
return false;
}
}
}
}
} else {
return false;
}
return true;
default:
return false;
}
}
function isSymbol(propType, propValue) {
// Native Symbol.
if (propType === 'symbol') {
return true;
}
// 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
if (propValue['@@toStringTag'] === 'Symbol') {
return true;
}
// Fallback for non-spec compliant Symbols which are polyfilled.
if (typeof Symbol === 'function' && propValue instanceof Symbol) {
return true;
}
return false;
}
// Equivalent of `typeof` but with special handling for array and regexp.
function getPropType(propValue) {
var propType = typeof propValue;
if (Array.isArray(propValue)) {
return 'array';
}
if (propValue instanceof RegExp) {
// Old webkits (at least until Android 4.0) return 'function' rather than
// 'object' for typeof a RegExp. We'll normalize this here so that /bla/
// passes PropTypes.object.
return 'object';
}
if (isSymbol(propType, propValue)) {
return 'symbol';
}
return propType;
}
// This handles more types than `getPropType`. Only used for error messages.
// See `createPrimitiveTypeChecker`.
function getPreciseType(propValue) {
if (typeof propValue === 'undefined' || propValue === null) {
return '' + propValue;
}
var propType = getPropType(propValue);
if (propType === 'object') {
if (propValue instanceof Date) {
return 'date';
} else if (propValue instanceof RegExp) {
return 'regexp';
}
}
return propType;
}
// Returns a string that is postfixed to a warning about an invalid type.
// For example, "undefined" or "of type array"
function getPostfixForTypeWarning(value) {
var type = getPreciseType(value);
switch (type) {
case 'array':
case 'object':
return 'an ' + type;
case 'boolean':
case 'date':
case 'regexp':
return 'a ' + type;
default:
return type;
}
}
// Returns class name of the object, if any.
function getClassName(propValue) {
if (!propValue.constructor || !propValue.constructor.name) {
return ANONYMOUS;
}
return propValue.constructor.name;
}
ReactPropTypes.checkPropTypes = checkPropTypes_1;
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
var propTypes = createCommonjsModule$$1(function (module) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
{
var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' &&
Symbol.for &&
Symbol.for('react.element')) ||
0xeac7;
var isValidElement = function(object) {
return typeof object === 'object' &&
object !== null &&
object.$$typeof === REACT_ELEMENT_TYPE;
};
// By explicitly using `prop-types` you are opting into new development behavior.
// http://fb.me/prop-types-in-prod
var throwOnDirectAccess = true;
module.exports = factoryWithTypeCheckers(isValidElement, throwOnDirectAccess);
}
});
var classnames = createCommonjsModule$$1(function (module) {
/*!
Copyright (c) 2016 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!arg) continue;
var argType = typeof arg;
if (argType === 'string' || argType === 'number') {
classes.push(arg);
} else if (Array.isArray(arg)) {
classes.push(classNames.apply(null, arg));
} else if (argType === 'object') {
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes.push(key);
}
}
}
}
return classes.join(' ');
}
if (module.exports) {
module.exports = classNames;
} else {
window.classNames = classNames;
}
}());
});
// @credits https://gist.github.com/rogozhnikoff/a43cfed27c41e4e68cdc
function findInArray(array /*: Array<any> | TouchList*/, callback /*: Function*/) /*: any*/ {
for (var i = 0, length = array.length; i < length; i++) {
if (callback.apply(callback, [array[i], i, array])) return array[i];
}
}
function isFunction(func /*: any*/) /*: boolean*/ {
return typeof func === 'function' || Object.prototype.toString.call(func) === '[object Function]';
}
function isNum(num /*: any*/) /*: boolean*/ {
return typeof num === 'number' && !isNaN(num);
}
function int(a /*: string*/) /*: number*/ {
return parseInt(a, 10);
}
function dontSetMe(props /*: Object*/, propName /*: string*/, componentName /*: string*/) {
if (props[propName]) {
return new Error('Invalid prop ' + propName + ' passed to ' + componentName + ' - do not set this, set it on the child.');
}
}
var prefixes = ['Moz', 'Webkit', 'O', 'ms'];
function getPrefix() /*: string*/ {
var prop /*: string*/ = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'transform';
// Checking specifically for 'window.document' is for pseudo-browser server-side
// environments that define 'window' as the global context.
// E.g. React-rails (see https://github.com/reactjs/react-rails/pull/84)
if (typeof window === 'undefined' || typeof window.document === 'undefined') return '';
var style = window.document.documentElement.style;
if (prop in style) return '';
for (var i = 0; i < prefixes.length; i++) {
if (browserPrefixToKey(prop, prefixes[i]) in style) return prefixes[i];
}
return '';
}
function browserPrefixToKey(prop /*: string*/, prefix /*: string*/) /*: string*/ {
return prefix ? '' + prefix + kebabToTitleCase(prop) : prop;
}
function kebabToTitleCase(str /*: string*/) /*: string*/ {
var out = '';
var shouldCapitalize = true;
for (var i = 0; i < str.length; i++) {
if (shouldCapitalize) {
out += str[i].toUpperCase();
shouldCapitalize = false;
} else if (str[i] === '-') {
shouldCapitalize = true;
} else {
out += str[i];
}
}
return out;
}
// Default export is the prefix itself, like 'Moz', 'Webkit', etc
// Note that you may have to re-test for certain things; for instance, Chrome 50
// can handle unprefixed `transform`, but not unprefixed `user-select`
var browserPrefix = getPrefix();
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var defineProperty = function (obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
};
var _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
var inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
};
var slicedToArray = function () {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
return function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
}();
/*:: import type {ControlPosition, MouseTouchEvent} from './types';*/
var matchesSelectorFunc = '';
function matchesSelector(el /*: Node*/, selector /*: string*/) /*: boolean*/ {
if (!matchesSelectorFunc) {
matchesSelectorFunc = findInArray(['matches', 'webkitMatchesSelector', 'mozMatchesSelector', 'msMatchesSelector', 'oMatchesSelector'], function (method) {
// $FlowIgnore: Doesn't think elements are indexable
return isFunction(el[method]);
});
}
// Might not be found entirely (not an Element?) - in that case, bail
// $FlowIgnore: Doesn't think elements are indexable
if (!isFunction(el[matchesSelectorFunc])) return false;
// $FlowIgnore: Doesn't think elements are indexable
return el[matchesSelectorFunc](selector);
}
// Works up the tree to the draggable itself attempting to match selector.
function matchesSelectorAndParentsTo(el /*: Node*/, selector /*: string*/, baseNode /*: Node*/) /*: boolean*/ {
var node = el;
do {
if (matchesSelector(node, selector)) return true;
if (node === baseNode) return false;
node = node.parentNode;
} while (node);
return false;
}
function addEvent(el /*: ?Node*/, event /*: string*/, handler /*: Function*/) /*: void*/ {
if (!el) {
return;
}
if (el.attachEvent) {
el.attachEvent('on' + event, handler);
} else if (el.addEventListener) {
el.addEventListener(event, handler, true);
} else {
// $FlowIgnore: Doesn't think elements are indexable
el['on' + event] = handler;
}
}
function removeEvent(el /*: ?Node*/, event /*: string*/, handler /*: Function*/) /*: void*/ {
if (!el) {
return;
}
if (el.detachEvent) {
el.detachEvent('on' + event, handler);
} else if (el.removeEventListener) {
el.removeEventListener(event, handler, true);
} else {
// $FlowIgnore: Doesn't think elements are indexable
el['on' + event] = null;
}
}
function outerHeight(node /*: HTMLElement*/) /*: number*/ {
// This is deliberately excluding margin for our calculations, since we are using
// offsetTop which is including margin. See getBoundPosition
var height = node.clientHeight;
var computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
height += int(computedStyle.borderTopWidth);
height += int(computedStyle.borderBottomWidth);
return height;
}
function outerWidth(node /*: HTMLElement*/) /*: number*/ {
// This is deliberately excluding margin for our calculations, since we are using
// offsetLeft which is including margin. See getBoundPosition
var width = node.clientWidth;
var computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
width += int(computedStyle.borderLeftWidth);
width += int(computedStyle.borderRightWidth);
return width;
}
function innerHeight(node /*: HTMLElement*/) /*: number*/ {
var height = node.clientHeight;
var computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
height -= int(computedStyle.paddingTop);
height -= int(computedStyle.paddingBottom);
return height;
}
function innerWidth(node /*: HTMLElement*/) /*: number*/ {
var width = node.clientWidth;
var computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
width -= int(computedStyle.paddingLeft);
width -= int(computedStyle.paddingRight);
return width;
}
// Get from offsetParent
function offsetXYFromParent(evt /*: {clientX: number, clientY: number}*/, offsetParent /*: HTMLElement*/) /*: ControlPosition*/ {
var isBody = offsetParent === offsetParent.ownerDocument.body;
var offsetParentRect = isBody ? { left: 0, top: 0 } : offsetParent.getBoundingClientRect();
var x = evt.clientX + offsetParent.scrollLeft - offsetParentRect.left;
var y = evt.clientY + offsetParent.scrollTop - offsetParentRect.top;
return { x: x, y: y };
}
function createCSSTransform(_ref) /*: Object*/ {
var x = _ref.x,
y = _ref.y;
// Replace unitless items with px
return defineProperty({}, browserPrefixToKey('transform', browserPrefix), 'translate(' + x + 'px,' + y + 'px)');
}
function createSVGTransform(_ref3) /*: string*/ {
var x = _ref3.x,
y = _ref3.y;
return 'translate(' + x + ',' + y + ')';
}
function getTouch(e /*: MouseTouchEvent*/, identifier /*: number*/) /*: ?{clientX: number, clientY: number}*/ {
return e.targetTouches && findInArray(e.targetTouches, function (t) {
return identifier === t.identifier;
}) || e.changedTouches && findInArray(e.changedTouches, function (t) {
return identifier === t.identifier;
});
}
function getTouchIdentifier(e /*: MouseTouchEvent*/) /*: ?number*/ {
if (e.targetTouches && e.targetTouches[0]) return e.targetTouches[0].identifier;
if (e.changedTouches && e.changedTouches[0]) return e.changedTouches[0].identifier;
}
// User-select Hacks:
//
// Useful for preventing blue highlights all over everything when dragging.
// Note we're passing `document` b/c we could be iframed
function addUserSelectStyles(doc /*: ?Document*/) {
if (!doc) return;
var styleEl = doc.getElementById('react-draggable-style-el');
if (!styleEl) {
styleEl = doc.createElement('style');
styleEl.type = 'text/css';
styleEl.id = 'react-draggable-style-el';
styleEl.innerHTML = '.react-draggable-transparent-selection *::-moz-selection {background: transparent;}\n';
styleEl.innerHTML += '.react-draggable-transparent-selection *::selection {background: transparent;}\n';
doc.getElementsByTagName('head')[0].appendChild(styleEl);
}
if (doc.body) addClassName(doc.body, 'react-draggable-transparent-selection');
}
function removeUserSelectStyles(doc /*: ?Document*/) {
try {
if (doc && doc.body) removeClassName(doc.body, 'react-draggable-transparent-selection');
// $FlowIgnore: IE
if (doc.selection) {
// $FlowIgnore: IE
doc.selection.empty();
} else {
window.getSelection().removeAllRanges(); // remove selection caused by scroll
}
} catch (e) {
// probably IE
}
}
function styleHacks() /*: Object*/ {
var childStyle /*: Object*/ = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
// Workaround IE pointer events; see #51
// https://github.com/mzabriskie/react-draggable/issues/51#issuecomment-103488278
return _extends({
touchAction: 'none'
}, childStyle);
}
function addClassName(el /*: HTMLElement*/, className /*: string*/) {
if (el.classList) {
el.classList.add(className);
} else {
if (!el.className.match(new RegExp('(?:^|\\s)' + className + '(?!\\S)'))) {
el.className += ' ' + className;
}
}
}
function removeClassName(el /*: HTMLElement*/, className /*: string*/) {
if (el.classList) {
el.classList.remove(className);
} else {
el.className = el.className.replace(new RegExp('(?:^|\\s)' + className + '(?!\\S)', 'g'), '');
}
}
/*:: import type Draggable from '../Draggable';*/
/*:: import type {Bounds, ControlPosition, DraggableData, MouseTouchEvent} from './types';*/
/*:: import type DraggableCore from '../DraggableCore';*/
function getBoundPosition(draggable /*: Draggable*/, x /*: number*/, y /*: number*/) /*: [number, number]*/ {
// If no bounds, short-circuit and move on
if (!draggable.props.bounds) return [x, y];
// Clone new bounds
var bounds = draggable.props.bounds;
bounds = typeof bounds === 'string' ? bounds : cloneBounds(bounds);
var node = findDOMNode(draggable);
if (typeof bounds === 'string') {
var ownerDocument = node.ownerDocument;
var ownerWindow = ownerDocument.defaultView;
var boundNode = void 0;
if (bounds === 'parent') {
boundNode = node.parentNode;
} else {
boundNode = ownerDocument.querySelector(bounds);
}
if (!(boundNode instanceof ownerWindow.HTMLElement)) {
throw new Error('Bounds selector "' + bounds + '" could not find an element.');
}
var nodeStyle = ownerWindow.getComputedStyle(node);
var boundNodeStyle = ownerWindow.getComputedStyle(boundNode);
// Compute bounds. This is a pain with padding and offsets but this gets it exactly right.
bounds = {
left: -node.offsetLeft + int(boundNodeStyle.paddingLeft) + int(nodeStyle.marginLeft),
top: -node.offsetTop + int(boundNodeStyle.paddingTop) + int(nodeStyle.marginTop),
right: innerWidth(boundNode) - outerWidth(node) - node.offsetLeft + int(boundNodeStyle.paddingRight) - int(nodeStyle.marginRight),
bottom: innerHeight(boundNode) - outerHeight(node) - node.offsetTop + int(boundNodeStyle.paddingBottom) - int(nodeStyle.marginBottom)
};
}
// Keep x and y below right and bottom limits...
if (isNum(bounds.right)) x = Math.min(x, bounds.right);
if (isNum(bounds.bottom)) y = Math.min(y, bounds.bottom);
// But above left and top limits.
if (isNum(bounds.left)) x = Math.max(x, bounds.left);
if (isNum(bounds.top)) y = Math.max(y, bounds.top);
return [x, y];
}
function snapToGrid(grid /*: [number, number]*/, pendingX /*: number*/, pendingY /*: number*/) /*: [number, number]*/ {
var x = Math.round(pendingX / grid[0]) * grid[0];
var y = Math.round(pendingY / grid[1]) * grid[1];
return [x, y];
}
function canDragX(draggable /*: Draggable*/) /*: boolean*/ {
return draggable.props.axis === 'both' || draggable.props.axis === 'x';
}
function canDragY(draggable /*: Draggable*/) /*: boolean*/ {
return draggable.props.axis === 'both' || draggable.props.axis === 'y';
}
// Get {x, y} positions from event.
function getControlPosition(e /*: MouseTouchEvent*/, touchIdentifier /*: ?number*/, draggableCore /*: DraggableCore*/) /*: ?ControlPosition*/ {
var touchObj = typeof touchIdentifier === 'number' ? getTouch(e, touchIdentifier) : null;
if (typeof touchIdentifier === 'number' && !touchObj) return null; // not the right touch
var node = findDOMNode(draggableCore);
// User can provide an offsetParent if desired.
var offsetParent = draggableCore.props.offsetParent || node.offsetParent || node.ownerDocument.body;
return offsetXYFromParent(touchObj || e, offsetParent);
}
// Create an data object exposed by <DraggableCore>'s events
function createCoreData(draggable /*: DraggableCore*/, x /*: number*/, y /*: number*/) /*: DraggableData*/ {
var state = draggable.state;
var isStart = !isNum(state.lastX);
var node = findDOMNode(draggable);
if (isStart) {
// If this is our first move, use the x and y as last coords.
return {
node: node,
deltaX: 0, deltaY: 0,
lastX: x, lastY: y,
x: x, y: y
};
} else {
// Otherwise calculate proper values.
return {
node: node,
deltaX: x - state.lastX, deltaY: y - state.lastY,
lastX: state.lastX, lastY: state.lastY,
x: x, y: y
};
}
}
// Create an data exposed by <Draggable>'s events
function createDraggableData(draggable /*: Draggable*/, coreData /*: DraggableData*/) /*: DraggableData*/ {
var scale = draggable.props.scale;
return {
node: coreData.node,
x: draggable.state.x + coreData.deltaX / scale,
y: draggable.state.y + coreData.deltaY / scale,
deltaX: coreData.deltaX / scale,
deltaY: coreData.deltaY / scale,
lastX: draggable.state.x,
lastY: draggable.state.y
};
}
// A lot faster than stringify/parse
function cloneBounds(bounds /*: Bounds*/) /*: Bounds*/ {
return {
left: bounds.left,
top: bounds.top,
right: bounds.right,
bottom: bounds.bottom
};
}
function findDOMNode(draggable /*: Draggable | DraggableCore*/) /*: HTMLElement*/ {
var node = ReactDOM.findDOMNode(draggable);
if (!node) {
throw new Error('<DraggableCore>: Unmounted during event!');
}
// $FlowIgnore we can't assert on HTMLElement due to tests... FIXME
return node;
}
/*eslint no-console:0*/
function log() {
}
/*:: import type {EventHandler, MouseTouchEvent} from './utils/types';*/
// Simple abstraction for dragging events names.
/*:: import type {Element as ReactElement} from 'react';*/
var eventsFor = {
touch: {
start: 'touchstart',
move: 'touchmove',
stop: 'touchend'
},
mouse: {
start: 'mousedown',
move: 'mousemove',
stop: 'mouseup'
}
};
// Default to mouse events.
var dragEventFor = eventsFor.mouse;
/*:: type DraggableCoreState = {
dragging: boolean,
lastX: number,
lastY: number,
touchIdentifier: ?number
};*/
/*:: export type DraggableBounds = {
left: number,
right: number,
top: number,
bottom: number,
};*/
/*:: export type DraggableData = {
node: HTMLElement,
x: number, y: number,
deltaX: number, deltaY: number,
lastX: number, lastY: number,
};*/
/*:: export type DraggableEventHandler = (e: MouseEvent, data: DraggableData) => void;*/
/*:: export type ControlPosition = {x: number, y: number};*/
//
// Define <DraggableCore>.
//
// <DraggableCore> is for advanced usage of <Draggable>. It maintains minimal internal state so it can
// work well with libraries that require more control over the element.
//
/*:: export type DraggableCoreProps = {
allowAnyClick: boolean,
cancel: string,
children: ReactElement<any>,
disabled: boolean,
enableUserSelectHack: boolean,
offsetParent: HTMLElement,
grid: [number, number],
handle: string,
onStart: DraggableEventHandler,
onDrag: DraggableEventHandler,
onStop: DraggableEventHandler,
onMouseDown: (e: MouseEvent) => void,
};*/
var DraggableCore = function (_React$Component) {
inherits(DraggableCore, _React$Component);
function DraggableCore() {
var _ref;
var _temp, _this, _ret;
classCallCheck(this, DraggableCore);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = DraggableCore.__proto__ || Object.getPrototypeOf(DraggableCore)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
dragging: false,
// Used while dragging to determine deltas.
lastX: NaN, lastY: NaN,
touchIdentifier: null
}, _this.handleDragStart = function (e) {
// Make it possible to attach event handlers on top of this one.
_this.props.onMouseDown(e);
// Only accept left-clicks.
if (!_this.props.allowAnyClick && typeof e.button === 'number' && e.button !== 0) return false;
// Get nodes. Be sure to grab relative document (could be iframed)
var thisNode = ReactDOM.findDOMNode(_this);
if (!thisNode || !thisNode.ownerDocument || !thisNode.ownerDocument.body) {
throw new Error('<DraggableCore> not mounted on DragStart!');
}
var ownerDocument = thisNode.ownerDocument;
// Short circuit if handle or cancel prop was provided and selector doesn't match.
if (_this.props.disabled || !(e.target instanceof ownerDocument.defaultView.Node) || _this.props.handle && !matchesSelectorAndParentsTo(e.target, _this.props.handle, thisNode) || _this.props.cancel && matchesSelectorAndParentsTo(e.target, _this.props.cancel, thisNode)) {
return;
}
// Set touch identifier in component state if this is a touch event. This allows us to
// distinguish between individual touches on multitouch screens by identifying which
// touchpoint was set to this element.
var touchIdentifier = getTouchIdentifier(e);
_this.setState({ touchIdentifier: touchIdentifier });
// Get the current drag point from the event. This is used as the offset.
var position = getControlPosition(e, touchIdentifier, _this);
if (position == null) return; // not possible but satisfies flow
var x = position.x,
y = position.y;
// Create an event object with all the data parents need to make a decision here.
var coreEvent = createCoreData(_this, x, y);
// Call event handler. If it returns explicit false, cancel.
log('calling', _this.props.onStart);
var shouldUpdate = _this.props.onStart(e, coreEvent);
if (shouldUpdate === false) return;
// Add a style to the body to disable user-select. This prevents text from
// being selected all over the page.
if (_this.props.enableUserSelectHack) addUserSelectStyles(ownerDocument);
// Initiate dragging. Set the current x and y as offsets
// so we know how much we've moved during the drag. This allows us
// to drag elements around even if they have been moved, without issue.
_this.setState({
dragging: true,
lastX: x,
lastY: y
});
// Add events to the document directly so we catch when the user's mouse/touch moves outside of
// this element. We use different events depending on whether or not we have detected that this
// is a touch-capable device.
addEvent(ownerDocument, dragEventFor.move, _this.handleDrag);
addEvent(ownerDocument, dragEventFor.stop, _this.handleDragStop);
}, _this.handleDrag = function (e) {
// Prevent scrolling on mobile devices, like ipad/iphone.
if (e.type === 'touchmove') e.preventDefault();
// Get the current drag point from the event. This is used as the offset.
var position = getControlPosition(e, _this.state.touchIdentifier, _this);
if (position == null) return;
var x = position.x,
y = position.y;
// Snap to grid if prop has been provided
if (Array.isArray(_this.props.grid)) {
var _deltaX = x - _this.state.lastX,
_deltaY = y - _this.state.lastY;
var _snapToGrid = snapToGrid(_this.props.grid, _deltaX, _deltaY);
var _snapToGrid2 = slicedToArray(_snapToGrid, 2);
_deltaX = _snapToGrid2[0];
_deltaY = _snapToGrid2[1];
if (!_deltaX && !_deltaY) return; // skip useless drag
x = _this.state.lastX + _deltaX, y = _this.state.lastY + _deltaY;
}
var coreEvent = createCoreData(_this, x, y);
// Call event handler. If it returns explicit false, trigger end.
var shouldUpdate = _this.props.onDrag(e, coreEvent);
if (shouldUpdate === false) {
try {
// $FlowIgnore
_this.handleDragStop(new MouseEvent('mouseup'));
} catch (err) {
// Old browsers
var event = ((document.createEvent('MouseEvents') /*: any*/) /*: MouseTouchEvent*/);
// I see why this insanity was deprecated
// $FlowIgnore
event.initMouseEvent('mouseup', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
_this.handleDragStop(event);
}
return;
}
_this.setState({
lastX: x,
lastY: y
});
}, _this.handleDragStop = function (e) {
if (!_this.state.dragging) return;
var position = getControlPosition(e, _this.state.touchIdentifier, _this);
if (position == null) return;
var x = position.x,
y = position.y;
var coreEvent = createCoreData(_this, x, y);
var thisNode = ReactDOM.findDOMNode(_this);
if (thisNode) {
// Remove user-select hack
if (_this.props.enableUserSelectHack) removeUserSelectStyles(thisNode.ownerDocument);
}
// Reset the el.
_this.setState({
dragging: false,
lastX: NaN,
lastY: NaN
});
// Call event handler
_this.props.onStop(e, coreEvent);
if (thisNode) {
removeEvent(thisNode.ownerDocument, dragEventFor.move, _this.handleDrag);
removeEvent(thisNode.ownerDocument, dragEventFor.stop, _this.handleDragStop);
}
}, _this.onMouseDown = function (e) {
dragEventFor = eventsFor.mouse; // on touchscreen laptops we could switch back to mouse
return _this.handleDragStart(e);
}, _this.onMouseUp = function (e) {
dragEventFor = eventsFor.mouse;
return _this.handleDragStop(e);
}, _this.onTouchStart = function (e) {
// We're on a touch device now, so change the event handlers
dragEventFor = eventsFor.touch;
return _this.handleDragStart(e);
}, _this.onTouchEnd = function (e) {
// We're on a touch device now, so change the event handlers
dragEventFor = eventsFor.touch;
return _this.handleDragStop(e);
}, _temp), possibleConstructorReturn(_this, _ret);
}
createClass(DraggableCore, [{
key: 'componentWillUnmount',
value: function componentWillUnmount() {
// Remove any leftover event handlers. Remove both touch and mouse handlers in case
// some browser quirk caused a touch event to fire during a mouse move, or vice versa.
var thisNode = ReactDOM.findDOMNode(this);
if (thisNode) {
var ownerDocument = thisNode.ownerDocument;
removeEvent(ownerDocument, eventsFor.mouse.move, this.handleDrag);
removeEvent(ownerDocument, eventsFor.touch.move, this.handleDrag);
removeEvent(ownerDocument, eventsFor.mouse.stop, this.handleDragStop);
removeEvent(ownerDocument, eventsFor.touch.stop, this.handleDragStop);
if (this.props.enableUserSelectHack) removeUserSelectStyles(ownerDocument);
}
}
// Same as onMouseDown (start drag), but now consider this a touch device.
}, {
key: 'render',
value: function render() {
// Reuse the child provided
// This makes it flexible to use whatever element is wanted (div, ul, etc)
return React$$1.cloneElement(React$$1.Children.only(this.props.children), {
style: styleHacks(this.props.children.props.style),
// Note: mouseMove handler is attached to document so it will still function
// when the user drags quickly and leaves the bounds of the element.
onMouseDown: this.onMouseDown,
onTouchStart: this.onTouchStart,
onMouseUp: this.onMouseUp,
onTouchEnd: this.onTouchEnd
});
}
}]);
return DraggableCore;
}(React$$1.Component);
DraggableCore.displayName = 'DraggableCore';
DraggableCore.propTypes = {
/**
* `allowAnyClick` allows dragging using any mouse button.
* By default, we only accept the left button.
*
* Defaults to `false`.
*/
allowAnyClick: propTypes.bool,
/**
* `disabled`, if true, stops the <Draggable> from dragging. All handlers,
* with the exception of `onMouseDown`, will not fire.
*/
disabled: propTypes.bool,
/**
* By default, we add 'user-select:none' attributes to the document body
* to prevent ugly text selection during drag. If this is causing problems
* for your app, set this to `false`.
*/
enableUserSelectHack: propTypes.bool,
/**
* `offsetParent`, if set, uses the passed DOM node to compute drag offsets
* instead of using the parent node.
*/
offsetParent: function offsetParent(props /*: DraggableCoreProps*/, propName /*: $Keys<DraggableCoreProps>*/) {
if (props[propName] && props[propName].nodeType !== 1) {
throw new Error('Draggable\'s offsetParent must be a DOM Node.');
}
},
/**
* `grid` specifies the x and y that dragging should snap to.
*/
grid: propTypes.arrayOf(propTypes.number),
/**
* `scale` specifies the scale of the area you are dragging inside of. It allows
* the drag deltas to scale correctly with how far zoomed in/out you are.
*/
scale: propTypes.number,
/**
* `handle` specifies a selector to be used as the handle that initiates drag.
*
* Example:
*
* ```jsx
* let App = React.createClass({
* render: function () {
* return (
* <Draggable handle=".handle">
* <div>
* <div className="handle">Click me to drag</div>
* <div>This is some other content</div>
* </div>
* </Draggable>
* );
* }
* });
* ```
*/
handle: propTypes.string,
/**
* `cancel` specifies a selector to be used to prevent drag initialization.
*
* Example:
*
* ```jsx
* let App = React.createClass({
* render: function () {
* return(
* <Draggable cancel=".cancel">
* <div>
* <div className="cancel">You can't drag from here</div>
* <div>Dragging here works fine</div>
* </div>
* </Draggable>
* );
* }
* });
* ```
*/
cancel: propTypes.string,
/**
* Called when dragging starts.
* If this function returns the boolean false, dragging will be canceled.
*/
onStart: propTypes.func,
/**
* Called while dragging.
* If this function returns the boolean false, dragging will be canceled.
*/
onDrag: propTypes.func,
/**
* Called when dragging stops.
* If this function returns the boolean false, the drag will remain active.
*/
onStop: propTypes.func,
/**
* A workaround option which can be passed if onMouseDown needs to be accessed,
* since it'll always be blocked (as there is internal use of onMouseDown)
*/
onMouseDown: propTypes.func,
/**
* These properties should be defined on the child, not here.
*/
className: dontSetMe,
style: dontSetMe,
transform: dontSetMe
};
DraggableCore.defaultProps = {
allowAnyClick: false, // by default only accept left click
cancel: null,
disabled: false,
enableUserSelectHack: true,
offsetParent: null,
handle: null,
grid: null,
transform: null,
onStart: function onStart() {},
onDrag: function onDrag() {},
onStop: function onStop() {},
onMouseDown: function onMouseDown() {}
};
/*:: import type {DraggableEventHandler} from './utils/types';*/
/*:: import type {Element as ReactElement} from 'react';*/
/*:: type DraggableState = {
dragging: boolean,
dragged: boolean,
x: number, y: number,
slackX: number, slackY: number,
isElementSVG: boolean
};*/
//
// Define <Draggable>
//
/*:: export type DraggableProps = {
...$Exact<DraggableCoreProps>,
axis: 'both' | 'x' | 'y' | 'none',
bounds: DraggableBounds | string | false,
defaultClassName: string,
defaultClassNameDragging: string,
defaultClassNameDragged: string,
defaultPosition: ControlPosition,
position: ControlPosition,
scale: number
};*/
var Draggable = function (_React$Component) {
inherits(Draggable, _React$Component);
function Draggable(props /*: DraggableProps*/) {
classCallCheck(this, Draggable);
var _this = possibleConstructorReturn(this, (Draggable.__proto__ || Object.getPrototypeOf(Draggable)).call(this, props));
_this.onDragStart = function (e, coreData) {
// Short-circuit if user's callback killed it.
var shouldStart = _this.props.onStart(e, createDraggableData(_this, coreData));
// Kills start event on core as well, so move handlers are never bound.
if (shouldStart === false) return false;
_this.setState({ dragging: true, dragged: true });
};
_this.onDrag = function (e, coreData) {
if (!_this.state.dragging) return false;
var uiData = createDraggableData(_this, coreData);
var newState /*: $Shape<DraggableState>*/ = {
x: uiData.x,
y: uiData.y
};
// Keep within bounds.
if (_this.props.bounds) {
// Save original x and y.
var _x = newState.x,
_y = newState.y;
// Add slack to the values used to calculate bound position. This will ensure that if
// we start removing slack, the element won't react to it right away until it's been
// completely removed.
newState.x += _this.state.slackX;
newState.y += _this.state.slackY;
// Get bound position. This will ceil/floor the x and y within the boundaries.
var _getBoundPosition = getBoundPosition(_this, newState.x, newState.y),
_getBoundPosition2 = slicedToArray(_getBoundPosition, 2),
newStateX = _getBoundPosition2[0],
newStateY = _getBoundPosition2[1];
newState.x = newStateX;
newState.y = newStateY;
// Recalculate slack by noting how much was shaved by the boundPosition handler.
newState.slackX = _this.state.slackX + (_x - newState.x);
newState.slackY = _this.state.slackY + (_y - newState.y);
// Update the event we fire to reflect what really happened after bounds took effect.
uiData.x = newState.x;
uiData.y = newState.y;
uiData.deltaX = newState.x - _this.state.x;
uiData.deltaY = newState.y - _this.state.y;
}
// Short-circuit if user's callback killed it.
var shouldUpdate = _this.props.onDrag(e, uiData);
if (shouldUpdate === false) return false;
_this.setState(newState);
};
_this.onDragStop = function (e, coreData) {
if (!_this.state.dragging) return false;
// Short-circuit if user's callback killed it.
var shouldStop = _this.props.onStop(e, createDraggableData(_this, coreData));
if (shouldStop === false) return false;
var newState /*: $Shape<DraggableState>*/ = {
dragging: false,
slackX: 0,
slackY: 0
};
// If this is a controlled component, the result of this operation will be to
// revert back to the old position. We expect a handler on `onDragStop`, at the least.
var controlled = Boolean(_this.props.position);
if (controlled) {
var _this$props$position = _this.props.position,
_x2 = _this$props$position.x,
_y2 = _this$props$position.y;
newState.x = _x2;
newState.y = _y2;
}
_this.setState(newState);
};
_this.state = {
// Whether or not we are currently dragging.
dragging: false,
// Whether or not we have been dragged before.
dragged: false,
// Current transform x and y.
x: props.position ? props.position.x : props.defaultPosition.x,
y: props.position ? props.position.y : props.defaultPosition.y,
// Used for compensating for out-of-bounds drags
slackX: 0, slackY: 0,
// Can only determine if SVG after mounting
isElementSVG: false
};
return _this;
}
createClass(Draggable, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.props.position && !(this.props.onDrag || this.props.onStop)) {
// eslint-disable-next-line
console.warn('A `position` was applied to this <Draggable>, without drag handlers. This will make this ' + 'component effectively undraggable. Please attach `onDrag` or `onStop` handlers so you can adjust the ' + '`position` of this element.');
}
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
// Check to see if the element passed is an instanceof SVGElement
if (typeof window.SVGElement !== 'undefined' && ReactDOM.findDOMNode(this) instanceof window.SVGElement) {
this.setState({ isElementSVG: true });
}
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps /*: Object*/) {
// Set x/y if position has changed
if (nextProps.position && (!this.props.position || nextProps.position.x !== this.props.position.x || nextProps.position.y !== this.props.position.y)) {
this.setState({ x: nextProps.position.x, y: nextProps.position.y });
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.setState({ dragging: false }); // prevents invariant if unmounted while dragging
}
}, {
key: 'render',
value: function render() /*: ReactElement<any>*/ {
var _classNames;
var style = {},
svgTransform = null;
// If this is controlled, we don't want to move it - unless it's dragging.
var controlled = Boolean(this.props.position);
var draggable = !controlled || this.state.dragging;
var position = this.props.position || this.props.defaultPosition;
var transformOpts = {
// Set left if horizontal drag is enabled
x: canDragX(this) && draggable ? this.state.x : position.x,
// Set top if vertical drag is enabled
y: canDragY(this) && draggable ? this.state.y : position.y
};
// If this element was SVG, we use the `transform` attribute.
if (this.state.isElementSVG) {
svgTransform = createSVGTransform(transformOpts);
} else {
// Add a CSS transform to move the element around. This allows us to move the element around
// without worrying about whether or not it is relatively or absolutely positioned.
// If the item you are dragging already has a transform set, wrap it in a <span> so <Draggable>
// has a clean slate.
style = createCSSTransform(transformOpts);
}
var _props = this.props,
defaultClassName = _props.defaultClassName,
defaultClassNameDragging = _props.defaultClassNameDragging,
defaultClassNameDragged = _props.defaultClassNameDragged;
var children = React$$1.Children.only(this.props.children);
// Mark with class while dragging
var className = classnames(children.props.className || '', defaultClassName, (_classNames = {}, defineProperty(_classNames, defaultClassNameDragging, this.state.dragging), defineProperty(_classNames, defaultClassNameDragged, this.state.dragged), _classNames));
// Reuse the child provided
// This makes it flexible to use whatever element is wanted (div, ul, etc)
return React$$1.createElement(
DraggableCore,
_extends({}, this.props, { onStart: this.onDragStart, onDrag: this.onDrag, onStop: this.onDragStop }),
React$$1.cloneElement(children, {
className: className,
style: _extends({}, children.props.style, style),
transform: svgTransform
})
);
}
}]);
return Draggable;
}(React$$1.Component);
Draggable.displayName = 'Draggable';
Draggable.propTypes = _extends({}, DraggableCore.propTypes, {
/**
* `axis` determines which axis the draggable can move.
*
* Note that all callbacks will still return data as normal. This only
* controls flushing to the DOM.
*
* 'both' allows movement horizontally and vertically.
* 'x' limits movement to horizontal axis.
* 'y' limits movement to vertical axis.
* 'none' limits all movement.
*
* Defaults to 'both'.
*/
axis: propTypes.oneOf(['both', 'x', 'y', 'none']),
/**
* `bounds` determines the range of movement available to the element.
* Available values are:
*
* 'parent' restricts movement within the Draggable's parent node.
*
* Alternatively, pass an object with the following properties, all of which are optional:
*
* {left: LEFT_BOUND, right: RIGHT_BOUND, bottom: BOTTOM_BOUND, top: TOP_BOUND}
*
* All values are in px.
*
* Example:
*
* ```jsx
* let App = React.createClass({
* render: function () {
* return (
* <Draggable bounds={{right: 300, bottom: 300}}>
* <div>Content</div>
* </Draggable>
* );
* }
* });
* ```
*/
bounds: propTypes.oneOfType([propTypes.shape({
left: propTypes.number,
right: propTypes.number,
top: propTypes.number,
bottom: propTypes.number
}), propTypes.string, propTypes.oneOf([false])]),
defaultClassName: propTypes.string,
defaultClassNameDragging: propTypes.string,
defaultClassNameDragged: propTypes.string,
/**
* `defaultPosition` specifies the x and y that the dragged item should start at
*
* Example:
*
* ```jsx
* let App = React.createClass({
* render: function () {
* return (
* <Draggable defaultPosition={{x: 25, y: 25}}>
* <div>I start with transformX: 25px and transformY: 25px;</div>
* </Draggable>
* );
* }
* });
* ```
*/
defaultPosition: propTypes.shape({
x: propTypes.number,
y: propTypes.number
}),
/**
* `position`, if present, defines the current position of the element.
*
* This is similar to how form elements in React work - if no `position` is supplied, the component
* is uncontrolled.
*
* Example:
*
* ```jsx
* let App = React.createClass({
* render: function () {
* return (
* <Draggable position={{x: 25, y: 25}}>
* <div>I start with transformX: 25px and transformY: 25px;</div>
* </Draggable>
* );
* }
* });
* ```
*/
position: propTypes.shape({
x: propTypes.number,
y: propTypes.number
}),
/**
* These properties should be defined on the child, not here.
*/
className: dontSetMe,
style: dontSetMe,
transform: dontSetMe
});
Draggable.defaultProps = _extends({}, DraggableCore.defaultProps, {
axis: 'both',
bounds: false,
defaultClassName: 'react-draggable',
defaultClassNameDragging: 'react-draggable-dragging',
defaultClassNameDragged: 'react-draggable-dragged',
defaultPosition: { x: 0, y: 0 },
position: null,
scale: 1
});
// Previous versions of this lib exported <Draggable> as the root export. As to not break
// them, or TypeScript, we export *both* as the root and as 'default'.
// See https://github.com/mzabriskie/react-draggable/pull/254
// and https://github.com/mzabriskie/react-draggable/issues/266
Draggable.default = Draggable;
Draggable.DraggableCore = DraggableCore;
return Draggable;
})));
});
var index_es5 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var Resizable$$1 = _interopDefault(Resizable);
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __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;
};
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)
t[p[i]] = s[p[i]];
return t;
}
var resizableStyle = {
width: "auto",
height: "auto",
display: "inline-block",
position: "absolute",
top: 0,
left: 0,
};
var Rnd = /** @class */ (function (_super) {
__extends(Rnd, _super);
function Rnd(props) {
var _this = _super.call(this, props) || this;
_this.isResizing = false;
_this.state = {
original: {
x: 0,
y: 0,
},
bounds: {
top: 0,
right: 0,
bottom: 0,
left: 0,
},
maxWidth: props.maxWidth,
maxHeight: props.maxHeight,
};
_this.onResizeStart = _this.onResizeStart.bind(_this);
_this.onResize = _this.onResize.bind(_this);
_this.onResizeStop = _this.onResizeStop.bind(_this);
_this.onDragStart = _this.onDragStart.bind(_this);
_this.onDrag = _this.onDrag.bind(_this);
_this.onDragStop = _this.onDragStop.bind(_this);
_this.getMaxSizesFromProps = _this.getMaxSizesFromProps.bind(_this);
return _this;
}
Rnd.prototype.componentDidMount = function () {
var _a = this.getOffsetFromParent(), left = _a.left, top = _a.top;
var _b = this.getDraggablePosition(), x = _b.x, y = _b.y;
this.draggable.setState({
x: x - left,
y: y - top,
});
// HACK: Apply position adjustment
this.forceUpdate();
};
// HACK: To get `react-draggable` state x and y.
Rnd.prototype.getDraggablePosition = function () {
var _a = this.draggable.state, x = _a.x, y = _a.y;
return { x: x, y: y };
};
Rnd.prototype.getParent = function () {
return this.resizable && this.resizable.parentNode;
};
Rnd.prototype.getParentSize = function () {
return this.resizable.getParentSize();
};
Rnd.prototype.getMaxSizesFromProps = function () {
var maxWidth = typeof this.props.maxWidth === "undefined" ? Number.MAX_SAFE_INTEGER : this.props.maxWidth;
var maxHeight = typeof this.props.maxHeight === "undefined" ? Number.MAX_SAFE_INTEGER : this.props.maxHeight;
return { maxWidth: maxWidth, maxHeight: maxHeight };
};
Rnd.prototype.getSelfElement = function () {
return this.resizable && this.resizable.resizable;
};
Rnd.prototype.getOffsetHeight = function (boundary) {
var scale = this.props.scale;
switch (this.props.bounds) {
case "window":
return window.innerHeight / scale;
case "body":
return document.body.offsetHeight / scale;
default:
return boundary.offsetHeight;
}
};
Rnd.prototype.getOffsetWidth = function (boundary) {
var scale = this.props.scale;
switch (this.props.bounds) {
case "window":
return window.innerWidth / scale;
case "body":
return document.body.offsetWidth / scale;
default:
return boundary.offsetWidth;
}
};
Rnd.prototype.onDragStart = function (e, data) {
if (this.props.onDragStart) {
this.props.onDragStart(e, data);
}
if (!this.props.bounds)
return;
var parent = this.getParent();
var scale = this.props.scale;
var boundary;
if (this.props.bounds === "parent") {
boundary = parent;
}
else if (this.props.bounds === "body") {
var parentRect_1 = parent.getBoundingClientRect();
var parentLeft_1 = parentRect_1.left;
var parentTop_1 = parentRect_1.top;
var bodyRect = document.body.getBoundingClientRect();
var left_1 = -(parentLeft_1 - parent.offsetLeft * scale - bodyRect.left) / scale;
var top_1 = -(parentTop_1 - parent.offsetTop * scale - bodyRect.top) / scale;
var right = (document.body.offsetWidth - this.resizable.size.width * scale) / scale + left_1;
var bottom = (document.body.offsetHeight - this.resizable.size.height * scale) / scale + top_1;
return this.setState({ bounds: { top: top_1, right: right, bottom: bottom, left: left_1 } });
}
else if (this.props.bounds === "window") {
if (!this.resizable)
return;
var parentRect_2 = parent.getBoundingClientRect();
var parentLeft_2 = parentRect_2.left;
var parentTop_2 = parentRect_2.top;
var left_2 = -(parentLeft_2 - parent.offsetLeft * scale) / scale;
var top_2 = -(parentTop_2 - parent.offsetTop * scale) / scale;
var right = (window.innerWidth - this.resizable.size.width * scale) / scale + left_2;
var bottom = (window.innerHeight - this.resizable.size.height * scale) / scale + top_2;
return this.setState({ bounds: { top: top_2, right: right, bottom: bottom, left: left_2 } });
}
else {
boundary = document.querySelector(this.props.bounds);
}
if (!(boundary instanceof HTMLElement) || !(parent instanceof HTMLElement)) {
return;
}
var boundaryRect = boundary.getBoundingClientRect();
var boundaryLeft = boundaryRect.left;
var boundaryTop = boundaryRect.top;
var parentRect = parent.getBoundingClientRect();
var parentLeft = parentRect.left;
var parentTop = parentRect.top;
var left = (boundaryLeft - parentLeft) / scale;
var top = boundaryTop - parentTop;
if (!this.resizable)
return;
var offset = this.getOffsetFromParent();
this.setState({
bounds: {
top: top - offset.top,
right: left + (boundary.offsetWidth - this.resizable.size.width) - offset.left / scale,
bottom: top + (boundary.offsetHeight - this.resizable.size.height) - offset.top,
left: left - offset.left / scale,
},
});
};
Rnd.prototype.onDrag = function (e, data) {
if (this.props.onDrag) {
var offset = this.getOffsetFromParent();
this.props.onDrag(e, __assign({}, data, { x: data.x - offset.left, y: data.y - offset.top }));
}
};
Rnd.prototype.onDragStop = function (e, data) {
if (this.props.onDragStop) {
var _a = this.getOffsetFromParent(), left = _a.left, top_3 = _a.top;
return this.props.onDragStop(e, __assign({}, data, { x: data.x + left, y: data.y + top_3 }));
}
};
Rnd.prototype.onResizeStart = function (e, dir, elementRef) {
e.stopPropagation();
this.isResizing = true;
var scale = this.props.scale;
this.setState({
original: this.getDraggablePosition(),
});
if (this.props.bounds) {
var parent_1 = this.getParent();
var boundary = void 0;
if (this.props.bounds === "parent") {
boundary = parent_1;
}
else if (this.props.bounds === "body") {
boundary = document.body;
}
else if (this.props.bounds === "window") {
boundary = window;
}
else {
boundary = document.querySelector(this.props.bounds);
}
var self_1 = this.getSelfElement();
if (self_1 instanceof Element &&
(boundary instanceof HTMLElement || boundary === window) &&
parent_1 instanceof HTMLElement) {
var _a = this.getMaxSizesFromProps(), maxWidth = _a.maxWidth, maxHeight = _a.maxHeight;
var parentSize = this.getParentSize();
if (maxWidth && typeof maxWidth === "string") {
if (maxWidth.endsWith("%")) {
var ratio = Number(maxWidth.replace("%", "")) / 100;
maxWidth = parentSize.width * ratio;
}
else if (maxWidth.endsWith("px")) {
maxWidth = Number(maxWidth.replace("px", ""));
}
}
if (maxHeight && typeof maxHeight === "string") {
if (maxHeight.endsWith("%")) {
var ratio = Number(maxHeight.replace("%", "")) / 100;
maxHeight = parentSize.width * ratio;
}
else if (maxHeight.endsWith("px")) {
maxHeight = Number(maxHeight.replace("px", ""));
}
}
var selfRect = self_1.getBoundingClientRect();
var selfLeft = selfRect.left;
var selfTop = selfRect.top;
var boundaryRect = this.props.bounds === "window" ? { left: 0, top: 0 } : boundary.getBoundingClientRect();
var boundaryLeft = boundaryRect.left;
var boundaryTop = boundaryRect.top;
var offsetWidth = this.getOffsetWidth(boundary);
var offsetHeight = this.getOffsetHeight(boundary);
var hasLeft = dir.toLowerCase().endsWith("left");
var hasRight = dir.toLowerCase().endsWith("right");
var hasTop = dir.startsWith("top");
var hasBottom = dir.startsWith("bottom");
if (hasLeft && this.resizable) {
var max = (selfLeft - boundaryLeft) / scale + this.resizable.size.width;
this.setState({ maxWidth: max > Number(maxWidth) ? maxWidth : max });
}
// INFO: To set bounds in `lock aspect ratio with bounds` case. See also that story.
if (hasRight || (this.props.lockAspectRatio && !hasLeft)) {
var max = offsetWidth + (boundaryLeft - selfLeft) / scale;
this.setState({ maxWidth: max > Number(maxWidth) ? maxWidth : max });
}
if (hasTop && this.resizable) {
var max = (selfTop - boundaryTop) / scale + this.resizable.size.height;
this.setState({
maxHeight: max > Number(maxHeight) ? maxHeight : max,
});
}
// INFO: To set bounds in `lock aspect ratio with bounds` case. See also that story.
if (hasBottom || (this.props.lockAspectRatio && !hasTop)) {
var max = offsetHeight + (boundaryTop - selfTop) / scale;
this.setState({
maxHeight: max > Number(maxHeight) ? maxHeight : max,
});
}
}
}
else {
this.setState({
maxWidth: this.props.maxWidth,
maxHeight: this.props.maxHeight,
});
}
if (this.props.onResizeStart) {
this.props.onResizeStart(e, dir, elementRef);
}
};
Rnd.prototype.onResize = function (e, direction, elementRef, delta) {
var x;
var y;
var offset = this.getOffsetFromParent();
if (/left/i.test(direction)) {
x = this.state.original.x - delta.width;
// INFO: If uncontrolled component, apply x position by resize to draggable.
if (!this.props.position) {
this.draggable.setState({ x: x });
}
x += offset.left;
}
if (/top/i.test(direction)) {
y = this.state.original.y - delta.height;
// INFO: If uncontrolled component, apply y position by resize to draggable.
if (!this.props.position) {
this.draggable.setState({ y: y });
}
y += offset.top;
}
if (this.props.onResize) {
if (typeof x === "undefined") {
x = this.getDraggablePosition().x + offset.left;
}
if (typeof y === "undefined") {
y = this.getDraggablePosition().y + offset.top;
}
this.props.onResize(e, direction, elementRef, delta, {
x: x,
y: y,
});
}
};
Rnd.prototype.onResizeStop = function (e, direction, elementRef, delta) {
this.isResizing = false;
var _a = this.getMaxSizesFromProps(), maxWidth = _a.maxWidth, maxHeight = _a.maxHeight;
this.setState({ maxWidth: maxWidth, maxHeight: maxHeight });
if (this.props.onResizeStop) {
var position = this.getDraggablePosition();
this.props.onResizeStop(e, direction, elementRef, delta, position);
}
};
Rnd.prototype.updateSize = function (size) {
if (!this.resizable)
return;
this.resizable.updateSize({ width: size.width, height: size.height });
};
Rnd.prototype.updatePosition = function (position) {
this.draggable.setState(position);
};
Rnd.prototype.getOffsetFromParent = function () {
var scale = this.props.scale;
var parent = this.getParent();
if (!parent) {
return {
top: 0,
left: 0,
};
}
var parentRect = parent.getBoundingClientRect();
var parentLeft = parentRect.left;
var parentTop = parentRect.top;
var selfRect = this.getSelfElement().getBoundingClientRect();
var position = this.getDraggablePosition();
return {
left: selfRect.left - parentLeft - position.x * scale,
top: selfRect.top - parentTop - position.y * scale,
};
};
Rnd.prototype.render = function () {
var _this = this;
var _a = this.props, disableDragging = _a.disableDragging, style = _a.style, dragHandleClassName = _a.dragHandleClassName, position = _a.position, onMouseDown = _a.onMouseDown, dragAxis = _a.dragAxis, dragGrid = _a.dragGrid, bounds = _a.bounds, enableUserSelectHack = _a.enableUserSelectHack, cancel = _a.cancel, children = _a.children, onResizeStart = _a.onResizeStart, onResize = _a.onResize, onResizeStop = _a.onResizeStop, onDragStart = _a.onDragStart, onDrag = _a.onDrag, onDragStop = _a.onDragStop, resizeHandleStyles = _a.resizeHandleStyles, resizeHandleClasses = _a.resizeHandleClasses, enableResizing = _a.enableResizing, resizeGrid = _a.resizeGrid, resizeHandleWrapperClass = _a.resizeHandleWrapperClass, resizeHandleWrapperStyle = _a.resizeHandleWrapperStyle, scale = _a.scale, resizableProps = __rest(_a, ["disableDragging", "style", "dragHandleClassName", "position", "onMouseDown", "dragAxis", "dragGrid", "bounds", "enableUserSelectHack", "cancel", "children", "onResizeStart", "onResize", "onResizeStop", "onDragStart", "onDrag", "onDragStop", "resizeHandleStyles", "resizeHandleClasses", "enableResizing", "resizeGrid", "resizeHandleWrapperClass", "resizeHandleWrapperStyle", "scale"]);
var defaultValue = this.props.default ? __assign({}, this.props.default) : undefined;
// Remove unknown props, see also https://reactjs.org/warnings/unknown-prop.html
delete resizableProps.default;
var cursorStyle = disableDragging || dragHandleClassName ? { cursor: "auto" } : { cursor: "move" };
var innerStyle = __assign({}, resizableStyle, cursorStyle, style);
var _b = this.getOffsetFromParent(), left = _b.left, top = _b.top;
var draggablePosition;
if (position) {
draggablePosition = {
x: position.x - left,
y: position.y - top,
};
}
return (React__default.createElement(reactDraggable, { ref: function (c) {
if (!c)
return;
_this.draggable = c;
}, handle: dragHandleClassName ? "." + dragHandleClassName : undefined, defaultPosition: defaultValue, onMouseDown: onMouseDown, onStart: this.onDragStart, onDrag: this.onDrag, onStop: this.onDragStop, axis: dragAxis, disabled: disableDragging, grid: dragGrid, bounds: bounds ? this.state.bounds : undefined, position: draggablePosition, enableUserSelectHack: enableUserSelectHack, cancel: cancel, scale: scale },
React__default.createElement(Resizable$$1, __assign({}, resizableProps, { ref: function (c) {
if (c) {
_this.resizable = c;
}
}, defaultSize: defaultValue, size: this.props.size, enable: enableResizing, onResizeStart: this.onResizeStart, onResize: this.onResize, onResizeStop: this.onResizeStop, style: innerStyle, minWidth: this.props.minWidth, minHeight: this.props.minHeight, maxWidth: this.isResizing ? this.state.maxWidth : this.props.maxWidth, maxHeight: this.isResizing ? this.state.maxHeight : this.props.maxHeight, grid: resizeGrid, handleWrapperClass: resizeHandleWrapperClass, handleWrapperStyle: resizeHandleWrapperStyle, lockAspectRatio: this.props.lockAspectRatio, lockAspectRatioExtraWidth: this.props.lockAspectRatioExtraWidth, lockAspectRatioExtraHeight: this.props.lockAspectRatioExtraHeight, handleStyles: resizeHandleStyles, handleClasses: resizeHandleClasses, scale: this.props.scale }), children)));
};
Rnd.defaultProps = {
maxWidth: Number.MAX_SAFE_INTEGER,
maxHeight: Number.MAX_SAFE_INTEGER,
scale: 1,
onResizeStart: function () { },
onResize: function () { },
onResizeStop: function () { },
onDragStart: function () { },
onDrag: function () { },
onDragStop: function () { },
};
return Rnd;
}(React__default.Component));
exports.Rnd = Rnd;
});
unwrapExports(index_es5);
var index_es5_1 = index_es5.Rnd;
var DialogContext = React__default.createContext({});
var Title = function Title(_ref) {
var title = _ref.title,
id = _ref.id;
return React__default.createElement("span", {
id: "dialog__title__".concat(id),
"data-testid": "dialog__header__title",
className: "dialog__header__title"
}, title);
};
var Close = function Close(_ref2) {
var onClose = _ref2.onClose;
return React__default.createElement("div", {
"data-testid": "dialog__header__icon",
className: "dialog__header__icon"
}, React__default.createElement(IconButton, {
onClick: onClose
}, React__default.createElement("i", {
className: "dialog__icon dialog__icon--close"
})));
};
var Actions = function Actions(_ref3) {
var closable = _ref3.closable,
onClose = _ref3.onClose;
return React__default.createElement("div", {
"data-testid": "dialog__header",
className: "dialog__header button-group"
}, React__default.createElement(Close, {
onClose: onClose
}));
};
function DialogHeader(props) {
var _React$useContext = React__default.useContext(DialogContext),
closable = _React$useContext.closable,
onClose = _React$useContext.onClose,
id = _React$useContext.id;
return React__default.createElement("div", {
className: "dialog__header"
}, React__default.createElement(Title, {
title: props.title,
id: id
}), closable ? React__default.createElement(Actions, {
closable: closable,
onClose: onClose
}) : null);
}
DialogHeader.displayName = "Dialog.Header";
DialogHeader.defaultProps = {
closable: true,
title: "\xA0" //
};
function Section(_ref) {
var children = _ref.children,
className = _ref.className,
_ref$collapsible = _ref.collapsible,
collapsible = _ref$collapsible === void 0 ? false : _ref$collapsible,
_ref$initialCollapsed = _ref.initialCollapsed,
initialCollapsed = _ref$initialCollapsed === void 0 ? false : _ref$initialCollapsed,
title = _ref.title,
toolbar = _ref.toolbar,
_ref$style = _ref.style,
style = _ref$style === void 0 ? {} : _ref$style,
maxHeight = _ref.maxHeight,
rest = objectWithoutProperties(_ref, ["children", "className", "collapsible", "initialCollapsed", "title", "toolbar", "style", "maxHeight"]);
var _React$useReducer = React.useReducer(function (state) {
return !state;
}, !initialCollapsed),
_React$useReducer2 = slicedToArray(_React$useReducer, 2),
expanded = _React$useReducer2[0],
toggleExpanded = _React$useReducer2[1];
var calculatedStyle = React.useMemo(function () {
return objectSpread({}, style, maxHeight ? {
maxHeight: "".concat(maxHeight, "px")
} : {});
}, [style, maxHeight]);
var handleCollapseKeyDown = React.useCallback(function (e) {
if (e.key === "Enter") {
toggleExpanded();
}
}, []);
return React.createElement("div", _extends_1({
className: classnames("section", className, {
"section--collapsed": !expanded
})
}, rest, {
style: calculatedStyle
}), React.createElement("div", {
className: "section__header"
}, React.createElement("div", {
className: "section__header__container"
}, collapsible ? React.createElement("i", {
onKeyDown: handleCollapseKeyDown,
role: "button",
tabIndex: "0",
className: classnames("section__header__toggle-expansion-icon", {
"section__header__toggle-expansion-icon--expanded": expanded
}),
onClick: toggleExpanded
}) : null, title, toolbar ? toolbar({
expanded: expanded
}) : null)), React.createElement("div", {
className: classnames("section__content", {
"section__content--collapsed": !expanded
})
}, children));
}
function Panel(_ref) {
var children = _ref.children,
collapsible = _ref.collapsible,
initialCollapsed = _ref.initialCollapsed,
maxHeight = _ref.maxHeight,
toolbar = _ref.toolbar,
title = _ref.title,
className = _ref.className,
rest = objectWithoutProperties(_ref, ["children", "collapsible", "initialCollapsed", "maxHeight", "toolbar", "title", "className"]);
return React.createElement("div", _extends_1({
className: classnames("panel", className)
}, rest), title ? React.createElement(Section, {
collapsible: collapsible,
children: children,
initialCollapsed: initialCollapsed,
title: title,
toolbar: toolbar,
maxHeight: maxHeight
}) : children);
}
var Instructions = function Instructions(_ref) {
var instructions = _ref.instructions;
return React.createElement("p", {
className: "dialog__content__text"
}, instructions);
};
function DialogContent(props) {
var context = React.useContext(DialogContext);
var instructions = context.instructions,
id = context.id;
if (!instructions) {
instructions = props.instructions;
}
if (!id) {
id = props.id;
}
return React.createElement("div", {
className: "dialog__content"
}, instructions ? React.createElement(Instructions, {
instructions: instructions
}) : null, typeof props.children === "function" ? props.children(id) : React.createElement(Panel, {
id: id ? "dialog__content__".concat(id) : null
}, React.createElement("p", null, props.children)));
}
DialogContent.displayName = "Dialog.Content";
var handleLinkClick = function handleLinkClick(link) {
return window.open(link);
};
var Help = React.memo(function (_ref) {
var help = _ref.help;
return React.createElement("div", {
className: "dialog__footer__help"
}, React.createElement(IconButton, {
title: "Open Help",
onClick: function onClick() {
return handleLinkClick(help);
}
}, React.createElement("i", {
className: "dialog__icon dialog__icon--help"
})));
});
function DialogFooter(_ref2) {
var children = _ref2.children,
rest = objectWithoutProperties(_ref2, ["children"]);
var _React$useContext = React.useContext(DialogContext),
help = _React$useContext.help,
onClose = _React$useContext.onClose;
return React.createElement("div", _extends_1({
className: "dialog__footer"
}, rest), help ? React.createElement(Help, {
help: help
}) : null, React.createElement("div", {
className: "dialog__footer__buttons button-group"
}, children(onClose)));
}
DialogFooter.displayName = "Dialog.Footer";
var reactIs_production_min = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports,"__esModule",{value:!0});
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.memo"):
60115,r=b?Symbol.for("react.lazy"):60116;function t(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 h:return a;default:return u}}case r:case q:case d:return u}}}function v(a){return t(a)===m}exports.typeOf=t;exports.AsyncMode=l;exports.ConcurrentMode=m;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=n;
exports.Fragment=e;exports.Lazy=r;exports.Memo=q;exports.Portal=d;exports.Profiler=g;exports.StrictMode=f;exports.Suspense=p;exports.isValidElementType=function(a){return "string"===typeof a||"function"===typeof a||a===e||a===m||a===g||a===f||a===p||"object"===typeof a&&null!==a&&(a.$$typeof===r||a.$$typeof===q||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n)};exports.isAsyncMode=function(a){return v(a)||t(a)===l};exports.isConcurrentMode=v;exports.isContextConsumer=function(a){return t(a)===k};
exports.isContextProvider=function(a){return t(a)===h};exports.isElement=function(a){return "object"===typeof a&&null!==a&&a.$$typeof===c};exports.isForwardRef=function(a){return t(a)===n};exports.isFragment=function(a){return t(a)===e};exports.isLazy=function(a){return t(a)===r};exports.isMemo=function(a){return t(a)===q};exports.isPortal=function(a){return t(a)===d};exports.isProfiler=function(a){return t(a)===g};exports.isStrictMode=function(a){return t(a)===f};
exports.isSuspense=function(a){return t(a)===p};
});
unwrapExports(reactIs_production_min);
var reactIs_production_min_1 = reactIs_production_min.typeOf;
var reactIs_production_min_2 = reactIs_production_min.AsyncMode;
var reactIs_production_min_3 = reactIs_production_min.ConcurrentMode;
var reactIs_production_min_4 = reactIs_production_min.ContextConsumer;
var reactIs_production_min_5 = reactIs_production_min.ContextProvider;
var reactIs_production_min_6 = reactIs_production_min.Element;
var reactIs_production_min_7 = reactIs_production_min.ForwardRef;
var reactIs_production_min_8 = reactIs_production_min.Fragment;
var reactIs_production_min_9 = reactIs_production_min.Lazy;
var reactIs_production_min_10 = reactIs_production_min.Memo;
var reactIs_production_min_11 = reactIs_production_min.Portal;
var reactIs_production_min_12 = reactIs_production_min.Profiler;
var reactIs_production_min_13 = reactIs_production_min.StrictMode;
var reactIs_production_min_14 = reactIs_production_min.Suspense;
var reactIs_production_min_15 = reactIs_production_min.isValidElementType;
var reactIs_production_min_16 = reactIs_production_min.isAsyncMode;
var reactIs_production_min_17 = reactIs_production_min.isConcurrentMode;
var reactIs_production_min_18 = reactIs_production_min.isContextConsumer;
var reactIs_production_min_19 = reactIs_production_min.isContextProvider;
var reactIs_production_min_20 = reactIs_production_min.isElement;
var reactIs_production_min_21 = reactIs_production_min.isForwardRef;
var reactIs_production_min_22 = reactIs_production_min.isFragment;
var reactIs_production_min_23 = reactIs_production_min.isLazy;
var reactIs_production_min_24 = reactIs_production_min.isMemo;
var reactIs_production_min_25 = reactIs_production_min.isPortal;
var reactIs_production_min_26 = reactIs_production_min.isProfiler;
var reactIs_production_min_27 = reactIs_production_min.isStrictMode;
var reactIs_production_min_28 = reactIs_production_min.isSuspense;
var reactIs_development = createCommonjsModule(function (module, exports) {
});
unwrapExports(reactIs_development);
var reactIs_development_1 = reactIs_development.typeOf;
var reactIs_development_2 = reactIs_development.AsyncMode;
var reactIs_development_3 = reactIs_development.ConcurrentMode;
var reactIs_development_4 = reactIs_development.ContextConsumer;
var reactIs_development_5 = reactIs_development.ContextProvider;
var reactIs_development_6 = reactIs_development.Element;
var reactIs_development_7 = reactIs_development.ForwardRef;
var reactIs_development_8 = reactIs_development.Fragment;
var reactIs_development_9 = reactIs_development.Lazy;
var reactIs_development_10 = reactIs_development.Memo;
var reactIs_development_11 = reactIs_development.Portal;
var reactIs_development_12 = reactIs_development.Profiler;
var reactIs_development_13 = reactIs_development.StrictMode;
var reactIs_development_14 = reactIs_development.Suspense;
var reactIs_development_15 = reactIs_development.isValidElementType;
var reactIs_development_16 = reactIs_development.isAsyncMode;
var reactIs_development_17 = reactIs_development.isConcurrentMode;
var reactIs_development_18 = reactIs_development.isContextConsumer;
var reactIs_development_19 = reactIs_development.isContextProvider;
var reactIs_development_20 = reactIs_development.isElement;
var reactIs_development_21 = reactIs_development.isForwardRef;
var reactIs_development_22 = reactIs_development.isFragment;
var reactIs_development_23 = reactIs_development.isLazy;
var reactIs_development_24 = reactIs_development.isMemo;
var reactIs_development_25 = reactIs_development.isPortal;
var reactIs_development_26 = reactIs_development.isProfiler;
var reactIs_development_27 = reactIs_development.isStrictMode;
var reactIs_development_28 = reactIs_development.isSuspense;
var reactIs = createCommonjsModule(function (module) {
{
module.exports = reactIs_production_min;
}
});
/**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var REACT_STATICS = {
childContextTypes: true,
contextType: true,
contextTypes: true,
defaultProps: true,
displayName: true,
getDefaultProps: true,
getDerivedStateFromError: true,
getDerivedStateFromProps: true,
mixins: true,
propTypes: true,
type: true
};
var KNOWN_STATICS = {
name: true,
length: true,
prototype: true,
caller: true,
callee: true,
arguments: true,
arity: true
};
var FORWARD_REF_STATICS = {
'$$typeof': true,
render: true,
defaultProps: true,
displayName: true,
propTypes: true
};
var MEMO_STATICS = {
'$$typeof': true,
compare: true,
defaultProps: true,
displayName: true,
propTypes: true,
type: true
};
var TYPE_STATICS = {};
TYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS;
function getStatics(component) {
if (reactIs.isMemo(component)) {
return MEMO_STATICS;
}
return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;
}
var defineProperty$1 = Object.defineProperty;
var getOwnPropertyNames = Object.getOwnPropertyNames;
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var getPrototypeOf$1 = 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$1(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$1(targetComponent, key, descriptor);
} catch (e) {}
}
}
return targetComponent;
}
return targetComponent;
}
var hoistNonReactStatics_cjs = hoistNonReactStatics;
var withPortal = function withPortal(_ref) {
var customSelector = _ref.customSelector,
customRoot = _ref.customRoot,
rest = objectWithoutProperties(_ref, ["customSelector", "customRoot"]);
return function withPortal(BaseComponent) {
var Component = function Component(props) {
if (customRoot && !(customRoot instanceof HTMLElement)) {
throw new Error("customRoot must be an instance of an HTMLElement");
}
return _reactDom.createPortal(React.createElement(BaseComponent, _extends_1({
className: customSelector
}, rest, props)), // $FlowFixMe
customRoot ? customRoot : document.body);
};
Component.displayName = BaseComponent.displayName;
hoistNonReactStatics_cjs(Component, BaseComponent);
return Component;
};
};
var rndDefault = null;
var ESC_KEY = 27;
var RegularDialog = function RegularDialog(props, id) {
var className = props.className,
style = props.style,
children = props.children,
rest = objectWithoutProperties(props, ["className", "style", "children"]);
rest.id = id;
if (props.draggable || props.resizable) {
var width = Math.round(window.innerWidth / 2);
var height = Math.round(window.innerHeight / 2);
if (rndDefault) {
if (rndDefault.x !== width) {
rndDefault.x = width;
}
if (rndDefault.y !== height) {
rndDefault.y = height;
}
}
}
return React.createElement("div", {
className: classnames("dialog", props.resizable ? "dialog--resize" : "", props.draggable ? "dialog--draggable" : "", className),
style: style,
role: "dialog",
"aria-labelledby": "dialog__title__".concat(id),
"aria-describedby": "dialog__content__".concat(id),
"aria-modal": "true",
"aria-hidden": props.closed
}, React.createElement(DialogContext.Provider, {
value: rest
}, children));
};
function Dialog(props) {
var handleKeyUp = React.useCallback(function (e) {
if (e.keyCode === ESC_KEY) {
props.onClose();
}
}, [props.onClose]);
React.useEffect(function () {
if (!rndDefault) {
rndDefault = {
x: Math.round(window.innerWidth / 2),
y: Math.round(window.innerHeight / 2)
};
}
if (!props.closed) {
window.addEventListener("keyup", handleKeyUp);
}
return function () {
window.removeEventListener("keyup", handleKeyUp);
};
}, [props.closed, rndDefault]);
if (props.closed) {
return null;
}
if (props.closable && !props.onClose) {
throw new Error("A closable dialog must contain an onClose callback");
}
var id = Math.round(Math.random() * 1000);
if (props.draggable || props.resizable) {
return React.createElement("div", {
className: "dimmer"
}, React.createElement(index_es5_1, _extends_1({
"default": rndDefault,
disableDragging: !props.draggable
}, props.rnd), RegularDialog(props, id)));
}
return React.createElement(React.Fragment, null, props.dimmer ? React.createElement("div", {
className: "dimmer"
}) : null, RegularDialog(props, id));
}
Dialog.Header = DialogHeader;
Dialog.Content = DialogContent;
Dialog.Footer = DialogFooter;
Dialog.Features = {
withPortal: function withPortal$$1(args) {
return withPortal(objectSpread({}, args, {
customSelector: "dialog--portal"
}));
}
};
Dialog.defaultProps = {
resizable: true,
draggable: true,
bounds: "window",
closable: true,
dimmer: true
};
var Loader =
/*#__PURE__*/
function (_Component) {
inherits(Loader, _Component);
function Loader() {
var _getPrototypeOf2;
var _this;
classCallCheck(this, Loader);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = possibleConstructorReturn(this, (_getPrototypeOf2 = getPrototypeOf(Loader)).call.apply(_getPrototypeOf2, [this].concat(args)));
defineProperty(assertThisInitialized(_this), "delayedTimer", null);
defineProperty(assertThisInitialized(_this), "errorTimer", null);
defineProperty(assertThisInitialized(_this), "showTimer", null);
defineProperty(assertThisInitialized(_this), "state", {
show: false,
showDelayed: false,
showError: false
});
defineProperty(assertThisInitialized(_this), "getMessage", function () {
if (_this.state.showError && _this.props.errorMessage) {
return _this.props.errorMessage;
}
if (_this.state.showDelayed) {
return _this.props.delayedMessage;
}
return _this.props.message;
});
return _this;
}
createClass(Loader, [{
key: "componentDidMount",
value: function componentDidMount() {
var _this2 = this;
if (this.props.delayedTimeout) {
this.delayedTimer = setTimeout(function () {
_this2.delayedTimer = null;
_this2.setState({
showDelayed: true
});
}, this.props.delayedTimeout);
}
if (this.props.errorTimeout) {
this.errorTimer = setTimeout(function () {
_this2.errorTimer = null;
_this2.setState({
showError: true
});
}, this.props.errorTimeout);
}
if (!this.props.delayShowTimeout) {
this.setState({
show: true
});
} else {
this.showTimer = setTimeout(function () {
_this2.showTimer = null;
_this2.setState({
show: true
});
}, this.props.delayShowTimeout);
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
if (this.delayedTimer) {
clearTimeout(this.delayedTimer);
}
if (this.errorTimer) {
clearTimeout(this.errorTimer);
}
if (this.showTimer) {
clearTimeout(this.showTimer);
}
}
}, {
key: "render",
value: function render() {
if (!this.state.show) {
return null;
}
return React__default.createElement("div", {
className: ["loader", this.props.darken ? "loader--darken" : null, this.props.lighten ? "loader--lighten" : null].join(" ")
}, React__default.createElement("div", {
className: "loader__spinner"
}, React__default.createElement("div", {
className: "sk-fading-circle"
}, React__default.createElement("div", {
className: "sk-circle1 sk-circle"
}), React__default.createElement("div", {
className: "sk-circle2 sk-circle"
}), React__default.createElement("div", {
className: "sk-circle3 sk-circle"
}), React__default.createElement("div", {
className: "sk-circle4 sk-circle"
}), React__default.createElement("div", {
className: "sk-circle5 sk-circle"
}), React__default.createElement("div", {
className: "sk-circle6 sk-circle"
}), React__default.createElement("div", {
className: "sk-circle7 sk-circle"
}), React__default.createElement("div", {
className: "sk-circle8 sk-circle"
}), React__default.createElement("div", {
className: "sk-circle9 sk-circle"
}), React__default.createElement("div", {
className: "sk-circle10 sk-circle"
}), React__default.createElement("div", {
className: "sk-circle11 sk-circle"
}), React__default.createElement("div", {
className: "sk-circle12 sk-circle"
}))), React__default.createElement("div", {
className: "loader__message"
}, this.getMessage()));
}
}]);
return Loader;
}(React.Component);
defineProperty(Loader, "defaultProps", {
lighten: false,
darken: false,
delayedMessage: "This is taking longer than expected...",
message: "Loading..."
});
var GroupContext = React__default.createContext();
var generateId = function generateId() {
return "form_".concat((Date.now() + Math.random()).toString().replace(".", ""));
};
function FormGroup(_ref) {
var children = _ref.children;
return React__default.createElement(GroupContext.Provider, {
value: generateId()
}, React__default.createElement("div", {
className: "form__group"
}, children));
}
FormGroup.Context = GroupContext;
/**
* Used for read-only states in the form.
* Using context here makes it easy to pass
* state down to all children components.
*/
var FormContext = React__default.createContext();
function _defineProperty$1(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _objectSpread$1(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === 'function') {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function (key) {
_defineProperty$1(target, key, source[key]);
});
}
return target;
}
function _slicedToArray$1(arr, i) {
return _arrayWithHoles$1(arr) || _iterableToArrayLimit$1(arr, i) || _nonIterableRest$1();
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2;
}
}
function _arrayWithHoles$1(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArray(iter) {
if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}
function _iterableToArrayLimit$1(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance");
}
function _nonIterableRest$1() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
/**
* Shamelessly stolen positioning logic from the Evergreen Components library. Thanks!
* https://github.com/segmentio/evergreen/blob/master/src/positioner/src/getPosition.js
*/
var Position = {
TOP: "top",
TOP_LEFT: "top-left",
TOP_RIGHT: "top-right",
BOTTOM: "bottom",
BOTTOM_LEFT: "bottom-left",
BOTTOM_RIGHT: "bottom-right",
LEFT: "left",
RIGHT: "right"
};
/**
* Function to create a Rect.
* @param {Object} dimensions
* @param {Number} dimensions.width
* @param {Number} dimensions.height
* @param {Object} position
* @param {Number} position.left
* @param {Number} position.top
* @return {Object} Rect { width, height, left, top, right, bottom }
*/
var makeRect = function makeRect(_ref, _ref2) {
var width = _ref.width,
height = _ref.height;
var left = _ref2.left,
top = _ref2.top;
var ceiledLeft = Math.ceil(left);
var ceiledTop = Math.ceil(top);
return {
width: width,
height: height,
left: ceiledLeft,
top: ceiledTop,
right: ceiledLeft + width,
bottom: ceiledTop + height
};
};
/**
* Function to flip a position upside down.
* @param {Position} position
* @return {Position} flipped position
*/
var flipHorizontal = function flipHorizontal(position) {
switch (position) {
case Position.TOP_LEFT:
return Position.BOTTOM_LEFT;
case Position.TOP:
default:
return Position.BOTTOM;
case Position.TOP_RIGHT:
return Position.BOTTOM_RIGHT;
case Position.BOTTOM_LEFT:
return Position.TOP_LEFT;
case Position.BOTTOM:
return Position.TOP;
case Position.BOTTOM_RIGHT:
return Position.TOP_RIGHT;
}
};
/**
* Function that returns if position is aligned on top.
* @param {Position} position
* @return {Boolean}
*/
var isAlignedOnTop = function isAlignedOnTop(position) {
switch (position) {
case Position.TOP_LEFT:
case Position.TOP:
case Position.TOP_RIGHT:
return true;
default:
return false;
}
};
/**
* Function that returns if position is aligned left or right.
* @param {Position} position
* @return {Boolean}
*/
var isAlignedHorizontal = function isAlignedHorizontal(position) {
switch (position) {
case Position.LEFT:
case Position.RIGHT:
return true;
default:
return false;
}
};
/**
* Function that returns if a rect fits on bottom.
* @param {Rect} rect
* @param {Object} viewport
* @param {Number} viewportOffset
* @return {Boolean}
*/
var getFitsOnBottom = function getFitsOnBottom(rect, viewport, viewportOffset) {
return rect.bottom < viewport.height - viewportOffset;
};
/**
* Function that returns if a rect fits on top.
* @param {Rect} rect
* @param {Number} viewportOffset
* @return {Boolean}
*/
var getFitsOnTop = function getFitsOnTop(rect, viewportOffset) {
return rect.top > viewportOffset;
};
/**
* Function that returns if a rect fits on right.
* @param {Rect} rect
* @param {Object} viewport
* @param {Number} viewportOffset
* @return {Boolean}
*/
var getFitsOnRight = function getFitsOnRight(rect, viewport, viewportOffset) {
return rect.right < viewport.width - viewportOffset;
};
/**
* Function that returns if a rect fits on left.
* @param {Rect} rect
* @param {Number} viewportOffset
* @return {Boolean}
*/
var getFitsOnLeft = function getFitsOnLeft(rect, viewportOffset) {
return rect.left > viewportOffset;
};
/**
* https://developer.mozilla.org/en-US/docs/Web/CSS/transform-origin
* Function that returns the CSS `tranform-origin` property.
* @param {Rect} rect
* @param {Position} position
* @param {Object} dimensions — the dimensions of the positioner.
* @param {Number} targetCenter - center of the target.
* @return {String} transform origin
*/
var getTransformOrigin = function getTransformOrigin(_ref3) {
var rect = _ref3.rect,
position = _ref3.position,
dimensions = _ref3.dimensions,
targetCenter = _ref3.targetCenter;
var centerY = Math.round(targetCenter - rect.top);
if (position === Position.LEFT) {
/* Syntax: x-offset | y-offset */
return "".concat(dimensions.width, "px ").concat(centerY, "px");
}
if (position === Position.RIGHT) {
/* Syntax: x-offset | y-offset */
return "0px ".concat(centerY, "px");
}
var centerX = Math.round(targetCenter - rect.left);
if (isAlignedOnTop(position)) {
/* Syntax: x-offset | y-offset */
return "".concat(centerX, "px ").concat(dimensions.height, "px ");
}
/* Syntax: x-offset | y-offset */
return "".concat(centerX, "px 0px ");
};
/**
* Function that takes in numbers and position and gives the final coords.
* @param {Position} position — the position the positioner should be on.
* @param {Object} dimensions — the dimensions of the positioner.
* @param {Object} targetRect — the rect of the target.
* @param {Number} targetOffset - offset from the target.
* @param {Object} viewport - the width and height of the viewport.
* @param {Object} viewportOffset - offset from the viewport.
* @return {Object} - { x: Number, y: Number }
*/
function getFittedPosition(_ref4) {
var position = _ref4.position,
dimensions = _ref4.dimensions,
targetRect = _ref4.targetRect,
targetOffset = _ref4.targetOffset,
viewport = _ref4.viewport,
_ref4$viewportOffset = _ref4.viewportOffset,
viewportOffset = _ref4$viewportOffset === void 0 ? 8 : _ref4$viewportOffset;
var _getPosition = getPosition({
position: position,
dimensions: dimensions,
targetRect: targetRect,
targetOffset: targetOffset,
viewport: viewport,
viewportOffset: viewportOffset
}),
rect = _getPosition.rect,
finalPosition = _getPosition.position; // Push rect to the right if overflowing on the left side of the viewport.
if (rect.left < viewportOffset) {
rect.right += Math.ceil(Math.abs(rect.left - viewportOffset));
rect.left = Math.ceil(viewportOffset);
} // Push rect to the left if overflowing on the right side of the viewport.
if (rect.right > viewport.width - viewportOffset) {
var delta = Math.ceil(rect.right - (viewport.width - viewportOffset));
rect.left -= delta;
rect.right -= delta;
} // Push rect down if overflowing on the top side of the viewport.
if (rect.top < viewportOffset) {
rect.top += Math.ceil(Math.abs(rect.top - viewportOffset));
rect.bottom = Math.ceil(viewportOffset);
} // Push rect up if overflowing on the bottom side of the viewport.
if (rect.bottom > viewport.height - viewportOffset) {
var _delta = Math.ceil(rect.bottom - (viewport.height - viewportOffset));
rect.top -= _delta;
rect.right -= _delta;
}
var targetCenter = isAlignedHorizontal(position) ? targetRect.top + targetRect.height / 2 : targetRect.left + targetRect.width / 2;
var transformOrigin = getTransformOrigin({
rect: rect,
position: finalPosition,
dimensions: dimensions,
targetCenter: targetCenter
});
return {
rect: rect,
position: finalPosition,
transformOrigin: transformOrigin
};
}
/**
* Function that takes in numbers and position and gives the final coords.
* @param {Position} position — the position the positioner should be on.
* @param {Object} dimensions — the dimensions of the positioner.
* @param {Object} targetRect — the rect of the target.
* @param {Number} targetOffset - offset from the target.
* @param {Object} viewport - the width and height of the viewport.
* @param {Object} viewportOffset - offset from the viewport.
* @return {Object} - { rect: Rect, position: Position }
*/
function getPosition(_ref5) {
var position = _ref5.position,
dimensions = _ref5.dimensions,
targetRect = _ref5.targetRect,
targetOffset = _ref5.targetOffset,
viewport = _ref5.viewport,
_ref5$viewportOffset = _ref5.viewportOffset,
viewportOffset = _ref5$viewportOffset === void 0 ? 8 : _ref5$viewportOffset;
var isHorizontal = isAlignedHorizontal(position); // Handle left and right positions
if (isHorizontal) {
var leftRect = getRect({
position: Position.LEFT,
dimensions: dimensions,
targetRect: targetRect,
targetOffset: targetOffset
});
var rightRect = getRect({
position: Position.RIGHT,
dimensions: dimensions,
targetRect: targetRect,
targetOffset: targetOffset
});
var fitsOnLeft = getFitsOnLeft(leftRect, viewportOffset);
var fitsOnRight = getFitsOnRight(rightRect, viewport, viewportOffset);
if (position === Position.LEFT) {
if (fitsOnLeft) {
return {
position: position,
rect: leftRect
};
}
if (fitsOnRight) {
return {
position: Position.RIGHT,
rect: rightRect
};
}
}
if (position === Position.RIGHT) {
if (fitsOnRight) {
return {
position: position,
rect: rightRect
};
}
if (fitsOnLeft) {
return {
position: Position.LEFT,
rect: leftRect
};
}
} // Default to using the position with the most space
var spaceRight = Math.abs(viewport.width - viewportOffset - rightRect.right);
var spaceLeft = Math.abs(leftRect.left - viewportOffset);
if (spaceRight < spaceLeft) {
return {
position: Position.RIGHT,
rect: rightRect
};
}
return {
position: Position.LEFT,
rect: leftRect
};
}
var positionIsAlignedOnTop = isAlignedOnTop(position);
var topRect;
var bottomRect;
if (positionIsAlignedOnTop) {
topRect = getRect({
position: position,
dimensions: dimensions,
targetRect: targetRect,
targetOffset: targetOffset
});
bottomRect = getRect({
position: flipHorizontal(position),
dimensions: dimensions,
targetRect: targetRect,
targetOffset: targetOffset
});
} else {
topRect = getRect({
position: flipHorizontal(position),
dimensions: dimensions,
targetRect: targetRect,
targetOffset: targetOffset
});
bottomRect = getRect({
position: position,
dimensions: dimensions,
targetRect: targetRect,
targetOffset: targetOffset
});
}
var topRectFitsOnTop = getFitsOnTop(topRect, viewportOffset);
var bottomRectFitsOnBottom = getFitsOnBottom(bottomRect, viewport, viewportOffset);
if (positionIsAlignedOnTop) {
if (topRectFitsOnTop) {
return {
position: position,
rect: topRect
};
}
if (bottomRectFitsOnBottom) {
return {
position: flipHorizontal(position),
rect: bottomRect
};
}
}
if (!positionIsAlignedOnTop) {
if (bottomRectFitsOnBottom) {
return {
position: position,
rect: bottomRect
};
}
if (topRectFitsOnTop) {
return {
position: flipHorizontal(position),
rect: topRect
};
}
} // Default to most spacious if there is no fit.
var spaceBottom = Math.abs(viewport.height - viewportOffset - bottomRect.bottom);
var spaceTop = Math.abs(topRect.top - viewportOffset);
if (spaceBottom < spaceTop) {
return {
position: positionIsAlignedOnTop ? flipHorizontal(position) : position,
rect: bottomRect
};
}
return {
position: positionIsAlignedOnTop ? position : flipHorizontal(position),
rect: topRect
};
}
/**
* Function that takes in numbers and position and gives the final coords.
* @param {Object} position - the width and height of the viewport.
* @param {Number} targetOffset - offset from the target.
* @param {Object} dimensions — the dimensions of the positioner.
* @param {Object} targetRect — the rect of the target.
* @return {Object} - { x: Number, y: Number }
*/
function getRect(_ref6) {
var position = _ref6.position,
targetOffset = _ref6.targetOffset,
dimensions = _ref6.dimensions,
targetRect = _ref6.targetRect;
var leftRect = targetRect.left + targetRect.width / 2 - dimensions.width / 2;
var alignedTopY = targetRect.top - dimensions.height - targetOffset;
var alignedBottomY = targetRect.bottom + targetOffset;
var alignedRightX = targetRect.right - dimensions.width;
var alignedLeftRightY = targetRect.top + targetRect.height / 2 - dimensions.height / 2;
switch (position) {
case Position.LEFT:
return makeRect(dimensions, {
left: targetRect.left - dimensions.width - targetOffset,
top: alignedLeftRightY
});
case Position.RIGHT:
return makeRect(dimensions, {
left: targetRect.right + targetOffset,
top: alignedLeftRightY
});
case Position.TOP:
return makeRect(dimensions, {
left: leftRect,
top: alignedTopY
});
case Position.TOP_LEFT:
return makeRect(dimensions, {
left: targetRect.left,
top: alignedTopY
});
case Position.TOP_RIGHT:
return makeRect(dimensions, {
left: alignedRightX,
top: alignedTopY
});
default:
case Position.BOTTOM:
return makeRect(dimensions, {
left: leftRect,
top: alignedBottomY
});
case Position.BOTTOM_LEFT:
return makeRect(dimensions, {
left: targetRect.left,
top: alignedBottomY
});
case Position.BOTTOM_RIGHT:
return makeRect(dimensions, {
left: alignedRightX,
top: alignedBottomY
});
}
}
var defaultProps = {
bodyOffset: 6,
position: Position.BOTTOM,
targetOffset: 6
};
var defaultStyle = {
position: "fixed"
};
var getStyle = function getStyle(targetRef, positionedRef, _ref) {
var position = _ref.position,
targetOffset = _ref.targetOffset,
bodyOffset = _ref.bodyOffset;
if (!targetRef.current || !positionedRef.current) {
return defaultStyle;
}
var targetRect = targetRef.current.getBoundingClientRect();
var positionedRect = positionedRef.current.getBoundingClientRect();
var _getPosition = getFittedPosition({
position: position,
targetOffset: targetOffset,
viewportOffset: bodyOffset,
targetRect: targetRect,
dimensions: positionedRect,
viewport: {
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight
}
}),
_getPosition$rect = _getPosition.rect,
top = _getPosition$rect.top,
left = _getPosition$rect.left,
transformOrigin = _getPosition.transformOrigin;
return _objectSpread$1({}, defaultStyle, {
left: Math.round(left),
top: Math.round(top),
transformOrigin: transformOrigin
});
};
function usePositionedStyle() {
var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultProps,
position = _ref2.position,
targetOffset = _ref2.targetOffset,
bodyOffset = _ref2.bodyOffset;
var dependencies = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var latestAnimationFrame = React__default.useRef(null);
var targetRef = React__default.useRef(null);
var positionedRef = React__default.useRef(null);
var _React$useState = React__default.useState(defaultStyle),
_React$useState2 = _slicedToArray$1(_React$useState, 2),
style = _React$useState2[0],
setStyle = _React$useState2[1];
var update = function update() {
if (!targetRef.current || !positionedRef.current) {
setStyle(defaultStyle);
}
var nextStyle = getStyle(targetRef, positionedRef, {
position: position,
targetOffset: targetOffset,
bodyOffset: bodyOffset
});
setStyle(nextStyle);
latestAnimationFrame.current = requestAnimationFrame(function () {
update();
});
};
React__default.useLayoutEffect(function () {
update();
return function () {
if (latestAnimationFrame.current) {
cancelAnimationFrame(latestAnimationFrame.current);
}
};
}, [position, targetOffset, bodyOffset].concat(_toConsumableArray(dependencies)));
return {
style: style,
targetRef: targetRef,
positionedRef: positionedRef
};
}
function Positioner(props) {
var _usePositionedStyle = usePositionedStyle({
position: props.position,
targetOffset: props.targetOffset,
bodyOffset: props.bodyOffset
}, [props.isShown]),
style = _usePositionedStyle.style,
targetRef = _usePositionedStyle.targetRef,
positionedRef = _usePositionedStyle.positionedRef;
return React__default.createElement(React__default.Fragment, null, React__default.cloneElement(props.children, {
ref: targetRef
}), props.isShown ? React__default.cloneElement(props.content, {
style: style,
ref: positionedRef
}) : null);
}
Positioner.defaultProps = defaultProps;
var invertPosition = function invertPosition(position) {
var inverted = {
top: "bottom",
bottom: "top",
left: "right",
right: "left"
};
return inverted[position];
};
function useTimer(fn, delay, dependencies) {
var timer = React.useRef(null);
var start = React.useCallback(function () {
clearTimeout(timer.current);
timer.current = setTimeout(fn, delay);
}, []);
var cancel = React.useCallback(function () {
clearTimeout(timer.current);
}, []);
React.useEffect(function () {
return function () {
clearTimeout(timer.current);
};
}, dependencies);
return [start, cancel];
}
function useTooltipTimer(_ref) {
var showDelay = _ref.showDelay,
hideDelay = _ref.hideDelay;
var _React$useState = React.useState(false),
_React$useState2 = slicedToArray(_React$useState, 2),
visible = _React$useState2[0],
setVisible = _React$useState2[1];
var _useTimer = useTimer(function () {
return setVisible(true);
}, showDelay, [visible]),
_useTimer2 = slicedToArray(_useTimer, 2),
startShowTimer = _useTimer2[0],
cancelShowTimer = _useTimer2[1];
var _useTimer3 = useTimer(function () {
return setVisible(false);
}, hideDelay, [visible]),
_useTimer4 = slicedToArray(_useTimer3, 2),
startHideTimer = _useTimer4[0],
cancelHideTimer = _useTimer4[1];
var handleMouseEnter = React.useCallback(function () {
cancelHideTimer();
startShowTimer();
}, []);
var handleMouseLeave = React.useCallback(function () {
startHideTimer();
cancelShowTimer();
}, []);
return {
visible: visible,
handleMouseEnter: handleMouseEnter,
handleMouseLeave: handleMouseLeave
};
}
function Tooltip(_ref2) {
var _ref2$targetOffset = _ref2.targetOffset,
targetOffset = _ref2$targetOffset === void 0 ? 8 : _ref2$targetOffset,
_ref2$bodyOffset = _ref2.bodyOffset,
bodyOffset = _ref2$bodyOffset === void 0 ? 6 : _ref2$bodyOffset,
children = _ref2.children,
content = _ref2.content,
position = _ref2.position,
_ref2$showDelay = _ref2.showDelay,
showDelay = _ref2$showDelay === void 0 ? 350 : _ref2$showDelay,
_ref2$hideDelay = _ref2.hideDelay,
hideDelay = _ref2$hideDelay === void 0 ? 350 : _ref2$hideDelay;
var _useTooltipTimer = useTooltipTimer({
showDelay: showDelay,
hideDelay: hideDelay
}),
visible = _useTooltipTimer.visible,
handleMouseEnter = _useTooltipTimer.handleMouseEnter,
handleMouseLeave = _useTooltipTimer.handleMouseLeave;
if (!children) return null;
return React.createElement(Positioner, {
targetOffset: targetOffset,
bodyOffset: bodyOffset,
content: React.createElement(Bubble, {
position: invertPosition(position),
variant: "dark",
onMouseEnter: handleMouseEnter,
onMouseLeave: handleMouseLeave
}, content),
isShown: visible,
position: position
}, React.cloneElement(wrapTextNode(children), {
onMouseEnter: handleMouseEnter,
onMouseLeave: handleMouseLeave
}));
}
Tooltip.defaultProps = {
position: "bottom"
};
var wrapText = function wrapText(str, maxlen) {
if (!maxlen || str.length <= maxlen) return React__default.createElement(React__default.Fragment, null, str);
var i = maxlen - 1;
while (i !== 0) {
if (str[i] === " ") break;
i = i - 1;
}
if (i === 0) {
return React__default.createElement(React__default.Fragment, null, str);
}
return React__default.createElement(React__default.Fragment, null, str.slice(0, i), React__default.createElement("br", null), str.slice(i + 1));
};
function FormLabel(props) {
// Required indicator is rendered only in edit mode
var _useContext = React.useContext(FormContext),
readOnly = _useContext.readOnly;
var groupId = React.useContext(FormGroup.Context);
return React__default.createElement("label", {
htmlFor: groupId,
className: classnames("form__label", props.className)
}, React__default.createElement("span", {
className: "form__label__text"
}, wrapText(props.children, props.wrapLength)), props.required && !readOnly ? React__default.createElement("span", {
className: "form__label__required-indicator"
}, "*") : null, props.info ? React__default.createElement(Tooltip, {
content: props.info
}, React__default.createElement("i", {
className: "form__label__info"
})) : null);
}
FormLabel.displayName = "Form.Label";
FormLabel.defaultProps = {
required: false,
wrapLength: 25
};
function FormField(_ref) {
var render = _ref.render,
component = _ref.component,
className = _ref.className,
children = _ref.children,
props = objectWithoutProperties(_ref, ["render", "component", "className", "children"]);
var groupId = React.useContext(FormGroup.Context);
var _useContext = React.useContext(FormContext),
layout = _useContext.layout;
var layoutClassName = layout ? "form__field--".concat(layout) : null;
if (render) {
return render({
className: classnames("form__field", layoutClassName, className),
id: groupId,
children: children
});
}
return React__default.createElement(component, objectSpread({
className: classnames("form__field", layoutClassName, className),
id: groupId,
children: children
}, props));
}
FormField.displayName = "Form.Field";
var Icon = React.memo(function (_ref) {
var onIconClick = _ref.onIconClick,
icon = _ref.icon,
tabIndex = _ref.tabIndex;
var handleKeyUp = React.useCallback(function (e) {
if (e && (e.keyCode === 13 || e.keyCode === 32) && onIconClick) {
onIconClick();
}
}, [onIconClick]);
return typeof icon === "function" ? icon() : React.createElement("i", {
className: icon + " icon",
onClick: onIconClick,
tabIndex: tabIndex,
role: "button",
onKeyUp: handleKeyUp
});
});
var Textarea = function Textarea(props) {
return React.createElement("textarea", props);
};
function Input(_ref2) {
var icon = _ref2.icon,
type = _ref2.type,
iconPosition = _ref2.iconPosition,
onIconClick = _ref2.onIconClick,
textarea = _ref2.textarea,
className = _ref2.className,
rest = objectWithoutProperties(_ref2, ["icon", "type", "iconPosition", "onIconClick", "textarea", "className"]);
return React.createElement("div", {
className: classnames("input", icon ? "icon" : "", icon && iconPosition === "left" ? "left" : "", className)
}, textarea ? React.createElement(Textarea, rest) : React.createElement(React.Fragment, null, React.createElement("input", _extends_1({
type: type
}, rest)), icon ? React.createElement(Icon, _extends_1({
icon: icon,
onIconClick: onIconClick
}, rest)) : null));
}
Input.defaultProps = {
type: "text",
disabled: false,
tabIndex: "0"
};
/* dist/pretty-checkbox-react.es.js:1.0.6 */
function _defineProperty$2(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _extends$1() {
_extends$1 = 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$1.apply(this, arguments);
}
function _objectSpread$2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === 'function') {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function (key) {
_defineProperty$2(target, key, source[key]);
});
}
return target;
}
function _objectWithoutPropertiesLoose$1(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties$1(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose$1(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}function createCommonjsModule$1(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}var classnames$2 = createCommonjsModule$1(function (module) {
/*!
Copyright (c) 2017 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
var hasOwn = {}.hasOwnProperty;
function classNames() {
var classes = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!arg) continue;
var argType = typeof arg;
if (argType === 'string' || argType === 'number') {
classes.push(arg);
} else if (Array.isArray(arg) && arg.length) {
var inner = classNames.apply(null, arg);
if (inner) {
classes.push(inner);
}
} else if (argType === 'object') {
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes.push(key);
}
}
}
}
return classes.join(' ');
}
if (module.exports) {
classNames.default = classNames;
module.exports = classNames;
} else {
window.classNames = classNames;
}
})();
});/**
* The base prefix for all pretty-checkbox class names.
*/
var PREFIX = 'p-';
/**
* Automatically append the className for icon component. This will automatically add
* `icon` to icon prop components, `svg` to prop svg components, and `image` to
* image prop components.
* @param {React.Element<*>} component The component to add the className to.
* @param {string} className The className to fill on the element.
*/
var fillClassNameForIcons = function fillClassNameForIcons(component, className) {
if (!component) {
return null;
}
return React.cloneElement(component, _objectSpread$2({}, component.props, {
className: classnames$2(className, component.props.className)
}));
};
/**
* Handles custom or default rendering of the pretty-checkbox `div.state` class.
*/
var PrettyInputState = function PrettyInputState(props) {
var node = null;
var children = props.children,
render = props.render,
id = props.id,
color = props.color; // yuck, needed for type refinement :(
if (props.svg) {
node = {
className: 'svg',
node: props.svg
};
} else if (props.icon) {
node = {
className: 'icon',
node: props.icon
};
} else if (props.image) {
node = {
className: 'image',
node: props.image
};
}
if (typeof children === 'function') {
return children(node);
}
if (typeof render === 'function') {
return render(node);
}
return React.createElement("div", {
className: classnames$2('state', color ? PREFIX + color : null),
"data-testid": "pcr-state"
}, node ? fillClassNameForIcons(node.node, node.className) : null, React.createElement("label", {
htmlFor: id
}, children));
};
function Input$1(props) {
var className = props.className,
value = props.value,
onChange = props.onChange,
id = props.id,
type = props.type,
inputProps = props.inputProps,
animation = props.animation,
checked = props.checked,
disabled = props.disabled,
locked = props.locked,
bigger = props.bigger,
shape = props.shape,
style = props.style,
plain = props.plain;
if (props.icon && props.svg || props.icon && props.image || props.svg && props.image) {
throw new Error('icon, svg, and image are mutually exclusive props; choose one');
}
return React.createElement("div", {
"data-testid": "pcr-wrapper",
className: classnames$2(props.prettySelector, animation ? PREFIX + animation : null, className, shape ? PREFIX + shape : null, style ? PREFIX + style : null, locked ? "".concat(PREFIX, "locked") : null, bigger ? "".concat(PREFIX, "bigger") : null, plain ? "".concat(PREFIX, "plain") : null)
}, React.createElement("input", _extends$1({
id: id || null,
type: type,
value: value,
onChange: onChange,
checked: checked,
disabled: disabled,
"data-testid": "pcr-input"
}, inputProps)), // $ExpectError
React.createElement(PrettyInputState, props));
}
Input$1.defaultProps = {
prettySelector: 'pretty'
};var getBaseClassName = function getBaseClassName(_ref, PREFIX) {
var icon = _ref.icon,
image = _ref.image,
svg = _ref.svg;
var base = "".concat(PREFIX, "default");
if (icon) {
base = "".concat(PREFIX, "icon");
} else if (svg) {
base = "".concat(PREFIX, "svg");
} else if (image) {
base = "".concat(PREFIX, "image");
}
return base;
};function Checkbox(props) {
var animation = props.animation,
className = props.className,
rest = _objectWithoutProperties$1(props, ["animation", "className"]);
if (animation && animation !== 'smooth' && animation !== 'pulse' && !props.icon && !props.image && !props.svg) {
throw new Error("animation '".concat(animation, "' is incompatible with default checkbox styles. You must specify an icon, image, or a svg."));
}
return React__default.createElement(Input$1, _extends$1({
type: "checkbox",
className: classnames$2( // $ExpectError
getBaseClassName(props, PREFIX), props.indeterminate ? 'p-has-indeterminate' : null, className),
animation: animation
}, rest));
}var _isObject = function (it) {
return typeof it === 'object' ? it !== null : typeof it === 'function';
};var _anObject = function (it) {
if (!_isObject(it)) throw TypeError(it + ' is not an object!');
return it;
};var _fails = function (exec) {
try {
return !!exec();
} catch (e) {
return true;
}
};// Thank's IE8 for his funny defineProperty
var _descriptors = !_fails(function () {
return Object.defineProperty({}, 'a', {
get: function () {
return 7;
}
}).a != 7;
});var _global = createCommonjsModule$1(function (module) {
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self // eslint-disable-next-line no-new-func
: Function('return this')();
if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef
});var document$1 = _global.document; // typeof document.createElement is 'object' in old IE
var is = _isObject(document$1) && _isObject(document$1.createElement);
var _domCreate = function (it) {
return is ? document$1.createElement(it) : {};
};var _ie8DomDefine = !_descriptors && !_fails(function () {
return Object.defineProperty(_domCreate('div'), 'a', {
get: function () {
return 7;
}
}).a != 7;
});// 7.1.1 ToPrimitive(input [, PreferredType])
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
var _toPrimitive = function (it, S) {
if (!_isObject(it)) return it;
var fn, val;
if (S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it))) return val;
if (typeof (fn = it.valueOf) == 'function' && !_isObject(val = fn.call(it))) return val;
if (!S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it))) return val;
throw TypeError("Can't convert object to primitive value");
};var dP = Object.defineProperty;
var f = _descriptors ? Object.defineProperty : function defineProperty(O, P, Attributes) {
_anObject(O);
P = _toPrimitive(P, true);
_anObject(Attributes);
if (_ie8DomDefine) try {
return dP(O, P, Attributes);
} catch (e) {
/* empty */
}
if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!');
if ('value' in Attributes) O[P] = Attributes.value;
return O;
};
var _objectDp = {
f: f
};var dP$1 = _objectDp.f;
var FProto = Function.prototype;
var nameRE = /^\s*function ([^ (]*)/;
var NAME = 'name'; // 19.2.4.2 name
NAME in FProto || _descriptors && dP$1(FProto, NAME, {
configurable: true,
get: function () {
try {
return ('' + this).match(nameRE)[1];
} catch (e) {
return '';
}
}
});function Radio(props) {
var className = props.className,
name = props.name,
inputProps = props.inputProps,
rest = _objectWithoutProperties$1(props, ["className", "name", "inputProps"]);
return React__default.createElement(Input$1, _extends$1({
type: "radio",
className: classnames$2( // $ExpectError
getBaseClassName(props, PREFIX), className),
inputProps: _objectSpread$2({}, inputProps, {
name: name
})
}, rest));
}
Radio.defaultProps = {
shape: 'round'
};
Checkbox$1.defaultProps = {
style: "fill",
icon: React__default.createElement("i", {
className: "aicon aicon__check"
})
};
function Checkbox$1(props) {
// $FlowFixMe
var style = props.style,
icon = props.icon,
rest = objectWithoutProperties(props, ["style", "icon"]);
return React__default.createElement(Checkbox, _extends_1({
style: props.indeterminate ? "default" : style,
icon: props.indeterminate ? null : icon
}, rest));
}
function Radio$1(props) {
return React__default.createElement(Radio, props);
}
function _arrayWithoutHoles$1(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
arr2[i] = arr[i];
}
return arr2;
}
}
var arrayWithoutHoles = _arrayWithoutHoles$1;
function _iterableToArray$1(iter) {
if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}
var iterableToArray = _iterableToArray$1;
function _nonIterableSpread$1() {
throw new TypeError("Invalid attempt to spread non-iterable instance");
}
var nonIterableSpread = _nonIterableSpread$1;
function _toConsumableArray$1(arr) {
return arrayWithoutHoles(arr) || iterableToArray(arr) || nonIterableSpread();
}
var toConsumableArray = _toConsumableArray$1;
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
var inheritsLoose = _inheritsLoose;
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols$1 = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols$1) {
symbols = getOwnPropertySymbols$1(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
var ReactPropTypesSecret_1 = ReactPropTypesSecret;
var has$1 = Function.call.bind(Object.prototype.hasOwnProperty);
function emptyFunction() {}
function emptyFunctionWithReset() {}
emptyFunctionWithReset.resetWarningCache = emptyFunction;
var factoryWithThrowingShims = function() {
function shim(props, propName, componentName, location, propFullName, secret) {
if (secret === ReactPropTypesSecret_1) {
// It is still safe when called from React.
return;
}
var err = new Error(
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use PropTypes.checkPropTypes() to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
err.name = 'Invariant Violation';
throw err;
} shim.isRequired = shim;
function getShim() {
return shim;
} // Important!
// Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
var ReactPropTypes = {
array: shim,
bool: shim,
func: shim,
number: shim,
object: shim,
string: shim,
symbol: shim,
any: shim,
arrayOf: getShim,
element: shim,
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;
};
var propTypes = createCommonjsModule(function (module) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
{
// By explicitly using `prop-types` you are opting into new production behavior.
// http://fb.me/prop-types-in-prod
module.exports = factoryWithThrowingShims();
}
});
function isElement(el) {
return el != null && typeof el === 'object' && el.nodeType === 1;
}
function canOverflow(overflow, skipOverflowHiddenElements) {
if (skipOverflowHiddenElements && overflow === 'hidden') {
return false;
}
return overflow !== 'visible' && overflow !== 'clip';
}
function isScrollable(el, skipOverflowHiddenElements) {
if (el.clientHeight < el.scrollHeight || el.clientWidth < el.scrollWidth) {
var style = getComputedStyle(el, null);
return canOverflow(style.overflowY, skipOverflowHiddenElements) || canOverflow(style.overflowX, skipOverflowHiddenElements);
}
return false;
}
function alignNearest(scrollingEdgeStart, scrollingEdgeEnd, scrollingSize, scrollingBorderStart, scrollingBorderEnd, elementEdgeStart, elementEdgeEnd, elementSize) {
if (elementEdgeStart < scrollingEdgeStart && elementEdgeEnd > scrollingEdgeEnd || elementEdgeStart > scrollingEdgeStart && elementEdgeEnd < scrollingEdgeEnd) {
return 0;
}
if (elementEdgeStart <= scrollingEdgeStart && elementSize <= scrollingSize || elementEdgeEnd >= scrollingEdgeEnd && elementSize >= scrollingSize) {
return elementEdgeStart - scrollingEdgeStart - scrollingBorderStart;
}
if (elementEdgeEnd > scrollingEdgeEnd && elementSize < scrollingSize || elementEdgeStart < scrollingEdgeStart && elementSize > scrollingSize) {
return elementEdgeEnd - scrollingEdgeEnd + scrollingBorderEnd;
}
return 0;
}
var require$$5 = (function (target, options) {
var scrollMode = options.scrollMode,
block = options.block,
inline = options.inline,
boundary = options.boundary,
skipOverflowHiddenElements = options.skipOverflowHiddenElements;
var checkBoundary = typeof boundary === 'function' ? boundary : function (node) {
return node !== boundary;
};
if (!isElement(target)) {
throw new TypeError('Invalid target');
}
var scrollingElement = document.scrollingElement || document.documentElement;
var frames = [];
var cursor = target;
while (isElement(cursor) && checkBoundary(cursor)) {
cursor = cursor.parentNode;
if (cursor === scrollingElement) {
frames.push(cursor);
break;
}
if (cursor === document.body && isScrollable(cursor) && !isScrollable(document.documentElement)) {
continue;
}
if (isScrollable(cursor, skipOverflowHiddenElements)) {
frames.push(cursor);
}
}
var viewportWidth = window.visualViewport ? visualViewport.width : innerWidth;
var viewportHeight = window.visualViewport ? visualViewport.height : innerHeight;
var viewportX = window.scrollX || pageXOffset;
var viewportY = window.scrollY || pageYOffset;
var _target$getBoundingCl = target.getBoundingClientRect(),
targetHeight = _target$getBoundingCl.height,
targetWidth = _target$getBoundingCl.width,
targetTop = _target$getBoundingCl.top,
targetRight = _target$getBoundingCl.right,
targetBottom = _target$getBoundingCl.bottom,
targetLeft = _target$getBoundingCl.left;
var targetBlock = block === 'start' || block === 'nearest' ? targetTop : block === 'end' ? targetBottom : targetTop + targetHeight / 2;
var targetInline = inline === 'center' ? targetLeft + targetWidth / 2 : inline === 'end' ? targetRight : targetLeft;
var computations = [];
for (var index = 0; index < frames.length; index++) {
var frame = frames[index];
var _frame$getBoundingCli = frame.getBoundingClientRect(),
_height = _frame$getBoundingCli.height,
_width = _frame$getBoundingCli.width,
_top = _frame$getBoundingCli.top,
right = _frame$getBoundingCli.right,
bottom = _frame$getBoundingCli.bottom,
_left = _frame$getBoundingCli.left;
if (scrollMode === 'if-needed' && targetTop >= 0 && targetLeft >= 0 && targetBottom <= viewportHeight && targetRight <= viewportWidth && targetTop >= _top && targetBottom <= bottom && targetLeft >= _left && targetRight <= right) {
return computations;
}
var frameStyle = getComputedStyle(frame);
var borderLeft = parseInt(frameStyle.borderLeftWidth, 10);
var borderTop = parseInt(frameStyle.borderTopWidth, 10);
var borderRight = parseInt(frameStyle.borderRightWidth, 10);
var borderBottom = parseInt(frameStyle.borderBottomWidth, 10);
var blockScroll = 0;
var inlineScroll = 0;
var scrollbarWidth = 'offsetWidth' in frame ? frame.offsetWidth - frame.clientWidth - borderLeft - borderRight : 0;
var scrollbarHeight = 'offsetHeight' in frame ? frame.offsetHeight - frame.clientHeight - borderTop - borderBottom : 0;
if (scrollingElement === frame) {
if (block === 'start') {
blockScroll = targetBlock;
} else if (block === 'end') {
blockScroll = targetBlock - viewportHeight;
} else if (block === 'nearest') {
blockScroll = alignNearest(viewportY, viewportY + viewportHeight, viewportHeight, borderTop, borderBottom, viewportY + targetBlock, viewportY + targetBlock + targetHeight, targetHeight);
} else {
blockScroll = targetBlock - viewportHeight / 2;
}
if (inline === 'start') {
inlineScroll = targetInline;
} else if (inline === 'center') {
inlineScroll = targetInline - viewportWidth / 2;
} else if (inline === 'end') {
inlineScroll = targetInline - viewportWidth;
} else {
inlineScroll = alignNearest(viewportX, viewportX + viewportWidth, viewportWidth, borderLeft, borderRight, viewportX + targetInline, viewportX + targetInline + targetWidth, targetWidth);
}
blockScroll = Math.max(0, blockScroll + viewportY);
inlineScroll = Math.max(0, inlineScroll + viewportX);
} else {
if (block === 'start') {
blockScroll = targetBlock - _top - borderTop;
} else if (block === 'end') {
blockScroll = targetBlock - bottom + borderBottom + scrollbarHeight;
} else if (block === 'nearest') {
blockScroll = alignNearest(_top, bottom, _height, borderTop, borderBottom + scrollbarHeight, targetBlock, targetBlock + targetHeight, targetHeight);
} else {
blockScroll = targetBlock - (_top + _height / 2) + scrollbarHeight / 2;
}
if (inline === 'start') {
inlineScroll = targetInline - _left - borderLeft;
} else if (inline === 'center') {
inlineScroll = targetInline - (_left + _width / 2) + scrollbarWidth / 2;
} else if (inline === 'end') {
inlineScroll = targetInline - right + borderRight + scrollbarWidth;
} else {
inlineScroll = alignNearest(_left, right, _width, borderLeft, borderRight + scrollbarWidth, targetInline, targetInline + targetWidth, targetWidth);
}
var scrollLeft = frame.scrollLeft,
scrollTop = frame.scrollTop;
blockScroll = Math.max(0, Math.min(scrollTop + blockScroll, frame.scrollHeight - _height + scrollbarHeight));
inlineScroll = Math.max(0, Math.min(scrollLeft + inlineScroll, frame.scrollWidth - _width + scrollbarWidth));
targetBlock += scrollTop - blockScroll;
targetInline += scrollLeft - inlineScroll;
}
computations.push({
el: frame,
top: blockScroll,
left: inlineScroll
});
}
return computations;
});
var downshift_cjs = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var _objectWithoutPropertiesLoose = _interopDefault(objectWithoutPropertiesLoose);
var _extends = _interopDefault(_extends_1);
var _assertThisInitialized = _interopDefault(assertThisInitialized);
var _inheritsLoose = _interopDefault(inheritsLoose);
var PropTypes = _interopDefault(propTypes);
var React__default$$1 = _interopDefault(React__default);
var computeScrollIntoView = _interopDefault(require$$5);
// istanbul ignore next
var statusDiv = typeof document === 'undefined' ? null : document.getElementById('a11y-status-message');
var statuses = [];
/**
* @param {String} status the status message
*/
function setStatus(status) {
var isSameAsLast = statuses[statuses.length - 1] === status;
if (isSameAsLast) {
statuses = [].concat(statuses, [status]);
} else {
statuses = [status];
}
var div = getStatusDiv(); // Remove previous children
while (div.lastChild) {
div.removeChild(div.firstChild);
}
statuses.filter(Boolean).forEach(function (statusItem, index) {
div.appendChild(getStatusChildDiv(statusItem, index));
});
}
/**
* @param {String} status the status message
* @param {Number} index the index
* @return {HTMLElement} the child node
*/
function getStatusChildDiv(status, index) {
var display = index === statuses.length - 1 ? 'block' : 'none';
var childDiv = document.createElement('div');
childDiv.style.display = display;
childDiv.textContent = status;
return childDiv;
}
/**
* Get the status node or create it if it does not already exist
* @return {HTMLElement} the status node
*/
function getStatusDiv() {
if (statusDiv) {
return statusDiv;
}
statusDiv = document.createElement('div');
statusDiv.setAttribute('id', 'a11y-status-message');
statusDiv.setAttribute('role', 'status');
statusDiv.setAttribute('aria-live', 'polite');
statusDiv.setAttribute('aria-relevant', 'additions text');
Object.assign(statusDiv.style, {
border: '0',
clip: 'rect(0 0 0 0)',
height: '1px',
margin: '-1px',
overflow: 'hidden',
padding: '0',
position: 'absolute',
width: '1px'
});
document.body.appendChild(statusDiv);
return statusDiv;
}
var unknown = 0;
var mouseUp = 1;
var itemMouseEnter = 2;
var keyDownArrowUp = 3;
var keyDownArrowDown = 4;
var keyDownEscape = 5;
var keyDownEnter = 6;
var keyDownHome = 7;
var keyDownEnd = 8;
var clickItem = 9;
var blurInput = 10;
var changeInput = 11;
var keyDownSpaceButton = 12;
var clickButton = 13;
var blurButton = 14;
var controlledPropUpdatedSelectedItem = 15;
var touchEnd = 16;
var stateChangeTypes = /*#__PURE__*/Object.freeze({
unknown: unknown,
mouseUp: mouseUp,
itemMouseEnter: itemMouseEnter,
keyDownArrowUp: keyDownArrowUp,
keyDownArrowDown: keyDownArrowDown,
keyDownEscape: keyDownEscape,
keyDownEnter: keyDownEnter,
keyDownHome: keyDownHome,
keyDownEnd: keyDownEnd,
clickItem: clickItem,
blurInput: blurInput,
changeInput: changeInput,
keyDownSpaceButton: keyDownSpaceButton,
clickButton: clickButton,
blurButton: blurButton,
controlledPropUpdatedSelectedItem: controlledPropUpdatedSelectedItem,
touchEnd: touchEnd
});
var idCounter = 0;
/**
* Accepts a parameter and returns it if it's a function
* or a noop function if it's not. This allows us to
* accept a callback, but not worry about it if it's not
* passed.
* @param {Function} cb the callback
* @return {Function} a function
*/
function cbToCb(cb) {
return typeof cb === 'function' ? cb : noop;
}
function noop() {}
/**
* Scroll node into view if necessary
* @param {HTMLElement} node the element that should scroll into view
* @param {HTMLElement} menuNode the menu element of the component
*/
function scrollIntoView(node, menuNode) {
if (node === null) {
return;
}
var actions = computeScrollIntoView(node, {
boundary: menuNode,
block: 'nearest',
scrollMode: 'if-needed'
});
actions.forEach(function (_ref) {
var el = _ref.el,
top = _ref.top,
left = _ref.left;
el.scrollTop = top;
el.scrollLeft = left;
});
}
/**
* @param {HTMLElement} parent the parent node
* @param {HTMLElement} child the child node
* @return {Boolean} whether the parent is the child or the child is in the parent
*/
function isOrContainsNode(parent, child) {
return parent === child || parent.contains && parent.contains(child);
}
/**
* Simple debounce implementation. Will call the given
* function once after the time given has passed since
* it was last called.
* @param {Function} fn the function to call after the time
* @param {Number} time the time to wait
* @return {Function} the debounced function
*/
function debounce(fn, time) {
var timeoutId;
function cancel() {
if (timeoutId) {
clearTimeout(timeoutId);
}
}
function wrapper() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
cancel();
timeoutId = setTimeout(function () {
timeoutId = null;
fn.apply(void 0, args);
}, time);
}
wrapper.cancel = cancel;
return wrapper;
}
/**
* This is intended to be used to compose event handlers.
* They are executed in order until one of them sets
* `event.preventDownshiftDefault = true`.
* @param {...Function} fns the event handler functions
* @return {Function} the event handler to add to an element
*/
function callAllEventHandlers() {
for (var _len2 = arguments.length, fns = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
fns[_key2] = arguments[_key2];
}
return function (event) {
for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
args[_key3 - 1] = arguments[_key3];
}
return fns.some(function (fn) {
if (fn) {
fn.apply(void 0, [event].concat(args));
}
return event.preventDownshiftDefault || event.hasOwnProperty('nativeEvent') && event.nativeEvent.preventDownshiftDefault;
});
};
}
/**
* This return a function that will call all the given functions with
* the arguments with which it's called. It does a null-check before
* attempting to call the functions and can take any number of functions.
* @param {...Function} fns the functions to call
* @return {Function} the function that calls all the functions
*/
function callAll() {
for (var _len4 = arguments.length, fns = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
fns[_key4] = arguments[_key4];
}
return function () {
for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
args[_key5] = arguments[_key5];
}
fns.forEach(function (fn) {
if (fn) {
fn.apply(void 0, args);
}
});
};
}
/**
* This generates a unique ID for an instance of Downshift
* @return {String} the unique ID
*/
function generateId() {
return String(idCounter++);
}
/**
* Resets idCounter to 0. Used for SSR.
*/
function resetIdCounter() {
idCounter = 0;
}
/**
* @param {Object} param the downshift state and other relevant properties
* @return {String} the a11y status message
*/
function getA11yStatusMessage(_ref2) {
var isOpen = _ref2.isOpen,
selectedItem = _ref2.selectedItem,
resultCount = _ref2.resultCount,
previousResultCount = _ref2.previousResultCount,
itemToString = _ref2.itemToString;
if (!isOpen) {
return selectedItem ? itemToString(selectedItem) : '';
}
if (!resultCount) {
return 'No results are available.';
}
if (resultCount !== previousResultCount) {
return resultCount + " result" + (resultCount === 1 ? ' is' : 's are') + " available, use up and down arrow keys to navigate. Press Enter key to select.";
}
return '';
}
/**
* Takes an argument and if it's an array, returns the first item in the array
* otherwise returns the argument
* @param {*} arg the maybe-array
* @param {*} defaultValue the value if arg is falsey not defined
* @return {*} the arg or it's first item
*/
function unwrapArray(arg, defaultValue) {
arg = Array.isArray(arg) ?
/* istanbul ignore next (preact) */
arg[0] : arg;
if (!arg && defaultValue) {
return defaultValue;
} else {
return arg;
}
}
/**
* @param {Object} element (P)react element
* @return {Boolean} whether it's a DOM element
*/
function isDOMElement(element) {
// then we assume this is react
return typeof element.type === 'string';
}
/**
* @param {Object} element (P)react element
* @return {Object} the props
*/
function getElementProps(element) {
return element.props;
}
var stateKeys = ['highlightedIndex', 'inputValue', 'isOpen', 'selectedItem', 'type'];
/**
* @param {Object} state the state object
* @return {Object} state that is relevant to downshift
*/
function pickState(state) {
if (state === void 0) {
state = {};
}
var result = {};
stateKeys.forEach(function (k) {
if (state.hasOwnProperty(k)) {
result[k] = state[k];
}
});
return result;
}
/**
* Normalizes the 'key' property of a KeyboardEvent in IE/Edge
* @param {Object} event a keyboardEvent object
* @return {String} keyboard key
*/
function normalizeArrowKey(event) {
var key = event.key,
keyCode = event.keyCode;
/* istanbul ignore next (ie) */
if (keyCode >= 37 && keyCode <= 40 && key.indexOf('Arrow') !== 0) {
return "Arrow" + key;
}
return key;
}
/**
* Returns the new index in the list, in a circular way. If next value is out of bonds from the total,
* it will wrap to either 0 or itemCount - 1.
*
* @param {number} moveAmount Number of positions to move. Negative to move backwards, positive forwards.
* @param {number} baseIndex The initial position to move from.
* @param {number} itemCount The total number of items.
* @returns {number} The new index after the move.
*/
function getNextWrappingIndex(moveAmount, baseIndex, itemCount) {
var itemsLastIndex = itemCount - 1;
if (typeof baseIndex !== 'number' || baseIndex < 0 || baseIndex >= itemCount) {
baseIndex = moveAmount > 0 ? -1 : itemsLastIndex + 1;
}
var newIndex = baseIndex + moveAmount;
if (newIndex < 0) {
newIndex = itemsLastIndex;
} else if (newIndex > itemsLastIndex) {
newIndex = 0;
}
return newIndex;
}
var Downshift =
/*#__PURE__*/
function (_Component) {
_inheritsLoose(Downshift, _Component);
function Downshift(_props) {
var _this = _Component.call(this, _props) || this;
_this.id = _this.props.id || "downshift-" + generateId();
_this.menuId = _this.props.menuId || _this.id + "-menu";
_this.labelId = _this.props.labelId || _this.id + "-label";
_this.inputId = _this.props.inputId || _this.id + "-input";
_this.getItemId = _this.props.getItemId || function (index) {
return _this.id + "-item-" + index;
};
_this.input = null;
_this.items = [];
_this.itemCount = null;
_this.previousResultCount = 0;
_this.timeoutIds = [];
_this.internalSetTimeout = function (fn, time) {
var id = setTimeout(function () {
_this.timeoutIds = _this.timeoutIds.filter(function (i) {
return i !== id;
});
fn();
}, time);
_this.timeoutIds.push(id);
};
_this.setItemCount = function (count) {
_this.itemCount = count;
};
_this.unsetItemCount = function () {
_this.itemCount = null;
};
_this.setHighlightedIndex = function (highlightedIndex, otherStateToSet) {
if (highlightedIndex === void 0) {
highlightedIndex = _this.props.defaultHighlightedIndex;
}
if (otherStateToSet === void 0) {
otherStateToSet = {};
}
otherStateToSet = pickState(otherStateToSet);
_this.internalSetState(_extends({
highlightedIndex: highlightedIndex
}, otherStateToSet));
};
_this.clearSelection = function (cb) {
_this.internalSetState({
selectedItem: null,
inputValue: '',
highlightedIndex: _this.props.defaultHighlightedIndex,
isOpen: _this.props.defaultIsOpen
}, cb);
};
_this.selectItem = function (item, otherStateToSet, cb) {
otherStateToSet = pickState(otherStateToSet);
_this.internalSetState(_extends({
isOpen: _this.props.defaultIsOpen,
highlightedIndex: _this.props.defaultHighlightedIndex,
selectedItem: item,
inputValue: _this.props.itemToString(item)
}, otherStateToSet), cb);
};
_this.selectItemAtIndex = function (itemIndex, otherStateToSet, cb) {
var item = _this.items[itemIndex];
if (item == null) {
return;
}
_this.selectItem(item, otherStateToSet, cb);
};
_this.selectHighlightedItem = function (otherStateToSet, cb) {
return _this.selectItemAtIndex(_this.getState().highlightedIndex, otherStateToSet, cb);
};
_this.internalSetState = function (stateToSet, cb) {
var isItemSelected, onChangeArg;
var onStateChangeArg = {};
var isStateToSetFunction = typeof stateToSet === 'function'; // we want to call `onInputValueChange` before the `setState` call
// so someone controlling the `inputValue` state gets notified of
// the input change as soon as possible. This avoids issues with
// preserving the cursor position.
// See https://github.com/downshift-js/downshift/issues/217 for more info.
if (!isStateToSetFunction && stateToSet.hasOwnProperty('inputValue')) {
_this.props.onInputValueChange(stateToSet.inputValue, _extends({}, _this.getStateAndHelpers(), stateToSet));
}
return _this.setState(function (state) {
state = _this.getState(state);
var newStateToSet = isStateToSetFunction ? stateToSet(state) : stateToSet; // Your own function that could modify the state that will be set.
newStateToSet = _this.props.stateReducer(state, newStateToSet); // checks if an item is selected, regardless of if it's different from
// what was selected before
// used to determine if onSelect and onChange callbacks should be called
isItemSelected = newStateToSet.hasOwnProperty('selectedItem'); // this keeps track of the object we want to call with setState
var nextState = {}; // this is just used to tell whether the state changed
var nextFullState = {}; // we need to call on change if the outside world is controlling any of our state
// and we're trying to update that state. OR if the selection has changed and we're
// trying to update the selection
if (isItemSelected && newStateToSet.selectedItem !== state.selectedItem) {
onChangeArg = newStateToSet.selectedItem;
}
newStateToSet.type = newStateToSet.type || unknown;
Object.keys(newStateToSet).forEach(function (key) {
// onStateChangeArg should only have the state that is
// actually changing
if (state[key] !== newStateToSet[key]) {
onStateChangeArg[key] = newStateToSet[key];
} // the type is useful for the onStateChangeArg
// but we don't actually want to set it in internal state.
// this is an undocumented feature for now... Not all internalSetState
// calls support it and I'm not certain we want them to yet.
// But it enables users controlling the isOpen state to know when
// the isOpen state changes due to mouseup events which is quite handy.
if (key === 'type') {
return;
}
nextFullState[key] = newStateToSet[key]; // if it's coming from props, then we don't care to set it internally
if (!_this.isControlledProp(key)) {
nextState[key] = newStateToSet[key];
}
}); // if stateToSet is a function, then we weren't able to call onInputValueChange
// earlier, so we'll call it now that we know what the inputValue state will be.
if (isStateToSetFunction && newStateToSet.hasOwnProperty('inputValue')) {
_this.props.onInputValueChange(newStateToSet.inputValue, _extends({}, _this.getStateAndHelpers(), newStateToSet));
}
return nextState;
}, function () {
// call the provided callback if it's a function
cbToCb(cb)(); // only call the onStateChange and onChange callbacks if
// we have relevant information to pass them.
var hasMoreStateThanType = Object.keys(onStateChangeArg).length > 1;
if (hasMoreStateThanType) {
_this.props.onStateChange(onStateChangeArg, _this.getStateAndHelpers());
}
if (isItemSelected) {
_this.props.onSelect(stateToSet.selectedItem, _this.getStateAndHelpers());
}
if (onChangeArg !== undefined) {
_this.props.onChange(onChangeArg, _this.getStateAndHelpers());
} // this is currently undocumented and therefore subject to change
// We'll try to not break it, but just be warned.
_this.props.onUserAction(onStateChangeArg, _this.getStateAndHelpers());
});
};
_this.rootRef = function (node) {
return _this._rootNode = node;
};
_this.getRootProps = function (_temp, _temp2) {
var _extends2;
var _ref = _temp === void 0 ? {} : _temp,
_ref$refKey = _ref.refKey,
refKey = _ref$refKey === void 0 ? 'ref' : _ref$refKey,
rest = _objectWithoutPropertiesLoose(_ref, ["refKey"]);
var _ref2 = _temp2 === void 0 ? {} : _temp2,
_ref2$suppressRefErro = _ref2.suppressRefError,
suppressRefError = _ref2$suppressRefErro === void 0 ? false : _ref2$suppressRefErro;
// this is used in the render to know whether the user has called getRootProps.
// It uses that to know whether to apply the props automatically
_this.getRootProps.called = true;
_this.getRootProps.refKey = refKey;
_this.getRootProps.suppressRefError = suppressRefError;
var _this$getState = _this.getState(),
isOpen = _this$getState.isOpen;
return _extends((_extends2 = {}, _extends2[refKey] = _this.rootRef, _extends2.role = 'combobox', _extends2['aria-expanded'] = isOpen, _extends2['aria-haspopup'] = 'listbox', _extends2['aria-owns'] = isOpen ? _this.menuId : null, _extends2['aria-labelledby'] = _this.labelId, _extends2), rest);
};
_this.keyDownHandlers = {
ArrowDown: function ArrowDown(event) {
var _this2 = this;
event.preventDefault();
if (this.getState().isOpen) {
var amount = event.shiftKey ? 5 : 1;
this.moveHighlightedIndex(amount, {
type: keyDownArrowDown
});
} else {
this.internalSetState({
isOpen: true,
type: keyDownArrowDown
}, function () {
var itemCount = _this2.getItemCount();
if (itemCount > 0) {
_this2.setHighlightedIndex(getNextWrappingIndex(1, _this2.getState().highlightedIndex, itemCount), {
type: keyDownArrowDown
});
}
});
}
},
ArrowUp: function ArrowUp(event) {
var _this3 = this;
event.preventDefault();
if (this.getState().isOpen) {
var amount = event.shiftKey ? -5 : -1;
this.moveHighlightedIndex(amount, {
type: keyDownArrowUp
});
} else {
this.internalSetState({
isOpen: true,
type: keyDownArrowUp
}, function () {
var itemCount = _this3.getItemCount();
if (itemCount > 0) {
_this3.setHighlightedIndex(getNextWrappingIndex(-1, _this3.getState().highlightedIndex, itemCount), {
type: keyDownArrowDown
});
}
});
}
},
Enter: function Enter(event) {
var _this$getState2 = this.getState(),
isOpen = _this$getState2.isOpen,
highlightedIndex = _this$getState2.highlightedIndex;
if (isOpen && highlightedIndex != null) {
event.preventDefault();
var item = this.items[highlightedIndex];
var itemNode = this.getItemNodeFromIndex(highlightedIndex);
if (item == null || itemNode && itemNode.hasAttribute('disabled')) {
return;
}
this.selectHighlightedItem({
type: keyDownEnter
});
}
},
Escape: function Escape(event) {
event.preventDefault();
this.reset({
type: keyDownEscape
});
}
};
_this.buttonKeyDownHandlers = _extends({}, _this.keyDownHandlers, {
' ': function _(event) {
event.preventDefault();
this.toggleMenu({
type: keyDownSpaceButton
});
}
});
_this.inputKeyDownHandlers = _extends({}, _this.keyDownHandlers, {
Home: function Home(event) {
this.highlightFirstOrLastIndex(event, true, {
type: keyDownHome
});
},
End: function End(event) {
this.highlightFirstOrLastIndex(event, false, {
type: keyDownEnd
});
}
});
_this.getToggleButtonProps = function (_temp3) {
var _ref3 = _temp3 === void 0 ? {} : _temp3,
onClick = _ref3.onClick,
onPress = _ref3.onPress,
onKeyDown = _ref3.onKeyDown,
onKeyUp = _ref3.onKeyUp,
onBlur = _ref3.onBlur,
rest = _objectWithoutPropertiesLoose(_ref3, ["onClick", "onPress", "onKeyDown", "onKeyUp", "onBlur"]);
var _this$getState3 = _this.getState(),
isOpen = _this$getState3.isOpen;
var enabledEventHandlers = {
onClick: callAllEventHandlers(onClick, _this.buttonHandleClick),
onKeyDown: callAllEventHandlers(onKeyDown, _this.buttonHandleKeyDown),
onKeyUp: callAllEventHandlers(onKeyUp, _this.buttonHandleKeyUp),
onBlur: callAllEventHandlers(onBlur, _this.buttonHandleBlur)
};
var eventHandlers = rest.disabled ? {} : enabledEventHandlers;
return _extends({
type: 'button',
role: 'button',
'aria-label': isOpen ? 'close menu' : 'open menu',
'aria-haspopup': true,
'data-toggle': true
}, eventHandlers, rest);
};
_this.buttonHandleKeyUp = function (event) {
// Prevent click event from emitting in Firefox
event.preventDefault();
};
_this.buttonHandleKeyDown = function (event) {
var key = normalizeArrowKey(event);
if (_this.buttonKeyDownHandlers[key]) {
_this.buttonKeyDownHandlers[key].call(_assertThisInitialized(_this), event);
}
};
_this.buttonHandleClick = function (event) {
event.preventDefault(); // handle odd case for Safari and Firefox which
// don't give the button the focus properly.
/* istanbul ignore if (can't reasonably test this) */
if (_this.props.environment.document.activeElement === _this.props.environment.document.body) {
event.target.focus();
} // to simplify testing components that use downshift, we'll not wrap this in a setTimeout
// if the NODE_ENV is test. With the proper build system, this should be dead code eliminated
// when building for production and should therefore have no impact on production code.
{
// Ensure that toggle of menu occurs after the potential blur event in iOS
_this.internalSetTimeout(function () {
return _this.toggleMenu({
type: clickButton
});
});
}
};
_this.buttonHandleBlur = function (event) {
var blurTarget = event.target; // Save blur target for comparison with activeElement later
// Need setTimeout, so that when the user presses Tab, the activeElement is the next focused element, not body element
_this.internalSetTimeout(function () {
if (!_this.isMouseDown && (_this.props.environment.document.activeElement == null || _this.props.environment.document.activeElement.id !== _this.inputId) && _this.props.environment.document.activeElement !== blurTarget // Do nothing if we refocus the same element again (to solve issue in Safari on iOS)
) {
_this.reset({
type: blurButton
});
}
});
};
_this.getLabelProps = function (props) {
return _extends({
htmlFor: _this.inputId,
id: _this.labelId
}, props);
};
_this.getInputProps = function (_temp4) {
var _ref4 = _temp4 === void 0 ? {} : _temp4,
onKeyDown = _ref4.onKeyDown,
onBlur = _ref4.onBlur,
onChange = _ref4.onChange,
onInput = _ref4.onInput,
onChangeText = _ref4.onChangeText,
rest = _objectWithoutPropertiesLoose(_ref4, ["onKeyDown", "onBlur", "onChange", "onInput", "onChangeText"]);
var onChangeKey;
var eventHandlers = {};
/* istanbul ignore next (preact) */
onChangeKey = 'onChange';
var _this$getState4 = _this.getState(),
inputValue = _this$getState4.inputValue,
isOpen = _this$getState4.isOpen,
highlightedIndex = _this$getState4.highlightedIndex;
if (!rest.disabled) {
var _eventHandlers;
eventHandlers = (_eventHandlers = {}, _eventHandlers[onChangeKey] = callAllEventHandlers(onChange, onInput, _this.inputHandleChange), _eventHandlers.onKeyDown = callAllEventHandlers(onKeyDown, _this.inputHandleKeyDown), _eventHandlers.onBlur = callAllEventHandlers(onBlur, _this.inputHandleBlur), _eventHandlers);
}
/* istanbul ignore if (react-native) */
return _extends({
'aria-autocomplete': 'list',
'aria-activedescendant': isOpen && typeof highlightedIndex === 'number' && highlightedIndex >= 0 ? _this.getItemId(highlightedIndex) : null,
'aria-controls': isOpen ? _this.menuId : null,
'aria-labelledby': _this.labelId,
// https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion
// revert back since autocomplete="nope" is ignored on latest Chrome and Opera
autoComplete: 'off',
value: inputValue,
id: _this.inputId
}, eventHandlers, rest);
};
_this.inputHandleKeyDown = function (event) {
var key = normalizeArrowKey(event);
if (key && _this.inputKeyDownHandlers[key]) {
_this.inputKeyDownHandlers[key].call(_assertThisInitialized(_this), event);
}
};
_this.inputHandleChange = function (event) {
_this.internalSetState({
type: changeInput,
isOpen: true,
inputValue: event.target.value,
highlightedIndex: _this.props.defaultHighlightedIndex
});
};
_this.inputHandleTextChange
/* istanbul ignore next (react-native) */
= function (text) {
_this.internalSetState({
type: changeInput,
isOpen: true,
inputValue: text,
highlightedIndex: _this.props.defaultHighlightedIndex
});
};
_this.inputHandleBlur = function () {
// Need setTimeout, so that when the user presses Tab, the activeElement is the next focused element, not the body element
_this.internalSetTimeout(function () {
var downshiftButtonIsActive = _this.props.environment.document && !!_this.props.environment.document.activeElement && !!_this.props.environment.document.activeElement.dataset && _this.props.environment.document.activeElement.dataset.toggle && _this._rootNode && _this._rootNode.contains(_this.props.environment.document.activeElement);
if (!_this.isMouseDown && !downshiftButtonIsActive) {
_this.reset({
type: blurInput
});
}
});
};
_this.menuRef = function (node) {
_this._menuNode = node;
};
_this.getMenuProps = function (_temp5, _temp6) {
var _extends3;
var _ref5 = _temp5 === void 0 ? {} : _temp5,
_ref5$refKey = _ref5.refKey,
refKey = _ref5$refKey === void 0 ? 'ref' : _ref5$refKey,
ref = _ref5.ref,
props = _objectWithoutPropertiesLoose(_ref5, ["refKey", "ref"]);
var _ref6 = _temp6 === void 0 ? {} : _temp6,
_ref6$suppressRefErro = _ref6.suppressRefError,
suppressRefError = _ref6$suppressRefErro === void 0 ? false : _ref6$suppressRefErro;
_this.getMenuProps.called = true;
_this.getMenuProps.refKey = refKey;
_this.getMenuProps.suppressRefError = suppressRefError;
return _extends((_extends3 = {}, _extends3[refKey] = callAll(ref, _this.menuRef), _extends3.role = 'listbox', _extends3['aria-labelledby'] = props && props['aria-label'] ? null : _this.labelId, _extends3.id = _this.menuId, _extends3), props);
};
_this.getItemProps = function (_temp7) {
var _enabledEventHandlers;
var _ref7 = _temp7 === void 0 ? {} : _temp7,
onMouseMove = _ref7.onMouseMove,
onMouseDown = _ref7.onMouseDown,
onClick = _ref7.onClick,
onPress = _ref7.onPress,
index = _ref7.index,
_ref7$item = _ref7.item,
item = _ref7$item === void 0 ? undefined : _ref7$item,
rest = _objectWithoutPropertiesLoose(_ref7, ["onMouseMove", "onMouseDown", "onClick", "onPress", "index", "item"]);
if (index === undefined) {
_this.items.push(item);
index = _this.items.indexOf(item);
} else {
_this.items[index] = item;
}
var onSelectKey = 'onClick';
var customClickHandler = onClick;
var enabledEventHandlers = (_enabledEventHandlers = {
// onMouseMove is used over onMouseEnter here. onMouseMove
// is only triggered on actual mouse movement while onMouseEnter
// can fire on DOM changes, interrupting keyboard navigation
onMouseMove: callAllEventHandlers(onMouseMove, function () {
if (index === _this.getState().highlightedIndex) {
return;
}
_this.setHighlightedIndex(index, {
type: itemMouseEnter
}); // We never want to manually scroll when changing state based
// on `onMouseMove` because we will be moving the element out
// from under the user which is currently scrolling/moving the
// cursor
_this.avoidScrolling = true;
_this.internalSetTimeout(function () {
return _this.avoidScrolling = false;
}, 250);
}),
onMouseDown: callAllEventHandlers(onMouseDown, function (event) {
// This prevents the activeElement from being changed
// to the item so it can remain with the current activeElement
// which is a more common use case.
event.preventDefault();
})
}, _enabledEventHandlers[onSelectKey] = callAllEventHandlers(customClickHandler, function () {
_this.selectItemAtIndex(index, {
type: clickItem
});
}), _enabledEventHandlers); // Passing down the onMouseDown handler to prevent redirect
// of the activeElement if clicking on disabled items
var eventHandlers = rest.disabled ? {
onMouseDown: enabledEventHandlers.onMouseDown
} : enabledEventHandlers;
return _extends({
id: _this.getItemId(index),
role: 'option',
'aria-selected': _this.getState().highlightedIndex === index
}, eventHandlers, rest);
};
_this.clearItems = function () {
_this.items = [];
};
_this.reset = function (otherStateToSet, cb) {
if (otherStateToSet === void 0) {
otherStateToSet = {};
}
otherStateToSet = pickState(otherStateToSet);
_this.internalSetState(function (_ref8) {
var selectedItem = _ref8.selectedItem;
return _extends({
isOpen: _this.props.defaultIsOpen,
highlightedIndex: _this.props.defaultHighlightedIndex,
inputValue: _this.props.itemToString(selectedItem)
}, otherStateToSet);
}, cb);
};
_this.toggleMenu = function (otherStateToSet, cb) {
if (otherStateToSet === void 0) {
otherStateToSet = {};
}
otherStateToSet = pickState(otherStateToSet);
_this.internalSetState(function (_ref9) {
var isOpen = _ref9.isOpen;
return _extends({
isOpen: !isOpen
}, isOpen && {
highlightedIndex: _this.props.defaultHighlightedIndex
}, otherStateToSet);
}, function () {
var _this$getState5 = _this.getState(),
isOpen = _this$getState5.isOpen,
highlightedIndex = _this$getState5.highlightedIndex;
if (isOpen) {
if (_this.getItemCount() > 0 && typeof highlightedIndex === 'number') {
_this.setHighlightedIndex(highlightedIndex, otherStateToSet);
}
}
cbToCb(cb)();
});
};
_this.openMenu = function (cb) {
_this.internalSetState({
isOpen: true
}, cb);
};
_this.closeMenu = function (cb) {
_this.internalSetState({
isOpen: false
}, cb);
};
_this.updateStatus = debounce(function () {
var state = _this.getState();
var item = _this.items[state.highlightedIndex];
var resultCount = _this.getItemCount();
var status = _this.props.getA11yStatusMessage(_extends({
itemToString: _this.props.itemToString,
previousResultCount: _this.previousResultCount,
resultCount: resultCount,
highlightedItem: item
}, state));
_this.previousResultCount = resultCount;
setStatus(status);
}, 200);
// fancy destructuring + defaults + aliases
// this basically says each value of state should either be set to
// the initial value or the default value if the initial value is not provided
var _this$props = _this.props,
defaultHighlightedIndex = _this$props.defaultHighlightedIndex,
_this$props$initialHi = _this$props.initialHighlightedIndex,
_highlightedIndex = _this$props$initialHi === void 0 ? defaultHighlightedIndex : _this$props$initialHi,
defaultIsOpen = _this$props.defaultIsOpen,
_this$props$initialIs = _this$props.initialIsOpen,
_isOpen = _this$props$initialIs === void 0 ? defaultIsOpen : _this$props$initialIs,
_this$props$initialIn = _this$props.initialInputValue,
_inputValue = _this$props$initialIn === void 0 ? '' : _this$props$initialIn,
_this$props$initialSe = _this$props.initialSelectedItem,
_selectedItem = _this$props$initialSe === void 0 ? null : _this$props$initialSe;
var _state = _this.getState({
highlightedIndex: _highlightedIndex,
isOpen: _isOpen,
inputValue: _inputValue,
selectedItem: _selectedItem
});
if (_state.selectedItem != null && _this.props.initialInputValue === undefined) {
_state.inputValue = _this.props.itemToString(_state.selectedItem);
}
_this.state = _state;
return _this;
}
var _proto = Downshift.prototype;
/**
* Clear all running timeouts
*/
_proto.internalClearTimeouts = function internalClearTimeouts() {
this.timeoutIds.forEach(function (id) {
clearTimeout(id);
});
this.timeoutIds = [];
}
/**
* Gets the state based on internal state or props
* If a state value is passed via props, then that
* is the value given, otherwise it's retrieved from
* stateToMerge
*
* This will perform a shallow merge of the given state object
* with the state coming from props
* (for the controlled component scenario)
* This is used in state updater functions so they're referencing
* the right state regardless of where it comes from.
*
* @param {Object} stateToMerge defaults to this.state
* @return {Object} the state
*/
;
_proto.getState = function getState(stateToMerge) {
var _this4 = this;
if (stateToMerge === void 0) {
stateToMerge = this.state;
}
return Object.keys(stateToMerge).reduce(function (state, key) {
state[key] = _this4.isControlledProp(key) ? _this4.props[key] : stateToMerge[key];
return state;
}, {});
}
/**
* This determines whether a prop is a "controlled prop" meaning it is
* state which is controlled by the outside of this component rather
* than within this component.
* @param {String} key the key to check
* @return {Boolean} whether it is a controlled controlled prop
*/
;
_proto.isControlledProp = function isControlledProp(key) {
return this.props[key] !== undefined;
};
_proto.getItemCount = function getItemCount() {
// things read better this way. They're in priority order:
// 1. `this.itemCount`
// 2. `this.props.itemCount`
// 3. `this.items.length`
var itemCount = this.items.length;
if (this.itemCount != null) {
itemCount = this.itemCount;
} else if (this.props.itemCount !== undefined) {
itemCount = this.props.itemCount;
}
return itemCount;
};
_proto.getItemNodeFromIndex = function getItemNodeFromIndex(index) {
return this.props.environment.document.getElementById(this.getItemId(index));
};
_proto.scrollHighlightedItemIntoView = function scrollHighlightedItemIntoView() {
/* istanbul ignore else (react-native) */
{
var node = this.getItemNodeFromIndex(this.getState().highlightedIndex);
this.props.scrollIntoView(node, this._menuNode);
}
};
_proto.moveHighlightedIndex = function moveHighlightedIndex(amount, otherStateToSet) {
var itemCount = this.getItemCount();
if (itemCount > 0) {
var nextHighlightedIndex = getNextWrappingIndex(amount, this.getState().highlightedIndex, itemCount);
this.setHighlightedIndex(nextHighlightedIndex, otherStateToSet);
}
};
_proto.highlightFirstOrLastIndex = function highlightFirstOrLastIndex(event, first, otherStateToSet) {
var itemsLastIndex = this.getItemCount() - 1;
if (itemsLastIndex < 0 || !this.getState().isOpen) {
return;
}
event.preventDefault();
this.setHighlightedIndex(first ? 0 : itemsLastIndex, otherStateToSet);
};
_proto.getStateAndHelpers = function getStateAndHelpers() {
var _this$getState6 = this.getState(),
highlightedIndex = _this$getState6.highlightedIndex,
inputValue = _this$getState6.inputValue,
selectedItem = _this$getState6.selectedItem,
isOpen = _this$getState6.isOpen;
var itemToString = this.props.itemToString;
var id = this.id;
var getRootProps = this.getRootProps,
getToggleButtonProps = this.getToggleButtonProps,
getLabelProps = this.getLabelProps,
getMenuProps = this.getMenuProps,
getInputProps = this.getInputProps,
getItemProps = this.getItemProps,
openMenu = this.openMenu,
closeMenu = this.closeMenu,
toggleMenu = this.toggleMenu,
selectItem = this.selectItem,
selectItemAtIndex = this.selectItemAtIndex,
selectHighlightedItem = this.selectHighlightedItem,
setHighlightedIndex = this.setHighlightedIndex,
clearSelection = this.clearSelection,
clearItems = this.clearItems,
reset = this.reset,
setItemCount = this.setItemCount,
unsetItemCount = this.unsetItemCount,
setState = this.internalSetState;
return {
// prop getters
getRootProps: getRootProps,
getToggleButtonProps: getToggleButtonProps,
getLabelProps: getLabelProps,
getMenuProps: getMenuProps,
getInputProps: getInputProps,
getItemProps: getItemProps,
// actions
reset: reset,
openMenu: openMenu,
closeMenu: closeMenu,
toggleMenu: toggleMenu,
selectItem: selectItem,
selectItemAtIndex: selectItemAtIndex,
selectHighlightedItem: selectHighlightedItem,
setHighlightedIndex: setHighlightedIndex,
clearSelection: clearSelection,
clearItems: clearItems,
setItemCount: setItemCount,
unsetItemCount: unsetItemCount,
setState: setState,
// props
itemToString: itemToString,
// derived
id: id,
// state
highlightedIndex: highlightedIndex,
inputValue: inputValue,
isOpen: isOpen,
selectedItem: selectedItem
};
} //////////////////////////// ROOT
;
_proto.componentDidMount = function componentDidMount() {
var _this5 = this;
/* istanbul ignore if (react-native) */
{
var targetWithinDownshift = function (target, checkActiveElement) {
if (checkActiveElement === void 0) {
checkActiveElement = true;
}
var document = _this5.props.environment.document;
return [_this5._rootNode, _this5._menuNode].some(function (contextNode) {
return contextNode && (isOrContainsNode(contextNode, target) || checkActiveElement && isOrContainsNode(contextNode, document.activeElement));
});
}; // this.isMouseDown helps us track whether the mouse is currently held down.
// This is useful when the user clicks on an item in the list, but holds the mouse
// down long enough for the list to disappear (because the blur event fires on the input)
// this.isMouseDown is used in the blur handler on the input to determine whether the blur event should
// trigger hiding the menu.
var onMouseDown = function () {
_this5.isMouseDown = true;
};
var onMouseUp = function (event) {
_this5.isMouseDown = false; // if the target element or the activeElement is within a downshift node
// then we don't want to reset downshift
var contextWithinDownshift = targetWithinDownshift(event.target);
if (!contextWithinDownshift && _this5.getState().isOpen) {
_this5.reset({
type: mouseUp
}, function () {
return _this5.props.onOuterClick(_this5.getStateAndHelpers());
});
}
}; // Touching an element in iOS gives focus and hover states, but touching out of
// the element will remove hover, and persist the focus state, resulting in the
// blur event not being triggered.
// this.isTouchMove helps us track whether the user is tapping or swiping on a touch screen.
// If the user taps outside of Downshift, the component should be reset,
// but not if the user is swiping
var onTouchStart = function () {
_this5.isTouchMove = false;
};
var onTouchMove = function () {
_this5.isTouchMove = true;
};
var onTouchEnd = function (event) {
var contextWithinDownshift = targetWithinDownshift(event.target, false);
if (!_this5.isTouchMove && !contextWithinDownshift && _this5.getState().isOpen) {
_this5.reset({
type: touchEnd
}, function () {
return _this5.props.onOuterClick(_this5.getStateAndHelpers());
});
}
};
this.props.environment.addEventListener('mousedown', onMouseDown);
this.props.environment.addEventListener('mouseup', onMouseUp);
this.props.environment.addEventListener('touchstart', onTouchStart);
this.props.environment.addEventListener('touchmove', onTouchMove);
this.props.environment.addEventListener('touchend', onTouchEnd);
this.cleanup = function () {
_this5.internalClearTimeouts();
_this5.updateStatus.cancel();
_this5.props.environment.removeEventListener('mousedown', onMouseDown);
_this5.props.environment.removeEventListener('mouseup', onMouseUp);
_this5.props.environment.removeEventListener('touchstart', onTouchStart);
_this5.props.environment.removeEventListener('touchmove', onTouchMove);
_this5.props.environment.removeEventListener('touchend', onTouchEnd);
};
}
};
_proto.shouldScroll = function shouldScroll(prevState, prevProps) {
var _ref10 = this.props.highlightedIndex === undefined ? this.getState() : this.props,
currentHighlightedIndex = _ref10.highlightedIndex;
var _ref11 = prevProps.highlightedIndex === undefined ? prevState : prevProps,
prevHighlightedIndex = _ref11.highlightedIndex;
var scrollWhenOpen = currentHighlightedIndex && this.getState().isOpen && !prevState.isOpen;
return scrollWhenOpen || currentHighlightedIndex !== prevHighlightedIndex;
};
_proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
if (this.isControlledProp('selectedItem') && this.props.selectedItemChanged(prevProps.selectedItem, this.props.selectedItem)) {
this.internalSetState({
type: controlledPropUpdatedSelectedItem,
inputValue: this.props.itemToString(this.props.selectedItem)
});
}
if (!this.avoidScrolling && this.shouldScroll(prevState, prevProps)) {
this.scrollHighlightedItemIntoView();
}
/* istanbul ignore else (react-native) */
this.updateStatus();
};
_proto.componentWillUnmount = function componentWillUnmount() {
this.cleanup(); // avoids memory leak
};
_proto.render = function render() {
var children = unwrapArray(this.props.children, noop); // because the items are rerendered every time we call the children
// we clear this out each render and it will be populated again as
// getItemProps is called.
this.clearItems(); // we reset this so we know whether the user calls getRootProps during
// this render. If they do then we don't need to do anything,
// if they don't then we need to clone the element they return and
// apply the props for them.
this.getRootProps.called = false;
this.getRootProps.refKey = undefined;
this.getRootProps.suppressRefError = undefined; // we do something similar for getMenuProps
this.getMenuProps.called = false;
this.getMenuProps.refKey = undefined;
this.getMenuProps.suppressRefError = undefined; // we do something similar for getLabelProps
this.getLabelProps.called = false; // and something similar for getInputProps
this.getInputProps.called = false;
var element = unwrapArray(children(this.getStateAndHelpers()));
if (!element) {
return null;
}
if (this.getRootProps.called || this.props.suppressRefError) {
return element;
} else if (isDOMElement(element)) {
// they didn't apply the root props, but we can clone
// this and apply the props ourselves
return React__default$$1.cloneElement(element, this.getRootProps(getElementProps(element)));
}
/* istanbul ignore next */
return undefined;
};
return Downshift;
}(React__default.Component);
Downshift.defaultProps = {
defaultHighlightedIndex: null,
defaultIsOpen: false,
getA11yStatusMessage: getA11yStatusMessage,
itemToString: function itemToString(i) {
if (i == null) {
return '';
}
return String(i);
},
onStateChange: noop,
onInputValueChange: noop,
onUserAction: noop,
onChange: noop,
onSelect: noop,
onOuterClick: noop,
selectedItemChanged: function selectedItemChanged(prevItem, item) {
return prevItem !== item;
},
environment: typeof window === 'undefined'
/* istanbul ignore next (ssr) */
? {} : window,
stateReducer: function stateReducer(state, stateToSet) {
return stateToSet;
},
suppressRefError: false,
scrollIntoView: scrollIntoView
};
Downshift.stateChangeTypes = stateChangeTypes;
exports.default = Downshift;
exports.resetIdCounter = resetIdCounter;
});
var Downshift = unwrapExports(downshift_cjs);
var downshift_cjs_1 = downshift_cjs.resetIdCounter;
var filterOptions = function filterOptions(options, query) {
var filteredOptions = query ? options.filter(function (item) {
return !query || item.text.toUpperCase().includes(query.toUpperCase());
}) : options;
if (filteredOptions.length < 1) ;
return filteredOptions;
};
var highlightQuery = function highlightQuery(str, query) {
var start = str.toUpperCase().indexOf(query.toUpperCase());
var end = start + query.length;
if (start < 0) {
start = 0;
end = 0;
}
return React__default.createElement("span", null, str.substr(0, start), React__default.createElement("span", {
className: "highlighted"
}, str.substr(start, end - start)), str.substr(end));
};
function DownshiftWrapper(props) {
var inputValue = props.inputValue,
multiple = props.multiple,
options = props.options,
search = props.search,
selectedItems = props.selectedItems,
setInputValue = props.setInputValue,
setSelectedItem = props.setSelectedItem,
setUserInput = props.setUserInput,
setVisibleOptions = props.setVisibleOptions;
var addItem = React.useCallback(function (itemArray, item) {
return [].concat(toConsumableArray(itemArray), [item]);
}, []);
var removeItem = React.useCallback(function (itemArray, item) {
return itemArray.filter(function (i) {
return i !== item;
});
}, []);
var handleChange = React.useCallback(function (item) {
if (multiple) {
var prevSelectedItems = selectedItems;
if (prevSelectedItems.includes(item)) {
prevSelectedItems = removeItem(prevSelectedItems, item);
} else {
prevSelectedItems = addItem(prevSelectedItems, item);
}
setSelectedItem(prevSelectedItems);
props.onChange(prevSelectedItems);
} else {
setSelectedItem(item);
props.onChange(item);
}
}, [multiple, options, selectedItems, setSelectedItem]);
var handleInputValueChange = React.useCallback(function (changes, downshiftState) {
switch (downshiftState.type) {
case Downshift.stateChangeTypes.keyDownEscape:
setUserInput(false);
setVisibleOptions(options);
if (multiple) {
setInputValue("");
} else {
setInputValue(changes);
}
break;
case Downshift.stateChangeTypes.changeInput:
if (search) {
setVisibleOptions(filterOptions(options, changes));
}
setUserInput(true);
setInputValue(changes);
break;
default:
}
}, [filterOptions, options, setUserInput, setVisibleOptions]);
var handleOuterClick = React.useCallback(function (downshiftState) {
if (multiple) {
setInputValue("");
} else {
setInputValue(downshiftState.selectedItem ? downshiftState.selectedItem.text : "");
}
setUserInput(false);
setVisibleOptions(options);
}, [options, setInputValue, setUserInput, setVisibleOptions]);
var handleSelect = React.useCallback(function (item) {
if (!multiple) {
setInputValue(item.text);
setUserInput(false);
setVisibleOptions(options);
}
}, [multiple, options, setInputValue, setUserInput, setVisibleOptions]);
var handleStateChange = React.useCallback(function (changes, state) {
var selectedItem = changes.selectedItem ? changes.selectedItem : state.selectedItem;
if (changes.hasOwnProperty("isOpen")) {
if (changes.isOpen) {
props.onOpen && props.onOpen(selectedItem);
} else {
props.onClose && props.onClose(selectedItem);
}
} else if (multiple && !state.isOpen && changes.type === Downshift.stateChangeTypes.controlledPropUpdatedSelectedItem) {
props.onClose && props.onClose(selectedItem);
}
}, [props.onOpen, props.onClose]);
var stateReducer = React.useCallback(function (state, changes) {
switch (changes.type) {
case Downshift.stateChangeTypes.changeInput:
if (search) {
return changes;
}
return objectSpread({}, changes, {
highlightedIndex: options.findIndex(function (option) {
return option.text.toUpperCase().includes(changes.inputValue.toUpperCase());
})
});
case Downshift.stateChangeTypes.clickItem:
case Downshift.stateChangeTypes.keyDownEnter:
if (multiple) {
return objectSpread({}, changes, {
highlightedIndex: state.highlightedIndex,
isOpen: true
});
}
return changes;
default:
return changes;
}
}, [multiple, options]);
var getStateAndHelpers = React.useCallback(function (downshift) {
return objectSpread({
handleChange: handleChange
}, downshift);
}, [handleChange]);
var render = props.render,
_props$children = props.children,
children = _props$children === void 0 ? render : _props$children;
return React.createElement(Downshift, _extends_1({}, props, {
inputValue: inputValue,
onChange: React.useCallback(function (e) {
return handleChange(e);
}, [handleChange]),
onInputValueChange: handleInputValueChange,
onOuterClick: handleOuterClick,
onSelect: handleSelect,
onStateChange: handleStateChange,
selectedItem: selectedItems,
stateReducer: stateReducer
}), function (downshift) {
return children(getStateAndHelpers(downshift));
});
}
function DropdownIcon(props) {
return React__default.createElement("div", _extends_1({
className: "dropdown__button"
}, props), React__default.createElement("i", {
className: "dropdown__button-icon"
}));
}
function SimpleDropdown(props) {
var placeholder = props.placeholder,
search = props.search,
userInput = props.userInput,
visibleOptions = props.visibleOptions;
return React.createElement(DownshiftWrapper, props, function (_ref) {
var getInputProps = _ref.getInputProps,
getItemProps = _ref.getItemProps,
getMenuProps = _ref.getMenuProps,
getToggleButtonProps = _ref.getToggleButtonProps,
highlightedIndex = _ref.highlightedIndex,
inputValue = _ref.inputValue,
isOpen = _ref.isOpen,
selectedItem = _ref.selectedItem;
return React.createElement("div", {
className: classnames("dropdown", props.className)
}, React.createElement("div", {
className: "dropdown__bar"
}, React.createElement("input", _extends_1({
className: "dropdown__search"
}, getInputProps({
placeholder: placeholder
}))), React.createElement(DropdownIcon, getToggleButtonProps())), isOpen ? React.createElement("div", _extends_1({
className: "dropdown__menu"
}, getMenuProps()), visibleOptions.map(function (item, index) {
return React.createElement("div", _extends_1({
className: classnames({
dropdown__item: true,
"dropdown__item--selected": selectedItem === item,
"dropdown__item--active": highlightedIndex === index
})
}, getItemProps({
key: item.value,
item: item,
index: index
})), search && userInput && inputValue ? highlightQuery(item.text, inputValue) : React.createElement("span", null, item.text));
})) : null);
});
}
var Pill = React.forwardRef(function (_ref, ref) {
var onClose = _ref.onClose,
className = _ref.className,
children = _ref.children,
hasMenu = _ref.hasMenu,
rest = objectWithoutProperties(_ref, ["onClose", "className", "children", "hasMenu"]);
return React.createElement("div", _extends_1({
className: classnames("pill", className)
}, rest, {
ref: ref
}), React.createElement("span", {
className: "pill__label"
}, children), hasMenu ? React.createElement("i", {
className: "pill__menu"
}) : null, onClose ? React.createElement(IconButton, {
onClick: onClose
}, React.createElement("i", {
className: "pill__dismiss"
})) : null);
});
function MultiDropdown(props) {
var checkbox = props.checkbox,
placeholder = props.placeholder,
search = props.search,
visibleOptions = props.visibleOptions;
var inputRef = React.createRef();
var focusInputBox = React.useCallback(function () {
inputRef.current.focus();
}, [inputRef]);
return React.createElement(DownshiftWrapper, props, function (_ref) {
var getInputProps = _ref.getInputProps,
getItemProps = _ref.getItemProps,
getToggleButtonProps = _ref.getToggleButtonProps,
getMenuProps = _ref.getMenuProps,
handleChange = _ref.handleChange,
highlightedIndex = _ref.highlightedIndex,
inputValue = _ref.inputValue,
isOpen = _ref.isOpen,
selectedItem = _ref.selectedItem;
return React.createElement("div", {
className: classnames("dropdown", props.className)
}, React.createElement("div", {
className: "dropdown__bar"
}, React.createElement("div", {
className: "dropdown__pills",
onClick: focusInputBox
}, selectedItem.length > 0 ? selectedItem.map(function (item, index) {
return React.createElement(Pill, {
className: "dropdown__pill",
key: item.value,
onClick: function onClick(e) {
return e.stopPropagation();
},
onClose: function onClose() {
return handleChange(selectedItem[index]);
}
}, item.text);
}) : null, React.createElement("input", _extends_1({
className: "dropdown__search",
ref: inputRef
}, getInputProps({
placeholder: selectedItem.length > 0 ? null : placeholder
})))), React.createElement(DropdownIcon, getToggleButtonProps())), isOpen ? React.createElement("div", _extends_1({
className: "dropdown__menu"
}, getMenuProps()), visibleOptions.map(function (item, index) {
return React.createElement("div", _extends_1({
className: classnames({
dropdown__item: true,
"dropdown__item--selected": selectedItem.includes(item),
"dropdown__item--active": highlightedIndex === index
})
}, getItemProps({
key: item.value,
item: item,
index: index
})), checkbox ? React.createElement(Checkbox$1, {
checked: selectedItem.includes(item),
onChange: function onChange() {}
}, inputValue && search ? highlightQuery(item.text, inputValue) : item.text) : inputValue && search ? highlightQuery(item.text, inputValue) : React.createElement("span", null, item.text));
})) : null);
});
}
function Dropdown(props) {
var multiple = props.multiple,
options = props.options,
value = props.value;
var initialSelected = multiple ? options.filter(function (item) {
return Array.isArray(value) && value.indexOf(item.value) !== -1;
}) : options.filter(function (item) {
return item.value === value;
});
var initialState = multiple ? initialSelected : initialSelected[0];
var _React$useState = React.useState(initialState),
_React$useState2 = slicedToArray(_React$useState, 2),
selectedItems = _React$useState2[0],
setSelectedItem = _React$useState2[1];
var _React$useState3 = React.useState(""),
_React$useState4 = slicedToArray(_React$useState3, 2),
inputValue = _React$useState4[0],
setInputValue = _React$useState4[1];
var _React$useState5 = React.useState(false),
_React$useState6 = slicedToArray(_React$useState5, 2),
userInput = _React$useState6[0],
setUserInput = _React$useState6[1];
var _React$useState7 = React.useState(options),
_React$useState8 = slicedToArray(_React$useState7, 2),
visibleOptions = _React$useState8[0],
setVisibleOptions = _React$useState8[1];
var handleChange = props.onChange ? props.onChange : function () {};
var handleOpen = props.onOpen ? props.onOpen : function () {};
var handleClose = props.onClose ? props.onClose : function () {};
var itemToString = function itemToString(item) {
return item ? item.text : "";
};
React.useEffect(function () {
if (initialState) {
multiple ? setInputValue("") : setInputValue(initialState.text);
setSelectedItem(initialState);
} else {
setInputValue("");
multiple ? setSelectedItem([]) : setSelectedItem("");
}
setVisibleOptions(options);
setUserInput(false);
}, [multiple, options, setInputValue]);
return React.createElement(multiple ? MultiDropdown : SimpleDropdown, objectSpread({
initialSelectedItem: selectedItems,
inputValue: inputValue,
itemToString: itemToString,
onChange: handleChange,
onOpen: handleOpen,
onClose: handleClose,
selectedItems: selectedItems,
setInputValue: setInputValue,
setSelectedItem: setSelectedItem,
setUserInput: setUserInput,
setVisibleOptions: setVisibleOptions,
userInput: userInput,
visibleOptions: visibleOptions
}, props));
}
Dropdown.defaultProps = {
options: [{
text: "No Objects Available",
value: 0
}]
};
var RadioCheckbox = function RadioCheckbox(props) {
var _React$useContext = React.useContext(FormContext),
readOnly = _React$useContext.readOnly;
if (readOnly) {
// In read mode, stand-alone checkbox labels appear only when they were checked in edit mode.
if (props.checked) {
return React.createElement("div", {
className: classnames("form--readOnly form__text", props.className)
}, props.children);
}
return null;
}
var radio = props.radio,
checked = props.checked,
children = props.children,
rest = objectWithoutProperties(props, ["radio", "checked", "children"]);
return React.createElement(radio ? Radio$1 : Checkbox$1, objectSpread({}, rest, {
checked: checked
}), children);
};
var Input$2 = function Input$$1(props) {
var _React$useContext2 = React.useContext(FormContext),
readOnly = _React$useContext2.readOnly;
if (readOnly) {
return React.createElement("div", {
className: classnames("form--readOnly form__text", props.className)
}, props.value);
}
return React.createElement(Input, props);
};
var Checkbox$2 = function Checkbox(props) {
return React.createElement(RadioCheckbox, props);
};
var Radio$2 = function Radio(props) {
return React.createElement(RadioCheckbox, _extends_1({
radio: true
}, props));
};
var Dropdown$1 = function Dropdown$$1(props) {
var getTextFromValue = function getTextFromValue(value) {
if (Array.isArray(value)) {
var valueToText = [];
var text;
var result;
for (var i = 0; i < props.options.length; i++) {
valueToText[props.options[i].value] = props.options[i].text;
}
for (var _i = 0; _i < value.length; _i++) {
text = valueToText[value[_i]];
if (text) {
if (result) {
result += ", " + text;
} else {
result = text;
}
}
}
return result;
}
for (var _i2 = 0; _i2 < props.options.length; _i2++) {
if (props.options[_i2].value === value) {
return props.options[_i2].text;
}
}
};
var _React$useContext3 = React.useContext(FormContext),
readOnly = _React$useContext3.readOnly;
if (readOnly) {
if (props.value) {
return React.createElement("div", {
className: classnames("form--readOnly form__text", props.className)
}, getTextFromValue(props.value));
}
return React.createElement("div", {
className: classnames("form--readOnly form__text", props.className)
});
}
return React.createElement(Dropdown, props);
};
var FormInputComponents = /*#__PURE__*/Object.freeze({
Input: Input$2,
Checkbox: Checkbox$2,
Radio: Radio$2,
Dropdown: Dropdown$1
});
function FormError(props) {
if (props.error && props.touched) {
return React__default.createElement("div", {
className: classnames("form__error", props.className)
}, React__default.createElement("i", {
className: "form__error-icon"
}), React__default.createElement("span", {
className: "form__error-message"
}, props.error));
}
return null;
}
FormError.displayName = "Form.Error";
function Form(props) {
return React__default.createElement(FormContext.Provider, {
value: {
readOnly: props.readOnly,
layout: props.layout
}
}, props.children);
}
Form.Group = FormGroup;
Form.Label = FormLabel;
Form.Field = FormField;
Form.Error = FormError;
Form.Context = FormContext;
Form.defaultProps = {
readOnly: false,
layout: "default"
};
Object.assign(Form, FormInputComponents);
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
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 (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
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 __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)
t[p[i]] = s[p[i]];
return t;
}
var isArray = Array.isArray;
var keyList = Object.keys;
var hasProp = Object.prototype.hasOwnProperty;
var hasElementType = typeof Element !== 'undefined';
function equal(a, b) {
// fast-deep-equal index.js 2.0.1
if (a === b) return true;
if (a && b && typeof a == 'object' && typeof b == 'object') {
var arrA = isArray(a)
, arrB = isArray(b)
, i
, length
, key;
if (arrA && arrB) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (!equal(a[i], b[i])) return false;
return true;
}
if (arrA != arrB) return false;
var dateA = a instanceof Date
, dateB = b instanceof Date;
if (dateA != dateB) return false;
if (dateA && dateB) return a.getTime() == b.getTime();
var regexpA = a instanceof RegExp
, regexpB = b instanceof RegExp;
if (regexpA != regexpB) return false;
if (regexpA && regexpB) return a.toString() == b.toString();
var keys = keyList(a);
length = keys.length;
if (length !== keyList(b).length)
return false;
for (i = length; i-- !== 0;)
if (!hasProp.call(b, keys[i])) return false;
// end fast-deep-equal
// start react-fast-compare
// custom handling for DOM elements
if (hasElementType && a instanceof Element && b instanceof Element)
return a === b;
// custom handling for React
for (i = length; i-- !== 0;) {
key = keys[i];
if (key === '_owner' && a.$$typeof) {
// React-specific: avoid traversing React elements' _owner.
// _owner contains circular references
// and is not needed when comparing the actual elements (and not their owners)
// .$$typeof and ._store on just reasonable markers of a react element
continue;
} else {
// all other properties should be traversed as usual
if (!equal(a[key], b[key])) return false;
}
}
// end react-fast-compare
// fast-deep-equal index.js 2.0.1
return true;
}
return a !== a && b !== b;
}
// end fast-deep-equal
var reactFastCompare = function exportedEqual(a, b) {
try {
return equal(a, b);
} catch (error) {
if ((error.message && error.message.match(/stack|recursion/i)) || (error.number === -2146828260)) {
// 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('Warning: react-fast-compare does not handle circular references.', error.name, error.message);
return false;
}
// some other error. we should definitely know about these
throw error;
}
};
var isMergeableObject = function isMergeableObject(value) {
return isNonNullObject(value)
&& !isSpecial(value)
};
function isNonNullObject(value) {
return !!value && typeof value === 'object'
}
function isSpecial(value) {
var stringValue = Object.prototype.toString.call(value);
return stringValue === '[object RegExp]'
|| stringValue === '[object Date]'
|| isReactElement(value)
}
// see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
function isReactElement(value) {
return value.$$typeof === REACT_ELEMENT_TYPE
}
function emptyTarget(val) {
return Array.isArray(val) ? [] : {}
}
function cloneUnlessOtherwiseSpecified(value, options) {
return (options.clone !== false && options.isMergeableObject(value))
? deepmerge(emptyTarget(value), value, options)
: value
}
function defaultArrayMerge(target, source, options) {
return target.concat(source).map(function(element) {
return cloneUnlessOtherwiseSpecified(element, options)
})
}
function mergeObject(target, source, options) {
var destination = {};
if (options.isMergeableObject(target)) {
Object.keys(target).forEach(function(key) {
destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
});
}
Object.keys(source).forEach(function(key) {
if (!options.isMergeableObject(source[key]) || !target[key]) {
destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
} else {
destination[key] = deepmerge(target[key], source[key], options);
}
});
return destination
}
function deepmerge(target, source, options) {
options = options || {};
options.arrayMerge = options.arrayMerge || defaultArrayMerge;
options.isMergeableObject = options.isMergeableObject || isMergeableObject;
var sourceIsArray = Array.isArray(source);
var targetIsArray = Array.isArray(target);
var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
if (!sourceAndTargetTypesMatch) {
return cloneUnlessOtherwiseSpecified(source, options)
} else if (sourceIsArray) {
return options.arrayMerge(target, source, options)
} else {
return mergeObject(target, source, options)
}
}
deepmerge.all = function deepmergeAll(array, options) {
if (!Array.isArray(array)) {
throw new Error('first argument should be an array')
}
return array.reduce(function(prev, next) {
return deepmerge(prev, next, options)
}, {})
};
var deepmerge_1 = deepmerge;
/**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var REACT_STATICS$1 = {
childContextTypes: true,
contextTypes: true,
defaultProps: true,
displayName: true,
getDefaultProps: true,
getDerivedStateFromProps: true,
mixins: true,
propTypes: true,
type: true
};
var KNOWN_STATICS$1 = {
name: true,
length: true,
prototype: true,
caller: true,
callee: true,
arguments: true,
arity: true
};
var defineProperty$2 = Object.defineProperty;
var getOwnPropertyNames$1 = Object.getOwnPropertyNames;
var getOwnPropertySymbols$2 = Object.getOwnPropertySymbols;
var getOwnPropertyDescriptor$1 = Object.getOwnPropertyDescriptor;
var getPrototypeOf$2 = Object.getPrototypeOf;
var objectPrototype$1 = getPrototypeOf$2 && getPrototypeOf$2(Object);
function hoistNonReactStatics$1(targetComponent, sourceComponent, blacklist) {
if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components
if (objectPrototype$1) {
var inheritedComponent = getPrototypeOf$2(sourceComponent);
if (inheritedComponent && inheritedComponent !== objectPrototype$1) {
hoistNonReactStatics$1(targetComponent, inheritedComponent, blacklist);
}
}
var keys = getOwnPropertyNames$1(sourceComponent);
if (getOwnPropertySymbols$2) {
keys = keys.concat(getOwnPropertySymbols$2(sourceComponent));
}
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (!REACT_STATICS$1[key] && !KNOWN_STATICS$1[key] && (!blacklist || !blacklist[key])) {
var descriptor = getOwnPropertyDescriptor$1(sourceComponent, key);
try { // Avoid failures from read-only properties
defineProperty$2(targetComponent, key, descriptor);
} catch (e) {}
}
}
return targetComponent;
}
return targetComponent;
}
var hoistNonReactStatics_cjs$1 = hoistNonReactStatics$1;
var key = '__global_unique_id__';
var gud = function() {
return commonjsGlobal[key] = (commonjsGlobal[key] || 0) + 1;
};
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
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$1 = function emptyFunction() {};
emptyFunction$1.thatReturns = makeEmptyFunction;
emptyFunction$1.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction$1.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction$1.thatReturnsNull = makeEmptyFunction(null);
emptyFunction$1.thatReturnsThis = function () {
return this;
};
emptyFunction$1.thatReturnsArgument = function (arg) {
return arg;
};
var emptyFunction_1 = emptyFunction$1;
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var warning = emptyFunction_1;
var warning_1 = warning;
var implementation = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
var _react2 = _interopRequireDefault(React__default);
var _propTypes2 = _interopRequireDefault(propTypes);
var _gud2 = _interopRequireDefault(gud);
var _warning2 = _interopRequireDefault(warning_1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var MAX_SIGNED_31_BIT_INT = 1073741823;
// Inlined Object.is polyfill.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
function objectIs(x, y) {
if (x === y) {
return x !== 0 || 1 / x === 1 / y;
} else {
return x !== x && y !== y;
}
}
function createEventEmitter(value) {
var handlers = [];
return {
on: function on(handler) {
handlers.push(handler);
},
off: function off(handler) {
handlers = handlers.filter(function (h) {
return h !== handler;
});
},
get: function get() {
return value;
},
set: function set(newValue, changedBits) {
value = newValue;
handlers.forEach(function (handler) {
return handler(value, changedBits);
});
}
};
}
function onlyChild(children) {
return Array.isArray(children) ? children[0] : children;
}
function createReactContext(defaultValue, calculateChangedBits) {
var _Provider$childContex, _Consumer$contextType;
var contextProp = '__create-react-context-' + (0, _gud2.default)() + '__';
var Provider = function (_Component) {
_inherits(Provider, _Component);
function Provider() {
var _temp, _this, _ret;
_classCallCheck(this, Provider);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.emitter = createEventEmitter(_this.props.value), _temp), _possibleConstructorReturn(_this, _ret);
}
Provider.prototype.getChildContext = function getChildContext() {
var _ref;
return _ref = {}, _ref[contextProp] = this.emitter, _ref;
};
Provider.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (this.props.value !== nextProps.value) {
var oldValue = this.props.value;
var newValue = nextProps.value;
var changedBits = void 0;
if (objectIs(oldValue, newValue)) {
changedBits = 0; // No change
} else {
changedBits = typeof calculateChangedBits === 'function' ? calculateChangedBits(oldValue, newValue) : MAX_SIGNED_31_BIT_INT;
changedBits |= 0;
if (changedBits !== 0) {
this.emitter.set(nextProps.value, changedBits);
}
}
}
};
Provider.prototype.render = function render() {
return this.props.children;
};
return Provider;
}(React__default.Component);
Provider.childContextTypes = (_Provider$childContex = {}, _Provider$childContex[contextProp] = _propTypes2.default.object.isRequired, _Provider$childContex);
var Consumer = function (_Component2) {
_inherits(Consumer, _Component2);
function Consumer() {
var _temp2, _this2, _ret2;
_classCallCheck(this, Consumer);
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return _ret2 = (_temp2 = (_this2 = _possibleConstructorReturn(this, _Component2.call.apply(_Component2, [this].concat(args))), _this2), _this2.state = {
value: _this2.getValue()
}, _this2.onUpdate = function (newValue, changedBits) {
var observedBits = _this2.observedBits | 0;
if ((observedBits & changedBits) !== 0) {
_this2.setState({ value: _this2.getValue() });
}
}, _temp2), _possibleConstructorReturn(_this2, _ret2);
}
Consumer.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
var observedBits = nextProps.observedBits;
this.observedBits = observedBits === undefined || observedBits === null ? MAX_SIGNED_31_BIT_INT // Subscribe to all changes by default
: observedBits;
};
Consumer.prototype.componentDidMount = function componentDidMount() {
if (this.context[contextProp]) {
this.context[contextProp].on(this.onUpdate);
}
var observedBits = this.props.observedBits;
this.observedBits = observedBits === undefined || observedBits === null ? MAX_SIGNED_31_BIT_INT // Subscribe to all changes by default
: observedBits;
};
Consumer.prototype.componentWillUnmount = function componentWillUnmount() {
if (this.context[contextProp]) {
this.context[contextProp].off(this.onUpdate);
}
};
Consumer.prototype.getValue = function getValue() {
if (this.context[contextProp]) {
return this.context[contextProp].get();
} else {
return defaultValue;
}
};
Consumer.prototype.render = function render() {
return onlyChild(this.props.children)(this.state.value);
};
return Consumer;
}(React__default.Component);
Consumer.contextTypes = (_Consumer$contextType = {}, _Consumer$contextType[contextProp] = _propTypes2.default.object, _Consumer$contextType);
return {
Provider: Provider,
Consumer: Consumer
};
}
exports.default = createReactContext;
module.exports = exports['default'];
});
unwrapExports(implementation);
var lib = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
var _react2 = _interopRequireDefault(React__default);
var _implementation2 = _interopRequireDefault(implementation);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _react2.default.createContext || _implementation2.default;
module.exports = exports['default'];
});
var createContext = unwrapExports(lib);
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
/**
* 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);
}
/**
* 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;
}
/** 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;
}
/**
* 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;
}
/**
* 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;
/**
* 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);
}
/** 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')();
/** Built-in value references. */
var Symbol$1 = root.Symbol;
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$1 = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/** Built-in value references. */
var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined;
/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/
function getRawTag(value) {
var isOwn = hasOwnProperty$1.call(value, symToStringTag),
tag = value[symToStringTag];
try {
value[symToStringTag] = undefined;
} catch (e) {}
var result = nativeObjectToString.call(value);
{
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
/** Used for built-in method references. */
var objectProto$1 = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString$1 = objectProto$1.toString;
/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/
function objectToString(value) {
return nativeObjectToString$1.call(value);
}
/** `Object#toString` result references. */
var nullTag = '[object Null]',
undefinedTag = '[object Undefined]';
/** Built-in value references. */
var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined;
/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
if (value == null) {
return value === undefined ? undefinedTag : nullTag;
}
return (symToStringTag$1 && symToStringTag$1 in Object(value))
? getRawTag(value)
: objectToString(value);
}
/**
* 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');
}
/** `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;
}
/** Used to detect overreaching core-js shims. */
var coreJsData = root['__core-js_shared__'];
/** 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);
}
/** 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 '';
}
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for built-in method references. */
var funcProto$1 = Function.prototype,
objectProto$2 = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString$1 = funcProto$1.toString;
/** Used to check objects for own properties. */
var hasOwnProperty$2 = objectProto$2.hasOwnProperty;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString$1.call(hasOwnProperty$2).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/
function baseIsNative(value) {
if (!isObject(value) || isMasked(value)) {
return false;
}
var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
/**
* 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];
}
/**
* 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;
}
/* Built-in method references that are verified to be native. */
var Map$1 = getNative(root, 'Map');
/* Built-in method references that are verified to be native. */
var nativeCreate = getNative(Object, 'create');
/**
* 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;
}
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used for built-in method references. */
var objectProto$3 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$3 = objectProto$3.hasOwnProperty;
/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(key) {
var data = this.__data__;
if (nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty$3.call(data, key) ? data[key] : undefined;
}
/** Used for built-in method references. */
var objectProto$4 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$4 = objectProto$4.hasOwnProperty;
/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(key) {
var data = this.__data__;
return nativeCreate ? (data[key] !== undefined) : hasOwnProperty$4.call(data, key);
}
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/
function hashSet(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value;
return this;
}
/**
* 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;
/**
* 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$1 || ListCache),
'string': new Hash
};
}
/**
* 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);
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
/** 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$1 || (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;
}
/**
* 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;
/**
* A specialized version of `_.forEach` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
var defineProperty$3 = (function() {
try {
var func = getNative(Object, 'defineProperty');
func({}, '', {});
return func;
} catch (e) {}
}());
/**
* 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$3) {
defineProperty$3(object, key, {
'configurable': true,
'enumerable': true,
'value': value,
'writable': true
});
} else {
object[key] = value;
}
}
/** Used for built-in method references. */
var objectProto$5 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$5 = objectProto$5.hasOwnProperty;
/**
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignValue(object, key, value) {
var objValue = object[key];
if (!(hasOwnProperty$5.call(object, key) && eq(objValue, value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value);
}
}
/**
* 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;
}
/**
* 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;
}
/**
* 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';
}
/** `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;
}
/** Used for built-in method references. */
var objectProto$6 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$6 = objectProto$6.hasOwnProperty;
/** Built-in value references. */
var propertyIsEnumerable = objectProto$6.propertyIsEnumerable;
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
return isObjectLike(value) && hasOwnProperty$6.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$1 = Array.isArray;
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/
function stubFalse() {
return false;
}
/** 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;
/** 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);
}
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER$1 = 9007199254740991;
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1;
}
/** `Object#toString` result references. */
var argsTag$1 = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag$1 = '[object Function]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[funcTag$1] =
typedArrayTags[mapTag] = typedArrayTags[numberTag] =
typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
typedArrayTags[setTag] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag] = false;
/**
* The base implementation of `_.isTypedArray` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
*/
function baseIsTypedArray(value) {
return isObjectLike(value) &&
isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
}
/**
* 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);
};
}
/** Detect free variable `exports`. */
var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1;
/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports$1 && freeGlobal.process;
/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
try {
// Use `util.types` for Node.js 10+.
var types = freeModule$1 && freeModule$1.require && freeModule$1.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 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;
/** Used for built-in method references. */
var objectProto$7 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$7 = objectProto$7.hasOwnProperty;
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
var isArr = isArray$1(value),
isArg = !isArr && isArguments(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$7.call(value, key)) &&
!(skipIndexes && (
// Safari 9 has enumerable `arguments.length` in strict mode.
key == 'length' ||
// Node.js 0.10 has enumerable non-index properties on buffers.
(isBuff && (key == 'offset' || key == 'parent')) ||
// PhantomJS 2 has enumerable non-index properties on typed arrays.
(isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
// Skip index properties.
isIndex(key, length)
))) {
result.push(key);
}
}
return result;
}
/** Used for built-in method references. */
var objectProto$8 = Object.prototype;
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$8;
return value === proto;
}
/**
* 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));
};
}
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = overArg(Object.keys, Object);
/** Used for built-in method references. */
var objectProto$9 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$8 = objectProto$9.hasOwnProperty;
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!isPrototype(object)) {
return nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty$8.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
/**
* 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);
}
/**
* 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);
}
/**
* 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);
}
/**
* 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;
}
/** Used for built-in method references. */
var objectProto$a = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$9 = objectProto$a.hasOwnProperty;
/**
* The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeysIn(object) {
if (!isObject(object)) {
return nativeKeysIn(object);
}
var isProto = isPrototype(object),
result = [];
for (var key in object) {
if (!(key == 'constructor' && (isProto || !hasOwnProperty$9.call(object, key)))) {
result.push(key);
}
}
return result;
}
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn$1(object) {
return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(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$1(source), object);
}
/** Detect free variable `exports`. */
var freeExports$2 = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule$2 = freeExports$2 && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports$2 = freeModule$2 && freeModule$2.exports === freeExports$2;
/** Built-in value references. */
var Buffer$1 = moduleExports$2 ? root.Buffer : undefined,
allocUnsafe = Buffer$1 ? Buffer$1.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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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 [];
}
/** Used for built-in method references. */
var objectProto$b = Object.prototype;
/** Built-in value references. */
var propertyIsEnumerable$1 = objectProto$b.propertyIsEnumerable;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;
/**
* Creates an array of the own enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
if (object == null) {
return [];
}
object = Object(object);
return arrayFilter(nativeGetSymbols(object), function(symbol) {
return propertyIsEnumerable$1.call(object, symbol);
});
};
/**
* 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);
}
/**
* 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;
}
/** Built-in value references. */
var getPrototype = overArg(Object.getPrototypeOf, Object);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols$1 = Object.getOwnPropertySymbols;
/**
* Creates an array of the own and inherited enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbolsIn = !nativeGetSymbols$1 ? stubArray : function(object) {
var result = [];
while (object) {
arrayPush(result, getSymbols(object));
object = getPrototype(object);
}
return result;
};
/**
* 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);
}
/**
* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
* `keysFunc` and `symbolsFunc` to get the enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Function} keysFunc The function to get the keys of `object`.
* @param {Function} symbolsFunc The function to get the symbols of `object`.
* @returns {Array} Returns the array of property names and symbols.
*/
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray$1(object) ? result : arrayPush(result, symbolsFunc(object));
}
/**
* 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$1, getSymbolsIn);
}
/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView');
/* Built-in method references that are verified to be native. */
var Promise$1 = getNative(root, 'Promise');
/* Built-in method references that are verified to be native. */
var Set = getNative(root, 'Set');
/* Built-in method references that are verified to be native. */
var WeakMap$1 = getNative(root, 'WeakMap');
/** `Object#toString` result references. */
var mapTag$1 = '[object Map]',
objectTag$1 = '[object Object]',
promiseTag = '[object Promise]',
setTag$1 = '[object Set]',
weakMapTag$1 = '[object WeakMap]';
var dataViewTag$1 = '[object DataView]';
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
mapCtorString = toSource(Map$1),
promiseCtorString = toSource(Promise$1),
setCtorString = toSource(Set),
weakMapCtorString = toSource(WeakMap$1);
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
var getTag = baseGetTag;
// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag$1) ||
(Map$1 && getTag(new Map$1) != mapTag$1) ||
(Promise$1 && getTag(Promise$1.resolve()) != promiseTag) ||
(Set && getTag(new Set) != setTag$1) ||
(WeakMap$1 && getTag(new WeakMap$1) != weakMapTag$1)) {
getTag = function(value) {
var result = baseGetTag(value),
Ctor = result == objectTag$1 ? value.constructor : undefined,
ctorString = Ctor ? toSource(Ctor) : '';
if (ctorString) {
switch (ctorString) {
case dataViewCtorString: return dataViewTag$1;
case mapCtorString: return mapTag$1;
case promiseCtorString: return promiseTag;
case setCtorString: return setTag$1;
case weakMapCtorString: return weakMapTag$1;
}
}
return result;
};
}
var getTag$1 = getTag;
/** Used for built-in method references. */
var objectProto$c = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$a = objectProto$c.hasOwnProperty;
/**
* Initializes an array clone.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the initialized clone.
*/
function initCloneArray(array) {
var length = array.length,
result = new array.constructor(length);
// Add properties assigned by `RegExp#exec`.
if (length && typeof array[0] == 'string' && hasOwnProperty$a.call(array, 'index')) {
result.index = array.index;
result.input = array.input;
}
return result;
}
/** Built-in value references. */
var Uint8Array = root.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;
}
/**
* 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);
}
/** 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;
}
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol$1 ? Symbol$1.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)) : {};
}
/**
* 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);
}
/** `Object#toString` result references. */
var boolTag$1 = '[object Boolean]',
dateTag$1 = '[object Date]',
mapTag$2 = '[object Map]',
numberTag$1 = '[object Number]',
regexpTag$1 = '[object RegExp]',
setTag$2 = '[object Set]',
stringTag$1 = '[object String]',
symbolTag = '[object Symbol]';
var arrayBufferTag$1 = '[object ArrayBuffer]',
dataViewTag$2 = '[object DataView]',
float32Tag$1 = '[object Float32Array]',
float64Tag$1 = '[object Float64Array]',
int8Tag$1 = '[object Int8Array]',
int16Tag$1 = '[object Int16Array]',
int32Tag$1 = '[object Int32Array]',
uint8Tag$1 = '[object Uint8Array]',
uint8ClampedTag$1 = '[object Uint8ClampedArray]',
uint16Tag$1 = '[object Uint16Array]',
uint32Tag$1 = '[object Uint32Array]';
/**
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
*
* @private
* @param {Object} object The object to clone.
* @param {string} tag The `toStringTag` of the object to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneByTag(object, tag, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag$1:
return cloneArrayBuffer(object);
case boolTag$1:
case dateTag$1:
return new Ctor(+object);
case dataViewTag$2:
return cloneDataView(object, isDeep);
case float32Tag$1: case float64Tag$1:
case int8Tag$1: case int16Tag$1: case int32Tag$1:
case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1:
return cloneTypedArray(object, isDeep);
case mapTag$2:
return new Ctor;
case numberTag$1:
case stringTag$1:
return new Ctor(object);
case regexpTag$1:
return cloneRegExp(object);
case setTag$2:
return new Ctor;
case symbolTag:
return cloneSymbol(object);
}
}
/** 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;
};
}());
/**
* 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))
: {};
}
/** `Object#toString` result references. */
var mapTag$3 = '[object Map]';
/**
* The base implementation of `_.isMap` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
*/
function baseIsMap(value) {
return isObjectLike(value) && getTag$1(value) == mapTag$3;
}
/* 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;
/** `Object#toString` result references. */
var setTag$3 = '[object Set]';
/**
* The base implementation of `_.isSet` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
*/
function baseIsSet(value) {
return isObjectLike(value) && getTag$1(value) == setTag$3;
}
/* 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;
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
CLONE_FLAT_FLAG = 2,
CLONE_SYMBOLS_FLAG = 4;
/** `Object#toString` result references. */
var argsTag$2 = '[object Arguments]',
arrayTag$1 = '[object Array]',
boolTag$2 = '[object Boolean]',
dateTag$2 = '[object Date]',
errorTag$1 = '[object Error]',
funcTag$2 = '[object Function]',
genTag$1 = '[object GeneratorFunction]',
mapTag$4 = '[object Map]',
numberTag$2 = '[object Number]',
objectTag$2 = '[object Object]',
regexpTag$2 = '[object RegExp]',
setTag$4 = '[object Set]',
stringTag$2 = '[object String]',
symbolTag$1 = '[object Symbol]',
weakMapTag$2 = '[object WeakMap]';
var arrayBufferTag$2 = '[object ArrayBuffer]',
dataViewTag$3 = '[object DataView]',
float32Tag$2 = '[object Float32Array]',
float64Tag$2 = '[object Float64Array]',
int8Tag$2 = '[object Int8Array]',
int16Tag$2 = '[object Int16Array]',
int32Tag$2 = '[object Int32Array]',
uint8Tag$2 = '[object Uint8Array]',
uint8ClampedTag$2 = '[object Uint8ClampedArray]',
uint16Tag$2 = '[object Uint16Array]',
uint32Tag$2 = '[object Uint32Array]';
/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[argsTag$2] = cloneableTags[arrayTag$1] =
cloneableTags[arrayBufferTag$2] = cloneableTags[dataViewTag$3] =
cloneableTags[boolTag$2] = cloneableTags[dateTag$2] =
cloneableTags[float32Tag$2] = cloneableTags[float64Tag$2] =
cloneableTags[int8Tag$2] = cloneableTags[int16Tag$2] =
cloneableTags[int32Tag$2] = cloneableTags[mapTag$4] =
cloneableTags[numberTag$2] = cloneableTags[objectTag$2] =
cloneableTags[regexpTag$2] = cloneableTags[setTag$4] =
cloneableTags[stringTag$2] = cloneableTags[symbolTag$1] =
cloneableTags[uint8Tag$2] = cloneableTags[uint8ClampedTag$2] =
cloneableTags[uint16Tag$2] = cloneableTags[uint32Tag$2] = true;
cloneableTags[errorTag$1] = cloneableTags[funcTag$2] =
cloneableTags[weakMapTag$2] = false;
/**
* The base implementation of `_.clone` and `_.cloneDeep` which tracks
* traversed objects.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} bitmask The bitmask flags.
* 1 - Deep clone
* 2 - Flatten inherited properties
* 4 - Clone symbols
* @param {Function} [customizer] The function to customize cloning.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The parent object of `value`.
* @param {Object} [stack] Tracks traversed objects and their clone counterparts.
* @returns {*} Returns the cloned value.
*/
function baseClone(value, bitmask, customizer, key, object, stack) {
var result,
isDeep = bitmask & CLONE_DEEP_FLAG,
isFlat = bitmask & CLONE_FLAT_FLAG,
isFull = bitmask & CLONE_SYMBOLS_FLAG;
if (customizer) {
result = object ? customizer(value, key, object, stack) : customizer(value);
}
if (result !== undefined) {
return result;
}
if (!isObject(value)) {
return value;
}
var isArr = isArray$1(value);
if (isArr) {
result = initCloneArray(value);
if (!isDeep) {
return copyArray(value, result);
}
} else {
var tag = getTag$1(value),
isFunc = tag == funcTag$2 || tag == genTag$1;
if (isBuffer(value)) {
return cloneBuffer(value, isDeep);
}
if (tag == objectTag$2 || tag == argsTag$2 || (isFunc && !object)) {
result = (isFlat || isFunc) ? {} : initCloneObject(value);
if (!isDeep) {
return isFlat
? copySymbolsIn(value, baseAssignIn(result, value))
: copySymbols(value, baseAssign(result, value));
}
} else {
if (!cloneableTags[tag]) {
return object ? value : {};
}
result = initCloneByTag(value, tag, isDeep);
}
}
// Check for circular references and return its corresponding clone.
stack || (stack = new Stack);
var stacked = stack.get(value);
if (stacked) {
return stacked;
}
stack.set(value, result);
if (isSet(value)) {
value.forEach(function(subValue) {
result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
});
return result;
}
if (isMap(value)) {
value.forEach(function(subValue, key) {
result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
return result;
}
var keysFunc = isFull
? (isFlat ? getAllKeysIn : getAllKeys)
: (isFlat ? keysIn : keys);
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;
}
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG$1 = 1,
CLONE_SYMBOLS_FLAG$1 = 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$1 | CLONE_SYMBOLS_FLAG$1);
}
/**
* 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;
}
/** `Object#toString` result references. */
var symbolTag$2 = '[object Symbol]';
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && baseGetTag(value) == symbolTag$2);
}
/** 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$1(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$1.Cache || MapCache);
return memoized;
}
// Expose `MapCache`.
memoize$1.Cache = MapCache;
/** Used as the maximum memoize cache size. */
var MAX_MEMOIZE_SIZE = 500;
/**
* A specialized version of `_.memoize` which clears the memoized function's
* cache when it exceeds `MAX_MEMOIZE_SIZE`.
*
* @private
* @param {Function} func The function to have its output memoized.
* @returns {Function} Returns the new memoized function.
*/
function memoizeCapped(func) {
var result = memoize$1(func, function(key) {
if (cache.size === MAX_MEMOIZE_SIZE) {
cache.clear();
}
return key;
});
var cache = result.cache;
return result;
}
/** 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;
});
/** 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;
}
/** Used as references for various `Number` constants. */
var INFINITY$1 = 1 / 0;
/** Used to convert symbols to primitives and strings. */
var symbolProto$1 = Symbol$1 ? Symbol$1.prototype : undefined,
symbolToString = symbolProto$1 ? symbolProto$1.toString : undefined;
/**
* The base implementation of `_.toString` which doesn't convert nullish
* values to empty strings.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
// Exit early for strings to avoid a performance hit in some environments.
if (typeof value == 'string') {
return value;
}
if (isArray$1(value)) {
// Recursively convert values (susceptible to call stack limits).
return arrayMap(value, baseToString) + '';
}
if (isSymbol(value)) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result;
}
/**
* 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);
}
/**
* 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$1(value)) {
return arrayMap(value, toKey);
}
return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value)));
}
var _a;
var FormikProvider = (_a =
/*#__PURE__*/
createContext({}), _a.Provider),
FormikConsumer = _a.Consumer;
function connect(Comp) {
var C = function (props) {
return React.createElement(FormikConsumer, null, function (formik) {
return React.createElement(Comp, __assign({}, props, {
formik: formik
}));
});
};
var componentDisplayName = Comp.displayName || Comp.name || Comp.constructor && Comp.constructor.name || 'Component';
C.WrappedComponent = Comp;
C.displayName = "FormikConnect(" + componentDisplayName + ")";
return hoistNonReactStatics_cjs$1(C, Comp);
}
function getIn(obj, key, def, p) {
if (p === void 0) {
p = 0;
}
var path = toPath(key);
while (obj && p < path.length) {
obj = obj[path[p++]];
}
return obj === undefined ? def : obj;
}
function setIn(obj, path, value) {
var res = {};
var resVal = res;
var i = 0;
var pathArray = toPath(path);
for (; i < pathArray.length - 1; i++) {
var currentPath = pathArray[i];
var currentObj = getIn(obj, pathArray.slice(0, i + 1));
if (resVal[currentPath]) {
resVal = resVal[currentPath];
} else if (currentObj) {
resVal = resVal[currentPath] = cloneDeep(currentObj);
} else {
var nextPath = pathArray[i + 1];
resVal = resVal[currentPath] = isInteger(nextPath) && Number(nextPath) >= 0 ? [] : {};
}
}
if ((i === 0 ? obj : resVal)[pathArray[i]] === value) {
return obj;
}
if (value === undefined) {
delete resVal[pathArray[i]];
} else {
resVal[pathArray[i]] = value;
}
var result = __assign({}, obj, res);
if (i === 0 && value === undefined) {
delete result[pathArray[i]];
}
return result;
}
function setNestedObjectValues(object, value, visited, response) {
if (visited === void 0) {
visited = new WeakMap();
}
if (response === void 0) {
response = {};
}
for (var _i = 0, _a = Object.keys(object); _i < _a.length; _i++) {
var k = _a[_i];
var val = object[k];
if (isObject$1(val)) {
if (!visited.get(val)) {
visited.set(val, true);
response[k] = Array.isArray(val) ? [] : {};
setNestedObjectValues(val, value, visited, response[k]);
}
} else {
response[k] = value;
}
}
return response;
}
var isFunction$1 = function (obj) {
return typeof obj === 'function';
};
var isObject$1 = function (obj) {
return obj !== null && typeof obj === 'object';
};
var isInteger = function (obj) {
return String(Math.floor(Number(obj))) === obj;
};
var isString = function (obj) {
return Object.prototype.toString.call(obj) === '[object String]';
};
var isNaN$1 = function (obj) {
return obj !== obj;
};
var isEmptyChildren = function (children) {
return React.Children.count(children) === 0;
};
var isPromise = function (value) {
return isObject$1(value) && isFunction$1(value.then);
};
var isInputEvent = function (value) {
return value && isObject$1(value) && isObject$1(value.target);
};
function makeCancelable(promise) {
var hasCanceled = false;
var wrappedPromise = new Promise(function (resolve, reject) {
promise.then(function (val) {
return hasCanceled ? reject({
isCanceled: true
}) : resolve(val);
}, function (error) {
return hasCanceled ? reject({
isCanceled: true
}) : reject(error);
});
});
return [wrappedPromise, function cancel() {
hasCanceled = true;
}];
}
var Formik =
/*#__PURE__*/
function (_super) {
__extends(Formik, _super);
function Formik(props) {
var _this = _super.call(this, props) || this;
_this.hcCache = {};
_this.hbCache = {};
_this.registerField = function (name, Comp) {
_this.fields[name] = Comp;
};
_this.unregisterField = function (name) {
delete _this.fields[name];
};
_this.setErrors = function (errors) {
_this.setState({
errors: errors
});
};
_this.setTouched = function (touched) {
_this.setState({
touched: touched
}, function () {
if (_this.props.validateOnBlur) {
_this.runValidations(_this.state.values);
}
});
};
_this.setValues = function (values) {
_this.setState({
values: values
}, function () {
if (_this.props.validateOnChange) {
_this.runValidations(values);
}
});
};
_this.setStatus = function (status) {
_this.setState({
status: status
});
};
_this.setError = function (error) {
_this.setState({
error: error
});
};
_this.setSubmitting = function (isSubmitting) {
if (_this.didMount) {
_this.setState({
isSubmitting: isSubmitting
});
}
};
_this.validateField = function (field) {
_this.setState({
isValidating: true
});
return _this.runSingleFieldLevelValidation(field, getIn(_this.state.values, field)).then(function (error) {
if (_this.didMount) {
_this.setState({
errors: setIn(_this.state.errors, field, error),
isValidating: false
});
}
return error;
});
};
_this.runSingleFieldLevelValidation = function (field, value) {
return new Promise(function (resolve) {
return resolve(_this.fields[field].props.validate(value));
}).then(function (x) {
return x;
}, function (e) {
return e;
});
};
_this.runValidationSchema = function (values) {
return new Promise(function (resolve) {
var validationSchema = _this.props.validationSchema;
var schema = isFunction$1(validationSchema) ? validationSchema() : validationSchema;
validateYupSchema(values, schema).then(function () {
resolve({});
}, function (err) {
resolve(yupToFormErrors(err));
});
});
};
_this.runValidations = function (values) {
if (values === void 0) {
values = _this.state.values;
}
if (_this.validator) {
_this.validator();
}
var _a = makeCancelable(Promise.all([_this.runFieldLevelValidations(values), _this.props.validationSchema ? _this.runValidationSchema(values) : {}, _this.props.validate ? _this.runValidateHandler(values) : {}]).then(function (_a) {
var fieldErrors = _a[0],
schemaErrors = _a[1],
handlerErrors = _a[2];
return deepmerge_1.all([fieldErrors, schemaErrors, handlerErrors], {
arrayMerge: arrayMerge
});
})),
promise = _a[0],
cancel = _a[1];
_this.validator = cancel;
return promise.then(function (errors) {
if (_this.didMount) {
_this.setState(function (prevState) {
if (!reactFastCompare(prevState.errors, errors)) {
return {
errors: errors
};
}
return null;
});
}
return errors;
}).catch(function (x) {
return x;
});
};
_this.handleChange = function (eventOrPath) {
var executeChange = function (eventOrValue, maybePath) {
var field = maybePath;
var value;
if (isInputEvent(eventOrValue)) {
var event_1 = eventOrValue;
if (event_1.persist) {
event_1.persist();
}
var _a = event_1.target,
type = _a.type,
name_1 = _a.name,
id = _a.id,
checked = _a.checked,
outerHTML = _a.outerHTML;
field = maybePath ? maybePath : name_1 ? name_1 : id;
if (!field && 'production' !== 'production') {
warnAboutMissingIdentifier({
htmlContent: outerHTML,
documentationAnchorLink: 'handlechange-e-reactchangeeventany--void',
handlerName: 'handleChange'
});
}
value = event_1.target.value;
if (/number|range/.test(type)) {
var parsed = parseFloat(event_1.target.value);
value = isNaN$1(parsed) ? '' : parsed;
}
if (/checkbox/.test(type)) {
value = checked;
}
} else {
value = eventOrValue;
}
if (field) {
_this.setState(function (prevState) {
return __assign({}, prevState, {
values: setIn(prevState.values, field, value)
});
}, function () {
if (_this.props.validateOnChange) {
_this.runValidations(setIn(_this.state.values, field, value));
}
});
}
};
if (isString(eventOrPath)) {
var path_1 = eventOrPath;
if (!isFunction$1(_this.hcCache[path_1])) {
_this.hcCache[path_1] = function (eventOrValue) {
return executeChange(eventOrValue, path_1);
};
}
return _this.hcCache[path_1];
} else {
var event_2 = eventOrPath;
executeChange(event_2);
}
};
_this.setFieldValue = function (field, value, shouldValidate) {
if (shouldValidate === void 0) {
shouldValidate = true;
}
if (_this.didMount) {
_this.setState(function (prevState) {
return __assign({}, prevState, {
values: setIn(prevState.values, field, value)
});
}, function () {
if (_this.props.validateOnChange && shouldValidate) {
_this.runValidations(_this.state.values);
}
});
}
};
_this.handleSubmit = function (e) {
if (e && e.preventDefault) {
e.preventDefault();
}
_this.submitForm();
};
_this.submitForm = function () {
_this.setState(function (prevState) {
return {
touched: setNestedObjectValues(prevState.values, true),
isSubmitting: true,
isValidating: true,
submitCount: prevState.submitCount + 1
};
});
return _this.runValidations(_this.state.values).then(function (combinedErrors) {
if (_this.didMount) {
_this.setState({
isValidating: false
});
}
var isValid = Object.keys(combinedErrors).length === 0;
if (isValid) {
_this.executeSubmit();
} else if (_this.didMount) {
_this.setState({
isSubmitting: false
});
}
});
};
_this.executeSubmit = function () {
_this.props.onSubmit(_this.state.values, _this.getFormikActions());
};
_this.handleBlur = function (eventOrPath) {
var executeBlur = function (maybeEvent, maybePath) {
var field = maybePath;
if (isInputEvent(maybeEvent)) {
var event_3 = maybeEvent;
if (event_3.persist) {
event_3.persist();
}
var _a = event_3.target,
name_2 = _a.name,
id = _a.id,
outerHTML = _a.outerHTML;
field = name_2 ? name_2 : id;
if (!field && 'production' !== 'production') {
warnAboutMissingIdentifier({
htmlContent: outerHTML,
documentationAnchorLink: 'handleblur-e-reactfocuseventany--void',
handlerName: 'handleBlur'
});
}
}
_this.setState(function (prevState) {
return {
touched: setIn(prevState.touched, field, true)
};
});
if (_this.props.validateOnBlur) {
_this.runValidations(_this.state.values);
}
};
if (isString(eventOrPath)) {
var path_2 = eventOrPath;
if (!isFunction$1(_this.hbCache[path_2])) {
_this.hbCache[path_2] = function (event) {
return executeBlur(event, path_2);
};
}
return _this.hbCache[path_2];
} else {
var event_4 = eventOrPath;
executeBlur(event_4);
}
};
_this.setFieldTouched = function (field, touched, shouldValidate) {
if (touched === void 0) {
touched = true;
}
if (shouldValidate === void 0) {
shouldValidate = true;
}
_this.setState(function (prevState) {
return __assign({}, prevState, {
touched: setIn(prevState.touched, field, touched)
});
}, function () {
if (_this.props.validateOnBlur && shouldValidate) {
_this.runValidations(_this.state.values);
}
});
};
_this.setFieldError = function (field, message) {
_this.setState(function (prevState) {
return __assign({}, prevState, {
errors: setIn(prevState.errors, field, message)
});
});
};
_this.resetForm = function (nextValues) {
var values = nextValues ? nextValues : _this.props.initialValues;
_this.initialValues = values;
_this.setState({
isSubmitting: false,
isValidating: false,
errors: {},
touched: {},
error: undefined,
status: _this.props.initialStatus,
values: values,
submitCount: 0
});
};
_this.handleReset = function () {
if (_this.props.onReset) {
var maybePromisedOnReset = _this.props.onReset(_this.state.values, _this.getFormikActions());
if (isPromise(maybePromisedOnReset)) {
maybePromisedOnReset.then(_this.resetForm);
} else {
_this.resetForm();
}
} else {
_this.resetForm();
}
};
_this.setFormikState = function (s, callback) {
return _this.setState(s, callback);
};
_this.validateForm = function (values) {
_this.setState({
isValidating: true
});
return _this.runValidations(values).then(function (errors) {
if (_this.didMount) {
_this.setState({
isValidating: false
});
}
return errors;
});
};
_this.getFormikActions = function () {
return {
resetForm: _this.resetForm,
submitForm: _this.submitForm,
validateForm: _this.validateForm,
validateField: _this.validateField,
setError: _this.setError,
setErrors: _this.setErrors,
setFieldError: _this.setFieldError,
setFieldTouched: _this.setFieldTouched,
setFieldValue: _this.setFieldValue,
setStatus: _this.setStatus,
setSubmitting: _this.setSubmitting,
setTouched: _this.setTouched,
setValues: _this.setValues,
setFormikState: _this.setFormikState
};
};
_this.getFormikComputedProps = function () {
var isInitialValid = _this.props.isInitialValid;
var dirty = !reactFastCompare(_this.initialValues, _this.state.values);
return {
dirty: dirty,
isValid: dirty ? _this.state.errors && Object.keys(_this.state.errors).length === 0 : isInitialValid !== false && isFunction$1(isInitialValid) ? isInitialValid(_this.props) : isInitialValid,
initialValues: _this.initialValues
};
};
_this.getFormikBag = function () {
return __assign({}, _this.state, _this.getFormikActions(), _this.getFormikComputedProps(), {
registerField: _this.registerField,
unregisterField: _this.unregisterField,
handleBlur: _this.handleBlur,
handleChange: _this.handleChange,
handleReset: _this.handleReset,
handleSubmit: _this.handleSubmit,
validateOnChange: _this.props.validateOnChange,
validateOnBlur: _this.props.validateOnBlur
});
};
_this.getFormikContext = function () {
return __assign({}, _this.getFormikBag(), {
validationSchema: _this.props.validationSchema,
validate: _this.props.validate,
initialValues: _this.initialValues
});
};
_this.state = {
values: props.initialValues || {},
errors: {},
touched: {},
isSubmitting: false,
isValidating: false,
submitCount: 0,
status: props.initialStatus
};
_this.didMount = false;
_this.fields = {};
_this.initialValues = props.initialValues || {};
return _this;
}
Formik.prototype.componentDidMount = function () {
this.didMount = true;
};
Formik.prototype.componentWillUnmount = function () {
this.didMount = false;
if (this.validator) {
this.validator();
}
};
Formik.prototype.componentDidUpdate = function (prevProps) {
if (this.props.enableReinitialize && !reactFastCompare(prevProps.initialValues, this.props.initialValues)) {
this.initialValues = this.props.initialValues;
this.resetForm(this.props.initialValues);
}
};
Formik.prototype.runFieldLevelValidations = function (values) {
var _this = this;
var fieldKeysWithValidation = Object.keys(this.fields).filter(function (f) {
return _this.fields && _this.fields[f] && _this.fields[f].props.validate && isFunction$1(_this.fields[f].props.validate);
});
var fieldValidations = fieldKeysWithValidation.length > 0 ? fieldKeysWithValidation.map(function (f) {
return _this.runSingleFieldLevelValidation(f, getIn(values, f));
}) : [Promise.resolve('DO_NOT_DELETE_YOU_WILL_BE_FIRED')];
return Promise.all(fieldValidations).then(function (fieldErrorsList) {
return fieldErrorsList.reduce(function (prev, curr, index) {
if (curr === 'DO_NOT_DELETE_YOU_WILL_BE_FIRED') {
return prev;
}
if (!!curr) {
prev = setIn(prev, fieldKeysWithValidation[index], curr);
}
return prev;
}, {});
});
};
Formik.prototype.runValidateHandler = function (values) {
var _this = this;
return new Promise(function (resolve) {
var maybePromisedErrors = _this.props.validate(values);
if (maybePromisedErrors === undefined) {
resolve({});
} else if (isPromise(maybePromisedErrors)) {
maybePromisedErrors.then(function () {
resolve({});
}, function (errors) {
resolve(errors);
});
} else {
resolve(maybePromisedErrors);
}
});
};
Formik.prototype.render = function () {
var _a = this.props,
component = _a.component,
render = _a.render,
children = _a.children;
var props = this.getFormikBag();
var ctx = this.getFormikContext();
return React.createElement(FormikProvider, {
value: ctx
}, component ? React.createElement(component, props) : render ? render(props) : children ? isFunction$1(children) ? children(props) : !isEmptyChildren(children) ? React.Children.only(children) : null : null);
};
Formik.defaultProps = {
validateOnChange: true,
validateOnBlur: true,
isInitialValid: false,
enableReinitialize: false
};
return Formik;
}(React.Component);
function warnAboutMissingIdentifier(_a) {
var htmlContent = _a.htmlContent,
documentationAnchorLink = _a.documentationAnchorLink,
handlerName = _a.handlerName;
console.warn("Warning: Formik called `" + handlerName + "`, but you forgot to pass an `id` or `name` attribute to your input:\n\n " + htmlContent + "\n\n Formik cannot determine which value to update. For more info see https://github.com/jaredpalmer/formik#" + documentationAnchorLink + "\n ");
}
function yupToFormErrors(yupError) {
var errors = {};
if (yupError.inner.length === 0) {
return setIn(errors, yupError.path, yupError.message);
}
for (var _i = 0, _a = yupError.inner; _i < _a.length; _i++) {
var err = _a[_i];
if (!errors[err.path]) {
errors = setIn(errors, err.path, err.message);
}
}
return errors;
}
function validateYupSchema(values, schema, sync, context) {
if (sync === void 0) {
sync = false;
}
if (context === void 0) {
context = {};
}
var validateData = {};
for (var k in values) {
if (values.hasOwnProperty(k)) {
var key = String(k);
validateData[key] = values[key] !== '' ? values[key] : undefined;
}
}
return schema[sync ? 'validateSync' : 'validate'](validateData, {
abortEarly: false,
context: context
});
}
function arrayMerge(target, source, options) {
var destination = target.slice();
source.forEach(function (e, i) {
if (typeof destination[i] === 'undefined') {
var cloneRequested = options.clone !== false;
var shouldClone = cloneRequested && options.isMergeableObject(e);
destination[i] = shouldClone ? deepmerge_1(Array.isArray(e) ? [] : {}, e, options) : e;
} else if (options.isMergeableObject(e)) {
destination[i] = deepmerge_1(target[i], e, options);
} else if (target.indexOf(e) === -1) {
destination.push(e);
}
});
return destination;
}
var FieldInner =
/*#__PURE__*/
function (_super) {
__extends(FieldInner, _super);
function FieldInner(props) {
var _this = _super.call(this, props) || this;
var render = props.render,
children = props.children,
component = props.component;
return _this;
}
FieldInner.prototype.componentDidMount = function () {
this.props.formik.registerField(this.props.name, this);
};
FieldInner.prototype.componentDidUpdate = function (prevProps) {
if (this.props.name !== prevProps.name) {
this.props.formik.unregisterField(prevProps.name);
this.props.formik.registerField(this.props.name, this);
}
if (this.props.validate !== prevProps.validate) {
this.props.formik.registerField(this.props.name, this);
}
};
FieldInner.prototype.componentWillUnmount = function () {
this.props.formik.unregisterField(this.props.name);
};
FieldInner.prototype.render = function () {
var _a = this.props,
validate = _a.validate,
name = _a.name,
render = _a.render,
children = _a.children,
_b = _a.component,
component = _b === void 0 ? 'input' : _b,
formik = _a.formik,
props = __rest(_a, ["validate", "name", "render", "children", "component", "formik"]);
var _validate = formik.validate,
_validationSchema = formik.validationSchema,
restOfFormik = __rest(formik, ["validate", "validationSchema"]);
var field = {
value: props.type === 'radio' || props.type === 'checkbox' ? props.value : getIn(formik.values, name),
name: name,
onChange: formik.handleChange,
onBlur: formik.handleBlur
};
var bag = {
field: field,
form: restOfFormik
};
if (render) {
return render(bag);
}
if (isFunction$1(children)) {
return children(bag);
}
if (typeof component === 'string') {
var innerRef = props.innerRef,
rest = __rest(props, ["innerRef"]);
return React.createElement(component, __assign({
ref: innerRef
}, field, rest, {
children: children
}));
}
return React.createElement(component, __assign({}, bag, props, {
children: children
}));
};
return FieldInner;
}(React.Component);
var Field =
/*#__PURE__*/
connect(FieldInner);
var Form$1 =
/*#__PURE__*/
connect(function (_a) {
var _b = _a.formik,
handleReset = _b.handleReset,
handleSubmit = _b.handleSubmit,
props = __rest(_a, ["formik"]);
return React.createElement("form", __assign({
onReset: handleReset,
onSubmit: handleSubmit
}, props));
});
Form$1.displayName = 'Form';
var move = function (array, from, to) {
var copy = (array || []).slice();
var value = copy[from];
copy.splice(from, 1);
copy.splice(to, 0, value);
return copy;
};
var swap = function (array, indexA, indexB) {
var copy = (array || []).slice();
var a = copy[indexA];
copy[indexA] = copy[indexB];
copy[indexB] = a;
return copy;
};
var insert = function (array, index, value) {
var copy = (array || []).slice();
copy.splice(index, 0, value);
return copy;
};
var replace = function (array, index, value) {
var copy = (array || []).slice();
copy[index] = value;
return copy;
};
var FieldArrayInner =
/*#__PURE__*/
function (_super) {
__extends(FieldArrayInner, _super);
function FieldArrayInner(props) {
var _this = _super.call(this, props) || this;
_this.updateArrayField = function (fn, alterTouched, alterErrors) {
var _a = _this.props,
name = _a.name,
validateOnChange = _a.validateOnChange,
_b = _a.formik,
setFormikState = _b.setFormikState,
validateForm = _b.validateForm;
setFormikState(function (prevState) {
var updateErrors = typeof alterErrors === 'function' ? alterErrors : fn;
var updateTouched = typeof alterTouched === 'function' ? alterTouched : fn;
return __assign({}, prevState, {
values: setIn(prevState.values, name, fn(getIn(prevState.values, name))),
errors: alterErrors ? setIn(prevState.errors, name, updateErrors(getIn(prevState.errors, name))) : prevState.errors,
touched: alterTouched ? setIn(prevState.touched, name, updateTouched(getIn(prevState.touched, name))) : prevState.touched
});
}, function () {
if (validateOnChange) {
validateForm();
}
});
};
_this.push = function (value) {
return _this.updateArrayField(function (array) {
return (array || []).concat([cloneDeep(value)]);
}, false, false);
};
_this.handlePush = function (value) {
return function () {
return _this.push(value);
};
};
_this.swap = function (indexA, indexB) {
return _this.updateArrayField(function (array) {
return swap(array, indexA, indexB);
}, true, true);
};
_this.handleSwap = function (indexA, indexB) {
return function () {
return _this.swap(indexA, indexB);
};
};
_this.move = function (from, to) {
return _this.updateArrayField(function (array) {
return move(array, from, to);
}, true, true);
};
_this.handleMove = function (from, to) {
return function () {
return _this.move(from, to);
};
};
_this.insert = function (index, value) {
return _this.updateArrayField(function (array) {
return insert(array, index, value);
}, function (array) {
return insert(array, index, null);
}, function (array) {
return insert(array, index, null);
});
};
_this.handleInsert = function (index, value) {
return function () {
return _this.insert(index, value);
};
};
_this.replace = function (index, value) {
return _this.updateArrayField(function (array) {
return replace(array, index, value);
}, false, false);
};
_this.handleReplace = function (index, value) {
return function () {
return _this.replace(index, value);
};
};
_this.unshift = function (value) {
var length = -1;
_this.updateArrayField(function (array) {
var arr = array ? [value].concat(array) : [value];
if (length < 0) {
length = arr.length;
}
return arr;
}, function (array) {
var arr = array ? [null].concat(array) : [null];
if (length < 0) length = arr.length;
return arr;
}, function (array) {
var arr = array ? [null].concat(array) : [null];
if (length < 0) length = arr.length;
return arr;
});
return length;
};
_this.handleUnshift = function (value) {
return function () {
return _this.unshift(value);
};
};
_this.handleRemove = function (index) {
return function () {
return _this.remove(index);
};
};
_this.handlePop = function () {
return function () {
return _this.pop();
};
};
_this.remove = _this.remove.bind(_this);
_this.pop = _this.pop.bind(_this);
return _this;
}
FieldArrayInner.prototype.remove = function (index) {
var result;
this.updateArrayField(function (array) {
var copy = array ? array.slice() : [];
if (!result) {
result = copy[index];
}
if (isFunction$1(copy.splice)) {
copy.splice(index, 1);
}
return copy;
}, true, true);
return result;
};
FieldArrayInner.prototype.pop = function () {
var result;
this.updateArrayField(function (array) {
var tmp = array;
if (!result) {
result = tmp && tmp.pop && tmp.pop();
}
return tmp;
}, true, true);
return result;
};
FieldArrayInner.prototype.render = function () {
var arrayHelpers = {
push: this.push,
pop: this.pop,
swap: this.swap,
move: this.move,
insert: this.insert,
replace: this.replace,
unshift: this.unshift,
remove: this.remove,
handlePush: this.handlePush,
handlePop: this.handlePop,
handleSwap: this.handleSwap,
handleMove: this.handleMove,
handleInsert: this.handleInsert,
handleReplace: this.handleReplace,
handleUnshift: this.handleUnshift,
handleRemove: this.handleRemove
};
var _a = this.props,
component = _a.component,
render = _a.render,
children = _a.children,
name = _a.name,
_b = _a.formik,
_validate = _b.validate,
_validationSchema = _b.validationSchema,
restOfFormik = __rest(_b, ["validate", "validationSchema"]);
var props = __assign({}, arrayHelpers, {
form: restOfFormik,
name: name
});
return component ? React.createElement(component, props) : render ? render(props) : children ? typeof children === 'function' ? children(props) : !isEmptyChildren(children) ? React.Children.only(children) : null : null;
};
FieldArrayInner.defaultProps = {
validateOnChange: true
};
return FieldArrayInner;
}(React.Component);
var FieldArray =
/*#__PURE__*/
connect(FieldArrayInner);
var FastFieldInner =
/*#__PURE__*/
function (_super) {
__extends(FastFieldInner, _super);
function FastFieldInner(props) {
var _this = _super.call(this, props) || this;
var render = props.render,
children = props.children,
component = props.component;
return _this;
}
FastFieldInner.prototype.shouldComponentUpdate = function (props) {
if (this.props.shouldUpdate) {
return this.props.shouldUpdate(props, this.props);
} else if (getIn(this.props.formik.values, this.props.name) !== getIn(props.formik.values, this.props.name) || getIn(this.props.formik.errors, this.props.name) !== getIn(props.formik.errors, this.props.name) || getIn(this.props.formik.touched, this.props.name) !== getIn(props.formik.touched, this.props.name) || Object.keys(this.props).length !== Object.keys(props).length || this.props.formik.isSubmitting !== props.formik.isSubmitting) {
return true;
} else {
return false;
}
};
FastFieldInner.prototype.componentDidMount = function () {
this.props.formik.registerField(this.props.name, this);
};
FastFieldInner.prototype.componentDidUpdate = function (prevProps) {
if (this.props.name !== prevProps.name) {
this.props.formik.unregisterField(prevProps.name);
this.props.formik.registerField(this.props.name, this);
}
if (this.props.validate !== prevProps.validate) {
this.props.formik.registerField(this.props.name, this);
}
};
FastFieldInner.prototype.componentWillUnmount = function () {
this.props.formik.unregisterField(this.props.name);
};
FastFieldInner.prototype.render = function () {
var _a = this.props,
validate = _a.validate,
name = _a.name,
render = _a.render,
children = _a.children,
_b = _a.component,
component = _b === void 0 ? 'input' : _b,
formik = _a.formik,
shouldUpdate = _a.shouldUpdate,
props = __rest(_a, ["validate", "name", "render", "children", "component", "formik", "shouldUpdate"]);
var _validate = formik.validate,
_validationSchema = formik.validationSchema,
restOfFormik = __rest(formik, ["validate", "validationSchema"]);
var field = {
value: props.type === 'radio' || props.type === 'checkbox' ? props.value : getIn(formik.values, name),
name: name,
onChange: formik.handleChange,
onBlur: formik.handleBlur
};
var bag = {
field: field,
form: restOfFormik
};
if (render) {
return render(bag);
}
if (isFunction$1(children)) {
return children(bag);
}
if (typeof component === 'string') {
var innerRef = props.innerRef,
rest = __rest(props, ["innerRef"]);
return React.createElement(component, __assign({
ref: innerRef
}, field, rest, {
children: children
}));
}
return React.createElement(component, __assign({}, bag, props, {
children: children
}));
};
return FastFieldInner;
}(React.Component);
var FastField =
/*#__PURE__*/
connect(FastFieldInner);
var ErrorMessageImpl =
/*#__PURE__*/
function (_super) {
__extends(ErrorMessageImpl, _super);
function ErrorMessageImpl() {
return _super !== null && _super.apply(this, arguments) || this;
}
ErrorMessageImpl.prototype.shouldComponentUpdate = function (props) {
if (getIn(this.props.formik.errors, this.props.name) !== getIn(props.formik.errors, this.props.name) || getIn(this.props.formik.touched, this.props.name) !== getIn(props.formik.touched, this.props.name) || Object.keys(this.props).length !== Object.keys(props).length) {
return true;
} else {
return false;
}
};
ErrorMessageImpl.prototype.render = function () {
var _a = this.props,
component = _a.component,
formik = _a.formik,
render = _a.render,
children = _a.children,
name = _a.name,
rest = __rest(_a, ["component", "formik", "render", "children", "name"]);
var touch = getIn(formik.touched, name);
var error = getIn(formik.errors, name);
return !!touch && !!error ? render ? isFunction$1(render) ? render(error) : null : children ? isFunction$1(children) ? children(error) : null : component ? React.createElement(component, rest, error) : error : null;
};
return ErrorMessageImpl;
}(React.Component);
var ErrorMessage =
/*#__PURE__*/
connect(ErrorMessageImpl);
var FormikGroupContext = React__default.createContext();
var Field$1 = function Field$$1(_ref) {
var name = _ref.name,
className = _ref.className,
rest = objectWithoutProperties(_ref, ["name", "className"]);
var groupName = React.useContext(FormikGroupContext);
var groupId = React.useContext(FormGroup.Context);
var _useContext = React.useContext(FormContext),
layout = _useContext.layout;
var layoutClassName = layout ? "form__field--".concat(layout) : null;
return React__default.createElement(Field, _extends_1({
name: groupName ? groupName : name,
id: groupId,
className: classnames("form__field", layoutClassName, className)
}, rest));
};
var Error$1 = function Error(_ref2) {
var name = _ref2.name,
formik = _ref2.formik,
className = _ref2.className;
var groupName = React.useContext(FormikGroupContext);
var nameToUse = groupName ? groupName : name;
var error = getIn(formik.errors, nameToUse);
var touched = getIn(formik.touched, nameToUse) || formik.submitCount > 0; // workaround for issue https://github.com/jaredpalmer/formik/issues/738
return React__default.createElement(FormError, {
error: error,
touched: touched,
className: className
});
};
var handleFieldChange = function handleFieldChange(_ref3, newValue) {
var name = _ref3.field.name,
_ref3$form = _ref3.form,
setFieldValue = _ref3$form.setFieldValue,
setFieldTouched = _ref3$form.setFieldTouched,
onChange = _ref3.onChange;
setFieldValue(name, newValue);
setFieldTouched(name, true);
if (onChange) {
for (var _len = arguments.length, rest = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
rest[_key - 2] = arguments[_key];
}
onChange.apply(void 0, rest);
}
};
var Input$3 = function Input(props) {
var value = props.field.value,
form = props.form,
rest = objectWithoutProperties(props, ["field", "form"]);
return React__default.createElement(Input$2, _extends_1({}, rest, {
value: value,
onChange: function onChange(e) {
return handleFieldChange(props, e.target.value, e);
}
}));
};
var Checkbox$3 = function Checkbox(props) {
var value = props.field.value,
form = props.form,
rest = objectWithoutProperties(props, ["field", "form"]);
return React__default.createElement(Checkbox$2, _extends_1({}, rest, {
checked: value,
onChange: function onChange(e) {
return handleFieldChange(props, e.target.checked, e);
}
}));
};
var Radio$3 = function Radio(props) {
var value = props.field.value,
form = props.form,
rest = objectWithoutProperties(props, ["field", "form"]);
return React__default.createElement(Radio$2, _extends_1({}, rest, {
checked: value === props.value,
onChange: function onChange(e) {
return handleFieldChange(props, props.value, e);
}
}));
};
var Dropdown$2 = function Dropdown(props) {
var value = props.field.value,
form = props.form,
rest = objectWithoutProperties(props, ["field", "form"]);
return React__default.createElement(Dropdown$1, _extends_1({}, rest, {
value: value,
onChange: function onChange(e) {
if (Array.isArray(e)) {
var values = e.map(function (selection) {
return selection.value;
});
handleFieldChange(props, values, e);
} else {
handleFieldChange(props, e.value, e);
}
}
}));
};
function withFormik$1(BaseForm) {
var Form = function Form(_ref4) {
var _ref4$formikProps = _ref4.formikProps,
formikProps = _ref4$formikProps === void 0 ? {} : _ref4$formikProps,
children = _ref4.children,
rest = objectWithoutProperties(_ref4, ["formikProps", "children"]);
return React__default.createElement(BaseForm, rest, React__default.createElement(Formik, formikProps, children));
};
hoistNonReactStatics_cjs(Form, BaseForm);
Form.Group = function (_ref5) {
var name = _ref5.name,
children = _ref5.children,
rest = objectWithoutProperties(_ref5, ["name", "children"]);
return React__default.createElement(FormikGroupContext.Provider, {
value: name
}, React__default.createElement(BaseForm.Group, rest, children));
};
Form.Field = Field$1;
Form.Error = connect(Error$1);
Form.Input = Input$3;
Form.Checkbox = Checkbox$3;
Form.Dropdown = Dropdown$2;
Form.Radio = Radio$3;
return Form;
}
function _slicedToArray$2(arr, i) {
return _arrayWithHoles$2(arr) || _iterableToArrayLimit$2(arr, i) || _nonIterableRest$2();
}
function _arrayWithHoles$2(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit$2(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableRest$2() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
function _objectSpread$1$1(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === 'function') {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function (key) {
_defineProperty$1$1(target, key, source[key]);
});
}
return target;
}
function _defineProperty$1$1(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
} //@flow
const getPreviousEnabled = (currentPage
/*: number*/
) => currentPage > 0;
const getNextEnabled = (currentPage
/*: number*/
, totalPages
/*: number*/
) => currentPage + 1 < totalPages;
const getTotalPages = (totalItems
/*: number*/
, pageSize
/*: number*/
) => Math.ceil(totalItems / pageSize);
const getStartIndex = (pageSize
/*: number*/
, currentPage
/*: number*/
) => pageSize * currentPage;
const getEndIndex = (pageSize
/*: number*/
, currentPage
/*: number*/
, totalItems
/*: number*/
) => {
const lastPageEndIndex = pageSize * (currentPage + 1);
if (lastPageEndIndex > totalItems) {
return totalItems - 1;
}
return lastPageEndIndex - 1;
};
const getPaginationState = (_ref) => {
let totalItems = _ref.totalItems,
pageSize = _ref.pageSize,
currentPage = _ref.currentPage;
const totalPages = getTotalPages(totalItems, pageSize);
return {
totalPages,
startIndex: getStartIndex(pageSize, currentPage),
endIndex: getEndIndex(pageSize, currentPage, totalItems),
previousEnabled: getPreviousEnabled(currentPage),
nextEnabled: getNextEnabled(currentPage, totalPages)
};
};
/*:: type CurrentPageReducerActions = {| type: "SET", page: number |} | {| type: "NEXT" | "PREV" |};*/
function usePagination() {
let _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref2$totalItems = _ref2.totalItems,
totalItems = _ref2$totalItems === void 0 ? 0 : _ref2$totalItems,
_ref2$initialPage = _ref2.initialPage,
initialPage = _ref2$initialPage === void 0 ? 0 : _ref2$initialPage,
_ref2$initialPageSize = _ref2.initialPageSize,
initialPageSize = _ref2$initialPageSize === void 0 ? 0 : _ref2$initialPageSize;
const _React$useState = React.useState(initialPageSize),
_React$useState2 = _slicedToArray$2(_React$useState, 2),
pageSize = _React$useState2[0],
setPageSize = _React$useState2[1];
const _React$useReducer = React.useReducer(function () {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialPage;
let action = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
switch (action.type) {
case "SET":
return action.page;
case "NEXT":
if (!getNextEnabled(state, getTotalPages(totalItems, pageSize))) {
return state;
}
return state + 1;
case "PREV":
if (!getPreviousEnabled(state)) {
return state;
}
return state - 1;
default:
return state;
}
}, initialPage),
_React$useReducer2 = _slicedToArray$2(_React$useReducer, 2),
currentPage = _React$useReducer2[0],
dispatch = _React$useReducer2[1];
const paginationState = React.useMemo(() => getPaginationState({
totalItems,
pageSize,
currentPage
}), [totalItems, pageSize, currentPage]);
return _objectSpread$1$1({
setPage: React.useCallback((page
/*: number*/
) => {
dispatch({
type: "SET",
page
});
}, [dispatch]),
setNextPage: React.useCallback(() => {
dispatch({
type: "NEXT"
});
}, [dispatch]),
setPreviousPage: React.useCallback(() => {
dispatch({
type: "PREV"
});
}, [dispatch]),
setPageSize: React.useCallback(function (pageSize
/*: number*/
) {
let nextPage
/*:: ?: number*/
= arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
setPageSize(pageSize);
dispatch({
type: "SET",
page: nextPage
});
}, [setPageSize]),
currentPage,
pageSize,
totalItems
}, paginationState);
}
/*:: type PaginationProps = {|
children: ($Call<typeof usePagination>) => React.Node,
totalItems?: number,
initialPage?: number,
initialPageSize: number,
|};*/
function Pagination(_ref3) {
let children = _ref3.children,
_ref3$totalItems = _ref3.totalItems,
totalItems = _ref3$totalItems === void 0 ? 0 : _ref3$totalItems,
_ref3$initialPage = _ref3.initialPage,
initialPage = _ref3$initialPage === void 0 ? 0 : _ref3$initialPage,
initialPageSize = _ref3.initialPageSize;
return children(usePagination({
totalItems,
initialPage,
initialPageSize
}));
}
Pagination.displayName = "Pagination";
var PaginationPageLocation =
/*#__PURE__*/
function (_PureComponent) {
inherits(PaginationPageLocation, _PureComponent);
function PaginationPageLocation() {
classCallCheck(this, PaginationPageLocation);
return possibleConstructorReturn(this, getPrototypeOf(PaginationPageLocation).apply(this, arguments));
}
createClass(PaginationPageLocation, [{
key: "render",
value: function render() {
return React__default.createElement("span", {
className: "pagination__page-location"
}, this.props.startIndex + 1, " \u2013 ", this.props.endIndex + 1, " of ", this.props.totalItems);
}
}]);
return PaginationPageLocation;
}(React.PureComponent);
defineProperty(PaginationPageLocation, "displayName", "Pagination.PageLocation");
var PaginationPageSelector =
/*#__PURE__*/
function (_PureComponent) {
inherits(PaginationPageSelector, _PureComponent);
function PaginationPageSelector() {
var _getPrototypeOf2;
var _this;
classCallCheck(this, PaginationPageSelector);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = possibleConstructorReturn(this, (_getPrototypeOf2 = getPrototypeOf(PaginationPageSelector)).call.apply(_getPrototypeOf2, [this].concat(args)));
defineProperty(assertThisInitialized(_this), "handlePrevious", function () {
_this.callOnChange(String(_this.props.currentPage - 1));
});
defineProperty(assertThisInitialized(_this), "handleNext", function () {
_this.callOnChange(String(_this.props.currentPage + 1));
});
defineProperty(assertThisInitialized(_this), "sanitizeInput", function (draftPage) {
var val = parseInt(draftPage);
if (isNaN(val) || typeof val !== "number") {
val = 1;
} else if (val < 1) {
val = 1;
} else if (val > _this.props.totalPages) {
val = _this.props.totalPages;
}
return val;
});
defineProperty(assertThisInitialized(_this), "callOnChange", function (draftPage) {
_this.props.onChange(_this.sanitizeInput(draftPage));
});
defineProperty(assertThisInitialized(_this), "state", {
draftPage: "1",
editing: false
});
defineProperty(assertThisInitialized(_this), "handleEnterPage", function (e) {
return _this.setState({
draftPage: e.target.value,
editing: true
});
});
defineProperty(assertThisInitialized(_this), "handleKeyPress", function (e) {
if (e.key === "Enter") {
_this.handleBlur();
}
});
defineProperty(assertThisInitialized(_this), "handleBlur", function () {
_this.setState(function (_ref) {
var draftPage = _ref.draftPage;
_this.callOnChange(draftPage);
return {
editing: false
};
});
});
return _this;
}
createClass(PaginationPageSelector, [{
key: "render",
value: function render() {
return React__default.createElement("span", {
className: "pagination__page-selector"
}, React__default.createElement(IconButton, {
onClick: this.handlePrevious,
disabled: !this.props.previousEnabled
}, React__default.createElement("i", {
className: "aicon aicon__chevron-right",
style: PaginationPageSelector.rotatedButtonStyle
})), React__default.createElement("input", {
type: "text",
value: this.state.draftPage,
size: this.props.totalPages.toString().length,
onKeyPress: this.handleKeyPress,
onChange: this.handleEnterPage,
onBlur: this.handleBlur,
className: "form-control"
}), " ", "of ", this.props.totalPages, React__default.createElement(IconButton, {
onClick: this.handleNext,
disabled: !this.props.nextEnabled
}, React__default.createElement("i", {
className: "aicon aicon__chevron-right"
})));
}
}], [{
key: "getDerivedStateFromProps",
value: function getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.currentPage !== Number(prevState.draftPage) && !prevState.editing) {
return {
draftPage: String(nextProps.currentPage),
editing: false
};
}
return null;
}
}]);
return PaginationPageSelector;
}(React.PureComponent);
defineProperty(PaginationPageSelector, "displayName", "Pagination.PageSelector");
defineProperty(PaginationPageSelector, "rotatedButtonStyle", {
transform: "rotate(180deg)",
transformOrigin: "44% 40%"
});
var PaginationPageSize =
/*#__PURE__*/
function (_PureComponent) {
inherits(PaginationPageSize, _PureComponent);
function PaginationPageSize() {
var _getPrototypeOf2;
var _this;
classCallCheck(this, PaginationPageSize);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = possibleConstructorReturn(this, (_getPrototypeOf2 = getPrototypeOf(PaginationPageSize)).call.apply(_getPrototypeOf2, [this].concat(args)));
defineProperty(assertThisInitialized(_this), "handleChange", function (e) {
_this.props.onChange(parseInt(e.target.value, 10));
});
return _this;
}
createClass(PaginationPageSize, [{
key: "render",
value: function render() {
return React__default.createElement("span", {
className: "pagination__page-size"
}, React__default.createElement("span", {
className: "pagination__page-size__label"
}, "Items Per Page:"), " ", React__default.createElement("select", {
className: "form-control",
value: this.props.value,
onChange: this.handleChange
}, this.props.pageSizeChoices ? this.props.pageSizeChoices.map(function (size) {
return React__default.createElement("option", {
key: size,
value: size
}, size);
}) : null));
}
}]);
return PaginationPageSize;
}(React.PureComponent);
defineProperty(PaginationPageSize, "displayName", "Pagination.PageSize");
defineProperty(PaginationPageSize, "defaultProps", {
pageSizeChoices: [25, 50, 100]
});
Pagination.DefaultLayout = function (props) {
if (props.totalItems === 0) {
return null;
}
return React.createElement("div", {
className: "pagination pagination--default-layout"
}, React.createElement(PaginationPageLocation, {
startIndex: props.startIndex,
endIndex: props.endIndex,
totalItems: props.totalItems
}), React.createElement(PaginationPageSelector, {
currentPage: props.currentPage + 1,
totalPages: props.totalPages,
onChange: function onChange(page) {
return props.setPage(page - 1);
},
previousEnabled: props.previousEnabled,
nextEnabled: props.nextEnabled
}), React.createElement(PaginationPageSize, {
value: props.pageSize,
onChange: props.setPageSize,
pageSizeChoices: props.pageSizeChoices
}));
};
Pagination.PageSize = PaginationPageSize;
Pagination.PageSelector = PaginationPageSelector;
Pagination.PageLocation = PaginationPageLocation;
Pagination.usePagination = usePagination;
Pagination.getPaginationState = getPaginationState;
var Header = (function (props) {
var buttonGroup = props.buttonGroup,
children = props.children,
className = props.className,
productName = props.productName,
toggleCollapse = props.toggleCollapse,
rest = objectWithoutProperties(props, ["buttonGroup", "children", "className", "productName", "toggleCollapse"]);
return React.createElement("header", _extends_1({
className: classnames("shell__header", className)
}, rest), React.createElement("i", {
onClick: toggleCollapse,
className: "icon shell__header__close-button"
}), React.createElement("span", {
className: "shell__header__infa-logo",
title: "Informatica"
}), React.createElement("h1", {
className: "shell__header__product-name"
}, productName), children, buttonGroup ? React.createElement("span", {
className: "shell__header__button-group"
}, buttonGroup) : null);
});
var NavLink = (function (props) {
var as = props.as,
children = props.children,
className = props.className,
icon = props.icon,
label = props.label,
rest = objectWithoutProperties(props, ["as", "children", "className", "icon", "label"]);
var ElementType = props.as ? props.as : "a";
return React.createElement("li", null, React.createElement(ElementType, _extends_1({
className: classnames("shell__nav__links__link", className)
}, rest), icon ? React.createElement("span", {
className: "shell__nav__links__link__icon"
}, icon) : null, React.createElement("span", {
className: "shell__nav__links__link__label"
}, label), children));
});
var Nav = function Nav(props) {
var children = props.children,
className = props.className,
collapsed = props.collapsed,
rest = objectWithoutProperties(props, ["children", "className", "collapsed"]);
return React.createElement("nav", _extends_1({
className: classnames("shell__nav", {
"shell__nav--collapsed": collapsed
}, className)
}, rest), React.createElement("ul", {
className: "shell__nav__links"
}, children));
};
Nav.NavLink = NavLink;
var Main = React.forwardRef(function (props, ref) {
var children = props.children,
className = props.className,
rest = objectWithoutProperties(props, ["children", "className"]);
return React.createElement("main", _extends_1({
className: classnames("shell__main", className),
ref: ref
}, rest), children);
});
var renderPageTitle = function renderPageTitle(breadcrumbs, buttonGroup) {
return React.createElement("header", {
className: "shell__page__title"
}, React.createElement("ul", {
className: "shell__page__title__breadcrumbs"
}, breadcrumbs.map(function (breadcrumb, index) {
return React.createElement("li", {
key: index,
className: "shell__page__title__breadcrumbs__breadcrumb"
}, breadcrumb);
})), buttonGroup ? React.createElement("span", {
className: "button-group"
}, buttonGroup) : null);
};
var Page = function Page(props) {
var breadcrumbs = props.breadcrumbs,
buttonGroup = props.buttonGroup,
children = props.children,
rest = objectWithoutProperties(props, ["breadcrumbs", "buttonGroup", "children"]);
return React.createElement(React.Fragment, null, breadcrumbs ? renderPageTitle(breadcrumbs, buttonGroup) : null, React.createElement("div", _extends_1({
className: "shell__page__content"
}, rest), children));
};
var Shell =
/*#__PURE__*/
function (_React$Component) {
inherits(Shell, _React$Component);
function Shell() {
var _getPrototypeOf2;
var _this;
classCallCheck(this, Shell);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = possibleConstructorReturn(this, (_getPrototypeOf2 = getPrototypeOf(Shell)).call.apply(_getPrototypeOf2, [this].concat(args)));
defineProperty(assertThisInitialized(_this), "state", {
collapsed: false
});
defineProperty(assertThisInitialized(_this), "toggleCollapse", function (e) {
e.preventDefault();
_this.setState(function (state) {
return {
collapsed: !state.collapsed
};
});
});
return _this;
}
createClass(Shell, [{
key: "render",
value: function render() {
var _this2 = this;
var _this$props = this.props,
children = _this$props.children,
className = _this$props.className,
rest = objectWithoutProperties(_this$props, ["children", "className"]);
return React.createElement("div", _extends_1({
className: classnames("shell", {
"shell--collapsed": this.state.collapsed
}, className)
}, rest), React.Children.map(children, function (child) {
if (child.type === Header) {
return React.cloneElement(child, {
toggleCollapse: _this2.toggleCollapse
});
} else if (child.type === Nav) {
return React.cloneElement(child, {
collapsed: _this2.state.collapsed
});
} else {
return child;
}
}));
}
}]);
return Shell;
}(React.Component);
defineProperty(Shell, "Header", Header);
defineProperty(Shell, "Nav", Nav);
defineProperty(Shell, "Main", Main);
defineProperty(Shell, "Page", Page);
var hocList = {
first: ["withSubgrid", "withRowSelection"],
last: []
};
var rankHoc = function rankHoc(priority) {
return function (a, b) {
// Read the function's `name` property (must use named functions for this to be set)
var a_index = priority.indexOf(a.name || "");
var b_index = priority.indexOf(b.name || "");
if (a_index === -1 && b_index === -1) {
// If neither function is in the list, don't modify their position relative to each other
return 0;
} else if (a_index === -1) {
// If a isn't in the list by here, then b was, so it should go first
return 1;
} else if (b_index === -1) {
// Same as above but flipped
return -1;
} else {
// If both are in the list, then sort by whichever comes first
// keeping in mind that lower index is higher priority
return a_index - b_index;
}
};
};
var prioritizeHoc = function prioritizeHoc(a, b) {
var first_result = rankHoc(hocList.first)(a, b);
var last_result = rankHoc(hocList.last)(a, b);
if (last_result !== 0) return last_result;
if (first_result !== 0) return first_result * -1;
return 0;
};
var compose = function compose() {
for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) {
funcs[_key] = arguments[_key];
}
return funcs.sort(prioritizeHoc).reduce(function (a, b) {
return function () {
return a(b.apply(void 0, arguments));
};
}, function (arg) {
return arg;
});
};
var spreadProps = function spreadProps(BaseComponent) {
return function (props) {
return typeof BaseComponent === "function" ? BaseComponent(props) : React__default.createElement(BaseComponent, props);
};
};
var getRow = function getRow(target) {
var node = target;
while (node !== null) {
if (node.dataset.id) {
return node;
}
node = node.parentNode;
}
};
var dist = createCommonjsModule(function (module, exports) {
(function webpackUniversalModuleDefinition(root, factory) {
module.exports = factory();
})(typeof self !== 'undefined' ? self : commonjsGlobal, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 2);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
module.exports = React__default;
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.Constants = {
POPOVER_CONTAINER_CLASS_NAME: 'react-tiny-popover-container',
DEFAULT_PADDING: 6,
DEFAULT_WINDOW_PADDING: 6,
FADE_TRANSITION: 0.35,
DEFAULT_ARROW_COLOR: 'black',
DEFAULT_POSITIONS: ['top', 'left', 'right', 'bottom'],
EMPTY_CLIENT_RECT: {
top: 0,
left: 0,
bottom: 0,
height: 0,
right: 0,
width: 0,
},
};
exports.arrayUnique = function (array) { return array.filter(function (value, index, self) { return self.indexOf(value) === index; }); };
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(3);
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var React$$1 = __webpack_require__(0);
var react_dom_1 = __webpack_require__(4);
var util_1 = __webpack_require__(1);
var ArrowContainer_1 = __webpack_require__(5);
exports.ArrowContainer = ArrowContainer_1.ArrowContainer;
var Popover = /** @class */ (function (_super) {
__extends(Popover, _super);
function Popover() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.target = null;
_this.targetRect = null;
_this.targetPositionIntervalHandler = null;
_this.popoverDiv = null;
_this.positionOrder = null;
_this.willUnmount = false;
_this.willMount = false;
_this.onResize = function (e) {
_this.renderPopover();
};
_this.onClick = function (e) {
var _a = _this.props, onClickOutside = _a.onClickOutside, isOpen = _a.isOpen;
if (!_this.willUnmount && !_this.willMount && !_this.popoverDiv.contains(e.target) && !_this.target.contains(e.target) && onClickOutside && isOpen) {
onClickOutside(e);
}
};
return _this;
}
Popover.prototype.componentDidMount = function () {
var _this = this;
window.setTimeout(function () { return _this.willMount = false; });
var _a = this.props, position = _a.position, isOpen = _a.isOpen;
this.target = react_dom_1.findDOMNode(this);
this.positionOrder = this.getPositionPriorityOrder(position);
this.updatePopover(isOpen);
};
Popover.prototype.componentDidUpdate = function (prevProps) {
var prevIsOpen = prevProps.isOpen, prevPosition = prevProps.position, prevBody = prevProps.content;
var _a = this.props, isOpen = _a.isOpen, content = _a.content, position = _a.position;
this.positionOrder = this.getPositionPriorityOrder(this.props.position);
if (prevIsOpen !== isOpen || prevBody !== content || prevPosition !== position) {
this.updatePopover(isOpen);
}
};
Popover.prototype.componentWillMount = function () {
this.willUnmount = false;
this.willMount = true;
};
Popover.prototype.componentWillUnmount = function () {
this.willUnmount = true;
this.removePopover();
};
Popover.prototype.render = function () {
return this.props.children;
};
Popover.prototype.updatePopover = function (isOpen) {
if (isOpen) {
if (!this.popoverDiv || !this.popoverDiv.parentNode) {
var transitionDuration = this.props.transitionDuration;
this.popoverDiv = this.createContainer();
this.popoverDiv.style.opacity = '0';
this.popoverDiv.style.transition = "opacity " + (transitionDuration || util_1.Constants.FADE_TRANSITION) + "s";
window.document.body.appendChild(this.popoverDiv);
window.addEventListener('resize', this.onResize);
window.addEventListener('click', this.onClick);
}
this.renderPopover();
}
else if (this.popoverDiv && this.popoverDiv.parentNode) {
this.removePopover();
}
};
Popover.prototype.renderPopover = function (positionIndex) {
var _this = this;
if (positionIndex === void 0) { positionIndex = 0; }
if (positionIndex >= this.positionOrder.length) {
this.removePopover();
return;
}
this.renderWithPosition({ position: this.positionOrder[positionIndex], targetRect: this.target.getBoundingClientRect() }, function (violation, rect) {
var _a = _this.props, disableReposition = _a.disableReposition, contentLocation = _a.contentLocation;
if (violation && !disableReposition && !(typeof contentLocation === 'object')) {
_this.renderPopover(positionIndex + 1);
}
else {
var _b = _this.props, contentLocation_1 = _b.contentLocation, align = _b.align;
var _c = _this.getNudgedPopoverPosition(rect), nudgedTop = _c.top, nudgedLeft = _c.left;
var rectTop = rect.top, rectLeft = rect.left;
var position = _this.positionOrder[positionIndex];
var _d = disableReposition ? { top: rectTop, left: rectLeft } : { top: nudgedTop, left: nudgedLeft }, top_1 = _d.top, left = _d.left;
if (contentLocation_1) {
var targetRect = _this.target.getBoundingClientRect();
var popoverRect = _this.popoverDiv.firstChild.getBoundingClientRect();
(_e = typeof contentLocation_1 === 'function' ? contentLocation_1({ targetRect: targetRect, popoverRect: popoverRect, position: position, align: align, nudgedLeft: nudgedLeft, nudgedTop: nudgedTop }) : contentLocation_1, top_1 = _e.top, left = _e.left);
_this.popoverDiv.style.left = left.toFixed() + "px";
_this.popoverDiv.style.top = top_1.toFixed() + "px";
}
else {
var _f = [top_1 + window.pageYOffset, left + window.pageXOffset], absoluteTop = _f[0], absoluteLeft = _f[1];
_this.popoverDiv.style.left = absoluteLeft.toFixed() + "px";
_this.popoverDiv.style.top = absoluteTop.toFixed() + "px";
}
_this.popoverDiv.style.width = null;
_this.popoverDiv.style.height = null;
_this.renderWithPosition({
position: position,
nudgedTop: nudgedTop - rect.top,
nudgedLeft: nudgedLeft - rect.left,
targetRect: _this.target.getBoundingClientRect(),
popoverRect: _this.popoverDiv.firstChild.getBoundingClientRect(),
}, function () {
_this.startTargetPositionListener(10);
if (_this.popoverDiv.style.opacity !== '1') {
_this.popoverDiv.style.opacity = '1';
}
});
}
var _e;
});
};
Popover.prototype.startTargetPositionListener = function (checkInterval) {
var _this = this;
if (this.targetPositionIntervalHandler === null) {
this.targetPositionIntervalHandler = window.setInterval(function () {
var newTargetRect = _this.target.getBoundingClientRect();
if (_this.targetPositionHasChanged(_this.targetRect, newTargetRect)) {
_this.renderPopover();
}
_this.targetRect = newTargetRect;
}, checkInterval);
}
};
Popover.prototype.renderWithPosition = function (_a, callback) {
var _this = this;
var position = _a.position, _b = _a.nudgedLeft, nudgedLeft = _b === void 0 ? 0 : _b, _c = _a.nudgedTop, nudgedTop = _c === void 0 ? 0 : _c, _d = _a.targetRect, targetRect = _d === void 0 ? util_1.Constants.EMPTY_CLIENT_RECT : _d, _e = _a.popoverRect, popoverRect = _e === void 0 ? util_1.Constants.EMPTY_CLIENT_RECT : _e;
var _f = this.props, padding = _f.windowBorderPadding, content = _f.content, align = _f.align;
var getContent = function (args) {
return typeof content === 'function'
? content(args)
: content;
};
react_dom_1.unstable_renderSubtreeIntoContainer(this, getContent({ position: position, nudgedLeft: nudgedLeft, nudgedTop: nudgedTop, targetRect: targetRect, popoverRect: popoverRect, align: align }), this.popoverDiv, function () {
var targetRect = _this.target.getBoundingClientRect();
var popoverRect = _this.popoverDiv.firstChild.getBoundingClientRect();
var _a = _this.getLocationForPosition(position, targetRect, popoverRect), top = _a.top, left = _a.left;
callback(position === 'top' && top < padding ||
position === 'left' && left < padding ||
position === 'right' && left + popoverRect.width > window.innerWidth - padding ||
position === 'bottom' && top + popoverRect.height > window.innerHeight - padding, { width: popoverRect.width, height: popoverRect.height, top: top, left: left });
});
};
Popover.prototype.getNudgedPopoverPosition = function (_a) {
var top = _a.top, left = _a.left, width = _a.width, height = _a.height;
var padding = this.props.windowBorderPadding;
top = top < padding ? padding : top;
top = top + height > window.innerHeight - padding ? window.innerHeight - padding - height : top;
left = left < padding ? padding : left;
left = left + width > window.innerWidth - padding ? window.innerWidth - padding - width : left;
return { top: top, left: left };
};
Popover.prototype.removePopover = function () {
var _this = this;
if (this.popoverDiv) {
var transitionDuration = this.props.transitionDuration;
this.popoverDiv.style.opacity = '0';
var remove = function () {
if (_this.willUnmount || !_this.props.isOpen || !_this.popoverDiv.parentNode) {
window.clearInterval(_this.targetPositionIntervalHandler);
window.removeEventListener('resize', _this.onResize);
window.removeEventListener('click', _this.onClick);
_this.targetPositionIntervalHandler = null;
if (_this.popoverDiv.parentNode) {
_this.popoverDiv.parentNode.removeChild(_this.popoverDiv);
}
}
};
if (!this.willUnmount) {
window.setTimeout(remove, (transitionDuration || util_1.Constants.FADE_TRANSITION) * 1000);
}
else {
remove();
}
}
};
Popover.prototype.getPositionPriorityOrder = function (position) {
if (position && typeof position !== 'string') {
if (util_1.Constants.DEFAULT_POSITIONS.every(function (defaultPosition) { return position.find(function (p) { return p === defaultPosition; }) !== undefined; })) {
return util_1.arrayUnique(position);
}
else {
var remainingPositions = util_1.Constants.DEFAULT_POSITIONS.filter(function (defaultPosition) { return position.find(function (p) { return p === defaultPosition; }) === undefined; });
return util_1.arrayUnique(position.concat(remainingPositions));
}
}
else if (position && typeof position === 'string') {
var remainingPositions = util_1.Constants.DEFAULT_POSITIONS.filter(function (defaultPosition) { return defaultPosition !== position; });
return util_1.arrayUnique([position].concat(remainingPositions));
}
};
Popover.prototype.createContainer = function () {
var _a = this.props, containerStyle = _a.containerStyle, containerClassName = _a.containerClassName;
var container = window.document.createElement('div');
container.style.overflow = 'hidden';
if (containerStyle) {
Object.keys(containerStyle).forEach(function (key) { return container.style[key] = containerStyle[key]; });
}
container.className = containerClassName;
container.style.position = 'absolute';
container.style.top = '0';
container.style.left = '0';
return container;
};
Popover.prototype.getLocationForPosition = function (position, newTargetRect, popoverRect) {
var _a = this.props, padding = _a.padding, align = _a.align;
var targetMidX = newTargetRect.left + (newTargetRect.width / 2);
var targetMidY = newTargetRect.top + (newTargetRect.height / 2);
var top;
var left;
switch (position) {
case 'top':
top = newTargetRect.top - popoverRect.height - padding;
left = targetMidX - (popoverRect.width / 2);
if (align === 'start') {
left = newTargetRect.left;
}
if (align === 'end') {
left = newTargetRect.right - popoverRect.width;
}
break;
case 'left':
top = targetMidY - (popoverRect.height / 2);
left = newTargetRect.left - padding - popoverRect.width;
if (align === 'start') {
top = newTargetRect.top;
}
if (align === 'end') {
top = newTargetRect.bottom - popoverRect.height;
}
break;
case 'bottom':
top = newTargetRect.bottom + padding;
left = targetMidX - (popoverRect.width / 2);
if (align === 'start') {
left = newTargetRect.left;
}
if (align === 'end') {
left = newTargetRect.right - popoverRect.width;
}
break;
case 'right':
top = targetMidY - (popoverRect.height / 2);
left = newTargetRect.right + padding;
if (align === 'start') {
top = newTargetRect.top;
}
if (align === 'end') {
top = newTargetRect.bottom - popoverRect.height;
}
break;
}
return { top: top, left: left };
};
Popover.prototype.targetPositionHasChanged = function (oldTargetRect, newTargetRect) {
return oldTargetRect === null
|| oldTargetRect.left !== newTargetRect.left
|| oldTargetRect.top !== newTargetRect.top
|| oldTargetRect.width !== newTargetRect.width
|| oldTargetRect.height !== newTargetRect.height;
};
Popover.defaultProps = {
padding: util_1.Constants.DEFAULT_PADDING,
windowBorderPadding: util_1.Constants.DEFAULT_WINDOW_PADDING,
position: ['top', 'right', 'left', 'bottom'],
align: 'center',
containerClassName: util_1.Constants.POPOVER_CONTAINER_CLASS_NAME,
};
return Popover;
}(React$$1.Component));
exports.default = Popover;
/***/ }),
/* 4 */
/***/ (function(module, exports) {
module.exports = _reactDom;
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
var __assign = (this && this.__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;
};
Object.defineProperty(exports, "__esModule", { value: true });
var React$$1 = __webpack_require__(0);
var util_1 = __webpack_require__(1);
var ArrowContainer = function (_a) {
var position = _a.position, children = _a.children, style = _a.style, _b = _a.arrowColor, arrowColor = _b === void 0 ? util_1.Constants.DEFAULT_ARROW_COLOR : _b, _c = _a.arrowSize, arrowSize = _c === void 0 ? 10 : _c, arrowStyle = _a.arrowStyle, popoverRect = _a.popoverRect, targetRect = _a.targetRect;
return (React$$1.createElement("div", { style: __assign({ paddingLeft: position === 'right' ? arrowSize : 0, paddingTop: position === 'bottom' ? arrowSize : 0, paddingBottom: position === 'top' ? arrowSize : 0, paddingRight: position === 'left' ? arrowSize : 0 }, style) },
React$$1.createElement("div", { style: __assign({ position: 'absolute' }, (function () {
var arrowWidth = arrowSize * 2;
var top = (targetRect.top - popoverRect.top) + (targetRect.height / 2) - (arrowWidth / 2);
var left = (targetRect.left - popoverRect.left) + (targetRect.width / 2) - (arrowWidth / 2);
left = left < 0 ? 0 : left;
left = left + arrowWidth > popoverRect.width ? popoverRect.width - arrowWidth : left;
top = top < 0 ? 0 : top;
top = top + arrowWidth > popoverRect.height ? popoverRect.height - arrowWidth : top;
switch (position) {
case 'right':
return {
borderTop: arrowSize + "px solid transparent",
borderBottom: arrowSize + "px solid transparent",
borderRight: arrowSize + "px solid " + arrowColor,
left: 0,
top: top,
};
case 'left':
return {
borderTop: arrowSize + "px solid transparent",
borderBottom: arrowSize + "px solid transparent",
borderLeft: arrowSize + "px solid " + arrowColor,
right: 0,
top: top,
};
case 'bottom':
return {
borderLeft: arrowSize + "px solid transparent",
borderRight: arrowSize + "px solid transparent",
borderBottom: arrowSize + "px solid " + arrowColor,
top: 0,
left: left,
};
case 'top':
default:
return {
borderLeft: arrowSize + "px solid transparent",
borderRight: arrowSize + "px solid transparent",
borderTop: arrowSize + "px solid " + arrowColor,
bottom: 0,
left: left,
};
}
})(), arrowStyle) }),
children));
};
exports.ArrowContainer = ArrowContainer;
/***/ })
/******/ ]);
});
});
var Popover = unwrapExports(dist);
var isSubmenu = function isSubmenu(e) {
return e.target.classList.contains("menu__submenu");
};
var isDisabledItem = function isDisabledItem(e) {
return e.target.classList.contains("disabled");
};
var openMenu = function openMenu(open, setOpen, onChange) {
if (open) {
return;
}
setOpen(true);
if (onChange) {
onChange(true);
}
};
var closeMenu = function closeMenu(open, setOpen, onChange) {
if (!open) {
return;
}
setOpen(false);
if (onChange) {
onChange(false);
}
};
var toggleMenu = function toggleMenu(open, setOpen, onChange) {
if (open) {
closeMenu(open, setOpen, onChange);
} else {
openMenu(open, setOpen, onChange);
}
};
var MenuOpener = function MenuOpener(_ref) {
var children = _ref.children,
trigger = _ref.trigger,
open = _ref.open,
setOpen = _ref.setOpen,
onChange = _ref.onChange,
rest = objectWithoutProperties(_ref, ["children", "trigger", "open", "setOpen", "onChange"]);
// Close the menu when an item (not a submenu) is clicked.
var handleClick = React__default.useCallback(function (e) {
if (!isSubmenu(e) && !isDisabledItem(e)) {
closeMenu(open, setOpen, onChange);
}
}, [open, setOpen]);
return React__default.createElement(Popover, _extends_1({
isOpen: open,
containerClassName: "menu__container",
content: React__default.createElement("ul", {
className: "menu",
onClick: handleClick
}, children)
}, rest), trigger);
};
function MenuItem(_ref) {
var className = _ref.className,
children = _ref.children,
icon = _ref.icon,
disabled = _ref.disabled,
onClick = _ref.onClick,
rest = objectWithoutProperties(_ref, ["className", "children", "icon", "disabled", "onClick"]);
var handleClick = React__default.useCallback(function (e) {
if (!disabled && onClick) {
onClick(e);
}
}, [disabled, onClick]);
return React__default.createElement("li", _extends_1({
className: classnames("menu__item", disabled ? "disabled" : "", className),
onClick: handleClick
}, rest), children);
}
MenuItem.defaultProps = {
disabled: false
};
MenuItem.displayName = "Menu.Item";
function Submenu(_ref) {
var children = _ref.children,
label = _ref.label,
disabled = _ref.disabled;
var _React$useState = React.useState(false),
_React$useState2 = slicedToArray(_React$useState, 2),
open = _React$useState2[0],
setOpen = _React$useState2[1];
var ref = React.useRef(null); // Close the submenu if the mouse moves to another sibling.
var handleMouseMove = React.useCallback(function (e) {
var parentRect = ref.current.parentNode.parentNode.getBoundingClientRect();
var inSameMenu = e.clientX >= parentRect.left && e.clientX <= parentRect.left + parentRect.width && e.clientY >= parentRect.top && e.clientY <= parentRect.top + parentRect.height;
var rect = ref.current.getBoundingClientRect();
var inDiffItem = e.clientY < rect.top || e.clientY > rect.top + ref.current.clientHeight;
if (inSameMenu && inDiffItem) {
closeMenu(open, setOpen);
}
});
React.useEffect(function () {
if (open) {
window.addEventListener("mousemove", handleMouseMove);
}
return function () {
return window.removeEventListener("mousemove", handleMouseMove);
};
}, [open]);
return React.createElement(MenuOpener, {
open: open,
setOpen: setOpen,
position: ["right", "start"],
align: "start",
contentLocation: function contentLocation(_ref2) {
var targetRect = _ref2.targetRect,
popoverRect = _ref2.popoverRect,
position = _ref2.position,
align = _ref2.align,
nudgedLeft = _ref2.nudgedLeft,
nudgedTop = _ref2.nudgedTop;
var _window = window,
windowX = _window.scrollX,
windowY = _window.scrollY;
return {
top: nudgedTop + windowY - 11,
left: nudgedLeft - windowX
};
},
onClickOutside: function onClickOutside() {
return closeMenu(open, setOpen);
},
trigger: React.createElement("li", {
ref: ref,
className: "menu__item menu__submenu",
onClick: function onClick() {
return openMenu(open, setOpen);
},
onMouseEnter: function onMouseEnter() {
return openMenu(open, setOpen);
}
}, label, React.createElement("i", {
className: "menu__submenu-icon"
}))
}, children);
}
Submenu.displayName = "Menu.Submenu";
var MENU_FLIP_PADDING = 10;
var MENU_TRIGGER_GAP = 5;
function Menu(_ref) {
var children = _ref.children,
trigger = _ref.trigger,
context = _ref.context,
onBeforeShow = _ref.onBeforeShow,
onOpen = _ref.onOpen,
onClose = _ref.onClose;
var _React$useState = React.useState(false),
_React$useState2 = slicedToArray(_React$useState, 2),
open = _React$useState2[0],
setOpen = _React$useState2[1];
var _React$useState3 = React.useState(),
_React$useState4 = slicedToArray(_React$useState3, 2),
mousePoint = _React$useState4[0],
setMousePoint = _React$useState4[1];
var handleChange = React.useCallback(function (state) {
if (state) {
if (onOpen) {
onOpen();
}
} else {
if (onClose) {
onClose();
}
}
}, [onOpen, onClose]);
var handleClick = React.useCallback(function () {
toggleMenu(open, setOpen, handleChange);
}, [open, handleChange]); // Called when mouse click happens outside the menu.
var handleClickOutside = React.useCallback(function (e) {
if (!isSubmenu(e)) {
closeMenu(open, setOpen, handleChange);
}
}, [open, handleChange]);
var handleContextMenu = React.useCallback(function (e) {
if (typeof onBeforeShow === "function") {
onBeforeShow(e);
}
openMenu(open, setOpen, handleChange);
setMousePoint({
pageX: e.pageX,
pageY: e.pageY,
clientX: e.clientX,
clientY: e.clientY
});
e.preventDefault();
e.stopPropagation();
}, [open, handleChange, onBeforeShow]); // Detect contextmenu events happened outside the menu.
var handleContextMenuOutside = React.useCallback(function (e) {
return closeMenu(open, setOpen, handleChange);
}, [open, handleChange]); // Specify the position of the context menu.
var menuLocation = React.useCallback(function (_ref2) {
var targetRect = _ref2.targetRect,
popoverRect = _ref2.popoverRect,
position = _ref2.position,
align = _ref2.align,
nudgedLeft = _ref2.nudgedLeft,
nudgedTop = _ref2.nudgedTop;
if (context) {
var _top = mousePoint.pageY;
var left = mousePoint.pageX;
var _window = window,
windowWidth = _window.innerWidth,
windowHeight = _window.innerHeight;
if (mousePoint.clientX + popoverRect.width > windowWidth) {
left -= mousePoint.clientX + popoverRect.width - windowWidth + MENU_FLIP_PADDING;
}
if (mousePoint.clientY + popoverRect.height > windowHeight) {
_top -= mousePoint.clientY + popoverRect.height - windowHeight + MENU_FLIP_PADDING;
}
return {
top: _top,
left: left
};
}
var _window2 = window,
windowX = _window2.scrollX,
windowY = _window2.scrollY;
var top = nudgedTop + windowY;
if (position === "bottom") {
top -= MENU_TRIGGER_GAP;
} else if (position === "top") {
top += MENU_TRIGGER_GAP;
}
return {
top: top,
left: nudgedLeft + windowX
};
});
var wrappedTrigger = React.useMemo(function () {
var triggerProps;
if (context) {
triggerProps = {
onContextMenu: handleContextMenu
};
return React.cloneElement(trigger, objectSpread({}, triggerProps, {
"aria-haspopup": true,
"aria-expanded": open
}));
}
return React.createElement("span", {
className: "menu__trigger",
onClick: handleClick,
"aria-haspopup": true,
"aria-expanded": open
}, trigger);
}, [open, context, trigger, handleChange, handleContextMenu, handleClick]);
React.useEffect(function () {
window.addEventListener("contextmenu", handleContextMenuOutside);
return function () {
return window.removeEventListener("contextmenu", handleContextMenuOutside);
};
});
return React.createElement(MenuOpener, {
open: open,
setOpen: setOpen,
onChange: handleChange,
position: ["bottom", "top"],
align: "end",
onClickOutside: handleClickOutside,
trigger: wrappedTrigger,
contentLocation: menuLocation
}, children);
}
Menu.Item = MenuItem;
Menu.Submenu = Submenu;
Menu.Separator = function () {
return React.createElement("li", {
className: "menu__separator"
});
};
Menu.defaultProps = {
context: false
};
var withRowActions = (function () {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
renderRowActions = _ref.renderRowActions,
_ref$rowActionsWidth = _ref.rowActionsWidth,
rowActionsWidth = _ref$rowActionsWidth === void 0 ? "100px" : _ref$rowActionsWidth,
renderActionMenuItems = _ref.renderActionMenuItems;
/**
* Render the content of the row actions cell
*/
var renderRowActionsCell = function renderRowActionsCell(_ref2) {
var rowId = _ref2.rowId,
onMenuOpen = _ref2.onMenuOpen,
onMenuClose = _ref2.onMenuClose;
return React.createElement(React.Fragment, null, renderRowActions ? renderRowActions(rowId).map(function (action, index) {
return React.createElement(IconButton, {
key: index,
variant: "action",
onClick: action.handler
}, action.icon);
}) : null, renderActionMenuItems ? React.createElement(Menu, {
onOpen: onMenuOpen,
onClose: onMenuClose,
trigger: React.createElement(IconButton, {
variant: "action"
}, React.createElement("i", {
className: "row-actions-menu__trigger"
}))
}, renderActionMenuItems(rowId)) : null);
};
var rowActionsReducerDefaultState = {
// Track if the mouse has left the row while the menu is open so we can hide the actions when the menu is closed
mouseLeft: true,
// If the actions should be visible
visible: false,
// Track when the menu is open
menuOpen: false
};
var rowActionsReducer = function rowActionsReducer() {
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : rowActionsReducerDefaultState;
var action = arguments.length > 1 ? arguments[1] : undefined;
switch (action) {
case "OPEN_MENU":
return objectSpread({}, state, {
menuOpen: true
});
case "CLOSE_MENU":
return objectSpread({}, state, {
menuOpen: false,
// If the user's mouse isn't in the row when the menu is closed, hide the actions
visible: !state.mouseLeft
});
case "MOUSE_OVER":
return objectSpread({}, state, {
visible: true,
mouseLeft: false
});
case "MOUSE_OUT":
return objectSpread({}, state, {
visible: state.menuOpen,
mouseLeft: true
});
default:
return state;
}
};
return function withRowActions(BaseComponent) {
var Table = spreadProps(BaseComponent);
Table.displayName = "Table";
hoistNonReactStatics_cjs(Table, BaseComponent); // Add the cell spacer offset to the header
Table.HeaderRow = function (_ref3) {
var children = _ref3.children,
rest = objectWithoutProperties(_ref3, ["children"]);
return spreadProps(BaseComponent.HeaderRow)(objectSpread({}, rest, {
children: React.createElement(React.Fragment, null, children, React.createElement(Table.HeaderCell, {
key: "offset",
className: "table__header__cell--spacer",
style: {
width: rowActionsWidth
}
}))
}));
};
Table.HeaderRow.displayName = "Table.HeaderRow";
Table.Row = function (_ref4) {
var children = _ref4.children,
rest = objectWithoutProperties(_ref4, ["children"]);
var _React$useReducer = React.useReducer(rowActionsReducer, rowActionsReducerDefaultState),
_React$useReducer2 = slicedToArray(_React$useReducer, 2),
visible = _React$useReducer2[0].visible,
dispatch = _React$useReducer2[1];
var handleMenuOpen = React.useCallback(function () {
dispatch("OPEN_MENU");
}, [dispatch]);
var handleMenuClose = React.useCallback(function () {
dispatch("CLOSE_MENU");
}, [dispatch]);
var onMouseEnter = React.useCallback(function () {
dispatch("MOUSE_OVER");
}, [dispatch]);
var onMouseLeave = React.useCallback(function () {
dispatch("MOUSE_OUT");
}, [dispatch]);
var wrappedChildren = [children, React.createElement(Table.Cell, {
key: "actions",
className: "table__body__cell--row-actions"
}, visible ? renderRowActionsCell({
rowId: rest["data-id"],
onMenuClose: handleMenuClose,
onMenuOpen: handleMenuOpen
}) : null)];
return spreadProps(BaseComponent.Row)(objectSpread({}, rest, {
children: wrappedChildren,
onMouseEnter: onMouseEnter,
onMouseLeave: onMouseLeave
}));
};
Table.Row.displayName = "Table.Row";
return Table;
};
});
var withRowContextMenu = (function (_ref) {
var renderMenu = _ref.renderMenu;
return function withRowContextMenu(BaseComponent) {
// We always need to start by making a copy of the BaseComponent. If we aren't customizing it,
// we can just forward the props directly:
var Table = spreadProps(BaseComponent);
Table.displayName = "Table"; // hoist helps us copy the statics of the Table component (Table.Header, Table.Cell, etc.) to the new component
hoistNonReactStatics_cjs(Table, BaseComponent);
Table.Body = function (_ref2) {
var rest = _extends_1({}, _ref2);
var _React$useState = React.useState(null),
_React$useState2 = slicedToArray(_React$useState, 2),
rowId = _React$useState2[0],
setRowId = _React$useState2[1];
var renderMenuItems = React.useMemo(function () {
return renderMenu(rowId);
});
var onBeforeShow = React.useCallback(function (e) {
setRowId(getRow(e.target).dataset.id);
});
return React.createElement(Menu, {
context: true,
trigger: React.createElement(BaseComponent.Body, rest),
onBeforeShow: onBeforeShow
}, renderMenuItems);
};
Table.Body.displayName = "Table.Body"; // Always return the new Table component at the end
return Table;
};
});
// import React from "react";
function withInlineEdit(BaseComponent) {
var Table = spreadProps(BaseComponent);
Table.displayName = "Table";
hoistNonReactStatics_cjs(Table, BaseComponent);
return Table;
}
var withRowSelection = (function () {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref$getRowIds = _ref.getRowIds,
getRowIds = _ref$getRowIds === void 0 ? function () {
return [];
} : _ref$getRowIds;
function rowSelectionReducer() {
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getRowIds().reduce(function (accum, rowId) {
accum[rowId] = false;
return accum;
}, {});
var action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case "SELECT_ROW":
// Don't modify the state if the id is already selected
if (state[action.id]) return state;
return objectSpread({}, action.state ? action.state : state, defineProperty({}, action.id, true));
case "DESELECT_ROW":
// Don't modify the state if the key is already unselected
if (!state[action.id]) return state;
return objectSpread({}, action.state ? action.state : state, defineProperty({}, action.id, false));
case "TOGGLE_ROW":
var nextState = objectSpread({}, action.state ? action.state : state);
return objectSpread({}, nextState, defineProperty({}, action.id, !nextState[action.id]));
case "SELECT_ALL_ROWS":
return action.ids.reduce(function (accum, id) {
accum[id] = true;
return accum;
}, {});
case "DESELECT_ALL_ROWS":
if (Object.keys(state).length === 0) return state;
return objectSpread({}, action.state ? action.state : {});
default:
return state;
}
}
var RowSelection = React__default.createContext({});
return function withRowSelection(BaseComponent) {
var Table = function Table(props) {
var _props$store = slicedToArray(props.store, 2),
rowSelection = _props$store[0].rowSelection,
dispatch = _props$store[1];
return React__default.createElement(RowSelection.Provider, {
value: {
rowSelection: rowSelection,
dispatch: dispatch
}
}, spreadProps(BaseComponent)(props));
};
Table.displayName = "Table";
hoistNonReactStatics_cjs(Table, BaseComponent);
Table.HeaderRow = function (_ref2) {
var children = _ref2.children,
rest = objectWithoutProperties(_ref2, ["children"]);
return spreadProps(BaseComponent.HeaderRow)(objectSpread({}, rest, {
children: React__default.createElement(React__default.Fragment, null, React__default.createElement(BaseComponent.HeaderCell, {
className: "table__header__cell--spacer"
}), children)
}));
};
Table.HeaderRow.displayName = "Table.HeaderRow";
Table.Row = function (_ref3) {
var children = _ref3.children,
rest = objectWithoutProperties(_ref3, ["children"]);
var _useContext = React.useContext(RowSelection),
rowSelection = _useContext.rowSelection,
dispatch = _useContext.dispatch;
var handleChange = React.useCallback(function (e) {
dispatch({
type: e.target.checked ? "SELECT_ROW" : "DESELECT_ROW",
id: rest["data-id"]
});
});
var selected = !!rowSelection[rest["data-id"]];
return spreadProps(BaseComponent.Row)(objectSpread({}, rest, {
children: [React__default.createElement(Table.Cell, {
key: "checkbox"
}, React__default.createElement(Checkbox$1, {
onChange: handleChange,
checked: selected
})), children]
}));
};
Table.Row.displayName = "Table.Row";
Table.reducer = function () {
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var action = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return objectSpread({}, BaseComponent.reducer(state, action), {
rowSelection: rowSelectionReducer(state.rowSelection, action)
});
};
return Table;
};
});
var columnResizer = createCommonjsModule(function (module, exports) {
!function(e,t){module.exports=t();}(commonjsGlobal,function(){return function(r){var i={};function __webpack_require__(e){if(i[e])return i[e].exports;var t=i[e]={i:e,l:!1,exports:{}};return r[e].call(t.exports,t,t.exports,__webpack_require__),t.l=!0,t.exports}return __webpack_require__.m=r,__webpack_require__.c=i,__webpack_require__.d=function(e,t,r){__webpack_require__.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r});},__webpack_require__.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0});},__webpack_require__.t=function(t,e){if(1&e&&(t=__webpack_require__(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(__webpack_require__.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)__webpack_require__.d(r,i,function(e){return t[e]}.bind(null,i));return r},__webpack_require__.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return __webpack_require__.d(t,"a",t),t},__webpack_require__.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},__webpack_require__.p="/",__webpack_require__(__webpack_require__.s=1)}([function(e,t,r){e.exports=function(e){for(var t=5381,r=e.length;r;)t=33*t^e.charCodeAt(--r);return t>>>0};},function(e,t,r){r.r(t),r.d(t,"default",function(){return l});var i=r(0),n=r.n(i);function _defineProperty(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var o,s=(o=0,function(){return o++}),l=function ColumnResizer(e){var c=this,t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,ColumnResizer),_defineProperty(this,"ID","id"),_defineProperty(this,"PX","px"),_defineProperty(this,"RESIZABLE","grip-resizable"),_defineProperty(this,"FLEX","grip-flex"),_defineProperty(this,"legacyIE",0<navigator.userAgent.indexOf("Trident/4.0")),_defineProperty(this,"reset",function(e){return c.init(e)}),_defineProperty(this,"onResize",function(){var e=c.tb;if(e.classList.remove(c.RESIZABLE),e.opt.fixed){e.tableWidth=Number(window.getComputedStyle(e).width.replace(/px/,"")).valueOf();for(var t=0,r=0;r<e.columnCnt;r++)t+=e.columns[r].w;for(var i=0;i<e.columnCnt;i++)e.columns[i].style.width=Math.round(1e3*e.columns[i].w/t)/10+"%",e.columns[i].locked=!0;}else c.applyBounds(),"flex"===e.opt.resizeMode&&e.opt.serialize&&c.serializeStore();e.classList.add(c.RESIZABLE),c.syncGrips();}),_defineProperty(this,"onGripMouseDown",function(e){var t=e.target.parentNode.data,r=c.tb,i=r.grips[t.i],o=e.touches;if(i.ox=o?o[0].pageX:e.pageX,i.l=i.offsetLeft,i.x=i.l,c.createStyle(document.querySelector("head"),"*{cursor:"+r.opt.dragCursor+"!important}"),document.addEventListener("touchmove",c.onGripDrag),document.addEventListener("mousemove",c.onGripDrag),document.addEventListener("touchend",c.onGripDragOver),document.addEventListener("mouseup",c.onGripDragOver),i.classList.add(r.opt.draggingClass),c.grip=i,r.columns[t.i].locked)for(var n,l=0;l<r.columnCnt;l++)(n=r.columns[l]).locked=!1,n.w=Number(window.getComputedStyle(n).width.replace(/px/,"")).valueOf();e.preventDefault();}),_defineProperty(this,"onGripDrag",function(e){var t=c.grip;if(t){var r=t.t,i=e.touches,o=(i?i[0].pageX:e.pageX)-t.ox+t.l,n=r.opt.minWidth,l=t.i,a=1.5*r.cellSpace+n+r.borderSpace,s=l===r.columnCnt-1,d=l?r.grips[l-1].offsetLeft+r.cellSpace+n:a,p=r.opt.fixed?l===r.columnCnt-1?r.tableWidth-a:r.grips[l+1].offsetLeft-r.cellSpace-n:1/0;if(o=Math.max(d,Math.min(p,o)),t.x=o,t.style.left=o+c.PX,s&&(t.w=r.columns[l].w+o-t.l),r.opt.liveDrag){s?(r.columns[l].style.width=t.w+c.PX,!r.opt.fixed&&r.opt.overflow?r.style.minWidth=r.tableWidth+o-t.l+c.PX:r.tableWidth=Number(window.getComputedStyle(r).width.replace(/px/,"")).valueOf()):c.syncCols(r,l,!1,r.opt),c.syncGrips();var u=r.opt.onDrag;u&&u(e);}e.preventDefault();}}),_defineProperty(this,"onGripDragOver",function(e){var t=c.grip;document.removeEventListener("touchend",c.onGripDragOver),document.removeEventListener("mouseup",c.onGripDragOver),document.removeEventListener("touchmove",c.onGripDrag),document.removeEventListener("mousemove",c.onGripDrag);var r=document.querySelector("head").lastChild;if(r.parentNode.removeChild(r),t){if(t.classList.remove(t.t.opt.draggingClass),t.x-t.l!=0){var i=t.t,o=i.opt.onResize,n=t.i;if(n===i.columnCnt-1){var l=i.columns[n];l.style.width=t.w+c.PX,l.w=t.w;}else c.syncCols(i,n,!0,i.opt);i.opt.fixed||c.applyBounds(),c.syncGrips(),o&&o(e),i.opt.serialize&&c.serializeStore();}c.grip=null;}}),_defineProperty(this,"init",function(e){if(e.disable)return c.destroy();var t=c.tb,r=t.getAttribute(c.ID)||c.RESIZABLE+s();if(!t.matches("table")||t.extended&&!e.partialRefresh)return null;var i=document.querySelector("head");if(c.createStyle(i," .grip-resizable{table-layout:fixed;} .grip-resizable > tbody > tr > td, .grip-resizable > tbody > tr > th{overflow:hidden} .grip-padding > tbody > tr > td, .grip-padding > tbody > tr > th{padding-left:0!important; padding-right:0!important;} .grip-container{ height:0px; position:relative;} .grip-handle{margin-left:-5px; position:absolute; z-index:5; } .grip-handle .grip-resizable{position:absolute;background-color:red;filter:alpha(opacity=1);opacity:0;width:10px;height:100%;cursor: col-resize;top:0px} .grip-lastgrip{position:absolute; width:1px; } .grip-drag{ border-left:1px dotted black;\t} .grip-flex{width:auto!important;} .grip-handle.grip-disabledgrip .grip-resizable{cursor:default; display:none;}"),e.hoverCursor&&"col-resize"!==e.hoverCursor){var o=".grip-handle .grip-resizable:hover{cursor:"+e.hoverCursor+"!important}";c.createStyle(i,o);}t.setAttribute(c.ID,r);var n=t.opt;t.opt=c.extendOptions(e);var l=c.getTableHeaders(t);if(c.extendTable(l),e.remoteTable&&e.remoteTable.matches("table")){var a=c.getTableHeaders(t.opt.remoteTable);l.length===a.length?c.extendRemoteTable(t.opt.remoteTable,a,t):console.warn("column count for remote table did not match");}return n}),_defineProperty(this,"applyBounds",function(){var e=c.tb,r=e.columns.map(function(e){return window.getComputedStyle(e).width});e.style.width=window.getComputedStyle(e).width,e.tableWidth=Number(e.style.width.replace(/px/,"")).valueOf(),e.classList.remove(c.FLEX),e.columns.forEach(function(e,t){e.style.width=r[t],e.w=Number(r[t].replace(/px/,"")).valueOf();}),e.classList.add(c.FLEX);}),_defineProperty(this,"serializeStore",function(){var e=c.store,t=c.tb;e[t.getAttribute(c.ID)]="";for(var r=0,i=0;i<t.columns.length;i++){var o=window.getComputedStyle(t.columns[i]).width.replace(/px/,"");e[t.getAttribute(c.ID)]+=o+";",r+=Number(o).valueOf();}e[t.getAttribute(c.ID)]+=r.toString(),t.opt.fixed||(e[t.getAttribute(c.ID)]+=";"+window.getComputedStyle(t).width.replace(/px/,""));}),_defineProperty(this,"syncGrips",function(){var e=c.tb;e.gripContainer.style.width=e.tableWidth+c.PX;for(var t=0;t<e.columnCnt;t++){var r=e.columns[t],i=r.getBoundingClientRect(),o=e.getBoundingClientRect();e.grips[t].style.left=i.left-o.left+r.offsetWidth+e.cellSpace/2+c.PX,e.grips[t].style.height=(e.opt.headerOnly?e.columns[0].offsetHeight:e.offsetHeight)+c.PX;}}),_defineProperty(this,"destroy",function(){var e=c.tb,t=e.getAttribute(c.ID);return t?(c.store[t]="",e.classList.remove(c.RESIZABLE),e.classList.remove(c.FLEX),e.remote&&(e.remote.classList.remove(c.RESIZABLE),e.remote.classList.remove(c.FLEX)),e.gripContainer&&e.gripContainer.parentNode&&e.gripContainer.parentNode.removeChild(e.gripContainer),delete e.extended,e.opt):null}),_defineProperty(this,"createStyle",function(e,t){var r=n()(t).toString(),i=e.querySelectorAll("style");if(!Array.from(i).filter(function(e){return e.gripid===r}).length){var o=document.createElement("style");o.type="text/css",o.gripid=r,o.styleSheet?o.styleSheet.cssText=t:o.appendChild(document.createTextNode(t)),e.appendChild(o);}}),_defineProperty(this,"extendOptions",function(e){var t=Object.assign({},ColumnResizer.DEFAULTS,e);switch(t.fixed=!0,t.overflow=!1,t.resizeMode){case"flex":t.fixed=!1;break;case"overflow":t.fixed=!1,t.overflow=!0;}return t}),_defineProperty(this,"getTableHeaders",function(e){var t="#"+e.id,r=Array.from(e.querySelectorAll(t+">thead>tr:nth-of-type(1)>th"));return (r=r.concat(Array.from(e.querySelectorAll(t+">thead>tr:nth-of-type(1)>td")))).length||(r=(r=(r=(r=Array.from(e.querySelectorAll(t+">tbody>tr:nth-of-type(1)>th"))).concat(Array.from(e.querySelectorAll(t+">tr:nth-of-type(1)>th")))).concat(Array.from(e.querySelectorAll(t+">tbody>tr:nth-of-type(1)>td")))).concat(Array.from(e.querySelectorAll(t+">tr:nth-of-type(1)>td")))),c.filterInvisible(r,!1)}),_defineProperty(this,"filterInvisible",function(e,i){return e.filter(function(e){var t=i?-1:e.offsetWidth,r=i?-1:e.offsetHeight;return !(0===t&&0===r||e.style&&e.style.display&&"none"===window.getComputedStyle(e).display||!1)})}),_defineProperty(this,"extendTable",function(e){var t=c.tb;t.opt.removePadding&&t.classList.add("grip-padding"),t.classList.add(c.RESIZABLE),t.insertAdjacentHTML("beforebegin",'<div class="grip-container"/>'),t.grips=[],t.columns=[],t.tableWidth=Number(window.getComputedStyle(t).width.replace(/px/,"")).valueOf(),t.gripContainer=t.previousElementSibling,t.opt.marginLeft&&(t.gripContainer.style.marginLeft=t.opt.marginLeft),t.opt.marginRight&&(t.gripContainer.style.marginRight=t.opt.marginRight),t.cellSpace=parseInt(c.legacyIE?t.cellSpacing||t.currentStyle.borderSpacing:window.getComputedStyle(t).borderSpacing.split(" ")[0].replace(/px/,""))||2,t.borderSpace=parseInt(c.legacyIE?t.border||t.currentStyle.borderLeftWidth:window.getComputedStyle(t).borderLeftWidth.replace(/px/,""))||1,t.extended=!0,c.createGrips(e);}),_defineProperty(this,"extendRemoteTable",function(i,o,n){n.opt.removePadding&&i.classList.add("grip-padding"),i.classList.add(c.RESIZABLE),i.getAttribute(c.ID)||i.setAttribute(c.ID,n.getAttribute(c.ID)+"remote"),i.columns=[],o.forEach(function(e,t){var r=o[t];r.w=n.columns[t].w,r.style.width=r.w+c.PX,r.removeAttribute("width"),i.columns.push(r);}),i.tableWidth=n.tableWidth,i.cellSpace=n.cellSpace,i.borderSpace=n.borderSpace;var e=Array.from(i.querySelectorAll("col"));i.columnGrp=c.filterInvisible(e,!0),i.columnGrp.forEach(function(e,t){e.removeAttribute("width"),e.style.width=n.columnGrp[t].style.width;}),n.remote=i;}),_defineProperty(this,"createGrips",function(n){var l=c.tb;l.columnGrp=c.filterInvisible(Array.from(l.querySelectorAll("col")),!0),l.columnGrp.forEach(function(e){e.removeAttribute("width");}),l.columnCnt=n.length;var a=!1;c.store[l.getAttribute(c.ID)]&&(c.deserializeStore(n),a=!0),l.opt.widths||(l.opt.widths=[]),n.forEach(function(e,t){var r=n[t],i=-1!==l.opt.disabledColumns.indexOf(t);c.createDiv(l.gripContainer,"grip-handle");var o=l.gripContainer.lastChild;!i&&l.opt.gripInnerHtml&&(o.innerHTML=l.opt.gripInnerHtml),c.createDiv(o,c.RESIZABLE),t===l.columnCnt-1&&(o.classList.add("grip-lastgrip"),l.opt.fixed&&(o.innerHTML="")),o.addEventListener("touchstart",c.onGripMouseDown,{capture:!0,passive:!0}),o.addEventListener("mousedown",c.onGripMouseDown,!0),i?o.classList.add("grip-disabledgrip"):(o.classList.remove("grip-disabledgrip"),o.addEventListener("touchstart",c.onGripMouseDown,{capture:!0,passive:!0}),o.addEventListener("mousedown",c.onGripMouseDown,!0)),o.t=l,o.i=t,l.opt.widths[t]?r.w=l.opt.widths[t]:r.w=a?Number(r.style.width.replace(/px/,"")).valueOf():Number(window.getComputedStyle(r).width.replace(/px/,"")).valueOf(),r.style.width=r.w+c.PX,r.removeAttribute("width"),o.data={i:t,t:l.getAttribute(c.ID),last:t===l.columnCnt-1},l.grips.push(o),l.columns.push(r);});var e=Array.from(l.querySelectorAll("td"));e.concat(Array.from(l.querySelectorAll("th"))),(e=(e=e.filter(function(e){for(var t=0;t<n.length;t++)if(n[t]===e)return !1;return !0})).filter(function(e){return !(e.querySelectorAll("table th").length||e.querySelectorAll("table td").length)})).forEach(function(e){e.removeAttribute("width");}),l.opt.fixed||(l.removeAttribute("width"),l.classList.add(c.FLEX)),c.syncGrips();}),_defineProperty(this,"deserializeStore",function(e){var t=c.tb;if(t.columnGrp.forEach(function(e){e.removeAttribute("width");}),t.opt.flush)c.store[t.getAttribute(c.ID)]="";else{var r=c.store[t.getAttribute(c.ID)].split(";"),i=r[t.columnCnt+1];!t.opt.fixed&&i&&(t.style.width=i+c.PX,t.opt.overflow&&(t.style.minWidth=i+c.PX,t.tableWidth=Number(i).valueOf()));for(var o=0;o<t.columnCnt;o++)e[o].style.width=r[o]+c.PX,t.columnGrp[o]&&(t.columnGrp[o].style.width=100*Number(r[o]).valueOf()/Number(r[t.columnCnt]).valueOf()+"%");}}),_defineProperty(this,"createDiv",function(e,t,r){var i=document.createElement("div");i.classList.add(t),r&&(i.innerHTML=r),e.appendChild(i);}),_defineProperty(this,"syncCols",function(e,t,r,i){var o=e.remote,n=c.grip.x-c.grip.l,l=e.columns[t],a=e.columns[t+1];if(l&&a){var s=l.w+n,d=a.w-n,p=s+c.PX;if(l.style.width=p,e.columnGrp[t]&&e.columnGrp[t].style.width&&(e.columnGrp[t].style.width=p),o&&(o.columns[t].style.width=p,o.columnGrp[t]&&o.columnGrp[t].style.width&&(o.columnGrp[t].style.width=p)),i.fixed){var u=d+c.PX;a.style.width=u,e.columnGrp[t+1]&&e.columnGrp[t+1].style.width&&(e.columnGrp[t+1].style.width=u),o&&(o.columns[t+1].style.width=u,o.columnGrp[t+1]&&o.columnGrp[t+1].style.width&&(o.columnGrp[t+1].style.width=u));}else i.overflow&&(e.style.minWidth=e.tableWidth+n+c.PX);r&&(l.w=s,a.w=i.fixed?d:a.w,o&&(o.columns[t].w=s,o.columns[t+1].w=i.fixed?d:a.w));}});try{this.store=sessionStorage;}catch(e){this.store={};}this.grip=null,this.tb=e,window.addEventListener("resize",this.onResize),Element.prototype.matches||(Element.prototype.matches=Element.prototype.msMatchesSelector),this.init(t);};l.DEFAULTS={resizeMode:"fit",draggingClass:"grip-drag",gripInnerHtml:"",liveDrag:!1,minWidth:15,headerOnly:!1,hoverCursor:"col-resize",dragCursor:"col-resize",flush:!1,marginLeft:null,marginRight:null,remoteTable:null,disable:!1,partialRefresh:!1,disabledColumns:[],removePadding:!0,widths:[],serialize:!0,onDrag:null,onResize:null};}])});
});
var ColumnResizer = unwrapExports(columnResizer);
var columnResizer_1 = columnResizer.ColumnResizer;
var withColumnResizing = (function () {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref$resizeOptions = _ref.resizeOptions,
resizeOptions = _ref$resizeOptions === void 0 ? {
liveDrag: true
} : _ref$resizeOptions;
return function withColumnResizing(BaseComponent) {
var Table = function Table(props) {
// Using refs as alternative to findDOMNode
var tableRef = React__default.useRef();
React__default.useEffect(function () {
// Use resizeOptions object provided by consumer or default one
var resizer = new ColumnResizer(tableRef.current, resizeOptions); // Cleanup resizer when Table is re-rendered
return function () {
resizer.destroy();
};
}, []); // Return a copy of the BaseComponent with column resize functionality
return spreadProps(BaseComponent)(objectSpread({}, props, {
ref: tableRef
}));
}; // Set displayName for debugging purposes
Table.displayName = "Table"; // Copy all non-React static properties over
hoistNonReactStatics_cjs(Table, BaseComponent);
return Table;
};
});
function columnSortingReducer() {
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var action = arguments.length > 1 ? arguments[1] : undefined;
var nextState = action.multisort ? state : {};
switch (action.type) {
case "SORT_COLUMN":
return objectSpread({}, nextState, defineProperty({}, action.id, action.direction));
case "UNSORT_COLUMN":
var newState = Object.keys(state).reduce(function (accum, id) {
if (id !== action.id) accum[id] = state[id];
return accum;
}, {});
return newState;
case "TOGGLE_SORT_COLUMN":
return objectSpread({}, nextState, defineProperty({}, action.id, state[action.id] === "ascending" ? "descending" : "ascending"));
default:
return state;
}
}
var ColumnSortingContext = React__default.createContext({});
var withColumnSorting = (function () {
return function withColumnSorting(BaseComponent) {
var Table = function Table(props) {
var _props$store = slicedToArray(props.store, 2),
sortedColumns = _props$store[0].sortedColumns,
dispatch = _props$store[1];
return React__default.createElement(ColumnSortingContext.Provider, {
value: {
sortedColumns: sortedColumns,
dispatch: dispatch
}
}, spreadProps(BaseComponent)(props));
};
Table.displayName = "Table";
hoistNonReactStatics_cjs(Table, BaseComponent);
Table.HeaderCell = function (_ref) {
var sortKey = _ref.sortKey,
className = _ref.className,
rest = objectWithoutProperties(_ref, ["sortKey", "className"]);
var _useContext = React.useContext(ColumnSortingContext),
sortedColumns = _useContext.sortedColumns,
dispatch = _useContext.dispatch;
var onClick = React.useCallback(function (e) {
dispatch({
type: "TOGGLE_SORT_COLUMN",
id: sortKey
});
}, [sortKey, sortedColumns, dispatch]);
var sortDirection = sortKey ? sortedColumns[sortKey] : undefined;
return spreadProps(BaseComponent.HeaderCell)(objectSpread({}, rest, {
onClick: sortKey ? onClick : undefined,
className: classnames(className, {
"table__header__cell--sortable": !!sortKey
}, defineProperty({}, "table__header__cell--sorted-".concat(sortDirection), sortDirection))
}));
};
Table.HeaderCell.displayName = "Table.HeaderCell";
Table.reducer = function () {
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var action = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return objectSpread({}, BaseComponent.reducer(state, action), {
sortedColumns: columnSortingReducer(state.sortedColumns, action)
});
};
return Table;
};
});
var withSubgrid = (function (_ref) {
var renderSubgrid = _ref.renderSubgrid;
return function withSubgrid(BaseComponent) {
var Table$$1 = spreadProps(BaseComponent);
Table$$1.displayName = "Table";
hoistNonReactStatics_cjs(Table$$1, BaseComponent);
Table$$1.HeaderRow = function (_ref2) {
var children = _ref2.children,
rest = objectWithoutProperties(_ref2, ["children"]);
return spreadProps(BaseComponent.HeaderRow)(objectSpread({
children: React__default.createElement(React__default.Fragment, null, React__default.createElement(Table.HeaderCell, {
className: "table__header__cell--spacer"
}), children)
}, rest));
};
Table$$1.HeaderRow.displayName = "Table.HeaderRow";
Table$$1.Row = function (_ref3) {
var children = _ref3.children,
rest = objectWithoutProperties(_ref3, ["children"]);
var _useState = React.useState(false),
_useState2 = slicedToArray(_useState, 2),
expanded = _useState2[0],
setExpanded = _useState2[1];
var toggleSubgrid = React.useCallback(function () {
setExpanded(!expanded);
}, [expanded, setExpanded]);
return React__default.createElement(React__default.Fragment, null, spreadProps(BaseComponent.Row)(objectSpread({
children: React__default.createElement(React__default.Fragment, null, React__default.createElement(BaseComponent.Cell, {
onClick: toggleSubgrid,
className: classnames("table__body__cell--subgrid__toggle", {
"table__body__cell--subgrid__toggle--expanded": expanded
})
}, React__default.createElement("span", {
className: "table__body__cell--subgrid__toggle__icon"
})), children)
}, rest)), expanded ? React__default.createElement(Table.Row, null, React__default.createElement(Table.Cell, {
colSpan: React__default.Children.count(children) + 1
}, renderSubgrid(rest["data-id"]))) : null);
};
Table$$1.Row.displayName = "Table.Row";
return Table$$1;
};
});
var util = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.Constants = {
POPOVER_CONTAINER_CLASS_NAME: 'react-tiny-popover-container',
DEFAULT_PADDING: 6,
DEFAULT_WINDOW_PADDING: 6,
FADE_TRANSITION: 0.35,
DEFAULT_ARROW_COLOR: 'black',
DEFAULT_POSITIONS: ['top', 'left', 'right', 'bottom'],
EMPTY_CLIENT_RECT: {
top: 0,
left: 0,
bottom: 0,
height: 0,
right: 0,
width: 0,
},
};
exports.arrayUnique = function (array) { return array.filter(function (value, index, self) { return self.indexOf(value) === index; }); };
});
unwrapExports(util);
var util_1 = util.Constants;
var util_2 = util.arrayUnique;
var ArrowContainer_1 = createCommonjsModule(function (module, exports) {
var __assign = (commonjsGlobal && commonjsGlobal.__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;
};
Object.defineProperty(exports, "__esModule", { value: true });
var ArrowContainer = function (_a) {
var position = _a.position, children = _a.children, style = _a.style, _b = _a.arrowColor, arrowColor = _b === void 0 ? util.Constants.DEFAULT_ARROW_COLOR : _b, _c = _a.arrowSize, arrowSize = _c === void 0 ? 10 : _c, arrowStyle = _a.arrowStyle, popoverRect = _a.popoverRect, targetRect = _a.targetRect;
return (React__default.createElement("div", { style: __assign({ paddingLeft: position === 'right' ? arrowSize : 0, paddingTop: position === 'bottom' ? arrowSize : 0, paddingBottom: position === 'top' ? arrowSize : 0, paddingRight: position === 'left' ? arrowSize : 0 }, style) },
React__default.createElement("div", { style: __assign({ position: 'absolute' }, (function () {
var arrowWidth = arrowSize * 2;
var top = (targetRect.top - popoverRect.top) + (targetRect.height / 2) - (arrowWidth / 2);
var left = (targetRect.left - popoverRect.left) + (targetRect.width / 2) - (arrowWidth / 2);
left = left < 0 ? 0 : left;
left = left + arrowWidth > popoverRect.width ? popoverRect.width - arrowWidth : left;
top = top < 0 ? 0 : top;
top = top + arrowWidth > popoverRect.height ? popoverRect.height - arrowWidth : top;
switch (position) {
case 'right':
return {
borderTop: arrowSize + "px solid transparent",
borderBottom: arrowSize + "px solid transparent",
borderRight: arrowSize + "px solid " + arrowColor,
left: 0,
top: top,
};
case 'left':
return {
borderTop: arrowSize + "px solid transparent",
borderBottom: arrowSize + "px solid transparent",
borderLeft: arrowSize + "px solid " + arrowColor,
right: 0,
top: top,
};
case 'bottom':
return {
borderLeft: arrowSize + "px solid transparent",
borderRight: arrowSize + "px solid transparent",
borderBottom: arrowSize + "px solid " + arrowColor,
top: 0,
left: left,
};
case 'top':
default:
return {
borderLeft: arrowSize + "px solid transparent",
borderRight: arrowSize + "px solid transparent",
borderTop: arrowSize + "px solid " + arrowColor,
bottom: 0,
left: left,
};
}
})(), arrowStyle) }),
children));
};
exports.ArrowContainer = ArrowContainer;
});
var ArrowContainer = unwrapExports(ArrowContainer_1);
var ArrowContainer_2 = ArrowContainer_1.ArrowContainer;
var getEventProps = function getEventProps(on, setOpen, toggle) {
return objectSpread({}, on.indexOf("hover") !== -1 ? {
onMouseEnter: function onMouseEnter() {
return setOpen(true);
},
onMouseLeave: function onMouseLeave() {
return setOpen(false);
}
} : {}, on.indexOf("focus") !== -1 ? {
onFocus: function onFocus() {
return setOpen(true);
},
onBlur: function onBlur() {
return setOpen(false);
}
} : {}, {
onClick: on.indexOf("click") !== -1 ? toggle : undefined
});
};
function Popup(_ref) {
var isOpen = _ref.isOpen,
trigger = _ref.trigger,
children = _ref.children,
_ref$on = _ref.on,
on = _ref$on === void 0 ? "" : _ref$on,
rest = objectWithoutProperties(_ref, ["isOpen", "trigger", "children", "on"]);
var _React$useState = React.useState(false),
_React$useState2 = slicedToArray(_React$useState, 2),
internalIsOpen = _React$useState2[0],
setInternalIsOpen = _React$useState2[1];
var triggers = React.useMemo(function () {
return getEventProps(on, setInternalIsOpen, function () {
return setInternalIsOpen(!internalIsOpen);
});
}, [internalIsOpen, on, setInternalIsOpen]);
return React.createElement(Popover, _extends_1({
containerClassName: "popup-container",
containerStyle: {
overflow: "visible"
}
}, rest, {
isOpen: isOpen || internalIsOpen
}), trigger ? React.cloneElement(trigger, objectSpread({}, triggers)) : children);
}
Popup.ArrowContainer = ArrowContainer;
/**
* A collection of shims that provide minimal functionality of the ES6 collections.
*
* These implementations are not meant to be used outside of the ResizeObserver
* modules as they cover only a limited range of use cases.
*/
/* eslint-disable require-jsdoc, valid-jsdoc */
var MapShim = (function () {
if (typeof Map !== 'undefined') {
return Map;
}
/**
* Returns index in provided array that matches the specified key.
*
* @param {Array<Array>} arr
* @param {*} key
* @returns {number}
*/
function getIndex(arr, key) {
var result = -1;
arr.some(function (entry, index) {
if (entry[0] === key) {
result = index;
return true;
}
return false;
});
return result;
}
return /** @class */ (function () {
function class_1() {
this.__entries__ = [];
}
Object.defineProperty(class_1.prototype, "size", {
/**
* @returns {boolean}
*/
get: function () {
return this.__entries__.length;
},
enumerable: true,
configurable: true
});
/**
* @param {*} key
* @returns {*}
*/
class_1.prototype.get = function (key) {
var index = getIndex(this.__entries__, key);
var entry = this.__entries__[index];
return entry && entry[1];
};
/**
* @param {*} key
* @param {*} value
* @returns {void}
*/
class_1.prototype.set = function (key, value) {
var index = getIndex(this.__entries__, key);
if (~index) {
this.__entries__[index][1] = value;
}
else {
this.__entries__.push([key, value]);
}
};
/**
* @param {*} key
* @returns {void}
*/
class_1.prototype.delete = function (key) {
var entries = this.__entries__;
var index = getIndex(entries, key);
if (~index) {
entries.splice(index, 1);
}
};
/**
* @param {*} key
* @returns {void}
*/
class_1.prototype.has = function (key) {
return !!~getIndex(this.__entries__, key);
};
/**
* @returns {void}
*/
class_1.prototype.clear = function () {
this.__entries__.splice(0);
};
/**
* @param {Function} callback
* @param {*} [ctx=null]
* @returns {void}
*/
class_1.prototype.forEach = function (callback, ctx) {
if (ctx === void 0) { ctx = null; }
for (var _i = 0, _a = this.__entries__; _i < _a.length; _i++) {
var entry = _a[_i];
callback.call(ctx, entry[1], entry[0]);
}
};
return class_1;
}());
})();
/**
* Detects whether window and document objects are available in current environment.
*/
var isBrowser$2 = typeof window !== 'undefined' && typeof document !== 'undefined' && window.document === document;
// Returns global object of a current environment.
var global$1 = (function () {
if (typeof global !== 'undefined' && global.Math === Math) {
return global;
}
if (typeof self !== 'undefined' && self.Math === Math) {
return self;
}
if (typeof window !== 'undefined' && window.Math === Math) {
return window;
}
// eslint-disable-next-line no-new-func
return Function('return this')();
})();
/**
* A shim for the requestAnimationFrame which falls back to the setTimeout if
* first one is not supported.
*
* @returns {number} Requests' identifier.
*/
var requestAnimationFrame$1 = (function () {
if (typeof requestAnimationFrame === 'function') {
// It's required to use a bounded function because IE sometimes throws
// an "Invalid calling object" error if rAF is invoked without the global
// object on the left hand side.
return requestAnimationFrame.bind(global$1);
}
return function (callback) { return setTimeout(function () { return callback(Date.now()); }, 1000 / 60); };
})();
// Defines minimum timeout before adding a trailing call.
var trailingTimeout = 2;
/**
* Creates a wrapper function which ensures that provided callback will be
* invoked only once during the specified delay period.
*
* @param {Function} callback - Function to be invoked after the delay period.
* @param {number} delay - Delay after which to invoke callback.
* @returns {Function}
*/
function throttle (callback, delay) {
var leadingCall = false, trailingCall = false, lastCallTime = 0;
/**
* Invokes the original callback function and schedules new invocation if
* the "proxy" was called during current request.
*
* @returns {void}
*/
function resolvePending() {
if (leadingCall) {
leadingCall = false;
callback();
}
if (trailingCall) {
proxy();
}
}
/**
* Callback invoked after the specified delay. It will further postpone
* invocation of the original function delegating it to the
* requestAnimationFrame.
*
* @returns {void}
*/
function timeoutCallback() {
requestAnimationFrame$1(resolvePending);
}
/**
* Schedules invocation of the original function.
*
* @returns {void}
*/
function proxy() {
var timeStamp = Date.now();
if (leadingCall) {
// Reject immediately following calls.
if (timeStamp - lastCallTime < trailingTimeout) {
return;
}
// Schedule new call to be in invoked when the pending one is resolved.
// This is important for "transitions" which never actually start
// immediately so there is a chance that we might miss one if change
// happens amids the pending invocation.
trailingCall = true;
}
else {
leadingCall = true;
trailingCall = false;
setTimeout(timeoutCallback, delay);
}
lastCallTime = timeStamp;
}
return proxy;
}
// Minimum delay before invoking the update of observers.
var REFRESH_DELAY = 20;
// A list of substrings of CSS properties used to find transition events that
// might affect dimensions of observed elements.
var transitionKeys = ['top', 'right', 'bottom', 'left', 'width', 'height', 'size', 'weight'];
// Check if MutationObserver is available.
var mutationObserverSupported = typeof MutationObserver !== 'undefined';
/**
* Singleton controller class which handles updates of ResizeObserver instances.
*/
var ResizeObserverController = /** @class */ (function () {
/**
* Creates a new instance of ResizeObserverController.
*
* @private
*/
function ResizeObserverController() {
/**
* Indicates whether DOM listeners have been added.
*
* @private {boolean}
*/
this.connected_ = false;
/**
* Tells that controller has subscribed for Mutation Events.
*
* @private {boolean}
*/
this.mutationEventsAdded_ = false;
/**
* Keeps reference to the instance of MutationObserver.
*
* @private {MutationObserver}
*/
this.mutationsObserver_ = null;
/**
* A list of connected observers.
*
* @private {Array<ResizeObserverSPI>}
*/
this.observers_ = [];
this.onTransitionEnd_ = this.onTransitionEnd_.bind(this);
this.refresh = throttle(this.refresh.bind(this), REFRESH_DELAY);
}
/**
* Adds observer to observers list.
*
* @param {ResizeObserverSPI} observer - Observer to be added.
* @returns {void}
*/
ResizeObserverController.prototype.addObserver = function (observer) {
if (!~this.observers_.indexOf(observer)) {
this.observers_.push(observer);
}
// Add listeners if they haven't been added yet.
if (!this.connected_) {
this.connect_();
}
};
/**
* Removes observer from observers list.
*
* @param {ResizeObserverSPI} observer - Observer to be removed.
* @returns {void}
*/
ResizeObserverController.prototype.removeObserver = function (observer) {
var observers = this.observers_;
var index = observers.indexOf(observer);
// Remove observer if it's present in registry.
if (~index) {
observers.splice(index, 1);
}
// Remove listeners if controller has no connected observers.
if (!observers.length && this.connected_) {
this.disconnect_();
}
};
/**
* Invokes the update of observers. It will continue running updates insofar
* it detects changes.
*
* @returns {void}
*/
ResizeObserverController.prototype.refresh = function () {
var changesDetected = this.updateObservers_();
// Continue running updates if changes have been detected as there might
// be future ones caused by CSS transitions.
if (changesDetected) {
this.refresh();
}
};
/**
* Updates every observer from observers list and notifies them of queued
* entries.
*
* @private
* @returns {boolean} Returns "true" if any observer has detected changes in
* dimensions of it's elements.
*/
ResizeObserverController.prototype.updateObservers_ = function () {
// Collect observers that have active observations.
var activeObservers = this.observers_.filter(function (observer) {
return observer.gatherActive(), observer.hasActive();
});
// Deliver notifications in a separate cycle in order to avoid any
// collisions between observers, e.g. when multiple instances of
// ResizeObserver are tracking the same element and the callback of one
// of them changes content dimensions of the observed target. Sometimes
// this may result in notifications being blocked for the rest of observers.
activeObservers.forEach(function (observer) { return observer.broadcastActive(); });
return activeObservers.length > 0;
};
/**
* Initializes DOM listeners.
*
* @private
* @returns {void}
*/
ResizeObserverController.prototype.connect_ = function () {
// Do nothing if running in a non-browser environment or if listeners
// have been already added.
if (!isBrowser$2 || this.connected_) {
return;
}
// Subscription to the "Transitionend" event is used as a workaround for
// delayed transitions. This way it's possible to capture at least the
// final state of an element.
document.addEventListener('transitionend', this.onTransitionEnd_);
window.addEventListener('resize', this.refresh);
if (mutationObserverSupported) {
this.mutationsObserver_ = new MutationObserver(this.refresh);
this.mutationsObserver_.observe(document, {
attributes: true,
childList: true,
characterData: true,
subtree: true
});
}
else {
document.addEventListener('DOMSubtreeModified', this.refresh);
this.mutationEventsAdded_ = true;
}
this.connected_ = true;
};
/**
* Removes DOM listeners.
*
* @private
* @returns {void}
*/
ResizeObserverController.prototype.disconnect_ = function () {
// Do nothing if running in a non-browser environment or if listeners
// have been already removed.
if (!isBrowser$2 || !this.connected_) {
return;
}
document.removeEventListener('transitionend', this.onTransitionEnd_);
window.removeEventListener('resize', this.refresh);
if (this.mutationsObserver_) {
this.mutationsObserver_.disconnect();
}
if (this.mutationEventsAdded_) {
document.removeEventListener('DOMSubtreeModified', this.refresh);
}
this.mutationsObserver_ = null;
this.mutationEventsAdded_ = false;
this.connected_ = false;
};
/**
* "Transitionend" event handler.
*
* @private
* @param {TransitionEvent} event
* @returns {void}
*/
ResizeObserverController.prototype.onTransitionEnd_ = function (_a) {
var _b = _a.propertyName, propertyName = _b === void 0 ? '' : _b;
// Detect whether transition may affect dimensions of an element.
var isReflowProperty = transitionKeys.some(function (key) {
return !!~propertyName.indexOf(key);
});
if (isReflowProperty) {
this.refresh();
}
};
/**
* Returns instance of the ResizeObserverController.
*
* @returns {ResizeObserverController}
*/
ResizeObserverController.getInstance = function () {
if (!this.instance_) {
this.instance_ = new ResizeObserverController();
}
return this.instance_;
};
/**
* Holds reference to the controller's instance.
*
* @private {ResizeObserverController}
*/
ResizeObserverController.instance_ = null;
return ResizeObserverController;
}());
/**
* Defines non-writable/enumerable properties of the provided target object.
*
* @param {Object} target - Object for which to define properties.
* @param {Object} props - Properties to be defined.
* @returns {Object} Target object.
*/
var defineConfigurable = (function (target, props) {
for (var _i = 0, _a = Object.keys(props); _i < _a.length; _i++) {
var key = _a[_i];
Object.defineProperty(target, key, {
value: props[key],
enumerable: false,
writable: false,
configurable: true
});
}
return target;
});
/**
* Returns the global object associated with provided element.
*
* @param {Object} target
* @returns {Object}
*/
var getWindowOf = (function (target) {
// Assume that the element is an instance of Node, which means that it
// has the "ownerDocument" property from which we can retrieve a
// corresponding global object.
var ownerGlobal = target && target.ownerDocument && target.ownerDocument.defaultView;
// Return the local global object if it's not possible extract one from
// provided element.
return ownerGlobal || global$1;
});
// Placeholder of an empty content rectangle.
var emptyRect = createRectInit(0, 0, 0, 0);
/**
* Converts provided string to a number.
*
* @param {number|string} value
* @returns {number}
*/
function toFloat(value) {
return parseFloat(value) || 0;
}
/**
* Extracts borders size from provided styles.
*
* @param {CSSStyleDeclaration} styles
* @param {...string} positions - Borders positions (top, right, ...)
* @returns {number}
*/
function getBordersSize(styles) {
var positions = [];
for (var _i = 1; _i < arguments.length; _i++) {
positions[_i - 1] = arguments[_i];
}
return positions.reduce(function (size, position) {
var value = styles['border-' + position + '-width'];
return size + toFloat(value);
}, 0);
}
/**
* Extracts paddings sizes from provided styles.
*
* @param {CSSStyleDeclaration} styles
* @returns {Object} Paddings box.
*/
function getPaddings(styles) {
var positions = ['top', 'right', 'bottom', 'left'];
var paddings = {};
for (var _i = 0, positions_1 = positions; _i < positions_1.length; _i++) {
var position = positions_1[_i];
var value = styles['padding-' + position];
paddings[position] = toFloat(value);
}
return paddings;
}
/**
* Calculates content rectangle of provided SVG element.
*
* @param {SVGGraphicsElement} target - Element content rectangle of which needs
* to be calculated.
* @returns {DOMRectInit}
*/
function getSVGContentRect(target) {
var bbox = target.getBBox();
return createRectInit(0, 0, bbox.width, bbox.height);
}
/**
* Calculates content rectangle of provided HTMLElement.
*
* @param {HTMLElement} target - Element for which to calculate the content rectangle.
* @returns {DOMRectInit}
*/
function getHTMLElementContentRect(target) {
// Client width & height properties can't be
// used exclusively as they provide rounded values.
var clientWidth = target.clientWidth, clientHeight = target.clientHeight;
// By this condition we can catch all non-replaced inline, hidden and
// detached elements. Though elements with width & height properties less
// than 0.5 will be discarded as well.
//
// Without it we would need to implement separate methods for each of
// those cases and it's not possible to perform a precise and performance
// effective test for hidden elements. E.g. even jQuery's ':visible' filter
// gives wrong results for elements with width & height less than 0.5.
if (!clientWidth && !clientHeight) {
return emptyRect;
}
var styles = getWindowOf(target).getComputedStyle(target);
var paddings = getPaddings(styles);
var horizPad = paddings.left + paddings.right;
var vertPad = paddings.top + paddings.bottom;
// Computed styles of width & height are being used because they are the
// only dimensions available to JS that contain non-rounded values. It could
// be possible to utilize the getBoundingClientRect if only it's data wasn't
// affected by CSS transformations let alone paddings, borders and scroll bars.
var width = toFloat(styles.width), height = toFloat(styles.height);
// Width & height include paddings and borders when the 'border-box' box
// model is applied (except for IE).
if (styles.boxSizing === 'border-box') {
// Following conditions are required to handle Internet Explorer which
// doesn't include paddings and borders to computed CSS dimensions.
//
// We can say that if CSS dimensions + paddings are equal to the "client"
// properties then it's either IE, and thus we don't need to subtract
// anything, or an element merely doesn't have paddings/borders styles.
if (Math.round(width + horizPad) !== clientWidth) {
width -= getBordersSize(styles, 'left', 'right') + horizPad;
}
if (Math.round(height + vertPad) !== clientHeight) {
height -= getBordersSize(styles, 'top', 'bottom') + vertPad;
}
}
// Following steps can't be applied to the document's root element as its
// client[Width/Height] properties represent viewport area of the window.
// Besides, it's as well not necessary as the <html> itself neither has
// rendered scroll bars nor it can be clipped.
if (!isDocumentElement(target)) {
// In some browsers (only in Firefox, actually) CSS width & height
// include scroll bars size which can be removed at this step as scroll
// bars are the only difference between rounded dimensions + paddings
// and "client" properties, though that is not always true in Chrome.
var vertScrollbar = Math.round(width + horizPad) - clientWidth;
var horizScrollbar = Math.round(height + vertPad) - clientHeight;
// Chrome has a rather weird rounding of "client" properties.
// E.g. for an element with content width of 314.2px it sometimes gives
// the client width of 315px and for the width of 314.7px it may give
// 314px. And it doesn't happen all the time. So just ignore this delta
// as a non-relevant.
if (Math.abs(vertScrollbar) !== 1) {
width -= vertScrollbar;
}
if (Math.abs(horizScrollbar) !== 1) {
height -= horizScrollbar;
}
}
return createRectInit(paddings.left, paddings.top, width, height);
}
/**
* Checks whether provided element is an instance of the SVGGraphicsElement.
*
* @param {Element} target - Element to be checked.
* @returns {boolean}
*/
var isSVGGraphicsElement = (function () {
// Some browsers, namely IE and Edge, don't have the SVGGraphicsElement
// interface.
if (typeof SVGGraphicsElement !== 'undefined') {
return function (target) { return target instanceof getWindowOf(target).SVGGraphicsElement; };
}
// If it's so, then check that element is at least an instance of the
// SVGElement and that it has the "getBBox" method.
// eslint-disable-next-line no-extra-parens
return function (target) { return (target instanceof getWindowOf(target).SVGElement &&
typeof target.getBBox === 'function'); };
})();
/**
* Checks whether provided element is a document element (<html>).
*
* @param {Element} target - Element to be checked.
* @returns {boolean}
*/
function isDocumentElement(target) {
return target === getWindowOf(target).document.documentElement;
}
/**
* Calculates an appropriate content rectangle for provided html or svg element.
*
* @param {Element} target - Element content rectangle of which needs to be calculated.
* @returns {DOMRectInit}
*/
function getContentRect(target) {
if (!isBrowser$2) {
return emptyRect;
}
if (isSVGGraphicsElement(target)) {
return getSVGContentRect(target);
}
return getHTMLElementContentRect(target);
}
/**
* Creates rectangle with an interface of the DOMRectReadOnly.
* Spec: https://drafts.fxtf.org/geometry/#domrectreadonly
*
* @param {DOMRectInit} rectInit - Object with rectangle's x/y coordinates and dimensions.
* @returns {DOMRectReadOnly}
*/
function createReadOnlyRect(_a) {
var x = _a.x, y = _a.y, width = _a.width, height = _a.height;
// If DOMRectReadOnly is available use it as a prototype for the rectangle.
var Constr = typeof DOMRectReadOnly !== 'undefined' ? DOMRectReadOnly : Object;
var rect = Object.create(Constr.prototype);
// Rectangle's properties are not writable and non-enumerable.
defineConfigurable(rect, {
x: x, y: y, width: width, height: height,
top: y,
right: x + width,
bottom: height + y,
left: x
});
return rect;
}
/**
* Creates DOMRectInit object based on the provided dimensions and the x/y coordinates.
* Spec: https://drafts.fxtf.org/geometry/#dictdef-domrectinit
*
* @param {number} x - X coordinate.
* @param {number} y - Y coordinate.
* @param {number} width - Rectangle's width.
* @param {number} height - Rectangle's height.
* @returns {DOMRectInit}
*/
function createRectInit(x, y, width, height) {
return { x: x, y: y, width: width, height: height };
}
/**
* Class that is responsible for computations of the content rectangle of
* provided DOM element and for keeping track of it's changes.
*/
var ResizeObservation = /** @class */ (function () {
/**
* Creates an instance of ResizeObservation.
*
* @param {Element} target - Element to be observed.
*/
function ResizeObservation(target) {
/**
* Broadcasted width of content rectangle.
*
* @type {number}
*/
this.broadcastWidth = 0;
/**
* Broadcasted height of content rectangle.
*
* @type {number}
*/
this.broadcastHeight = 0;
/**
* Reference to the last observed content rectangle.
*
* @private {DOMRectInit}
*/
this.contentRect_ = createRectInit(0, 0, 0, 0);
this.target = target;
}
/**
* Updates content rectangle and tells whether it's width or height properties
* have changed since the last broadcast.
*
* @returns {boolean}
*/
ResizeObservation.prototype.isActive = function () {
var rect = getContentRect(this.target);
this.contentRect_ = rect;
return (rect.width !== this.broadcastWidth ||
rect.height !== this.broadcastHeight);
};
/**
* Updates 'broadcastWidth' and 'broadcastHeight' properties with a data
* from the corresponding properties of the last observed content rectangle.
*
* @returns {DOMRectInit} Last observed content rectangle.
*/
ResizeObservation.prototype.broadcastRect = function () {
var rect = this.contentRect_;
this.broadcastWidth = rect.width;
this.broadcastHeight = rect.height;
return rect;
};
return ResizeObservation;
}());
var ResizeObserverEntry = /** @class */ (function () {
/**
* Creates an instance of ResizeObserverEntry.
*
* @param {Element} target - Element that is being observed.
* @param {DOMRectInit} rectInit - Data of the element's content rectangle.
*/
function ResizeObserverEntry(target, rectInit) {
var contentRect = createReadOnlyRect(rectInit);
// According to the specification following properties are not writable
// and are also not enumerable in the native implementation.
//
// Property accessors are not being used as they'd require to define a
// private WeakMap storage which may cause memory leaks in browsers that
// don't support this type of collections.
defineConfigurable(this, { target: target, contentRect: contentRect });
}
return ResizeObserverEntry;
}());
var ResizeObserverSPI = /** @class */ (function () {
/**
* Creates a new instance of ResizeObserver.
*
* @param {ResizeObserverCallback} callback - Callback function that is invoked
* when one of the observed elements changes it's content dimensions.
* @param {ResizeObserverController} controller - Controller instance which
* is responsible for the updates of observer.
* @param {ResizeObserver} callbackCtx - Reference to the public
* ResizeObserver instance which will be passed to callback function.
*/
function ResizeObserverSPI(callback, controller, callbackCtx) {
/**
* Collection of resize observations that have detected changes in dimensions
* of elements.
*
* @private {Array<ResizeObservation>}
*/
this.activeObservations_ = [];
/**
* Registry of the ResizeObservation instances.
*
* @private {Map<Element, ResizeObservation>}
*/
this.observations_ = new MapShim();
if (typeof callback !== 'function') {
throw new TypeError('The callback provided as parameter 1 is not a function.');
}
this.callback_ = callback;
this.controller_ = controller;
this.callbackCtx_ = callbackCtx;
}
/**
* Starts observing provided element.
*
* @param {Element} target - Element to be observed.
* @returns {void}
*/
ResizeObserverSPI.prototype.observe = function (target) {
if (!arguments.length) {
throw new TypeError('1 argument required, but only 0 present.');
}
// Do nothing if current environment doesn't have the Element interface.
if (typeof Element === 'undefined' || !(Element instanceof Object)) {
return;
}
if (!(target instanceof getWindowOf(target).Element)) {
throw new TypeError('parameter 1 is not of type "Element".');
}
var observations = this.observations_;
// Do nothing if element is already being observed.
if (observations.has(target)) {
return;
}
observations.set(target, new ResizeObservation(target));
this.controller_.addObserver(this);
// Force the update of observations.
this.controller_.refresh();
};
/**
* Stops observing provided element.
*
* @param {Element} target - Element to stop observing.
* @returns {void}
*/
ResizeObserverSPI.prototype.unobserve = function (target) {
if (!arguments.length) {
throw new TypeError('1 argument required, but only 0 present.');
}
// Do nothing if current environment doesn't have the Element interface.
if (typeof Element === 'undefined' || !(Element instanceof Object)) {
return;
}
if (!(target instanceof getWindowOf(target).Element)) {
throw new TypeError('parameter 1 is not of type "Element".');
}
var observations = this.observations_;
// Do nothing if element is not being observed.
if (!observations.has(target)) {
return;
}
observations.delete(target);
if (!observations.size) {
this.controller_.removeObserver(this);
}
};
/**
* Stops observing all elements.
*
* @returns {void}
*/
ResizeObserverSPI.prototype.disconnect = function () {
this.clearActive();
this.observations_.clear();
this.controller_.removeObserver(this);
};
/**
* Collects observation instances the associated element of which has changed
* it's content rectangle.
*
* @returns {void}
*/
ResizeObserverSPI.prototype.gatherActive = function () {
var _this = this;
this.clearActive();
this.observations_.forEach(function (observation) {
if (observation.isActive()) {
_this.activeObservations_.push(observation);
}
});
};
/**
* Invokes initial callback function with a list of ResizeObserverEntry
* instances collected from active resize observations.
*
* @returns {void}
*/
ResizeObserverSPI.prototype.broadcastActive = function () {
// Do nothing if observer doesn't have active observations.
if (!this.hasActive()) {
return;
}
var ctx = this.callbackCtx_;
// Create ResizeObserverEntry instance for every active observation.
var entries = this.activeObservations_.map(function (observation) {
return new ResizeObserverEntry(observation.target, observation.broadcastRect());
});
this.callback_.call(ctx, entries, ctx);
this.clearActive();
};
/**
* Clears the collection of active observations.
*
* @returns {void}
*/
ResizeObserverSPI.prototype.clearActive = function () {
this.activeObservations_.splice(0);
};
/**
* Tells whether observer has active observations.
*
* @returns {boolean}
*/
ResizeObserverSPI.prototype.hasActive = function () {
return this.activeObservations_.length > 0;
};
return ResizeObserverSPI;
}());
// Registry of internal observers. If WeakMap is not available use current shim
// for the Map collection as it has all required methods and because WeakMap
// can't be fully polyfilled anyway.
var observers = typeof WeakMap !== 'undefined' ? new WeakMap() : new MapShim();
/**
* ResizeObserver API. Encapsulates the ResizeObserver SPI implementation
* exposing only those methods and properties that are defined in the spec.
*/
var ResizeObserver = /** @class */ (function () {
/**
* Creates a new instance of ResizeObserver.
*
* @param {ResizeObserverCallback} callback - Callback that is invoked when
* dimensions of the observed elements change.
*/
function ResizeObserver(callback) {
if (!(this instanceof ResizeObserver)) {
throw new TypeError('Cannot call a class as a function.');
}
if (!arguments.length) {
throw new TypeError('1 argument required, but only 0 present.');
}
var controller = ResizeObserverController.getInstance();
var observer = new ResizeObserverSPI(callback, controller, this);
observers.set(this, observer);
}
return ResizeObserver;
}());
// Expose public methods of ResizeObserver.
[
'observe',
'unobserve',
'disconnect'
].forEach(function (method) {
ResizeObserver.prototype[method] = function () {
var _a;
return (_a = observers.get(this))[method].apply(_a, arguments);
};
});
var index = (function () {
// Export existing implementation if available.
if (typeof global$1.ResizeObserver !== 'undefined') {
return global$1.ResizeObserver;
}
return ResizeObserver;
})();
/**
* 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();
};
/** Used as references for various `Number` constants. */
var NAN = 0 / 0;
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
if (isObject(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = value.replace(reTrim, '');
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
/** Error message constants. */
var FUNC_ERROR_TEXT$1 = '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$1);
}
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.
timerId = setTimeout(timerExpired, wait);
return invokeFunc(lastCallTime);
}
}
if (timerId === undefined) {
timerId = setTimeout(timerExpired, wait);
}
return result;
}
debounced.cancel = cancel;
debounced.flush = flush;
return debounced;
}
/** Error message constants. */
var FUNC_ERROR_TEXT$2 = '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$1(func, wait, options) {
var leading = true,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT$2);
}
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
});
}
function _typeof(obj) { 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$2(arr) { return _arrayWithoutHoles$2(arr) || _iterableToArray$2(arr) || _nonIterableSpread$2(); }
function _nonIterableSpread$2() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
function _iterableToArray$2(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
function _arrayWithoutHoles$2(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
function _classCallCheck$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties$1(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$1(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$1(Constructor.prototype, protoProps); if (staticProps) _defineProperties$1(Constructor, staticProps); return Constructor; }
function _possibleConstructorReturn$1(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized$1(self); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _inherits$1(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 _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _assertThisInitialized$1(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _defineProperty$3(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var listMode = {
debounce: debounce,
throttle: throttle$1
};
var styles$1 = {
position: 'absolute',
width: 0,
height: 0,
visibility: 'hidden',
display: 'none'
};
/**
* detect component's children and convert them to array
* @param {*} children - component's children
*/
function convertChildrenToArray(children) {
if (!children) return [];
if (!Array.isArray(children)) return [children];
return children;
}
var ResizeDetector =
/*#__PURE__*/
function (_PureComponent) {
_inherits$1(ResizeDetector, _PureComponent);
function ResizeDetector(props) {
var _this;
_classCallCheck$1(this, ResizeDetector);
_this = _possibleConstructorReturn$1(this, _getPrototypeOf(ResizeDetector).call(this, props));
_defineProperty$3(_assertThisInitialized$1(_assertThisInitialized$1(_this)), "getElement", function () {
var resizableElementId = _this.props.resizableElementId;
var otherElement = resizableElementId && document.getElementById(resizableElementId);
var parentElement = _this.el && _this.el.parentElement;
var resizableElement = otherElement || parentElement;
return resizableElement;
});
_defineProperty$3(_assertThisInitialized$1(_assertThisInitialized$1(_this)), "createResizeHandler", function (entries) {
var _this$props = _this.props,
handleWidth = _this$props.handleWidth,
handleHeight = _this$props.handleHeight,
onResize = _this$props.onResize;
entries.forEach(function (entry) {
var _entry$contentRect = entry.contentRect,
width = _entry$contentRect.width,
height = _entry$contentRect.height;
var notifyWidth = handleWidth && _this.state.width !== width;
var notifyHeight = handleHeight && _this.state.height !== height;
if (!_this.skipOnMount && (notifyWidth || notifyHeight) && typeof window !== 'undefined') {
_this.animationFrameID = window.requestAnimationFrame(function () {
onResize(width, height);
_this.setState({
width: width,
height: height
});
});
}
_this.skipOnMount = false;
});
});
_defineProperty$3(_assertThisInitialized$1(_assertThisInitialized$1(_this)), "handleRenderProp", function () {
var _this$state = _this.state,
width = _this$state.width,
height = _this$state.height;
var render = _this.props.render;
if (render && typeof render === 'function') {
return React.cloneElement(render({
width: width,
height: height
}), {
key: 'render'
});
}
return undefined;
});
_defineProperty$3(_assertThisInitialized$1(_assertThisInitialized$1(_this)), "renderChildren", function () {
var _this$state2 = _this.state,
width = _this$state2.width,
height = _this$state2.height;
var children = _this.props.children;
return convertChildrenToArray(children).filter(function (child) {
return !!child;
}).map(function (child, key) {
if (isFunction(child)) return React.cloneElement(child(width, height), {
key: key
});
if (React.isValidElement(child)) return React.cloneElement(child, {
width: width,
height: height,
key: key
});
return child;
});
});
var skipOnMount = props.skipOnMount,
refreshMode = props.refreshMode,
refreshRate = props.refreshRate,
refreshOptions = props.refreshOptions;
_this.state = {
width: undefined,
height: undefined
};
_this.skipOnMount = skipOnMount;
_this.animationFrameID = null;
_this.resizeHandler = listMode[refreshMode] ? listMode[refreshMode](_this.createResizeHandler, refreshRate, refreshOptions) : _this.createResizeHandler;
_this.ro = new index(_this.resizeHandler);
return _this;
}
_createClass$1(ResizeDetector, [{
key: "componentDidMount",
value: function componentDidMount() {
var resizableElement = this.getElement();
if (resizableElement) this.ro.observe(resizableElement);
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
var resizableElement = this.getElement();
if (resizableElement) this.ro.unobserve(resizableElement);
if (typeof window !== 'undefined' && this.animationFrameID) {
window.cancelAnimationFrame(this.animationFrameID);
}
if (this.resizeHandler && this.resizeHandler.cancel) {
// cancel debounced handler
this.resizeHandler.cancel();
}
}
}, {
key: "render",
value: function render() {
var _this2 = this;
var nodeType = this.props.nodeType;
var resizeDetector = React.createElement(nodeType, {
key: 'resize-detector',
style: styles$1,
ref: function ref(el) {
_this2.el = el;
}
});
return [resizeDetector, this.handleRenderProp()].concat(_toConsumableArray$2(this.renderChildren()));
}
}]);
return ResizeDetector;
}(React.PureComponent);
ResizeDetector.propTypes = {
handleWidth: propTypes.bool,
handleHeight: propTypes.bool,
skipOnMount: propTypes.bool,
refreshRate: propTypes.number,
refreshMode: propTypes.string,
refreshOptions: propTypes.shape({
leading: propTypes.bool,
trailing: propTypes.bool
}),
resizableElementId: propTypes.string,
onResize: propTypes.func,
render: propTypes.func,
children: propTypes.any,
// eslint-disable-line react/forbid-prop-types
nodeType: propTypes.node // eslint-disable-line react/forbid-prop-types
};
ResizeDetector.defaultProps = {
handleWidth: false,
handleHeight: false,
skipOnMount: false,
refreshRate: 1000,
refreshMode: undefined,
refreshOptions: undefined,
resizableElementId: '',
onResize: function onResize(e) {
return e;
},
render: undefined,
children: null,
nodeType: 'div'
};
function Toolbar(props) {
var alignLeft = props.alignLeft,
children = props.children,
className = props.className,
overflowCutoff = props.overflowCutoff,
responsive = props.responsive,
rest = objectWithoutProperties(props, ["alignLeft", "children", "className", "overflowCutoff", "responsive"]);
var overflow;
var items = [];
var filterChild = function filterChild(child) {
if (child.type === Toolbar.Overflow) {
overflow = child;
} else {
items.push(child);
}
};
var aChildren = React.Children.toArray(children);
aChildren.forEach(filterChild);
return React.createElement("div", _extends_1({
className: classnames("toolbar", className, {
"align-left": alignLeft
})
}, rest), responsive ? React.createElement(ResizeDetector, {
handleWidth: true
}, function (width) {
if (width > overflowCutoff) {
return React.createElement("div", {
className: "toolbar__content"
}, items);
}
return React.createElement(Popup, {
on: "click",
trigger: React.createElement("i", {
className: "aicon aicon__hamburger"
}),
content: overflow || items,
position: "bottom"
});
}) : React.createElement("div", {
className: "toolbar__content"
}, items));
}
Toolbar.defaultProps = {
alignLeft: false,
responsive: false,
overflowCutoff: 400
};
Toolbar.Separator = function () {
return React.createElement("span", {
className: "toolbar__separator"
});
};
Toolbar.Overflow = function (props) {
return React.createElement("div", null, props.children);
};
Toolbar.displayName = "Toolbar";
Toolbar.Separator.displayName = "ToolbarSeparator";
Toolbar.Overflow.displayName = "ToolbarOverflow";
function Popover$1(_ref) {
var _ref$bodyOffset = _ref.bodyOffset,
bodyOffset = _ref$bodyOffset === void 0 ? 6 : _ref$bodyOffset,
children = _ref.children,
content = _ref.content,
_ref$defaultOpen = _ref.defaultOpen,
defaultOpen = _ref$defaultOpen === void 0 ? false : _ref$defaultOpen,
open = _ref.open,
_ref$on = _ref.on,
on = _ref$on === void 0 ? "" : _ref$on,
onOpen = _ref.onOpen,
onClose = _ref.onClose,
_ref$position = _ref.position,
position = _ref$position === void 0 ? "bottom" : _ref$position,
_ref$targetOffset = _ref.targetOffset,
targetOffset = _ref$targetOffset === void 0 ? 8 : _ref$targetOffset,
trigger = _ref.trigger,
rest = objectWithoutProperties(_ref, ["bodyOffset", "children", "content", "defaultOpen", "open", "on", "onOpen", "onClose", "position", "targetOffset", "trigger"]);
var _React$useState = React.useState(defaultOpen),
_React$useState2 = slicedToArray(_React$useState, 2),
internalIsOpen = _React$useState2[0],
setInternalIsOpen = _React$useState2[1];
var _React$useState3 = React.useState(false),
_React$useState4 = slicedToArray(_React$useState3, 2),
focus = _React$useState4[0],
setFocus = _React$useState4[1]; // Handle close event
var handleClose = React.useCallback(function (e) {
onClose && onClose(e); // Trigger user's custom onClose event
setInternalIsOpen(false);
}, [onClose, setInternalIsOpen]); // Handle clicks on content component
var handleContentClick = React.useCallback(function (e) {
if (content.props && content.props.onClick) {
content.props.onClick(e); // Trigger any onClick events inside content
} // Prevent document's click listener from closing content when clicked
e.nativeEvent.stopImmediatePropagation();
}, [content.props]); // Handle open event
var handleOpen = React.useCallback(function (e) {
onOpen && onOpen(e); // Trigger
setInternalIsOpen(true);
}, [onOpen]); // Handle clicks on trigger component
var handleToggle = React.useCallback(function (e) {
if (open || open === undefined && internalIsOpen) {
handleClose(e);
} else {
handleOpen(e);
}
}, [open, internalIsOpen, handleClose, handleOpen]);
var getEventProps = React.useMemo(function () {
return objectSpread({}, on.indexOf("hover") !== -1 ? {
onMouseEnter: handleOpen,
onMouseLeave: handleClose
} : {}, on.indexOf("focus") !== -1 ? {
onFocus: function onFocus(e) {
handleOpen(e);
setFocus(true);
},
// TODO: Fix the race condition with document click listener
onBlur: function onBlur() {
return setFocus(false);
}
} : {}, on.indexOf("click") !== -1 ? {
onClick: handleToggle
} : {});
}, [on, handleClose, handleOpen, handleToggle, setFocus]); // Click listener for clicks outside of the trigger component
React.useEffect(function () {
if ((open || open === undefined && internalIsOpen) && !focus) {
document.addEventListener("click", handleClose);
}
return function () {
return document.removeEventListener("click", handleClose);
};
}, [internalIsOpen, open, focus, handleClose]);
return React.createElement(Positioner, {
content: React.cloneElement(content, {
onClick: handleContentClick
}),
isShown: open !== undefined ? open : internalIsOpen,
position: position,
bodyOffset: bodyOffset,
targetOffset: targetOffset
}, React.cloneElement(trigger || children, objectSpread({}, getEventProps)));
}
function filterReducer(state, action) {
switch (action.type) {
case "ADD_FIELD":
return [].concat(toConsumableArray(state), [{
field: action.field,
value: action.value
}]);
case "DELETE_FIELD":
return state.filter(function (filter) {
return filter.field !== action.field;
});
case "UPDATE_FIELD":
return state.map(function (filter) {
return filter.field !== action.field ? filter : {
field: action.field,
value: action.value
};
});
default:
return state;
}
}
function FilterControlsText() {
var Text = function Text(_ref) {
var label = _ref.label,
value = _ref.value,
setValue = _ref.setValue,
onDelete = _ref.onDelete,
initialOpen = _ref.initialOpen;
var _React$useState = React__default.useState(initialOpen),
_React$useState2 = slicedToArray(_React$useState, 2),
isOpen = _React$useState2[0],
setIsOpen = _React$useState2[1];
var _React$useState3 = React__default.useState(""),
_React$useState4 = slicedToArray(_React$useState3, 2),
text = _React$useState4[0],
setText = _React$useState4[1];
var handleToggle = React__default.useCallback(function () {
setIsOpen(!isOpen);
setValue(text);
}, [isOpen, setIsOpen, text, setValue]);
return React__default.createElement(Popover$1, {
key: label,
on: "click",
open: isOpen,
onOpen: handleToggle,
onClose: handleToggle,
content: React__default.createElement(Bubble, {
position: "none"
}, "Values: \xA0", React__default.createElement(Input, {
icon: "filter__dismiss link",
value: text,
onChange: function onChange(e) {
return setText(e.target.value);
},
onIconClick: function onIconClick() {
return setText("");
}
}))
}, React__default.createElement(Pill, {
hasMenu: true,
onClose: function onClose(e) {
e.stopPropagation();
onDelete(value);
}
}, React__default.createElement("strong", null, label, ":"), " ", value));
};
Text.getInitialValue = function () {
return "";
};
Text.shouldPillOpen = function (value) {
return value === Text.getInitialValue();
};
return Text;
}
var MultiSelectRow = React__default.memo(function (_ref) {
var selected = _ref.selected,
onClick = _ref.onClick,
children = _ref.children,
value = _ref.value,
rest = objectWithoutProperties(_ref, ["selected", "onClick", "children", "value"]);
return React__default.createElement("div", _extends_1({
className: "menu__item",
key: value,
"data-value": value
}, rest), React__default.createElement(Checkbox$1, {
checked: selected,
value: value,
onChange: onClick
}, children));
});
function FilterControlsMultiSelect(_ref2) {
var options = _ref2.options;
var optionsLabelsMap = {};
options.forEach(function (option) {
optionsLabelsMap[option.value] = option.label;
});
var MultiSelect = function MultiSelect(_ref3) {
var label = _ref3.label,
value = _ref3.value,
setValue = _ref3.setValue,
onDelete = _ref3.onDelete,
initialOpen = _ref3.initialOpen;
var _React$useState = React__default.useState(initialOpen),
_React$useState2 = slicedToArray(_React$useState, 2),
isOpen = _React$useState2[0],
setIsOpen = _React$useState2[1];
var _React$useState3 = React__default.useState(value),
_React$useState4 = slicedToArray(_React$useState3, 2),
selectedValues = _React$useState4[0],
setSelectedValues = _React$useState4[1];
var _React$useState5 = React__default.useState(""),
_React$useState6 = slicedToArray(_React$useState5, 2),
findText = _React$useState6[0],
setFindText = _React$useState6[1];
var handleToggle = React__default.useCallback(function (e) {
e.stopPropagation();
setValue(selectedValues);
setIsOpen(!isOpen);
}, [isOpen, setIsOpen, selectedValues, setValue]);
var handleChange = React__default.useCallback(function (e) {
var _e$target = e.target,
value = _e$target.value,
checked = _e$target.checked;
checked ? setSelectedValues([].concat(toConsumableArray(selectedValues), [value])) : setSelectedValues(selectedValues.filter(function (entry) {
return entry !== value;
}));
}, [selectedValues, setSelectedValues]);
var getRenderedOptions = React__default.useCallback(function () {
return options.filter(function (option) {
return option.label.toLowerCase().includes(findText.toLowerCase());
}).map(function (option) {
return React__default.createElement(MultiSelectRow, {
key: option.value,
selected: selectedValues.includes(option.value),
value: option.value,
onClick: handleChange
}, option.label);
});
}, [options, findText, selectedValues, handleChange]);
return React__default.createElement(Popover$1, {
key: label,
on: "click",
open: isOpen,
onOpen: handleToggle,
onClose: handleToggle,
content: React__default.createElement(Bubble, {
position: "none"
}, options.length > 10 ? React__default.createElement(Input, {
placeholder: "Find...",
icon: "aicon aicon__close-solid link",
value: findText,
onChange: function onChange(e) {
return setFindText(e.target.value);
},
onIconClick: function onIconClick() {
return setFindText("");
}
}) : null, React__default.createElement("div", {
className: "menu__scrollable"
}, getRenderedOptions()))
}, React__default.createElement(Pill, {
title: label,
hasMenu: true,
onClose: function onClose(e) {
e.stopPropagation();
onDelete(value);
}
}, React__default.createElement("strong", null, label, ":"), " ", value.map(function (val, index, array) {
return index === value.length - 1 ? optionsLabelsMap[val] : "".concat(optionsLabelsMap[val], ", ");
})));
};
MultiSelect.getInitialValue = function () {
return [];
};
MultiSelect.shouldPillOpen = function (value) {
return value.length === 0;
};
return MultiSelect;
}
var SingleSelectRow = React__default.memo(function (_ref) {
var active = _ref.active,
onChange = _ref.onChange,
children = _ref.children,
value = _ref.value,
rest = objectWithoutProperties(_ref, ["active", "onChange", "children", "value"]);
return React__default.createElement("div", _extends_1({
onClick: onChange,
"data-value": value,
className: classnames("menu__item", "filter__single-select__row", active ? "filter__single-select__row--active" : null)
}, rest), active ? React__default.createElement(React__default.Fragment, null, React__default.createElement("i", {
className: "filter__selected"
}), "\xA0") : null, children);
});
function FilterControlsSingleSelect(_ref2) {
var options = _ref2.options;
var optionsLabelsMap = {};
options.forEach(function (option) {
optionsLabelsMap[option.value] = option.label;
});
var SingleSelect = function SingleSelect(_ref3) {
var label = _ref3.label,
value = _ref3.value,
setValue = _ref3.setValue,
onDelete = _ref3.onDelete,
initialOpen = _ref3.initialOpen;
var _React$useState = React__default.useState(initialOpen),
_React$useState2 = slicedToArray(_React$useState, 2),
isOpen = _React$useState2[0],
setIsOpen = _React$useState2[1];
var _React$useState3 = React__default.useState(value),
_React$useState4 = slicedToArray(_React$useState3, 2),
selectedValue = _React$useState4[0],
setSelectedValue = _React$useState4[1];
var _React$useState5 = React__default.useState(""),
_React$useState6 = slicedToArray(_React$useState5, 2),
findText = _React$useState6[0],
setFindText = _React$useState6[1];
var handleToggle = React__default.useCallback(function (e) {
e.stopPropagation();
setValue(selectedValue);
setIsOpen(!isOpen);
}, [isOpen, setIsOpen, selectedValue, setValue]);
var handleChange = React__default.useCallback(function (e) {
setSelectedValue(e.target.getAttribute("data-value"));
}, [selectedValue, setSelectedValue]);
var getRenderedOptions = React__default.useCallback(function () {
return options.filter(function (option) {
return option.label.toLowerCase().includes(findText.toLowerCase());
}).map(function (option) {
return React__default.createElement(SingleSelectRow, {
active: selectedValue.toString() === option.value.toString(),
key: option.value,
onChange: handleChange,
value: option.value
}, option.label);
});
}, [options, findText, selectedValue, handleChange]);
return React__default.createElement(Popover$1, {
key: label,
on: "click",
open: isOpen,
onOpen: handleToggle,
onClose: handleToggle,
content: React__default.createElement(Bubble, {
position: "none"
}, options.length > 10 ? React__default.createElement(Input, {
placeholder: "Find...",
icon: "aicon aicon__close-solid link",
value: findText,
onChange: function onChange(e) {
return setFindText(e.target.value);
},
onIconClick: function onIconClick() {
return setFindText("");
}
}) : null, React__default.createElement("div", {
className: "menu__scrollable"
}, getRenderedOptions()))
}, React__default.createElement(Pill, {
title: label,
hasMenu: true,
onClose: function onClose(e) {
e.stopPropagation();
onDelete(value);
}
}, React__default.createElement("strong", null, label, ":"), " ", optionsLabelsMap[value]));
};
SingleSelect.getInitialValue = function () {
return "";
};
SingleSelect.shouldPillOpen = function (value) {
return value === SingleSelect.getInitialValue();
};
return SingleSelect;
}
var moment = createCommonjsModule(function (module, exports) {
(function (global, factory) {
module.exports = factory();
}(commonjsGlobal, (function () {
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 isObjectEmpty(obj) {
if (Object.getOwnPropertyNames) {
return (Object.getOwnPropertyNames(obj).length === 0);
} else {
var k;
for (k in obj) {
if (obj.hasOwnProperty(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;
for (i = 0; i < arr.length; ++i) {
res.push(fn(arr[i], i));
}
return res;
}
function hasOwnProp(a, b) {
return Object.prototype.hasOwnProperty.call(a, b);
}
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,
invalidMonth : null,
invalidFormat : false,
userInvalidated : false,
iso : false,
parsedDateParts : [],
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);
var len = t.length >>> 0;
for (var 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);
var parsedParts = some.call(flags.parsedDateParts, function (i) {
return i != null;
});
var isNowValid = !isNaN(m._d.getTime()) &&
flags.overflow < 0 &&
!flags.empty &&
!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 = [];
function copyConfig(to, from) {
var i, prop, val;
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 (momentProperties.length > 0) {
for (i = 0; i < momentProperties.length; i++) {
prop = momentProperties[i];
val = from[prop];
if (!isUndefined(val)) {
to[prop] = val;
}
}
}
return to;
}
var updateInProgress = false;
// 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 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;
}
// 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;
}
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 = [];
var arg;
for (var i = 0; i < arguments.length; i++) {
arg = '';
if (typeof arguments[i] === 'object') {
arg += '\n[' + i + '] ';
for (var key in arguments[0]) {
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 input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
}
function set (config) {
var prop, i;
for (i in config) {
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;
}
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.replace(/MMMM|MM|DD|dddd/g, function (val) {
return val.slice(1);
});
return this._longDateFormat[key];
}
var defaultInvalidDate = 'Invalid date';
function invalidDate () {
return this._invalidDate;
}
var defaultOrdinal = '%d';
var 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',
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 = [];
for (var u in unitsObj) {
units.push({unit: u, priority: priorities[u]});
}
units.sort(function (a, b) {
return a.priority - b.priority;
});
return units;
}
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?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g;
var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;
var formatFunctions = {};
var 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 match1 = /\d/; // 0 - 9
var match2 = /\d\d/; // 00 - 99
var match3 = /\d{3}/; // 000 - 999
var match4 = /\d{4}/; // 0000 - 9999
var match6 = /[+-]?\d{6}/; // -999999 - 999999
var match1to2 = /\d\d?/; // 0 - 99
var match3to4 = /\d\d\d\d?/; // 999 - 9999
var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999
var match1to3 = /\d{1,3}/; // 0 - 999
var match1to4 = /\d{1,4}/; // 0 - 9999
var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999
var matchUnsigned = /\d+/; // 0 - inf
var matchSigned = /[+-]?\d+/; // -inf - inf
var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z
var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z
var 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
var 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;
var 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;
if (typeof token === 'string') {
token = [token];
}
if (isNumber(callback)) {
func = function (input, array) {
array[callback] = toInt(input);
};
}
for (i = 0; i < token.length; 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;
var MONTH = 1;
var DATE = 2;
var HOUR = 3;
var MINUTE = 4;
var SECOND = 5;
var MILLISECOND = 6;
var WEEK = 7;
var WEEKDAY = 8;
// FORMATTING
addFormatToken('Y', 0, 0, function () {
var y = this.year();
return y <= 9999 ? '' + y : '+' + 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;
}
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
// 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 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) {
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);
for (var i = 0; i < prioritized.length; i++) {
this[prioritized[i].unit](units[prioritized[i].unit]);
}
} else {
units = normalizeUnits(units);
if (isFunction(this[units])) {
return this[units](value);
}
}
return this;
}
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 MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;
var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
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()];
}
var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
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());
}
var defaultMonthsShortRegex = matchWord;
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;
}
}
var defaultMonthsRegex = matchWord;
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');
}
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;
// the Date.UTC function remaps years 0-99 to 1900-1999
if (y < 100 && y >= 0) {
var 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('_');
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;
}
var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
function localeWeekdaysShort (m) {
return (m === true) ? shiftWeekdays(this._weekdaysShort, this._week.dow)
: (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort;
}
var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
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;
}
}
var defaultWeekdaysRegex = matchWord;
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;
}
}
var defaultWeekdaysShortRegex = matchWord;
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;
}
}
var defaultWeekdaysMinRegex = matchWord;
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 = this.weekdaysMin(mom, '');
shortp = this.weekdaysShort(mom, '');
longp = 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);
for (i = 0; i < 7; i++) {
shortPieces[i] = regexEscape(shortPieces[i]);
longPieces[i] = regexEscape(longPieces[i]);
mixedPieces[i] = regexEscape(mixedPieces[i]);
}
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;
var 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;
var 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;
function localeMeridiem (hours, minutes, isLower) {
if (hours > 11) {
return isLower ? 'pm' : 'PM';
} else {
return isLower ? 'am' : 'AM';
}
}
// MOMENTS
// 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.
var getSetHour = makeGetSet('Hours', true);
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 = {};
var localeFamilies = {};
var globalLocale;
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 && compareArrays(split, next, true) >= j - 1) {
//the next array item is better than a shallower substring of this one
break;
}
j--;
}
i++;
}
return globalLocale;
}
function loadLocale(name) {
var oldLocale = null;
// TODO: Find a better way to register and load all the locales in Node
if (!locales[name] && ('object' !== 'undefined') &&
module && module.exports) {
try {
oldLocale = globalLocale._abbr;
var aliasedRequire = commonjsRequire;
aliasedRequire('./locale/' + name);
getSetGlobalLocale(oldLocale);
} catch (e) {}
}
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;
// MERGE
tmpLocale = loadLocale(name);
if (tmpLocale != null) {
parentConfig = tmpLocale._config;
}
config = mergeConfigs(parentConfig, config);
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;
} 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;
var 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;
}
// 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;
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;
var 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;
}
}
// 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)?)?$/;
var 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)?)?$/;
var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/;
var 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}/],
// YYYYMM is NOT allowed by the standard
['GGGG[W]WWE', /\d{4}W\d{3}/],
['GGGG[W]WW', /\d{4}W\d{2}/, false],
['YYYYDDD', /\d{7}/]
];
// iso time formats and regexes
var 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/]
];
var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i;
// date from iso format
function configFromISO(config) {
var i, l,
string = config._i,
match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
allowTime, dateFormat, timeFormat, tzFormat;
if (match) {
getParsingFlags(config).iso = true;
for (i = 0, l = isoDates.length; 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 = isoTimes.length; 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;
}
}
// RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
var 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}))$/;
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 indepentent 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;
}
var 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
};
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);
var 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));
if (match) {
var 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 iso format or fallback
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;
}
// 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 and will be removed in an upcoming major release. Please refer to ' +
'http://momentjs.com/guides/#/warnings/js-date/ for more info.',
function (config) {
config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
}
);
// 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;
tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];
for (i = 0; i < tokens.length; i++) {
token = tokens[i];
parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
// console.log('token', token, 'parsedInput', parsedInput,
// 'regex', getParseRegexForToken(token, config));
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);
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;
if (config._f.length === 0) {
getParsingFlags(config).invalidFormat = true;
config._d = new Date(NaN);
return;
}
for (i = 0; i < config._f.length; i++) {
currentScore = 0;
tempConfig = copyConfig({}, config);
if (config._useUTC != null) {
tempConfig._useUTC = config._useUTC;
}
tempConfig._f = config._f[i];
configFromStringAndFormat(tempConfig);
if (!isValid(tempConfig)) {
continue;
}
// 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 (scoreToBeat == null || currentScore < scoreToBeat) {
scoreToBeat = currentScore;
bestMoment = tempConfig;
}
}
extend(config, bestMoment || tempConfig);
}
function configFromObject(config) {
if (config._d) {
return;
}
var i = normalizeObjectUnits(config._i);
config._a = map([i.year, i.month, i.day || i.date, 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 (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();
}
}
);
var 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) {
for (var key in m) {
if (!(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) {
return false;
}
}
var unitHasDecimal = false;
for (var i = 0; i < ordering.length; ++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);
}
}
// FORMATTING
function offset (token, separator) {
addFormatToken(token, 0, 0, function () {
var offset = this.utcOffset();
var 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);
if (matches === null) {
return null;
}
var chunk = matches[matches.length - 1] || [];
var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
var 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() / 15) * 15;
}
// 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 = {};
copyConfig(c, this);
c = prepareConfig(c);
if (c._a) {
var 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
var 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)) {
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;
}
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;
}
val = typeof val === 'string' ? +val : val;
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');
var subtract = createAdder(-1, 'subtract');
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) {
// 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';
var 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) {
// 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;
var 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';
var zone = '';
if (!this.isLocal()) {
func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
zone = 'Z';
}
var prefix = '[' + func + '("]';
var year = (0 <= this.year() && this.year() <= 9999) ? 'YYYY' : 'YYYYYY';
var datetime = '-MM-DD[T]HH:mm:ss.SSS';
var 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;
var MS_PER_MINUTE = 60 * MS_PER_SECOND;
var MS_PER_HOUR = 60 * MS_PER_MINUTE;
var 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;
units = normalizeUnits(units);
if (units === undefined || units === 'millisecond' || !this.isValid()) {
return this;
}
var 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;
units = normalizeUnits(units);
if (units === undefined || units === 'millisecond' || !this.isValid()) {
return this;
}
var 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
};
}
// 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 getWeeksInYear () {
var weekInfo = this.localeData()._week;
return weeksInYear(this.year(), 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;
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);
}
// MOMENTS
var 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;
proto.toJSON = toJSON;
proto.toString = toString;
proto.unix = unix;
proto.valueOf = valueOf;
proto.creationData = creationData;
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.isoWeeksInYear = getISOWeeksInYear;
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.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();
var 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;
var 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;
if (index != null) {
return get$1(format, (index + shift) % 7, field, 'day');
}
var i;
var out = [];
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', {
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;
var days = this._days;
var months = this._months;
var data = this._data;
var 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;
var months;
var 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');
var asSeconds = makeAs('s');
var asMinutes = makeAs('m');
var asHours = makeAs('h');
var asDays = makeAs('d');
var asWeeks = makeAs('w');
var asMonths = makeAs('M');
var asQuarters = makeAs('Q');
var 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');
var seconds = makeGetter('seconds');
var minutes = makeGetter('minutes');
var hours = makeGetter('hours');
var days = makeGetter('days');
var months = makeGetter('months');
var years = makeGetter('years');
function weeks () {
return absFloor(this.days() / 7);
}
var round = Math.round;
var 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
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, locale) {
var duration = createDuration(posNegDuration).abs();
var seconds = round(duration.as('s'));
var minutes = round(duration.as('m'));
var hours = round(duration.as('h'));
var days = round(duration.as('d'));
var months = round(duration.as('M'));
var years = round(duration.as('y'));
var 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] ||
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 (withSuffix) {
if (!this.isValid()) {
return this.localeData().invalidDate();
}
var locale = this.localeData();
var output = relativeTime$1(this, !withSuffix, 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;
var days = abs$1(this._days);
var months = abs$1(this._months);
var minutes, hours, years;
// 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
var Y = years;
var M = months;
var D = days;
var h = hours;
var m = minutes;
var s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
var total = this.asSeconds();
if (!total) {
// this is the same as C#'s (Noda) and python (isodate)...
// but not other JS (goog.date)
return 'P0D';
}
var totalSign = total < 0 ? '-' : '';
var ymSign = sign(this._months) !== sign(total) ? '-' : '';
var daysSign = sign(this._days) !== sign(total) ? '-' : '';
var hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';
return totalSign + 'P' +
(Y ? ymSign + Y + 'Y' : '') +
(M ? ymSign + M + 'M' : '') +
(D ? daysSign + D + 'D' : '') +
((h || m || s) ? 'T' : '') +
(h ? hmsSign + h + 'H' : '') +
(m ? hmsSign + m + 'M' : '') +
(s ? 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;
// Side effect imports
// 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, 10) * 1000);
});
addParseToken('x', function (input, array, config) {
config._d = new Date(toInt(input));
});
// Side effect imports
hooks.version = '2.24.0';
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;
})));
});
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var invariant$1 = function(condition, format, a, b, c, d, e, f) {
if (!condition) {
var error;
if (format === undefined) {
error = new Error(
'Minified exception occurred; use the non-minified dev environment ' +
'for the full error message and additional helpful warnings.'
);
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(
format.replace(/%s/g, function() { return args[argIndex++]; })
);
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
};
var invariant_1 = invariant$1;
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
var warning$2 = function() {};
var warning_1$1 = warning$2;
var _ = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.isShallowEqual = isShallowEqual;
exports.chunk = chunk;
exports.groupBySortedKeys = groupBySortedKeys;
exports.has = exports.makeArray = void 0;
var _warning = _interopRequireDefault(warning_1$1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var makeArray = function makeArray(obj) {
return obj == null ? [] : [].concat(obj);
};
exports.makeArray = makeArray;
var has = function has(o, k) {
return o ? Object.prototype.hasOwnProperty.call(o, k) : false;
};
exports.has = has;
function isShallowEqual(a, b) {
if (a === b) return true;
if (a instanceof Date && b instanceof Date) return +a === +b;
if (typeof a !== 'object' && typeof b !== 'object') return a === b;
if (typeof a !== typeof b) return false;
if (a == null || b == null) return false; // if they were both null we wouldn't be here
var keysA = Object.keys(a);
var keysB = Object.keys(b);
if (keysA.length !== keysB.length) return false;
for (var i = 0; i < keysA.length; i++) {
if (!has(b, keysA[i]) || a[keysA[i]] !== b[keysA[i]]) return false;
}
return true;
}
function chunk(array, chunkSize) {
var index = 0,
length = array ? array.length : 0;
var result = [];
chunkSize = Math.max(+chunkSize || 1, 1);
while (index < length) {
result.push(array.slice(index, index += chunkSize));
}
return result;
}
function groupBySortedKeys(groupBy, data, keys) {
var iter = typeof groupBy === 'function' ? groupBy : function (item) {
return item[groupBy];
}; // the keys array ensures that groups are rendered in the order they came in
// which means that if you sort the data array it will render sorted,
// so long as you also sorted by group
keys = keys || [];
return data.reduce(function (grps, item) {
var group = iter(item);
if (has(grps, group)) {
grps[group].push(item);
} else {
keys.push(group);
grps[group] = [item];
}
return grps;
}, {});
}
});
unwrapExports(_);
var __1 = _.isShallowEqual;
var __2 = _.chunk;
var __3 = _.groupBySortedKeys;
var __4 = _.has;
var __5 = _.makeArray;
var localizers = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.setNumber = setNumber;
exports.setDate = setDate;
exports.date = exports.number = void 0;
var _invariant = _interopRequireDefault(invariant_1);
var _propTypes = _interopRequireDefault(propTypes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var localePropType = _propTypes.default.oneOfType([_propTypes.default.string, _propTypes.default.func]);
var _numberLocalizer = createWrapper('NumberPicker');
var number = {
propType: function propType() {
var _numberLocalizer2;
return (_numberLocalizer2 = _numberLocalizer).propType.apply(_numberLocalizer2, arguments);
},
getFormat: function getFormat(key, format) {
return format || _numberLocalizer.formats[key];
},
parse: function parse() {
var _numberLocalizer3;
return (_numberLocalizer3 = _numberLocalizer).parse.apply(_numberLocalizer3, arguments);
},
format: function format() {
var _numberLocalizer4;
return (_numberLocalizer4 = _numberLocalizer).format.apply(_numberLocalizer4, arguments);
},
decimalChar: function decimalChar() {
var _numberLocalizer5;
return (_numberLocalizer5 = _numberLocalizer).decimalChar.apply(_numberLocalizer5, arguments);
},
precision: function precision() {
var _numberLocalizer6;
return (_numberLocalizer6 = _numberLocalizer).precision.apply(_numberLocalizer6, arguments);
}
};
exports.number = number;
function setNumber(_ref) {
var format = _ref.format,
_parse = _ref.parse,
formats = _ref.formats,
_ref$propType = _ref.propType,
propType = _ref$propType === void 0 ? localePropType : _ref$propType,
_ref$decimalChar = _ref.decimalChar,
decimalChar = _ref$decimalChar === void 0 ? function () {
return '.';
} : _ref$decimalChar,
_ref$precision = _ref.precision,
precision = _ref$precision === void 0 ? function () {
return null;
} : _ref$precision;
_numberLocalizer = {
formats: formats,
precision: precision,
decimalChar: decimalChar,
propType: propType,
format: wrapFormat(format),
parse: function parse(value, culture, format) {
var result = _parse.call(this, value, culture, format);
!(result == null || typeof result === 'number') ? invariant(false) : void 0;
return result;
}
};
}
var _dateLocalizer = createWrapper('DateTimePicker');
var date = {
propType: function propType() {
var _dateLocalizer2;
return (_dateLocalizer2 = _dateLocalizer).propType.apply(_dateLocalizer2, arguments);
},
getFormat: function getFormat(key, format) {
return format || _dateLocalizer.formats[key];
},
parse: function parse() {
var _dateLocalizer3;
return (_dateLocalizer3 = _dateLocalizer).parse.apply(_dateLocalizer3, arguments);
},
format: function format() {
var _dateLocalizer4;
return (_dateLocalizer4 = _dateLocalizer).format.apply(_dateLocalizer4, arguments);
},
firstOfWeek: function firstOfWeek() {
var _dateLocalizer5;
return (_dateLocalizer5 = _dateLocalizer).firstOfWeek.apply(_dateLocalizer5, arguments);
}
};
exports.date = date;
function setDate(_ref2) {
var formats = _ref2.formats,
format = _ref2.format,
_parse2 = _ref2.parse,
firstOfWeek = _ref2.firstOfWeek,
_ref2$propType = _ref2.propType,
propType = _ref2$propType === void 0 ? localePropType : _ref2$propType;
_dateLocalizer = {
formats: formats,
propType: propType,
firstOfWeek: firstOfWeek,
format: wrapFormat(format),
parse: function parse(value, format, culture) {
var result = _parse2.call(this, value, format, culture);
!(result == null || result instanceof Date && !isNaN(result.getTime())) ? invariant(false) : void 0;
return result;
}
};
}
var wrapFormat = function wrapFormat(formatter) {
return function (value, format, culture) {
var result = typeof format === 'function' ? format(value, culture, this) : formatter.call(this, value, format, culture);
!(result == null || typeof result === 'string') ? invariant(false) : void 0;
return result;
};
};
function createWrapper() {
var dummy = {};
return dummy;
}
});
unwrapExports(localizers);
var localizers_1 = localizers.setNumber;
var localizers_2 = localizers.setDate;
var localizers_3 = localizers.date;
var localizers_4 = localizers.number;
var configure = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var localizers$$1 = _interopRequireWildcard(localizers);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
var _default = {
setLocalizers: function setLocalizers(_ref) {
var date = _ref.date,
number = _ref.number;
date && this.setDateLocalizer(date);
number && this.setNumberLocalizer(number);
},
setDateLocalizer: localizers$$1.setDate,
setNumberLocalizer: localizers$$1.setNumber
};
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(configure);
var reactWidgetsMoment = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = momentLocalizer;
var _moment = _interopRequireDefault(moment);
var _configure = _interopRequireDefault(configure);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
if (typeof _moment.default !== 'function') throw new TypeError('You must provide a valid moment object');
var localField = typeof (0, _moment.default)().locale === 'function' ? 'locale' : 'lang',
hasLocaleData = !!_moment.default.localeData;
if (!hasLocaleData) throw new TypeError('The Moment localizer depends on the `localeData` api, please provide a moment object v2.2.0 or higher');
function getMoment(culture, value, format) {
return culture ? (0, _moment.default)(value, format, true)[localField](culture) : (0, _moment.default)(value, format, true);
}
function endOfDecade(date) {
return (0, _moment.default)(date).add(10, 'year').add(-1, 'millisecond').toDate();
}
function endOfCentury(date) {
return (0, _moment.default)(date).add(100, 'year').add(-1, 'millisecond').toDate();
}
function momentLocalizer() {
var localizer = {
formats: {
date: 'L',
time: 'LT',
default: 'lll',
header: 'MMMM YYYY',
footer: 'LL',
weekday: 'dd',
dayOfMonth: 'DD',
month: 'MMM',
year: 'YYYY',
decade: function decade(date, culture, localizer) {
return localizer.format(date, 'YYYY', culture) + ' - ' + localizer.format(endOfDecade(date), 'YYYY', culture);
},
century: function century(date, culture, localizer) {
return localizer.format(date, 'YYYY', culture) + ' - ' + localizer.format(endOfCentury(date), 'YYYY', culture);
}
},
firstOfWeek: function firstOfWeek(culture) {
return _moment.default.localeData(culture).firstDayOfWeek();
},
parse: function parse(value, format, culture) {
if (!value) return null;
var m = getMoment(culture, value, format);
if (m.isValid()) return m.toDate();
return null;
},
format: function format(value, _format, culture) {
return getMoment(culture, value).format(_format);
}
};
_configure.default.setDateLocalizer(localizer);
}
module.exports = exports["default"];
});
var momentLocalizer = unwrapExports(reactWidgetsMoment);
var interopRequireDefault = createCommonjsModule(function (module) {
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
module.exports = _interopRequireDefault;
});
unwrapExports(interopRequireDefault);
var ownerDocument_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = ownerDocument;
function ownerDocument(node) {
return node && node.ownerDocument || document;
}
module.exports = exports["default"];
});
unwrapExports(ownerDocument_1);
var activeElement_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = activeElement;
var _ownerDocument = interopRequireDefault(ownerDocument_1);
function activeElement(doc) {
if (doc === void 0) {
doc = (0, _ownerDocument.default)();
}
try {
return doc.activeElement;
} catch (e) {
/* ie throws if no active element */
}
}
module.exports = exports["default"];
});
unwrapExports(activeElement_1);
var LIFECYCLE_HOOKS = {
componentWillMount: true,
componentDidMount: true,
componentWillReceiveProps: true,
getSnapshotBeforeUpdate: true,
shouldComponentUpdate: true,
componentWillUpdate: true,
componentDidUpdate: true,
componentWillUnmount: true,
};
var STATIC_HOOKS = {
getDerivedStateFromProps: true,
};
function wrap(base, method, isStatic) {
var before = true;
if (Array.isArray(method)) {
before = method[0] !== 'after';
method = method[1];
}
if (!base) return method
return function wrappedLifecyclehook() {
var ctx = isStatic ? null : this;
before && method.apply(ctx, arguments);
base.apply(ctx, arguments);
!before && method.apply(ctx, arguments);
}
}
var spyOnComponent_1 = function spyOnComponent(component, hooks) {
var originals = Object.create(null);
for (var key in hooks)
if (STATIC_HOOKS[key])
component.constructor[key] = wrap(
(originals[key] = component.constructor[key]),
hooks[key],
true
);
for (var key in hooks)
if (LIFECYCLE_HOOKS[key])
component[key] = wrap((originals[key] = component[key]), hooks[key]);
return function reset(key) {
var subject = STATIC_HOOKS[key] ? component.constructor : component;
if (key && key in originals) subject[key] = originals[key];
else for (var key in originals) subject[key] = originals[key];
}
};
var mixin = function mixinIntoComponent(componentClass, hooks) {
spyOnComponent(componentClass.prototype, hooks);
return componentClass
};
spyOnComponent_1.mixin = mixin;
var autoFocus = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = makeAutoFocusable;
exports.PropTypes = void 0;
var _spyOnComponent = _interopRequireDefault(spyOnComponent_1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var PropTypes = {
autoFocus: propTypes.bool
};
exports.PropTypes = PropTypes;
function makeAutoFocusable(instance) {
(0, _spyOnComponent.default)(instance, {
componentDidMount: function componentDidMount() {
var autoFocus = this.props.autoFocus;
if (autoFocus) this.focus ? this.focus() : (0, _reactDom.findDOMNode)(this).focus();
}
});
}
});
unwrapExports(autoFocus);
var autoFocus_1 = autoFocus.PropTypes;
var mountManager = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = spyOnMount;
var _spyOnComponent = _interopRequireDefault(spyOnComponent_1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function spyOnMount(componentInstance) {
var mounted = true;
(0, _spyOnComponent.default)(componentInstance, {
componentWillUnmount: function componentWillUnmount() {
mounted = false;
}
});
return function () {
return mounted;
};
}
module.exports = exports["default"];
});
unwrapExports(mountManager);
var timeoutManager = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = createTimeoutManager;
var _spyOnComponent = _interopRequireDefault(spyOnComponent_1);
var _mountManager = _interopRequireDefault(mountManager);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function createTimeoutManager(componentInstance) {
var isMounted = (0, _mountManager.default)(componentInstance);
var timers = Object.create(null);
var manager;
(0, _spyOnComponent.default)(componentInstance, {
componentWillUnmount: function componentWillUnmount() {
for (var k in timers) {
clearTimeout(timers[k]);
}
timers = null;
}
});
return manager = {
clear: function clear(key) {
clearTimeout(timers[key]);
},
set: function set(key, fn, ms) {
if (!isMounted()) return;
manager.clear(key);
timers[key] = setTimeout(fn, ms);
}
};
}
module.exports = exports["default"];
});
unwrapExports(timeoutManager);
var focusManager = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.callFocusEventHandler = callFocusEventHandler;
exports.default = createFocusManager;
var _timeoutManager = _interopRequireDefault(timeoutManager);
var _mountManager = _interopRequireDefault(mountManager);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function callFocusEventHandler(inst, focused, e) {
var handler = inst.props[focused ? 'onFocus' : 'onBlur'];
handler && handler(e);
}
function createFocusManager(instance, _temp) {
var _ref = _temp === void 0 ? {} : _temp,
willHandle = _ref.willHandle,
didHandle = _ref.didHandle,
onChange = _ref.onChange,
_ref$isDisabled = _ref.isDisabled,
isDisabled = _ref$isDisabled === void 0 ? function () {
return !!instance.props.disabled;
} : _ref$isDisabled;
var lastFocused;
var timeouts = (0, _timeoutManager.default)(instance);
var isMounted = (0, _mountManager.default)(instance);
function _handleFocus(focused, event) {
if (event && event.persist) event.persist();
if (willHandle && willHandle(focused, event) === false) return;
timeouts.set('focus', function () {
(0, _reactDom.unstable_batchedUpdates)(function () {
if (focused !== lastFocused) {
if (didHandle) didHandle.call(instance, focused, event); // only fire a change when unmounted if its a blur
if (isMounted() || !focused) {
lastFocused = focused;
onChange && onChange(focused, event);
}
}
});
});
}
return {
handleBlur: function handleBlur(event) {
if (!isDisabled()) _handleFocus(false, event);
},
handleFocus: function handleFocus(event) {
if (!isDisabled()) _handleFocus(true, event);
}
};
}
});
unwrapExports(focusManager);
var focusManager_1 = focusManager.callFocusEventHandler;
var mixin_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.mixin = mixin;
exports.default = mixIntoClass;
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 _objectWithoutProperties(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]; } if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function mixin(componentClass, _ref) {
var propTypes = _ref.propTypes,
contextTypes = _ref.contextTypes,
childContextTypes = _ref.childContextTypes,
getChildContext = _ref.getChildContext,
protoSpec = _objectWithoutProperties(_ref, ["propTypes", "contextTypes", "childContextTypes", "getChildContext"]);
if (propTypes) componentClass.propTypes = _extends({}, componentClass.propTypes, propTypes);
if (contextTypes) componentClass.contextTypes = _extends({}, componentClass.contextTypes, contextTypes);
if (childContextTypes) componentClass.childContextTypes = _extends({}, componentClass.childContextTypes, childContextTypes);
if (getChildContext) {
var baseGCContext = componentClass.prototype.getChildContext;
componentClass.prototype.getChildContext = function $getChildContext() {
return _extends({}, baseGCContext && baseGCContext.call(this), getChildContext.call(this));
};
}
_extends(componentClass.prototype, protoSpec);
return componentClass;
}
function mixIntoClass(spec) {
return function (componentClass) {
return mixin(componentClass, spec);
};
}
});
unwrapExports(mixin_1);
var mixin_2 = mixin_1.mixin;
var lib$1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
var _spyOnComponent = _interopRequireDefault(spyOnComponent_1);
exports.spyOnComponent = _spyOnComponent.default;
var _autoFocus = _interopRequireDefault(autoFocus);
exports.autoFocus = _autoFocus.default;
var _focusManager = _interopRequireDefault(focusManager);
exports.focusManager = _focusManager.default;
var _mountManager = _interopRequireDefault(mountManager);
exports.mountManager = _mountManager.default;
var _timeoutManager = _interopRequireDefault(timeoutManager);
exports.timeoutManager = _timeoutManager.default;
var _mixin = _interopRequireDefault(mixin_1);
exports.mixin = _mixin.default;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
});
unwrapExports(lib$1);
var lib_1 = lib$1.spyOnComponent;
var lib_2 = lib$1.autoFocus;
var lib_3 = lib$1.focusManager;
var lib_4 = lib$1.mountManager;
var lib_5 = lib$1.timeoutManager;
var lib_6 = lib$1.mixin;
/**
* 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 componentWillMount() {
// Call this.constructor.gDSFP to support sub-classes.
var state = this.constructor.getDerivedStateFromProps(this.props, this.state);
if (state !== null && state !== undefined) {
this.setState(state);
}
}
function componentWillReceiveProps(nextProps) {
// Call this.constructor.gDSFP to support sub-classes.
// Use the setState() updater to ensure state isn't stale in certain edge cases.
function updater(prevState) {
var state = this.constructor.getDerivedStateFromProps(nextProps, prevState);
return state !== null && state !== undefined ? state : null;
}
// Binding "this" is important for shallow renderer support.
this.setState(updater.bind(this));
}
function componentWillUpdate(nextProps, nextState) {
try {
var prevProps = this.props;
var prevState = this.state;
this.props = nextProps;
this.state = nextState;
this.__reactInternalSnapshotFlag = true;
this.__reactInternalSnapshot = this.getSnapshotBeforeUpdate(
prevProps,
prevState
);
} finally {
this.props = prevProps;
this.state = prevState;
}
}
// React may warn about cWM/cWRP/cWU methods being deprecated.
// Add a flag to suppress these warnings for this special case.
componentWillMount.__suppressDeprecationWarning = true;
componentWillReceiveProps.__suppressDeprecationWarning = true;
componentWillUpdate.__suppressDeprecationWarning = true;
function polyfill(Component) {
var prototype = Component.prototype;
if (!prototype || !prototype.isReactComponent) {
throw new Error('Can only polyfill class components');
}
if (
typeof Component.getDerivedStateFromProps !== 'function' &&
typeof prototype.getSnapshotBeforeUpdate !== 'function'
) {
return Component;
}
// If new component APIs are defined, "unsafe" lifecycles won't be called.
// Error if any of these lifecycles are present,
// Because they would work differently between older and newer (16.3+) versions of React.
var foundWillMountName = null;
var foundWillReceivePropsName = null;
var foundWillUpdateName = null;
if (typeof prototype.componentWillMount === 'function') {
foundWillMountName = 'componentWillMount';
} else if (typeof prototype.UNSAFE_componentWillMount === 'function') {
foundWillMountName = 'UNSAFE_componentWillMount';
}
if (typeof prototype.componentWillReceiveProps === 'function') {
foundWillReceivePropsName = 'componentWillReceiveProps';
} else if (typeof prototype.UNSAFE_componentWillReceiveProps === 'function') {
foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
}
if (typeof prototype.componentWillUpdate === 'function') {
foundWillUpdateName = 'componentWillUpdate';
} else if (typeof prototype.UNSAFE_componentWillUpdate === 'function') {
foundWillUpdateName = 'UNSAFE_componentWillUpdate';
}
if (
foundWillMountName !== null ||
foundWillReceivePropsName !== null ||
foundWillUpdateName !== null
) {
var componentName = Component.displayName || Component.name;
var newApiName =
typeof Component.getDerivedStateFromProps === 'function'
? 'getDerivedStateFromProps()'
: 'getSnapshotBeforeUpdate()';
throw Error(
'Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' +
componentName +
' uses ' +
newApiName +
' but also contains the following legacy lifecycles:' +
(foundWillMountName !== null ? '\n ' + foundWillMountName : '') +
(foundWillReceivePropsName !== null
? '\n ' + foundWillReceivePropsName
: '') +
(foundWillUpdateName !== null ? '\n ' + foundWillUpdateName : '') +
'\n\nThe above lifecycles should be removed. Learn more about this warning here:\n' +
'https://fb.me/react-async-component-lifecycle-hooks'
);
}
// React <= 16.2 does not support static getDerivedStateFromProps.
// As a workaround, use cWM and cWRP to invoke the new static lifecycle.
// Newer versions of React will ignore these lifecycles if gDSFP exists.
if (typeof Component.getDerivedStateFromProps === 'function') {
prototype.componentWillMount = componentWillMount;
prototype.componentWillReceiveProps = componentWillReceiveProps;
}
// React <= 16.2 does not support getSnapshotBeforeUpdate.
// As a workaround, use cWU to invoke the new lifecycle.
// Newer versions of React will ignore that lifecycle if gSBU exists.
if (typeof prototype.getSnapshotBeforeUpdate === 'function') {
if (typeof prototype.componentDidUpdate !== 'function') {
throw new Error(
'Cannot polyfill getSnapshotBeforeUpdate() for components that do not define componentDidUpdate() on the prototype'
);
}
prototype.componentWillUpdate = componentWillUpdate;
var componentDidUpdate = prototype.componentDidUpdate;
prototype.componentDidUpdate = function componentDidUpdatePolyfill(
prevProps,
prevState,
maybeSnapshot
) {
// 16.3+ will not execute our will-update method;
// It will pass a snapshot value to did-update though.
// Older versions will require our polyfilled will-update value.
// We need to handle both cases, but can't just check for the presence of "maybeSnapshot",
// Because for <= 15.x versions this might be a "prevContext" object.
// We also can't just check "__reactInternalSnapshot",
// Because get-snapshot might return a falsy value.
// So check for the explicit __reactInternalSnapshotFlag flag to determine behavior.
var snapshot = this.__reactInternalSnapshotFlag
? this.__reactInternalSnapshot
: maybeSnapshot;
componentDidUpdate.call(this, prevProps, prevState, snapshot);
};
}
return Component;
}
var reactLifecyclesCompat_es = /*#__PURE__*/Object.freeze({
polyfill: polyfill
});
var utils = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.uncontrolledPropTypes = uncontrolledPropTypes;
exports.isProp = isProp;
exports.defaultKey = defaultKey;
exports.isReactComponent = isReactComponent;
var _invariant = _interopRequireDefault(invariant_1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var noop = function noop() {};
function uncontrolledPropTypes(controlledValues, displayName) {
var propTypes = {};
Object.keys(controlledValues).forEach(function (prop) {
// add default propTypes for folks that use runtime checks
propTypes[defaultKey(prop)] = noop;
});
return propTypes;
}
function isProp(props, prop) {
return props[prop] !== undefined;
}
function defaultKey(key) {
return 'default' + key.charAt(0).toUpperCase() + key.substr(1);
}
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function isReactComponent(component) {
return !!(component && component.prototype && component.prototype.isReactComponent);
}
});
unwrapExports(utils);
var utils_1 = utils.uncontrolledPropTypes;
var utils_2 = utils.isProp;
var utils_3 = utils.defaultKey;
var utils_4 = utils.isReactComponent;
var uncontrollable_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = uncontrollable;
var _react = _interopRequireDefault(React__default);
var _invariant = _interopRequireDefault(invariant_1);
var Utils = _interopRequireWildcard(utils);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
function uncontrollable(Component, controlledValues, methods) {
if (methods === void 0) {
methods = [];
}
var displayName = Component.displayName || Component.name || 'Component';
var isCompositeComponent = Utils.isReactComponent(Component);
var controlledProps = Object.keys(controlledValues);
var PROPS_TO_OMIT = controlledProps.map(Utils.defaultKey);
!(isCompositeComponent || !methods.length) ? invariant(false) : void 0;
var UncontrolledComponent =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(UncontrolledComponent, _React$Component);
function UncontrolledComponent() {
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.handlers = Object.create(null);
controlledProps.forEach(function (propName) {
var handlerName = controlledValues[propName];
var handleChange = function handleChange(value) {
if (_this.props[handlerName]) {
var _this$props;
_this._notifying = true;
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
(_this$props = _this.props)[handlerName].apply(_this$props, [value].concat(args));
_this._notifying = false;
}
_this._values[propName] = value;
if (!_this.unmounted) _this.forceUpdate();
};
_this.handlers[handlerName] = handleChange;
});
if (isCompositeComponent) _this.attachRef = function (ref) {
_this.inner = ref;
};
return _this;
}
var _proto = UncontrolledComponent.prototype;
_proto.shouldComponentUpdate = function shouldComponentUpdate() {
//let the forceUpdate trigger the update
return !this._notifying;
};
_proto.componentWillMount = function componentWillMount() {
var _this2 = this;
var props = this.props;
this._values = Object.create(null);
controlledProps.forEach(function (key) {
_this2._values[key] = props[Utils.defaultKey(key)];
});
};
_proto.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
var _this3 = this;
var props = this.props;
controlledProps.forEach(function (key) {
/**
* If a prop switches from controlled to Uncontrolled
* reset its value to the defaultValue
*/
if (!Utils.isProp(nextProps, key) && Utils.isProp(props, key)) {
_this3._values[key] = nextProps[Utils.defaultKey(key)];
}
});
};
_proto.componentWillUnmount = function componentWillUnmount() {
this.unmounted = true;
};
_proto.getControlledInstance = function getControlledInstance() {
return this.inner;
};
_proto.render = function render() {
var _this4 = this;
var props = _extends({}, this.props);
PROPS_TO_OMIT.forEach(function (prop) {
delete props[prop];
});
var newProps = {};
controlledProps.forEach(function (propName) {
var propValue = _this4.props[propName];
newProps[propName] = propValue !== undefined ? propValue : _this4._values[propName];
});
return _react.default.createElement(Component, _extends({}, props, newProps, this.handlers, {
ref: this.attachRef
}));
};
return UncontrolledComponent;
}(_react.default.Component);
UncontrolledComponent.displayName = "Uncontrolled(" + displayName + ")";
UncontrolledComponent.propTypes = Utils.uncontrolledPropTypes(controlledValues, displayName);
methods.forEach(function (method) {
UncontrolledComponent.prototype[method] = function $proxiedMethod() {
var _inner;
return (_inner = this.inner)[method].apply(_inner, arguments);
};
});
UncontrolledComponent.ControlledComponent = Component;
/**
* useful when wrapping a Component and you want to control
* everything
*/
UncontrolledComponent.deferControlTo = function (newComponent, additions, nextMethods) {
if (additions === void 0) {
additions = {};
}
return uncontrollable(newComponent, _extends({}, controlledValues, additions), nextMethods);
};
return UncontrolledComponent;
}
module.exports = exports["default"];
});
unwrapExports(uncontrollable_1);
var Widget_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _react = _interopRequireDefault(React__default);
var _propTypes = _interopRequireDefault(propTypes);
var _classnames = _interopRequireDefault(classnames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutProperties(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]; } if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var Widget =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(Widget, _React$Component);
function Widget() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = Widget.prototype;
_proto.render = function render() {
var _this$props = this.props,
className = _this$props.className,
tabIndex = _this$props.tabIndex,
focused = _this$props.focused,
open = _this$props.open,
dropUp = _this$props.dropUp,
disabled = _this$props.disabled,
readOnly = _this$props.readOnly,
autofilling = _this$props.autofilling,
_this$props$isRtl = _this$props.isRtl,
isRtl = _this$props$isRtl === void 0 ? this.context.isRtl : _this$props$isRtl,
props = _objectWithoutProperties(_this$props, ["className", "tabIndex", "focused", "open", "dropUp", "disabled", "readOnly", "autofilling", "isRtl"]);
tabIndex = tabIndex != null ? tabIndex : '-1';
return _react.default.createElement("div", _extends({}, props, {
tabIndex: tabIndex,
className: (0, _classnames.default)(className, 'rw-widget', isRtl && 'rw-rtl', disabled && 'rw-state-disabled', readOnly && 'rw-state-readonly', focused && 'rw-state-focus', autofilling && 'rw-webkit-autofill', open && "rw-open" + (dropUp ? '-up' : ''))
}));
};
return Widget;
}(_react.default.Component);
Widget.contextTypes = {
isRtl: _propTypes.default.bool
};
Widget.propTypes = {
tabIndex: _propTypes.default.node,
focused: _propTypes.default.bool,
disabled: _propTypes.default.bool,
readOnly: _propTypes.default.bool,
autofilling: _propTypes.default.bool,
open: _propTypes.default.bool,
dropUp: _propTypes.default.bool,
isRtl: _propTypes.default.bool
};
var _default = Widget;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(Widget_1);
var WidgetPicker_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _react = _interopRequireDefault(React__default);
var _propTypes = _interopRequireDefault(propTypes);
var _classnames = _interopRequireDefault(classnames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutProperties(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]; } if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var WidgetPicker =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(WidgetPicker, _React$Component);
function WidgetPicker() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = WidgetPicker.prototype;
_proto.render = function render() {
var _this$props = this.props,
open = _this$props.open,
dropUp = _this$props.dropUp,
className = _this$props.className,
disabled = _this$props.disabled,
readOnly = _this$props.readOnly,
focused = _this$props.focused,
props = _objectWithoutProperties(_this$props, ["open", "dropUp", "className", "disabled", "readOnly", "focused"]);
var openClass = "rw-open" + (dropUp ? '-up' : '');
return _react.default.createElement("div", _extends({}, props, {
className: (0, _classnames.default)(className, 'rw-widget-picker', 'rw-widget-container', open && openClass, disabled && 'rw-state-disabled', readOnly && 'rw-state-readonly', focused && 'rw-state-focus')
}));
};
return WidgetPicker;
}(_react.default.Component);
WidgetPicker.propTypes = {
tabIndex: _propTypes.default.node,
focused: _propTypes.default.bool,
disabled: _propTypes.default.bool,
readOnly: _propTypes.default.bool,
open: _propTypes.default.bool,
dropUp: _propTypes.default.bool,
picker: _propTypes.default.bool
};
var _default = WidgetPicker;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(WidgetPicker_1);
var Button_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _react = _interopRequireDefault(React__default);
var _propTypes = _interopRequireDefault(propTypes);
var _classnames = _interopRequireDefault(classnames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutProperties(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]; } if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var Loading = function Loading() {
return _react.default.createElement("span", {
"aria-hidden": "true",
className: "rw-i rw-loading"
});
};
var Button =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(Button, _React$Component);
function Button() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = Button.prototype;
_proto.render = function render() {
var _this$props = this.props,
className = _this$props.className,
disabled = _this$props.disabled,
label = _this$props.label,
icon = _this$props.icon,
busy = _this$props.busy,
active = _this$props.active,
children = _this$props.children,
_this$props$variant = _this$props.variant,
variant = _this$props$variant === void 0 ? 'primary' : _this$props$variant,
_this$props$spinner = _this$props.spinner,
spinner = _this$props$spinner === void 0 ? _react.default.createElement(Loading, null) : _this$props$spinner,
_this$props$component = _this$props.component,
Tag = _this$props$component === void 0 ? 'button' : _this$props$component,
props = _objectWithoutProperties(_this$props, ["className", "disabled", "label", "icon", "busy", "active", "children", "variant", "spinner", "component"]);
var type = props.type;
if (Tag === 'button') type = type || 'button';
return _react.default.createElement(Tag, _extends({}, props, {
tabIndex: "-1",
title: label,
type: type,
disabled: disabled,
"aria-disabled": disabled,
"aria-label": label,
className: (0, _classnames.default)(className, 'rw-btn', active && !disabled && 'rw-state-active', variant && 'rw-btn-' + variant)
}), busy ? spinner : icon, children);
};
return Button;
}(_react.default.Component);
Button.propTypes = {
disabled: _propTypes.default.bool,
label: _propTypes.default.string,
icon: _propTypes.default.node,
busy: _propTypes.default.bool,
active: _propTypes.default.bool,
variant: _propTypes.default.oneOf(['primary', 'select']),
component: _propTypes.default.any,
spinner: _propTypes.default.node
};
var _default = Button;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(Button_1);
var Select_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _react = _interopRequireDefault(React__default);
var _propTypes = _interopRequireDefault(propTypes);
var _classnames = _interopRequireDefault(classnames);
var _Button = _interopRequireDefault(Button_1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutProperties(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]; } if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var Select =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(Select, _React$Component);
function Select() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = Select.prototype;
_proto.render = function render() {
var _this$props = this.props,
className = _this$props.className,
bordered = _this$props.bordered,
children = _this$props.children,
props = _objectWithoutProperties(_this$props, ["className", "bordered", "children"]);
return _react.default.createElement("span", {
className: (0, _classnames.default)(className, 'rw-select', bordered && 'rw-select-bordered')
}, children ? _react.default.Children.map(children, function (child) {
return child && _react.default.cloneElement(child, {
variant: 'select'
});
}) : _react.default.createElement(_Button.default, _extends({}, props, {
variant: "select"
})));
};
return Select;
}(_react.default.Component);
Select.propTypes = {
bordered: _propTypes.default.bool
};
var _default = Select;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(Select_1);
var inDOM = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _default = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(inDOM);
var on_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _inDOM = interopRequireDefault(inDOM);
var on = function on() {};
if (_inDOM.default) {
on = function () {
if (document.addEventListener) return function (node, eventName, handler, capture) {
return node.addEventListener(eventName, handler, capture || false);
};else if (document.attachEvent) return function (node, eventName, handler) {
return node.attachEvent('on' + eventName, function (e) {
e = e || window.event;
e.target = e.target || e.srcElement;
e.currentTarget = node;
handler.call(node, e);
});
};
}();
}
var _default = on;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(on_1);
var off_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _inDOM = interopRequireDefault(inDOM);
var off = function off() {};
if (_inDOM.default) {
off = function () {
if (document.addEventListener) return function (node, eventName, handler, capture) {
return node.removeEventListener(eventName, handler, capture || false);
};else if (document.attachEvent) return function (node, eventName, handler) {
return node.detachEvent('on' + eventName, handler);
};
}();
}
var _default = off;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(off_1);
var contains = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _inDOM = interopRequireDefault(inDOM);
var _default = function () {
// HTML DOM and SVG DOM may have different support levels,
// so we need to check on context instead of a document root element.
return _inDOM.default ? function (context, node) {
if (context.contains) {
return context.contains(node);
} else if (context.compareDocumentPosition) {
return context === node || !!(context.compareDocumentPosition(node) & 16);
} else {
return fallback(context, node);
}
} : fallback;
}();
exports.default = _default;
function fallback(context, node) {
if (node) do {
if (node === context) return true;
} while (node = node.parentNode);
return false;
}
module.exports = exports["default"];
});
unwrapExports(contains);
var querySelectorAll = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = qsa;
// Zepto.js
// (c) 2010-2015 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
var simpleSelectorRE = /^[\w-]*$/;
var toArray = Function.prototype.bind.call(Function.prototype.call, [].slice);
function qsa(element, selector) {
var maybeID = selector[0] === '#',
maybeClass = selector[0] === '.',
nameOnly = maybeID || maybeClass ? selector.slice(1) : selector,
isSimple = simpleSelectorRE.test(nameOnly),
found;
if (isSimple) {
if (maybeID) {
element = element.getElementById ? element : document;
return (found = element.getElementById(nameOnly)) ? [found] : [];
}
if (element.getElementsByClassName && maybeClass) return toArray(element.getElementsByClassName(nameOnly));
return toArray(element.getElementsByTagName(selector));
}
return toArray(element.querySelectorAll(selector));
}
module.exports = exports["default"];
});
unwrapExports(querySelectorAll);
var filter = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = filterEvents;
var _contains = interopRequireDefault(contains);
var _querySelectorAll = interopRequireDefault(querySelectorAll);
function filterEvents(selector, handler) {
return function filterHandler(e) {
var top = e.currentTarget,
target = e.target,
matches = (0, _querySelectorAll.default)(top, selector);
if (matches.some(function (match) {
return (0, _contains.default)(match, target);
})) handler.call(this, e);
};
}
module.exports = exports["default"];
});
unwrapExports(filter);
var listen_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _inDOM = interopRequireDefault(inDOM);
var _on = interopRequireDefault(on_1);
var _off = interopRequireDefault(off_1);
var listen = function listen() {};
if (_inDOM.default) {
listen = function listen(node, eventName, handler, capture) {
(0, _on.default)(node, eventName, handler, capture);
return function () {
(0, _off.default)(node, eventName, handler, capture);
};
};
}
var _default = listen;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(listen_1);
var events = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _on = interopRequireDefault(on_1);
exports.on = _on.default;
var _off = interopRequireDefault(off_1);
exports.off = _off.default;
var _filter = interopRequireDefault(filter);
exports.filter = _filter.default;
var _listen = interopRequireDefault(listen_1);
exports.listen = _listen.default;
var _default = {
on: _on.default,
off: _off.default,
filter: _filter.default,
listen: _listen.default
};
exports.default = _default;
});
unwrapExports(events);
var events_1 = events.on;
var events_2 = events.off;
var events_3 = events.filter;
var events_4 = events.listen;
var camelize_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = camelize;
var rHyphen = /-(.)/g;
function camelize(string) {
return string.replace(rHyphen, function (_, chr) {
return chr.toUpperCase();
});
}
module.exports = exports["default"];
});
unwrapExports(camelize_1);
var camelizeStyle = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = camelizeStyleName;
var _camelize = interopRequireDefault(camelize_1);
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
* https://github.com/facebook/react/blob/2aeb8a2a6beb00617a4217f7f8284924fa2ad819/src/vendor/core/camelizeStyleName.js
*/
var msPattern = /^-ms-/;
function camelizeStyleName(string) {
return (0, _camelize.default)(string.replace(msPattern, 'ms-'));
}
module.exports = exports["default"];
});
unwrapExports(camelizeStyle);
var hyphenate_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = hyphenate;
var rUpper = /([A-Z])/g;
function hyphenate(string) {
return string.replace(rUpper, '-$1').toLowerCase();
}
module.exports = exports["default"];
});
unwrapExports(hyphenate_1);
var hyphenateStyle = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = hyphenateStyleName;
var _hyphenate = interopRequireDefault(hyphenate_1);
/**
* Copyright 2013-2014, Facebook, Inc.
* All rights reserved.
* https://github.com/facebook/react/blob/2aeb8a2a6beb00617a4217f7f8284924fa2ad819/src/vendor/core/hyphenateStyleName.js
*/
var msPattern = /^ms-/;
function hyphenateStyleName(string) {
return (0, _hyphenate.default)(string).replace(msPattern, '-ms-');
}
module.exports = exports["default"];
});
unwrapExports(hyphenateStyle);
var getComputedStyle$1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = _getComputedStyle;
var _camelizeStyle = interopRequireDefault(camelizeStyle);
var rposition = /^(top|right|bottom|left)$/;
var rnumnonpx = /^([+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|))(?!px)[a-z%]+$/i;
function _getComputedStyle(node) {
if (!node) throw new TypeError('No Element passed to `getComputedStyle()`');
var doc = node.ownerDocument;
return 'defaultView' in doc ? doc.defaultView.opener ? node.ownerDocument.defaultView.getComputedStyle(node, null) : window.getComputedStyle(node, null) : {
//ie 8 "magic" from: https://github.com/jquery/jquery/blob/1.11-stable/src/css/curCSS.js#L72
getPropertyValue: function getPropertyValue(prop) {
var style = node.style;
prop = (0, _camelizeStyle.default)(prop);
if (prop == 'float') prop = 'styleFloat';
var current = node.currentStyle[prop] || null;
if (current == null && style && style[prop]) current = style[prop];
if (rnumnonpx.test(current) && !rposition.test(prop)) {
// Remember the original values
var left = style.left;
var runStyle = node.runtimeStyle;
var rsLeft = runStyle && runStyle.left; // Put in the new values to get a computed value out
if (rsLeft) runStyle.left = node.currentStyle.left;
style.left = prop === 'fontSize' ? '1em' : current;
current = style.pixelLeft + 'px'; // Revert the changed values
style.left = left;
if (rsLeft) runStyle.left = rsLeft;
}
return current;
}
};
}
module.exports = exports["default"];
});
unwrapExports(getComputedStyle$1);
var removeStyle_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = removeStyle;
function removeStyle(node, key) {
return 'removeProperty' in node.style ? node.style.removeProperty(key) : node.style.removeAttribute(key);
}
module.exports = exports["default"];
});
unwrapExports(removeStyle_1);
var properties = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = exports.animationEnd = exports.animationDelay = exports.animationTiming = exports.animationDuration = exports.animationName = exports.transitionEnd = exports.transitionDuration = exports.transitionDelay = exports.transitionTiming = exports.transitionProperty = exports.transform = void 0;
var _inDOM = interopRequireDefault(inDOM);
var transform = 'transform';
exports.transform = transform;
var prefix, transitionEnd, animationEnd;
exports.animationEnd = animationEnd;
exports.transitionEnd = transitionEnd;
var transitionProperty, transitionDuration, transitionTiming, transitionDelay;
exports.transitionDelay = transitionDelay;
exports.transitionTiming = transitionTiming;
exports.transitionDuration = transitionDuration;
exports.transitionProperty = transitionProperty;
var animationName, animationDuration, animationTiming, animationDelay;
exports.animationDelay = animationDelay;
exports.animationTiming = animationTiming;
exports.animationDuration = animationDuration;
exports.animationName = animationName;
if (_inDOM.default) {
var _getTransitionPropert = getTransitionProperties();
prefix = _getTransitionPropert.prefix;
exports.transitionEnd = transitionEnd = _getTransitionPropert.transitionEnd;
exports.animationEnd = animationEnd = _getTransitionPropert.animationEnd;
exports.transform = transform = prefix + "-" + transform;
exports.transitionProperty = transitionProperty = prefix + "-transition-property";
exports.transitionDuration = transitionDuration = prefix + "-transition-duration";
exports.transitionDelay = transitionDelay = prefix + "-transition-delay";
exports.transitionTiming = transitionTiming = prefix + "-transition-timing-function";
exports.animationName = animationName = prefix + "-animation-name";
exports.animationDuration = animationDuration = prefix + "-animation-duration";
exports.animationTiming = animationTiming = prefix + "-animation-delay";
exports.animationDelay = animationDelay = prefix + "-animation-timing-function";
}
var _default = {
transform: transform,
end: transitionEnd,
property: transitionProperty,
timing: transitionTiming,
delay: transitionDelay,
duration: transitionDuration
};
exports.default = _default;
function getTransitionProperties() {
var style = document.createElement('div').style;
var vendorMap = {
O: function O(e) {
return "o" + e.toLowerCase();
},
Moz: function Moz(e) {
return e.toLowerCase();
},
Webkit: function Webkit(e) {
return "webkit" + e;
},
ms: function ms(e) {
return "MS" + e;
}
};
var vendors = Object.keys(vendorMap);
var transitionEnd, animationEnd;
var prefix = '';
for (var i = 0; i < vendors.length; i++) {
var vendor = vendors[i];
if (vendor + "TransitionProperty" in style) {
prefix = "-" + vendor.toLowerCase();
transitionEnd = vendorMap[vendor]('TransitionEnd');
animationEnd = vendorMap[vendor]('AnimationEnd');
break;
}
}
if (!transitionEnd && 'transitionProperty' in style) transitionEnd = 'transitionend';
if (!animationEnd && 'animationName' in style) animationEnd = 'animationend';
style = null;
return {
animationEnd: animationEnd,
transitionEnd: transitionEnd,
prefix: prefix
};
}
});
unwrapExports(properties);
var properties_1 = properties.animationEnd;
var properties_2 = properties.animationDelay;
var properties_3 = properties.animationTiming;
var properties_4 = properties.animationDuration;
var properties_5 = properties.animationName;
var properties_6 = properties.transitionEnd;
var properties_7 = properties.transitionDuration;
var properties_8 = properties.transitionDelay;
var properties_9 = properties.transitionTiming;
var properties_10 = properties.transitionProperty;
var properties_11 = properties.transform;
var isTransform_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = isTransform;
var supportedTransforms = /^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i;
function isTransform(property) {
return !!(property && supportedTransforms.test(property));
}
module.exports = exports["default"];
});
unwrapExports(isTransform_1);
var style_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = style;
var _camelizeStyle = interopRequireDefault(camelizeStyle);
var _hyphenateStyle = interopRequireDefault(hyphenateStyle);
var _getComputedStyle2 = interopRequireDefault(getComputedStyle$1);
var _removeStyle = interopRequireDefault(removeStyle_1);
var _isTransform = interopRequireDefault(isTransform_1);
function style(node, property, value) {
var css = '';
var transforms = '';
var props = property;
if (typeof property === 'string') {
if (value === undefined) {
return node.style[(0, _camelizeStyle.default)(property)] || (0, _getComputedStyle2.default)(node).getPropertyValue((0, _hyphenateStyle.default)(property));
} else {
(props = {})[property] = value;
}
}
Object.keys(props).forEach(function (key) {
var value = props[key];
if (!value && value !== 0) {
(0, _removeStyle.default)(node, (0, _hyphenateStyle.default)(key));
} else if ((0, _isTransform.default)(key)) {
transforms += key + "(" + value + ") ";
} else {
css += (0, _hyphenateStyle.default)(key) + ": " + value + ";";
}
});
if (transforms) {
css += properties.transform + ": " + transforms + ";";
}
node.style.cssText += ';' + css;
}
module.exports = exports["default"];
});
unwrapExports(style_1);
var isWindow = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = getWindow;
function getWindow(node) {
return node === node.window ? node : node.nodeType === 9 ? node.defaultView || node.parentWindow : false;
}
module.exports = exports["default"];
});
unwrapExports(isWindow);
var offset_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = offset;
var _contains = interopRequireDefault(contains);
var _isWindow = interopRequireDefault(isWindow);
var _ownerDocument = interopRequireDefault(ownerDocument_1);
function offset(node) {
var doc = (0, _ownerDocument.default)(node),
win = (0, _isWindow.default)(doc),
docElem = doc && doc.documentElement,
box = {
top: 0,
left: 0,
height: 0,
width: 0
};
if (!doc) return; // Make sure it's not a disconnected DOM node
if (!(0, _contains.default)(docElem, node)) return box;
if (node.getBoundingClientRect !== undefined) box = node.getBoundingClientRect(); // IE8 getBoundingClientRect doesn't support width & height
box = {
top: box.top + (win.pageYOffset || docElem.scrollTop) - (docElem.clientTop || 0),
left: box.left + (win.pageXOffset || docElem.scrollLeft) - (docElem.clientLeft || 0),
width: (box.width == null ? node.offsetWidth : box.width) || 0,
height: (box.height == null ? node.offsetHeight : box.height) || 0
};
return box;
}
module.exports = exports["default"];
});
unwrapExports(offset_1);
var height_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = height;
var _offset = interopRequireDefault(offset_1);
var _isWindow = interopRequireDefault(isWindow);
function height(node, client) {
var win = (0, _isWindow.default)(node);
return win ? win.innerHeight : client ? node.clientHeight : (0, _offset.default)(node).height;
}
module.exports = exports["default"];
});
unwrapExports(height_1);
var PropTypes = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.classNamesShape = exports.timeoutsShape = void 0;
var _propTypes = _interopRequireDefault(propTypes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var timeoutsShape = null;
exports.timeoutsShape = timeoutsShape;
var classNamesShape = null;
exports.classNamesShape = classNamesShape;
});
unwrapExports(PropTypes);
var PropTypes_1 = PropTypes.classNamesShape;
var PropTypes_2 = PropTypes.timeoutsShape;
var Transition_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = exports.EXITING = exports.ENTERED = exports.ENTERING = exports.EXITED = exports.UNMOUNTED = void 0;
var PropTypes$$1 = _interopRequireWildcard(propTypes);
var _react = _interopRequireDefault(React__default);
var _reactDom$$1 = _interopRequireDefault(_reactDom);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var UNMOUNTED = 'unmounted';
exports.UNMOUNTED = UNMOUNTED;
var EXITED = 'exited';
exports.EXITED = EXITED;
var ENTERING = 'entering';
exports.ENTERING = ENTERING;
var ENTERED = 'entered';
exports.ENTERED = ENTERED;
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: 0 },
* entered: { opacity: 1 },
* };
*
* 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'`.
*/
exports.EXITING = EXITING;
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.transitionGroup; // 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;
}
var _proto = Transition.prototype;
_proto.getChildContext = function getChildContext() {
return {
transitionGroup: null // allows for nested Transitions
};
};
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 }
// }
_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();
var node = _reactDom$$1.default.findDOMNode(this);
if (nextStatus === ENTERING) {
this.performEnter(node, mounting);
} else {
this.performExit(node);
}
} else if (this.props.unmountOnExit && this.state.status === EXITED) {
this.setState({
status: UNMOUNTED
});
}
};
_proto.performEnter = function performEnter(node, mounting) {
var _this2 = this;
var enter = this.props.enter;
var appearing = this.context.transitionGroup ? this.context.transitionGroup.isMounting : mounting;
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) {
this.safeSetState({
status: ENTERED
}, function () {
_this2.props.onEntered(node);
});
return;
}
this.props.onEnter(node, appearing);
this.safeSetState({
status: ENTERING
}, function () {
_this2.props.onEntering(node, appearing);
_this2.onTransitionEnd(node, enterTimeout, function () {
_this2.safeSetState({
status: ENTERED
}, function () {
_this2.props.onEntered(node, appearing);
});
});
});
};
_proto.performExit = function performExit(node) {
var _this3 = this;
var exit = this.props.exit;
var timeouts = this.getTimeouts(); // no exit animation skip right to EXITED
if (!exit) {
this.safeSetState({
status: EXITED
}, function () {
_this3.props.onExited(node);
});
return;
}
this.props.onExit(node);
this.safeSetState({
status: EXITING
}, function () {
_this3.props.onExiting(node);
_this3.onTransitionEnd(node, timeouts.exit, function () {
_this3.safeSetState({
status: EXITED
}, function () {
_this3.props.onExited(node);
});
});
});
};
_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(node, timeout, handler) {
this.setNextCallback(handler);
var doesNotHaveTimeoutOrListener = timeout == null && !this.props.addEndListener;
if (!node || doesNotHaveTimeoutOrListener) {
setTimeout(this.nextCallback, 0);
return;
}
if (this.props.addEndListener) {
this.props.addEndListener(node, this.nextCallback);
}
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,
childProps = _objectWithoutPropertiesLoose(_this$props, ["children"]); // filter props for Transtition
delete childProps.in;
delete childProps.mountOnEnter;
delete childProps.unmountOnExit;
delete childProps.appear;
delete childProps.enter;
delete childProps.exit;
delete childProps.timeout;
delete childProps.addEndListener;
delete childProps.onEnter;
delete childProps.onEntering;
delete childProps.onEntered;
delete childProps.onExit;
delete childProps.onExiting;
delete childProps.onExited;
if (typeof children === 'function') {
return children(status, childProps);
}
var child = _react.default.Children.only(children);
return _react.default.cloneElement(child, childProps);
};
return Transition;
}(_react.default.Component);
Transition.contextTypes = {
transitionGroup: PropTypes$$1.object
};
Transition.childContextTypes = {
transitionGroup: function transitionGroup() {}
};
Transition.propTypes = {};
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 = 0;
Transition.EXITED = 1;
Transition.ENTERING = 2;
Transition.ENTERED = 3;
Transition.EXITING = 4;
var _default = (0, reactLifecyclesCompat_es.polyfill)(Transition);
exports.default = _default;
});
unwrapExports(Transition_1);
var Transition_2 = Transition_1.EXITING;
var Transition_3 = Transition_1.ENTERED;
var Transition_4 = Transition_1.ENTERING;
var Transition_5 = Transition_1.EXITED;
var Transition_6 = Transition_1.UNMOUNTED;
var SlideDownTransition_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _classnames = _interopRequireDefault(classnames);
var _events = _interopRequireDefault(events);
var _style = _interopRequireDefault(style_1);
var _height = _interopRequireDefault(height_1);
var _propTypes = _interopRequireDefault(propTypes);
var _react = _interopRequireDefault(React__default);
var _Transition = _interopRequireWildcard(Transition_1);
var _transitionClasses;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var transitionClasses = (_transitionClasses = {}, _transitionClasses[_Transition.ENTERING] = 'rw-popup-transition-entering', _transitionClasses[_Transition.EXITING] = 'rw-popup-transition-exiting', _transitionClasses[_Transition.EXITED] = 'rw-popup-transition-exited', _transitionClasses);
var propTypes$$1 = {
in: _propTypes.default.bool.isRequired,
dropUp: _propTypes.default.bool,
onEntering: _propTypes.default.func,
onEntered: _propTypes.default.func
};
function parseDuration(node) {
var str = (0, _style.default)(node, properties.transitionDuration);
var mult = str.indexOf('ms') === -1 ? 1000 : 1;
return parseFloat(str) * mult;
}
var SlideDownTransition =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(SlideDownTransition, _React$Component);
function SlideDownTransition() {
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.setContainerHeight = function (elem) {
elem.style.height = _this.getHeight() + 'px';
};
_this.clearContainerHeight = function (elem) {
elem.style.height = '';
};
_this.handleEntered = function (elem) {
_this.clearContainerHeight(elem);
if (_this.props.onEntered) _this.props.onEntered();
};
_this.handleEntering = function () {
if (_this.props.onEntering) _this.props.onEntering();
};
_this.handleTransitionEnd = function (node, done) {
var duration = parseDuration(node.lastChild) || 0;
var handler = function handler() {
_events.default.off(node, properties.transitionEnd, handler, false);
done();
};
setTimeout(handler, duration * 1.5);
_events.default.on(node, properties.transitionEnd, handler, false);
};
_this.attachRef = function (ref) {
return _this.element = ref;
};
return _this;
}
var _proto = SlideDownTransition.prototype;
_proto.getHeight = function getHeight() {
var container = this.element;
var content = container.firstChild;
var margin = parseInt((0, _style.default)(content, 'margin-top'), 10) + parseInt((0, _style.default)(content, 'margin-bottom'), 10);
var old = container.style.display;
var height;
container.style.display = 'block';
height = ((0, _height.default)(content) || 0) + (isNaN(margin) ? 0 : margin);
container.style.display = old;
return height;
};
_proto.render = function render() {
var _this2 = this;
var _this$props = this.props,
children = _this$props.children,
className = _this$props.className,
dropUp = _this$props.dropUp;
return _react.default.createElement(_Transition.default, {
appear: true,
in: this.props.in,
timeout: 5000,
onEnter: this.setContainerHeight,
onEntering: this.handleEntering,
onEntered: this.handleEntered,
onExit: this.setContainerHeight,
onExited: this.clearContainerHeight,
addEndListener: this.handleTransitionEnd
}, function (status, innerProps) {
return _react.default.createElement("div", _extends({}, innerProps, {
ref: _this2.attachRef,
className: (0, _classnames.default)(className, dropUp && 'rw-dropup', transitionClasses[status])
}), _react.default.createElement("div", {
className: "rw-popup-transition"
}, children));
});
};
return SlideDownTransition;
}(_react.default.Component);
SlideDownTransition.propTypes = propTypes$$1;
var _default = SlideDownTransition;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(SlideDownTransition_1);
var createChainableTypeChecker_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = createChainableTypeChecker;
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
// Mostly taken from ReactPropTypes.
function createChainableTypeChecker(validate) {
function checkType(isRequired, props, propName, componentName, location, propFullName) {
var componentNameSafe = componentName || '<<anonymous>>';
var propFullNameSafe = propFullName || propName;
if (props[propName] == null) {
if (isRequired) {
return new Error('Required ' + location + ' `' + propFullNameSafe + '` was not specified ' + ('in `' + componentNameSafe + '`.'));
}
return null;
}
for (var _len = arguments.length, args = Array(_len > 6 ? _len - 6 : 0), _key = 6; _key < _len; _key++) {
args[_key - 6] = arguments[_key];
}
return validate.apply(undefined, [props, propName, componentNameSafe, location, propFullNameSafe].concat(args));
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
module.exports = exports['default'];
});
unwrapExports(createChainableTypeChecker_1);
var elementType_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react2 = _interopRequireDefault(React__default);
var _createChainableTypeChecker2 = _interopRequireDefault(createChainableTypeChecker_1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function elementType(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (_react2.default.isValidElement(propValue)) {
return new Error('Invalid ' + location + ' `' + propFullName + '` of type ReactElement ' + ('supplied to `' + componentName + '`,expected an element type (a string ') + ', component class, or function component).');
}
if (!(0, reactIs.isValidElementType)(propValue)) {
return new Error('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected an element type (a string ') + ', component class, or function component).');
}
return null;
}
exports.default = (0, _createChainableTypeChecker2.default)(elementType);
module.exports = exports['default'];
});
unwrapExports(elementType_1);
var PropTypes$2 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.message = exports.accessor = exports.disabled = exports.dateFormat = exports.numberFormat = void 0;
var _propTypes = _interopRequireDefault(propTypes);
var _elementType = _interopRequireDefault(elementType_1);
exports.elementType = _elementType.default;
var _createChainableTypeChecker = _interopRequireDefault(createChainableTypeChecker_1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var numberFormat = (0, _createChainableTypeChecker.default)(function () {
return localizers.number.propType.apply(localizers.number, arguments);
});
exports.numberFormat = numberFormat;
var dateFormat = (0, _createChainableTypeChecker.default)(function () {
return localizers.date.propType.apply(localizers.date, arguments);
});
exports.dateFormat = dateFormat;
var disabled = (0, _createChainableTypeChecker.default)(function () {
return _propTypes.default.bool.apply(_propTypes.default, arguments);
});
exports.disabled = disabled;
disabled.acceptsArray = _propTypes.default.oneOfType([disabled, _propTypes.default.array]);
var accessor = _propTypes.default.oneOfType([_propTypes.default.string, _propTypes.default.func]);
exports.accessor = accessor;
var message = _propTypes.default.oneOfType([_propTypes.default.node, _propTypes.default.string, _propTypes.default.func]);
exports.message = message;
});
unwrapExports(PropTypes$2);
var PropTypes_1$1 = PropTypes$2.message;
var PropTypes_2$1 = PropTypes$2.accessor;
var PropTypes_3 = PropTypes$2.disabled;
var PropTypes_4 = PropTypes$2.dateFormat;
var PropTypes_5 = PropTypes$2.numberFormat;
var PropTypes_6 = PropTypes$2.elementType;
var Popup_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _classnames = _interopRequireDefault(classnames);
var _propTypes = _interopRequireDefault(propTypes);
var _react = _interopRequireWildcard(React__default);
var _SlideDownTransition = _interopRequireDefault(SlideDownTransition_1);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutProperties(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]; } if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var StaticContainer =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(StaticContainer, _React$Component);
function StaticContainer() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = StaticContainer.prototype;
_proto.shouldComponentUpdate = function shouldComponentUpdate(_ref) {
var shouldUpdate = _ref.shouldUpdate;
return !!shouldUpdate;
};
_proto.render = function render() {
var _this$props = this.props,
className = _this$props.className,
children = _this$props.children,
props = _objectWithoutProperties(_this$props, ["className", "children"]);
delete props.shouldUpdate;
return (0, _react.cloneElement)(children, _extends({}, props, {
className: (0, _classnames.default)(className, children.props.className, 'rw-popup')
}));
};
return StaticContainer;
}(_react.default.Component);
StaticContainer.propTypes = {
shouldUpdate: function shouldUpdate() {}
};
var Popup =
/*#__PURE__*/
function (_React$Component2) {
_inheritsLoose(Popup, _React$Component2);
function Popup() {
return _React$Component2.apply(this, arguments) || this;
}
var _proto2 = Popup.prototype;
_proto2.render = function render() {
var _this$props2 = this.props,
className = _this$props2.className,
dropUp = _this$props2.dropUp,
open = _this$props2.open,
Transition = _this$props2.transition,
props = _objectWithoutProperties(_this$props2, ["className", "dropUp", "open", "transition"]);
return _react.default.createElement(Transition, _extends({}, props, {
in: open,
dropUp: dropUp,
className: (0, _classnames.default)(className, 'rw-popup-container')
}), _react.default.createElement(StaticContainer, {
shouldUpdate: open
}, _react.default.Children.only(this.props.children)));
};
return Popup;
}(_react.default.Component);
Popup.defaultProps = {
open: false,
transition: _SlideDownTransition.default
};
Popup.propTypes = {
open: _propTypes.default.bool,
dropUp: _propTypes.default.bool,
onEntering: _propTypes.default.func,
onEntered: _propTypes.default.func,
transition: PropTypes$2.elementType
};
var _default = Popup;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(Popup_1);
var Props = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.pick = pick;
exports.pickElementProps = pickElementProps;
exports.omitOwn = omitOwn;
var whitelist = ['style', 'className', 'role', 'id', 'autocomplete', 'size', 'tabIndex', 'maxLength', 'name'];
var whitelistRegex = [/^aria-/, /^data-/, /^on[A-Z]\w+/];
function pick(props, componentClass) {
var keys = Object.keys(componentClass.propTypes);
var result = {};
Object.keys(props).forEach(function (key) {
if (keys.indexOf(key) === -1) return;
result[key] = props[key];
});
return result;
}
function pickElementProps(component) {
for (var _len = arguments.length, others = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
others[_key - 1] = arguments[_key];
}
var props = omitOwn.apply(void 0, [component].concat(others));
var result = {};
Object.keys(props).forEach(function (key) {
if (whitelist.indexOf(key) !== -1 || whitelistRegex.some(function (r) {
return !!key.match(r);
})) result[key] = props[key];
});
return result;
}
function omitOwn(component) {
var initial = Object.keys(component.constructor.propTypes);
for (var _len2 = arguments.length, others = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
others[_key2 - 1] = arguments[_key2];
}
var keys = others.reduce(function (arr, compClass) {
return arr.concat(Object.keys(compClass.propTypes));
}, initial);
var result = {};
Object.keys(component.props).forEach(function (key) {
if (keys.indexOf(key) !== -1) return;
result[key] = component.props[key];
});
return result;
}
});
unwrapExports(Props);
var Props_1 = Props.pick;
var Props_2 = Props.pickElementProps;
var Props_3 = Props.omitOwn;
var widgetHelpers = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.notify = notify;
exports.instanceId = instanceId;
exports.isFirstFocusedRender = isFirstFocusedRender;
var idCount = 0;
function uniqueId(prefix) {
return '' + ((prefix == null ? '' : prefix) + ++idCount);
}
function notify(handler, args) {
handler && handler.apply(null, [].concat(args));
}
function instanceId(component, suffix) {
if (suffix === void 0) {
suffix = '';
}
component.__id || (component.__id = uniqueId('rw_'));
return (component.props.id || component.__id) + suffix;
}
/**
* Allows for defering popup rendering untill the widget is focused,
* or has been opened (in order to not remove it suddenly on close)
*/
function isFirstFocusedRender(component) {
return component._firstFocus || (component.state.focused || !!component.props.open) && (component._firstFocus = true);
}
});
unwrapExports(widgetHelpers);
var widgetHelpers_1 = widgetHelpers.notify;
var widgetHelpers_2 = widgetHelpers.instanceId;
var widgetHelpers_3 = widgetHelpers.isFirstFocusedRender;
var dataHelpers = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.dataIndexOf = dataIndexOf;
exports.valueMatcher = valueMatcher;
exports.dataItem = dataItem;
exports.dataText = exports.dataValue = void 0;
var dataValue = function dataValue(data, field) {
var value = data;
if (typeof field === 'function') value = field(data);else if (data == null) value = data;else if (typeof field === 'string' && typeof data === 'object' && field in data) value = data[field];
return value;
};
exports.dataValue = dataValue;
var dataText = function dataText(item, textField) {
var value = dataValue(item, textField);
return value == null ? '' : value + '';
};
exports.dataText = dataText;
function dataIndexOf(data, item, valueField) {
var idx = -1;
var isValueEqual = function isValueEqual(datum) {
return valueMatcher(item, datum, valueField);
};
while (++idx < data.length) {
var datum = data[idx];
if (datum === item || isValueEqual(datum)) return idx;
}
return -1;
}
/**
* I don't know that the shallow equal makes sense here but am too afraid to
* remove it.
*/
function valueMatcher(a, b, valueField) {
return (0, _.isShallowEqual)(dataValue(a, valueField), dataValue(b, valueField));
}
function dataItem(data, item, valueField) {
var idx = dataIndexOf(data, item, valueField);
return idx !== -1 ? data[idx] : item;
}
});
unwrapExports(dataHelpers);
var dataHelpers_1 = dataHelpers.dataIndexOf;
var dataHelpers_2 = dataHelpers.valueMatcher;
var dataHelpers_3 = dataHelpers.dataItem;
var dataHelpers_4 = dataHelpers.dataText;
var dataHelpers_5 = dataHelpers.dataValue;
var Filter = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.indexOf = indexOf;
exports.filter = filter;
exports.suggest = suggest;
exports.propTypes = exports.presets = void 0;
var _propTypes = _interopRequireDefault(propTypes);
var CustomPropTypes = _interopRequireWildcard(PropTypes$2);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(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]; } if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
var presets = {
eq: function eq(a, b) {
return a === b;
},
neq: function neq(a, b) {
return a !== b;
},
gt: function gt(a, b) {
return a > b;
},
gte: function gte(a, b) {
return a >= b;
},
lt: function lt(a, b) {
return a < b;
},
lte: function lte(a, b) {
return a <= b;
},
contains: function contains(a, b) {
return a.indexOf(b) !== -1;
},
startsWith: function startsWith(a, b) {
return a.lastIndexOf(b, 0) === 0;
},
endsWith: function endsWith(a, b) {
var pos = a.length - b.length;
var lastIndex = a.indexOf(b, pos);
return lastIndex !== -1 && lastIndex === pos;
}
};
exports.presets = presets;
function normalizeFilterType(type) {
if (type === false) return null;
if (type === true) return 'startsWith';
return type || 'eq';
}
function normalizeFilter(_ref) {
var filter = _ref.filter,
_ref$caseSensitive = _ref.caseSensitive,
caseSensitive = _ref$caseSensitive === void 0 ? false : _ref$caseSensitive,
textField = _ref.textField;
filter = normalizeFilterType(filter);
if (typeof filter === 'function' || !filter) {
return filter;
}
filter = presets[filter];
return function (item, searchTerm) {
var textValue = (0, dataHelpers.dataText)(item, textField);
if (!caseSensitive) {
textValue = textValue.toLowerCase();
searchTerm = searchTerm.toLowerCase();
}
return filter(textValue, searchTerm);
};
}
function normalizeOptions(nextOptions) {
var options = _extends({}, nextOptions);
options.minLengh = options.minLengh || 0;
options.filter = normalizeFilter(options);
return options;
}
var propTypes$$1 = {
textField: CustomPropTypes.accessor,
caseSensitive: _propTypes.default.bool,
minLength: _propTypes.default.number,
filter: _propTypes.default.oneOfType([_propTypes.default.func, _propTypes.default.bool, _propTypes.default.oneOf(Object.keys(presets))])
};
exports.propTypes = propTypes$$1;
function indexOf(data, _ref2) {
var _ref2$searchTerm = _ref2.searchTerm,
searchTerm = _ref2$searchTerm === void 0 ? '' : _ref2$searchTerm,
options = _objectWithoutProperties(_ref2, ["searchTerm"]);
var _normalizeOptions = normalizeOptions(options),
filter = _normalizeOptions.filter,
minLength = _normalizeOptions.minLength;
if (!filter || !searchTerm || !searchTerm.trim() || searchTerm.length < minLength) return -1;
for (var idx = 0; idx < data.length; idx++) {
if (filter(data[idx], searchTerm, idx)) return idx;
}
return -1;
}
function filter(data, _ref3) {
var _ref3$searchTerm = _ref3.searchTerm,
searchTerm = _ref3$searchTerm === void 0 ? '' : _ref3$searchTerm,
options = _objectWithoutProperties(_ref3, ["searchTerm"]);
var _normalizeOptions2 = normalizeOptions(options),
filter = _normalizeOptions2.filter,
minLength = _normalizeOptions2.minLength;
if (!filter || !searchTerm || !searchTerm.trim() || searchTerm.length < minLength) return data;
return data.filter(function (item, idx) {
return filter(item, searchTerm, idx);
});
}
function suggest(data, _ref4) {
var _ref4$searchTerm = _ref4.searchTerm,
searchTerm = _ref4$searchTerm === void 0 ? '' : _ref4$searchTerm,
options = _objectWithoutProperties(_ref4, ["searchTerm"]);
var _normalizeOptions3 = normalizeOptions(options),
filter = _normalizeOptions3.filter,
minLength = _normalizeOptions3.minLength;
if (!filter || !searchTerm || !searchTerm.trim() || searchTerm.length < minLength) return searchTerm;
for (var idx = 0; idx < data.length; idx++) {
if (filter(data[idx], searchTerm, idx)) return data[idx];
}
return searchTerm;
}
});
unwrapExports(Filter);
var Filter_1 = Filter.indexOf;
var Filter_2 = Filter.filter;
var Filter_3 = Filter.suggest;
var Filter_4 = Filter.propTypes;
var Filter_5 = Filter.presets;
var reduceToListState_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.defaultGetDataState = defaultGetDataState;
exports.getCommonListProps = getCommonListProps;
exports.default = reduceToListState;
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); }
var EMPTY_VALUE = {};
var returnFalse = function returnFalse() {
return false;
};
function defaultGetDataState(data, _ref, lastState) {
var groupBy = _ref.groupBy;
if (lastState === void 0) {
lastState = {};
}
if (lastState.data !== data || lastState.groupBy !== groupBy) {
if (!groupBy) return {};
var keys = [];
var groups = (0, _.groupBySortedKeys)(groupBy, data, keys);
return {
data: data,
groupBy: groupBy,
groups: groups,
sortedKeys: keys,
sequentialData: Object.keys(groups).reduce(function (flat, grp) {
return flat.concat(groups[grp]);
}, [])
};
}
return lastState;
}
var getStateGetterFromList = function getStateGetterFromList(_ref2) {
var l = _ref2.listComponent;
return l && l.getDataState;
};
var getIsDisabled = function getIsDisabled(disabledProp, valueField) {
return !Array.isArray(disabledProp) ? returnFalse : function (item) {
return disabledProp.some(function (i) {
return (0, dataHelpers.dataValue)(item, valueField) === (0, dataHelpers.dataValue)(i, valueField);
});
};
};
function getCommonListProps(list, accessors, _ref3) {
var groupBy = _ref3.groupBy,
optionComponent = _ref3.optionComponent,
itemComponent = _ref3.itemComponent,
groupComponent = _ref3.groupComponent,
searchTerm = _ref3.searchTerm,
listProps = _ref3.listProps;
return _extends({
searchTerm: searchTerm,
groupBy: groupBy,
groupComponent: groupComponent,
itemComponent: itemComponent,
optionComponent: optionComponent
}, listProps, {
data: list.data,
dataState: list.state,
textAccessor: accessors.text,
valueAccessor: accessors.value
});
}
function reduceToListState(nextListData, prevList, _temp) {
var _ref4 = _temp === void 0 ? {} : _temp,
nextProps = _ref4.nextProps,
getDataState = _ref4.getDataState;
var disabled = nextProps.disabled,
valueField = nextProps.valueField,
textField = nextProps.textField;
getDataState = getDataState || getStateGetterFromList(nextProps) || defaultGetDataState;
var dataState = getDataState(nextListData, nextProps, prevList && prevList.dataState);
var data = dataState && dataState.sequentialData || nextListData;
var isDisabled = getIsDisabled(disabled, valueField);
var moveNext = function moveNext(item, word) {
return isDisabled(item) || word && !Filter.presets.startsWith((0, dataHelpers.dataText)(item, textField).toLowerCase(), word.toLowerCase());
};
var list = {
dataState: dataState,
isDisabled: isDisabled,
first: function first() {
return list.next(EMPTY_VALUE);
},
last: function last() {
return list.prevEnabled(data[data.length - 1]);
},
prev: function prev(item, word) {
var nextIdx = Math.max(0, data.indexOf(item)) - 1;
while (nextIdx > -1 && moveNext(data[nextIdx], word)) {
nextIdx--;
}
if (nextIdx >= 0) return data[nextIdx];
return isDisabled(item) ? null : item;
},
next: function next(item, word) {
var nextIdx = data.indexOf(item) + 1;
while (nextIdx < data.length && moveNext(data[nextIdx], word)) {
nextIdx++;
}
if (nextIdx < data.length) return data[nextIdx];
return isDisabled(item) ? null : item;
},
prevEnabled: function prevEnabled(item) {
return isDisabled(item) ? list.prev(item) : item;
},
nextEnabled: function nextEnabled(item) {
return isDisabled(item) ? list.next(item) : item;
}
};
return list;
}
});
unwrapExports(reduceToListState_1);
var reduceToListState_2 = reduceToListState_1.defaultGetDataState;
var reduceToListState_3 = reduceToListState_1.getCommonListProps;
var Listbox_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _react = _interopRequireDefault(React__default);
var _propTypes = _interopRequireDefault(propTypes);
var _classnames = _interopRequireDefault(classnames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutProperties(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]; } if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var propTypes$$1 = {
className: _propTypes.default.string,
role: _propTypes.default.string,
nodeRef: _propTypes.default.func,
emptyListMessage: _propTypes.default.node
};
var Listbox =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(Listbox, _React$Component);
function Listbox() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = Listbox.prototype;
_proto.render = function render() {
var _this$props = this.props,
className = _this$props.className,
role = _this$props.role,
children = _this$props.children,
emptyListMessage = _this$props.emptyListMessage,
nodeRef = _this$props.nodeRef,
props = _objectWithoutProperties(_this$props, ["className", "role", "children", "emptyListMessage", "nodeRef"]);
var id = (0, widgetHelpers.instanceId)(this);
return _react.default.createElement("ul", _extends({
id: id,
tabIndex: "-1",
ref: nodeRef,
className: (0, _classnames.default)(className, 'rw-list'),
role: role === undefined ? 'listbox' : role
}, props), _react.default.Children.count(children) ? children : _react.default.createElement("li", {
className: "rw-list-empty"
}, emptyListMessage));
};
return Listbox;
}(_react.default.Component);
Listbox.propTypes = propTypes$$1;
var _default = Listbox;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(Listbox_1);
var ListOption_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _react = _interopRequireDefault(React__default);
var _propTypes = _interopRequireDefault(propTypes);
var _classnames = _interopRequireDefault(classnames);
var Props$$1 = _interopRequireWildcard(Props);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var ListOption =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(ListOption, _React$Component);
function ListOption() {
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.handleSelect = function (event) {
var _this$props = _this.props,
onSelect = _this$props.onSelect,
disabled = _this$props.disabled,
dataItem = _this$props.dataItem;
if (onSelect && !disabled) onSelect(dataItem, event);
};
return _this;
}
var _proto = ListOption.prototype;
_proto.render = function render() {
var _this$props2 = this.props,
className = _this$props2.className,
children = _this$props2.children,
focused = _this$props2.focused,
selected = _this$props2.selected,
disabled = _this$props2.disabled,
activeId = _this$props2.activeId;
var Tag = this.props.component || 'li';
var props = Props$$1.omitOwn(this);
var classes = {
'rw-state-focus': focused,
'rw-state-selected': selected,
'rw-state-disabled': disabled
};
var id = focused ? activeId : undefined;
return _react.default.createElement(Tag, _extends({
id: id,
role: "option",
tabIndex: !disabled ? '-1' : undefined,
"aria-selected": !!selected,
className: (0, _classnames.default)('rw-list-option', className, classes),
onClick: this.handleSelect
}, props), children);
};
return ListOption;
}(_react.default.Component);
ListOption.propTypes = {
activeId: _propTypes.default.string,
dataItem: _propTypes.default.any,
index: _propTypes.default.number,
focused: _propTypes.default.bool,
selected: _propTypes.default.bool,
disabled: _propTypes.default.bool,
onSelect: _propTypes.default.func,
component: _propTypes.default.string
};
var _default = ListOption;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(ListOption_1);
var ListOptionGroup_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _classnames = _interopRequireDefault(classnames);
var _react = _interopRequireDefault(React__default);
var _propTypes = _interopRequireDefault(propTypes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var propTypes$$1 = {
className: _propTypes.default.string,
component: _propTypes.default.string
};
function ListOptionGroup(_ref) {
var children = _ref.children,
className = _ref.className,
_ref$component = _ref.component,
component = _ref$component === void 0 ? 'li' : _ref$component;
var Tag = component;
return _react.default.createElement(Tag, {
tabIndex: "-1",
role: "separator",
className: (0, _classnames.default)(className, 'rw-list-optgroup')
}, children);
}
ListOptionGroup.propTypes = propTypes$$1;
var _default = ListOptionGroup;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(ListOptionGroup_1);
var messages_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.getMessages = getMessages;
var _react = _interopRequireDefault(React__default);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var messages = {
moveBack: 'Navigate back',
moveForward: 'Navigate forward',
dateButton: 'Select date',
timeButton: 'Select time',
openCombobox: 'open combobox',
openDropdown: 'open dropdown',
placeholder: '',
filterPlaceholder: '',
emptyList: 'There are no items in this list',
emptyFilter: 'The filter returned no results',
createOption: function createOption(_ref) {
var searchTerm = _ref.searchTerm;
return [' Create option', searchTerm && ' ', searchTerm && _react.default.createElement("strong", {
key: "_"
}, "\"" + searchTerm + "\"")];
},
tagsLabel: 'Selected items',
removeLabel: 'Remove selected item',
noneSelected: 'no selected items',
selectedItems: function selectedItems(labels) {
return "Selected items: " + labels.join(', ');
},
// number
increment: 'Increment value',
decrement: 'Decrement value'
};
function getMessages(defaults) {
if (defaults === void 0) {
defaults = {};
}
var processed = {};
Object.keys(messages).forEach(function (message) {
var value = defaults[message];
if (value == null) value = messages[message];
processed[message] = typeof value === 'function' ? value : function () {
return value;
};
});
return processed;
}
});
unwrapExports(messages_1);
var messages_2 = messages_1.getMessages;
var List_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _propTypes = _interopRequireDefault(propTypes);
var _react = _interopRequireDefault(React__default);
var CustomPropTypes = _interopRequireWildcard(PropTypes$2);
var Props$$1 = _interopRequireWildcard(Props);
var _Listbox = _interopRequireDefault(Listbox_1);
var _ListOption = _interopRequireDefault(ListOption_1);
var _ListOptionGroup = _interopRequireDefault(ListOptionGroup_1);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutProperties(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]; } if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var EMPTY_DATA_STATE = {};
var propTypes$$1 = {
data: _propTypes.default.array,
dataState: _propTypes.default.shape({
sortedKeys: _propTypes.default.array,
groups: _propTypes.default.object,
data: _propTypes.default.array,
sequentialData: _propTypes.default.array
}),
valueAccessor: CustomPropTypes.accessor,
textAccessor: CustomPropTypes.accessor,
onSelect: _propTypes.default.func,
onMove: _propTypes.default.func,
activeId: _propTypes.default.string,
itemComponent: CustomPropTypes.elementType,
groupComponent: CustomPropTypes.elementType,
optionComponent: CustomPropTypes.elementType,
renderItem: _propTypes.default.func,
renderGroup: _propTypes.default.func,
focusedItem: _propTypes.default.any,
selectedItem: _propTypes.default.any,
searchTerm: _propTypes.default.string,
isDisabled: _propTypes.default.func.isRequired,
messages: _propTypes.default.shape({
emptyList: _propTypes.default.func.isRequired
})
};
var defaultProps = {
onSelect: function onSelect() {},
data: [],
dataState: EMPTY_DATA_STATE,
optionComponent: _ListOption.default
};
var List =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(List, _React$Component);
function List() {
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.renderItem = function (_ref) {
var item = _ref.item,
rest = _objectWithoutProperties(_ref, ["item"]);
var _this$props = _this.props,
isDisabled = _this$props.isDisabled,
renderItem = _this$props.renderItem,
textAccessor = _this$props.textAccessor,
valueAccessor = _this$props.valueAccessor;
var Component = _this.props.itemComponent;
if (renderItem) {
return renderItem(_extends({
item: item
}, rest));
} else if (Component) {
return _react.default.createElement(Component, _extends({
item: item,
value: valueAccessor(item),
text: textAccessor(item),
disabled: isDisabled(item)
}, rest));
}
return textAccessor(item);
};
_this.renderGroup = function (group) {
var _this$props2 = _this.props,
renderGroup = _this$props2.renderGroup,
Component = _this$props2.groupComponent;
if (renderGroup) {
return renderGroup({
group: group
});
} else if (Component) {
return _react.default.createElement(Component, {
item: group
});
}
return group;
};
return _this;
}
var _proto = List.prototype;
_proto.componentDidMount = function componentDidMount() {
this.move();
};
_proto.componentDidUpdate = function componentDidUpdate() {
this.move();
};
_proto.mapItems = function mapItems(fn) {
var _this$props3 = this.props,
data = _this$props3.data,
dataState = _this$props3.dataState;
var sortedKeys = dataState.sortedKeys,
groups = dataState.groups;
if (!groups) return data.map(function (item, idx) {
return fn(item, idx, false);
});
var idx = -1;
return sortedKeys.reduce(function (items, key) {
var group = groups[key];
return items.concat(fn(key, idx, true), group.map(function (item) {
return fn(item, ++idx, false);
}));
}, []);
};
_proto.move = function move() {
var _this$props4 = this.props,
focusedItem = _this$props4.focusedItem,
onMove = _this$props4.onMove,
data = _this$props4.data,
dataState = _this$props4.dataState;
var list = (0, _reactDom.findDOMNode)(this);
var idx = renderedIndexOf(focusedItem, list, data, dataState);
var selectedItem = list.children[idx];
if (selectedItem) (0, widgetHelpers.notify)(onMove, [selectedItem, list, focusedItem]);
};
_proto.renderOption = function renderOption(item, index) {
var _this$props5 = this.props,
activeId = _this$props5.activeId,
focusedItem = _this$props5.focusedItem,
selectedItem = _this$props5.selectedItem,
onSelect = _this$props5.onSelect,
isDisabled = _this$props5.isDisabled,
searchTerm = _this$props5.searchTerm,
Option = _this$props5.optionComponent;
var isFocused = focusedItem === item;
return _react.default.createElement(Option, {
dataItem: item,
key: 'item_' + index,
index: index,
activeId: activeId,
focused: isFocused,
onSelect: onSelect,
disabled: isDisabled(item),
selected: selectedItem === item
}, this.renderItem({
item: item,
index: index,
searchTerm: searchTerm
}));
};
_proto.render = function render() {
var _this2 = this;
var _this$props6 = this.props,
className = _this$props6.className,
messages = _this$props6.messages;
var elementProps = Props$$1.pickElementProps(this);
var _getMessages = (0, messages_1.getMessages)(messages),
emptyList = _getMessages.emptyList;
return _react.default.createElement(_Listbox.default, _extends({}, elementProps, {
className: className,
emptyListMessage: emptyList(this.props)
}), this.mapItems(function (item, idx, isHeader) {
return isHeader ? _react.default.createElement(_ListOptionGroup.default, {
key: 'group_' + item,
group: item
}, _this2.renderGroup(item)) : _this2.renderOption(item, idx);
}));
};
return List;
}(_react.default.Component);
List.getDataState = reduceToListState_1.defaultGetDataState;
function renderedIndexOf(item, list, data, dataState) {
var groups = dataState.groups,
sortedKeys = dataState.sortedKeys;
if (!groups) return data.indexOf(item);
var runningIdx = -1;
var idx = -1;
sortedKeys.some(function (group) {
var itemIdx = groups[group].indexOf(item);
runningIdx++;
if (itemIdx !== -1) {
idx = runningIdx + itemIdx + 1;
return true;
}
runningIdx += groups[group].length;
});
return idx;
}
List.propTypes = propTypes$$1;
List.defaultProps = defaultProps;
var _default = List;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(List_1);
var AddToListOption_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var PropTypes = _interopRequireWildcard(propTypes);
var _react = _interopRequireDefault(React__default);
var _Listbox = _interopRequireDefault(Listbox_1);
var _ListOption = _interopRequireDefault(ListOption_1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
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 _objectWithoutProperties(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]; } if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
var propTypes$$1 = {
searchTerm: PropTypes.string,
focused: PropTypes.bool,
onSelect: PropTypes.func.isRequired,
activeId: PropTypes.string
};
function AddToListOption(_ref) {
var searchTerm = _ref.searchTerm,
onSelect = _ref.onSelect,
focused = _ref.focused,
children = _ref.children,
activeId = _ref.activeId,
props = _objectWithoutProperties(_ref, ["searchTerm", "onSelect", "focused", "children", "activeId"]);
return _react.default.createElement(_Listbox.default, _extends({}, props, {
className: "rw-list-option-create"
}), _react.default.createElement(_ListOption.default, {
onSelect: onSelect,
focused: focused,
activeId: activeId,
dataItem: searchTerm
}, children));
}
AddToListOption.propTypes = propTypes$$1;
var _default = AddToListOption;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(AddToListOption_1);
var DropdownListInput_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _react = _interopRequireDefault(React__default);
var _classnames = _interopRequireDefault(classnames);
var _propTypes = _interopRequireDefault(propTypes);
var CustomPropTypes = _interopRequireWildcard(PropTypes$2);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var DropdownListInput =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(DropdownListInput, _React$Component);
function DropdownListInput() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_this.state = {
autofilling: false
};
_this.handleAutofillDetect = function (_ref) {
var animationName = _ref.animationName;
var autofilling;
if (animationName === 'react-widgets-autofill-start') autofilling = true;else if (animationName === 'react-widgets-autofill-cancel') autofilling = false;else return;
_this.setState({
autofilling: autofilling
});
_this.props.onAutofill(autofilling);
};
_this.handleAutofill = function (e) {
_this.setState({
autofilling: false
});
_this.props.onAutofillChange(e);
};
return _this;
}
var _proto = DropdownListInput.prototype;
_proto.render = function render() {
var _this$props = this.props,
name = _this$props.name,
placeholder = _this$props.placeholder,
value = _this$props.value,
textField = _this$props.textField,
autoComplete = _this$props.autoComplete,
Component = _this$props.valueComponent;
var autofilling = this.state.autofilling;
var child = null;
if (!autofilling && autoComplete !== 'off') {
child = !value && placeholder ? _react.default.createElement("span", {
className: "rw-placeholder"
}, placeholder) : Component ? _react.default.createElement(Component, {
item: value
}) : (0, dataHelpers.dataText)(value, textField);
}
var val = (0, dataHelpers.dataValue)(value);
return _react.default.createElement("div", {
className: "rw-input rw-dropdown-list-input"
}, autoComplete !== 'off' && _react.default.createElement("input", {
tabIndex: "-1",
name: name,
value: val == null ? '' : val,
autoComplete: autoComplete,
onChange: this.handleAutofill,
onAnimationStart: this.handleAutofillDetect,
className: (0, _classnames.default)('rw-dropdown-list-autofill rw-detect-autofill', !autofilling && 'rw-sr')
}), child);
};
return DropdownListInput;
}(_react.default.Component);
DropdownListInput.propTypes = {
value: _propTypes.default.any,
placeholder: _propTypes.default.string,
name: _propTypes.default.string,
autoComplete: _propTypes.default.string,
textField: CustomPropTypes.accessor,
valueComponent: CustomPropTypes.elementType,
onAutofill: _propTypes.default.func.isRequired,
onAutofillChange: _propTypes.default.func.isRequired
};
var _default = DropdownListInput;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(DropdownListInput_1);
var matches_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = matches;
var _inDOM = interopRequireDefault(inDOM);
var _querySelectorAll = interopRequireDefault(querySelectorAll);
var matchesCache;
function matches(node, selector) {
if (!matchesCache && _inDOM.default) {
var body = document.body;
var nativeMatch = body.matches || body.matchesSelector || body.webkitMatchesSelector || body.mozMatchesSelector || body.msMatchesSelector;
matchesCache = nativeMatch ? function (node, selector) {
return nativeMatch.call(node, selector);
} : ie8MatchesSelector;
}
return matchesCache ? matchesCache(node, selector) : null;
}
function ie8MatchesSelector(node, selector) {
var matches = (0, _querySelectorAll.default)(node.document || node.ownerDocument, selector),
i = 0;
while (matches[i] && matches[i] !== node) {
i++;
}
return !!matches[i];
}
module.exports = exports["default"];
});
unwrapExports(matches_1);
var interaction = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.widgetEditable = exports.widgetEnabled = exports.isInDisabledFieldset = void 0;
var _matches = _interopRequireDefault(matches_1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var isInDisabledFieldset = function isInDisabledFieldset(inst) {
var node;
try {
node = (0, _reactDom.findDOMNode)(inst);
} catch (err) {
/* ignore */
}
return !!node && (0, _matches.default)(node, 'fieldset[disabled] *');
};
exports.isInDisabledFieldset = isInDisabledFieldset;
var widgetEnabled = interactionDecorator(true);
exports.widgetEnabled = widgetEnabled;
var widgetEditable = interactionDecorator(false);
exports.widgetEditable = widgetEditable;
function interactionDecorator(disabledOnly) {
function wrap(method) {
return function decoratedMethod() {
var _this$props = this.props,
disabled = _this$props.disabled,
readOnly = _this$props.readOnly;
disabled = isInDisabledFieldset(this) || disabled == true || !disabledOnly && readOnly === true;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (!disabled) return method.apply(this, args);
};
}
return function decorate(target, key, desc) {
if (desc.initializer) {
var init = desc.initializer;
desc.initializer = function () {
return wrap(init.call(this)).bind(this);
};
} else desc.value = wrap(desc.value);
return desc;
};
}
});
unwrapExports(interaction);
var interaction_1 = interaction.widgetEditable;
var interaction_2 = interaction.widgetEnabled;
var interaction_3 = interaction.isInDisabledFieldset;
var focusManager$2 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = createFocusManager;
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 createFocusManager(inst, options) {
var _didHandle = options.didHandle;
return (0, lib$1.focusManager)(inst, _extends({}, options, {
onChange: function onChange(focused) {
inst.setState({
focused: focused
});
},
isDisabled: function isDisabled() {
return inst.props.disabled === true || (0, interaction.isInDisabledFieldset)(inst);
},
didHandle: function didHandle(focused, event) {
var handler = this.props[focused ? 'onFocus' : 'onBlur'];
handler && handler(event);
if (_didHandle && !event.isWidgetDefaultPrevented) _didHandle(focused, event);
}
}));
}
module.exports = exports["default"];
});
unwrapExports(focusManager$2);
var getAccessors = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = createAccessors;
var helpers = _interopRequireWildcard(dataHelpers);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function createAccessors(_ref) {
var textField = _ref.textField,
valueField = _ref.valueField;
return {
text: function text(item) {
return helpers.dataText(item, textField);
},
value: function value(item) {
return helpers.dataValue(item, valueField);
},
indexOf: function indexOf(data, item) {
return helpers.dataIndexOf(data, item, valueField);
},
matches: function matches(a, b) {
return helpers.valueMatcher(a, b, valueField);
},
findOrSelf: function findOrSelf(data, item) {
return helpers.dataItem(data, item, valueField);
},
includes: function includes(data, item) {
return helpers.dataIndexOf(data, item, valueField) !== -1;
}
};
}
module.exports = exports["default"];
});
unwrapExports(getAccessors);
var scrollParent = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = scrollPrarent;
var _style = interopRequireDefault(style_1);
var _height = interopRequireDefault(height_1);
function scrollPrarent(node) {
var position = (0, _style.default)(node, 'position'),
excludeStatic = position === 'absolute',
ownerDoc = node.ownerDocument;
if (position === 'fixed') return ownerDoc || document;
while ((node = node.parentNode) && node.nodeType !== 9) {
var isStatic = excludeStatic && (0, _style.default)(node, 'position') === 'static',
style = (0, _style.default)(node, 'overflow') + (0, _style.default)(node, 'overflow-y') + (0, _style.default)(node, 'overflow-x');
if (isStatic) continue;
if (/(auto|scroll)/.test(style) && (0, _height.default)(node) < node.scrollHeight) return node;
}
return document;
}
module.exports = exports["default"];
});
unwrapExports(scrollParent);
var scrollTop_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = scrollTop;
var _isWindow = interopRequireDefault(isWindow);
function scrollTop(node, val) {
var win = (0, _isWindow.default)(node);
if (val === undefined) return win ? 'pageYOffset' in win ? win.pageYOffset : win.document.documentElement.scrollTop : node.scrollTop;
if (win) win.scrollTo('pageXOffset' in win ? win.pageXOffset : win.document.documentElement.scrollLeft, val);else node.scrollTop = val;
}
module.exports = exports["default"];
});
unwrapExports(scrollTop_1);
var requestAnimationFrame$2 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _inDOM = interopRequireDefault(inDOM);
var vendors = ['', 'webkit', 'moz', 'o', 'ms'];
var cancel = 'clearTimeout';
var raf = fallback;
var compatRaf;
var getKey = function getKey(vendor, k) {
return vendor + (!vendor ? k : k[0].toUpperCase() + k.substr(1)) + 'AnimationFrame';
};
if (_inDOM.default) {
vendors.some(function (vendor) {
var rafKey = getKey(vendor, 'request');
if (rafKey in window) {
cancel = getKey(vendor, 'cancel');
return raf = function raf(cb) {
return window[rafKey](cb);
};
}
});
}
/* https://github.com/component/raf */
var prev = new Date().getTime();
function fallback(fn) {
var curr = new Date().getTime(),
ms = Math.max(0, 16 - (curr - prev)),
req = setTimeout(fn, ms);
prev = curr;
return req;
}
compatRaf = function compatRaf(cb) {
return raf(cb);
};
compatRaf.cancel = function (id) {
window[cancel] && typeof window[cancel] === 'function' && window[cancel](id);
};
var _default = compatRaf;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(requestAnimationFrame$2);
var scrollTo_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = scrollTo;
var _offset = interopRequireDefault(offset_1);
var _height = interopRequireDefault(height_1);
var _scrollParent = interopRequireDefault(scrollParent);
var _scrollTop = interopRequireDefault(scrollTop_1);
var _requestAnimationFrame = interopRequireDefault(requestAnimationFrame$2);
var _isWindow = interopRequireDefault(isWindow);
function scrollTo(selected, scrollParent$$1) {
var offset = (0, _offset.default)(selected);
var poff = {
top: 0,
left: 0
};
var list, listScrollTop, selectedTop, isWin;
var selectedHeight, listHeight, bottom;
if (!selected) return;
list = scrollParent$$1 || (0, _scrollParent.default)(selected);
isWin = (0, _isWindow.default)(list);
listScrollTop = (0, _scrollTop.default)(list);
listHeight = (0, _height.default)(list, true);
isWin = (0, _isWindow.default)(list);
if (!isWin) poff = (0, _offset.default)(list);
offset = {
top: offset.top - poff.top,
left: offset.left - poff.left,
height: offset.height,
width: offset.width
};
selectedHeight = offset.height;
selectedTop = offset.top + (isWin ? 0 : listScrollTop);
bottom = selectedTop + selectedHeight;
listScrollTop = listScrollTop > selectedTop ? selectedTop : bottom > listScrollTop + listHeight ? bottom - listHeight : listScrollTop;
var id = (0, _requestAnimationFrame.default)(function () {
return (0, _scrollTop.default)(list, listScrollTop);
});
return function () {
return _requestAnimationFrame.default.cancel(id);
};
}
module.exports = exports["default"];
});
unwrapExports(scrollTo_1);
var scrollManager = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = createScrollManager;
var _scrollTo = _interopRequireDefault(scrollTo_1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function createScrollManager(inst, getScrollParent) {
if (getScrollParent === void 0) {
getScrollParent = function getScrollParent(list) {
return list.parentNode;
};
}
var isMounted = (0, lib$1.mountManager)(inst);
var currentFocused, currentVisible, cancelScroll;
function handleScroll(selected, list, nextFocused) {
if (!isMounted()) return;
var lastVisible = currentVisible;
var lastItem = currentFocused;
var shown, changed;
currentVisible = !(!list.offsetWidth || !list.offsetHeight);
currentFocused = nextFocused;
changed = lastItem !== nextFocused;
shown = currentVisible && !lastVisible;
if (shown || currentVisible && changed) {
if (this.props.onMove) this.props.onMove(selected, list, nextFocused);else {
cancelScroll && cancelScroll();
cancelScroll = (0, _scrollTo.default)(selected, false && getScrollParent(list));
}
}
}
return handleScroll.bind(inst);
}
module.exports = exports["default"];
});
unwrapExports(scrollManager);
var Icon_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = exports.search = exports.clock = exports.calendar = exports.chevronLeft = exports.chevronRight = exports.caretDown = exports.caretUp = void 0;
var _propTypes = _interopRequireDefault(propTypes);
var _react = _interopRequireDefault(React__default);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var propTypes$$1 = {
icon: _propTypes.default.string.isRequired
};
var Icon = function Icon(_ref) {
var icon = _ref.icon;
return _react.default.createElement("span", {
"aria-hidden": "true",
className: "rw-i rw-i-" + icon
});
};
Icon.propTypes = propTypes$$1;
var caretUp = _react.default.createElement(Icon, {
icon: "caret-up"
});
exports.caretUp = caretUp;
var caretDown = _react.default.createElement(Icon, {
icon: "caret-down"
});
exports.caretDown = caretDown;
var chevronRight = _react.default.createElement(Icon, {
icon: "chevron-right"
});
exports.chevronRight = chevronRight;
var chevronLeft = _react.default.createElement(Icon, {
icon: "chevron-left"
});
exports.chevronLeft = chevronLeft;
var calendar = _react.default.createElement(Icon, {
icon: "calendar"
});
exports.calendar = calendar;
var clock = _react.default.createElement(Icon, {
icon: "clock-o"
});
exports.clock = clock;
var search = _react.default.createElement(Icon, {
icon: "search"
});
exports.search = search;
var _default = Icon;
exports.default = _default;
});
unwrapExports(Icon_1);
var Icon_2 = Icon_1.search;
var Icon_3 = Icon_1.clock;
var Icon_4 = Icon_1.calendar;
var Icon_5 = Icon_1.chevronLeft;
var Icon_6 = Icon_1.chevronRight;
var Icon_7 = Icon_1.caretDown;
var Icon_8 = Icon_1.caretUp;
var DropdownList_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _react = _interopRequireDefault(React__default);
var _propTypes = _interopRequireDefault(propTypes);
var _activeElement = _interopRequireDefault(activeElement_1);
var _classnames = _interopRequireDefault(classnames);
var _uncontrollable = _interopRequireDefault(uncontrollable_1);
var _Widget = _interopRequireDefault(Widget_1);
var _WidgetPicker = _interopRequireDefault(WidgetPicker_1);
var _Select = _interopRequireDefault(Select_1);
var _Popup = _interopRequireDefault(Popup_1);
var _List = _interopRequireDefault(List_1);
var _AddToListOption = _interopRequireDefault(AddToListOption_1);
var _DropdownListInput = _interopRequireDefault(DropdownListInput_1);
var Props$$1 = _interopRequireWildcard(Props);
var Filter$$1 = _interopRequireWildcard(Filter);
var _focusManager = _interopRequireDefault(focusManager$2);
var CustomPropTypes = _interopRequireWildcard(PropTypes$2);
var _reduceToListState = _interopRequireDefault(reduceToListState_1);
var _getAccessors = _interopRequireDefault(getAccessors);
var _scrollManager = _interopRequireDefault(scrollManager);
var _class, _class2, _descriptor, _descriptor2, _descriptor3, _descriptor4, _descriptor5, _class3, _temp;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _initializerDefineProperty(target, property, descriptor, context) { if (!descriptor) return; Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 }); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { var desc = {}; Object['ke' + 'ys'](descriptor).forEach(function (key) { desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer) { desc.writable = true; } desc = decorators.slice().reverse().reduce(function (desc, decorator) { return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0) { desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0) { Object['define' + 'Property'](target, property, desc); desc = null; } return desc; }
var CREATE_OPTION = {};
/**
* ---
* shortcuts:
* - { key: alt + down arrow, label: open dropdown }
* - { key: alt + up arrow, label: close dropdown }
* - { key: down arrow, label: move focus to next item }
* - { key: up arrow, label: move focus to previous item }
* - { key: home, label: move focus to first item }
* - { key: end, label: move focus to last item }
* - { key: enter, label: select focused item }
* - { key: ctrl + enter, label: create new option from current searchTerm }
* - { key: any key, label: search list for item starting with key }
* ---
*
* A `<select>` replacement for single value lists.
* @public
*/
var DropdownList = (0, reactLifecyclesCompat_es.polyfill)(_class = (_class2 = (_temp = _class3 =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(DropdownList, _React$Component);
function DropdownList() {
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.handleFocusChanged = function (focused) {
if (!focused) _this.close();
};
_initializerDefineProperty(_this, "handleSelect", _descriptor, _assertThisInitialized(_assertThisInitialized(_this)));
_initializerDefineProperty(_this, "handleCreate", _descriptor2, _assertThisInitialized(_assertThisInitialized(_this)));
_initializerDefineProperty(_this, "handleClick", _descriptor3, _assertThisInitialized(_assertThisInitialized(_this)));
_initializerDefineProperty(_this, "handleKeyDown", _descriptor4, _assertThisInitialized(_assertThisInitialized(_this)));
_initializerDefineProperty(_this, "handleKeyPress", _descriptor5, _assertThisInitialized(_assertThisInitialized(_this)));
_this.handleInputChange = function (e) {
_this.search(e.target.value, e, 'input');
};
_this.handleAutofillChange = function (e) {
var data = _this.props.data;
var filledValue = e.target.value.toLowerCase();
if (filledValue === '') return void _this.change(null);
for (var _iterator = data, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var item = _ref;
var value = (0, dataHelpers.dataValue)(item);
if (String(value).toLowerCase() === filledValue || (0, dataHelpers.dataText)(item).toLowerCase() === filledValue) {
_this.change(item, e);
break;
}
}
};
_this.handleAutofill = function (autofilling) {
_this.setState({
autofilling: autofilling
});
};
_this.attachInputRef = function (ref) {
return _this.inputRef = ref;
};
_this.attachFilterRef = function (ref) {
return _this.filterRef = ref;
};
_this.attachListRef = function (ref) {
return _this.listRef = ref;
};
_this.focus = function (target) {
var _this$props = _this.props,
filter = _this$props.filter,
open = _this$props.open;
var inst = target || (filter && open ? _this.filterRef : _this.inputRef);
inst = (0, _reactDom.findDOMNode)(inst);
if (inst && (0, _activeElement.default)() !== inst) inst.focus();
};
(0, lib$1.autoFocus)(_assertThisInitialized(_assertThisInitialized(_this)));
_this.inputId = (0, widgetHelpers.instanceId)(_assertThisInitialized(_assertThisInitialized(_this)), '_input');
_this.listId = (0, widgetHelpers.instanceId)(_assertThisInitialized(_assertThisInitialized(_this)), '_listbox');
_this.activeId = (0, widgetHelpers.instanceId)(_assertThisInitialized(_assertThisInitialized(_this)), '_listbox_active_option');
_this.mounted = (0, lib$1.mountManager)(_assertThisInitialized(_assertThisInitialized(_this)));
_this.timeouts = (0, lib$1.timeoutManager)(_assertThisInitialized(_assertThisInitialized(_this)));
_this.handleScroll = (0, _scrollManager.default)(_assertThisInitialized(_assertThisInitialized(_this)));
_this.focusManager = (0, _focusManager.default)(_assertThisInitialized(_assertThisInitialized(_this)), {
didHandle: _this.handleFocusChanged
});
_this.state = {};
return _this;
}
DropdownList.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, prevState) {
var open = nextProps.open,
value = nextProps.value,
data = nextProps.data,
messages = nextProps.messages,
searchTerm = nextProps.searchTerm,
filter = nextProps.filter,
minLength = nextProps.minLength,
caseSensitive = nextProps.caseSensitive;
var focusedItem = prevState.focusedItem;
var accessors = (0, _getAccessors.default)(nextProps);
var valueChanged = value !== prevState.lastValue;
var initialIdx = valueChanged && accessors.indexOf(data, value);
if (open) data = Filter$$1.filter(data, {
filter: filter,
searchTerm: searchTerm,
minLength: minLength,
caseSensitive: caseSensitive,
textField: accessors.text
});
var list = (0, _reduceToListState.default)(data, prevState.list, {
nextProps: nextProps
});
var selectedItem = data[initialIdx];
var nextFocusedItem = ~data.indexOf(focusedItem) ? focusedItem : data[0];
return {
data: data,
list: list,
accessors: accessors,
lastValue: value,
messages: (0, messages_1.getMessages)(messages),
selectedItem: valueChanged ? list.nextEnabled(selectedItem) : prevState.selectedItem,
focusedItem: valueChanged || !focusedItem ? list.nextEnabled(selectedItem || nextFocusedItem) : nextFocusedItem
};
};
var _proto = DropdownList.prototype;
_proto.change = function change(nextValue, originalEvent) {
var _this$props2 = this.props,
onChange = _this$props2.onChange,
searchTerm = _this$props2.searchTerm,
lastValue = _this$props2.value;
if (!this.state.accessors.matches(nextValue, lastValue)) {
(0, widgetHelpers.notify)(onChange, [nextValue, {
originalEvent: originalEvent,
lastValue: lastValue,
searchTerm: searchTerm
}]);
this.clearSearch(originalEvent);
this.close();
}
};
_proto.renderList = function renderList() {
var _this$props3 = this.props,
open = _this$props3.open,
filter = _this$props3.filter,
data = _this$props3.data,
searchTerm = _this$props3.searchTerm,
searchIcon = _this$props3.searchIcon,
optionComponent = _this$props3.optionComponent,
itemComponent = _this$props3.itemComponent,
groupComponent = _this$props3.groupComponent,
listProps = _this$props3.listProps;
var _this$state = this.state,
list = _this$state.list,
accessors = _this$state.accessors,
focusedItem = _this$state.focusedItem,
selectedItem = _this$state.selectedItem,
messages = _this$state.messages,
filteredData = _this$state.data;
var List = this.props.listComponent;
return _react.default.createElement("div", null, filter && _react.default.createElement(_WidgetPicker.default, {
className: "rw-filter-input rw-input"
}, _react.default.createElement("input", {
value: searchTerm,
className: "rw-input-reset",
onChange: this.handleInputChange,
placeholder: messages.filterPlaceholder(this.props),
ref: this.attachFilterRef
}), _react.default.createElement(_Select.default, {
icon: searchIcon,
role: "presentation",
"aria-hidden": "true"
})), _react.default.createElement(List, _extends({}, listProps, {
id: this.listId,
activeId: this.activeId,
data: filteredData,
dataState: list.dataState,
isDisabled: list.isDisabled,
searchTerm: searchTerm,
textAccessor: accessors.text,
valueAccessor: accessors.value,
itemComponent: itemComponent,
groupComponent: groupComponent,
optionComponent: optionComponent,
selectedItem: selectedItem,
focusedItem: open ? focusedItem : null,
onSelect: this.handleSelect,
onMove: this.handleScroll,
"aria-live": open && 'polite',
"aria-labelledby": this.inputId,
"aria-hidden": !this.props.open,
ref: this.attachListRef,
messages: {
emptyList: data.length ? messages.emptyFilter : messages.emptyList
}
})), this.allowCreate() && _react.default.createElement(_AddToListOption.default, {
id: this.createId,
searchTerm: searchTerm,
onSelect: this.handleCreate,
focused: !focusedItem || focusedItem === CREATE_OPTION
}, messages.createOption(this.props)));
};
_proto.render = function render() {
var _this2 = this;
var _this$props4 = this.props,
className = _this$props4.className,
tabIndex = _this$props4.tabIndex,
popupTransition = _this$props4.popupTransition,
textField = _this$props4.textField,
data = _this$props4.data,
busy = _this$props4.busy,
dropUp = _this$props4.dropUp,
placeholder = _this$props4.placeholder,
value = _this$props4.value,
open = _this$props4.open,
isRtl = _this$props4.isRtl,
filter = _this$props4.filter,
inputProps = _this$props4.inputProps,
selectIcon = _this$props4.selectIcon,
busySpinner = _this$props4.busySpinner,
containerClassName = _this$props4.containerClassName,
valueComponent = _this$props4.valueComponent;
var _this$state2 = this.state,
focused = _this$state2.focused,
accessors = _this$state2.accessors,
messages = _this$state2.messages,
autofilling = _this$state2.autofilling;
var disabled = this.props.disabled === true;
var readOnly = this.props.readOnly === true;
var valueItem = accessors.findOrSelf(data, value);
var shouldRenderPopup = (0, widgetHelpers.isFirstFocusedRender)(this);
var elementProps = _extends(Props$$1.pickElementProps(this), {
name: undefined,
role: 'combobox',
id: this.inputId,
tabIndex: open && filter ? -1 : tabIndex || 0,
'aria-owns': this.listId,
'aria-activedescendant': open ? this.activeId : null,
'aria-expanded': !!open,
'aria-haspopup': true,
'aria-busy': !!busy,
'aria-live': !open && 'polite',
'aria-autocomplete': 'list',
'aria-disabled': disabled,
'aria-readonly': readOnly
});
return _react.default.createElement(_Widget.default, _extends({}, elementProps, {
open: open,
isRtl: isRtl,
dropUp: dropUp,
focused: focused,
disabled: disabled,
readOnly: readOnly,
autofilling: autofilling,
onBlur: this.focusManager.handleBlur,
onFocus: this.focusManager.handleFocus,
onKeyDown: this.handleKeyDown,
onKeyPress: this.handleKeyPress,
className: (0, _classnames.default)(className, 'rw-dropdown-list'),
ref: this.attachInputRef
}), _react.default.createElement(_WidgetPicker.default, {
onClick: this.handleClick,
className: (0, _classnames.default)(containerClassName, 'rw-widget-input')
}, _react.default.createElement(_DropdownListInput.default, _extends({}, inputProps, {
value: valueItem,
textField: textField,
name: this.props.name,
autoComplete: this.props.autoComplete,
onAutofill: this.handleAutofill,
onAutofillChange: this.handleAutofillChange,
placeholder: placeholder,
valueComponent: valueComponent
})), _react.default.createElement(_Select.default, {
busy: busy,
icon: selectIcon,
spinner: busySpinner,
role: "presentational",
"aria-hidden": "true",
disabled: disabled || readOnly,
label: messages.openDropdown(this.props)
})), shouldRenderPopup && _react.default.createElement(_Popup.default, {
open: open,
dropUp: dropUp,
transition: popupTransition,
onEntered: function onEntered() {
return _this2.focus();
},
onEntering: function onEntering() {
return _this2.listRef.forceUpdate();
}
}, this.renderList(messages)));
};
_proto.findOption = function findOption(character, cb) {
var _this3 = this;
var word = ((this._currentWord || '') + character).toLowerCase();
if (!character) return;
this._currentWord = word;
this.timeouts.set('search', function () {
var list = _this3.state.list;
var key = _this3.props.open ? 'focusedItem' : 'selectedItem';
var item = list.next(_this3.state[key], word);
if (item === _this3.state[key]) {
item = list.next(null, word);
}
_this3._currentWord = '';
if (item) cb(item);
}, this.props.delay);
};
_proto.clearSearch = function clearSearch(originalEvent) {
this.search('', originalEvent, 'clear');
};
_proto.search = function search(searchTerm, originalEvent, action) {
if (action === void 0) {
action = 'input';
}
var _this$props5 = this.props,
onSearch = _this$props5.onSearch,
lastSearchTerm = _this$props5.searchTerm;
if (searchTerm !== lastSearchTerm) (0, widgetHelpers.notify)(onSearch, [searchTerm, {
action: action,
lastSearchTerm: lastSearchTerm,
originalEvent: originalEvent
}]);
};
_proto.open = function open() {
if (!this.props.open) (0, widgetHelpers.notify)(this.props.onToggle, true);
};
_proto.close = function close() {
if (this.props.open) (0, widgetHelpers.notify)(this.props.onToggle, false);
};
_proto.toggle = function toggle() {
this.props.open ? this.close() : this.open();
};
_proto.allowCreate = function allowCreate() {
var _this$props6 = this.props,
searchTerm = _this$props6.searchTerm,
onCreate = _this$props6.onCreate,
allowCreate = _this$props6.allowCreate;
return !!(onCreate && (allowCreate === true || allowCreate === 'onFilter' && searchTerm) && !this.hasExtactMatch());
};
_proto.hasExtactMatch = function hasExtactMatch() {
var _this$props7 = this.props,
searchTerm = _this$props7.searchTerm,
caseSensitive = _this$props7.caseSensitive,
filter = _this$props7.filter;
var _this$state3 = this.state,
data = _this$state3.data,
accessors = _this$state3.accessors;
var lower = function lower(text) {
return caseSensitive ? text : text.toLowerCase();
}; // if there is an exact match on textFields:
return filter && data.some(function (v) {
return lower(accessors.text(v)) === lower(searchTerm);
});
};
return DropdownList;
}(_react.default.Component), _class3.propTypes = _extends({}, Filter$$1.propTypes, {
value: _propTypes.default.any,
/**
* @type {function (
* dataItems: ?any,
* metadata: {
* lastValue: ?any,
* searchTerm: ?string
* originalEvent: SyntheticEvent,
* }
* ): void}
*/
onChange: _propTypes.default.func,
open: _propTypes.default.bool,
onToggle: _propTypes.default.func,
data: _propTypes.default.array,
valueField: CustomPropTypes.accessor,
textField: CustomPropTypes.accessor,
allowCreate: _propTypes.default.oneOf([true, false, 'onFilter']),
/**
* A React component for customizing the rendering of the DropdownList
* value
*/
valueComponent: CustomPropTypes.elementType,
itemComponent: CustomPropTypes.elementType,
listComponent: CustomPropTypes.elementType,
optionComponent: CustomPropTypes.elementType,
groupComponent: CustomPropTypes.elementType,
groupBy: CustomPropTypes.accessor,
/**
*
* @type {(dataItem: ?any, metadata: { originalEvent: SyntheticEvent }) => void}
*/
onSelect: _propTypes.default.func,
onCreate: _propTypes.default.func,
/**
* @type function(searchTerm: string, metadata: { action, lastSearchTerm, originalEvent? })
*/
onSearch: _propTypes.default.func,
searchTerm: _propTypes.default.string,
busy: _propTypes.default.bool,
/** Specify the element used to render the select (down arrow) icon. */
selectIcon: _propTypes.default.node,
searchIcon: _propTypes.default.node,
/** Specify the element used to render the busy indicator */
busySpinner: _propTypes.default.node,
placeholder: _propTypes.default.string,
dropUp: _propTypes.default.bool,
popupTransition: CustomPropTypes.elementType,
disabled: CustomPropTypes.disabled.acceptsArray,
readOnly: CustomPropTypes.disabled,
/** Adds a css class to the input container element. */
containerClassName: _propTypes.default.string,
inputProps: _propTypes.default.object,
listProps: _propTypes.default.object,
isRtl: _propTypes.default.bool,
messages: _propTypes.default.shape({
open: _propTypes.default.string,
emptyList: CustomPropTypes.message,
emptyFilter: CustomPropTypes.message,
filterPlaceholder: _propTypes.default.string,
createOption: CustomPropTypes.message
})
}), _class3.defaultProps = {
data: [],
delay: 500,
searchTerm: '',
allowCreate: false,
searchIcon: Icon_1.search,
selectIcon: Icon_1.caretDown,
listComponent: _List.default
}, _temp), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, "handleSelect", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this4 = this;
return function (dataItem, originalEvent) {
if (dataItem === undefined || dataItem === CREATE_OPTION) {
_this4.handleCreate(_this4.props.searchTerm);
return;
}
(0, widgetHelpers.notify)(_this4.props.onSelect, [dataItem, {
originalEvent: originalEvent
}]);
_this4.change(dataItem, originalEvent);
_this4.close();
_this4.focus(_this4);
};
}
}), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, "handleCreate", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this5 = this;
return function (searchTerm, event) {
if (searchTerm === void 0) {
searchTerm = '';
}
(0, widgetHelpers.notify)(_this5.props.onCreate, searchTerm);
_this5.clearSearch(event);
_this5.close();
_this5.focus(_this5);
};
}
}), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, "handleClick", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this6 = this;
return function (e) {
_this6.focus();
_this6.toggle();
(0, widgetHelpers.notify)(_this6.props.onClick, e);
};
}
}), _descriptor4 = _applyDecoratedDescriptor(_class2.prototype, "handleKeyDown", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this7 = this;
return function (e) {
var key = e.key,
altKey = e.altKey,
ctrlKey = e.ctrlKey;
var _this7$props = _this7.props,
open = _this7$props.open,
onKeyDown = _this7$props.onKeyDown,
filter = _this7$props.filter,
searchTerm = _this7$props.searchTerm;
var _this7$state = _this7.state,
focusedItem = _this7$state.focusedItem,
selectedItem = _this7$state.selectedItem,
list = _this7$state.list;
var createIsFocused = focusedItem === CREATE_OPTION;
var canCreate = _this7.allowCreate();
(0, widgetHelpers.notify)(onKeyDown, [e]);
var closeWithFocus = function closeWithFocus() {
_this7.close();
(0, _reactDom.findDOMNode)(_this7).focus();
};
var change = function change(item) {
return item != null && _this7.change(item, e);
};
var focusItem = function focusItem(item) {
return _this7.setState({
focusedItem: item
});
};
if (e.defaultPrevented) return;
if (key === 'End') {
e.preventDefault();
if (open) focusItem(list.last());else change(list.last());
} else if (key === 'Home') {
e.preventDefault();
if (open) focusItem(list.first());else change(list.first());
} else if (key === 'Escape' && open) {
e.preventDefault();
closeWithFocus();
} else if (key === 'Enter' && open && ctrlKey && canCreate) {
e.preventDefault();
_this7.handleCreate(searchTerm, e);
} else if ((key === 'Enter' || key === ' ' && !filter) && open) {
e.preventDefault();
_this7.handleSelect(focusedItem, e);
} else if (key === ' ' && !open) {
e.preventDefault();
_this7.open();
} else if (key === 'ArrowDown') {
e.preventDefault();
if (altKey) return _this7.open();
if (!open) change(list.next(selectedItem));
var next = list.next(focusedItem);
var creating = createIsFocused || canCreate && focusedItem === next;
focusItem(creating ? CREATE_OPTION : next);
} else if (key === 'ArrowUp') {
e.preventDefault();
if (altKey) return closeWithFocus();
if (!open) return change(list.prev(selectedItem));
focusItem(createIsFocused ? list.last() : list.prev(focusedItem));
}
};
}
}), _descriptor5 = _applyDecoratedDescriptor(_class2.prototype, "handleKeyPress", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this8 = this;
return function (e) {
(0, widgetHelpers.notify)(_this8.props.onKeyPress, [e]);
if (e.defaultPrevented) return;
if (!(_this8.props.filter && _this8.props.open)) _this8.findOption(String.fromCharCode(e.which), function (item) {
_this8.mounted() && _this8.props.open ? _this8.setState({
focusedItem: item
}) : item && _this8.change(item, e);
});
};
}
})), _class2)) || _class;
var _default = (0, _uncontrollable.default)(DropdownList, {
open: 'onToggle',
value: 'onChange',
searchTerm: 'onSearch'
}, ['focus']);
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(DropdownList_1);
var Input_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _react = _interopRequireDefault(React__default);
var _propTypes = _interopRequireDefault(propTypes);
var _classnames = _interopRequireDefault(classnames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutProperties(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]; } 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; }
Input.propTypes = {
disabled: _propTypes.default.bool,
readOnly: _propTypes.default.bool,
value: _propTypes.default.string,
type: _propTypes.default.string,
tabIndex: _propTypes.default.string,
component: _propTypes.default.any,
nodeRef: _propTypes.default.func
};
function Input(_ref) {
var className = _ref.className,
disabled = _ref.disabled,
readOnly = _ref.readOnly,
value = _ref.value,
tabIndex = _ref.tabIndex,
nodeRef = _ref.nodeRef,
_ref$type = _ref.type,
type = _ref$type === void 0 ? 'text' : _ref$type,
_ref$component = _ref.component,
Component = _ref$component === void 0 ? 'input' : _ref$component,
props = _objectWithoutProperties(_ref, ["className", "disabled", "readOnly", "value", "tabIndex", "nodeRef", "type", "component"]);
return _react.default.createElement(Component, _extends({}, props, {
type: type,
ref: nodeRef,
tabIndex: tabIndex || 0,
autoComplete: "off",
disabled: disabled,
readOnly: readOnly,
"aria-disabled": disabled,
"aria-readonly": readOnly,
value: value == null ? '' : value,
className: (0, _classnames.default)(className, 'rw-input')
}));
}
var _default = Input;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(Input_1);
var ComboboxInput_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = exports.caretSet = void 0;
var _react = _interopRequireDefault(React__default);
var _propTypes = _interopRequireDefault(propTypes);
var _Input = _interopRequireDefault(Input_1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutProperties(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]; } if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var caretSet = function caretSet(node, start, end) {
if (end === void 0) {
end = start;
}
try {
node.setSelectionRange(start, end);
} catch (e) {
/* not focused or not visible */
}
};
exports.caretSet = caretSet;
var ComboboxInput =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(ComboboxInput, _React$Component);
function ComboboxInput() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_this.handleChange = function (e) {
var _this$props = _this.props,
placeholder = _this$props.placeholder,
value = _this$props.value,
onChange = _this$props.onChange;
var stringValue = e.target.value;
var hasPlaceholder = !!placeholder; // IE fires input events when setting/unsetting placeholders.
// issue #112
if (hasPlaceholder && !stringValue && stringValue === (value || '')) return;
_this._last = stringValue;
onChange(e, stringValue);
};
return _this;
}
var _proto = ComboboxInput.prototype;
_proto.componentDidUpdate = function componentDidUpdate() {
var input = (0, _reactDom.findDOMNode)(this);
var val = this.props.value;
if (this.isSuggesting()) {
var start = val.toLowerCase().indexOf(this._last.toLowerCase()) + this._last.length;
var end = val.length - start;
if (start >= 0 && end !== 0) {
caretSet(input, start, start + end);
}
}
};
_proto.accept = function accept(clearSelection) {
if (clearSelection === void 0) {
clearSelection = false;
}
this._last = null;
if (clearSelection) {
var node = (0, _reactDom.findDOMNode)(this);
caretSet(node, node.value.length);
}
};
_proto.focus = function focus() {
(0, _reactDom.findDOMNode)(this).focus();
};
_proto.isSuggesting = function isSuggesting() {
var _this$props2 = this.props,
value = _this$props2.value,
suggest = _this$props2.suggest;
if (!suggest) return false;
return this._last != null && value.toLowerCase().indexOf(this._last.toLowerCase()) !== -1;
};
_proto.render = function render() {
var _this$props3 = this.props,
onKeyDown = _this$props3.onKeyDown,
props = _objectWithoutProperties(_this$props3, ["onKeyDown"]);
delete props.suggest;
return _react.default.createElement(_Input.default, _extends({}, props, {
className: "rw-widget-input",
onKeyDown: onKeyDown,
onChange: this.handleChange
}));
};
return ComboboxInput;
}(_react.default.Component);
ComboboxInput.defaultProps = {
value: ''
};
ComboboxInput.propTypes = {
value: _propTypes.default.string,
placeholder: _propTypes.default.string,
suggest: _propTypes.default.bool,
onChange: _propTypes.default.func.isRequired,
onKeyDown: _propTypes.default.func
};
var _default = ComboboxInput;
exports.default = _default;
});
unwrapExports(ComboboxInput_1);
var ComboboxInput_2 = ComboboxInput_1.caretSet;
var Combobox_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _react = _interopRequireDefault(React__default);
var _propTypes = _interopRequireDefault(propTypes);
var _classnames = _interopRequireDefault(classnames);
var _uncontrollable = _interopRequireDefault(uncontrollable_1);
var _Widget = _interopRequireDefault(Widget_1);
var _WidgetPicker = _interopRequireDefault(WidgetPicker_1);
var _List = _interopRequireDefault(List_1);
var _Popup = _interopRequireDefault(Popup_1);
var _Select = _interopRequireDefault(Select_1);
var _ComboboxInput = _interopRequireDefault(ComboboxInput_1);
var _focusManager = _interopRequireDefault(focusManager$2);
var _reduceToListState = _interopRequireDefault(reduceToListState_1);
var _getAccessors = _interopRequireDefault(getAccessors);
var CustomPropTypes = _interopRequireWildcard(PropTypes$2);
var _scrollManager = _interopRequireDefault(scrollManager);
var Props$$1 = _interopRequireWildcard(Props);
var Filter$$1 = _interopRequireWildcard(Filter);
var _class, _class2, _descriptor, _descriptor2, _descriptor3, _class3, _temp;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _initializerDefineProperty(target, property, descriptor, context) { if (!descriptor) return; Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 }); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { var desc = {}; Object['ke' + 'ys'](descriptor).forEach(function (key) { desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer) { desc.writable = true; } desc = decorators.slice().reverse().reduce(function (desc, decorator) { return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0) { desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0) { Object['define' + 'Property'](target, property, desc); desc = null; } return desc; }
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); }
var propTypes$$1 = _extends({}, Filter$$1.propTypes, {
value: _propTypes.default.any,
onChange: _propTypes.default.func,
open: _propTypes.default.bool,
onToggle: _propTypes.default.func,
itemComponent: CustomPropTypes.elementType,
listComponent: CustomPropTypes.elementType,
groupComponent: CustomPropTypes.elementType,
groupBy: CustomPropTypes.accessor,
data: _propTypes.default.array,
valueField: CustomPropTypes.accessor,
textField: CustomPropTypes.accessor,
name: _propTypes.default.string,
/**
*
* @type {(dataItem: ?any, metadata: { originalEvent: SyntheticEvent }) => void}
*/
onSelect: _propTypes.default.func,
autoFocus: _propTypes.default.bool,
disabled: CustomPropTypes.disabled.acceptsArray,
readOnly: CustomPropTypes.disabled,
/**
* When `true` the Combobox will suggest, or fill in, values as you type. The suggestions
* are always "startsWith", meaning it will search from the start of the `textField` property
*/
suggest: Filter$$1.propTypes.filter,
busy: _propTypes.default.bool,
/** Specify the element used to render the select (down arrow) icon. */
selectIcon: _propTypes.default.node,
/** Specify the element used to render the busy indicator */
busySpinner: _propTypes.default.node,
delay: _propTypes.default.number,
dropUp: _propTypes.default.bool,
popupTransition: CustomPropTypes.elementType,
placeholder: _propTypes.default.string,
/** Adds a css class to the input container element. */
containerClassName: _propTypes.default.string,
inputProps: _propTypes.default.object,
listProps: _propTypes.default.object,
isRtl: _propTypes.default.bool,
messages: _propTypes.default.shape({
openCombobox: CustomPropTypes.message,
emptyList: CustomPropTypes.message,
emptyFilter: CustomPropTypes.message
})
/**
* ---
* shortcuts:
* - { key: alt + down arrow, label: open combobox }
* - { key: alt + up arrow, label: close combobox }
* - { key: down arrow, label: move focus to next item }
* - { key: up arrow, label: move focus to previous item }
* - { key: home, label: move focus to first item }
* - { key: end, label: move focus to last item }
* - { key: enter, label: select focused item }
* - { key: any key, label: search list for item starting with key }
* ---
*
* Select an item from the list, or input a custom value. The Combobox can also make suggestions as you type.
* @public
*/
});
var Combobox = (0, reactLifecyclesCompat_es.polyfill)(_class = (_class2 = (_temp = _class3 =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(Combobox, _React$Component);
function Combobox(props, context) {
var _this;
_this = _React$Component.call(this, props, context) || this;
_this.handleFocusWillChange = function (focused) {
if (!focused && _this.inputRef) _this.inputRef.accept();
if (focused) _this.focus();
};
_this.handleFocusChanged = function (focused) {
if (!focused) _this.close();
};
_initializerDefineProperty(_this, "handleSelect", _descriptor, _assertThisInitialized(_assertThisInitialized(_this)));
_this.handleInputKeyDown = function (_ref) {
var key = _ref.key;
_this._deleting = key === 'Backspace' || key === 'Delete';
_this._isTyping = true;
};
_this.handleInputChange = function (event) {
var suggestion = _this.suggest(event.target.value);
_this.change(suggestion, true, event);
_this.open();
};
_initializerDefineProperty(_this, "handleKeyDown", _descriptor2, _assertThisInitialized(_assertThisInitialized(_this)));
_this.attachListRef = function (ref) {
_this.listRef = ref;
};
_this.attachInputRef = function (ref) {
_this.inputRef = ref;
};
_initializerDefineProperty(_this, "toggle", _descriptor3, _assertThisInitialized(_assertThisInitialized(_this)));
_this.inputId = (0, widgetHelpers.instanceId)(_assertThisInitialized(_assertThisInitialized(_this)), '_input');
_this.listId = (0, widgetHelpers.instanceId)(_assertThisInitialized(_assertThisInitialized(_this)), '_listbox');
_this.activeId = (0, widgetHelpers.instanceId)(_assertThisInitialized(_assertThisInitialized(_this)), '_listbox_active_option');
_this.handleScroll = (0, _scrollManager.default)(_assertThisInitialized(_assertThisInitialized(_this)));
_this.focusManager = (0, _focusManager.default)(_assertThisInitialized(_assertThisInitialized(_this)), {
willHandle: _this.handleFocusWillChange,
didHandle: _this.handleFocusChanged
});
_this.state = {
isSuggesting: function isSuggesting() {
return _this.inputRef && _this.inputRef.isSuggesting();
}
};
return _this;
}
var _proto = Combobox.prototype;
_proto.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) {
var isSuggesting = nextState.isSuggesting(),
stateChanged = !(0, _.isShallowEqual)(nextState, this.state),
valueChanged = !(0, _.isShallowEqual)(nextProps, this.props);
return isSuggesting || stateChanged || valueChanged;
};
Combobox.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, prevState) {
var value = nextProps.value,
data = nextProps.data,
messages = nextProps.messages,
filter = nextProps.filter,
minLength = nextProps.minLength,
caseSensitive = nextProps.caseSensitive;
var focusedItem = prevState.focusedItem;
var accessors = (0, _getAccessors.default)(nextProps);
var valueChanged = value !== prevState.lastValue;
var selectedIndex = accessors.indexOf(data, value);
var dataItem = selectedIndex === -1 ? value : data[selectedIndex];
var searchTerm; // filter only when the value is not an item in the data list
if (selectedIndex === -1 || prevState.isSuggesting()) {
searchTerm = accessors.text(dataItem);
}
data = Filter$$1.filter(data, {
filter: filter,
searchTerm: searchTerm,
minLength: minLength,
caseSensitive: caseSensitive,
textField: accessors.text
});
var list = (0, _reduceToListState.default)(data, prevState.list, {
nextProps: nextProps
}); // index may have changed after filtering
if (selectedIndex !== -1) {
selectedIndex = accessors.indexOf(data, value);
}
var focusedIndex = accessors.indexOf(data, focusedItem);
if (focusedIndex === -1) {
// value isn't a dataItem so find the close match
focusedIndex = Filter$$1.indexOf(data, {
searchTerm: searchTerm,
textField: accessors.text,
filter: filter || true
});
}
var selectedItem = data[selectedIndex];
var nextFocusedItem = null; // If no item is focused, or is no longer in the dataset, default to either the selected item, or to the first item in the list
if (focusedIndex === -1) {
if (selectedItem) {
nextFocusedItem = selectedItem;
} else {
nextFocusedItem = data[0];
}
} else {
nextFocusedItem = data[focusedIndex];
}
return {
data: data,
list: list,
accessors: accessors,
lastValue: value,
messages: (0, messages_1.getMessages)(messages),
selectedItem: valueChanged ? list.nextEnabled(selectedItem) : prevState.selectedItem,
focusedItem: valueChanged || !focusedItem ? list.nextEnabled(selectedItem || nextFocusedItem) : nextFocusedItem
};
}; // has to be done early since `accept()` re-focuses the input
_proto.renderInput = function renderInput() {
var _this$props = this.props,
suggest = _this$props.suggest,
filter = _this$props.filter,
busy = _this$props.busy,
name = _this$props.name,
data = _this$props.data,
value = _this$props.value,
autoFocus = _this$props.autoFocus,
tabIndex = _this$props.tabIndex,
placeholder = _this$props.placeholder,
inputProps = _this$props.inputProps,
disabled = _this$props.disabled,
readOnly = _this$props.readOnly,
open = _this$props.open;
var accessors = this.state.accessors;
var valueItem = accessors.findOrSelf(data, value);
var completeType = suggest ? filter ? 'both' : 'inline' : filter ? 'list' : '';
return _react.default.createElement(_ComboboxInput.default, _extends({}, inputProps, {
role: "combobox",
name: name,
id: this.inputId,
autoFocus: autoFocus,
tabIndex: tabIndex,
suggest: suggest,
disabled: disabled === true,
readOnly: readOnly === true,
"aria-busy": !!busy,
"aria-owns": this.listId,
"aria-autocomplete": completeType,
"aria-activedescendant": open ? this.activeId : null,
"aria-expanded": open,
"aria-haspopup": true,
placeholder: placeholder,
value: accessors.text(valueItem),
onChange: this.handleInputChange,
onKeyDown: this.handleInputKeyDown,
ref: this.attachInputRef
}));
};
_proto.renderList = function renderList(messages) {
var activeId = this.activeId,
inputId = this.inputId,
listId = this.listId;
var _this$props2 = this.props,
open = _this$props2.open,
data = _this$props2.data,
value = _this$props2.value,
listProps = _this$props2.listProps,
optionComponent = _this$props2.optionComponent,
itemComponent = _this$props2.itemComponent,
groupComponent = _this$props2.groupComponent;
var _this$state = this.state,
list = _this$state.list,
accessors = _this$state.accessors,
focusedItem = _this$state.focusedItem,
selectedItem = _this$state.selectedItem,
filteredData = _this$state.data;
var List = this.props.listComponent;
return _react.default.createElement(List, _extends({}, listProps, {
id: listId,
activeId: activeId,
data: filteredData,
dataState: list.dataState,
isDisabled: list.isDisabled,
textAccessor: accessors.text,
valueAccessor: accessors.value,
itemComponent: itemComponent,
groupComponent: groupComponent,
optionComponent: optionComponent,
selectedItem: selectedItem,
focusedItem: open ? focusedItem : null,
searchTerm: accessors.text(value) || '',
"aria-hidden": !open,
"aria-labelledby": inputId,
"aria-live": open && 'polite',
onSelect: this.handleSelect,
onMove: this.handleScroll,
ref: this.attachListRef,
messages: {
emptyList: data.length ? messages.emptyFilter : messages.emptyList
}
}));
};
_proto.render = function render() {
var _this2 = this;
var _this$props3 = this.props,
isRtl = _this$props3.isRtl,
className = _this$props3.className,
popupTransition = _this$props3.popupTransition,
busy = _this$props3.busy,
dropUp = _this$props3.dropUp,
open = _this$props3.open,
selectIcon = _this$props3.selectIcon,
busySpinner = _this$props3.busySpinner,
containerClassName = _this$props3.containerClassName;
var _this$state2 = this.state,
focused = _this$state2.focused,
messages = _this$state2.messages;
var disabled = this.props.disabled === true,
readOnly = this.props.readOnly === true;
var elementProps = Props$$1.pickElementProps(this);
var shouldRenderPopup = (0, widgetHelpers.isFirstFocusedRender)(this);
return _react.default.createElement(_Widget.default, _extends({}, elementProps, {
open: open,
isRtl: isRtl,
dropUp: dropUp,
focused: focused,
disabled: disabled,
readOnly: readOnly,
onBlur: this.focusManager.handleBlur,
onFocus: this.focusManager.handleFocus,
onKeyDown: this.handleKeyDown,
className: (0, _classnames.default)(className, 'rw-combobox')
}), _react.default.createElement(_WidgetPicker.default, {
className: containerClassName
}, this.renderInput(), _react.default.createElement(_Select.default, {
bordered: true,
busy: busy,
icon: selectIcon,
spinner: busySpinner,
onClick: this.toggle,
disabled: disabled || readOnly,
label: messages.openCombobox(this.props)
})), shouldRenderPopup && _react.default.createElement(_Popup.default, {
open: open,
dropUp: dropUp,
transition: popupTransition,
onEntering: function onEntering() {
return _this2.listRef.forceUpdate();
}
}, _react.default.createElement("div", null, this.renderList(messages))));
};
_proto.focus = function focus() {
if (this.inputRef) this.inputRef.focus();
};
_proto.change = function change(nextValue, typing, originalEvent) {
var _this$props4 = this.props,
onChange = _this$props4.onChange,
lastValue = _this$props4.value;
this._typedChange = !!typing;
(0, widgetHelpers.notify)(onChange, [nextValue, {
lastValue: lastValue,
originalEvent: originalEvent
}]);
};
_proto.open = function open() {
if (!this.props.open) (0, widgetHelpers.notify)(this.props.onToggle, true);
};
_proto.close = function close() {
if (this.props.open) (0, widgetHelpers.notify)(this.props.onToggle, false);
};
_proto.suggest = function suggest(searchTerm) {
var _this$props5 = this.props,
textField = _this$props5.textField,
suggest = _this$props5.suggest,
minLength = _this$props5.minLength;
var data = this.state.data;
if (!this._deleting) return Filter$$1.suggest(data, {
minLength: minLength,
textField: textField,
searchTerm: searchTerm,
filter: suggest,
caseSensitive: false
});
return searchTerm;
};
return Combobox;
}(_react.default.Component), _class3.propTypes = propTypes$$1, _class3.defaultProps = {
data: [],
value: '',
open: false,
suggest: false,
filter: false,
delay: 500,
selectIcon: Icon_1.caretDown,
listComponent: _List.default
}, _temp), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, "handleSelect", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this3 = this;
return function (data, originalEvent) {
_this3.close();
(0, widgetHelpers.notify)(_this3.props.onSelect, [data, {
originalEvent: originalEvent
}]);
_this3.change(data, false, originalEvent);
_this3.inputRef && _this3.inputRef.accept(true);
_this3.focus();
};
}
}), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, "handleKeyDown", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this4 = this;
return function (e) {
var key = e.key,
altKey = e.altKey;
var _this4$props = _this4.props,
open = _this4$props.open,
onKeyDown = _this4$props.onKeyDown;
var _this4$state = _this4.state,
focusedItem = _this4$state.focusedItem,
selectedItem = _this4$state.selectedItem,
list = _this4$state.list;
(0, widgetHelpers.notify)(onKeyDown, [e]);
if (e.defaultPrevented) return;
var select = function select(item) {
return item != null && _this4.handleSelect(item, e);
};
var focusItem = function focusItem(item) {
return _this4.setState({
focusedItem: item
});
};
if (key === 'End' && open) {
e.preventDefault();
focusItem(list.last());
} else if (key === 'Home' && open) {
e.preventDefault();
focusItem(list.first());
} else if (key === 'Escape' && open) {
e.preventDefault();
_this4.close();
} else if (key === 'Enter' && open) {
e.preventDefault();
select(_this4.state.focusedItem);
} else if (key === 'Tab') {
_this4.inputRef.accept();
} else if (key === 'ArrowDown') {
e.preventDefault();
if (altKey) return _this4.open();
if (open) focusItem(list.next(focusedItem));else select(list.next(selectedItem));
} else if (key === 'ArrowUp') {
e.preventDefault();
if (altKey) return _this4.close();
if (open) focusItem(list.prev(focusedItem));else select(list.prev(selectedItem));
}
};
}
}), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, "toggle", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this5 = this;
return function () {
_this5.focus();
_this5.props.open ? _this5.close() : _this5.open();
};
}
})), _class2)) || _class;
var _default = (0, _uncontrollable.default)(Combobox, {
open: 'onToggle',
value: 'onChange'
}, ['focus']);
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(Combobox_1);
var Header_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _react = _interopRequireDefault(React__default);
var _propTypes = _interopRequireDefault(propTypes);
var _Button = _interopRequireDefault(Button_1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var Header =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(Header, _React$Component);
function Header() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = Header.prototype;
_proto.render = function render() {
var _this$props = this.props,
messages = _this$props.messages,
label = _this$props.label,
labelId = _this$props.labelId,
onMoveRight = _this$props.onMoveRight,
onMoveLeft = _this$props.onMoveLeft,
onViewChange = _this$props.onViewChange,
prevDisabled = _this$props.prevDisabled,
upDisabled = _this$props.upDisabled,
nextDisabled = _this$props.nextDisabled,
_this$props$navigateP = _this$props.navigatePrevIcon,
navigatePrevIcon = _this$props$navigateP === void 0 ? Icon_1.chevronLeft : _this$props$navigateP,
_this$props$navigateN = _this$props.navigateNextIcon,
navigateNextIcon = _this$props$navigateN === void 0 ? Icon_1.chevronRight : _this$props$navigateN,
isRtl = _this$props.isRtl;
return _react.default.createElement("div", {
className: "rw-calendar-header"
}, _react.default.createElement(_Button.default, {
className: "rw-calendar-btn-left",
onClick: onMoveLeft,
disabled: prevDisabled,
label: messages.moveBack(),
icon: isRtl ? navigateNextIcon : navigatePrevIcon
}), _react.default.createElement(_Button.default, {
id: labelId,
onClick: onViewChange,
className: "rw-calendar-btn-view",
disabled: upDisabled,
"aria-live": "polite",
"aria-atomic": "true"
}, label), _react.default.createElement(_Button.default, {
className: "rw-calendar-btn-right",
onClick: onMoveRight,
disabled: nextDisabled,
label: messages.moveForward(),
icon: isRtl ? navigatePrevIcon : navigateNextIcon
}));
};
return Header;
}(_react.default.Component);
Header.propTypes = {
label: _propTypes.default.string.isRequired,
labelId: _propTypes.default.string,
upDisabled: _propTypes.default.bool.isRequired,
prevDisabled: _propTypes.default.bool.isRequired,
nextDisabled: _propTypes.default.bool.isRequired,
onViewChange: _propTypes.default.func.isRequired,
onMoveLeft: _propTypes.default.func.isRequired,
onMoveRight: _propTypes.default.func.isRequired,
navigatePrevIcon: _propTypes.default.node,
navigateNextIcon: _propTypes.default.node,
messages: _propTypes.default.shape({
moveBack: _propTypes.default.func.isRequired,
moveForward: _propTypes.default.func.isRequired
}),
isRtl: _propTypes.default.bool
};
var _default = Header;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(Header_1);
var Footer_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = Footer;
var _react = _interopRequireDefault(React__default);
var _propTypes = _interopRequireDefault(propTypes);
var _Button = _interopRequireDefault(Button_1);
var CustomPropTypes = _interopRequireWildcard(PropTypes$2);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var propTypes$$1 = {
disabled: _propTypes.default.bool,
readOnly: _propTypes.default.bool,
value: _propTypes.default.instanceOf(Date),
onClick: _propTypes.default.func.isRequired,
culture: _propTypes.default.string,
format: CustomPropTypes.dateFormat
};
function Footer(_ref) {
var disabled = _ref.disabled,
readOnly = _ref.readOnly,
value = _ref.value,
onClick = _ref.onClick,
culture = _ref.culture,
format = _ref.format;
return _react.default.createElement("div", {
className: "rw-calendar-footer"
}, _react.default.createElement(_Button.default, {
disabled: !!(disabled || readOnly),
onClick: onClick.bind(null, value)
}, localizers.date.format(value, localizers.date.getFormat('footer', format), culture)));
}
Footer.propTypes = propTypes$$1;
module.exports = exports["default"];
});
unwrapExports(Footer_1);
var dateArithmetic = createCommonjsModule(function (module) {
var MILI = 'milliseconds'
, SECONDS = 'seconds'
, MINUTES = 'minutes'
, HOURS = 'hours'
, DAY = 'day'
, WEEK = 'week'
, MONTH = 'month'
, YEAR = 'year'
, DECADE = 'decade'
, CENTURY = 'century';
var dates = module.exports = {
add: function(date, num, unit) {
date = new Date(date);
switch (unit){
case MILI:
case SECONDS:
case MINUTES:
case HOURS:
case YEAR:
return dates[unit](date, dates[unit](date) + num)
case DAY:
return dates.date(date, dates.date(date) + num)
case WEEK:
return dates.date(date, dates.date(date) + (7 * num))
case MONTH:
return monthMath(date, num)
case DECADE:
return dates.year(date, dates.year(date) + (num * 10))
case CENTURY:
return dates.year(date, dates.year(date) + (num * 100))
}
throw new TypeError('Invalid units: "' + unit + '"')
},
subtract: function(date, num, unit) {
return dates.add(date, -num, unit)
},
startOf: function(date, unit, firstOfWeek) {
date = new Date(date);
switch (unit) {
case 'century':
case 'decade':
case 'year':
date = dates.month(date, 0);
case 'month':
date = dates.date(date, 1);
case 'week':
case 'day':
date = dates.hours(date, 0);
case 'hours':
date = dates.minutes(date, 0);
case 'minutes':
date = dates.seconds(date, 0);
case 'seconds':
date = dates.milliseconds(date, 0);
}
if (unit === DECADE)
date = dates.subtract(date, dates.year(date) % 10, 'year');
if (unit === CENTURY)
date = dates.subtract(date, dates.year(date) % 100, 'year');
if (unit === WEEK)
date = dates.weekday(date, 0, firstOfWeek);
return date
},
endOf: function(date, unit, firstOfWeek){
date = new Date(date);
date = dates.startOf(date, unit, firstOfWeek);
date = dates.add(date, 1, unit);
date = dates.subtract(date, 1, MILI);
return date
},
eq: createComparer(function(a, b){ return a === b }),
neq: createComparer(function(a, b){ return a !== b }),
gt: createComparer(function(a, b){ return a > b }),
gte: createComparer(function(a, b){ return a >= b }),
lt: createComparer(function(a, b){ return a < b }),
lte: createComparer(function(a, b){ return a <= b }),
min: function(){
return new Date(Math.min.apply(Math, arguments))
},
max: function(){
return new Date(Math.max.apply(Math, arguments))
},
inRange: function(day, min, max, unit){
unit = unit || 'day';
return (!min || dates.gte(day, min, unit))
&& (!max || dates.lte(day, max, unit))
},
milliseconds: createAccessor('Milliseconds'),
seconds: createAccessor('Seconds'),
minutes: createAccessor('Minutes'),
hours: createAccessor('Hours'),
day: createAccessor('Day'),
date: createAccessor('Date'),
month: createAccessor('Month'),
year: createAccessor('FullYear'),
decade: function (date, val) {
return val === undefined
? dates.year(dates.startOf(date, DECADE))
: dates.add(date, val + 10, YEAR);
},
century: function (date, val) {
return val === undefined
? dates.year(dates.startOf(date, CENTURY))
: dates.add(date, val + 100, YEAR);
},
weekday: function (date, val, firstDay) {
var weekday = (dates.day(date) + 7 - (firstDay || 0) ) % 7;
return val === undefined
? weekday
: dates.add(date, val - weekday, DAY);
},
diff: function (date1, date2, unit, asFloat) {
var dividend, divisor, result;
switch (unit) {
case MILI:
case SECONDS:
case MINUTES:
case HOURS:
case DAY:
case WEEK:
dividend = date2.getTime() - date1.getTime(); break;
case MONTH:
case YEAR:
case DECADE:
case CENTURY:
dividend = (dates.year(date2) - dates.year(date1)) * 12 + dates.month(date2) - dates.month(date1); break;
default:
throw new TypeError('Invalid units: "' + unit + '"');
}
switch (unit) {
case MILI:
divisor = 1; break;
case SECONDS:
divisor = 1000; break;
case MINUTES:
divisor = 1000 * 60; break;
case HOURS:
divisor = 1000 * 60 * 60; break;
case DAY:
divisor = 1000 * 60 * 60 * 24; break;
case WEEK:
divisor = 1000 * 60 * 60 * 24 * 7; break;
case MONTH:
divisor = 1; break;
case YEAR:
divisor = 12; break;
case DECADE:
divisor = 120; break;
case CENTURY:
divisor = 1200; break;
default:
throw new TypeError('Invalid units: "' + unit + '"');
}
result = dividend / divisor;
return asFloat ? result : absoluteFloor(result);
}
};
function absoluteFloor(number) {
return number < 0 ? Math.ceil(number) : Math.floor(number);
}
function monthMath(date, val){
var current = dates.month(date)
, newMonth = (current + val);
date = dates.month(date, newMonth);
while (newMonth < 0 ) newMonth = 12 + newMonth;
//month rollover
if ( dates.month(date) !== ( newMonth % 12))
date = dates.date(date, 0); //move to last of month
return date
}
function createAccessor(method){
return function(date, val){
if (val === undefined)
return date['get' + method]()
date = new Date(date);
date['set' + method](val);
return date
}
}
function createComparer(operator) {
return function (a, b, unit) {
return operator(+dates.startOf(a, unit), +dates.startOf(b, unit))
};
}
});
var dateArithmetic_1 = dateArithmetic.add;
var dateArithmetic_2 = dateArithmetic.subtract;
var dateArithmetic_3 = dateArithmetic.startOf;
var dateArithmetic_4 = dateArithmetic.endOf;
var dateArithmetic_5 = dateArithmetic.eq;
var dateArithmetic_6 = dateArithmetic.neq;
var dateArithmetic_7 = dateArithmetic.gt;
var dateArithmetic_8 = dateArithmetic.gte;
var dateArithmetic_9 = dateArithmetic.lt;
var dateArithmetic_10 = dateArithmetic.lte;
var dateArithmetic_11 = dateArithmetic.min;
var dateArithmetic_12 = dateArithmetic.max;
var dateArithmetic_13 = dateArithmetic.inRange;
var dateArithmetic_14 = dateArithmetic.milliseconds;
var dateArithmetic_15 = dateArithmetic.seconds;
var dateArithmetic_16 = dateArithmetic.minutes;
var dateArithmetic_17 = dateArithmetic.hours;
var dateArithmetic_18 = dateArithmetic.day;
var dateArithmetic_19 = dateArithmetic.date;
var dateArithmetic_20 = dateArithmetic.month;
var dateArithmetic_21 = dateArithmetic.year;
var dateArithmetic_22 = dateArithmetic.decade;
var dateArithmetic_23 = dateArithmetic.century;
var dateArithmetic_24 = dateArithmetic.weekday;
var dateArithmetic_25 = dateArithmetic.diff;
var dates_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _dateArithmetic = _interopRequireDefault(dateArithmetic);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
var dates = _extends({}, _dateArithmetic.default, {
monthsInYear: function monthsInYear(year) {
var date = new Date(year, 0, 1);
return [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].map(function (i) {
return dates.month(date, i);
});
},
firstVisibleDay: function firstVisibleDay(date, culture) {
var firstOfMonth = dates.startOf(date, 'month');
return dates.startOf(firstOfMonth, 'week', localizers.date.firstOfWeek(culture));
},
lastVisibleDay: function lastVisibleDay(date, culture) {
var endOfMonth = dates.endOf(date, 'month');
return dates.endOf(endOfMonth, 'week', localizers.date.firstOfWeek(culture));
},
visibleDays: function visibleDays(date, culture) {
var current = dates.firstVisibleDay(date, culture);
var last = dates.lastVisibleDay(date, culture);
var days = [];
while (dates.lte(current, last, 'day')) {
days.push(current);
current = dates.add(current, 1, 'day');
}
return days;
},
merge: function merge(date, time, defaultDate) {
if (time == null && date == null) return null;
if (time == null) time = defaultDate || new Date();
if (date == null) date = defaultDate || new Date();
date = dates.startOf(date, 'day');
date = dates.hours(date, dates.hours(time));
date = dates.minutes(date, dates.minutes(time));
date = dates.seconds(date, dates.seconds(time));
return dates.milliseconds(date, dates.milliseconds(time));
},
today: function today() {
return dates.startOf(new Date(), 'day');
},
tomorrow: function tomorrow() {
return dates.add(dates.startOf(new Date(), 'day'), 1, 'day');
}
});
var _default = dates;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(dates_1);
var CalendarView_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _react = _interopRequireDefault(React__default);
var _propTypes = _interopRequireDefault(propTypes);
var _classnames = _interopRequireDefault(classnames);
var _dates = _interopRequireDefault(dates_1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutProperties(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]; } if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var VIEW_UNITS = ['month', 'year', 'decade', 'century'];
function clamp(date, min, max) {
return _dates.default.max(_dates.default.min(date, max), min);
}
var CalendarView =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(CalendarView, _React$Component);
function CalendarView() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = CalendarView.prototype;
_proto.render = function render() {
var _this$props = this.props,
className = _this$props.className,
activeId = _this$props.activeId,
props = _objectWithoutProperties(_this$props, ["className", "activeId"]);
return _react.default.createElement("table", _extends({}, props, {
role: "grid",
tabIndex: "-1",
"aria-activedescendant": activeId || null,
className: (0, _classnames.default)(className, 'rw-nav-view', 'rw-calendar-grid')
}));
};
return CalendarView;
}(_react.default.Component);
CalendarView.propTypes = {
activeId: _propTypes.default.string
};
var CalendarViewCell =
/*#__PURE__*/
function (_React$Component2) {
_inheritsLoose(CalendarViewCell, _React$Component2);
function CalendarViewCell() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component2.call.apply(_React$Component2, [this].concat(args)) || this;
_this.handleChange = function () {
var _this$props2 = _this.props,
onChange = _this$props2.onChange,
min = _this$props2.min,
max = _this$props2.max,
date = _this$props2.date;
onChange(clamp(date, min, max));
};
return _this;
}
var _proto2 = CalendarViewCell.prototype;
_proto2.isEmpty = function isEmpty() {
var _this$props3 = this.props,
unit = _this$props3.unit,
min = _this$props3.min,
max = _this$props3.max,
date = _this$props3.date;
return !_dates.default.inRange(date, min, max, unit);
};
_proto2.isEqual = function isEqual(date) {
return _dates.default.eq(this.props.date, date, this.props.unit);
};
_proto2.isFocused = function isFocused() {
return !this.props.disabled && !this.isEmpty() && this.isEqual(this.props.focused);
};
_proto2.isNow = function isNow() {
return this.props.now && this.isEqual(this.props.now);
};
_proto2.isOffView = function isOffView() {
var _this$props4 = this.props,
viewUnit = _this$props4.viewUnit,
focused = _this$props4.focused,
date = _this$props4.date;
return date && focused && viewUnit && _dates.default[viewUnit](date) !== _dates.default[viewUnit](focused);
};
_proto2.isSelected = function isSelected() {
return this.props.selected && this.isEqual(this.props.selected);
};
_proto2.render = function render() {
var _this$props5 = this.props,
children = _this$props5.children,
activeId = _this$props5.activeId,
label = _this$props5.label,
disabled = _this$props5.disabled;
var isDisabled = disabled || this.isEmpty();
return _react.default.createElement("td", {
role: "gridcell",
id: this.isFocused() ? activeId : null,
title: label,
"aria-label": label,
"aria-readonly": disabled,
"aria-selected": this.isSelected(),
onClick: !isDisabled ? this.handleChange : undefined,
className: (0, _classnames.default)('rw-cell', this.isNow() && 'rw-now', isDisabled && 'rw-state-disabled', this.isEmpty() && 'rw-cell-not-allowed', this.isOffView() && 'rw-cell-off-range', this.isFocused() && 'rw-state-focus', this.isSelected() && 'rw-state-selected')
}, children);
};
return CalendarViewCell;
}(_react.default.Component);
CalendarViewCell.propTypes = {
id: _propTypes.default.string,
activeId: _propTypes.default.string.isRequired,
label: _propTypes.default.string,
now: _propTypes.default.instanceOf(Date),
date: _propTypes.default.instanceOf(Date),
selected: _propTypes.default.instanceOf(Date),
focused: _propTypes.default.instanceOf(Date),
min: _propTypes.default.instanceOf(Date),
max: _propTypes.default.instanceOf(Date),
unit: _propTypes.default.oneOf(['day'].concat(VIEW_UNITS)),
viewUnit: _propTypes.default.oneOf(VIEW_UNITS),
onChange: _propTypes.default.func.isRequired,
disabled: _propTypes.default.bool
};
CalendarView.Body = function (props) {
return _react.default.createElement("tbody", _extends({
className: "rw-calendar-body"
}, props));
};
CalendarView.Row = function (props) {
return _react.default.createElement("tr", _extends({
role: "row",
className: "rw-calendar-row"
}, props));
};
CalendarView.Cell = CalendarViewCell;
var _default = CalendarView;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(CalendarView_1);
var Month = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _classnames = _interopRequireDefault(classnames);
var _propTypes = _interopRequireDefault(propTypes);
var _react = _interopRequireDefault(React__default);
var _CalendarView = _interopRequireDefault(CalendarView_1);
var _dates = _interopRequireDefault(dates_1);
var CustomPropTypes = _interopRequireWildcard(PropTypes$2);
var Props$$1 = _interopRequireWildcard(Props);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var isEqual = function isEqual(dateA, dateB) {
return _dates.default.eq(dateA, dateB, 'day');
};
var MonthView =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(MonthView, _React$Component);
function MonthView() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_this.renderRow = function (row, rowIdx) {
var _this$props = _this.props,
focused = _this$props.focused,
today = _this$props.today,
activeId = _this$props.activeId,
disabled = _this$props.disabled,
onChange = _this$props.onChange,
value = _this$props.value,
culture = _this$props.culture,
min = _this$props.min,
max = _this$props.max,
footerFormat = _this$props.footerFormat,
dateFormat = _this$props.dateFormat,
Day = _this$props.dayComponent;
footerFormat = localizers.date.getFormat('footer', footerFormat);
dateFormat = localizers.date.getFormat('dayOfMonth', dateFormat);
return _react.default.createElement(_CalendarView.default.Row, {
key: rowIdx
}, row.map(function (date, colIdx) {
var formattedDate = localizers.date.format(date, dateFormat, culture);
var label = localizers.date.format(date, footerFormat, culture);
return _react.default.createElement(_CalendarView.default.Cell, {
key: colIdx,
activeId: activeId,
label: label,
date: date,
now: today,
min: min,
max: max,
unit: "day",
viewUnit: "month",
onChange: onChange,
focused: focused,
selected: value,
disabled: disabled
}, Day ? _react.default.createElement(Day, {
date: date,
label: formattedDate
}) : formattedDate);
}));
};
return _this;
}
var _proto = MonthView.prototype;
_proto.renderHeaders = function renderHeaders(week, format, culture) {
var firstOfWeek = localizers.date.firstOfWeek(culture);
return week.map(function (date) {
return _react.default.createElement("th", {
className: "rw-head-cell",
key: 'header_' + _dates.default.weekday(date, undefined, firstOfWeek)
}, localizers.date.format(date, format, culture));
});
};
_proto.render = function render() {
var _this$props2 = this.props,
className = _this$props2.className,
focused = _this$props2.focused,
culture = _this$props2.culture,
activeId = _this$props2.activeId,
dayFormat = _this$props2.dayFormat;
var month = _dates.default.visibleDays(focused, culture);
var rows = (0, _.chunk)(month, 7);
dayFormat = localizers.date.getFormat('weekday', dayFormat);
return _react.default.createElement(_CalendarView.default, _extends({}, Props$$1.omitOwn(this), {
activeId: activeId,
className: (0, _classnames.default)(className, 'rw-calendar-month')
}), _react.default.createElement("thead", {
className: "rw-calendar-head"
}, _react.default.createElement("tr", {
className: "rw-calendar-row"
}, this.renderHeaders(rows[0], dayFormat, culture))), _react.default.createElement(_CalendarView.default.Body, null, rows.map(this.renderRow)));
};
return MonthView;
}(_react.default.Component);
MonthView.isEqual = isEqual;
MonthView.propTypes = {
activeId: _propTypes.default.string,
culture: _propTypes.default.string,
today: _propTypes.default.instanceOf(Date),
value: _propTypes.default.instanceOf(Date),
focused: _propTypes.default.instanceOf(Date),
min: _propTypes.default.instanceOf(Date),
max: _propTypes.default.instanceOf(Date),
onChange: _propTypes.default.func.isRequired,
dayComponent: CustomPropTypes.elementType,
dayFormat: CustomPropTypes.dateFormat,
dateFormat: CustomPropTypes.dateFormat,
footerFormat: CustomPropTypes.dateFormat,
disabled: _propTypes.default.bool
};
var _default = MonthView;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(Month);
var Year = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _react = _interopRequireDefault(React__default);
var _propTypes = _interopRequireDefault(propTypes);
var _CalendarView = _interopRequireDefault(CalendarView_1);
var _dates = _interopRequireDefault(dates_1);
var Props$$1 = _interopRequireWildcard(Props);
var CustomPropTypes = _interopRequireWildcard(PropTypes$2);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var YearView =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(YearView, _React$Component);
function YearView() {
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.renderRow = function (row, rowIdx) {
var _this$props = _this.props,
focused = _this$props.focused,
activeId = _this$props.activeId,
disabled = _this$props.disabled,
onChange = _this$props.onChange,
value = _this$props.value,
today = _this$props.today,
culture = _this$props.culture,
headerFormat = _this$props.headerFormat,
monthFormat = _this$props.monthFormat,
min = _this$props.min,
max = _this$props.max;
headerFormat = localizers.date.getFormat('header', headerFormat);
monthFormat = localizers.date.getFormat('month', monthFormat);
return _react.default.createElement(_CalendarView.default.Row, {
key: rowIdx
}, row.map(function (date, colIdx) {
var label = localizers.date.format(date, headerFormat, culture);
return _react.default.createElement(_CalendarView.default.Cell, {
key: colIdx,
activeId: activeId,
label: label,
date: date,
now: today,
min: min,
max: max,
unit: "month",
onChange: onChange,
focused: focused,
selected: value,
disabled: disabled
}, localizers.date.format(date, monthFormat, culture));
}));
};
return _this;
}
var _proto = YearView.prototype;
_proto.render = function render() {
var _this$props2 = this.props,
focused = _this$props2.focused,
activeId = _this$props2.activeId,
months = _dates.default.monthsInYear(_dates.default.year(focused));
return _react.default.createElement(_CalendarView.default, _extends({}, Props$$1.omitOwn(this), {
activeId: activeId
}), _react.default.createElement(_CalendarView.default.Body, null, (0, _.chunk)(months, 4).map(this.renderRow)));
};
return YearView;
}(_react.default.Component);
YearView.propTypes = {
activeId: _propTypes.default.string,
culture: _propTypes.default.string,
today: _propTypes.default.instanceOf(Date),
value: _propTypes.default.instanceOf(Date),
focused: _propTypes.default.instanceOf(Date),
min: _propTypes.default.instanceOf(Date),
max: _propTypes.default.instanceOf(Date),
onChange: _propTypes.default.func.isRequired,
headerFormat: CustomPropTypes.dateFormat,
monthFormat: CustomPropTypes.dateFormat,
disabled: _propTypes.default.bool
};
var _default = YearView;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(Year);
var Decade = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _react = _interopRequireDefault(React__default);
var _propTypes = _interopRequireDefault(propTypes);
var _CalendarView = _interopRequireDefault(CalendarView_1);
var _dates = _interopRequireDefault(dates_1);
var Props$$1 = _interopRequireWildcard(Props);
var CustomPropTypes = _interopRequireWildcard(PropTypes$2);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var DecadeView =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(DecadeView, _React$Component);
function DecadeView() {
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.renderRow = function (row, rowIdx) {
var _this$props = _this.props,
focused = _this$props.focused,
activeId = _this$props.activeId,
disabled = _this$props.disabled,
onChange = _this$props.onChange,
yearFormat = _this$props.yearFormat,
value = _this$props.value,
today = _this$props.today,
culture = _this$props.culture,
min = _this$props.min,
max = _this$props.max;
return _react.default.createElement(_CalendarView.default.Row, {
key: rowIdx
}, row.map(function (date, colIdx) {
var label = localizers.date.format(date, localizers.date.getFormat('year', yearFormat), culture);
return _react.default.createElement(_CalendarView.default.Cell, {
key: colIdx,
unit: "year",
activeId: activeId,
label: label,
date: date,
now: today,
min: min,
max: max,
onChange: onChange,
focused: focused,
selected: value,
disabled: disabled
}, label);
}));
};
return _this;
}
var _proto = DecadeView.prototype;
_proto.render = function render() {
var _this$props2 = this.props,
focused = _this$props2.focused,
activeId = _this$props2.activeId;
return _react.default.createElement(_CalendarView.default, _extends({}, Props$$1.omitOwn(this), {
activeId: activeId
}), _react.default.createElement(_CalendarView.default.Body, null, (0, _.chunk)(getDecadeYears(focused), 4).map(this.renderRow)));
};
return DecadeView;
}(_react.default.Component);
DecadeView.propTypes = {
activeId: _propTypes.default.string,
culture: _propTypes.default.string,
today: _propTypes.default.instanceOf(Date),
value: _propTypes.default.instanceOf(Date),
focused: _propTypes.default.instanceOf(Date),
min: _propTypes.default.instanceOf(Date),
max: _propTypes.default.instanceOf(Date),
onChange: _propTypes.default.func.isRequired,
yearFormat: CustomPropTypes.dateFormat,
disabled: _propTypes.default.bool
};
function getDecadeYears(_date) {
var days = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
date = _dates.default.add(_dates.default.startOf(_date, 'decade'), -2, 'year');
return days.map(function () {
return date = _dates.default.add(date, 1, 'year');
});
}
var _default = DecadeView;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(Decade);
var Century = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _react = _interopRequireDefault(React__default);
var _propTypes = _interopRequireDefault(propTypes);
var _CalendarView = _interopRequireDefault(CalendarView_1);
var _dates = _interopRequireDefault(dates_1);
var Props$$1 = _interopRequireWildcard(Props);
var CustomPropTypes = _interopRequireWildcard(PropTypes$2);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var CenturyView =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(CenturyView, _React$Component);
function CenturyView() {
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.renderRow = function (row, rowIdx) {
var _this$props = _this.props,
focused = _this$props.focused,
activeId = _this$props.activeId,
disabled = _this$props.disabled,
onChange = _this$props.onChange,
value = _this$props.value,
today = _this$props.today,
culture = _this$props.culture,
min = _this$props.min,
decadeFormat = _this$props.decadeFormat,
max = _this$props.max;
decadeFormat = localizers.date.getFormat('decade', decadeFormat);
return _react.default.createElement(_CalendarView.default.Row, {
key: rowIdx
}, row.map(function (date, colIdx) {
var label = localizers.date.format(_dates.default.startOf(date, 'decade'), decadeFormat, culture);
return _react.default.createElement(_CalendarView.default.Cell, {
key: colIdx,
unit: "decade",
activeId: activeId,
label: label,
date: date,
now: today,
min: min,
max: max,
onChange: onChange,
focused: focused,
selected: value,
disabled: disabled
}, label);
}));
};
return _this;
}
var _proto = CenturyView.prototype;
_proto.render = function render() {
var _this$props2 = this.props,
focused = _this$props2.focused,
activeId = _this$props2.activeId;
return _react.default.createElement(_CalendarView.default, _extends({}, Props$$1.omitOwn(this), {
activeId: activeId
}), _react.default.createElement(_CalendarView.default.Body, null, (0, _.chunk)(getCenturyDecades(focused), 4).map(this.renderRow)));
};
return CenturyView;
}(_react.default.Component);
CenturyView.propTypes = {
activeId: _propTypes.default.string,
culture: _propTypes.default.string,
today: _propTypes.default.instanceOf(Date),
value: _propTypes.default.instanceOf(Date),
focused: _propTypes.default.instanceOf(Date),
min: _propTypes.default.instanceOf(Date),
max: _propTypes.default.instanceOf(Date),
onChange: _propTypes.default.func.isRequired,
decadeFormat: CustomPropTypes.dateFormat,
disabled: _propTypes.default.bool
};
function getCenturyDecades(_date) {
var days = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
date = _dates.default.add(_dates.default.startOf(_date, 'century'), -20, 'year');
return days.map(function () {
return date = _dates.default.add(date, 10, 'year');
});
}
var _default = CenturyView;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(Century);
var ChildMapping = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.getChildMapping = getChildMapping;
exports.mergeChildMappings = mergeChildMappings;
exports.getInitialChildMapping = getInitialChildMapping;
exports.getNextChildMapping = getNextChildMapping;
/**
* Given `this.props.children`, return an object mapping key to child.
*
* @param {*} children `this.props.children`
* @return {object} Mapping of key to child
*/
function getChildMapping(children, mapFn) {
var mapper = function mapper(child) {
return mapFn && (0, React__default.isValidElement)(child) ? mapFn(child) : child;
};
var result = Object.create(null);
if (children) React__default.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.
*/
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];
}
function getInitialChildMapping(props, onExited) {
return getChildMapping(props.children, function (child) {
return (0, React__default.cloneElement)(child, {
onExited: onExited.bind(null, child),
in: true,
appear: getProp(child, 'appear', props),
enter: getProp(child, 'enter', props),
exit: getProp(child, 'exit', props)
});
});
}
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 (!(0, React__default.isValidElement)(child)) return;
var hasPrev = key in prevChildMapping;
var hasNext = key in nextChildMapping;
var prevChild = prevChildMapping[key];
var isLeaving = (0, React__default.isValidElement)(prevChild) && !prevChild.props.in; // item is new (entering)
if (hasNext && (!hasPrev || isLeaving)) {
// console.log('entering', key)
children[key] = (0, React__default.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] = (0, React__default.cloneElement)(child, {
in: false
});
} else if (hasNext && hasPrev && (0, React__default.isValidElement)(prevChild)) {
// item hasn't changed transition states
// copy over the last transition props;
// console.log('unchanged', key)
children[key] = (0, React__default.cloneElement)(child, {
onExited: onExited.bind(null, child),
in: prevChild.props.in,
exit: getProp(child, 'exit', nextProps),
enter: getProp(child, 'enter', nextProps)
});
}
});
return children;
}
});
unwrapExports(ChildMapping);
var ChildMapping_1 = ChildMapping.getChildMapping;
var ChildMapping_2 = ChildMapping.mergeChildMappings;
var ChildMapping_3 = ChildMapping.getInitialChildMapping;
var ChildMapping_4 = ChildMapping.getNextChildMapping;
var TransitionGroup_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _propTypes = _interopRequireDefault(propTypes);
var _react = _interopRequireDefault(React__default);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _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 _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
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(_assertThisInitialized(_this))); // Initial children should all be entering, dependent on appear
_this.state = {
handleExited: handleExited,
firstRender: true
};
return _this;
}
var _proto = TransitionGroup.prototype;
_proto.getChildContext = function getChildContext() {
return {
transitionGroup: {
isMounting: !this.appeared
}
};
};
_proto.componentDidMount = function componentDidMount() {
this.appeared = true;
this.mounted = true;
};
_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 ? (0, ChildMapping.getInitialChildMapping)(nextProps, handleExited) : (0, ChildMapping.getNextChildMapping)(nextProps, prevChildMapping, handleExited),
firstRender: false
};
};
_proto.handleExited = function handleExited(child, node) {
var currentChildMapping = (0, ChildMapping.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 children = values(this.state.children).map(childFactory);
delete props.appear;
delete props.enter;
delete props.exit;
if (Component === null) {
return children;
}
return _react.default.createElement(Component, props, children);
};
return TransitionGroup;
}(_react.default.Component);
TransitionGroup.childContextTypes = {
transitionGroup: _propTypes.default.object.isRequired
};
TransitionGroup.propTypes = {};
TransitionGroup.defaultProps = defaultProps;
var _default = (0, reactLifecyclesCompat_es.polyfill)(TransitionGroup);
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(TransitionGroup_1);
var SlideTransitionGroup_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _classnames = _interopRequireDefault(classnames);
var _events = _interopRequireDefault(events);
var _style = _interopRequireDefault(style_1);
var _height = _interopRequireDefault(height_1);
var _propTypes = _interopRequireDefault(propTypes);
var _TransitionGroup = _interopRequireDefault(TransitionGroup_1);
var _Transition = _interopRequireWildcard(Transition_1);
var _react = _interopRequireDefault(React__default);
var Props$$1 = _interopRequireWildcard(Props);
var _transitionStyle, _transitionClasses;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
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 _objectWithoutProperties(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]; } if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var DirectionPropType = _propTypes.default.oneOf(['left', 'right', 'top', 'bottom']);
var transitionStyle = (_transitionStyle = {}, _transitionStyle[_Transition.ENTERING] = {
position: 'absolute'
}, _transitionStyle[_Transition.EXITING] = {
position: 'absolute'
}, _transitionStyle);
var transitionClasses = (_transitionClasses = {}, _transitionClasses[_Transition.ENTERED] = 'rw-calendar-transition-entered', _transitionClasses[_Transition.ENTERING] = 'rw-calendar-transition-entering', _transitionClasses[_Transition.EXITING] = 'rw-calendar-transition-exiting', _transitionClasses[_Transition.EXITED] = 'rw-calendar-transition-exited', _transitionClasses);
function parseDuration(node) {
var str = (0, _style.default)(node, properties.transitionDuration);
var mult = str.indexOf('ms') === -1 ? 1000 : 1;
return parseFloat(str) * mult;
}
var SlideTransition =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(SlideTransition, _React$Component);
function SlideTransition() {
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.handleTransitionEnd = function (node, done) {
var duration = parseDuration(node) || 300;
var handler = function handler() {
_events.default.off(node, properties.transitionEnd, handler, false);
done();
};
setTimeout(handler, duration * 1.5);
_events.default.on(node, properties.transitionEnd, handler, false);
};
return _this;
}
var _proto = SlideTransition.prototype;
_proto.render = function render() {
var _this$props = this.props,
children = _this$props.children,
props = _objectWithoutProperties(_this$props, ["children"]);
var direction = this.context.direction;
var child = _react.default.Children.only(children);
return _react.default.createElement(_Transition.default, _extends({}, props, {
timeout: 5000,
addEndListener: this.handleTransitionEnd
}), function (status, innerProps) {
return _react.default.cloneElement(child, _extends({}, innerProps, {
style: transitionStyle[status],
className: (0, _classnames.default)(child.props.className, 'rw-calendar-transition', "rw-calendar-transition-" + direction, transitionClasses[status])
}));
});
};
return SlideTransition;
}(_react.default.Component);
SlideTransition.contextTypes = {
direction: DirectionPropType
};
var SlideTransitionGroup =
/*#__PURE__*/
function (_React$Component2) {
_inheritsLoose(SlideTransitionGroup, _React$Component2);
function SlideTransitionGroup() {
var _this2;
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
_this2 = _React$Component2.call.apply(_React$Component2, [this].concat(args)) || this;
_this2.handleEnter = function (child) {
var node = (0, _reactDom.findDOMNode)(_assertThisInitialized(_assertThisInitialized(_this2)));
if (!child) return;
var height = (0, _height.default)(child) + 'px';
(0, _style.default)(node, {
height: height,
overflow: 'hidden'
});
};
_this2.handleExited = function () {
var node = (0, _reactDom.findDOMNode)(_assertThisInitialized(_assertThisInitialized(_this2)));
(0, _style.default)(node, {
overflow: '',
height: ''
});
};
return _this2;
}
var _proto2 = SlideTransitionGroup.prototype;
_proto2.getChildContext = function getChildContext() {
return {
direction: this.props.direction
};
};
_proto2.render = function render() {
var _this$props2 = this.props,
children = _this$props2.children,
direction = _this$props2.direction;
return _react.default.createElement(_TransitionGroup.default, _extends({}, Props$$1.omitOwn(this), {
component: "div",
className: "rw-calendar-transition-group"
}), _react.default.createElement(SlideTransition, {
key: children.key,
direction: direction,
onEnter: this.handleEnter,
onExited: this.handleExited
}, children));
};
return SlideTransitionGroup;
}(_react.default.Component);
SlideTransitionGroup.childContextTypes = {
direction: DirectionPropType
};
SlideTransitionGroup.defaultProps = {
direction: 'left'
};
SlideTransitionGroup.propTypes = {
direction: DirectionPropType
};
var _default = SlideTransitionGroup;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(SlideTransitionGroup_1);
var Calendar_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _react = _interopRequireDefault(React__default);
var _propTypes = _interopRequireDefault(propTypes);
var _classnames = _interopRequireDefault(classnames);
var _uncontrollable = _interopRequireDefault(uncontrollable_1);
var _Widget = _interopRequireDefault(Widget_1);
var _Header = _interopRequireDefault(Header_1);
var _Footer = _interopRequireDefault(Footer_1);
var _Month = _interopRequireDefault(Month);
var _Year = _interopRequireDefault(Year);
var _Decade = _interopRequireDefault(Decade);
var _Century = _interopRequireDefault(Century);
var _SlideTransitionGroup = _interopRequireDefault(SlideTransitionGroup_1);
var _focusManager = _interopRequireDefault(focusManager$2);
var CustomPropTypes = _interopRequireWildcard(PropTypes$2);
var Props$$1 = _interopRequireWildcard(Props);
var _dates = _interopRequireDefault(dates_1);
var _class, _class2, _descriptor, _descriptor2, _descriptor3, _descriptor4, _descriptor5, _descriptor6, _class3, _temp;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _initializerDefineProperty(target, property, descriptor, context) { if (!descriptor) return; Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 }); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { var desc = {}; Object['ke' + 'ys'](descriptor).forEach(function (key) { desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer) { desc.writable = true; } desc = decorators.slice().reverse().reduce(function (desc, decorator) { return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0) { desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0) { Object['define' + 'Property'](target, property, desc); desc = null; } return desc; }
var last = function last(a) {
return a[a.length - 1];
};
var VIEW_UNIT = {
month: 'day',
year: 'month',
decade: 'year',
century: 'decade'
};
var VIEW_OPTIONS = ['month', 'year', 'decade', 'century'];
var VIEW = {
month: _Month.default,
year: _Year.default,
decade: _Decade.default,
century: _Century.default
};
var ARROWS_TO_DIRECTION = {
ArrowDown: 'DOWN',
ArrowUp: 'UP',
ArrowRight: 'RIGHT',
ArrowLeft: 'LEFT'
};
var OPPOSITE_DIRECTION = {
LEFT: 'RIGHT',
RIGHT: 'LEFT'
};
var MULTIPLIER = {
year: 1,
decade: 10,
century: 100
};
function inRangeValue(_value, min, max) {
var value = dateOrNull(_value);
if (value === null) return value;
return _dates.default.max(_dates.default.min(value, max), min);
}
var propTypes$$1 = {
/** @ignore */
activeId: _propTypes.default.string,
/**
* @example ['disabled', ['new Date()']]
*/
disabled: CustomPropTypes.disabled,
/**
* @example ['readOnly', ['new Date()']]
*/
readOnly: CustomPropTypes.disabled,
/**
* @example ['onChangePicker', [ ['new Date()'] ]]
*/
onChange: _propTypes.default.func,
/**
* @example ['valuePicker', [ ['new Date()'] ]]
*/
value: _propTypes.default.instanceOf(Date),
/**
* The minimum date that the Calendar can navigate from.
*
* @example ['prop', ['min', 'new Date()']]
*/
min: _propTypes.default.instanceOf(Date).isRequired,
/**
* The maximum date that the Calendar can navigate to.
*
* @example ['prop', ['max', 'new Date()']]
*/
max: _propTypes.default.instanceOf(Date).isRequired,
/**
* Default current date at which the calendar opens. If none is provided, opens at today's date or the `value` date (if any).
*/
currentDate: _propTypes.default.instanceOf(Date),
/**
* Change event Handler that is called when the currentDate is changed. The handler is called with the currentDate object.
*/
onCurrentDateChange: _propTypes.default.func,
/** Specify the navigate into the past header icon */
navigatePrevIcon: _propTypes.default.node,
/** Specify the navigate into the future header icon */
navigateNextIcon: _propTypes.default.node,
/**
* Controls the currently displayed calendar view. Use `defaultView` to set a unique starting view.
*
* @type {("month"|"year"|"decade"|"century")}
* @controllable onViewChange
*/
view: function view(props) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return _propTypes.default.oneOf(props.views || VIEW_OPTIONS).apply(void 0, [props].concat(args));
},
/**
* Defines a list of views the Calendar can traverse through, starting with the
* first in the list to the last.
*
* @type array<"month"|"year"|"decade"|"century">
*/
views: _propTypes.default.arrayOf(_propTypes.default.oneOf(VIEW_OPTIONS)).isRequired,
/**
* A callback fired when the `view` changes.
*
* @controllable view
*/
onViewChange: _propTypes.default.func,
/**
* Callback fired when the Calendar navigates between views, or forward and backwards in time.
*
* @type function(date: ?Date, direction: string, view: string)
*/
onNavigate: _propTypes.default.func,
culture: _propTypes.default.string,
autoFocus: _propTypes.default.bool,
/**
* Show or hide the Calendar footer.
*
* @example ['prop', ['footer', true]]
*/
footer: _propTypes.default.bool,
/**
* Provide a custom component to render the days of the month. The Component is provided the following props
*
* - `date`: a `Date` object for the day of the month to render
* - `label`: a formatted `string` of the date to render. To adjust the format of the `label` string use the `dateFormat` prop, listed below.
*/
dayComponent: CustomPropTypes.elementType,
/**
* A formatter for the header button of the month view.
*
* @example ['dateFormat', ['headerFormat', "{ date: 'medium' }"]]
*/
headerFormat: CustomPropTypes.dateFormat,
/**
* A formatter for the Calendar footer, formats today's Date as a string.
*
* @example ['dateFormat', ['footerFormat', "{ date: 'medium' }", "date => 'Today is: ' + formatter(date)"]]
*/
footerFormat: CustomPropTypes.dateFormat,
/**
* A formatter calendar days of the week, the default formats each day as a Narrow name: "Mo", "Tu", etc.
*
* @example ['prop', { dayFormat: "day => \n['🎉', 'M', 'T','W','Th', 'F', '🎉'][day.getDay()]" }]
*/
dayFormat: CustomPropTypes.dateFormat,
/**
* A formatter for day of the month
*
* @example ['prop', { dateFormat: "dt => String(dt.getDate())" }]
*/
dateFormat: CustomPropTypes.dateFormat,
/**
* A formatter for month name.
*
* @example ['dateFormat', ['monthFormat', "{ raw: 'MMMM' }", null, { defaultView: '"year"' }]]
*/
monthFormat: CustomPropTypes.dateFormat,
/**
* A formatter for month name.
*
* @example ['dateFormat', ['yearFormat', "{ raw: 'yy' }", null, { defaultView: '"decade"' }]]
*/
yearFormat: CustomPropTypes.dateFormat,
/**
* A formatter for decade, the default formats the first and last year of the decade like: 2000 - 2009.
*/
decadeFormat: CustomPropTypes.dateFormat,
/**
* A formatter for century, the default formats the first and last year of the century like: 1900 - 1999.
*/
centuryFormat: CustomPropTypes.dateFormat,
isRtl: _propTypes.default.bool,
messages: _propTypes.default.shape({
moveBack: _propTypes.default.string,
moveForward: _propTypes.default.string
}),
onKeyDown: _propTypes.default.func,
/** @ignore */
tabIndex: _propTypes.default.any
/**
* ---
* localized: true
* shortcuts:
* - { key: ctrl + down arrow, label: navigate to next view }
* - { key: ctrl + up arrow, label: navigate to previous view }
* - { key: ctrl + left arrow, label: "navigate to previous: month, year, decade, or century" }
* - { key: ctrl + right arrow, label: "navigate to next: month, year, decade, or century" }
* - { key: left arrow, label: move focus to previous date}
* - { key: right arrow, label: move focus to next date }
* - { key: up arrow, label: move focus up within view }
* - { key: down key, label: move focus down within view }
* ---
*
* @public
*/
};
var Calendar = (0, reactLifecyclesCompat_es.polyfill)(_class = (_class2 = (_temp = _class3 =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(Calendar, _React$Component);
Calendar.move = function move(date, min, max, unit, direction) {
var isMonth = unit === 'month';
var isUpOrDown = direction === 'UP' || direction === 'DOWN';
var rangeUnit = VIEW_UNIT[unit];
var addUnit = isMonth && isUpOrDown ? 'week' : VIEW_UNIT[unit];
var amount = isMonth || !isUpOrDown ? 1 : 4;
var newDate;
if (direction === 'UP' || direction === 'LEFT') amount *= -1;
newDate = _dates.default.add(date, amount, addUnit);
return _dates.default.inRange(newDate, min, max, rangeUnit) ? newDate : date;
};
function Calendar() {
var _this;
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_this.handleFocusWillChange = function () {
if (_this.props.tabIndex == -1) return false;
};
_initializerDefineProperty(_this, "handleViewChange", _descriptor, _assertThisInitialized(_assertThisInitialized(_this)));
_initializerDefineProperty(_this, "handleMoveBack", _descriptor2, _assertThisInitialized(_assertThisInitialized(_this)));
_initializerDefineProperty(_this, "handleMoveForward", _descriptor3, _assertThisInitialized(_assertThisInitialized(_this)));
_initializerDefineProperty(_this, "handleChange", _descriptor4, _assertThisInitialized(_assertThisInitialized(_this)));
_initializerDefineProperty(_this, "handleFooterClick", _descriptor5, _assertThisInitialized(_assertThisInitialized(_this)));
_initializerDefineProperty(_this, "handleKeyDown", _descriptor6, _assertThisInitialized(_assertThisInitialized(_this)));
_this.viewId = (0, widgetHelpers.instanceId)(_assertThisInitialized(_assertThisInitialized(_this)), '_calendar');
_this.labelId = (0, widgetHelpers.instanceId)(_assertThisInitialized(_assertThisInitialized(_this)), '_calendar_label');
_this.activeId = _this.props.activeId || (0, widgetHelpers.instanceId)(_assertThisInitialized(_assertThisInitialized(_this)), '_calendar_active_cell');
(0, lib$1.autoFocus)(_assertThisInitialized(_assertThisInitialized(_this)));
_this.focusManager = (0, _focusManager.default)(_assertThisInitialized(_assertThisInitialized(_this)), {
willHandle: _this.handleFocusWillChange
});
var _this$props = _this.props,
view = _this$props.view,
views = _this$props.views;
_this.state = {
selectedIndex: 0,
view: view || views[0]
};
return _this;
}
Calendar.getDerivedStateFromProps = function getDerivedStateFromProps(_ref, prevState) {
var messages = _ref.messages,
view = _ref.view,
views = _ref.views,
value = _ref.value,
currentDate = _ref.currentDate;
view = view || views[0];
var slideDirection = prevState.slideDirection,
lastView = prevState.view,
lastDate = prevState.currentDate;
if (lastView !== view) {
slideDirection = views.indexOf(lastView) > views.indexOf(view) ? 'top' : 'bottom';
} else if (lastDate !== currentDate) {
slideDirection = _dates.default.gt(currentDate, lastDate) ? 'left' : 'right';
}
return {
view: view,
slideDirection: slideDirection,
messages: (0, messages_1.getMessages)(messages),
currentDate: currentDate || value || new Date()
};
};
var _proto = Calendar.prototype;
_proto.componentDidUpdate = function componentDidUpdate(prevProps) {
var _this$props2 = this.props,
value = _this$props2.value,
min = _this$props2.min,
max = _this$props2.max;
var view = this.state.view;
value = inRangeValue(value, min, max);
if (!_dates.default.eq(value, dateOrNull(prevProps.value), VIEW_UNIT[view])) this.maybeSetCurrentDate(value);
};
_proto.render = function render() {
var _this$props3 = this.props,
className = _this$props3.className,
value = _this$props3.value,
footerFormat = _this$props3.footerFormat,
disabled = _this$props3.disabled,
readOnly = _this$props3.readOnly,
footer = _this$props3.footer,
views = _this$props3.views,
min = _this$props3.min,
max = _this$props3.max,
culture = _this$props3.culture,
tabIndex = _this$props3.tabIndex;
var _this$state = this.state,
currentDate = _this$state.currentDate,
view = _this$state.view,
slideDirection = _this$state.slideDirection,
focused = _this$state.focused,
messages = _this$state.messages;
var View = VIEW[view],
todaysDate = new Date(),
todayNotInRange = !_dates.default.inRange(todaysDate, min, max, view);
var key = view + '_' + _dates.default[view](currentDate);
var elementProps = Props$$1.pickElementProps(this),
viewProps = Props$$1.pick(this.props, View);
var isDisabled = disabled || readOnly;
return _react.default.createElement(_Widget.default, _extends({}, elementProps, {
role: "group",
focused: focused,
disabled: disabled,
readOnly: readOnly,
tabIndex: tabIndex || 0,
onKeyDown: this.handleKeyDown,
onBlur: this.focusManager.handleBlur,
onFocus: this.focusManager.handleFocus,
className: (0, _classnames.default)(className, 'rw-calendar rw-widget-container'),
"aria-activedescendant": this.activeId
}), _react.default.createElement(_Header.default, {
isRtl: this.isRtl(),
label: this.getHeaderLabel(),
labelId: this.labelId,
messages: messages,
upDisabled: isDisabled || view === last(views),
prevDisabled: isDisabled || !_dates.default.inRange(this.nextDate('LEFT'), min, max, view),
nextDisabled: isDisabled || !_dates.default.inRange(this.nextDate('RIGHT'), min, max, view),
onViewChange: this.handleViewChange,
onMoveLeft: this.handleMoveBack,
onMoveRight: this.handleMoveForward
}), _react.default.createElement(Calendar.Transition, {
direction: slideDirection
}, _react.default.createElement(View, _extends({}, viewProps, {
key: key,
id: this.viewId,
activeId: this.activeId,
value: value,
today: todaysDate,
disabled: disabled,
focused: currentDate,
onChange: this.handleChange,
onKeyDown: this.handleKeyDown,
"aria-labelledby": this.labelId
}))), footer && _react.default.createElement(_Footer.default, {
value: todaysDate,
format: footerFormat,
culture: culture,
disabled: disabled || todayNotInRange,
readOnly: readOnly,
onClick: this.handleFooterClick
}));
};
_proto.navigate = function navigate(direction, date) {
var _this$props4 = this.props,
views = _this$props4.views,
min = _this$props4.min,
max = _this$props4.max,
onNavigate = _this$props4.onNavigate,
onViewChange = _this$props4.onViewChange;
var _this$state2 = this.state,
view = _this$state2.view,
currentDate = _this$state2.currentDate;
var slideDir = direction === 'LEFT' || direction === 'UP' ? 'right' : 'left';
if (direction === 'UP') view = views[views.indexOf(view) + 1] || view;
if (direction === 'DOWN') view = views[views.indexOf(view) - 1] || view;
if (!date) date = ['LEFT', 'RIGHT'].indexOf(direction) !== -1 ? this.nextDate(direction) : currentDate;
if (_dates.default.inRange(date, min, max, view)) {
(0, widgetHelpers.notify)(onNavigate, [date, slideDir, view]);
this.focus(true);
this.maybeSetCurrentDate(date);
(0, widgetHelpers.notify)(onViewChange, [view]);
}
};
_proto.focus = function focus() {
if (+this.props.tabIndex > -1) (0, _reactDom.findDOMNode)(this).focus();
};
_proto.maybeSetCurrentDate = function maybeSetCurrentDate(date) {
var _this$props5 = this.props,
min = _this$props5.min,
max = _this$props5.max;
var _this$state3 = this.state,
view = _this$state3.view,
currentDate = _this$state3.currentDate;
var inRangeDate = inRangeValue(date ? new Date(date) : currentDate, min, max);
if (date === currentDate || _dates.default.eq(inRangeDate, dateOrNull(currentDate), VIEW_UNIT[view])) return;
(0, widgetHelpers.notify)(this.props.onCurrentDateChange, inRangeDate);
};
_proto.nextDate = function nextDate(direction) {
var method = direction === 'LEFT' ? 'subtract' : 'add';
var _this$state4 = this.state,
currentDate = _this$state4.currentDate,
view = _this$state4.view;
var unit = view === 'month' ? view : 'year';
var multi = MULTIPLIER[view] || 1;
return _dates.default[method](currentDate, 1 * multi, unit);
};
_proto.getHeaderLabel = function getHeaderLabel() {
var _this$props6 = this.props,
culture = _this$props6.culture,
decadeFormat = _this$props6.decadeFormat,
yearFormat = _this$props6.yearFormat,
headerFormat = _this$props6.headerFormat,
centuryFormat = _this$props6.centuryFormat;
var _this$state5 = this.state,
currentDate = _this$state5.currentDate,
view = _this$state5.view;
switch (view) {
case 'month':
headerFormat = localizers.date.getFormat('header', headerFormat);
return localizers.date.format(currentDate, headerFormat, culture);
case 'year':
yearFormat = localizers.date.getFormat('year', yearFormat);
return localizers.date.format(currentDate, yearFormat, culture);
case 'decade':
decadeFormat = localizers.date.getFormat('decade', decadeFormat);
return localizers.date.format(_dates.default.startOf(currentDate, 'decade'), decadeFormat, culture);
case 'century':
centuryFormat = localizers.date.getFormat('century', centuryFormat);
return localizers.date.format(_dates.default.startOf(currentDate, 'century'), centuryFormat, culture);
}
};
_proto.isRtl = function isRtl() {
return !!(this.props.isRtl || this.context && this.context.isRtl);
};
_proto.isValidView = function isValidView(next, views) {
if (views === void 0) {
views = this.props.views;
}
return views.indexOf(next) !== -1;
};
return Calendar;
}(_react.default.Component), _class3.displayName = 'Calendar', _class3.propTypes = propTypes$$1, _class3.defaultProps = {
value: null,
min: new Date(1900, 0, 1),
max: new Date(2099, 11, 31),
views: VIEW_OPTIONS,
tabIndex: '0',
footer: true
}, _class3.contextTypes = {
isRtl: _propTypes.default.bool
}, _class3.Transition = _SlideTransitionGroup.default, _temp), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, "handleViewChange", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this2 = this;
return function () {
_this2.navigate('UP');
};
}
}), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, "handleMoveBack", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this3 = this;
return function () {
_this3.navigate('LEFT');
};
}
}), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, "handleMoveForward", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this4 = this;
return function () {
_this4.navigate('RIGHT');
};
}
}), _descriptor4 = _applyDecoratedDescriptor(_class2.prototype, "handleChange", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this5 = this;
return function (date) {
var _this5$props = _this5.props,
views = _this5$props.views,
onChange = _this5$props.onChange;
var view = _this5.state.view;
if (views[0] === view) {
_this5.maybeSetCurrentDate(date);
(0, widgetHelpers.notify)(onChange, date);
_this5.focus();
return;
}
_this5.navigate('DOWN', date);
};
}
}), _descriptor5 = _applyDecoratedDescriptor(_class2.prototype, "handleFooterClick", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this6 = this;
return function (date) {
var _this6$props = _this6.props,
views = _this6$props.views,
min = _this6$props.min,
max = _this6$props.max,
onViewChange = _this6$props.onViewChange;
var firstView = views[0];
(0, widgetHelpers.notify)(_this6.props.onChange, date);
if (_dates.default.inRange(date, min, max, firstView)) {
_this6.focus();
_this6.maybeSetCurrentDate(date);
(0, widgetHelpers.notify)(onViewChange, [firstView]);
}
};
}
}), _descriptor6 = _applyDecoratedDescriptor(_class2.prototype, "handleKeyDown", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this7 = this;
return function (e) {
var _this7$state = _this7.state,
currentDate = _this7$state.currentDate,
view = _this7$state.view;
var ctrl = e.ctrlKey || e.metaKey;
var key = e.key;
var direction = ARROWS_TO_DIRECTION[key];
var unit = VIEW_UNIT[view];
if (key === 'Enter') {
e.preventDefault();
return _this7.handleChange(currentDate);
}
if (direction) {
if (ctrl) {
e.preventDefault();
_this7.navigate(direction);
} else {
if (_this7.isRtl() && OPPOSITE_DIRECTION[direction]) direction = OPPOSITE_DIRECTION[direction];
var nextDate = Calendar.move(currentDate, _this7.props.min, _this7.props.max, view, direction);
if (!_dates.default.eq(currentDate, nextDate, unit)) {
e.preventDefault();
if (_dates.default.gt(nextDate, currentDate, view)) _this7.navigate('RIGHT', nextDate);else if (_dates.default.lt(nextDate, currentDate, view)) _this7.navigate('LEFT', nextDate);else _this7.maybeSetCurrentDate(nextDate);
}
}
}
(0, widgetHelpers.notify)(_this7.props.onKeyDown, [e]);
};
}
})), _class2)) || _class;
function dateOrNull(dt) {
if (dt && !isNaN(dt.getTime())) return dt;
return null;
}
var _default = (0, _uncontrollable.default)(Calendar, {
value: 'onChange',
currentDate: 'onCurrentDateChange',
view: 'onViewChange'
}, ['focus']);
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(Calendar_1);
var deprecated_1 = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = deprecated;
var _warning2 = _interopRequireDefault(warning_1$1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var warned = {};
function deprecated(validator, reason) {
return function validate(props, propName, componentName, location, propFullName) {
var componentNameSafe = componentName || '<<anonymous>>';
var propFullNameSafe = propFullName || propName;
if (props[propName] != null) {
var messageKey = componentName + '.' + propName;
(0, _warning2.default)(warned[messageKey], 'The ' + location + ' `' + propFullNameSafe + '` of ' + ('`' + componentNameSafe + '` is deprecated. ' + reason + '.'));
warned[messageKey] = true;
}
for (var _len = arguments.length, args = Array(_len > 5 ? _len - 5 : 0), _key = 5; _key < _len; _key++) {
args[_key - 5] = arguments[_key];
}
return validator.apply(undefined, [props, propName, componentName, location, propFullName].concat(args));
};
}
/* eslint-disable no-underscore-dangle */
function _resetWarned() {
warned = {};
}
deprecated._resetWarned = _resetWarned;
/* eslint-enable no-underscore-dangle */
module.exports = exports['default'];
});
unwrapExports(deprecated_1);
var DateTimePickerInput_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _propTypes = _interopRequireDefault(propTypes);
var _react = _interopRequireDefault(React__default);
var _Input = _interopRequireDefault(Input_1);
var CustomPropTypes = _interopRequireWildcard(PropTypes$2);
var Props$$1 = _interopRequireWildcard(Props);
var _class, _class2, _temp;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var DateTimePickerInput = (0, reactLifecyclesCompat_es.polyfill)(_class = (_temp = _class2 =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(DateTimePickerInput, _React$Component);
function DateTimePickerInput() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_this.state = {};
_this.handleBlur = function (event) {
var _this$props = _this.props,
format = _this$props.format,
culture = _this$props.culture,
parse = _this$props.parse,
onChange = _this$props.onChange,
onBlur = _this$props.onBlur;
onBlur && onBlur(event);
if (_this._needsFlush) {
var date = parse(event.target.value);
var dateIsInvalid = event.target.value != '' && date == null;
if (dateIsInvalid) {
_this.setState({
textValue: ''
});
}
_this._needsFlush = false;
onChange(date, formatDate(date, format, culture));
}
};
_this.handleChange = function (_ref) {
var value = _ref.target.value;
_this._needsFlush = true;
_this.setState({
textValue: value
});
};
return _this;
}
DateTimePickerInput.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, prevState) {
var value = nextProps.value,
editing = nextProps.editing,
editFormat = nextProps.editFormat,
format = nextProps.format,
culture = nextProps.culture;
var textValue = formatDate(value, editing && editFormat ? editFormat : format, culture);
if (prevState.lastValueFromProps !== textValue) return {
textValue: textValue,
lastValueFromProps: textValue
};
return null;
};
var _proto = DateTimePickerInput.prototype;
_proto.focus = function focus() {
(0, _reactDom.findDOMNode)(this).focus();
};
_proto.render = function render() {
var _this$props2 = this.props,
disabled = _this$props2.disabled,
readOnly = _this$props2.readOnly;
var textValue = this.state.textValue;
var props = Props$$1.omitOwn(this);
return _react.default.createElement(_Input.default, _extends({}, props, {
type: "text",
className: "rw-widget-input",
value: textValue,
disabled: disabled,
readOnly: readOnly,
onChange: this.handleChange,
onBlur: this.handleBlur
}));
};
return DateTimePickerInput;
}(_react.default.Component), _class2.propTypes = {
format: CustomPropTypes.dateFormat.isRequired,
editing: _propTypes.default.bool,
editFormat: CustomPropTypes.dateFormat,
parse: _propTypes.default.func.isRequired,
value: _propTypes.default.instanceOf(Date),
onChange: _propTypes.default.func.isRequired,
onBlur: _propTypes.default.func,
culture: _propTypes.default.string,
disabled: CustomPropTypes.disabled,
readOnly: CustomPropTypes.disabled
}, _temp)) || _class;
var _default = DateTimePickerInput;
exports.default = _default;
function isValid(d) {
return !isNaN(d.getTime());
}
function formatDate(date, format, culture) {
var val = '';
if (date instanceof Date && isValid(date)) val = localizers.date.format(date, format, culture);
return val;
}
module.exports = exports["default"];
});
unwrapExports(DateTimePickerInput_1);
var TimeList_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _react = _interopRequireDefault(React__default);
var _propTypes = _interopRequireDefault(propTypes);
var _List = _interopRequireDefault(List_1);
var _dates = _interopRequireDefault(dates_1);
var _reduceToListState = _interopRequireDefault(reduceToListState_1);
var CustomPropTypes = _interopRequireWildcard(PropTypes$2);
var _class, _class2, _temp;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
function _objectWithoutProperties(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]; } if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
var format = function format(props) {
return localizers.date.getFormat('time', props.format);
};
var accessors = {
text: function text(item) {
return item.label;
},
value: function value(item) {
return item.date;
}
};
var find = function find(arr, fn) {
for (var i = 0; i < arr.length; i++) {
if (fn(arr[i])) return arr[i];
}
return null;
};
function getBounds(_ref) {
var min = _ref.min,
max = _ref.max,
currentDate = _ref.currentDate,
value = _ref.value,
preserveDate = _ref.preserveDate;
//compare just the time regradless of whether they fall on the same day
if (!preserveDate) {
var _start = _dates.default.startOf(_dates.default.merge(new Date(), min, currentDate), 'minutes');
var _end = _dates.default.startOf(_dates.default.merge(new Date(), max, currentDate), 'minutes');
if (_dates.default.lte(_end, _start) && _dates.default.gt(max, min, 'day')) _end = _dates.default.tomorrow();
return {
min: _start,
max: _end
};
}
var start = _dates.default.today();
var end = _dates.default.tomorrow();
value = value || currentDate || start; //date parts are equal
return {
min: _dates.default.eq(value, min, 'day') ? _dates.default.merge(start, min, currentDate) : start,
max: _dates.default.eq(value, max, 'day') ? _dates.default.merge(start, max, currentDate) : end
};
}
function getDates(_ref2) {
var step = _ref2.step,
culture = _ref2.culture,
props = _objectWithoutProperties(_ref2, ["step", "culture"]);
var times = [];
var _getBounds = getBounds(props),
min = _getBounds.min,
max = _getBounds.max;
var startDay = _dates.default.date(min);
while (_dates.default.date(min) === startDay && _dates.default.lte(min, max)) {
times.push({
date: min,
label: localizers.date.format(min, format(props), culture)
});
min = _dates.default.add(min, step || 30, 'minutes');
}
return times;
}
var TimeList = (0, reactLifecyclesCompat_es.polyfill)(_class = (_temp = _class2 =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(TimeList, _React$Component);
function TimeList() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_this.state = {};
_this.handleKeyDown = function (e) {
var key = e.key;
var _this$state = _this.state,
focusedItem = _this$state.focusedItem,
list = _this$state.list;
if (key === 'End') {
e.preventDefault();
_this.setState({
focusedItem: list.last()
});
} else if (key === 'Home') {
e.preventDefault();
_this.setState({
focusedItem: list.first()
});
} else if (key === 'Enter') {
_this.props.onSelect(focusedItem);
} else if (key === 'ArrowDown') {
e.preventDefault();
_this.setState({
focusedItem: list.next(focusedItem)
});
} else if (key === 'ArrowUp') {
e.preventDefault();
_this.setState({
focusedItem: list.prev(focusedItem)
});
}
};
return _this;
}
TimeList.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, prevState) {
var value = nextProps.value,
currentDate = nextProps.currentDate,
step = nextProps.step;
var data = getDates(nextProps);
var currentValue = value || currentDate;
var valueChanged = !prevState.lastValue || !_dates.default.eq(currentValue, prevState.lastValue, 'minutes');
var list = (0, _reduceToListState.default)(data, prevState.list, {
nextProps: nextProps
});
var selectedItem = find(data, function (t) {
return _dates.default.eq(t.date, currentValue, 'minutes');
});
var closestDate = find(data, function (t) {
return Math.abs(_dates.default.diff(t.date, currentValue, 'minutes')) < step;
});
return {
data: data,
list: list,
lastValue: currentValue,
selectedItem: list.nextEnabled(selectedItem),
focusedItem: valueChanged || !prevState.focusedItem ? list.nextEnabled(selectedItem || closestDate || data[0]) : find(data, function (t) {
return _dates.default.eq(t.date, prevState.focusedItem.date, 'minutes');
})
};
};
var _proto = TimeList.prototype;
_proto.componentWillUnmount = function componentWillUnmount() {
this.unmounted = true;
};
_proto.render = function render() {
var _this$props = this.props,
listProps = _this$props.listProps,
props = _objectWithoutProperties(_this$props, ["listProps"]);
var _this$state2 = this.state,
data = _this$state2.data,
list = _this$state2.list,
focusedItem = _this$state2.focusedItem,
selectedItem = _this$state2.selectedItem;
delete props.currentDate;
delete props.min;
delete props.max;
delete props.step;
delete props.format;
delete props.culture;
delete props.preserveDate;
delete props.value;
return _react.default.createElement(_List.default, _extends({}, props, listProps, {
data: data,
dataState: list.dataState,
isDisabled: list.isDisabled,
textAccessor: accessors.text,
valueAccessor: accessors.value,
selectedItem: selectedItem,
focusedItem: focusedItem
}));
};
return TimeList;
}(_react.default.Component), _class2.defaultProps = {
step: 30,
currentDate: new Date(),
min: new Date(1900, 0, 1),
max: new Date(2099, 11, 31),
preserveDate: true
}, _class2.propTypes = {
value: _propTypes.default.instanceOf(Date),
step: _propTypes.default.number,
min: _propTypes.default.instanceOf(Date),
max: _propTypes.default.instanceOf(Date),
currentDate: _propTypes.default.instanceOf(Date),
itemComponent: CustomPropTypes.elementType,
listProps: _propTypes.default.object,
format: CustomPropTypes.dateFormat,
onSelect: _propTypes.default.func,
preserveDate: _propTypes.default.bool,
culture: _propTypes.default.string
}, _temp)) || _class;
var _default = TimeList;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(TimeList_1);
var DateTimePicker_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _invariant = _interopRequireDefault(invariant_1);
var _propTypes = _interopRequireDefault(propTypes);
var _react = _interopRequireDefault(React__default);
var _activeElement = _interopRequireDefault(activeElement_1);
var _classnames = _interopRequireDefault(classnames);
var _deprecated = _interopRequireDefault(deprecated_1);
var _uncontrollable = _interopRequireDefault(uncontrollable_1);
var _Widget = _interopRequireDefault(Widget_1);
var _WidgetPicker = _interopRequireDefault(WidgetPicker_1);
var _Popup = _interopRequireDefault(Popup_1);
var _Button = _interopRequireDefault(Button_1);
var _Calendar = _interopRequireDefault(Calendar_1);
var _DateTimePickerInput = _interopRequireDefault(DateTimePickerInput_1);
var _Select = _interopRequireDefault(Select_1);
var _TimeList = _interopRequireDefault(TimeList_1);
var Props$$1 = _interopRequireWildcard(Props);
var CustomPropTypes = _interopRequireWildcard(PropTypes$2);
var _focusManager = _interopRequireDefault(focusManager$2);
var _scrollManager = _interopRequireDefault(scrollManager);
var _dates = _interopRequireDefault(dates_1);
var _class, _class2, _descriptor, _descriptor2, _descriptor3, _descriptor4, _descriptor5, _descriptor6, _descriptor7, _class3, _temp;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _initializerDefineProperty(target, property, descriptor, context) { if (!descriptor) return; Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 }); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { var desc = {}; Object['ke' + 'ys'](descriptor).forEach(function (key) { desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer) { desc.writable = true; } desc = decorators.slice().reverse().reduce(function (desc, decorator) { return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0) { desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0) { Object['define' + 'Property'](target, property, desc); desc = null; } return desc; }
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); }
var NEXT_VIEW = {
date: 'time',
time: 'date'
};
var isBothOrNeither = function isBothOrNeither(a, b) {
return a && b || !a && !b;
};
var propTypes$$1 = _extends({}, _Calendar.default.ControlledComponent.propTypes, {
/**
* @example ['valuePicker', [ ['new Date()', null] ]]
*/
value: _propTypes.default.instanceOf(Date),
/**
* @example ['onChangePicker', [ ['new Date()', null] ]]
*/
onChange: _propTypes.default.func,
/**
* @type {(false | 'time' | 'date')}
* @example ['openDateTime']
*/
open: _propTypes.default.oneOf([false, 'time', 'date']),
onToggle: _propTypes.default.func,
/**
* Default current date at which the calendar opens. If none is provided, opens at today's date or the `value` date (if any).
*/
currentDate: _propTypes.default.instanceOf(Date),
/**
* Change event Handler that is called when the currentDate is changed. The handler is called with the currentDate object.
*/
onCurrentDateChange: _propTypes.default.func,
onSelect: _propTypes.default.func,
/**
* The minimum Date that can be selected. Min only limits selection, it doesn't constrain the date values that
* can be typed or pasted into the widget. If you need this behavior you can constrain values via
* the `onChange` handler.
*
* @example ['prop', ['min', 'new Date()']]
*/
min: _propTypes.default.instanceOf(Date),
/**
* The maximum Date that can be selected. Max only limits selection, it doesn't constrain the date values that
* can be typed or pasted into the widget. If you need this behavior you can constrain values via
* the `onChange` handler.
*
* @example ['prop', ['max', 'new Date()']]
*/
max: _propTypes.default.instanceOf(Date),
/**
* The amount of minutes between each entry in the time list.
*
* @example ['prop', { step: 90 }]
*/
step: _propTypes.default.number,
culture: _propTypes.default.string,
/**
* A formatter used to display the date value. For more information about formats
* visit the [Localization page](/localization)
*
* @example ['dateFormat', ['format', "{ raw: 'MMM dd, yyyy' }", null, { defaultValue: 'new Date()', time: 'false' }]]
*/
format: CustomPropTypes.dateFormat,
/**
* A formatter used by the time dropdown to render times. For more information about formats visit
* the [Localization page](/localization).
*
* @example ['dateFormat', ['timeFormat', "{ time: 'medium' }", null, { date: 'false', open: '"time"' }]]
*/
timeFormat: CustomPropTypes.dateFormat,
/**
* A formatter to be used while the date input has focus. Useful for showing a simpler format for inputing.
* For more information about formats visit the [Localization page](/localization)
*
* @example ['dateFormat', ['editFormat', "{ date: 'short' }", null, { defaultValue: 'new Date()', format: "{ raw: 'MMM dd, yyyy' }", time: 'false' }]]
*/
editFormat: CustomPropTypes.dateFormat,
/**
* Enable the calendar component of the picker.
*/
date: _propTypes.default.bool,
/**
* Enable the time list component of the picker.
*/
time: _propTypes.default.bool,
/** @ignore */
calendar: (0, _deprecated.default)(_propTypes.default.bool, 'Use `date` instead'),
/**
* A customize the rendering of times but providing a custom component.
*/
timeComponent: CustomPropTypes.elementType,
/** Specify the element used to render the calendar dropdown icon. */
dateIcon: _propTypes.default.node,
/** Specify the element used to render the time list dropdown icon. */
timeIcon: _propTypes.default.node,
dropUp: _propTypes.default.bool,
popupTransition: CustomPropTypes.elementType,
placeholder: _propTypes.default.string,
name: _propTypes.default.string,
autoFocus: _propTypes.default.bool,
/**
* @example ['disabled', ['new Date()']]
*/
disabled: CustomPropTypes.disabled,
/**
* @example ['readOnly', ['new Date()']]
*/
readOnly: CustomPropTypes.disabled,
/**
* Determines how the widget parses the typed date string into a Date object. You can provide an array of formats to try,
* or provide a function that returns a date to handle parsing yourself. When `parse` is unspecified and
* the `format` prop is a `string` parse will automatically use that format as its default.
*/
parse: _propTypes.default.oneOfType([_propTypes.default.arrayOf(_propTypes.default.string), _propTypes.default.string, _propTypes.default.func]),
/** @ignore */
tabIndex: _propTypes.default.any,
/** @ignore */
'aria-labelledby': _propTypes.default.string,
/** @ignore */
'aria-describedby': _propTypes.default.string,
onKeyDown: _propTypes.default.func,
onKeyPress: _propTypes.default.func,
onBlur: _propTypes.default.func,
onFocus: _propTypes.default.func,
/** Adds a css class to the input container element. */
containerClassName: _propTypes.default.string,
inputProps: _propTypes.default.object,
isRtl: _propTypes.default.bool,
messages: _propTypes.default.shape({
dateButton: _propTypes.default.string,
timeButton: _propTypes.default.string
})
/**
* ---
* subtitle: DatePicker, TimePicker
* localized: true
* shortcuts:
* - { key: alt + down arrow, label: open calendar or time }
* - { key: alt + up arrow, label: close calendar or time }
* - { key: down arrow, label: move focus to next item }
* - { key: up arrow, label: move focus to previous item }
* - { key: home, label: move focus to first item }
* - { key: end, label: move focus to last item }
* - { key: enter, label: select focused item }
* - { key: any key, label: search list for item starting with key }
* ---
*
* @public
* @extends Calendar
*/
});
var DateTimePicker = (0, reactLifecyclesCompat_es.polyfill)(_class = (_class2 = (_temp = _class3 =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(DateTimePicker, _React$Component);
function DateTimePicker() {
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;
_initializerDefineProperty(_this, "handleChange", _descriptor, _assertThisInitialized(_assertThisInitialized(_this)));
_initializerDefineProperty(_this, "handleKeyDown", _descriptor2, _assertThisInitialized(_assertThisInitialized(_this)));
_initializerDefineProperty(_this, "handleKeyPress", _descriptor3, _assertThisInitialized(_assertThisInitialized(_this)));
_initializerDefineProperty(_this, "handleDateSelect", _descriptor4, _assertThisInitialized(_assertThisInitialized(_this)));
_initializerDefineProperty(_this, "handleTimeSelect", _descriptor5, _assertThisInitialized(_assertThisInitialized(_this)));
_initializerDefineProperty(_this, "handleCalendarClick", _descriptor6, _assertThisInitialized(_assertThisInitialized(_this)));
_initializerDefineProperty(_this, "handleTimeClick", _descriptor7, _assertThisInitialized(_assertThisInitialized(_this)));
_this.attachCalRef = function (ref) {
return _this.calRef = ref;
};
_this.attachTimeRef = function (ref) {
return _this.timeRef = ref;
};
_this.attachInputRef = function (ref) {
return _this.inputRef = ref;
};
_this.parse = function (string) {
var _this$props = _this.props,
parse = _this$props.parse,
culture = _this$props.culture,
editFormat = _this$props.editFormat;
var format = getFormat(_this.props, true);
!(parse || format || editFormat) ? invariant(false) : void 0;
var date;
var formats = [format, editFormat];
if (typeof parse == 'function') {
date = parse(string, culture);
if (date) return date;
} else {
// parse is a string format or array of string formats
formats = formats.concat(parse).filter(Boolean);
}
for (var i = 0; i < formats.length; i++) {
date = localizers.date.parse(string, formats[i], culture);
if (date) return date;
}
return null;
};
_this.inputId = (0, widgetHelpers.instanceId)(_assertThisInitialized(_assertThisInitialized(_this)), '_input');
_this.dateId = (0, widgetHelpers.instanceId)(_assertThisInitialized(_assertThisInitialized(_this)), '_date');
_this.listId = (0, widgetHelpers.instanceId)(_assertThisInitialized(_assertThisInitialized(_this)), '_listbox');
_this.activeCalendarId = (0, widgetHelpers.instanceId)(_assertThisInitialized(_assertThisInitialized(_this)), '_calendar_active_cell');
_this.activeOptionId = (0, widgetHelpers.instanceId)(_assertThisInitialized(_assertThisInitialized(_this)), '_listbox_active_option');
_this.handleScroll = (0, _scrollManager.default)(_assertThisInitialized(_assertThisInitialized(_this)));
_this.focusManager = (0, _focusManager.default)(_assertThisInitialized(_assertThisInitialized(_this)), {
didHandle: function didHandle(focused) {
if (!focused) _this.close();
}
});
_this.state = {
focused: false,
messages: (0, messages_1.getMessages)(_this.props.messages)
};
return _this;
}
DateTimePicker.getDerivedStateFromProps = function getDerivedStateFromProps(_ref) {
var messages = _ref.messages;
return {
messages: (0, messages_1.getMessages)(messages)
};
};
var _proto = DateTimePicker.prototype;
_proto.renderInput = function renderInput(owns) {
var _this$props2 = this.props,
open = _this$props2.open,
value = _this$props2.value,
editFormat = _this$props2.editFormat,
culture = _this$props2.culture,
placeholder = _this$props2.placeholder,
disabled = _this$props2.disabled,
readOnly = _this$props2.readOnly,
name = _this$props2.name,
tabIndex = _this$props2.tabIndex,
autoFocus = _this$props2.autoFocus,
inputProps = _this$props2.inputProps,
ariaLabelledby = _this$props2['aria-labelledby'],
ariaDescribedby = _this$props2['aria-describedby'];
var focused = this.state.focused;
var inputReadOnly = inputProps ? inputProps.readOnly : null;
var activeId = null;
if (open === 'time') {
activeId = this.activeOptionId;
} else if (open === 'date') {
activeId = this.activeCalendarId;
}
return _react.default.createElement(_DateTimePickerInput.default, _extends({}, inputProps, {
id: this.inputId,
ref: this.attachInputRef,
role: "combobox",
name: name,
value: value,
tabIndex: tabIndex,
autoFocus: autoFocus,
placeholder: placeholder,
disabled: disabled,
readOnly: inputReadOnly != null ? inputReadOnly : readOnly,
format: getFormat(this.props),
editFormat: editFormat,
editing: focused,
culture: culture,
parse: this.parse,
onChange: this.handleChange,
"aria-haspopup": true,
"aria-activedescendant": activeId,
"aria-labelledby": ariaLabelledby,
"aria-describedby": ariaDescribedby,
"aria-expanded": !!open,
"aria-owns": owns
}));
};
_proto.renderButtons = function renderButtons() {
var _this$props3 = this.props,
date = _this$props3.date,
dateIcon = _this$props3.dateIcon,
time = _this$props3.time,
timeIcon = _this$props3.timeIcon,
disabled = _this$props3.disabled,
readOnly = _this$props3.readOnly;
if (!date && !time) {
return null;
}
var messages = this.state.messages;
return _react.default.createElement(_Select.default, {
bordered: true
}, date && _react.default.createElement(_Button.default, {
icon: dateIcon,
label: messages.dateButton(),
disabled: disabled || readOnly,
onClick: this.handleCalendarClick
}), time && _react.default.createElement(_Button.default, {
icon: timeIcon,
label: messages.timeButton(),
disabled: disabled || readOnly,
onClick: this.handleTimeClick
}));
};
_proto.renderCalendar = function renderCalendar() {
var _this2 = this;
var activeCalendarId = this.activeCalendarId,
inputId = this.inputId,
dateId = this.dateId;
var _this$props4 = this.props,
open = _this$props4.open,
value = _this$props4.value,
popupTransition = _this$props4.popupTransition,
dropUp = _this$props4.dropUp,
onCurrentDateChange = _this$props4.onCurrentDateChange,
currentDate = _this$props4.currentDate;
var calendarProps = Props$$1.pick(this.props, _Calendar.default.ControlledComponent); // manually include the last controlled default Props
calendarProps.defaultView = this.props.defaultView;
return _react.default.createElement(_Popup.default, {
dropUp: dropUp,
open: open === 'date',
className: "rw-calendar-popup",
transition: popupTransition
}, _react.default.createElement(_Calendar.default, _extends({}, calendarProps, {
id: dateId,
activeId: activeCalendarId,
tabIndex: "-1",
value: value,
autoFocus: false,
onChange: this.handleDateSelect // #75: need to aggressively reclaim focus from the calendar otherwise
// disabled header/footer buttons will drop focus completely from the widget
,
onNavigate: function onNavigate() {
return _this2.focus();
},
currentDate: currentDate,
onCurrentDateChange: onCurrentDateChange,
"aria-hidden": !open,
"aria-live": "polite",
"aria-labelledby": inputId,
ref: this.attachCalRef
})));
};
_proto.renderTimeList = function renderTimeList() {
var _this3 = this;
var activeOptionId = this.activeOptionId,
inputId = this.inputId,
listId = this.listId;
var _this$props5 = this.props,
open = _this$props5.open,
value = _this$props5.value,
min = _this$props5.min,
max = _this$props5.max,
step = _this$props5.step,
currentDate = _this$props5.currentDate,
dropUp = _this$props5.dropUp,
date = _this$props5.date,
culture = _this$props5.culture,
timeFormat = _this$props5.timeFormat,
timeComponent = _this$props5.timeComponent,
timeListProps = _this$props5.timeListProps,
popupTransition = _this$props5.popupTransition;
return _react.default.createElement(_Popup.default, {
dropUp: dropUp,
transition: popupTransition,
open: open === 'time',
onEntering: function onEntering() {
return _this3.timeRef.forceUpdate();
}
}, _react.default.createElement("div", null, _react.default.createElement(_TimeList.default, {
id: listId,
min: min,
max: max,
step: step,
listProps: timeListProps,
currentDate: currentDate,
activeId: activeOptionId,
format: timeFormat,
culture: culture,
value: dateOrNull(value),
onMove: this.handleScroll,
onSelect: this.handleTimeSelect,
preserveDate: !!date,
itemComponent: timeComponent,
"aria-labelledby": inputId,
"aria-live": open && 'polite',
"aria-hidden": !open,
messages: this.state.messages,
ref: this.attachTimeRef
})));
};
_proto.render = function render() {
var _this$props6 = this.props,
className = _this$props6.className,
date = _this$props6.date,
time = _this$props6.time,
open = _this$props6.open,
disabled = _this$props6.disabled,
readOnly = _this$props6.readOnly,
dropUp = _this$props6.dropUp,
containerClassName = _this$props6.containerClassName;
var focused = this.state.focused;
var elementProps = Props$$1.pickElementProps(this, _Calendar.default.ControlledComponent);
var shouldRenderList = (0, widgetHelpers.isFirstFocusedRender)(this);
var shouldRenderTimeList = !!(shouldRenderList && time);
var shouldRenderCalendar = !!(shouldRenderList && date);
var owns = '';
if (shouldRenderCalendar && open === 'date') owns += this.dateId;
if (shouldRenderTimeList && open === 'time') owns += ' ' + this.listId;
return _react.default.createElement(_Widget.default, _extends({}, elementProps, {
open: !!open,
dropUp: dropUp,
focused: focused,
disabled: disabled,
readOnly: readOnly,
onKeyDown: this.handleKeyDown,
onKeyPress: this.handleKeyPress,
onBlur: this.focusManager.handleBlur,
onFocus: this.focusManager.handleFocus,
className: (0, _classnames.default)(className, 'rw-datetime-picker')
}), _react.default.createElement(_WidgetPicker.default, {
className: containerClassName
}, this.renderInput(owns.trim()), this.renderButtons()), shouldRenderTimeList && this.renderTimeList(), shouldRenderCalendar && this.renderCalendar());
};
_proto.focus = function focus() {
if (this.inputRef && (0, _activeElement.default)() !== (0, _reactDom.findDOMNode)(this.inputRef)) this.inputRef.focus();
};
_proto.toggle = function toggle(view) {
var open = this.props.open;
if (!open || open !== view) this.open(view);else this.close();
};
_proto.open = function open(view) {
var _this$props7 = this.props,
open = _this$props7.open,
date = _this$props7.date,
time = _this$props7.time,
onToggle = _this$props7.onToggle;
if (!view) {
if (time) view = 'time';
if (date) view = 'date';
if (isBothOrNeither(date, time)) view = NEXT_VIEW[open] || 'date';
}
if (open !== view) (0, widgetHelpers.notify)(onToggle, view);
};
_proto.close = function close() {
if (this.props.open) (0, widgetHelpers.notify)(this.props.onToggle, false);
};
_proto.inRangeValue = function inRangeValue(value) {
if (value == null) return value;
return _dates.default.max(_dates.default.min(value, this.props.max), this.props.min);
};
return DateTimePicker;
}(_react.default.Component), _class3.displayName = 'DateTimePicker', _class3.propTypes = propTypes$$1, _class3.defaultProps = _extends({}, _Calendar.default.ControlledComponent.defaultProps, {
value: null,
min: new Date(1900, 0, 1),
max: new Date(2099, 11, 31),
date: true,
time: true,
open: false,
dateIcon: Icon_1.calendar,
timeIcon: Icon_1.clock
}), _temp), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, "handleChange", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this4 = this;
return function (date, str, constrain) {
var _this4$props = _this4.props,
onChange = _this4$props.onChange,
value = _this4$props.value;
if (constrain) date = _this4.inRangeValue(date);
if (onChange) {
if (date == null || value == null) {
if (date != value //eslint-disable-line eqeqeq
) onChange(date, str);
} else if (!_dates.default.eq(date, value)) {
onChange(date, str);
}
}
};
}
}), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, "handleKeyDown", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this5 = this;
return function (e) {
var _this5$props = _this5.props,
open = _this5$props.open,
onKeyDown = _this5$props.onKeyDown;
(0, widgetHelpers.notify)(onKeyDown, [e]);
if (e.defaultPrevented) return;
if (e.key === 'Escape' && open) _this5.close();else if (e.altKey) {
if (e.key === 'ArrowDown') {
e.preventDefault();
_this5.open();
} else if (e.key === 'ArrowUp') {
e.preventDefault();
_this5.close();
}
} else if (open) {
if (open === 'date') _this5.calRef.inner.handleKeyDown(e);
if (open === 'time') _this5.timeRef.handleKeyDown(e);
}
};
}
}), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, "handleKeyPress", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this6 = this;
return function (e) {
(0, widgetHelpers.notify)(_this6.props.onKeyPress, [e]);
if (e.defaultPrevented) return;
};
}
}), _descriptor4 = _applyDecoratedDescriptor(_class2.prototype, "handleDateSelect", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this7 = this;
return function (date) {
var format = getFormat(_this7.props),
dateTime = _dates.default.merge(date, _this7.props.value, _this7.props.currentDate),
dateStr = formatDate(date, format, _this7.props.culture);
_this7.close();
(0, widgetHelpers.notify)(_this7.props.onSelect, [dateTime, dateStr]);
_this7.handleChange(dateTime, dateStr, true);
_this7.focus();
};
}
}), _descriptor5 = _applyDecoratedDescriptor(_class2.prototype, "handleTimeSelect", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this8 = this;
return function (datum) {
var format = getFormat(_this8.props),
dateTime = _dates.default.merge(_this8.props.value, datum.date, _this8.props.currentDate),
dateStr = formatDate(datum.date, format, _this8.props.culture);
_this8.close();
(0, widgetHelpers.notify)(_this8.props.onSelect, [dateTime, dateStr]);
_this8.handleChange(dateTime, dateStr, true);
_this8.focus();
};
}
}), _descriptor6 = _applyDecoratedDescriptor(_class2.prototype, "handleCalendarClick", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this9 = this;
return function () {
_this9.focus();
_this9.toggle('date');
};
}
}), _descriptor7 = _applyDecoratedDescriptor(_class2.prototype, "handleTimeClick", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this10 = this;
return function () {
_this10.focus();
_this10.toggle('time');
};
}
})), _class2)) || _class;
var _default = (0, _uncontrollable.default)(DateTimePicker, {
open: 'onToggle',
value: 'onChange',
currentDate: 'onCurrentDateChange'
}, ['focus']);
exports.default = _default;
function getFormat(props) {
var isDate = props.date != null ? props.date : true;
var isTime = props.time != null ? props.time : true;
return props.format ? props.format : isDate && isTime || !isDate && !isTime ? localizers.date.getFormat('default') : localizers.date.getFormat(isDate ? 'date' : 'time');
}
function formatDate(date, format, culture) {
var val = '';
if (date instanceof Date && !isNaN(date.getTime())) val = localizers.date.format(date, format, culture);
return val;
}
function dateOrNull(dt) {
if (dt && !isNaN(dt.getTime())) return dt;
return null;
}
module.exports = exports["default"];
});
unwrapExports(DateTimePicker_1);
var DatePicker_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _react = _interopRequireDefault(React__default);
var _propTypes = _interopRequireDefault(propTypes);
var _DateTimePicker = _interopRequireDefault(DateTimePicker_1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var propTypes$$1 = {
open: _propTypes.default.bool,
defaultOpen: _propTypes.default.bool,
onToggle: _propTypes.default.func
};
var DatePicker =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(DatePicker, _React$Component);
function DatePicker(props, context) {
var _this;
_this = _React$Component.call(this, props, context) || this;
_this.handleToggle = function (open) {
_this.toggleState = !!open;
if (_this.props.onToggle) _this.props.onToggle(_this.toggleState);else _this.forceUpdate();
};
_this.toggleState = props.defaultOpen;
return _this;
}
var _proto = DatePicker.prototype;
_proto.render = function render() {
var open = this.props.open;
open = open === undefined ? this.toggleState : open;
return _react.default.createElement(_DateTimePicker.default, _extends({}, this.props, {
time: false,
open: open ? 'date' : open,
onToggle: this.handleToggle
}));
};
return DatePicker;
}(_react.default.Component);
DatePicker.propTypes = propTypes$$1;
var _default = DatePicker;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(DatePicker_1);
var TimePicker_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _react = _interopRequireDefault(React__default);
var _propTypes = _interopRequireDefault(propTypes);
var _DateTimePicker = _interopRequireDefault(DateTimePicker_1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var propTypes$$1 = {
open: _propTypes.default.bool,
defaultOpen: _propTypes.default.bool,
onToggle: _propTypes.default.func
};
var TimePicker =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(TimePicker, _React$Component);
function TimePicker(props, context) {
var _this;
_this = _React$Component.call(this, props, context) || this;
_this.handleToggle = function (open) {
_this.toggleState = !!open;
if (_this.props.onToggle) _this.props.onToggle(_this.toggleState);else _this.forceUpdate();
};
_this.toggleState = props.defaultOpen;
return _this;
}
var _proto = TimePicker.prototype;
_proto.render = function render() {
var open = this.props.open;
open = open === undefined ? this.toggleState : open;
return _react.default.createElement(_DateTimePicker.default, _extends({}, this.props, {
date: false,
open: open ? 'time' : open,
onToggle: this.handleToggle
}));
};
return TimePicker;
}(_react.default.Component);
TimePicker.propTypes = propTypes$$1;
var _default = TimePicker;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(TimePicker_1);
var NumberInput = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _inDOM = _interopRequireDefault(inDOM);
var _activeElement = _interopRequireDefault(activeElement_1);
var _propTypes = _interopRequireDefault(propTypes);
var _react = _interopRequireDefault(React__default);
var _Input = _interopRequireDefault(Input_1);
var Props$$1 = _interopRequireWildcard(Props);
var CustomPropTypes = _interopRequireWildcard(PropTypes$2);
var _class, _class2, _temp;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var getFormat = function getFormat(props) {
return localizers.number.getFormat('default', props.format);
};
var isSign = function isSign(val) {
return (val || '').trim() === '-';
};
function isPaddedZeros(str, culture) {
var localeChar = localizers.number.decimalChar(null, culture);
var _str$split = str.split(localeChar),
_ = _str$split[0],
decimals = _str$split[1];
return !!(decimals && decimals.match(/0+$/));
}
function isAtDelimiter(num, str, culture) {
var localeChar = localizers.number.decimalChar(null, culture),
lastIndex = str.length - 1,
char;
if (str.length < 1) return false;
char = str[lastIndex];
return !!(char === localeChar && str.indexOf(char) === lastIndex);
}
var NumberPickerInput = (0, reactLifecyclesCompat_es.polyfill)(_class = (_temp = _class2 =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(NumberPickerInput, _React$Component);
function NumberPickerInput() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_this.state = {};
_this.handleBlur = function (event) {
var str = _this.state.stringValue,
number = _this.parseNumber(str); // if number is below the min
// we need to flush low values and decimal stops, onBlur means i'm done inputing
if (_this.isIntermediateValue(number, str)) {
if (isNaN(number)) {
number = null;
}
_this.props.onChange(number, event);
}
};
_this.handleChange = function (event) {
var _this$props = _this.props,
value = _this$props.value,
onChange = _this$props.onChange;
var stringValue = event.target.value,
numberValue = _this.parseNumber(stringValue);
var isIntermediate = _this.isIntermediateValue(numberValue, stringValue);
if (stringValue == null || stringValue.trim() === '') {
_this.setStringValue('');
onChange(null, event);
return;
} // order here matters a lot
if (isIntermediate) {
_this.setStringValue(stringValue);
} else if (numberValue !== value) {
onChange(numberValue, event);
} else if (stringValue != _this.state.stringValue) {
_this.setStringValue(stringValue);
}
};
return _this;
}
var _proto = NumberPickerInput.prototype;
_proto.getSnapshotBeforeUpdate = function getSnapshotBeforeUpdate(_ref) {
var editing = _ref.editing;
return {
reselectText: !editing && this.props.editing && this.isSelectingAllText()
};
};
NumberPickerInput.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, prevState) {
var value = nextProps.value,
culture = nextProps.culture,
editing = nextProps.editing;
var decimal = localizers.number.decimalChar(null, culture);
var format = getFormat(nextProps);
if (value == null || isNaN(value)) value = '';else value = editing ? ('' + value).replace('.', decimal) : localizers.number.format(value, format, culture);
var stringValue = '' + value;
if (prevState.lastValueFromProps !== stringValue) return {
stringValue: stringValue,
lastValueFromProps: stringValue
};
return null;
};
_proto.componentDidUpdate = function componentDidUpdate(_, __, _ref2) {
var reselectText = _ref2.reselectText;
if (reselectText) (0, _reactDom.findDOMNode)(this).select();
}; // this intermediate state is for when one runs into
// the decimal or are typing the number
_proto.setStringValue = function setStringValue(stringValue) {
this.setState({
stringValue: stringValue
});
};
_proto.isIntermediateValue = function isIntermediateValue(num, str) {
var _this$props2 = this.props,
culture = _this$props2.culture,
min = _this$props2.min;
return !!(num < min || isSign(str) || isAtDelimiter(num, str, culture) || isPaddedZeros(str, culture));
};
_proto.isSelectingAllText = function isSelectingAllText() {
var node = _inDOM.default && (0, _reactDom.findDOMNode)(this);
return _inDOM.default && (0, _activeElement.default)() === node && node.selectionStart === 0 && node.selectionEnd === node.value.length;
};
_proto.parseNumber = function parseNumber(strVal) {
var _this$props3 = this.props,
culture = _this$props3.culture,
userParse = _this$props3.parse;
var delimChar = localizers.number.decimalChar(null, culture);
if (userParse) return userParse(strVal, culture);
strVal = strVal.replace(delimChar, '.');
strVal = parseFloat(strVal);
return strVal;
};
_proto.render = function render() {
var _this$props4 = this.props,
disabled = _this$props4.disabled,
readOnly = _this$props4.readOnly,
placeholder = _this$props4.placeholder,
min = _this$props4.min,
max = _this$props4.max;
var value = this.state.stringValue;
var props = Props$$1.omitOwn(this);
return _react.default.createElement(_Input.default, _extends({}, props, {
className: "rw-widget-input",
onChange: this.handleChange,
onBlur: this.handleBlur,
"aria-valuenow": value,
"aria-valuemin": isFinite(min) ? min : null,
"aria-valuemax": isFinite(max) ? max : null,
disabled: disabled,
readOnly: readOnly,
placeholder: placeholder,
value: value
}));
};
return NumberPickerInput;
}(_react.default.Component), _class2.defaultProps = {
value: null,
editing: false
}, _class2.propTypes = {
value: _propTypes.default.number,
editing: _propTypes.default.bool,
placeholder: _propTypes.default.string,
format: CustomPropTypes.numberFormat,
parse: _propTypes.default.func,
culture: _propTypes.default.string,
min: _propTypes.default.number,
max: _propTypes.default.number,
disabled: CustomPropTypes.disabled,
readOnly: CustomPropTypes.disabled,
onChange: _propTypes.default.func.isRequired
}, _temp)) || _class;
var _default = NumberPickerInput;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(NumberInput);
var NumberPicker_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _classnames = _interopRequireDefault(classnames);
var _propTypes = _interopRequireDefault(propTypes);
var _react = _interopRequireDefault(React__default);
var _uncontrollable = _interopRequireDefault(uncontrollable_1);
var _Widget = _interopRequireDefault(Widget_1);
var _WidgetPicker = _interopRequireDefault(WidgetPicker_1);
var _Select = _interopRequireDefault(Select_1);
var _NumberInput = _interopRequireDefault(NumberInput);
var _Button = _interopRequireDefault(Button_1);
var Props$$1 = _interopRequireWildcard(Props);
var _focusManager = _interopRequireDefault(focusManager$2);
var CustomPropTypes = _interopRequireWildcard(PropTypes$2);
var _class, _class2, _descriptor, _descriptor2, _descriptor3, _class3, _temp;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _initializerDefineProperty(target, property, descriptor, context) { if (!descriptor) return; Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 }); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { var desc = {}; Object['ke' + 'ys'](descriptor).forEach(function (key) { desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer) { desc.writable = true; } desc = decorators.slice().reverse().reduce(function (desc, decorator) { return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0) { desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0) { Object['define' + 'Property'](target, property, desc); desc = null; } return desc; }
var format = function format(props) {
return localizers.number.getFormat('default', props.format);
}; // my tests in ie11/chrome/FF indicate that keyDown repeats
// at about 35ms+/- 5ms after an initial 500ms delay. callback fires on the leading edge
function createInterval(callback) {
var _fn;
var id,
cancel = function cancel() {
return clearTimeout(id);
};
id = setTimeout(_fn = function fn() {
id = setTimeout(_fn, 35);
callback(); //fire after everything in case the user cancels on the first call
}, 500);
return cancel;
}
function clamp(value, min, max) {
max = max == null ? Infinity : max;
min = min == null ? -Infinity : min;
if (value == null || value === '') return null;
return Math.max(Math.min(value, max), min);
}
/**
* ---
* localized: true
* shortcuts:
* - { key: down arrow, label: decrement value }
* - { key: up arrow, label: increment value }
* - { key: home, label: set value to minimum value, if finite }
* - { key: end, label: set value to maximum value, if finite }
* ---
*
* @public
*/
var NumberPicker = (0, reactLifecyclesCompat_es.polyfill)(_class = (_class2 = (_temp = _class3 =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(NumberPicker, _React$Component);
function NumberPicker() {
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;
_initializerDefineProperty(_this, "handleMouseDown", _descriptor, _assertThisInitialized(_assertThisInitialized(_this)));
_initializerDefineProperty(_this, "handleMouseUp", _descriptor2, _assertThisInitialized(_assertThisInitialized(_this)));
_initializerDefineProperty(_this, "handleKeyDown", _descriptor3, _assertThisInitialized(_assertThisInitialized(_this)));
_this.handleChange = function (rawValue, originalEvent) {
if (originalEvent === void 0) {
originalEvent = null;
}
var _this$props = _this.props,
onChange = _this$props.onChange,
lastValue = _this$props.value,
min = _this$props.min,
max = _this$props.max;
var nextValue = clamp(rawValue, min, max);
if (lastValue !== nextValue) (0, widgetHelpers.notify)(onChange, [nextValue, {
rawValue: rawValue,
lastValue: lastValue,
originalEvent: originalEvent
}]);
};
_this.attachInputRef = function (ref) {
_this.inputRef = ref;
};
_this.focusManager = (0, _focusManager.default)(_assertThisInitialized(_assertThisInitialized(_this)), {
willHandle: function willHandle(focused) {
if (focused) _this.focus();
}
});
_this.state = {
focused: false
};
return _this;
}
NumberPicker.getDerivedStateFromProps = function getDerivedStateFromProps(_ref) {
var messages = _ref.messages;
return {
messages: (0, messages_1.getMessages)(messages)
};
};
var _proto = NumberPicker.prototype;
_proto.renderInput = function renderInput(value) {
var _this$props2 = this.props,
placeholder = _this$props2.placeholder,
autoFocus = _this$props2.autoFocus,
tabIndex = _this$props2.tabIndex,
parse = _this$props2.parse,
name = _this$props2.name,
onKeyPress = _this$props2.onKeyPress,
onKeyUp = _this$props2.onKeyUp,
min = _this$props2.min,
max = _this$props2.max,
disabled = _this$props2.disabled,
readOnly = _this$props2.readOnly,
inputProps = _this$props2.inputProps,
format = _this$props2.format,
culture = _this$props2.culture;
return _react.default.createElement(_NumberInput.default, _extends({}, inputProps, {
role: "spinbutton",
tabIndex: tabIndex,
value: value,
placeholder: placeholder,
autoFocus: autoFocus,
editing: this.state.focused,
format: format,
culture: culture,
parse: parse,
name: name,
min: min,
max: max,
disabled: disabled,
readOnly: readOnly,
onChange: this.handleChange,
onKeyPress: onKeyPress,
onKeyUp: onKeyUp,
nodeRef: this.attachInputRef
}));
};
_proto.render = function render() {
var _this2 = this;
var _this$props3 = this.props,
className = _this$props3.className,
containerClassName = _this$props3.containerClassName,
disabled = _this$props3.disabled,
readOnly = _this$props3.readOnly,
value = _this$props3.value,
min = _this$props3.min,
max = _this$props3.max,
incrementIcon = _this$props3.incrementIcon,
decrementIcon = _this$props3.decrementIcon;
var _this$state = this.state,
focused = _this$state.focused,
messages = _this$state.messages;
var elementProps = Props$$1.pickElementProps(this);
value = clamp(value, min, max);
return _react.default.createElement(_Widget.default, _extends({}, elementProps, {
focused: focused,
disabled: disabled,
readOnly: readOnly,
onKeyDown: this.handleKeyDown,
onBlur: this.focusManager.handleBlur,
onFocus: this.focusManager.handleFocus,
className: (0, _classnames.default)(className, 'rw-number-picker')
}), _react.default.createElement(_WidgetPicker.default, {
className: containerClassName
}, this.renderInput(value), _react.default.createElement(_Select.default, {
bordered: true
}, _react.default.createElement(_Button.default, {
icon: incrementIcon,
onClick: this.handleFocus,
disabled: value === max || disabled,
label: messages.increment({
value: value,
min: min,
max: max
}),
onMouseUp: function onMouseUp(e) {
return _this2.handleMouseUp('UP', e);
},
onMouseDown: function onMouseDown(e) {
return _this2.handleMouseDown('UP', e);
},
onMouseLeave: function onMouseLeave(e) {
return _this2.handleMouseUp('UP', e);
}
}), _react.default.createElement(_Button.default, {
icon: decrementIcon,
onClick: this.handleFocus,
disabled: value === min || disabled,
label: messages.decrement({
value: value,
min: min,
max: max
}),
onMouseUp: function onMouseUp(e) {
return _this2.handleMouseUp('DOWN', e);
},
onMouseDown: function onMouseDown(e) {
return _this2.handleMouseDown('DOWN', e);
},
onMouseLeave: function onMouseLeave(e) {
return _this2.handleMouseUp('DOWN', e);
}
}))));
};
_proto.focus = function focus() {
this.inputRef.focus();
};
_proto.increment = function increment(event) {
return this.step(this.props.step, event);
};
_proto.decrement = function decrement(event) {
return this.step(-this.props.step, event);
};
_proto.step = function step(amount, event) {
var value = (this.props.value || 0) + amount;
var decimals = this.props.precision != null ? this.props.precision : localizers.number.precision(format(this.props));
this.handleChange(decimals != null ? round(value, decimals) : value, event);
return value;
};
return NumberPicker;
}(_react.default.Component), _class3.propTypes = {
value: _propTypes.default.number,
/**
* @example ['onChangePicker', [ [1, null] ]]
*/
onChange: _propTypes.default.func,
/**
* The minimum number that the NumberPicker value.
* @example ['prop', ['min', 0]]
*/
min: _propTypes.default.number,
/**
* The maximum number that the NumberPicker value.
*
* @example ['prop', ['max', 0]]
*/
max: _propTypes.default.number,
/**
* Amount to increase or decrease value when using the spinner buttons.
*
* @example ['prop', ['step', 5]]
*/
step: _propTypes.default.number,
/**
* Specify how precise the `value` should be when typing, incrementing, or decrementing the value.
* When empty, precision is parsed from the current `format` and culture.
*/
precision: _propTypes.default.number,
culture: _propTypes.default.string,
/**
* A format string used to display the number value. Localizer dependent, read [localization](../localization) for more info.
*
* @example ['prop', { max: 1, min: -1 , defaultValue: 0.2585, format: "{ style: 'percent' }" }]
*/
format: CustomPropTypes.numberFormat,
/**
* Determines how the NumberPicker parses a number from the localized string representation.
* You can also provide a parser `function` to pair with a custom `format`.
*/
parse: _propTypes.default.func,
incrementIcon: _propTypes.default.node,
decrementIcon: _propTypes.default.node,
/** @ignore */
tabIndex: _propTypes.default.any,
name: _propTypes.default.string,
placeholder: _propTypes.default.string,
onKeyDown: _propTypes.default.func,
onKeyPress: _propTypes.default.func,
onKeyUp: _propTypes.default.func,
autoFocus: _propTypes.default.bool,
/**
* @example ['disabled', ['1']]
*/
disabled: CustomPropTypes.disabled,
/**
* @example ['readOnly', ['1.5']]
*/
readOnly: CustomPropTypes.disabled,
/** Adds a css class to the input container element. */
containerClassName: _propTypes.default.string,
inputProps: _propTypes.default.object,
isRtl: _propTypes.default.bool,
messages: _propTypes.default.shape({
increment: _propTypes.default.string,
decrement: _propTypes.default.string
})
}, _class3.defaultProps = {
value: null,
open: false,
incrementIcon: Icon_1.caretUp,
decrementIcon: Icon_1.caretDown,
min: -Infinity,
max: Infinity,
step: 1
}, _temp), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, "handleMouseDown", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this3 = this;
return function (direction, event) {
var _this3$props = _this3.props,
min = _this3$props.min,
max = _this3$props.max;
event && event.persist();
var method = direction === 'UP' ? _this3.increment : _this3.decrement;
var value = method.call(_this3, event),
atTop = direction === 'UP' && value === max,
atBottom = direction === 'DOWN' && value === min;
if (atTop || atBottom) _this3.handleMouseUp();else if (!_this3._cancelRepeater) {
_this3._cancelRepeater = createInterval(function () {
_this3.handleMouseDown(direction, event);
});
}
};
}
}), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, "handleMouseUp", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this4 = this;
return function () {
_this4._cancelRepeater && _this4._cancelRepeater();
_this4._cancelRepeater = null;
};
}
}), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, "handleKeyDown", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this5 = this;
return function (event) {
var _this5$props = _this5.props,
min = _this5$props.min,
max = _this5$props.max,
onKeyDown = _this5$props.onKeyDown;
var key = event.key;
(0, widgetHelpers.notify)(onKeyDown, [event]);
if (event.defaultPrevented) return;
if (key === 'End' && isFinite(max)) _this5.handleChange(max, event);else if (key === 'Home' && isFinite(min)) _this5.handleChange(min, event);else if (key === 'ArrowDown') {
event.preventDefault();
_this5.decrement(event);
} else if (key === 'ArrowUp') {
event.preventDefault();
_this5.increment(event);
}
};
}
})), _class2)) || _class;
var _default = (0, _uncontrollable.default)(NumberPicker, {
value: 'onChange'
}, ['focus']); // thank you kendo ui core
// https://github.com/telerik/kendo-ui-core/blob/master/src/kendo.core.js#L1036
exports.default = _default;
function round(value, precision) {
precision = precision || 0;
value = ('' + value).split('e');
value = Math.round(+(value[0] + 'e' + (value[1] ? +value[1] + precision : precision)));
value = ('' + value).split('e');
value = +(value[0] + 'e' + (value[1] ? +value[1] - precision : -precision));
return value.toFixed(precision);
}
module.exports = exports["default"];
});
unwrapExports(NumberPicker_1);
var closest_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = closest;
var _matches = interopRequireDefault(matches_1);
var isDoc = function isDoc(obj) {
return obj != null && obj.nodeType === obj.DOCUMENT_NODE;
};
function closest(node, selector, context) {
while (node && (isDoc(node) || !(0, _matches.default)(node, selector))) {
node = node !== context && !isDoc(node) ? node.parentNode : undefined;
}
return node;
}
module.exports = exports["default"];
});
unwrapExports(closest_1);
var MultiselectInput_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _activeElement = _interopRequireDefault(activeElement_1);
var _propTypes = _interopRequireDefault(propTypes);
var _react = _interopRequireDefault(React__default);
var CustomPropTypes = _interopRequireWildcard(PropTypes$2);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutProperties(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]; } if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var MultiselectInput =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(MultiselectInput, _React$Component);
function MultiselectInput() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = MultiselectInput.prototype;
_proto.focus = function focus() {
var node = (0, _reactDom.findDOMNode)(this);
if ((0, _activeElement.default)() === node) return;
node.focus();
};
_proto.select = function select() {
(0, _reactDom.findDOMNode)(this).select();
};
_proto.render = function render() {
var _this$props = this.props,
disabled = _this$props.disabled,
readOnly = _this$props.readOnly,
props = _objectWithoutProperties(_this$props, ["disabled", "readOnly"]);
var size = Math.max((props.value || props.placeholder).length, 1) + 1;
return _react.default.createElement("input", _extends({}, props, {
size: size,
className: "rw-input-reset",
autoComplete: "off",
"aria-disabled": disabled,
"aria-readonly": readOnly,
disabled: disabled,
readOnly: readOnly
}));
};
return MultiselectInput;
}(_react.default.Component);
MultiselectInput.propTypes = {
value: _propTypes.default.string,
placeholder: _propTypes.default.string,
maxLength: _propTypes.default.number,
onChange: _propTypes.default.func.isRequired,
disabled: CustomPropTypes.disabled,
readOnly: CustomPropTypes.disabled
};
var _default = MultiselectInput;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(MultiselectInput_1);
var MultiselectTag_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _classnames = _interopRequireDefault(classnames);
var _react = _interopRequireDefault(React__default);
var _propTypes = _interopRequireDefault(propTypes);
var _Button = _interopRequireDefault(Button_1);
var _class, _descriptor, _class2, _temp;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _initializerDefineProperty(target, property, descriptor, context) { if (!descriptor) return; Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 }); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { var desc = {}; Object['ke' + 'ys'](descriptor).forEach(function (key) { desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer) { desc.writable = true; } desc = decorators.slice().reverse().reduce(function (desc, decorator) { return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0) { desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0) { Object['define' + 'Property'](target, property, desc); desc = null; } return desc; }
var MultiselectTag = (_class = (_temp = _class2 =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(MultiselectTag, _React$Component);
function MultiselectTag() {
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;
_initializerDefineProperty(_this, "onClick", _descriptor, _assertThisInitialized(_assertThisInitialized(_this)));
return _this;
}
var _proto = MultiselectTag.prototype;
_proto.renderDelete = function renderDelete() {
var _this$props = this.props,
label = _this$props.label,
disabled = _this$props.disabled,
readOnly = _this$props.readOnly;
return _react.default.createElement(_Button.default, {
variant: "select",
onClick: this.onClick,
className: "rw-multiselect-tag-btn",
disabled: disabled || readOnly,
"aria-label": label || 'Remove item'
}, _react.default.createElement("span", {
"aria-hidden": "true"
}, "\xD7"));
};
_proto.render = function render() {
var _this$props2 = this.props,
id = _this$props2.id,
children = _this$props2.children,
focused = _this$props2.focused,
disabled = _this$props2.disabled;
return _react.default.createElement("li", {
id: id,
role: "option",
className: (0, _classnames.default)('rw-multiselect-tag', disabled && 'rw-state-disabled', focused && !disabled && 'rw-state-focus')
}, children, _react.default.createElement("div", null, this.renderDelete()));
};
return MultiselectTag;
}(_react.default.Component), _class2.propTypes = {
id: _propTypes.default.string,
onClick: _propTypes.default.func.isRequired,
focused: _propTypes.default.bool,
disabled: _propTypes.default.bool,
readOnly: _propTypes.default.bool,
label: _propTypes.default.string,
value: _propTypes.default.any
}, _temp), (_descriptor = _applyDecoratedDescriptor(_class.prototype, "onClick", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this2 = this;
return function (event) {
var _this2$props = _this2.props,
value = _this2$props.value,
disabled = _this2$props.disabled,
onClick = _this2$props.onClick;
if (!disabled) onClick(value, event);
};
}
})), _class);
var _default = MultiselectTag;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(MultiselectTag_1);
var MultiselectTagList_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _react = _interopRequireDefault(React__default);
var _propTypes = _interopRequireDefault(propTypes);
var _MultiselectTag = _interopRequireDefault(MultiselectTag_1);
var CustomPropTypes = _interopRequireWildcard(PropTypes$2);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
// disabled === true || [1, 2, 3, etc]
var isDisabled = function isDisabled(item, list, value) {
return !!(Array.isArray(list) ? ~(0, dataHelpers.dataIndexOf)(list, item, value) : list);
};
var MultiselectTagList =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(MultiselectTagList, _React$Component);
function MultiselectTagList() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = MultiselectTagList.prototype;
_proto.render = function render() {
var _this$props = this.props,
id = _this$props.id,
value = _this$props.value,
activeId = _this$props.activeId,
valueAccessor = _this$props.valueAccessor,
textAccessor = _this$props.textAccessor,
label = _this$props.label,
disabled = _this$props.disabled,
onDelete = _this$props.onDelete,
focusedItem = _this$props.focusedItem,
ValueComponent = _this$props.valueComponent;
return _react.default.createElement("ul", {
id: id,
role: "listbox",
"aria-label": label,
className: "rw-multiselect-taglist"
}, value.map(function (item, i) {
var isFocused = focusedItem === item;
return _react.default.createElement(_MultiselectTag.default, {
key: i,
id: isFocused ? activeId : null,
value: item,
focused: isFocused,
onClick: onDelete,
disabled: isDisabled(item, disabled, valueAccessor)
}, ValueComponent ? _react.default.createElement(ValueComponent, {
item: item
}) : _react.default.createElement("span", null, textAccessor(item)));
}));
};
return MultiselectTagList;
}(_react.default.Component);
MultiselectTagList.propTypes = {
id: _propTypes.default.string.isRequired,
activeId: _propTypes.default.string.isRequired,
label: _propTypes.default.string,
value: _propTypes.default.array,
focusedItem: _propTypes.default.any,
valueAccessor: _propTypes.default.func.isRequired,
textAccessor: _propTypes.default.func.isRequired,
onDelete: _propTypes.default.func.isRequired,
valueComponent: _propTypes.default.func,
disabled: CustomPropTypes.disabled.acceptsArray
};
var _default = MultiselectTagList;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(MultiselectTagList_1);
var Multiselect_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _classnames = _interopRequireDefault(classnames);
var _closest = _interopRequireDefault(closest_1);
var _propTypes = _interopRequireDefault(propTypes);
var _react = _interopRequireDefault(React__default);
var _uncontrollable = _interopRequireDefault(uncontrollable_1);
var _Widget = _interopRequireDefault(Widget_1);
var _WidgetPicker = _interopRequireDefault(WidgetPicker_1);
var _Select = _interopRequireDefault(Select_1);
var _Popup = _interopRequireDefault(Popup_1);
var _MultiselectInput = _interopRequireDefault(MultiselectInput_1);
var _MultiselectTagList = _interopRequireDefault(MultiselectTagList_1);
var _List = _interopRequireDefault(List_1);
var _AddToListOption = _interopRequireDefault(AddToListOption_1);
var Filter$$1 = _interopRequireWildcard(Filter);
var Props$$1 = _interopRequireWildcard(Props);
var CustomPropTypes = _interopRequireWildcard(PropTypes$2);
var _reduceToListState = _interopRequireWildcard(reduceToListState_1);
var _getAccessors = _interopRequireDefault(getAccessors);
var _focusManager = _interopRequireDefault(focusManager$2);
var _scrollManager = _interopRequireDefault(scrollManager);
var _class, _class2, _descriptor, _descriptor2, _descriptor3, _descriptor4, _descriptor5, _class3, _temp;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _initializerDefineProperty(target, property, descriptor, context) { if (!descriptor) return; Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 }); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { var desc = {}; Object['ke' + 'ys'](descriptor).forEach(function (key) { desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer) { desc.writable = true; } desc = decorators.slice().reverse().reduce(function (desc, decorator) { return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0) { desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0) { Object['define' + 'Property'](target, property, desc); desc = null; } return desc; }
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); }
var CREATE_OPTION = {};
var ENTER = 13;
var INSERT = 'insert';
var REMOVE = 'remove';
var propTypes$$1 = _extends({}, Filter$$1.propTypes, {
data: _propTypes.default.array,
//-- controlled props --
value: _propTypes.default.array,
/**
* @type {function (
* dataItems: ?any[],
* metadata: {
* dataItem: any,
* action: 'insert' | 'remove',
* originalEvent: SyntheticEvent,
* lastValue: ?any[],
* searchTerm: ?string
* }
* ): void}
*/
onChange: _propTypes.default.func,
searchTerm: _propTypes.default.string,
/**
* @type {function (
* searchTerm: ?string,
* metadata: {
* action: 'clear' | 'input',
* lastSearchTerm: ?string,
* originalEvent: SyntheticEvent,
* }
* ): void}
*/
onSearch: _propTypes.default.func,
open: _propTypes.default.bool,
onToggle: _propTypes.default.func,
//-------------------------------------------
valueField: CustomPropTypes.accessor,
textField: CustomPropTypes.accessor,
tagComponent: CustomPropTypes.elementType,
itemComponent: CustomPropTypes.elementType,
listComponent: CustomPropTypes.elementType,
groupComponent: CustomPropTypes.elementType,
groupBy: CustomPropTypes.accessor,
allowCreate: _propTypes.default.oneOf([true, false, 'onFilter']),
/**
*
* @type { (dataItem: ?any, metadata: { originalEvent: SyntheticEvent }) => void }
*/
onSelect: _propTypes.default.func,
/**
* @type { (searchTerm: string) => void }
*/
onCreate: _propTypes.default.func,
busy: _propTypes.default.bool,
/** Specify the element used to render the select (down arrow) icon. */
selectIcon: _propTypes.default.node,
/** Specify the element used to render the busy indicator */
busySpinner: _propTypes.default.node,
dropUp: _propTypes.default.bool,
popupTransition: CustomPropTypes.elementType,
/** Adds a css class to the input container element. */
containerClassName: _propTypes.default.string,
inputProps: _propTypes.default.object,
listProps: _propTypes.default.object,
autoFocus: _propTypes.default.bool,
placeholder: _propTypes.default.string,
/** Continue to show the input placeholder even if tags are selected */
showPlaceholderWithValues: _propTypes.default.bool,
disabled: CustomPropTypes.disabled.acceptsArray,
readOnly: CustomPropTypes.disabled,
isRtl: _propTypes.default.bool,
messages: _propTypes.default.shape({
open: CustomPropTypes.message,
emptyList: CustomPropTypes.message,
emptyFilter: CustomPropTypes.message,
createOption: CustomPropTypes.message,
tagsLabel: CustomPropTypes.message,
selectedItems: CustomPropTypes.message,
noneSelected: CustomPropTypes.message,
removeLabel: CustomPropTypes.message
})
/**
* ---
* shortcuts:
* - { key: left arrow, label: move focus to previous tag }
* - { key: right arrow, label: move focus to next tag }
* - { key: delete, deselect focused tag }
* - { key: backspace, deselect next tag }
* - { key: alt + up arrow, label: close Multiselect }
* - { key: down arrow, label: open Multiselect, and move focus to next item }
* - { key: up arrow, label: move focus to previous item }
* - { key: home, label: move focus to first item }
* - { key: end, label: move focus to last item }
* - { key: enter, label: select focused item }
* - { key: ctrl + enter, label: create new tag from current searchTerm }
* - { key: any key, label: search list for item starting with key }
* ---
*
* A select listbox alternative.
*
* @public
*/
});
var Multiselect = (0, reactLifecyclesCompat_es.polyfill)(_class = (_class2 = (_temp = _class3 =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(Multiselect, _React$Component);
function Multiselect() {
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.handleFocusDidChange = function (focused) {
if (focused) return _this.focus();
_this.close();
_this.clearSearch();
if (_this.tagsRef) _this.setState({
focusedTag: null
});
};
_this.handleDelete = function (dataItem, event) {
var _this$props = _this.props,
disabled = _this$props.disabled,
readOnly = _this$props.readOnly;
if (disabled == true || readOnly) return;
_this.focus();
_this.change(dataItem, event, REMOVE);
};
_this.handleSearchKeyDown = function (e) {
if (e.key === 'Backspace' && e.target.value && !_this._deletingText) _this._deletingText = true;
};
_this.handleSearchKeyUp = function (e) {
if (e.key === 'Backspace' && _this._deletingText) _this._deletingText = false;
};
_this.handleInputChange = function (e) {
_this.search(e.target.value, e, 'input');
_this.open();
};
_initializerDefineProperty(_this, "handleClick", _descriptor, _assertThisInitialized(_assertThisInitialized(_this)));
_initializerDefineProperty(_this, "handleDoubleClick", _descriptor2, _assertThisInitialized(_assertThisInitialized(_this)));
_initializerDefineProperty(_this, "handleSelect", _descriptor3, _assertThisInitialized(_assertThisInitialized(_this)));
_initializerDefineProperty(_this, "handleCreate", _descriptor4, _assertThisInitialized(_assertThisInitialized(_this)));
_initializerDefineProperty(_this, "handleKeyDown", _descriptor5, _assertThisInitialized(_assertThisInitialized(_this)));
_this.attachListRef = function (ref) {
return _this.listRef = ref;
};
_this.attachTagsRef = function (ref) {
return _this.tagsRef = ref;
};
_this.attachInputRef = function (ref) {
return _this.inputRef = ref;
};
_this.inputId = (0, widgetHelpers.instanceId)(_assertThisInitialized(_assertThisInitialized(_this)), '_input');
_this.tagsId = (0, widgetHelpers.instanceId)(_assertThisInitialized(_assertThisInitialized(_this)), '_taglist');
_this.notifyId = (0, widgetHelpers.instanceId)(_assertThisInitialized(_assertThisInitialized(_this)), '_notify_area');
_this.listId = (0, widgetHelpers.instanceId)(_assertThisInitialized(_assertThisInitialized(_this)), '_listbox');
_this.createId = (0, widgetHelpers.instanceId)(_assertThisInitialized(_assertThisInitialized(_this)), '_createlist_option');
_this.activeTagId = (0, widgetHelpers.instanceId)(_assertThisInitialized(_assertThisInitialized(_this)), '_taglist_active_tag');
_this.activeOptionId = (0, widgetHelpers.instanceId)(_assertThisInitialized(_assertThisInitialized(_this)), '_listbox_active_option');
_this.handleScroll = (0, _scrollManager.default)(_assertThisInitialized(_assertThisInitialized(_this)));
_this.focusManager = (0, _focusManager.default)(_assertThisInitialized(_assertThisInitialized(_this)), {
didHandle: _this.handleFocusDidChange
});
_this.state = {
focusedTag: null
};
return _this;
}
Multiselect.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, prevState) {
var data = nextProps.data,
searchTerm = nextProps.searchTerm,
messages = nextProps.messages,
minLength = nextProps.minLength,
caseSensitive = nextProps.caseSensitive,
filter = nextProps.filter;
var focusedItem = prevState.focusedItem,
focusedTag = prevState.focusedTag;
var accessors = (0, _getAccessors.default)(nextProps);
var valueChanged = nextProps.value !== prevState.lastValue;
var values = (0, _.makeArray)(nextProps.value);
var dataItems = valueChanged ? values.map(function (item) {
return accessors.findOrSelf(data, item);
}) : prevState.dataItems;
data = data.filter(function (i) {
return !values.some(function (v) {
return accessors.matches(i, v);
});
});
var lengthWithoutValues = data.length;
data = Filter$$1.filter(data, {
filter: filter,
searchTerm: searchTerm,
minLength: minLength,
caseSensitive: caseSensitive,
textField: accessors.text
});
var list = (0, _reduceToListState.default)(data, prevState.list, {
nextProps: nextProps
});
var tagList = (0, _reduceToListState.default)(dataItems, prevState.tagList, {
nextProps: nextProps,
getDataState: _reduceToListState.defaultGetDataState
});
var nextFocusedItem = ~data.indexOf(focusedItem) ? focusedItem : data[0];
return {
data: data,
dataItems: dataItems,
list: list,
tagList: tagList,
accessors: accessors,
lengthWithoutValues: lengthWithoutValues,
lastValue: nextProps.value,
messages: (0, messages_1.getMessages)(messages),
focusedTag: valueChanged ? list.nextEnabled(~dataItems.indexOf(focusedTag) ? focusedTag : null) : focusedTag,
focusedItem: valueChanged || !prevState.focusedItem ? list.nextEnabled(nextFocusedItem) : nextFocusedItem
};
};
var _proto = Multiselect.prototype;
_proto.renderInput = function renderInput(ownedIds) {
var _this$props2 = this.props,
searchTerm = _this$props2.searchTerm,
maxLength = _this$props2.maxLength,
tabIndex = _this$props2.tabIndex,
busy = _this$props2.busy,
autoFocus = _this$props2.autoFocus,
inputProps = _this$props2.inputProps,
open = _this$props2.open;
var _this$state = this.state,
focusedItem = _this$state.focusedItem,
focusedTag = _this$state.focusedTag;
var disabled = this.props.disabled === true;
var readOnly = this.props.readOnly === true;
var active;
if (!open) active = focusedTag ? this.activeTagId : '';else if (focusedItem || this.allowCreate()) active = this.activeOptionId;
return _react.default.createElement(_MultiselectInput.default, _extends({}, inputProps, {
autoFocus: autoFocus,
tabIndex: tabIndex || 0,
role: "listbox",
"aria-expanded": !!open,
"aria-busy": !!busy,
"aria-owns": ownedIds,
"aria-haspopup": true,
"aria-activedescendant": active || null,
value: searchTerm,
maxLength: maxLength,
disabled: disabled,
readOnly: readOnly,
placeholder: this.getPlaceholder(),
onKeyDown: this.handleSearchKeyDown,
onKeyUp: this.handleSearchKeyUp,
onChange: this.handleInputChange,
ref: this.attachInputRef
}));
};
_proto.renderList = function renderList() {
var inputId = this.inputId,
activeOptionId = this.activeOptionId,
listId = this.listId;
var _this$props3 = this.props,
open = _this$props3.open,
searchTerm = _this$props3.searchTerm,
optionComponent = _this$props3.optionComponent,
itemComponent = _this$props3.itemComponent,
groupComponent = _this$props3.groupComponent,
listProps = _this$props3.listProps;
var _this$state2 = this.state,
focusedItem = _this$state2.focusedItem,
list = _this$state2.list,
lengthWithoutValues = _this$state2.lengthWithoutValues,
accessors = _this$state2.accessors,
data = _this$state2.data,
messages = _this$state2.messages;
var List = this.props.listComponent;
return _react.default.createElement(List, _extends({}, listProps, {
id: listId,
activeId: activeOptionId,
data: data,
dataState: list.dataState,
isDisabled: list.isDisabled,
searchTerm: searchTerm,
textAccessor: accessors.text,
valueAccessor: accessors.value,
itemComponent: itemComponent,
groupComponent: groupComponent,
optionComponent: optionComponent,
focusedItem: focusedItem,
onSelect: this.handleSelect,
onMove: this.handleScroll,
"aria-live": "polite",
"aria-labelledby": inputId,
"aria-hidden": !open,
ref: this.attachListRef,
messages: {
emptyList: lengthWithoutValues ? messages.emptyFilter : messages.emptyList
}
}));
};
_proto.renderNotificationArea = function renderNotificationArea() {
var _this$state3 = this.state,
focused = _this$state3.focused,
dataItems = _this$state3.dataItems,
accessors = _this$state3.accessors,
messages = _this$state3.messages;
var itemLabels = dataItems.map(function (item) {
return accessors.text(item);
});
return _react.default.createElement("span", {
id: this.notifyId,
role: "status",
className: "rw-sr",
"aria-live": "assertive",
"aria-atomic": "true",
"aria-relevant": "additions removals text"
}, focused && (dataItems.length ? messages.selectedItems(itemLabels) : messages.noneSelected()));
};
_proto.renderTags = function renderTags() {
var _this$props4 = this.props,
readOnly = _this$props4.readOnly,
disabled = _this$props4.disabled;
var _this$state4 = this.state,
focusedTag = _this$state4.focusedTag,
dataItems = _this$state4.dataItems,
accessors = _this$state4.accessors,
messages = _this$state4.messages;
var Component = this.props.tagComponent;
return _react.default.createElement(_MultiselectTagList.default, {
id: this.tagsId,
activeId: this.activeTagId,
textAccessor: accessors.text,
valueAccessor: accessors.value,
label: messages.tagsLabel(),
value: dataItems,
readOnly: readOnly,
disabled: disabled,
focusedItem: focusedTag,
onDelete: this.handleDelete,
valueComponent: Component,
ref: this.attachTagsRef
});
};
_proto.render = function render() {
var _this2 = this;
var _this$props5 = this.props,
className = _this$props5.className,
busy = _this$props5.busy,
dropUp = _this$props5.dropUp,
open = _this$props5.open,
searchTerm = _this$props5.searchTerm,
selectIcon = _this$props5.selectIcon,
busySpinner = _this$props5.busySpinner,
containerClassName = _this$props5.containerClassName,
popupTransition = _this$props5.popupTransition;
var _this$state5 = this.state,
focused = _this$state5.focused,
focusedItem = _this$state5.focusedItem,
dataItems = _this$state5.dataItems,
messages = _this$state5.messages;
var elementProps = Props$$1.pickElementProps(this);
var shouldRenderTags = !!dataItems.length,
shouldRenderPopup = (0, widgetHelpers.isFirstFocusedRender)(this),
allowCreate = this.allowCreate();
var inputOwns = this.listId + " " + this.notifyId + " " + (shouldRenderTags ? this.tagsId : '') + (allowCreate ? this.createId : '');
var disabled = this.props.disabled === true;
var readOnly = this.props.readOnly === true;
return _react.default.createElement(_Widget.default, _extends({}, elementProps, {
open: open,
dropUp: dropUp,
focused: focused,
disabled: disabled,
readOnly: readOnly,
onKeyDown: this.handleKeyDown,
onBlur: this.focusManager.handleBlur,
onFocus: this.focusManager.handleFocus,
className: (0, _classnames.default)(className, 'rw-multiselect')
}), this.renderNotificationArea(messages), _react.default.createElement(_WidgetPicker.default, {
onClick: this.handleClick,
onTouchEnd: this.handleClick,
onDoubleClick: this.handleDoubleClick,
className: (0, _classnames.default)(containerClassName, 'rw-widget-input')
}, _react.default.createElement("div", null, shouldRenderTags && this.renderTags(messages), this.renderInput(inputOwns)), _react.default.createElement(_Select.default, {
busy: busy,
spinner: busySpinner,
icon: focused ? selectIcon : null,
"aria-hidden": "true",
role: "presentational",
disabled: disabled || readOnly
})), shouldRenderPopup && _react.default.createElement(_Popup.default, {
dropUp: dropUp,
open: open,
transition: popupTransition,
onEntering: function onEntering() {
return _this2.listRef.forceUpdate();
}
}, _react.default.createElement("div", null, this.renderList(), allowCreate && _react.default.createElement(_AddToListOption.default, {
id: this.createId,
searchTerm: searchTerm,
onSelect: this.handleCreate,
focused: !focusedItem || focusedItem === CREATE_OPTION
}, messages.createOption(this.props)))));
};
_proto.change = function change(dataItem, originalEvent, action) {
var _this$props6 = this.props,
onChange = _this$props6.onChange,
searchTerm = _this$props6.searchTerm,
lastValue = _this$props6.value;
var dataItems = this.state.dataItems;
switch (action) {
case INSERT:
dataItems = dataItems.concat(dataItem);
break;
case REMOVE:
dataItems = dataItems.filter(function (d) {
return d !== dataItem;
});
break;
}
(0, widgetHelpers.notify)(onChange, [dataItems, {
action: action,
dataItem: dataItem,
originalEvent: originalEvent,
lastValue: lastValue,
searchTerm: searchTerm
}]);
this.clearSearch(originalEvent);
};
_proto.clearSearch = function clearSearch(originalEvent) {
this.search('', originalEvent, 'clear');
};
_proto.search = function search(searchTerm, originalEvent, action) {
if (action === void 0) {
action = 'input';
}
var _this$props7 = this.props,
onSearch = _this$props7.onSearch,
lastSearchTerm = _this$props7.searchTerm;
if (searchTerm !== lastSearchTerm) (0, widgetHelpers.notify)(onSearch, [searchTerm, {
action: action,
lastSearchTerm: lastSearchTerm,
originalEvent: originalEvent
}]);
};
_proto.focus = function focus() {
if (this.inputRef) this.inputRef.focus();
};
_proto.toggle = function toggle() {
this.props.open ? this.close() : this.open();
};
_proto.open = function open() {
if (!this.props.open) (0, widgetHelpers.notify)(this.props.onToggle, true);
};
_proto.close = function close() {
if (this.props.open) (0, widgetHelpers.notify)(this.props.onToggle, false);
};
_proto.allowCreate = function allowCreate() {
var _this$props8 = this.props,
searchTerm = _this$props8.searchTerm,
onCreate = _this$props8.onCreate,
allowCreate = _this$props8.allowCreate;
return !!(onCreate && (allowCreate === true || allowCreate === 'onFilter' && searchTerm) && !this.hasExtactMatch());
};
_proto.hasExtactMatch = function hasExtactMatch() {
var _this$props9 = this.props,
searchTerm = _this$props9.searchTerm,
caseSensitive = _this$props9.caseSensitive;
var _this$state6 = this.state,
data = _this$state6.data,
dataItems = _this$state6.dataItems,
accessors = _this$state6.accessors;
var lower = function lower(text) {
return caseSensitive ? text : text.toLowerCase();
};
var eq = function eq(v) {
return lower(accessors.text(v)) === lower(searchTerm);
}; // if there is an exact match on textFields:
// "john" => { name: "john" }, don't show
return dataItems.some(eq) || data.some(eq);
};
_proto.getPlaceholder = function getPlaceholder() {
var _this$props10 = this.props,
value = _this$props10.value,
placeholder = _this$props10.placeholder,
showPlaceholderWithValues = _this$props10.showPlaceholderWithValues;
return (value && value.length && !showPlaceholderWithValues ? '' : placeholder) || '';
};
return Multiselect;
}(_react.default.Component), _class3.propTypes = propTypes$$1, _class3.defaultProps = {
data: [],
allowCreate: 'onFilter',
filter: 'startsWith',
value: [],
searchTerm: '',
selectIcon: Icon_1.caretDown,
listComponent: _List.default,
showPlaceholderWithValues: false
}, _temp), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, "handleClick", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this3 = this;
return function (_ref) {
var target = _ref.target;
_this3.focus();
if ((0, _closest.default)(target, '.rw-select')) _this3.toggle();else _this3.open();
};
}
}), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, "handleDoubleClick", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this4 = this;
return function () {
if (!_this4.inputRef) return;
_this4.focus();
_this4.inputRef.select();
};
}
}), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, "handleSelect", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this5 = this;
return function (dataItem, originalEvent) {
if (dataItem === undefined || dataItem === CREATE_OPTION) {
_this5.handleCreate(_this5.props.searchTerm, originalEvent);
return;
}
(0, widgetHelpers.notify)(_this5.props.onSelect, [dataItem, {
originalEvent: originalEvent
}]);
_this5.change(dataItem, originalEvent, INSERT);
_this5.focus();
};
}
}), _descriptor4 = _applyDecoratedDescriptor(_class2.prototype, "handleCreate", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this6 = this;
return function (searchTerm, event) {
if (searchTerm === void 0) {
searchTerm = '';
}
(0, widgetHelpers.notify)(_this6.props.onCreate, searchTerm);
_this6.clearSearch(event);
_this6.focus();
};
}
}), _descriptor5 = _applyDecoratedDescriptor(_class2.prototype, "handleKeyDown", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this7 = this;
return function (event) {
var _this7$props = _this7.props,
open = _this7$props.open,
searchTerm = _this7$props.searchTerm,
onKeyDown = _this7$props.onKeyDown;
var key = event.key,
keyCode = event.keyCode,
altKey = event.altKey,
ctrlKey = event.ctrlKey;
var _this7$state = _this7.state,
focusedTag = _this7$state.focusedTag,
focusedItem = _this7$state.focusedItem,
list = _this7$state.list,
tagList = _this7$state.tagList;
var createIsFocused = focusedItem === CREATE_OPTION;
var canCreate = _this7.allowCreate();
var focusTag = function focusTag(tag) {
return _this7.setState({
focusedTag: tag
});
};
var focusItem = function focusItem(item) {
return _this7.setState({
focusedItem: item,
focusedTag: null
});
};
(0, widgetHelpers.notify)(onKeyDown, [event]);
if (event.defaultPrevented) return;
if (key === 'ArrowDown') {
event.preventDefault();
if (!open) return _this7.open();
var next = list.next(focusedItem);
var creating = createIsFocused || canCreate && focusedItem === next;
focusItem(creating ? CREATE_OPTION : next);
} else if (key === 'ArrowUp' && (open || altKey)) {
event.preventDefault();
if (altKey) return _this7.close();
focusItem(createIsFocused ? list.last() : list.prev(focusedItem));
} else if (key === 'End') {
event.preventDefault();
if (open) focusItem(list.last());else focusTag(tagList.last());
} else if (key === 'Home') {
event.preventDefault();
if (open) focusItem(list.first());else focusTag(tagList.first());
} else if (open && keyCode === ENTER) {
// using keyCode to ignore enter for japanese IME
event.preventDefault();
if (ctrlKey && canCreate) return _this7.handleCreate(searchTerm, event);
_this7.handleSelect(focusedItem, event);
} else if (key === 'Escape') {
open ? _this7.close() : tagList && focusTag(null);
} else if (!searchTerm && !_this7._deletingText) {
if (key === 'ArrowLeft') {
focusTag(tagList.prev(focusedTag) || tagList.last());
} else if (key === 'ArrowRight' && focusedTag) {
var nextTag = tagList.next(focusedTag);
focusTag(nextTag === focusedTag ? null : nextTag);
} else if (key === 'Delete' && !tagList.isDisabled(focusedTag)) {
_this7.handleDelete(focusedTag, event);
} else if (key === 'Backspace') {
_this7.handleDelete(tagList.last(), event);
} else if (key === ' ' && !open) {
event.preventDefault();
_this7.open();
}
}
};
}
})), _class2)) || _class;
var _default = (0, _uncontrollable.default)(Multiselect, {
open: 'onToggle',
value: 'onChange',
searchTerm: 'onSearch'
}, ['focus']);
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(Multiselect_1);
var SelectListItem_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _react = _interopRequireDefault(React__default);
var _propTypes = _interopRequireDefault(propTypes);
var _ListOption = _interopRequireDefault(ListOption_1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutProperties(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]; } if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var SelectListItem =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(SelectListItem, _React$Component);
function SelectListItem() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_this.handleChange = function (e) {
var _this$props = _this.props,
onChange = _this$props.onChange,
disabled = _this$props.disabled,
dataItem = _this$props.dataItem;
if (!disabled) onChange(dataItem, e.target.checked);
};
return _this;
}
var _proto = SelectListItem.prototype;
_proto.render = function render() {
var _this$props2 = this.props,
children = _this$props2.children,
disabled = _this$props2.disabled,
readOnly = _this$props2.readOnly,
name = _this$props2.name,
type = _this$props2.type,
checked = _this$props2.checked,
onMouseDown = _this$props2.onMouseDown,
props = _objectWithoutProperties(_this$props2, ["children", "disabled", "readOnly", "name", "type", "checked", "onMouseDown"]);
delete props.onChange;
return _react.default.createElement(_ListOption.default, _extends({}, props, {
role: type,
disabled: disabled,
"aria-checked": !!checked
}), _react.default.createElement("label", {
onMouseDown: onMouseDown,
className: "rw-select-list-label"
}, _react.default.createElement("input", {
name: name,
type: type,
tabIndex: "-1",
checked: checked,
disabled: disabled || !!readOnly,
role: "presentation",
className: "rw-select-list-input",
onChange: this.handleChange
}), children));
};
return SelectListItem;
}(_react.default.Component);
SelectListItem.propTypes = {
type: _propTypes.default.string.isRequired,
name: _propTypes.default.string.isRequired,
disabled: _propTypes.default.bool,
readOnly: _propTypes.default.bool,
dataItem: _propTypes.default.any,
checked: _propTypes.default.bool.isRequired,
onChange: _propTypes.default.func.isRequired,
onMouseDown: _propTypes.default.func.isRequired
};
var _default = SelectListItem;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(SelectListItem_1);
var SelectList_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _react = _interopRequireDefault(React__default);
var _propTypes = _interopRequireDefault(propTypes);
var _classnames = _interopRequireDefault(classnames);
var _uncontrollable = _interopRequireDefault(uncontrollable_1);
var _List = _interopRequireDefault(List_1);
var _Widget = _interopRequireDefault(Widget_1);
var _SelectListItem = _interopRequireDefault(SelectListItem_1);
var Props$$1 = _interopRequireWildcard(Props);
var CustomPropTypes = _interopRequireWildcard(PropTypes$2);
var _reduceToListState = _interopRequireDefault(reduceToListState_1);
var _getAccessors = _interopRequireDefault(getAccessors);
var _focusManager = _interopRequireDefault(focusManager$2);
var _scrollManager = _interopRequireDefault(scrollManager);
var _class, _class2, _descriptor, _descriptor2, _class3, _temp;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _initializerDefineProperty(target, property, descriptor, context) { if (!descriptor) return; Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 }); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { var desc = {}; Object['ke' + 'ys'](descriptor).forEach(function (key) { desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer) { desc.writable = true; } desc = decorators.slice().reverse().reduce(function (desc, decorator) { return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0) { desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0) { Object['define' + 'Property'](target, property, desc); desc = null; } return desc; }
var BusyMask = function BusyMask() {
return _react.default.createElement("span", {
className: "rw-loading-mask"
});
};
function getFirstValue(data, values) {
if (!values.length) return null;
for (var idx = 0; idx < data.length; idx++) {
if (~values.indexOf(data[idx])) return data[idx];
}
return null;
}
/**
* ---
* shortcuts:
* - { key: down arrow, label: move focus, or select previous option }
* - { key: up arrow, label: move focus, or select next option }
* - { key: home, label: move focus to first option }
* - { key: end, label: move focus to last option }
* - { key: spacebar, label: toggle focused option }
* - { key: ctrl + a, label: ctoggle select all/select none }
* - { key: any key, label: search list for option starting with key }
* ---
*
* A group of radio buttons or checkboxes bound to a dataset.
*
* @public
*/
var SelectList = (0, reactLifecyclesCompat_es.polyfill)(_class = (_class2 = (_temp = _class3 =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(SelectList, _React$Component);
function SelectList() {
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.handleMouseDown = function () {
_this._clicking = true;
};
_this.handleFocusChanged = function (focused) {
var _this$props = _this.props,
data = _this$props.data,
disabled = _this$props.disabled;
var _this$state = _this.state,
dataItems = _this$state.dataItems,
accessors = _this$state.accessors,
list = _this$state.list; // the rigamarole here is to avoid flicker went clicking an item and
// gaining focus at the same time.
if (focused !== _this.state.focused) {
if (!focused) _this.setState({
focusedItem: null
});else if (focused && !_this._clicking) {
var allowed = Array.isArray(disabled) ? dataItems.filter(function (v) {
return !accessors.includes(disabled, v);
}) : dataItems;
_this.setState({
focusedItem: getFirstValue(data, allowed) || list.nextEnabled(data[0])
});
}
_this._clicking = false;
}
};
_initializerDefineProperty(_this, "handleKeyDown", _descriptor, _assertThisInitialized(_assertThisInitialized(_this)));
_initializerDefineProperty(_this, "handleKeyPress", _descriptor2, _assertThisInitialized(_assertThisInitialized(_this)));
_this.handleChange = function (item, checked, originalEvent) {
var _this$props2 = _this.props,
multiple = _this$props2.multiple,
onChange = _this$props2.onChange;
var lastValue = _this.state.dataItems;
_this.setState({
focusedItem: item
});
if (!multiple) return (0, widgetHelpers.notify)(onChange, [checked ? item : null, {
originalEvent: originalEvent,
lastValue: lastValue,
checked: checked
}]);
var nextValue = checked ? lastValue.concat(item) : lastValue.filter(function (v) {
return v !== item;
});
(0, widgetHelpers.notify)(onChange, [nextValue || [], {
checked: checked,
lastValue: lastValue,
originalEvent: originalEvent,
dataItem: item
}]);
};
_this.attachListRef = function (ref) {
return _this.listRef = ref;
};
_this.renderListItem = function (itemProps) {
var _this$props3 = _this.props,
name = _this$props3.name,
multiple = _this$props3.multiple,
disabled = _this$props3.disabled,
readOnly = _this$props3.readOnly;
var _this$state2 = _this.state,
dataItems = _this$state2.dataItems,
accessors = _this$state2.accessors;
return _react.default.createElement(_SelectListItem.default, _extends({}, itemProps, {
name: name || _this.itemName,
type: multiple ? 'checkbox' : 'radio',
readOnly: disabled === true || readOnly,
onChange: _this.handleChange,
onMouseDown: _this.handleMouseDown,
checked: accessors.includes(dataItems, itemProps.dataItem)
}));
};
(0, lib$1.autoFocus)(_assertThisInitialized(_assertThisInitialized(_this)));
_this.widgetId = (0, widgetHelpers.instanceId)(_assertThisInitialized(_assertThisInitialized(_this)), '_widget');
_this.listId = (0, widgetHelpers.instanceId)(_assertThisInitialized(_assertThisInitialized(_this)), '_listbox');
_this.activeId = (0, widgetHelpers.instanceId)(_assertThisInitialized(_assertThisInitialized(_this)), '_listbox_active_option');
_this.itemName = (0, widgetHelpers.instanceId)(_assertThisInitialized(_assertThisInitialized(_this)), '_name');
_this.timeouts = (0, lib$1.timeoutManager)(_assertThisInitialized(_assertThisInitialized(_this)));
_this.handleScroll = (0, _scrollManager.default)(_assertThisInitialized(_assertThisInitialized(_this)), false);
_this.focusManager = (0, _focusManager.default)(_assertThisInitialized(_assertThisInitialized(_this)), {
didHandle: _this.handleFocusChanged
});
_this.state = {};
return _this;
}
SelectList.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, prevState) {
var value = nextProps.value,
data = nextProps.data,
messages = nextProps.messages;
var accessors = (0, _getAccessors.default)(nextProps);
var list = (0, _reduceToListState.default)(data, prevState.list, {
nextProps: nextProps
});
return {
list: list,
accessors: accessors,
messages: (0, messages_1.getMessages)(messages),
dataItems: (0, _.makeArray)(value).map(function (item) {
return accessors.findOrSelf(data, item);
})
};
};
var _proto = SelectList.prototype;
_proto.render = function render() {
var _this$props4 = this.props,
className = _this$props4.className,
tabIndex = _this$props4.tabIndex,
busy = _this$props4.busy,
data = _this$props4.data,
busySpinner = _this$props4.busySpinner,
itemComponent = _this$props4.itemComponent,
groupComponent = _this$props4.groupComponent,
listProps = _this$props4.listProps;
var elementProps = Props$$1.pickElementProps(this);
var _this$state3 = this.state,
focusedItem = _this$state3.focusedItem,
focused = _this$state3.focused,
accessors = _this$state3.accessors,
list = _this$state3.list,
messages = _this$state3.messages;
var List = this.props.listComponent;
var disabled = this.props.disabled === true,
readOnly = this.props.readOnly === true;
focusedItem = focused && !disabled && !readOnly && focusedItem;
return _react.default.createElement(_Widget.default, _extends({}, elementProps, {
id: this.widgetId,
onBlur: this.focusManager.handleBlur,
onFocus: this.focusManager.handleFocus,
onKeyDown: this.handleKeyDown,
onKeyPress: this.handleKeyPress,
focused: focused,
disabled: disabled,
readOnly: readOnly,
role: "radiogroup",
"aria-busy": !!busy,
"aria-activedescendant": this.activeId,
className: (0, _classnames.default)(className, 'rw-select-list', 'rw-widget-input', 'rw-widget-container')
}), _react.default.createElement(List, _extends({}, listProps, {
role: "radiogroup",
tabIndex: tabIndex || '0',
id: this.listId,
activeId: this.activeId,
data: data,
dataState: list.dataState,
isDisabled: list.isDisabled,
textAccessor: accessors.text,
valueAccessor: accessors.value,
itemComponent: itemComponent,
groupComponent: groupComponent,
optionComponent: this.renderListItem,
focusedItem: focusedItem,
onMove: this.handleScroll,
messages: {
emptyList: messages.emptyList
},
ref: this.attachListRef
})), busy && busySpinner);
};
_proto.focus = function focus() {
(0, _reactDom.findDOMNode)(this.refs.list).focus();
};
_proto.selectAll = function selectAll() {
var accessors = this.accessors;
var _this$props5 = this.props,
data = _this$props5.data,
disabled = _this$props5.disabled,
onChange = _this$props5.onChange;
var values = this.state.dataItems;
disabled = Array.isArray(disabled) ? disabled : [];
var disabledValues;
var enabledData = data;
if (disabled.length) {
disabledValues = values.filter(function (v) {
return accessors.includes(disabled, v);
});
enabledData = data.filter(function (v) {
return !accessors.includes(disabled, v);
});
}
var nextValues = values.length >= enabledData.length ? values.filter(function (v) {
return accessors.includes(disabled, v);
}) : enabledData.concat(disabledValues);
(0, widgetHelpers.notify)(onChange, [nextValues]);
};
_proto.search = function search(character, originalEvent) {
var _this2 = this;
var _searchTerm = this._searchTerm,
list = this.list;
var word = ((_searchTerm || '') + character).toLowerCase();
var multiple = this.props.multiple;
if (!multiple) originalEvent.persist();
if (!character) return;
this._searchTerm = word;
this.timeouts.set('search', function () {
var focusedItem = list.next(_this2.state.focusedItem, word);
_this2._searchTerm = '';
if (focusedItem) {
!multiple ? _this2.handleChange(focusedItem, true, originalEvent) : _this2.setState({
focusedItem: focusedItem
});
}
}, this.props.delay);
};
return SelectList;
}(_react.default.Component), _class3.propTypes = {
data: _propTypes.default.array,
value: _propTypes.default.oneOfType([_propTypes.default.any, _propTypes.default.array]),
onChange: _propTypes.default.func,
/**
* A handler called when focus shifts on the SelectList. Internally this is used to ensure the focused item is in view.
* If you want to define your own "scrollTo" behavior or just disable the default one specify an `onMove` handler.
* The handler is called with the relevant DOM nodes needed to implement scroll behavior: the list element,
* the element that is currently focused, and a focused value.
*
* @type {function(list: HTMLELement, focusedNode: HTMLElement, focusedItem: any)}
*/
onMove: _propTypes.default.func,
/**
* Whether or not the SelectList allows multiple selection or not. when `false` the SelectList will
* render as a list of radio buttons, and checkboxes when `true`.
*/
multiple: _propTypes.default.bool,
onKeyDown: _propTypes.default.func,
onKeyPress: _propTypes.default.func,
itemComponent: CustomPropTypes.elementType,
busySpinner: _propTypes.default.node,
listComponent: CustomPropTypes.elementType,
groupComponent: CustomPropTypes.elementType,
groupBy: CustomPropTypes.accessor,
valueField: CustomPropTypes.accessor,
textField: CustomPropTypes.accessor,
busy: _propTypes.default.bool,
delay: _propTypes.default.number,
autoFocus: _propTypes.default.bool,
disabled: CustomPropTypes.disabled.acceptsArray,
readOnly: CustomPropTypes.disabled,
listProps: _propTypes.default.object,
tabIndex: _propTypes.default.any,
/**
* The HTML `name` attribute used to group checkboxes and radio buttons
* together.
*/
name: _propTypes.default.string,
isRtl: _propTypes.default.bool,
messages: _propTypes.default.shape({
emptyList: CustomPropTypes.message
})
}, _class3.defaultProps = {
delay: 250,
value: [],
data: [],
busySpinner: _react.default.createElement(BusyMask, null),
listComponent: _List.default
}, _temp), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, "handleKeyDown", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this3 = this;
return function (event) {
var multiple = _this3.props.multiple;
var _this3$state = _this3.state,
dataItems = _this3$state.dataItems,
focusedItem = _this3$state.focusedItem,
list = _this3$state.list,
accessors = _this3$state.accessors;
var keyCode = event.keyCode,
key = event.key,
ctrlKey = event.ctrlKey;
var change = function change(item) {
if (!item) return;
var checked = multiple ? !accessors.includes(dataItems, item) // toggle value
: true;
_this3.handleChange(item, checked, event);
};
(0, widgetHelpers.notify)(_this3.props.onKeyDown, [event]);
if (event.defaultPrevented) return;
if (key === 'End') {
event.preventDefault();
focusedItem = list.last();
_this3.setState({
focusedItem: focusedItem
});
if (!multiple) change(focusedItem);
} else if (key === 'Home') {
event.preventDefault();
focusedItem = list.first();
_this3.setState({
focusedItem: focusedItem
});
if (!multiple) change(focusedItem);
} else if (key === 'Enter' || key === ' ') {
event.preventDefault();
change(focusedItem);
} else if (key === 'ArrowDown' || key === 'ArrowRight') {
event.preventDefault();
focusedItem = list.next(focusedItem);
_this3.setState({
focusedItem: focusedItem
});
if (!multiple) change(focusedItem);
} else if (key === 'ArrowUp' || key === 'ArrowLeft') {
event.preventDefault();
focusedItem = list.prev(focusedItem);
_this3.setState({
focusedItem: focusedItem
});
if (!multiple) change(focusedItem);
} else if (multiple && keyCode === 65 && ctrlKey) {
event.preventDefault();
_this3.selectAll();
}
};
}
}), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, "handleKeyPress", [interaction.widgetEditable], {
enumerable: true,
initializer: function initializer() {
var _this4 = this;
return function (event) {
(0, widgetHelpers.notify)(_this4.props.onKeyPress, [event]);
if (event.defaultPrevented) return;
_this4.search(String.fromCharCode(event.which), event);
};
}
})), _class2)) || _class;
var _default = (0, _uncontrollable.default)(SelectList, {
value: 'onChange'
}, ['selectAll', 'focus']);
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(SelectList_1);
var lib$2 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.setNumberLocalizer = exports.setDateLocalizer = exports.setLocalizers = exports.utils = void 0;
var _configure = _interopRequireDefault(configure);
var _DropdownList = _interopRequireDefault(DropdownList_1);
exports.DropdownList = _DropdownList.default;
var _Combobox = _interopRequireDefault(Combobox_1);
exports.Combobox = _Combobox.default;
var _Calendar = _interopRequireDefault(Calendar_1);
exports.Calendar = _Calendar.default;
var _DatePicker = _interopRequireDefault(DatePicker_1);
exports.DatePicker = _DatePicker.default;
var _TimePicker = _interopRequireDefault(TimePicker_1);
exports.TimePicker = _TimePicker.default;
var _DateTimePicker = _interopRequireDefault(DateTimePicker_1);
exports.DateTimePicker = _DateTimePicker.default;
var _NumberPicker = _interopRequireDefault(NumberPicker_1);
exports.NumberPicker = _NumberPicker.default;
var _Multiselect = _interopRequireDefault(Multiselect_1);
exports.Multiselect = _Multiselect.default;
var _SelectList = _interopRequireDefault(SelectList_1);
exports.SelectList = _SelectList.default;
var _SlideTransitionGroup = _interopRequireDefault(SlideTransitionGroup_1);
var _SlideDownTransition = _interopRequireDefault(SlideDownTransition_1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable global-require */
var setLocalizers = _configure.default.setLocalizers,
setDateLocalizer = _configure.default.setDateLocalizer,
setNumberLocalizer = _configure.default.setNumberLocalizer;
exports.setNumberLocalizer = setNumberLocalizer;
exports.setDateLocalizer = setDateLocalizer;
exports.setLocalizers = setLocalizers;
var utils = {
SlideTransitionGroup: _SlideTransitionGroup.default,
SlideDownTransition: _SlideDownTransition.default
};
exports.utils = utils;
});
unwrapExports(lib$2);
var lib_1$1 = lib$2.setNumberLocalizer;
var lib_2$1 = lib$2.setDateLocalizer;
var lib_3$1 = lib$2.setLocalizers;
var lib_4$1 = lib$2.utils;
var lib_5$1 = lib$2.DropdownList;
var lib_6$1 = lib$2.Combobox;
var lib_7 = lib$2.Calendar;
var lib_8 = lib$2.DatePicker;
var lib_9 = lib$2.TimePicker;
var lib_10 = lib$2.DateTimePicker;
var lib_11 = lib$2.NumberPicker;
var lib_12 = lib$2.Multiselect;
var lib_13 = lib$2.SelectList;
/**
* A small, pure function component to render the calendar + time picker combo.
* @param {CalendarTimePickerProps} props
*/
function CalendarTimePicker(props) {
var locale = props.locale,
min = props.min,
max = props.max,
value = props.value,
onDateChange = props.onDateChange,
onTimeChange = props.onTimeChange,
rwProps = props.rwProps;
moment.locale(locale);
momentLocalizer();
return React.createElement(React.Fragment, null, React.createElement(lib_7, _extends_1({
culture: locale,
value: value,
onChange: onDateChange,
min: min,
max: max
}, rwProps)), React.createElement(lib_10, _extends_1({
culture: locale,
value: value,
date: false,
className: "date-range-picker__time",
onChange: onTimeChange,
min: min,
max: max
}, rwProps)));
}
var en = {
OK: "OK",
Cancel: "Cancel",
From: "From",
To: "To",
"Any Time": "Any Time",
Today: "Today",
"Last Week": "Last Week",
"Last Month": "Last Month",
"Last Year": "Last Year",
Custom: "Custom...",
Equals: "Equals",
"Does not equal": "Does not equal",
"Less than": "Less than",
"Less than or equal to": "Less than or equal to",
"Greater than": "Greater than",
"Greater than or equal to": "Greater than or equal to",
Between: "Between",
"Custom Range": "Custom Range",
"Add Field": "Add Field",
Comfortable: "Comfortable",
Cozy: "Cozy",
Compact: "Compact",
Value: "Value",
"And value": "And value",
Filter: "Filter",
Clear: "Clear",
Close: "Close"
};
var es = {
OK: "Aceptar",
Cancel: "Cancelar",
From: "Desde",
To: "Para",
"Any Time": "Cualquier hora",
Today: "Hoy",
"Last Week": "Semana pasada",
"Last Month": "Mes pasado",
"Last Year": "A\xF1o pasado",
Custom: "Personalizar...",
Equals: "Igual a",
"Does not equal": "No es igual a",
"Less than": "Menor que",
"Less than or equal to": "Menor o igual que",
"Greater than": "Mayor que",
"Greater than or equal to": "Mayor o igual que",
Between: "Entre",
"Custom Range": "Intervalo personalizado",
"Add Field": "A\xF1adir campo",
Comfortable: "C\xF3modo",
Cozy: "Estrecho",
Compact: "Compacto",
Value: "Valor",
"And value": "Y un valor",
Filter: "Filtro",
Clear: "Borrar",
Close: "Cerrar"
};
var de = {
OK: "OK",
Cancel: "Abbrechen",
From: "Von",
To: "Bis",
"Any Time": "Jederzeit",
Today: "Heute",
"Last Week": "Letzte Woche",
"Last Month": "Letzter Monat",
"Last Year": "Letztes Jahr",
Custom: "Benutzerdefiniert...",
Equals: "Ist gleich",
"Does not equal": "Ist nicht gleich",
"Less than": "Kleiner als",
"Less than or equal to": "Kleiner oder gleich",
"Greater than": "Gr\xF6\xDFer als",
"Greater than or equal to": "Gr\xF6\xDFer oder gleich",
Between: "Zwischen",
"Custom Range": "Benutzerdefinierter Bereich",
"Add Field": "Feld hinzuf\xFCgen",
Comfortable: "Komfortabel",
Cozy: "Bequem",
Compact: "Kompakt",
Value: "Wert",
"And value": "Und Wert",
Filter: "Filtern",
Clear: "L\xF6schen",
Close: "Schlie\xDFen"
};
var fr = {
OK: "OK",
Cancel: "Annuler",
From: "De\xA0",
To: "\xC0\xA0",
"Any Time": "\xC0 tout moment",
Today: "Aujourd'hui",
"Last Week": "La semaine derni\xE8re",
"Last Month": "Le mois dernier",
"Last Year": "L'ann\xE9e derni\xE8re",
Custom: "Personnaliser\u2026",
Equals: "Est \xE9gal \xE0",
"Does not equal": "Pas \xE9gal \xE0",
"Less than": "Inf\xE9rieur \xE0",
"Less than or equal to": "Inf\xE9rieur ou \xE9gal \xE0",
"Greater than": "Sup\xE9rieur \xE0",
"Greater than or equal to": "Sup\xE9rieur ou \xE9gal \xE0",
Between: "Entre",
"Custom Range": "Plage personnalis\xE9e",
"Add Field": "Ajouter un champ",
Comfortable: "Confortable",
Cozy: "Conviviale",
Compact: "Compacte",
Value: "Valeur",
"And value": "Et la valeur",
Filter: "Filtre",
Clear: "Effacer",
Close: "Fermer"
};
var ko = {
OK: "\uD655\uC778",
Cancel: "\uCDE8\uC18C",
From: "\uBCF4\uB0B4\uB294 \uC0AC\uB78C",
To: "\uBC1B\uB294 \uC0AC\uB78C",
"Any Time": "\uC784\uC758\uC758 \uC2DC\uAC04",
Today: "\uC624\uB298",
"Last Week": "\uC9C0\uB09C \uC8FC",
"Last Month": "\uC9C0\uB09C \uB2EC",
"Last Year": "\uC791\uB144",
Custom: "\uC0AC\uC6A9\uC790 \uC9C0\uC815...",
Equals: "\uAC19\uC74C",
"Does not equal": "\uAC19\uC9C0 \uC54A\uC74C",
"Less than": "\uB2E4\uC74C\uBCF4\uB2E4 \uC791\uC74C",
"Less than or equal to": "\uC791\uAC70\uB098 \uAC19\uC74C",
"Greater than": "\uB2E4\uC74C\uBCF4\uB2E4 \uD07C",
"Greater than or equal to": "\uD06C\uAC70\uB098 \uAC19\uC74C",
Between: "\uBC94\uC704",
"Custom Range": "\uC0AC\uC6A9\uC790 \uC9C0\uC815 \uBC94\uC704",
"Add Field": "\uD544\uB4DC \uCD94\uAC00",
Comfortable: "\uD3B8\uB9AC\uD55C",
Cozy: "\uC548\uB77D\uD55C",
Compact: "\uC555\uCD95",
Value: "\uAC12",
"And value": "\uBC0F \uAC12",
Filter: "\uD544\uD130",
Clear: "\uC9C0\uC6B0\uAE30",
Close: "\uB2EB\uAE30"
};
var ja = {
OK: "OK",
Cancel: "\u30AD\u30E3\u30F3\u30BB\u30EB",
From: "\u30EA\u30F3\u30AF\u5143",
To: "\u30EA\u30F3\u30AF\u5148",
"Any Time": "\u4EFB\u610F\u306E\u6642\u523B",
Today: "\u4ECA\u65E5",
"Last Week": "\u5148\u9031",
"Last Month": "\u5148\u6708",
"Last Year": "\u6628\u5E74",
Custom: "\u30AB\u30B9\u30BF\u30E0\u2026",
Equals: "\u6B21\u306E\u5024\u306B\u7B49\u3057\u3044",
"Does not equal": "\u6B21\u306E\u5024\u306B\u7B49\u3057\u304F\u306A\u3044",
"Less than": "\u6B21\u306E\u5024\u3088\u308A\u5C0F\u3055\u3044",
"Less than or equal to": "\u6B21\u306E\u5024\u3088\u308A\u5C0F\u3055\u3044\u304B\u7B49\u3057\u3044",
"Greater than": "\u6B21\u306E\u5024\u3088\u308A\u5927\u304D\u3044",
"Greater than or equal to": "\u6B21\u306E\u5024\u4EE5\u4E0A",
Between: "\u671F\u9593",
"Custom Range": "\u30AB\u30B9\u30BF\u30E0\u7BC4\u56F2",
"Add Field": "\u30D5\u30A3\u30FC\u30EB\u30C9\u306E\u8FFD\u52A0",
Comfortable: "\u30B3\u30F3\u30D1\u30AF\u30C8",
Cozy: "\u9069\u5EA6",
Compact: "\u5341\u5206",
Value: "\u5024",
"And value": "\u5024\u306E\u8FFD\u52A0",
Filter: "\u30D5\u30A3\u30EB\u30BF",
Clear: "\u30AF\u30EA\u30A2",
Close: "\u9589\u3058\u308B"
};
var ru = {
OK: "\u041E\u041A",
Cancel: "\u041E\u0442\u043C\u0435\u043D\u0430",
From: "\u041E\u0442",
To: "\u0414\u043E",
"Any Time": "\u0412 \u043B\u044E\u0431\u043E\u0435 \u0432\u0440\u0435\u043C\u044F",
Today: "\u0421\u0435\u0433\u043E\u0434\u043D\u044F",
"Last Week": "\u0417\u0430 \u043F\u043E\u0441\u043B\u0435\u0434\u043D\u044E\u044E \u043D\u0435\u0434\u0435\u043B\u044E",
"Last Month": "\u0417\u0430 \u043F\u043E\u0441\u043B\u0435\u0434\u043D\u0438\u0439 \u043C\u0435\u0441\u044F\u0446",
"Last Year": "\u0417\u0430 \u043F\u043E\u0441\u043B\u0435\u0434\u043D\u0438\u0439 \u0433\u043E\u0434",
Custom: "\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0430\u044F...",
Equals: "\u0420\u0430\u0432\u043D\u043E",
"Does not equal": "\u041D\u0435 \u0440\u0430\u0432\u043D\u043E",
"Less than": "\u041C\u0435\u043D\u044C\u0448\u0435 \u0447\u0435\u043C",
"Less than or equal to": "\u041C\u0435\u043D\u044C\u0448\u0435 \u0438\u043B\u0438 \u0440\u0430\u0432\u043D\u043E",
"Greater than": "\u0411\u043E\u043B\u044C\u0448\u0435 \u0447\u0435\u043C",
"Greater than or equal to": "\u0411\u043E\u043B\u044C\u0448\u0435 \u0438\u043B\u0438 \u0440\u0430\u0432\u043D\u043E",
Between: "\u041C\u0435\u0436\u0434\u0443",
"Custom Range": "\u041D\u0430\u0441\u0442\u0440\u0430\u0438\u0432\u0430\u0435\u043C\u044B\u0439 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",
"Add Field": "\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u043F\u043E\u043B\u0435",
Comfortable: "\u0423\u0434\u043E\u0431\u043D\u043E",
Cozy: "\u0423\u044E\u0442\u043D\u043E",
Compact: "\u041A\u043E\u043C\u043F\u0430\u043A\u0442\u043D\u044B\u0439",
Value: "\u0417\u043D\u0430\u0447\u0435\u043D\u0438\u0435",
"And value": "\u0418 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435",
Filter: "\u0424\u0438\u043B\u044C\u0442\u0440",
Clear: "\u041E\u0447\u0438\u0441\u0442\u0438\u0442\u044C",
Close: "\u043A\u043E\u043D\u0435\u0446"
};
var pt_BR = {
OK: "OK",
Cancel: "Cancelar",
From: "De",
To: "Para",
"Any Time": "Qualquer Hora",
Today: "Hoje",
"Last Week": "\xDAltima Semana",
"Last Month": "\xDAltimo M\xEAs",
"Last Year": "Ano Passado",
Custom: "Personalizado...",
Equals: "Igual a",
"Does not equal": "Dose n\xE3o \xE9 igual",
"Less than": "Menor que",
"Less than or equal to": "Menor que ou igual a",
"Greater than": "Maior que",
"Greater than or equal to": "Maior que ou igual a",
Between: "Entre",
"Custom Range": "Intervalo personalizado",
"Add Field": "Adicionar Campo",
Comfortable: "Confort\xE1vel",
Cozy: "Acolhedora",
Compact: "Compacta",
Value: "Valor",
"And value": "E valor",
Filter: "Filtro",
Clear: "Limpar",
Close: "Fechar"
};
var zh_CN = {
OK: "\u786E\u5B9A",
Cancel: "\u53D6\u6D88",
From: "\u4ECE",
To: "\u5230",
"Any Time": "\u4EFB\u4F55\u65F6\u95F4",
Today: "\u4ECA\u5929",
"Last Week": "\u4E0A\u5468",
"Last Month": "\u4E0A\u6708",
"Last Year": "\u4E0A\u5E74\u5EA6",
Custom: "\u81EA\u5B9A\u4E49...",
Equals: "\u7B49\u4E8E",
"Does not equal": "\u4E0D\u7B49\u4E8E",
"Less than": "\u5C0F\u4E8E",
"Less than or equal to": "\u5C0F\u4E8E\u6216\u7B49\u4E8E",
"Greater than": "\u5927\u4E8E",
"Greater than or equal to": "\u5927\u4E8E\u6216\u7B49\u4E8E",
Between: "\u4E4B\u95F4",
"Custom Range": "\u81EA\u5B9A\u4E49\u8303\u56F4",
"Add Field": "\u6DFB\u52A0\u5B57\u6BB5",
Comfortable: "\u8212\u670D",
Cozy: "\u8212\u9002",
Compact: "\u538B\u7F29",
Value: "\u503C",
"And value": "\u548C\u503C",
Filter: "\u7B5B\u9009\u5668",
Clear: "\u6E05\u9664",
Close: "\u5173\u95ED"
};
var index$6 = {
en: en,
es: es,
de: de,
fr: fr,
ko: ko,
ja: ja,
ru: ru,
pt_BR: pt_BR,
zh_CN: zh_CN
};
var files = /*#__PURE__*/Object.freeze({
default: index$6,
en: en,
es: es,
de: de,
fr: fr,
ko: ko,
ja: ja,
ru: ru,
pt_BR: pt_BR,
zh_CN: zh_CN
});
var he = createCommonjsModule(function (module, exports) {
(function(root) {
// Detect free variables `exports`.
var freeExports = exports;
// Detect free variable `module`.
var freeModule = module &&
module.exports == freeExports && module;
// Detect free variable `global`, from Node.js or Browserified code,
// and use it as `root`.
var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal;
if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
root = freeGlobal;
}
/*--------------------------------------------------------------------------*/
// All astral symbols.
var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
// All ASCII symbols (not just printable ASCII) except those listed in the
// first column of the overrides table.
// https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides
var regexAsciiWhitelist = /[\x01-\x7F]/g;
// All BMP symbols that are not ASCII newlines, printable ASCII symbols, or
// code points listed in the first column of the overrides table on
// https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides.
var regexBmpWhitelist = /[\x01-\t\x0B\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g;
var regexEncodeNonAscii = /<\u20D2|=\u20E5|>\u20D2|\u205F\u200A|\u219D\u0338|\u2202\u0338|\u2220\u20D2|\u2229\uFE00|\u222A\uFE00|\u223C\u20D2|\u223D\u0331|\u223E\u0333|\u2242\u0338|\u224B\u0338|\u224D\u20D2|\u224E\u0338|\u224F\u0338|\u2250\u0338|\u2261\u20E5|\u2264\u20D2|\u2265\u20D2|\u2266\u0338|\u2267\u0338|\u2268\uFE00|\u2269\uFE00|\u226A\u0338|\u226A\u20D2|\u226B\u0338|\u226B\u20D2|\u227F\u0338|\u2282\u20D2|\u2283\u20D2|\u228A\uFE00|\u228B\uFE00|\u228F\u0338|\u2290\u0338|\u2293\uFE00|\u2294\uFE00|\u22B4\u20D2|\u22B5\u20D2|\u22D8\u0338|\u22D9\u0338|\u22DA\uFE00|\u22DB\uFE00|\u22F5\u0338|\u22F9\u0338|\u2933\u0338|\u29CF\u0338|\u29D0\u0338|\u2A6D\u0338|\u2A70\u0338|\u2A7D\u0338|\u2A7E\u0338|\u2AA1\u0338|\u2AA2\u0338|\u2AAC\uFE00|\u2AAD\uFE00|\u2AAF\u0338|\u2AB0\u0338|\u2AC5\u0338|\u2AC6\u0338|\u2ACB\uFE00|\u2ACC\uFE00|\u2AFD\u20E5|[\xA0-\u0113\u0116-\u0122\u0124-\u012B\u012E-\u014D\u0150-\u017E\u0192\u01B5\u01F5\u0237\u02C6\u02C7\u02D8-\u02DD\u0311\u0391-\u03A1\u03A3-\u03A9\u03B1-\u03C9\u03D1\u03D2\u03D5\u03D6\u03DC\u03DD\u03F0\u03F1\u03F5\u03F6\u0401-\u040C\u040E-\u044F\u0451-\u045C\u045E\u045F\u2002-\u2005\u2007-\u2010\u2013-\u2016\u2018-\u201A\u201C-\u201E\u2020-\u2022\u2025\u2026\u2030-\u2035\u2039\u203A\u203E\u2041\u2043\u2044\u204F\u2057\u205F-\u2063\u20AC\u20DB\u20DC\u2102\u2105\u210A-\u2113\u2115-\u211E\u2122\u2124\u2127-\u2129\u212C\u212D\u212F-\u2131\u2133-\u2138\u2145-\u2148\u2153-\u215E\u2190-\u219B\u219D-\u21A7\u21A9-\u21AE\u21B0-\u21B3\u21B5-\u21B7\u21BA-\u21DB\u21DD\u21E4\u21E5\u21F5\u21FD-\u2205\u2207-\u2209\u220B\u220C\u220F-\u2214\u2216-\u2218\u221A\u221D-\u2238\u223A-\u2257\u2259\u225A\u225C\u225F-\u2262\u2264-\u228B\u228D-\u229B\u229D-\u22A5\u22A7-\u22B0\u22B2-\u22BB\u22BD-\u22DB\u22DE-\u22E3\u22E6-\u22F7\u22F9-\u22FE\u2305\u2306\u2308-\u2310\u2312\u2313\u2315\u2316\u231C-\u231F\u2322\u2323\u232D\u232E\u2336\u233D\u233F\u237C\u23B0\u23B1\u23B4-\u23B6\u23DC-\u23DF\u23E2\u23E7\u2423\u24C8\u2500\u2502\u250C\u2510\u2514\u2518\u251C\u2524\u252C\u2534\u253C\u2550-\u256C\u2580\u2584\u2588\u2591-\u2593\u25A1\u25AA\u25AB\u25AD\u25AE\u25B1\u25B3-\u25B5\u25B8\u25B9\u25BD-\u25BF\u25C2\u25C3\u25CA\u25CB\u25EC\u25EF\u25F8-\u25FC\u2605\u2606\u260E\u2640\u2642\u2660\u2663\u2665\u2666\u266A\u266D-\u266F\u2713\u2717\u2720\u2736\u2758\u2772\u2773\u27C8\u27C9\u27E6-\u27ED\u27F5-\u27FA\u27FC\u27FF\u2902-\u2905\u290C-\u2913\u2916\u2919-\u2920\u2923-\u292A\u2933\u2935-\u2939\u293C\u293D\u2945\u2948-\u294B\u294E-\u2976\u2978\u2979\u297B-\u297F\u2985\u2986\u298B-\u2996\u299A\u299C\u299D\u29A4-\u29B7\u29B9\u29BB\u29BC\u29BE-\u29C5\u29C9\u29CD-\u29D0\u29DC-\u29DE\u29E3-\u29E5\u29EB\u29F4\u29F6\u2A00-\u2A02\u2A04\u2A06\u2A0C\u2A0D\u2A10-\u2A17\u2A22-\u2A27\u2A29\u2A2A\u2A2D-\u2A31\u2A33-\u2A3C\u2A3F\u2A40\u2A42-\u2A4D\u2A50\u2A53-\u2A58\u2A5A-\u2A5D\u2A5F\u2A66\u2A6A\u2A6D-\u2A75\u2A77-\u2A9A\u2A9D-\u2AA2\u2AA4-\u2AB0\u2AB3-\u2AC8\u2ACB\u2ACC\u2ACF-\u2ADB\u2AE4\u2AE6-\u2AE9\u2AEB-\u2AF3\u2AFD\uFB00-\uFB04]|\uD835[\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDCCF\uDD04\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDD6B]/g;
var encodeMap = {'\xAD':'shy','\u200C':'zwnj','\u200D':'zwj','\u200E':'lrm','\u2063':'ic','\u2062':'it','\u2061':'af','\u200F':'rlm','\u200B':'ZeroWidthSpace','\u2060':'NoBreak','\u0311':'DownBreve','\u20DB':'tdot','\u20DC':'DotDot','\t':'Tab','\n':'NewLine','\u2008':'puncsp','\u205F':'MediumSpace','\u2009':'thinsp','\u200A':'hairsp','\u2004':'emsp13','\u2002':'ensp','\u2005':'emsp14','\u2003':'emsp','\u2007':'numsp','\xA0':'nbsp','\u205F\u200A':'ThickSpace','\u203E':'oline','_':'lowbar','\u2010':'dash','\u2013':'ndash','\u2014':'mdash','\u2015':'horbar',',':'comma',';':'semi','\u204F':'bsemi',':':'colon','\u2A74':'Colone','!':'excl','\xA1':'iexcl','?':'quest','\xBF':'iquest','.':'period','\u2025':'nldr','\u2026':'mldr','\xB7':'middot','\'':'apos','\u2018':'lsquo','\u2019':'rsquo','\u201A':'sbquo','\u2039':'lsaquo','\u203A':'rsaquo','"':'quot','\u201C':'ldquo','\u201D':'rdquo','\u201E':'bdquo','\xAB':'laquo','\xBB':'raquo','(':'lpar',')':'rpar','[':'lsqb',']':'rsqb','{':'lcub','}':'rcub','\u2308':'lceil','\u2309':'rceil','\u230A':'lfloor','\u230B':'rfloor','\u2985':'lopar','\u2986':'ropar','\u298B':'lbrke','\u298C':'rbrke','\u298D':'lbrkslu','\u298E':'rbrksld','\u298F':'lbrksld','\u2990':'rbrkslu','\u2991':'langd','\u2992':'rangd','\u2993':'lparlt','\u2994':'rpargt','\u2995':'gtlPar','\u2996':'ltrPar','\u27E6':'lobrk','\u27E7':'robrk','\u27E8':'lang','\u27E9':'rang','\u27EA':'Lang','\u27EB':'Rang','\u27EC':'loang','\u27ED':'roang','\u2772':'lbbrk','\u2773':'rbbrk','\u2016':'Vert','\xA7':'sect','\xB6':'para','@':'commat','*':'ast','/':'sol','undefined':null,'&':'amp','#':'num','%':'percnt','\u2030':'permil','\u2031':'pertenk','\u2020':'dagger','\u2021':'Dagger','\u2022':'bull','\u2043':'hybull','\u2032':'prime','\u2033':'Prime','\u2034':'tprime','\u2057':'qprime','\u2035':'bprime','\u2041':'caret','`':'grave','\xB4':'acute','\u02DC':'tilde','^':'Hat','\xAF':'macr','\u02D8':'breve','\u02D9':'dot','\xA8':'die','\u02DA':'ring','\u02DD':'dblac','\xB8':'cedil','\u02DB':'ogon','\u02C6':'circ','\u02C7':'caron','\xB0':'deg','\xA9':'copy','\xAE':'reg','\u2117':'copysr','\u2118':'wp','\u211E':'rx','\u2127':'mho','\u2129':'iiota','\u2190':'larr','\u219A':'nlarr','\u2192':'rarr','\u219B':'nrarr','\u2191':'uarr','\u2193':'darr','\u2194':'harr','\u21AE':'nharr','\u2195':'varr','\u2196':'nwarr','\u2197':'nearr','\u2198':'searr','\u2199':'swarr','\u219D':'rarrw','\u219D\u0338':'nrarrw','\u219E':'Larr','\u219F':'Uarr','\u21A0':'Rarr','\u21A1':'Darr','\u21A2':'larrtl','\u21A3':'rarrtl','\u21A4':'mapstoleft','\u21A5':'mapstoup','\u21A6':'map','\u21A7':'mapstodown','\u21A9':'larrhk','\u21AA':'rarrhk','\u21AB':'larrlp','\u21AC':'rarrlp','\u21AD':'harrw','\u21B0':'lsh','\u21B1':'rsh','\u21B2':'ldsh','\u21B3':'rdsh','\u21B5':'crarr','\u21B6':'cularr','\u21B7':'curarr','\u21BA':'olarr','\u21BB':'orarr','\u21BC':'lharu','\u21BD':'lhard','\u21BE':'uharr','\u21BF':'uharl','\u21C0':'rharu','\u21C1':'rhard','\u21C2':'dharr','\u21C3':'dharl','\u21C4':'rlarr','\u21C5':'udarr','\u21C6':'lrarr','\u21C7':'llarr','\u21C8':'uuarr','\u21C9':'rrarr','\u21CA':'ddarr','\u21CB':'lrhar','\u21CC':'rlhar','\u21D0':'lArr','\u21CD':'nlArr','\u21D1':'uArr','\u21D2':'rArr','\u21CF':'nrArr','\u21D3':'dArr','\u21D4':'iff','\u21CE':'nhArr','\u21D5':'vArr','\u21D6':'nwArr','\u21D7':'neArr','\u21D8':'seArr','\u21D9':'swArr','\u21DA':'lAarr','\u21DB':'rAarr','\u21DD':'zigrarr','\u21E4':'larrb','\u21E5':'rarrb','\u21F5':'duarr','\u21FD':'loarr','\u21FE':'roarr','\u21FF':'hoarr','\u2200':'forall','\u2201':'comp','\u2202':'part','\u2202\u0338':'npart','\u2203':'exist','\u2204':'nexist','\u2205':'empty','\u2207':'Del','\u2208':'in','\u2209':'notin','\u220B':'ni','\u220C':'notni','\u03F6':'bepsi','\u220F':'prod','\u2210':'coprod','\u2211':'sum','+':'plus','\xB1':'pm','\xF7':'div','\xD7':'times','<':'lt','\u226E':'nlt','<\u20D2':'nvlt','=':'equals','\u2260':'ne','=\u20E5':'bne','\u2A75':'Equal','>':'gt','\u226F':'ngt','>\u20D2':'nvgt','\xAC':'not','|':'vert','\xA6':'brvbar','\u2212':'minus','\u2213':'mp','\u2214':'plusdo','\u2044':'frasl','\u2216':'setmn','\u2217':'lowast','\u2218':'compfn','\u221A':'Sqrt','\u221D':'prop','\u221E':'infin','\u221F':'angrt','\u2220':'ang','\u2220\u20D2':'nang','\u2221':'angmsd','\u2222':'angsph','\u2223':'mid','\u2224':'nmid','\u2225':'par','\u2226':'npar','\u2227':'and','\u2228':'or','\u2229':'cap','\u2229\uFE00':'caps','\u222A':'cup','\u222A\uFE00':'cups','\u222B':'int','\u222C':'Int','\u222D':'tint','\u2A0C':'qint','\u222E':'oint','\u222F':'Conint','\u2230':'Cconint','\u2231':'cwint','\u2232':'cwconint','\u2233':'awconint','\u2234':'there4','\u2235':'becaus','\u2236':'ratio','\u2237':'Colon','\u2238':'minusd','\u223A':'mDDot','\u223B':'homtht','\u223C':'sim','\u2241':'nsim','\u223C\u20D2':'nvsim','\u223D':'bsim','\u223D\u0331':'race','\u223E':'ac','\u223E\u0333':'acE','\u223F':'acd','\u2240':'wr','\u2242':'esim','\u2242\u0338':'nesim','\u2243':'sime','\u2244':'nsime','\u2245':'cong','\u2247':'ncong','\u2246':'simne','\u2248':'ap','\u2249':'nap','\u224A':'ape','\u224B':'apid','\u224B\u0338':'napid','\u224C':'bcong','\u224D':'CupCap','\u226D':'NotCupCap','\u224D\u20D2':'nvap','\u224E':'bump','\u224E\u0338':'nbump','\u224F':'bumpe','\u224F\u0338':'nbumpe','\u2250':'doteq','\u2250\u0338':'nedot','\u2251':'eDot','\u2252':'efDot','\u2253':'erDot','\u2254':'colone','\u2255':'ecolon','\u2256':'ecir','\u2257':'cire','\u2259':'wedgeq','\u225A':'veeeq','\u225C':'trie','\u225F':'equest','\u2261':'equiv','\u2262':'nequiv','\u2261\u20E5':'bnequiv','\u2264':'le','\u2270':'nle','\u2264\u20D2':'nvle','\u2265':'ge','\u2271':'nge','\u2265\u20D2':'nvge','\u2266':'lE','\u2266\u0338':'nlE','\u2267':'gE','\u2267\u0338':'ngE','\u2268\uFE00':'lvnE','\u2268':'lnE','\u2269':'gnE','\u2269\uFE00':'gvnE','\u226A':'ll','\u226A\u0338':'nLtv','\u226A\u20D2':'nLt','\u226B':'gg','\u226B\u0338':'nGtv','\u226B\u20D2':'nGt','\u226C':'twixt','\u2272':'lsim','\u2274':'nlsim','\u2273':'gsim','\u2275':'ngsim','\u2276':'lg','\u2278':'ntlg','\u2277':'gl','\u2279':'ntgl','\u227A':'pr','\u2280':'npr','\u227B':'sc','\u2281':'nsc','\u227C':'prcue','\u22E0':'nprcue','\u227D':'sccue','\u22E1':'nsccue','\u227E':'prsim','\u227F':'scsim','\u227F\u0338':'NotSucceedsTilde','\u2282':'sub','\u2284':'nsub','\u2282\u20D2':'vnsub','\u2283':'sup','\u2285':'nsup','\u2283\u20D2':'vnsup','\u2286':'sube','\u2288':'nsube','\u2287':'supe','\u2289':'nsupe','\u228A\uFE00':'vsubne','\u228A':'subne','\u228B\uFE00':'vsupne','\u228B':'supne','\u228D':'cupdot','\u228E':'uplus','\u228F':'sqsub','\u228F\u0338':'NotSquareSubset','\u2290':'sqsup','\u2290\u0338':'NotSquareSuperset','\u2291':'sqsube','\u22E2':'nsqsube','\u2292':'sqsupe','\u22E3':'nsqsupe','\u2293':'sqcap','\u2293\uFE00':'sqcaps','\u2294':'sqcup','\u2294\uFE00':'sqcups','\u2295':'oplus','\u2296':'ominus','\u2297':'otimes','\u2298':'osol','\u2299':'odot','\u229A':'ocir','\u229B':'oast','\u229D':'odash','\u229E':'plusb','\u229F':'minusb','\u22A0':'timesb','\u22A1':'sdotb','\u22A2':'vdash','\u22AC':'nvdash','\u22A3':'dashv','\u22A4':'top','\u22A5':'bot','\u22A7':'models','\u22A8':'vDash','\u22AD':'nvDash','\u22A9':'Vdash','\u22AE':'nVdash','\u22AA':'Vvdash','\u22AB':'VDash','\u22AF':'nVDash','\u22B0':'prurel','\u22B2':'vltri','\u22EA':'nltri','\u22B3':'vrtri','\u22EB':'nrtri','\u22B4':'ltrie','\u22EC':'nltrie','\u22B4\u20D2':'nvltrie','\u22B5':'rtrie','\u22ED':'nrtrie','\u22B5\u20D2':'nvrtrie','\u22B6':'origof','\u22B7':'imof','\u22B8':'mumap','\u22B9':'hercon','\u22BA':'intcal','\u22BB':'veebar','\u22BD':'barvee','\u22BE':'angrtvb','\u22BF':'lrtri','\u22C0':'Wedge','\u22C1':'Vee','\u22C2':'xcap','\u22C3':'xcup','\u22C4':'diam','\u22C5':'sdot','\u22C6':'Star','\u22C7':'divonx','\u22C8':'bowtie','\u22C9':'ltimes','\u22CA':'rtimes','\u22CB':'lthree','\u22CC':'rthree','\u22CD':'bsime','\u22CE':'cuvee','\u22CF':'cuwed','\u22D0':'Sub','\u22D1':'Sup','\u22D2':'Cap','\u22D3':'Cup','\u22D4':'fork','\u22D5':'epar','\u22D6':'ltdot','\u22D7':'gtdot','\u22D8':'Ll','\u22D8\u0338':'nLl','\u22D9':'Gg','\u22D9\u0338':'nGg','\u22DA\uFE00':'lesg','\u22DA':'leg','\u22DB':'gel','\u22DB\uFE00':'gesl','\u22DE':'cuepr','\u22DF':'cuesc','\u22E6':'lnsim','\u22E7':'gnsim','\u22E8':'prnsim','\u22E9':'scnsim','\u22EE':'vellip','\u22EF':'ctdot','\u22F0':'utdot','\u22F1':'dtdot','\u22F2':'disin','\u22F3':'isinsv','\u22F4':'isins','\u22F5':'isindot','\u22F5\u0338':'notindot','\u22F6':'notinvc','\u22F7':'notinvb','\u22F9':'isinE','\u22F9\u0338':'notinE','\u22FA':'nisd','\u22FB':'xnis','\u22FC':'nis','\u22FD':'notnivc','\u22FE':'notnivb','\u2305':'barwed','\u2306':'Barwed','\u230C':'drcrop','\u230D':'dlcrop','\u230E':'urcrop','\u230F':'ulcrop','\u2310':'bnot','\u2312':'profline','\u2313':'profsurf','\u2315':'telrec','\u2316':'target','\u231C':'ulcorn','\u231D':'urcorn','\u231E':'dlcorn','\u231F':'drcorn','\u2322':'frown','\u2323':'smile','\u232D':'cylcty','\u232E':'profalar','\u2336':'topbot','\u233D':'ovbar','\u233F':'solbar','\u237C':'angzarr','\u23B0':'lmoust','\u23B1':'rmoust','\u23B4':'tbrk','\u23B5':'bbrk','\u23B6':'bbrktbrk','\u23DC':'OverParenthesis','\u23DD':'UnderParenthesis','\u23DE':'OverBrace','\u23DF':'UnderBrace','\u23E2':'trpezium','\u23E7':'elinters','\u2423':'blank','\u2500':'boxh','\u2502':'boxv','\u250C':'boxdr','\u2510':'boxdl','\u2514':'boxur','\u2518':'boxul','\u251C':'boxvr','\u2524':'boxvl','\u252C':'boxhd','\u2534':'boxhu','\u253C':'boxvh','\u2550':'boxH','\u2551':'boxV','\u2552':'boxdR','\u2553':'boxDr','\u2554':'boxDR','\u2555':'boxdL','\u2556':'boxDl','\u2557':'boxDL','\u2558':'boxuR','\u2559':'boxUr','\u255A':'boxUR','\u255B':'boxuL','\u255C':'boxUl','\u255D':'boxUL','\u255E':'boxvR','\u255F':'boxVr','\u2560':'boxVR','\u2561':'boxvL','\u2562':'boxVl','\u2563':'boxVL','\u2564':'boxHd','\u2565':'boxhD','\u2566':'boxHD','\u2567':'boxHu','\u2568':'boxhU','\u2569':'boxHU','\u256A':'boxvH','\u256B':'boxVh','\u256C':'boxVH','\u2580':'uhblk','\u2584':'lhblk','\u2588':'block','\u2591':'blk14','\u2592':'blk12','\u2593':'blk34','\u25A1':'squ','\u25AA':'squf','\u25AB':'EmptyVerySmallSquare','\u25AD':'rect','\u25AE':'marker','\u25B1':'fltns','\u25B3':'xutri','\u25B4':'utrif','\u25B5':'utri','\u25B8':'rtrif','\u25B9':'rtri','\u25BD':'xdtri','\u25BE':'dtrif','\u25BF':'dtri','\u25C2':'ltrif','\u25C3':'ltri','\u25CA':'loz','\u25CB':'cir','\u25EC':'tridot','\u25EF':'xcirc','\u25F8':'ultri','\u25F9':'urtri','\u25FA':'lltri','\u25FB':'EmptySmallSquare','\u25FC':'FilledSmallSquare','\u2605':'starf','\u2606':'star','\u260E':'phone','\u2640':'female','\u2642':'male','\u2660':'spades','\u2663':'clubs','\u2665':'hearts','\u2666':'diams','\u266A':'sung','\u2713':'check','\u2717':'cross','\u2720':'malt','\u2736':'sext','\u2758':'VerticalSeparator','\u27C8':'bsolhsub','\u27C9':'suphsol','\u27F5':'xlarr','\u27F6':'xrarr','\u27F7':'xharr','\u27F8':'xlArr','\u27F9':'xrArr','\u27FA':'xhArr','\u27FC':'xmap','\u27FF':'dzigrarr','\u2902':'nvlArr','\u2903':'nvrArr','\u2904':'nvHarr','\u2905':'Map','\u290C':'lbarr','\u290D':'rbarr','\u290E':'lBarr','\u290F':'rBarr','\u2910':'RBarr','\u2911':'DDotrahd','\u2912':'UpArrowBar','\u2913':'DownArrowBar','\u2916':'Rarrtl','\u2919':'latail','\u291A':'ratail','\u291B':'lAtail','\u291C':'rAtail','\u291D':'larrfs','\u291E':'rarrfs','\u291F':'larrbfs','\u2920':'rarrbfs','\u2923':'nwarhk','\u2924':'nearhk','\u2925':'searhk','\u2926':'swarhk','\u2927':'nwnear','\u2928':'toea','\u2929':'tosa','\u292A':'swnwar','\u2933':'rarrc','\u2933\u0338':'nrarrc','\u2935':'cudarrr','\u2936':'ldca','\u2937':'rdca','\u2938':'cudarrl','\u2939':'larrpl','\u293C':'curarrm','\u293D':'cularrp','\u2945':'rarrpl','\u2948':'harrcir','\u2949':'Uarrocir','\u294A':'lurdshar','\u294B':'ldrushar','\u294E':'LeftRightVector','\u294F':'RightUpDownVector','\u2950':'DownLeftRightVector','\u2951':'LeftUpDownVector','\u2952':'LeftVectorBar','\u2953':'RightVectorBar','\u2954':'RightUpVectorBar','\u2955':'RightDownVectorBar','\u2956':'DownLeftVectorBar','\u2957':'DownRightVectorBar','\u2958':'LeftUpVectorBar','\u2959':'LeftDownVectorBar','\u295A':'LeftTeeVector','\u295B':'RightTeeVector','\u295C':'RightUpTeeVector','\u295D':'RightDownTeeVector','\u295E':'DownLeftTeeVector','\u295F':'DownRightTeeVector','\u2960':'LeftUpTeeVector','\u2961':'LeftDownTeeVector','\u2962':'lHar','\u2963':'uHar','\u2964':'rHar','\u2965':'dHar','\u2966':'luruhar','\u2967':'ldrdhar','\u2968':'ruluhar','\u2969':'rdldhar','\u296A':'lharul','\u296B':'llhard','\u296C':'rharul','\u296D':'lrhard','\u296E':'udhar','\u296F':'duhar','\u2970':'RoundImplies','\u2971':'erarr','\u2972':'simrarr','\u2973':'larrsim','\u2974':'rarrsim','\u2975':'rarrap','\u2976':'ltlarr','\u2978':'gtrarr','\u2979':'subrarr','\u297B':'suplarr','\u297C':'lfisht','\u297D':'rfisht','\u297E':'ufisht','\u297F':'dfisht','\u299A':'vzigzag','\u299C':'vangrt','\u299D':'angrtvbd','\u29A4':'ange','\u29A5':'range','\u29A6':'dwangle','\u29A7':'uwangle','\u29A8':'angmsdaa','\u29A9':'angmsdab','\u29AA':'angmsdac','\u29AB':'angmsdad','\u29AC':'angmsdae','\u29AD':'angmsdaf','\u29AE':'angmsdag','\u29AF':'angmsdah','\u29B0':'bemptyv','\u29B1':'demptyv','\u29B2':'cemptyv','\u29B3':'raemptyv','\u29B4':'laemptyv','\u29B5':'ohbar','\u29B6':'omid','\u29B7':'opar','\u29B9':'operp','\u29BB':'olcross','\u29BC':'odsold','\u29BE':'olcir','\u29BF':'ofcir','\u29C0':'olt','\u29C1':'ogt','\u29C2':'cirscir','\u29C3':'cirE','\u29C4':'solb','\u29C5':'bsolb','\u29C9':'boxbox','\u29CD':'trisb','\u29CE':'rtriltri','\u29CF':'LeftTriangleBar','\u29CF\u0338':'NotLeftTriangleBar','\u29D0':'RightTriangleBar','\u29D0\u0338':'NotRightTriangleBar','\u29DC':'iinfin','\u29DD':'infintie','\u29DE':'nvinfin','\u29E3':'eparsl','\u29E4':'smeparsl','\u29E5':'eqvparsl','\u29EB':'lozf','\u29F4':'RuleDelayed','\u29F6':'dsol','\u2A00':'xodot','\u2A01':'xoplus','\u2A02':'xotime','\u2A04':'xuplus','\u2A06':'xsqcup','\u2A0D':'fpartint','\u2A10':'cirfnint','\u2A11':'awint','\u2A12':'rppolint','\u2A13':'scpolint','\u2A14':'npolint','\u2A15':'pointint','\u2A16':'quatint','\u2A17':'intlarhk','\u2A22':'pluscir','\u2A23':'plusacir','\u2A24':'simplus','\u2A25':'plusdu','\u2A26':'plussim','\u2A27':'plustwo','\u2A29':'mcomma','\u2A2A':'minusdu','\u2A2D':'loplus','\u2A2E':'roplus','\u2A2F':'Cross','\u2A30':'timesd','\u2A31':'timesbar','\u2A33':'smashp','\u2A34':'lotimes','\u2A35':'rotimes','\u2A36':'otimesas','\u2A37':'Otimes','\u2A38':'odiv','\u2A39':'triplus','\u2A3A':'triminus','\u2A3B':'tritime','\u2A3C':'iprod','\u2A3F':'amalg','\u2A40':'capdot','\u2A42':'ncup','\u2A43':'ncap','\u2A44':'capand','\u2A45':'cupor','\u2A46':'cupcap','\u2A47':'capcup','\u2A48':'cupbrcap','\u2A49':'capbrcup','\u2A4A':'cupcup','\u2A4B':'capcap','\u2A4C':'ccups','\u2A4D':'ccaps','\u2A50':'ccupssm','\u2A53':'And','\u2A54':'Or','\u2A55':'andand','\u2A56':'oror','\u2A57':'orslope','\u2A58':'andslope','\u2A5A':'andv','\u2A5B':'orv','\u2A5C':'andd','\u2A5D':'ord','\u2A5F':'wedbar','\u2A66':'sdote','\u2A6A':'simdot','\u2A6D':'congdot','\u2A6D\u0338':'ncongdot','\u2A6E':'easter','\u2A6F':'apacir','\u2A70':'apE','\u2A70\u0338':'napE','\u2A71':'eplus','\u2A72':'pluse','\u2A73':'Esim','\u2A77':'eDDot','\u2A78':'equivDD','\u2A79':'ltcir','\u2A7A':'gtcir','\u2A7B':'ltquest','\u2A7C':'gtquest','\u2A7D':'les','\u2A7D\u0338':'nles','\u2A7E':'ges','\u2A7E\u0338':'nges','\u2A7F':'lesdot','\u2A80':'gesdot','\u2A81':'lesdoto','\u2A82':'gesdoto','\u2A83':'lesdotor','\u2A84':'gesdotol','\u2A85':'lap','\u2A86':'gap','\u2A87':'lne','\u2A88':'gne','\u2A89':'lnap','\u2A8A':'gnap','\u2A8B':'lEg','\u2A8C':'gEl','\u2A8D':'lsime','\u2A8E':'gsime','\u2A8F':'lsimg','\u2A90':'gsiml','\u2A91':'lgE','\u2A92':'glE','\u2A93':'lesges','\u2A94':'gesles','\u2A95':'els','\u2A96':'egs','\u2A97':'elsdot','\u2A98':'egsdot','\u2A99':'el','\u2A9A':'eg','\u2A9D':'siml','\u2A9E':'simg','\u2A9F':'simlE','\u2AA0':'simgE','\u2AA1':'LessLess','\u2AA1\u0338':'NotNestedLessLess','\u2AA2':'GreaterGreater','\u2AA2\u0338':'NotNestedGreaterGreater','\u2AA4':'glj','\u2AA5':'gla','\u2AA6':'ltcc','\u2AA7':'gtcc','\u2AA8':'lescc','\u2AA9':'gescc','\u2AAA':'smt','\u2AAB':'lat','\u2AAC':'smte','\u2AAC\uFE00':'smtes','\u2AAD':'late','\u2AAD\uFE00':'lates','\u2AAE':'bumpE','\u2AAF':'pre','\u2AAF\u0338':'npre','\u2AB0':'sce','\u2AB0\u0338':'nsce','\u2AB3':'prE','\u2AB4':'scE','\u2AB5':'prnE','\u2AB6':'scnE','\u2AB7':'prap','\u2AB8':'scap','\u2AB9':'prnap','\u2ABA':'scnap','\u2ABB':'Pr','\u2ABC':'Sc','\u2ABD':'subdot','\u2ABE':'supdot','\u2ABF':'subplus','\u2AC0':'supplus','\u2AC1':'submult','\u2AC2':'supmult','\u2AC3':'subedot','\u2AC4':'supedot','\u2AC5':'subE','\u2AC5\u0338':'nsubE','\u2AC6':'supE','\u2AC6\u0338':'nsupE','\u2AC7':'subsim','\u2AC8':'supsim','\u2ACB\uFE00':'vsubnE','\u2ACB':'subnE','\u2ACC\uFE00':'vsupnE','\u2ACC':'supnE','\u2ACF':'csub','\u2AD0':'csup','\u2AD1':'csube','\u2AD2':'csupe','\u2AD3':'subsup','\u2AD4':'supsub','\u2AD5':'subsub','\u2AD6':'supsup','\u2AD7':'suphsub','\u2AD8':'supdsub','\u2AD9':'forkv','\u2ADA':'topfork','\u2ADB':'mlcp','\u2AE4':'Dashv','\u2AE6':'Vdashl','\u2AE7':'Barv','\u2AE8':'vBar','\u2AE9':'vBarv','\u2AEB':'Vbar','\u2AEC':'Not','\u2AED':'bNot','\u2AEE':'rnmid','\u2AEF':'cirmid','\u2AF0':'midcir','\u2AF1':'topcir','\u2AF2':'nhpar','\u2AF3':'parsim','\u2AFD':'parsl','\u2AFD\u20E5':'nparsl','\u266D':'flat','\u266E':'natur','\u266F':'sharp','\xA4':'curren','\xA2':'cent','$':'dollar','\xA3':'pound','\xA5':'yen','\u20AC':'euro','\xB9':'sup1','\xBD':'half','\u2153':'frac13','\xBC':'frac14','\u2155':'frac15','\u2159':'frac16','\u215B':'frac18','\xB2':'sup2','\u2154':'frac23','\u2156':'frac25','\xB3':'sup3','\xBE':'frac34','\u2157':'frac35','\u215C':'frac38','\u2158':'frac45','\u215A':'frac56','\u215D':'frac58','\u215E':'frac78','\uD835\uDCB6':'ascr','\uD835\uDD52':'aopf','\uD835\uDD1E':'afr','\uD835\uDD38':'Aopf','\uD835\uDD04':'Afr','\uD835\uDC9C':'Ascr','\xAA':'ordf','\xE1':'aacute','\xC1':'Aacute','\xE0':'agrave','\xC0':'Agrave','\u0103':'abreve','\u0102':'Abreve','\xE2':'acirc','\xC2':'Acirc','\xE5':'aring','\xC5':'angst','\xE4':'auml','\xC4':'Auml','\xE3':'atilde','\xC3':'Atilde','\u0105':'aogon','\u0104':'Aogon','\u0101':'amacr','\u0100':'Amacr','\xE6':'aelig','\xC6':'AElig','\uD835\uDCB7':'bscr','\uD835\uDD53':'bopf','\uD835\uDD1F':'bfr','\uD835\uDD39':'Bopf','\u212C':'Bscr','\uD835\uDD05':'Bfr','\uD835\uDD20':'cfr','\uD835\uDCB8':'cscr','\uD835\uDD54':'copf','\u212D':'Cfr','\uD835\uDC9E':'Cscr','\u2102':'Copf','\u0107':'cacute','\u0106':'Cacute','\u0109':'ccirc','\u0108':'Ccirc','\u010D':'ccaron','\u010C':'Ccaron','\u010B':'cdot','\u010A':'Cdot','\xE7':'ccedil','\xC7':'Ccedil','\u2105':'incare','\uD835\uDD21':'dfr','\u2146':'dd','\uD835\uDD55':'dopf','\uD835\uDCB9':'dscr','\uD835\uDC9F':'Dscr','\uD835\uDD07':'Dfr','\u2145':'DD','\uD835\uDD3B':'Dopf','\u010F':'dcaron','\u010E':'Dcaron','\u0111':'dstrok','\u0110':'Dstrok','\xF0':'eth','\xD0':'ETH','\u2147':'ee','\u212F':'escr','\uD835\uDD22':'efr','\uD835\uDD56':'eopf','\u2130':'Escr','\uD835\uDD08':'Efr','\uD835\uDD3C':'Eopf','\xE9':'eacute','\xC9':'Eacute','\xE8':'egrave','\xC8':'Egrave','\xEA':'ecirc','\xCA':'Ecirc','\u011B':'ecaron','\u011A':'Ecaron','\xEB':'euml','\xCB':'Euml','\u0117':'edot','\u0116':'Edot','\u0119':'eogon','\u0118':'Eogon','\u0113':'emacr','\u0112':'Emacr','\uD835\uDD23':'ffr','\uD835\uDD57':'fopf','\uD835\uDCBB':'fscr','\uD835\uDD09':'Ffr','\uD835\uDD3D':'Fopf','\u2131':'Fscr','\uFB00':'fflig','\uFB03':'ffilig','\uFB04':'ffllig','\uFB01':'filig','fj':'fjlig','\uFB02':'fllig','\u0192':'fnof','\u210A':'gscr','\uD835\uDD58':'gopf','\uD835\uDD24':'gfr','\uD835\uDCA2':'Gscr','\uD835\uDD3E':'Gopf','\uD835\uDD0A':'Gfr','\u01F5':'gacute','\u011F':'gbreve','\u011E':'Gbreve','\u011D':'gcirc','\u011C':'Gcirc','\u0121':'gdot','\u0120':'Gdot','\u0122':'Gcedil','\uD835\uDD25':'hfr','\u210E':'planckh','\uD835\uDCBD':'hscr','\uD835\uDD59':'hopf','\u210B':'Hscr','\u210C':'Hfr','\u210D':'Hopf','\u0125':'hcirc','\u0124':'Hcirc','\u210F':'hbar','\u0127':'hstrok','\u0126':'Hstrok','\uD835\uDD5A':'iopf','\uD835\uDD26':'ifr','\uD835\uDCBE':'iscr','\u2148':'ii','\uD835\uDD40':'Iopf','\u2110':'Iscr','\u2111':'Im','\xED':'iacute','\xCD':'Iacute','\xEC':'igrave','\xCC':'Igrave','\xEE':'icirc','\xCE':'Icirc','\xEF':'iuml','\xCF':'Iuml','\u0129':'itilde','\u0128':'Itilde','\u0130':'Idot','\u012F':'iogon','\u012E':'Iogon','\u012B':'imacr','\u012A':'Imacr','\u0133':'ijlig','\u0132':'IJlig','\u0131':'imath','\uD835\uDCBF':'jscr','\uD835\uDD5B':'jopf','\uD835\uDD27':'jfr','\uD835\uDCA5':'Jscr','\uD835\uDD0D':'Jfr','\uD835\uDD41':'Jopf','\u0135':'jcirc','\u0134':'Jcirc','\u0237':'jmath','\uD835\uDD5C':'kopf','\uD835\uDCC0':'kscr','\uD835\uDD28':'kfr','\uD835\uDCA6':'Kscr','\uD835\uDD42':'Kopf','\uD835\uDD0E':'Kfr','\u0137':'kcedil','\u0136':'Kcedil','\uD835\uDD29':'lfr','\uD835\uDCC1':'lscr','\u2113':'ell','\uD835\uDD5D':'lopf','\u2112':'Lscr','\uD835\uDD0F':'Lfr','\uD835\uDD43':'Lopf','\u013A':'lacute','\u0139':'Lacute','\u013E':'lcaron','\u013D':'Lcaron','\u013C':'lcedil','\u013B':'Lcedil','\u0142':'lstrok','\u0141':'Lstrok','\u0140':'lmidot','\u013F':'Lmidot','\uD835\uDD2A':'mfr','\uD835\uDD5E':'mopf','\uD835\uDCC2':'mscr','\uD835\uDD10':'Mfr','\uD835\uDD44':'Mopf','\u2133':'Mscr','\uD835\uDD2B':'nfr','\uD835\uDD5F':'nopf','\uD835\uDCC3':'nscr','\u2115':'Nopf','\uD835\uDCA9':'Nscr','\uD835\uDD11':'Nfr','\u0144':'nacute','\u0143':'Nacute','\u0148':'ncaron','\u0147':'Ncaron','\xF1':'ntilde','\xD1':'Ntilde','\u0146':'ncedil','\u0145':'Ncedil','\u2116':'numero','\u014B':'eng','\u014A':'ENG','\uD835\uDD60':'oopf','\uD835\uDD2C':'ofr','\u2134':'oscr','\uD835\uDCAA':'Oscr','\uD835\uDD12':'Ofr','\uD835\uDD46':'Oopf','\xBA':'ordm','\xF3':'oacute','\xD3':'Oacute','\xF2':'ograve','\xD2':'Ograve','\xF4':'ocirc','\xD4':'Ocirc','\xF6':'ouml','\xD6':'Ouml','\u0151':'odblac','\u0150':'Odblac','\xF5':'otilde','\xD5':'Otilde','\xF8':'oslash','\xD8':'Oslash','\u014D':'omacr','\u014C':'Omacr','\u0153':'oelig','\u0152':'OElig','\uD835\uDD2D':'pfr','\uD835\uDCC5':'pscr','\uD835\uDD61':'popf','\u2119':'Popf','\uD835\uDD13':'Pfr','\uD835\uDCAB':'Pscr','\uD835\uDD62':'qopf','\uD835\uDD2E':'qfr','\uD835\uDCC6':'qscr','\uD835\uDCAC':'Qscr','\uD835\uDD14':'Qfr','\u211A':'Qopf','\u0138':'kgreen','\uD835\uDD2F':'rfr','\uD835\uDD63':'ropf','\uD835\uDCC7':'rscr','\u211B':'Rscr','\u211C':'Re','\u211D':'Ropf','\u0155':'racute','\u0154':'Racute','\u0159':'rcaron','\u0158':'Rcaron','\u0157':'rcedil','\u0156':'Rcedil','\uD835\uDD64':'sopf','\uD835\uDCC8':'sscr','\uD835\uDD30':'sfr','\uD835\uDD4A':'Sopf','\uD835\uDD16':'Sfr','\uD835\uDCAE':'Sscr','\u24C8':'oS','\u015B':'sacute','\u015A':'Sacute','\u015D':'scirc','\u015C':'Scirc','\u0161':'scaron','\u0160':'Scaron','\u015F':'scedil','\u015E':'Scedil','\xDF':'szlig','\uD835\uDD31':'tfr','\uD835\uDCC9':'tscr','\uD835\uDD65':'topf','\uD835\uDCAF':'Tscr','\uD835\uDD17':'Tfr','\uD835\uDD4B':'Topf','\u0165':'tcaron','\u0164':'Tcaron','\u0163':'tcedil','\u0162':'Tcedil','\u2122':'trade','\u0167':'tstrok','\u0166':'Tstrok','\uD835\uDCCA':'uscr','\uD835\uDD66':'uopf','\uD835\uDD32':'ufr','\uD835\uDD4C':'Uopf','\uD835\uDD18':'Ufr','\uD835\uDCB0':'Uscr','\xFA':'uacute','\xDA':'Uacute','\xF9':'ugrave','\xD9':'Ugrave','\u016D':'ubreve','\u016C':'Ubreve','\xFB':'ucirc','\xDB':'Ucirc','\u016F':'uring','\u016E':'Uring','\xFC':'uuml','\xDC':'Uuml','\u0171':'udblac','\u0170':'Udblac','\u0169':'utilde','\u0168':'Utilde','\u0173':'uogon','\u0172':'Uogon','\u016B':'umacr','\u016A':'Umacr','\uD835\uDD33':'vfr','\uD835\uDD67':'vopf','\uD835\uDCCB':'vscr','\uD835\uDD19':'Vfr','\uD835\uDD4D':'Vopf','\uD835\uDCB1':'Vscr','\uD835\uDD68':'wopf','\uD835\uDCCC':'wscr','\uD835\uDD34':'wfr','\uD835\uDCB2':'Wscr','\uD835\uDD4E':'Wopf','\uD835\uDD1A':'Wfr','\u0175':'wcirc','\u0174':'Wcirc','\uD835\uDD35':'xfr','\uD835\uDCCD':'xscr','\uD835\uDD69':'xopf','\uD835\uDD4F':'Xopf','\uD835\uDD1B':'Xfr','\uD835\uDCB3':'Xscr','\uD835\uDD36':'yfr','\uD835\uDCCE':'yscr','\uD835\uDD6A':'yopf','\uD835\uDCB4':'Yscr','\uD835\uDD1C':'Yfr','\uD835\uDD50':'Yopf','\xFD':'yacute','\xDD':'Yacute','\u0177':'ycirc','\u0176':'Ycirc','\xFF':'yuml','\u0178':'Yuml','\uD835\uDCCF':'zscr','\uD835\uDD37':'zfr','\uD835\uDD6B':'zopf','\u2128':'Zfr','\u2124':'Zopf','\uD835\uDCB5':'Zscr','\u017A':'zacute','\u0179':'Zacute','\u017E':'zcaron','\u017D':'Zcaron','\u017C':'zdot','\u017B':'Zdot','\u01B5':'imped','\xFE':'thorn','\xDE':'THORN','\u0149':'napos','\u03B1':'alpha','\u0391':'Alpha','\u03B2':'beta','\u0392':'Beta','\u03B3':'gamma','\u0393':'Gamma','\u03B4':'delta','\u0394':'Delta','\u03B5':'epsi','\u03F5':'epsiv','\u0395':'Epsilon','\u03DD':'gammad','\u03DC':'Gammad','\u03B6':'zeta','\u0396':'Zeta','\u03B7':'eta','\u0397':'Eta','\u03B8':'theta','\u03D1':'thetav','\u0398':'Theta','\u03B9':'iota','\u0399':'Iota','\u03BA':'kappa','\u03F0':'kappav','\u039A':'Kappa','\u03BB':'lambda','\u039B':'Lambda','\u03BC':'mu','\xB5':'micro','\u039C':'Mu','\u03BD':'nu','\u039D':'Nu','\u03BE':'xi','\u039E':'Xi','\u03BF':'omicron','\u039F':'Omicron','\u03C0':'pi','\u03D6':'piv','\u03A0':'Pi','\u03C1':'rho','\u03F1':'rhov','\u03A1':'Rho','\u03C3':'sigma','\u03A3':'Sigma','\u03C2':'sigmaf','\u03C4':'tau','\u03A4':'Tau','\u03C5':'upsi','\u03A5':'Upsilon','\u03D2':'Upsi','\u03C6':'phi','\u03D5':'phiv','\u03A6':'Phi','\u03C7':'chi','\u03A7':'Chi','\u03C8':'psi','\u03A8':'Psi','\u03C9':'omega','\u03A9':'ohm','\u0430':'acy','\u0410':'Acy','\u0431':'bcy','\u0411':'Bcy','\u0432':'vcy','\u0412':'Vcy','\u0433':'gcy','\u0413':'Gcy','\u0453':'gjcy','\u0403':'GJcy','\u0434':'dcy','\u0414':'Dcy','\u0452':'djcy','\u0402':'DJcy','\u0435':'iecy','\u0415':'IEcy','\u0451':'iocy','\u0401':'IOcy','\u0454':'jukcy','\u0404':'Jukcy','\u0436':'zhcy','\u0416':'ZHcy','\u0437':'zcy','\u0417':'Zcy','\u0455':'dscy','\u0405':'DScy','\u0438':'icy','\u0418':'Icy','\u0456':'iukcy','\u0406':'Iukcy','\u0457':'yicy','\u0407':'YIcy','\u0439':'jcy','\u0419':'Jcy','\u0458':'jsercy','\u0408':'Jsercy','\u043A':'kcy','\u041A':'Kcy','\u045C':'kjcy','\u040C':'KJcy','\u043B':'lcy','\u041B':'Lcy','\u0459':'ljcy','\u0409':'LJcy','\u043C':'mcy','\u041C':'Mcy','\u043D':'ncy','\u041D':'Ncy','\u045A':'njcy','\u040A':'NJcy','\u043E':'ocy','\u041E':'Ocy','\u043F':'pcy','\u041F':'Pcy','\u0440':'rcy','\u0420':'Rcy','\u0441':'scy','\u0421':'Scy','\u0442':'tcy','\u0422':'Tcy','\u045B':'tshcy','\u040B':'TSHcy','\u0443':'ucy','\u0423':'Ucy','\u045E':'ubrcy','\u040E':'Ubrcy','\u0444':'fcy','\u0424':'Fcy','\u0445':'khcy','\u0425':'KHcy','\u0446':'tscy','\u0426':'TScy','\u0447':'chcy','\u0427':'CHcy','\u045F':'dzcy','\u040F':'DZcy','\u0448':'shcy','\u0428':'SHcy','\u0449':'shchcy','\u0429':'SHCHcy','\u044A':'hardcy','\u042A':'HARDcy','\u044B':'ycy','\u042B':'Ycy','\u044C':'softcy','\u042C':'SOFTcy','\u044D':'ecy','\u042D':'Ecy','\u044E':'yucy','\u042E':'YUcy','\u044F':'yacy','\u042F':'YAcy','\u2135':'aleph','\u2136':'beth','\u2137':'gimel','\u2138':'daleth'};
var regexEscape = /["&'<>`]/g;
var escapeMap = {
'"': '"',
'&': '&',
'\'': ''',
'<': '<',
// See https://mathiasbynens.be/notes/ambiguous-ampersands: in HTML, the
// following is not strictly necessary unless it’s part of a tag or an
// unquoted attribute value. We’re only escaping it to support those
// situations, and for XML support.
'>': '>',
// In Internet Explorer ≤ 8, the backtick character can be used
// to break out of (un)quoted attribute values or HTML comments.
// See http://html5sec.org/#102, http://html5sec.org/#108, and
// http://html5sec.org/#133.
'`': '`'
};
var regexInvalidEntity = /&#(?:[xX][^a-fA-F0-9]|[^0-9xX])/;
var regexInvalidRawCodePoint = /[\0-\x08\x0B\x0E-\x1F\x7F-\x9F\uFDD0-\uFDEF\uFFFE\uFFFF]|[\uD83F\uD87F\uD8BF\uD8FF\uD93F\uD97F\uD9BF\uD9FF\uDA3F\uDA7F\uDABF\uDAFF\uDB3F\uDB7F\uDBBF\uDBFF][\uDFFE\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
var regexDecode = /&(CounterClockwiseContourIntegral|DoubleLongLeftRightArrow|ClockwiseContourIntegral|NotNestedGreaterGreater|NotSquareSupersetEqual|DiacriticalDoubleAcute|NotRightTriangleEqual|NotSucceedsSlantEqual|NotPrecedesSlantEqual|CloseCurlyDoubleQuote|NegativeVeryThinSpace|DoubleContourIntegral|FilledVerySmallSquare|CapitalDifferentialD|OpenCurlyDoubleQuote|EmptyVerySmallSquare|NestedGreaterGreater|DoubleLongRightArrow|NotLeftTriangleEqual|NotGreaterSlantEqual|ReverseUpEquilibrium|DoubleLeftRightArrow|NotSquareSubsetEqual|NotDoubleVerticalBar|RightArrowLeftArrow|NotGreaterFullEqual|NotRightTriangleBar|SquareSupersetEqual|DownLeftRightVector|DoubleLongLeftArrow|leftrightsquigarrow|LeftArrowRightArrow|NegativeMediumSpace|blacktriangleright|RightDownVectorBar|PrecedesSlantEqual|RightDoubleBracket|SucceedsSlantEqual|NotLeftTriangleBar|RightTriangleEqual|SquareIntersection|RightDownTeeVector|ReverseEquilibrium|NegativeThickSpace|longleftrightarrow|Longleftrightarrow|LongLeftRightArrow|DownRightTeeVector|DownRightVectorBar|GreaterSlantEqual|SquareSubsetEqual|LeftDownVectorBar|LeftDoubleBracket|VerticalSeparator|rightleftharpoons|NotGreaterGreater|NotSquareSuperset|blacktriangleleft|blacktriangledown|NegativeThinSpace|LeftDownTeeVector|NotLessSlantEqual|leftrightharpoons|DoubleUpDownArrow|DoubleVerticalBar|LeftTriangleEqual|FilledSmallSquare|twoheadrightarrow|NotNestedLessLess|DownLeftTeeVector|DownLeftVectorBar|RightAngleBracket|NotTildeFullEqual|NotReverseElement|RightUpDownVector|DiacriticalTilde|NotSucceedsTilde|circlearrowright|NotPrecedesEqual|rightharpoondown|DoubleRightArrow|NotSucceedsEqual|NonBreakingSpace|NotRightTriangle|LessEqualGreater|RightUpTeeVector|LeftAngleBracket|GreaterFullEqual|DownArrowUpArrow|RightUpVectorBar|twoheadleftarrow|GreaterEqualLess|downharpoonright|RightTriangleBar|ntrianglerighteq|NotSupersetEqual|LeftUpDownVector|DiacriticalAcute|rightrightarrows|vartriangleright|UpArrowDownArrow|DiacriticalGrave|UnderParenthesis|EmptySmallSquare|LeftUpVectorBar|leftrightarrows|DownRightVector|downharpoonleft|trianglerighteq|ShortRightArrow|OverParenthesis|DoubleLeftArrow|DoubleDownArrow|NotSquareSubset|bigtriangledown|ntrianglelefteq|UpperRightArrow|curvearrowright|vartriangleleft|NotLeftTriangle|nleftrightarrow|LowerRightArrow|NotHumpDownHump|NotGreaterTilde|rightthreetimes|LeftUpTeeVector|NotGreaterEqual|straightepsilon|LeftTriangleBar|rightsquigarrow|ContourIntegral|rightleftarrows|CloseCurlyQuote|RightDownVector|LeftRightVector|nLeftrightarrow|leftharpoondown|circlearrowleft|SquareSuperset|OpenCurlyQuote|hookrightarrow|HorizontalLine|DiacriticalDot|NotLessGreater|ntriangleright|DoubleRightTee|InvisibleComma|InvisibleTimes|LowerLeftArrow|DownLeftVector|NotSubsetEqual|curvearrowleft|trianglelefteq|NotVerticalBar|TildeFullEqual|downdownarrows|NotGreaterLess|RightTeeVector|ZeroWidthSpace|looparrowright|LongRightArrow|doublebarwedge|ShortLeftArrow|ShortDownArrow|RightVectorBar|GreaterGreater|ReverseElement|rightharpoonup|LessSlantEqual|leftthreetimes|upharpoonright|rightarrowtail|LeftDownVector|Longrightarrow|NestedLessLess|UpperLeftArrow|nshortparallel|leftleftarrows|leftrightarrow|Leftrightarrow|LeftRightArrow|longrightarrow|upharpoonleft|RightArrowBar|ApplyFunction|LeftTeeVector|leftarrowtail|NotEqualTilde|varsubsetneqq|varsupsetneqq|RightTeeArrow|SucceedsEqual|SucceedsTilde|LeftVectorBar|SupersetEqual|hookleftarrow|DifferentialD|VerticalTilde|VeryThinSpace|blacktriangle|bigtriangleup|LessFullEqual|divideontimes|leftharpoonup|UpEquilibrium|ntriangleleft|RightTriangle|measuredangle|shortparallel|longleftarrow|Longleftarrow|LongLeftArrow|DoubleLeftTee|Poincareplane|PrecedesEqual|triangleright|DoubleUpArrow|RightUpVector|fallingdotseq|looparrowleft|PrecedesTilde|NotTildeEqual|NotTildeTilde|smallsetminus|Proportional|triangleleft|triangledown|UnderBracket|NotHumpEqual|exponentiale|ExponentialE|NotLessTilde|HilbertSpace|RightCeiling|blacklozenge|varsupsetneq|HumpDownHump|GreaterEqual|VerticalLine|LeftTeeArrow|NotLessEqual|DownTeeArrow|LeftTriangle|varsubsetneq|Intersection|NotCongruent|DownArrowBar|LeftUpVector|LeftArrowBar|risingdotseq|GreaterTilde|RoundImplies|SquareSubset|ShortUpArrow|NotSuperset|quaternions|precnapprox|backepsilon|preccurlyeq|OverBracket|blacksquare|MediumSpace|VerticalBar|circledcirc|circleddash|CircleMinus|CircleTimes|LessGreater|curlyeqprec|curlyeqsucc|diamondsuit|UpDownArrow|Updownarrow|RuleDelayed|Rrightarrow|updownarrow|RightVector|nRightarrow|nrightarrow|eqslantless|LeftCeiling|Equilibrium|SmallCircle|expectation|NotSucceeds|thickapprox|GreaterLess|SquareUnion|NotPrecedes|NotLessLess|straightphi|succnapprox|succcurlyeq|SubsetEqual|sqsupseteq|Proportion|Laplacetrf|ImaginaryI|supsetneqq|NotGreater|gtreqqless|NotElement|ThickSpace|TildeEqual|TildeTilde|Fouriertrf|rmoustache|EqualTilde|eqslantgtr|UnderBrace|LeftVector|UpArrowBar|nLeftarrow|nsubseteqq|subsetneqq|nsupseteqq|nleftarrow|succapprox|lessapprox|UpTeeArrow|upuparrows|curlywedge|lesseqqgtr|varepsilon|varnothing|RightFloor|complement|CirclePlus|sqsubseteq|Lleftarrow|circledast|RightArrow|Rightarrow|rightarrow|lmoustache|Bernoullis|precapprox|mapstoleft|mapstodown|longmapsto|dotsquare|downarrow|DoubleDot|nsubseteq|supsetneq|leftarrow|nsupseteq|subsetneq|ThinSpace|ngeqslant|subseteqq|HumpEqual|NotSubset|triangleq|NotCupCap|lesseqgtr|heartsuit|TripleDot|Leftarrow|Coproduct|Congruent|varpropto|complexes|gvertneqq|LeftArrow|LessTilde|supseteqq|MinusPlus|CircleDot|nleqslant|NotExists|gtreqless|nparallel|UnionPlus|LeftFloor|checkmark|CenterDot|centerdot|Mellintrf|gtrapprox|bigotimes|OverBrace|spadesuit|therefore|pitchfork|rationals|PlusMinus|Backslash|Therefore|DownBreve|backsimeq|backprime|DownArrow|nshortmid|Downarrow|lvertneqq|eqvparsl|imagline|imagpart|infintie|integers|Integral|intercal|LessLess|Uarrocir|intlarhk|sqsupset|angmsdaf|sqsubset|llcorner|vartheta|cupbrcap|lnapprox|Superset|SuchThat|succnsim|succneqq|angmsdag|biguplus|curlyvee|trpezium|Succeeds|NotTilde|bigwedge|angmsdah|angrtvbd|triminus|cwconint|fpartint|lrcorner|smeparsl|subseteq|urcorner|lurdshar|laemptyv|DDotrahd|approxeq|ldrushar|awconint|mapstoup|backcong|shortmid|triangle|geqslant|gesdotol|timesbar|circledR|circledS|setminus|multimap|naturals|scpolint|ncongdot|RightTee|boxminus|gnapprox|boxtimes|andslope|thicksim|angmsdaa|varsigma|cirfnint|rtriltri|angmsdab|rppolint|angmsdac|barwedge|drbkarow|clubsuit|thetasym|bsolhsub|capbrcup|dzigrarr|doteqdot|DotEqual|dotminus|UnderBar|NotEqual|realpart|otimesas|ulcorner|hksearow|hkswarow|parallel|PartialD|elinters|emptyset|plusacir|bbrktbrk|angmsdad|pointint|bigoplus|angmsdae|Precedes|bigsqcup|varkappa|notindot|supseteq|precneqq|precnsim|profalar|profline|profsurf|leqslant|lesdotor|raemptyv|subplus|notnivb|notnivc|subrarr|zigrarr|vzigzag|submult|subedot|Element|between|cirscir|larrbfs|larrsim|lotimes|lbrksld|lbrkslu|lozenge|ldrdhar|dbkarow|bigcirc|epsilon|simrarr|simplus|ltquest|Epsilon|luruhar|gtquest|maltese|npolint|eqcolon|npreceq|bigodot|ddagger|gtrless|bnequiv|harrcir|ddotseq|equivDD|backsim|demptyv|nsqsube|nsqsupe|Upsilon|nsubset|upsilon|minusdu|nsucceq|swarrow|nsupset|coloneq|searrow|boxplus|napprox|natural|asympeq|alefsym|congdot|nearrow|bigstar|diamond|supplus|tritime|LeftTee|nvinfin|triplus|NewLine|nvltrie|nvrtrie|nwarrow|nexists|Diamond|ruluhar|Implies|supmult|angzarr|suplarr|suphsub|questeq|because|digamma|Because|olcross|bemptyv|omicron|Omicron|rotimes|NoBreak|intprod|angrtvb|orderof|uwangle|suphsol|lesdoto|orslope|DownTee|realine|cudarrl|rdldhar|OverBar|supedot|lessdot|supdsub|topfork|succsim|rbrkslu|rbrksld|pertenk|cudarrr|isindot|planckh|lessgtr|pluscir|gesdoto|plussim|plustwo|lesssim|cularrp|rarrsim|Cayleys|notinva|notinvb|notinvc|UpArrow|Uparrow|uparrow|NotLess|dwangle|precsim|Product|curarrm|Cconint|dotplus|rarrbfs|ccupssm|Cedilla|cemptyv|notniva|quatint|frac35|frac38|frac45|frac56|frac58|frac78|tridot|xoplus|gacute|gammad|Gammad|lfisht|lfloor|bigcup|sqsupe|gbreve|Gbreve|lharul|sqsube|sqcups|Gcedil|apacir|llhard|lmidot|Lmidot|lmoust|andand|sqcaps|approx|Abreve|spades|circeq|tprime|divide|topcir|Assign|topbot|gesdot|divonx|xuplus|timesd|gesles|atilde|solbar|SOFTcy|loplus|timesb|lowast|lowbar|dlcorn|dlcrop|softcy|dollar|lparlt|thksim|lrhard|Atilde|lsaquo|smashp|bigvee|thinsp|wreath|bkarow|lsquor|lstrok|Lstrok|lthree|ltimes|ltlarr|DotDot|simdot|ltrPar|weierp|xsqcup|angmsd|sigmav|sigmaf|zeetrf|Zcaron|zcaron|mapsto|vsupne|thetav|cirmid|marker|mcomma|Zacute|vsubnE|there4|gtlPar|vsubne|bottom|gtrarr|SHCHcy|shchcy|midast|midcir|middot|minusb|minusd|gtrdot|bowtie|sfrown|mnplus|models|colone|seswar|Colone|mstpos|searhk|gtrsim|nacute|Nacute|boxbox|telrec|hairsp|Tcedil|nbumpe|scnsim|ncaron|Ncaron|ncedil|Ncedil|hamilt|Scedil|nearhk|hardcy|HARDcy|tcedil|Tcaron|commat|nequiv|nesear|tcaron|target|hearts|nexist|varrho|scedil|Scaron|scaron|hellip|Sacute|sacute|hercon|swnwar|compfn|rtimes|rthree|rsquor|rsaquo|zacute|wedgeq|homtht|barvee|barwed|Barwed|rpargt|horbar|conint|swarhk|roplus|nltrie|hslash|hstrok|Hstrok|rmoust|Conint|bprime|hybull|hyphen|iacute|Iacute|supsup|supsub|supsim|varphi|coprod|brvbar|agrave|Supset|supset|igrave|Igrave|notinE|Agrave|iiiint|iinfin|copysr|wedbar|Verbar|vangrt|becaus|incare|verbar|inodot|bullet|drcorn|intcal|drcrop|cularr|vellip|Utilde|bumpeq|cupcap|dstrok|Dstrok|CupCap|cupcup|cupdot|eacute|Eacute|supdot|iquest|easter|ecaron|Ecaron|ecolon|isinsv|utilde|itilde|Itilde|curarr|succeq|Bumpeq|cacute|ulcrop|nparsl|Cacute|nprcue|egrave|Egrave|nrarrc|nrarrw|subsup|subsub|nrtrie|jsercy|nsccue|Jsercy|kappav|kcedil|Kcedil|subsim|ulcorn|nsimeq|egsdot|veebar|kgreen|capand|elsdot|Subset|subset|curren|aacute|lacute|Lacute|emptyv|ntilde|Ntilde|lagran|lambda|Lambda|capcap|Ugrave|langle|subdot|emsp13|numero|emsp14|nvdash|nvDash|nVdash|nVDash|ugrave|ufisht|nvHarr|larrfs|nvlArr|larrhk|larrlp|larrpl|nvrArr|Udblac|nwarhk|larrtl|nwnear|oacute|Oacute|latail|lAtail|sstarf|lbrace|odblac|Odblac|lbrack|udblac|odsold|eparsl|lcaron|Lcaron|ograve|Ograve|lcedil|Lcedil|Aacute|ssmile|ssetmn|squarf|ldquor|capcup|ominus|cylcty|rharul|eqcirc|dagger|rfloor|rfisht|Dagger|daleth|equals|origof|capdot|equest|dcaron|Dcaron|rdquor|oslash|Oslash|otilde|Otilde|otimes|Otimes|urcrop|Ubreve|ubreve|Yacute|Uacute|uacute|Rcedil|rcedil|urcorn|parsim|Rcaron|Vdashl|rcaron|Tstrok|percnt|period|permil|Exists|yacute|rbrack|rbrace|phmmat|ccaron|Ccaron|planck|ccedil|plankv|tstrok|female|plusdo|plusdu|ffilig|plusmn|ffllig|Ccedil|rAtail|dfisht|bernou|ratail|Rarrtl|rarrtl|angsph|rarrpl|rarrlp|rarrhk|xwedge|xotime|forall|ForAll|Vvdash|vsupnE|preceq|bigcap|frac12|frac13|frac14|primes|rarrfs|prnsim|frac15|Square|frac16|square|lesdot|frac18|frac23|propto|prurel|rarrap|rangle|puncsp|frac25|Racute|qprime|racute|lesges|frac34|abreve|AElig|eqsim|utdot|setmn|urtri|Equal|Uring|seArr|uring|searr|dashv|Dashv|mumap|nabla|iogon|Iogon|sdote|sdotb|scsim|napid|napos|equiv|natur|Acirc|dblac|erarr|nbump|iprod|erDot|ucirc|awint|esdot|angrt|ncong|isinE|scnap|Scirc|scirc|ndash|isins|Ubrcy|nearr|neArr|isinv|nedot|ubrcy|acute|Ycirc|iukcy|Iukcy|xutri|nesim|caret|jcirc|Jcirc|caron|twixt|ddarr|sccue|exist|jmath|sbquo|ngeqq|angst|ccaps|lceil|ngsim|UpTee|delta|Delta|rtrif|nharr|nhArr|nhpar|rtrie|jukcy|Jukcy|kappa|rsquo|Kappa|nlarr|nlArr|TSHcy|rrarr|aogon|Aogon|fflig|xrarr|tshcy|ccirc|nleqq|filig|upsih|nless|dharl|nlsim|fjlig|ropar|nltri|dharr|robrk|roarr|fllig|fltns|roang|rnmid|subnE|subne|lAarr|trisb|Ccirc|acirc|ccups|blank|VDash|forkv|Vdash|langd|cedil|blk12|blk14|laquo|strns|diams|notin|vDash|larrb|blk34|block|disin|uplus|vdash|vBarv|aelig|starf|Wedge|check|xrArr|lates|lbarr|lBarr|notni|lbbrk|bcong|frasl|lbrke|frown|vrtri|vprop|vnsup|gamma|Gamma|wedge|xodot|bdquo|srarr|doteq|ldquo|boxdl|boxdL|gcirc|Gcirc|boxDl|boxDL|boxdr|boxdR|boxDr|TRADE|trade|rlhar|boxDR|vnsub|npart|vltri|rlarr|boxhd|boxhD|nprec|gescc|nrarr|nrArr|boxHd|boxHD|boxhu|boxhU|nrtri|boxHu|clubs|boxHU|times|colon|Colon|gimel|xlArr|Tilde|nsime|tilde|nsmid|nspar|THORN|thorn|xlarr|nsube|nsubE|thkap|xhArr|comma|nsucc|boxul|boxuL|nsupe|nsupE|gneqq|gnsim|boxUl|boxUL|grave|boxur|boxuR|boxUr|boxUR|lescc|angle|bepsi|boxvh|varpi|boxvH|numsp|Theta|gsime|gsiml|theta|boxVh|boxVH|boxvl|gtcir|gtdot|boxvL|boxVl|boxVL|crarr|cross|Cross|nvsim|boxvr|nwarr|nwArr|sqsup|dtdot|Uogon|lhard|lharu|dtrif|ocirc|Ocirc|lhblk|duarr|odash|sqsub|Hacek|sqcup|llarr|duhar|oelig|OElig|ofcir|boxvR|uogon|lltri|boxVr|csube|uuarr|ohbar|csupe|ctdot|olarr|olcir|harrw|oline|sqcap|omacr|Omacr|omega|Omega|boxVR|aleph|lneqq|lnsim|loang|loarr|rharu|lobrk|hcirc|operp|oplus|rhard|Hcirc|orarr|Union|order|ecirc|Ecirc|cuepr|szlig|cuesc|breve|reals|eDDot|Breve|hoarr|lopar|utrif|rdquo|Umacr|umacr|efDot|swArr|ultri|alpha|rceil|ovbar|swarr|Wcirc|wcirc|smtes|smile|bsemi|lrarr|aring|parsl|lrhar|bsime|uhblk|lrtri|cupor|Aring|uharr|uharl|slarr|rbrke|bsolb|lsime|rbbrk|RBarr|lsimg|phone|rBarr|rbarr|icirc|lsquo|Icirc|emacr|Emacr|ratio|simne|plusb|simlE|simgE|simeq|pluse|ltcir|ltdot|empty|xharr|xdtri|iexcl|Alpha|ltrie|rarrw|pound|ltrif|xcirc|bumpe|prcue|bumpE|asymp|amacr|cuvee|Sigma|sigma|iiint|udhar|iiota|ijlig|IJlig|supnE|imacr|Imacr|prime|Prime|image|prnap|eogon|Eogon|rarrc|mdash|mDDot|cuwed|imath|supne|imped|Amacr|udarr|prsim|micro|rarrb|cwint|raquo|infin|eplus|range|rangd|Ucirc|radic|minus|amalg|veeeq|rAarr|epsiv|ycirc|quest|sharp|quot|zwnj|Qscr|race|qscr|Qopf|qopf|qint|rang|Rang|Zscr|zscr|Zopf|zopf|rarr|rArr|Rarr|Pscr|pscr|prop|prod|prnE|prec|ZHcy|zhcy|prap|Zeta|zeta|Popf|popf|Zdot|plus|zdot|Yuml|yuml|phiv|YUcy|yucy|Yscr|yscr|perp|Yopf|yopf|part|para|YIcy|Ouml|rcub|yicy|YAcy|rdca|ouml|osol|Oscr|rdsh|yacy|real|oscr|xvee|andd|rect|andv|Xscr|oror|ordm|ordf|xscr|ange|aopf|Aopf|rHar|Xopf|opar|Oopf|xopf|xnis|rhov|oopf|omid|xmap|oint|apid|apos|ogon|ascr|Ascr|odot|odiv|xcup|xcap|ocir|oast|nvlt|nvle|nvgt|nvge|nvap|Wscr|wscr|auml|ntlg|ntgl|nsup|nsub|nsim|Nscr|nscr|nsce|Wopf|ring|npre|wopf|npar|Auml|Barv|bbrk|Nopf|nopf|nmid|nLtv|beta|ropf|Ropf|Beta|beth|nles|rpar|nleq|bnot|bNot|nldr|NJcy|rscr|Rscr|Vscr|vscr|rsqb|njcy|bopf|nisd|Bopf|rtri|Vopf|nGtv|ngtr|vopf|boxh|boxH|boxv|nges|ngeq|boxV|bscr|scap|Bscr|bsim|Vert|vert|bsol|bull|bump|caps|cdot|ncup|scnE|ncap|nbsp|napE|Cdot|cent|sdot|Vbar|nang|vBar|chcy|Mscr|mscr|sect|semi|CHcy|Mopf|mopf|sext|circ|cire|mldr|mlcp|cirE|comp|shcy|SHcy|vArr|varr|cong|copf|Copf|copy|COPY|malt|male|macr|lvnE|cscr|ltri|sime|ltcc|simg|Cscr|siml|csub|Uuml|lsqb|lsim|uuml|csup|Lscr|lscr|utri|smid|lpar|cups|smte|lozf|darr|Lopf|Uscr|solb|lopf|sopf|Sopf|lneq|uscr|spar|dArr|lnap|Darr|dash|Sqrt|LJcy|ljcy|lHar|dHar|Upsi|upsi|diam|lesg|djcy|DJcy|leqq|dopf|Dopf|dscr|Dscr|dscy|ldsh|ldca|squf|DScy|sscr|Sscr|dsol|lcub|late|star|Star|Uopf|Larr|lArr|larr|uopf|dtri|dzcy|sube|subE|Lang|lang|Kscr|kscr|Kopf|kopf|KJcy|kjcy|KHcy|khcy|DZcy|ecir|edot|eDot|Jscr|jscr|succ|Jopf|jopf|Edot|uHar|emsp|ensp|Iuml|iuml|eopf|isin|Iscr|iscr|Eopf|epar|sung|epsi|escr|sup1|sup2|sup3|Iota|iota|supe|supE|Iopf|iopf|IOcy|iocy|Escr|esim|Esim|imof|Uarr|QUOT|uArr|uarr|euml|IEcy|iecy|Idot|Euml|euro|excl|Hscr|hscr|Hopf|hopf|TScy|tscy|Tscr|hbar|tscr|flat|tbrk|fnof|hArr|harr|half|fopf|Fopf|tdot|gvnE|fork|trie|gtcc|fscr|Fscr|gdot|gsim|Gscr|gscr|Gopf|gopf|gneq|Gdot|tosa|gnap|Topf|topf|geqq|toea|GJcy|gjcy|tint|gesl|mid|Sfr|ggg|top|ges|gla|glE|glj|geq|gne|gEl|gel|gnE|Gcy|gcy|gap|Tfr|tfr|Tcy|tcy|Hat|Tau|Ffr|tau|Tab|hfr|Hfr|ffr|Fcy|fcy|icy|Icy|iff|ETH|eth|ifr|Ifr|Eta|eta|int|Int|Sup|sup|ucy|Ucy|Sum|sum|jcy|ENG|ufr|Ufr|eng|Jcy|jfr|els|ell|egs|Efr|efr|Jfr|uml|kcy|Kcy|Ecy|ecy|kfr|Kfr|lap|Sub|sub|lat|lcy|Lcy|leg|Dot|dot|lEg|leq|les|squ|div|die|lfr|Lfr|lgE|Dfr|dfr|Del|deg|Dcy|dcy|lne|lnE|sol|loz|smt|Cup|lrm|cup|lsh|Lsh|sim|shy|map|Map|mcy|Mcy|mfr|Mfr|mho|gfr|Gfr|sfr|cir|Chi|chi|nap|Cfr|vcy|Vcy|cfr|Scy|scy|ncy|Ncy|vee|Vee|Cap|cap|nfr|scE|sce|Nfr|nge|ngE|nGg|vfr|Vfr|ngt|bot|nGt|nis|niv|Rsh|rsh|nle|nlE|bne|Bfr|bfr|nLl|nlt|nLt|Bcy|bcy|not|Not|rlm|wfr|Wfr|npr|nsc|num|ocy|ast|Ocy|ofr|xfr|Xfr|Ofr|ogt|ohm|apE|olt|Rho|ape|rho|Rfr|rfr|ord|REG|ang|reg|orv|And|and|AMP|Rcy|amp|Afr|ycy|Ycy|yen|yfr|Yfr|rcy|par|pcy|Pcy|pfr|Pfr|phi|Phi|afr|Acy|acy|zcy|Zcy|piv|acE|acd|zfr|Zfr|pre|prE|psi|Psi|qfr|Qfr|zwj|Or|ge|Gg|gt|gg|el|oS|lt|Lt|LT|Re|lg|gl|eg|ne|Im|it|le|DD|wp|wr|nu|Nu|dd|lE|Sc|sc|pi|Pi|ee|af|ll|Ll|rx|gE|xi|pm|Xi|ic|pr|Pr|in|ni|mp|mu|ac|Mu|or|ap|Gt|GT|ii);|&(Aacute|Agrave|Atilde|Ccedil|Eacute|Egrave|Iacute|Igrave|Ntilde|Oacute|Ograve|Oslash|Otilde|Uacute|Ugrave|Yacute|aacute|agrave|atilde|brvbar|ccedil|curren|divide|eacute|egrave|frac12|frac14|frac34|iacute|igrave|iquest|middot|ntilde|oacute|ograve|oslash|otilde|plusmn|uacute|ugrave|yacute|AElig|Acirc|Aring|Ecirc|Icirc|Ocirc|THORN|Ucirc|acirc|acute|aelig|aring|cedil|ecirc|icirc|iexcl|laquo|micro|ocirc|pound|raquo|szlig|thorn|times|ucirc|Auml|COPY|Euml|Iuml|Ouml|QUOT|Uuml|auml|cent|copy|euml|iuml|macr|nbsp|ordf|ordm|ouml|para|quot|sect|sup1|sup2|sup3|uuml|yuml|AMP|ETH|REG|amp|deg|eth|not|reg|shy|uml|yen|GT|LT|gt|lt)(?!;)([=a-zA-Z0-9]?)|&#([0-9]+)(;?)|&#[xX]([a-fA-F0-9]+)(;?)|&([0-9a-zA-Z]+)/g;
var decodeMap = {'aacute':'\xE1','Aacute':'\xC1','abreve':'\u0103','Abreve':'\u0102','ac':'\u223E','acd':'\u223F','acE':'\u223E\u0333','acirc':'\xE2','Acirc':'\xC2','acute':'\xB4','acy':'\u0430','Acy':'\u0410','aelig':'\xE6','AElig':'\xC6','af':'\u2061','afr':'\uD835\uDD1E','Afr':'\uD835\uDD04','agrave':'\xE0','Agrave':'\xC0','alefsym':'\u2135','aleph':'\u2135','alpha':'\u03B1','Alpha':'\u0391','amacr':'\u0101','Amacr':'\u0100','amalg':'\u2A3F','amp':'&','AMP':'&','and':'\u2227','And':'\u2A53','andand':'\u2A55','andd':'\u2A5C','andslope':'\u2A58','andv':'\u2A5A','ang':'\u2220','ange':'\u29A4','angle':'\u2220','angmsd':'\u2221','angmsdaa':'\u29A8','angmsdab':'\u29A9','angmsdac':'\u29AA','angmsdad':'\u29AB','angmsdae':'\u29AC','angmsdaf':'\u29AD','angmsdag':'\u29AE','angmsdah':'\u29AF','angrt':'\u221F','angrtvb':'\u22BE','angrtvbd':'\u299D','angsph':'\u2222','angst':'\xC5','angzarr':'\u237C','aogon':'\u0105','Aogon':'\u0104','aopf':'\uD835\uDD52','Aopf':'\uD835\uDD38','ap':'\u2248','apacir':'\u2A6F','ape':'\u224A','apE':'\u2A70','apid':'\u224B','apos':'\'','ApplyFunction':'\u2061','approx':'\u2248','approxeq':'\u224A','aring':'\xE5','Aring':'\xC5','ascr':'\uD835\uDCB6','Ascr':'\uD835\uDC9C','Assign':'\u2254','ast':'*','asymp':'\u2248','asympeq':'\u224D','atilde':'\xE3','Atilde':'\xC3','auml':'\xE4','Auml':'\xC4','awconint':'\u2233','awint':'\u2A11','backcong':'\u224C','backepsilon':'\u03F6','backprime':'\u2035','backsim':'\u223D','backsimeq':'\u22CD','Backslash':'\u2216','Barv':'\u2AE7','barvee':'\u22BD','barwed':'\u2305','Barwed':'\u2306','barwedge':'\u2305','bbrk':'\u23B5','bbrktbrk':'\u23B6','bcong':'\u224C','bcy':'\u0431','Bcy':'\u0411','bdquo':'\u201E','becaus':'\u2235','because':'\u2235','Because':'\u2235','bemptyv':'\u29B0','bepsi':'\u03F6','bernou':'\u212C','Bernoullis':'\u212C','beta':'\u03B2','Beta':'\u0392','beth':'\u2136','between':'\u226C','bfr':'\uD835\uDD1F','Bfr':'\uD835\uDD05','bigcap':'\u22C2','bigcirc':'\u25EF','bigcup':'\u22C3','bigodot':'\u2A00','bigoplus':'\u2A01','bigotimes':'\u2A02','bigsqcup':'\u2A06','bigstar':'\u2605','bigtriangledown':'\u25BD','bigtriangleup':'\u25B3','biguplus':'\u2A04','bigvee':'\u22C1','bigwedge':'\u22C0','bkarow':'\u290D','blacklozenge':'\u29EB','blacksquare':'\u25AA','blacktriangle':'\u25B4','blacktriangledown':'\u25BE','blacktriangleleft':'\u25C2','blacktriangleright':'\u25B8','blank':'\u2423','blk12':'\u2592','blk14':'\u2591','blk34':'\u2593','block':'\u2588','bne':'=\u20E5','bnequiv':'\u2261\u20E5','bnot':'\u2310','bNot':'\u2AED','bopf':'\uD835\uDD53','Bopf':'\uD835\uDD39','bot':'\u22A5','bottom':'\u22A5','bowtie':'\u22C8','boxbox':'\u29C9','boxdl':'\u2510','boxdL':'\u2555','boxDl':'\u2556','boxDL':'\u2557','boxdr':'\u250C','boxdR':'\u2552','boxDr':'\u2553','boxDR':'\u2554','boxh':'\u2500','boxH':'\u2550','boxhd':'\u252C','boxhD':'\u2565','boxHd':'\u2564','boxHD':'\u2566','boxhu':'\u2534','boxhU':'\u2568','boxHu':'\u2567','boxHU':'\u2569','boxminus':'\u229F','boxplus':'\u229E','boxtimes':'\u22A0','boxul':'\u2518','boxuL':'\u255B','boxUl':'\u255C','boxUL':'\u255D','boxur':'\u2514','boxuR':'\u2558','boxUr':'\u2559','boxUR':'\u255A','boxv':'\u2502','boxV':'\u2551','boxvh':'\u253C','boxvH':'\u256A','boxVh':'\u256B','boxVH':'\u256C','boxvl':'\u2524','boxvL':'\u2561','boxVl':'\u2562','boxVL':'\u2563','boxvr':'\u251C','boxvR':'\u255E','boxVr':'\u255F','boxVR':'\u2560','bprime':'\u2035','breve':'\u02D8','Breve':'\u02D8','brvbar':'\xA6','bscr':'\uD835\uDCB7','Bscr':'\u212C','bsemi':'\u204F','bsim':'\u223D','bsime':'\u22CD','bsol':'\\','bsolb':'\u29C5','bsolhsub':'\u27C8','bull':'\u2022','bullet':'\u2022','bump':'\u224E','bumpe':'\u224F','bumpE':'\u2AAE','bumpeq':'\u224F','Bumpeq':'\u224E','cacute':'\u0107','Cacute':'\u0106','cap':'\u2229','Cap':'\u22D2','capand':'\u2A44','capbrcup':'\u2A49','capcap':'\u2A4B','capcup':'\u2A47','capdot':'\u2A40','CapitalDifferentialD':'\u2145','caps':'\u2229\uFE00','caret':'\u2041','caron':'\u02C7','Cayleys':'\u212D','ccaps':'\u2A4D','ccaron':'\u010D','Ccaron':'\u010C','ccedil':'\xE7','Ccedil':'\xC7','ccirc':'\u0109','Ccirc':'\u0108','Cconint':'\u2230','ccups':'\u2A4C','ccupssm':'\u2A50','cdot':'\u010B','Cdot':'\u010A','cedil':'\xB8','Cedilla':'\xB8','cemptyv':'\u29B2','cent':'\xA2','centerdot':'\xB7','CenterDot':'\xB7','cfr':'\uD835\uDD20','Cfr':'\u212D','chcy':'\u0447','CHcy':'\u0427','check':'\u2713','checkmark':'\u2713','chi':'\u03C7','Chi':'\u03A7','cir':'\u25CB','circ':'\u02C6','circeq':'\u2257','circlearrowleft':'\u21BA','circlearrowright':'\u21BB','circledast':'\u229B','circledcirc':'\u229A','circleddash':'\u229D','CircleDot':'\u2299','circledR':'\xAE','circledS':'\u24C8','CircleMinus':'\u2296','CirclePlus':'\u2295','CircleTimes':'\u2297','cire':'\u2257','cirE':'\u29C3','cirfnint':'\u2A10','cirmid':'\u2AEF','cirscir':'\u29C2','ClockwiseContourIntegral':'\u2232','CloseCurlyDoubleQuote':'\u201D','CloseCurlyQuote':'\u2019','clubs':'\u2663','clubsuit':'\u2663','colon':':','Colon':'\u2237','colone':'\u2254','Colone':'\u2A74','coloneq':'\u2254','comma':',','commat':'@','comp':'\u2201','compfn':'\u2218','complement':'\u2201','complexes':'\u2102','cong':'\u2245','congdot':'\u2A6D','Congruent':'\u2261','conint':'\u222E','Conint':'\u222F','ContourIntegral':'\u222E','copf':'\uD835\uDD54','Copf':'\u2102','coprod':'\u2210','Coproduct':'\u2210','copy':'\xA9','COPY':'\xA9','copysr':'\u2117','CounterClockwiseContourIntegral':'\u2233','crarr':'\u21B5','cross':'\u2717','Cross':'\u2A2F','cscr':'\uD835\uDCB8','Cscr':'\uD835\uDC9E','csub':'\u2ACF','csube':'\u2AD1','csup':'\u2AD0','csupe':'\u2AD2','ctdot':'\u22EF','cudarrl':'\u2938','cudarrr':'\u2935','cuepr':'\u22DE','cuesc':'\u22DF','cularr':'\u21B6','cularrp':'\u293D','cup':'\u222A','Cup':'\u22D3','cupbrcap':'\u2A48','cupcap':'\u2A46','CupCap':'\u224D','cupcup':'\u2A4A','cupdot':'\u228D','cupor':'\u2A45','cups':'\u222A\uFE00','curarr':'\u21B7','curarrm':'\u293C','curlyeqprec':'\u22DE','curlyeqsucc':'\u22DF','curlyvee':'\u22CE','curlywedge':'\u22CF','curren':'\xA4','curvearrowleft':'\u21B6','curvearrowright':'\u21B7','cuvee':'\u22CE','cuwed':'\u22CF','cwconint':'\u2232','cwint':'\u2231','cylcty':'\u232D','dagger':'\u2020','Dagger':'\u2021','daleth':'\u2138','darr':'\u2193','dArr':'\u21D3','Darr':'\u21A1','dash':'\u2010','dashv':'\u22A3','Dashv':'\u2AE4','dbkarow':'\u290F','dblac':'\u02DD','dcaron':'\u010F','Dcaron':'\u010E','dcy':'\u0434','Dcy':'\u0414','dd':'\u2146','DD':'\u2145','ddagger':'\u2021','ddarr':'\u21CA','DDotrahd':'\u2911','ddotseq':'\u2A77','deg':'\xB0','Del':'\u2207','delta':'\u03B4','Delta':'\u0394','demptyv':'\u29B1','dfisht':'\u297F','dfr':'\uD835\uDD21','Dfr':'\uD835\uDD07','dHar':'\u2965','dharl':'\u21C3','dharr':'\u21C2','DiacriticalAcute':'\xB4','DiacriticalDot':'\u02D9','DiacriticalDoubleAcute':'\u02DD','DiacriticalGrave':'`','DiacriticalTilde':'\u02DC','diam':'\u22C4','diamond':'\u22C4','Diamond':'\u22C4','diamondsuit':'\u2666','diams':'\u2666','die':'\xA8','DifferentialD':'\u2146','digamma':'\u03DD','disin':'\u22F2','div':'\xF7','divide':'\xF7','divideontimes':'\u22C7','divonx':'\u22C7','djcy':'\u0452','DJcy':'\u0402','dlcorn':'\u231E','dlcrop':'\u230D','dollar':'$','dopf':'\uD835\uDD55','Dopf':'\uD835\uDD3B','dot':'\u02D9','Dot':'\xA8','DotDot':'\u20DC','doteq':'\u2250','doteqdot':'\u2251','DotEqual':'\u2250','dotminus':'\u2238','dotplus':'\u2214','dotsquare':'\u22A1','doublebarwedge':'\u2306','DoubleContourIntegral':'\u222F','DoubleDot':'\xA8','DoubleDownArrow':'\u21D3','DoubleLeftArrow':'\u21D0','DoubleLeftRightArrow':'\u21D4','DoubleLeftTee':'\u2AE4','DoubleLongLeftArrow':'\u27F8','DoubleLongLeftRightArrow':'\u27FA','DoubleLongRightArrow':'\u27F9','DoubleRightArrow':'\u21D2','DoubleRightTee':'\u22A8','DoubleUpArrow':'\u21D1','DoubleUpDownArrow':'\u21D5','DoubleVerticalBar':'\u2225','downarrow':'\u2193','Downarrow':'\u21D3','DownArrow':'\u2193','DownArrowBar':'\u2913','DownArrowUpArrow':'\u21F5','DownBreve':'\u0311','downdownarrows':'\u21CA','downharpoonleft':'\u21C3','downharpoonright':'\u21C2','DownLeftRightVector':'\u2950','DownLeftTeeVector':'\u295E','DownLeftVector':'\u21BD','DownLeftVectorBar':'\u2956','DownRightTeeVector':'\u295F','DownRightVector':'\u21C1','DownRightVectorBar':'\u2957','DownTee':'\u22A4','DownTeeArrow':'\u21A7','drbkarow':'\u2910','drcorn':'\u231F','drcrop':'\u230C','dscr':'\uD835\uDCB9','Dscr':'\uD835\uDC9F','dscy':'\u0455','DScy':'\u0405','dsol':'\u29F6','dstrok':'\u0111','Dstrok':'\u0110','dtdot':'\u22F1','dtri':'\u25BF','dtrif':'\u25BE','duarr':'\u21F5','duhar':'\u296F','dwangle':'\u29A6','dzcy':'\u045F','DZcy':'\u040F','dzigrarr':'\u27FF','eacute':'\xE9','Eacute':'\xC9','easter':'\u2A6E','ecaron':'\u011B','Ecaron':'\u011A','ecir':'\u2256','ecirc':'\xEA','Ecirc':'\xCA','ecolon':'\u2255','ecy':'\u044D','Ecy':'\u042D','eDDot':'\u2A77','edot':'\u0117','eDot':'\u2251','Edot':'\u0116','ee':'\u2147','efDot':'\u2252','efr':'\uD835\uDD22','Efr':'\uD835\uDD08','eg':'\u2A9A','egrave':'\xE8','Egrave':'\xC8','egs':'\u2A96','egsdot':'\u2A98','el':'\u2A99','Element':'\u2208','elinters':'\u23E7','ell':'\u2113','els':'\u2A95','elsdot':'\u2A97','emacr':'\u0113','Emacr':'\u0112','empty':'\u2205','emptyset':'\u2205','EmptySmallSquare':'\u25FB','emptyv':'\u2205','EmptyVerySmallSquare':'\u25AB','emsp':'\u2003','emsp13':'\u2004','emsp14':'\u2005','eng':'\u014B','ENG':'\u014A','ensp':'\u2002','eogon':'\u0119','Eogon':'\u0118','eopf':'\uD835\uDD56','Eopf':'\uD835\uDD3C','epar':'\u22D5','eparsl':'\u29E3','eplus':'\u2A71','epsi':'\u03B5','epsilon':'\u03B5','Epsilon':'\u0395','epsiv':'\u03F5','eqcirc':'\u2256','eqcolon':'\u2255','eqsim':'\u2242','eqslantgtr':'\u2A96','eqslantless':'\u2A95','Equal':'\u2A75','equals':'=','EqualTilde':'\u2242','equest':'\u225F','Equilibrium':'\u21CC','equiv':'\u2261','equivDD':'\u2A78','eqvparsl':'\u29E5','erarr':'\u2971','erDot':'\u2253','escr':'\u212F','Escr':'\u2130','esdot':'\u2250','esim':'\u2242','Esim':'\u2A73','eta':'\u03B7','Eta':'\u0397','eth':'\xF0','ETH':'\xD0','euml':'\xEB','Euml':'\xCB','euro':'\u20AC','excl':'!','exist':'\u2203','Exists':'\u2203','expectation':'\u2130','exponentiale':'\u2147','ExponentialE':'\u2147','fallingdotseq':'\u2252','fcy':'\u0444','Fcy':'\u0424','female':'\u2640','ffilig':'\uFB03','fflig':'\uFB00','ffllig':'\uFB04','ffr':'\uD835\uDD23','Ffr':'\uD835\uDD09','filig':'\uFB01','FilledSmallSquare':'\u25FC','FilledVerySmallSquare':'\u25AA','fjlig':'fj','flat':'\u266D','fllig':'\uFB02','fltns':'\u25B1','fnof':'\u0192','fopf':'\uD835\uDD57','Fopf':'\uD835\uDD3D','forall':'\u2200','ForAll':'\u2200','fork':'\u22D4','forkv':'\u2AD9','Fouriertrf':'\u2131','fpartint':'\u2A0D','frac12':'\xBD','frac13':'\u2153','frac14':'\xBC','frac15':'\u2155','frac16':'\u2159','frac18':'\u215B','frac23':'\u2154','frac25':'\u2156','frac34':'\xBE','frac35':'\u2157','frac38':'\u215C','frac45':'\u2158','frac56':'\u215A','frac58':'\u215D','frac78':'\u215E','frasl':'\u2044','frown':'\u2322','fscr':'\uD835\uDCBB','Fscr':'\u2131','gacute':'\u01F5','gamma':'\u03B3','Gamma':'\u0393','gammad':'\u03DD','Gammad':'\u03DC','gap':'\u2A86','gbreve':'\u011F','Gbreve':'\u011E','Gcedil':'\u0122','gcirc':'\u011D','Gcirc':'\u011C','gcy':'\u0433','Gcy':'\u0413','gdot':'\u0121','Gdot':'\u0120','ge':'\u2265','gE':'\u2267','gel':'\u22DB','gEl':'\u2A8C','geq':'\u2265','geqq':'\u2267','geqslant':'\u2A7E','ges':'\u2A7E','gescc':'\u2AA9','gesdot':'\u2A80','gesdoto':'\u2A82','gesdotol':'\u2A84','gesl':'\u22DB\uFE00','gesles':'\u2A94','gfr':'\uD835\uDD24','Gfr':'\uD835\uDD0A','gg':'\u226B','Gg':'\u22D9','ggg':'\u22D9','gimel':'\u2137','gjcy':'\u0453','GJcy':'\u0403','gl':'\u2277','gla':'\u2AA5','glE':'\u2A92','glj':'\u2AA4','gnap':'\u2A8A','gnapprox':'\u2A8A','gne':'\u2A88','gnE':'\u2269','gneq':'\u2A88','gneqq':'\u2269','gnsim':'\u22E7','gopf':'\uD835\uDD58','Gopf':'\uD835\uDD3E','grave':'`','GreaterEqual':'\u2265','GreaterEqualLess':'\u22DB','GreaterFullEqual':'\u2267','GreaterGreater':'\u2AA2','GreaterLess':'\u2277','GreaterSlantEqual':'\u2A7E','GreaterTilde':'\u2273','gscr':'\u210A','Gscr':'\uD835\uDCA2','gsim':'\u2273','gsime':'\u2A8E','gsiml':'\u2A90','gt':'>','Gt':'\u226B','GT':'>','gtcc':'\u2AA7','gtcir':'\u2A7A','gtdot':'\u22D7','gtlPar':'\u2995','gtquest':'\u2A7C','gtrapprox':'\u2A86','gtrarr':'\u2978','gtrdot':'\u22D7','gtreqless':'\u22DB','gtreqqless':'\u2A8C','gtrless':'\u2277','gtrsim':'\u2273','gvertneqq':'\u2269\uFE00','gvnE':'\u2269\uFE00','Hacek':'\u02C7','hairsp':'\u200A','half':'\xBD','hamilt':'\u210B','hardcy':'\u044A','HARDcy':'\u042A','harr':'\u2194','hArr':'\u21D4','harrcir':'\u2948','harrw':'\u21AD','Hat':'^','hbar':'\u210F','hcirc':'\u0125','Hcirc':'\u0124','hearts':'\u2665','heartsuit':'\u2665','hellip':'\u2026','hercon':'\u22B9','hfr':'\uD835\uDD25','Hfr':'\u210C','HilbertSpace':'\u210B','hksearow':'\u2925','hkswarow':'\u2926','hoarr':'\u21FF','homtht':'\u223B','hookleftarrow':'\u21A9','hookrightarrow':'\u21AA','hopf':'\uD835\uDD59','Hopf':'\u210D','horbar':'\u2015','HorizontalLine':'\u2500','hscr':'\uD835\uDCBD','Hscr':'\u210B','hslash':'\u210F','hstrok':'\u0127','Hstrok':'\u0126','HumpDownHump':'\u224E','HumpEqual':'\u224F','hybull':'\u2043','hyphen':'\u2010','iacute':'\xED','Iacute':'\xCD','ic':'\u2063','icirc':'\xEE','Icirc':'\xCE','icy':'\u0438','Icy':'\u0418','Idot':'\u0130','iecy':'\u0435','IEcy':'\u0415','iexcl':'\xA1','iff':'\u21D4','ifr':'\uD835\uDD26','Ifr':'\u2111','igrave':'\xEC','Igrave':'\xCC','ii':'\u2148','iiiint':'\u2A0C','iiint':'\u222D','iinfin':'\u29DC','iiota':'\u2129','ijlig':'\u0133','IJlig':'\u0132','Im':'\u2111','imacr':'\u012B','Imacr':'\u012A','image':'\u2111','ImaginaryI':'\u2148','imagline':'\u2110','imagpart':'\u2111','imath':'\u0131','imof':'\u22B7','imped':'\u01B5','Implies':'\u21D2','in':'\u2208','incare':'\u2105','infin':'\u221E','infintie':'\u29DD','inodot':'\u0131','int':'\u222B','Int':'\u222C','intcal':'\u22BA','integers':'\u2124','Integral':'\u222B','intercal':'\u22BA','Intersection':'\u22C2','intlarhk':'\u2A17','intprod':'\u2A3C','InvisibleComma':'\u2063','InvisibleTimes':'\u2062','iocy':'\u0451','IOcy':'\u0401','iogon':'\u012F','Iogon':'\u012E','iopf':'\uD835\uDD5A','Iopf':'\uD835\uDD40','iota':'\u03B9','Iota':'\u0399','iprod':'\u2A3C','iquest':'\xBF','iscr':'\uD835\uDCBE','Iscr':'\u2110','isin':'\u2208','isindot':'\u22F5','isinE':'\u22F9','isins':'\u22F4','isinsv':'\u22F3','isinv':'\u2208','it':'\u2062','itilde':'\u0129','Itilde':'\u0128','iukcy':'\u0456','Iukcy':'\u0406','iuml':'\xEF','Iuml':'\xCF','jcirc':'\u0135','Jcirc':'\u0134','jcy':'\u0439','Jcy':'\u0419','jfr':'\uD835\uDD27','Jfr':'\uD835\uDD0D','jmath':'\u0237','jopf':'\uD835\uDD5B','Jopf':'\uD835\uDD41','jscr':'\uD835\uDCBF','Jscr':'\uD835\uDCA5','jsercy':'\u0458','Jsercy':'\u0408','jukcy':'\u0454','Jukcy':'\u0404','kappa':'\u03BA','Kappa':'\u039A','kappav':'\u03F0','kcedil':'\u0137','Kcedil':'\u0136','kcy':'\u043A','Kcy':'\u041A','kfr':'\uD835\uDD28','Kfr':'\uD835\uDD0E','kgreen':'\u0138','khcy':'\u0445','KHcy':'\u0425','kjcy':'\u045C','KJcy':'\u040C','kopf':'\uD835\uDD5C','Kopf':'\uD835\uDD42','kscr':'\uD835\uDCC0','Kscr':'\uD835\uDCA6','lAarr':'\u21DA','lacute':'\u013A','Lacute':'\u0139','laemptyv':'\u29B4','lagran':'\u2112','lambda':'\u03BB','Lambda':'\u039B','lang':'\u27E8','Lang':'\u27EA','langd':'\u2991','langle':'\u27E8','lap':'\u2A85','Laplacetrf':'\u2112','laquo':'\xAB','larr':'\u2190','lArr':'\u21D0','Larr':'\u219E','larrb':'\u21E4','larrbfs':'\u291F','larrfs':'\u291D','larrhk':'\u21A9','larrlp':'\u21AB','larrpl':'\u2939','larrsim':'\u2973','larrtl':'\u21A2','lat':'\u2AAB','latail':'\u2919','lAtail':'\u291B','late':'\u2AAD','lates':'\u2AAD\uFE00','lbarr':'\u290C','lBarr':'\u290E','lbbrk':'\u2772','lbrace':'{','lbrack':'[','lbrke':'\u298B','lbrksld':'\u298F','lbrkslu':'\u298D','lcaron':'\u013E','Lcaron':'\u013D','lcedil':'\u013C','Lcedil':'\u013B','lceil':'\u2308','lcub':'{','lcy':'\u043B','Lcy':'\u041B','ldca':'\u2936','ldquo':'\u201C','ldquor':'\u201E','ldrdhar':'\u2967','ldrushar':'\u294B','ldsh':'\u21B2','le':'\u2264','lE':'\u2266','LeftAngleBracket':'\u27E8','leftarrow':'\u2190','Leftarrow':'\u21D0','LeftArrow':'\u2190','LeftArrowBar':'\u21E4','LeftArrowRightArrow':'\u21C6','leftarrowtail':'\u21A2','LeftCeiling':'\u2308','LeftDoubleBracket':'\u27E6','LeftDownTeeVector':'\u2961','LeftDownVector':'\u21C3','LeftDownVectorBar':'\u2959','LeftFloor':'\u230A','leftharpoondown':'\u21BD','leftharpoonup':'\u21BC','leftleftarrows':'\u21C7','leftrightarrow':'\u2194','Leftrightarrow':'\u21D4','LeftRightArrow':'\u2194','leftrightarrows':'\u21C6','leftrightharpoons':'\u21CB','leftrightsquigarrow':'\u21AD','LeftRightVector':'\u294E','LeftTee':'\u22A3','LeftTeeArrow':'\u21A4','LeftTeeVector':'\u295A','leftthreetimes':'\u22CB','LeftTriangle':'\u22B2','LeftTriangleBar':'\u29CF','LeftTriangleEqual':'\u22B4','LeftUpDownVector':'\u2951','LeftUpTeeVector':'\u2960','LeftUpVector':'\u21BF','LeftUpVectorBar':'\u2958','LeftVector':'\u21BC','LeftVectorBar':'\u2952','leg':'\u22DA','lEg':'\u2A8B','leq':'\u2264','leqq':'\u2266','leqslant':'\u2A7D','les':'\u2A7D','lescc':'\u2AA8','lesdot':'\u2A7F','lesdoto':'\u2A81','lesdotor':'\u2A83','lesg':'\u22DA\uFE00','lesges':'\u2A93','lessapprox':'\u2A85','lessdot':'\u22D6','lesseqgtr':'\u22DA','lesseqqgtr':'\u2A8B','LessEqualGreater':'\u22DA','LessFullEqual':'\u2266','LessGreater':'\u2276','lessgtr':'\u2276','LessLess':'\u2AA1','lesssim':'\u2272','LessSlantEqual':'\u2A7D','LessTilde':'\u2272','lfisht':'\u297C','lfloor':'\u230A','lfr':'\uD835\uDD29','Lfr':'\uD835\uDD0F','lg':'\u2276','lgE':'\u2A91','lHar':'\u2962','lhard':'\u21BD','lharu':'\u21BC','lharul':'\u296A','lhblk':'\u2584','ljcy':'\u0459','LJcy':'\u0409','ll':'\u226A','Ll':'\u22D8','llarr':'\u21C7','llcorner':'\u231E','Lleftarrow':'\u21DA','llhard':'\u296B','lltri':'\u25FA','lmidot':'\u0140','Lmidot':'\u013F','lmoust':'\u23B0','lmoustache':'\u23B0','lnap':'\u2A89','lnapprox':'\u2A89','lne':'\u2A87','lnE':'\u2268','lneq':'\u2A87','lneqq':'\u2268','lnsim':'\u22E6','loang':'\u27EC','loarr':'\u21FD','lobrk':'\u27E6','longleftarrow':'\u27F5','Longleftarrow':'\u27F8','LongLeftArrow':'\u27F5','longleftrightarrow':'\u27F7','Longleftrightarrow':'\u27FA','LongLeftRightArrow':'\u27F7','longmapsto':'\u27FC','longrightarrow':'\u27F6','Longrightarrow':'\u27F9','LongRightArrow':'\u27F6','looparrowleft':'\u21AB','looparrowright':'\u21AC','lopar':'\u2985','lopf':'\uD835\uDD5D','Lopf':'\uD835\uDD43','loplus':'\u2A2D','lotimes':'\u2A34','lowast':'\u2217','lowbar':'_','LowerLeftArrow':'\u2199','LowerRightArrow':'\u2198','loz':'\u25CA','lozenge':'\u25CA','lozf':'\u29EB','lpar':'(','lparlt':'\u2993','lrarr':'\u21C6','lrcorner':'\u231F','lrhar':'\u21CB','lrhard':'\u296D','lrm':'\u200E','lrtri':'\u22BF','lsaquo':'\u2039','lscr':'\uD835\uDCC1','Lscr':'\u2112','lsh':'\u21B0','Lsh':'\u21B0','lsim':'\u2272','lsime':'\u2A8D','lsimg':'\u2A8F','lsqb':'[','lsquo':'\u2018','lsquor':'\u201A','lstrok':'\u0142','Lstrok':'\u0141','lt':'<','Lt':'\u226A','LT':'<','ltcc':'\u2AA6','ltcir':'\u2A79','ltdot':'\u22D6','lthree':'\u22CB','ltimes':'\u22C9','ltlarr':'\u2976','ltquest':'\u2A7B','ltri':'\u25C3','ltrie':'\u22B4','ltrif':'\u25C2','ltrPar':'\u2996','lurdshar':'\u294A','luruhar':'\u2966','lvertneqq':'\u2268\uFE00','lvnE':'\u2268\uFE00','macr':'\xAF','male':'\u2642','malt':'\u2720','maltese':'\u2720','map':'\u21A6','Map':'\u2905','mapsto':'\u21A6','mapstodown':'\u21A7','mapstoleft':'\u21A4','mapstoup':'\u21A5','marker':'\u25AE','mcomma':'\u2A29','mcy':'\u043C','Mcy':'\u041C','mdash':'\u2014','mDDot':'\u223A','measuredangle':'\u2221','MediumSpace':'\u205F','Mellintrf':'\u2133','mfr':'\uD835\uDD2A','Mfr':'\uD835\uDD10','mho':'\u2127','micro':'\xB5','mid':'\u2223','midast':'*','midcir':'\u2AF0','middot':'\xB7','minus':'\u2212','minusb':'\u229F','minusd':'\u2238','minusdu':'\u2A2A','MinusPlus':'\u2213','mlcp':'\u2ADB','mldr':'\u2026','mnplus':'\u2213','models':'\u22A7','mopf':'\uD835\uDD5E','Mopf':'\uD835\uDD44','mp':'\u2213','mscr':'\uD835\uDCC2','Mscr':'\u2133','mstpos':'\u223E','mu':'\u03BC','Mu':'\u039C','multimap':'\u22B8','mumap':'\u22B8','nabla':'\u2207','nacute':'\u0144','Nacute':'\u0143','nang':'\u2220\u20D2','nap':'\u2249','napE':'\u2A70\u0338','napid':'\u224B\u0338','napos':'\u0149','napprox':'\u2249','natur':'\u266E','natural':'\u266E','naturals':'\u2115','nbsp':'\xA0','nbump':'\u224E\u0338','nbumpe':'\u224F\u0338','ncap':'\u2A43','ncaron':'\u0148','Ncaron':'\u0147','ncedil':'\u0146','Ncedil':'\u0145','ncong':'\u2247','ncongdot':'\u2A6D\u0338','ncup':'\u2A42','ncy':'\u043D','Ncy':'\u041D','ndash':'\u2013','ne':'\u2260','nearhk':'\u2924','nearr':'\u2197','neArr':'\u21D7','nearrow':'\u2197','nedot':'\u2250\u0338','NegativeMediumSpace':'\u200B','NegativeThickSpace':'\u200B','NegativeThinSpace':'\u200B','NegativeVeryThinSpace':'\u200B','nequiv':'\u2262','nesear':'\u2928','nesim':'\u2242\u0338','NestedGreaterGreater':'\u226B','NestedLessLess':'\u226A','NewLine':'\n','nexist':'\u2204','nexists':'\u2204','nfr':'\uD835\uDD2B','Nfr':'\uD835\uDD11','nge':'\u2271','ngE':'\u2267\u0338','ngeq':'\u2271','ngeqq':'\u2267\u0338','ngeqslant':'\u2A7E\u0338','nges':'\u2A7E\u0338','nGg':'\u22D9\u0338','ngsim':'\u2275','ngt':'\u226F','nGt':'\u226B\u20D2','ngtr':'\u226F','nGtv':'\u226B\u0338','nharr':'\u21AE','nhArr':'\u21CE','nhpar':'\u2AF2','ni':'\u220B','nis':'\u22FC','nisd':'\u22FA','niv':'\u220B','njcy':'\u045A','NJcy':'\u040A','nlarr':'\u219A','nlArr':'\u21CD','nldr':'\u2025','nle':'\u2270','nlE':'\u2266\u0338','nleftarrow':'\u219A','nLeftarrow':'\u21CD','nleftrightarrow':'\u21AE','nLeftrightarrow':'\u21CE','nleq':'\u2270','nleqq':'\u2266\u0338','nleqslant':'\u2A7D\u0338','nles':'\u2A7D\u0338','nless':'\u226E','nLl':'\u22D8\u0338','nlsim':'\u2274','nlt':'\u226E','nLt':'\u226A\u20D2','nltri':'\u22EA','nltrie':'\u22EC','nLtv':'\u226A\u0338','nmid':'\u2224','NoBreak':'\u2060','NonBreakingSpace':'\xA0','nopf':'\uD835\uDD5F','Nopf':'\u2115','not':'\xAC','Not':'\u2AEC','NotCongruent':'\u2262','NotCupCap':'\u226D','NotDoubleVerticalBar':'\u2226','NotElement':'\u2209','NotEqual':'\u2260','NotEqualTilde':'\u2242\u0338','NotExists':'\u2204','NotGreater':'\u226F','NotGreaterEqual':'\u2271','NotGreaterFullEqual':'\u2267\u0338','NotGreaterGreater':'\u226B\u0338','NotGreaterLess':'\u2279','NotGreaterSlantEqual':'\u2A7E\u0338','NotGreaterTilde':'\u2275','NotHumpDownHump':'\u224E\u0338','NotHumpEqual':'\u224F\u0338','notin':'\u2209','notindot':'\u22F5\u0338','notinE':'\u22F9\u0338','notinva':'\u2209','notinvb':'\u22F7','notinvc':'\u22F6','NotLeftTriangle':'\u22EA','NotLeftTriangleBar':'\u29CF\u0338','NotLeftTriangleEqual':'\u22EC','NotLess':'\u226E','NotLessEqual':'\u2270','NotLessGreater':'\u2278','NotLessLess':'\u226A\u0338','NotLessSlantEqual':'\u2A7D\u0338','NotLessTilde':'\u2274','NotNestedGreaterGreater':'\u2AA2\u0338','NotNestedLessLess':'\u2AA1\u0338','notni':'\u220C','notniva':'\u220C','notnivb':'\u22FE','notnivc':'\u22FD','NotPrecedes':'\u2280','NotPrecedesEqual':'\u2AAF\u0338','NotPrecedesSlantEqual':'\u22E0','NotReverseElement':'\u220C','NotRightTriangle':'\u22EB','NotRightTriangleBar':'\u29D0\u0338','NotRightTriangleEqual':'\u22ED','NotSquareSubset':'\u228F\u0338','NotSquareSubsetEqual':'\u22E2','NotSquareSuperset':'\u2290\u0338','NotSquareSupersetEqual':'\u22E3','NotSubset':'\u2282\u20D2','NotSubsetEqual':'\u2288','NotSucceeds':'\u2281','NotSucceedsEqual':'\u2AB0\u0338','NotSucceedsSlantEqual':'\u22E1','NotSucceedsTilde':'\u227F\u0338','NotSuperset':'\u2283\u20D2','NotSupersetEqual':'\u2289','NotTilde':'\u2241','NotTildeEqual':'\u2244','NotTildeFullEqual':'\u2247','NotTildeTilde':'\u2249','NotVerticalBar':'\u2224','npar':'\u2226','nparallel':'\u2226','nparsl':'\u2AFD\u20E5','npart':'\u2202\u0338','npolint':'\u2A14','npr':'\u2280','nprcue':'\u22E0','npre':'\u2AAF\u0338','nprec':'\u2280','npreceq':'\u2AAF\u0338','nrarr':'\u219B','nrArr':'\u21CF','nrarrc':'\u2933\u0338','nrarrw':'\u219D\u0338','nrightarrow':'\u219B','nRightarrow':'\u21CF','nrtri':'\u22EB','nrtrie':'\u22ED','nsc':'\u2281','nsccue':'\u22E1','nsce':'\u2AB0\u0338','nscr':'\uD835\uDCC3','Nscr':'\uD835\uDCA9','nshortmid':'\u2224','nshortparallel':'\u2226','nsim':'\u2241','nsime':'\u2244','nsimeq':'\u2244','nsmid':'\u2224','nspar':'\u2226','nsqsube':'\u22E2','nsqsupe':'\u22E3','nsub':'\u2284','nsube':'\u2288','nsubE':'\u2AC5\u0338','nsubset':'\u2282\u20D2','nsubseteq':'\u2288','nsubseteqq':'\u2AC5\u0338','nsucc':'\u2281','nsucceq':'\u2AB0\u0338','nsup':'\u2285','nsupe':'\u2289','nsupE':'\u2AC6\u0338','nsupset':'\u2283\u20D2','nsupseteq':'\u2289','nsupseteqq':'\u2AC6\u0338','ntgl':'\u2279','ntilde':'\xF1','Ntilde':'\xD1','ntlg':'\u2278','ntriangleleft':'\u22EA','ntrianglelefteq':'\u22EC','ntriangleright':'\u22EB','ntrianglerighteq':'\u22ED','nu':'\u03BD','Nu':'\u039D','num':'#','numero':'\u2116','numsp':'\u2007','nvap':'\u224D\u20D2','nvdash':'\u22AC','nvDash':'\u22AD','nVdash':'\u22AE','nVDash':'\u22AF','nvge':'\u2265\u20D2','nvgt':'>\u20D2','nvHarr':'\u2904','nvinfin':'\u29DE','nvlArr':'\u2902','nvle':'\u2264\u20D2','nvlt':'<\u20D2','nvltrie':'\u22B4\u20D2','nvrArr':'\u2903','nvrtrie':'\u22B5\u20D2','nvsim':'\u223C\u20D2','nwarhk':'\u2923','nwarr':'\u2196','nwArr':'\u21D6','nwarrow':'\u2196','nwnear':'\u2927','oacute':'\xF3','Oacute':'\xD3','oast':'\u229B','ocir':'\u229A','ocirc':'\xF4','Ocirc':'\xD4','ocy':'\u043E','Ocy':'\u041E','odash':'\u229D','odblac':'\u0151','Odblac':'\u0150','odiv':'\u2A38','odot':'\u2299','odsold':'\u29BC','oelig':'\u0153','OElig':'\u0152','ofcir':'\u29BF','ofr':'\uD835\uDD2C','Ofr':'\uD835\uDD12','ogon':'\u02DB','ograve':'\xF2','Ograve':'\xD2','ogt':'\u29C1','ohbar':'\u29B5','ohm':'\u03A9','oint':'\u222E','olarr':'\u21BA','olcir':'\u29BE','olcross':'\u29BB','oline':'\u203E','olt':'\u29C0','omacr':'\u014D','Omacr':'\u014C','omega':'\u03C9','Omega':'\u03A9','omicron':'\u03BF','Omicron':'\u039F','omid':'\u29B6','ominus':'\u2296','oopf':'\uD835\uDD60','Oopf':'\uD835\uDD46','opar':'\u29B7','OpenCurlyDoubleQuote':'\u201C','OpenCurlyQuote':'\u2018','operp':'\u29B9','oplus':'\u2295','or':'\u2228','Or':'\u2A54','orarr':'\u21BB','ord':'\u2A5D','order':'\u2134','orderof':'\u2134','ordf':'\xAA','ordm':'\xBA','origof':'\u22B6','oror':'\u2A56','orslope':'\u2A57','orv':'\u2A5B','oS':'\u24C8','oscr':'\u2134','Oscr':'\uD835\uDCAA','oslash':'\xF8','Oslash':'\xD8','osol':'\u2298','otilde':'\xF5','Otilde':'\xD5','otimes':'\u2297','Otimes':'\u2A37','otimesas':'\u2A36','ouml':'\xF6','Ouml':'\xD6','ovbar':'\u233D','OverBar':'\u203E','OverBrace':'\u23DE','OverBracket':'\u23B4','OverParenthesis':'\u23DC','par':'\u2225','para':'\xB6','parallel':'\u2225','parsim':'\u2AF3','parsl':'\u2AFD','part':'\u2202','PartialD':'\u2202','pcy':'\u043F','Pcy':'\u041F','percnt':'%','period':'.','permil':'\u2030','perp':'\u22A5','pertenk':'\u2031','pfr':'\uD835\uDD2D','Pfr':'\uD835\uDD13','phi':'\u03C6','Phi':'\u03A6','phiv':'\u03D5','phmmat':'\u2133','phone':'\u260E','pi':'\u03C0','Pi':'\u03A0','pitchfork':'\u22D4','piv':'\u03D6','planck':'\u210F','planckh':'\u210E','plankv':'\u210F','plus':'+','plusacir':'\u2A23','plusb':'\u229E','pluscir':'\u2A22','plusdo':'\u2214','plusdu':'\u2A25','pluse':'\u2A72','PlusMinus':'\xB1','plusmn':'\xB1','plussim':'\u2A26','plustwo':'\u2A27','pm':'\xB1','Poincareplane':'\u210C','pointint':'\u2A15','popf':'\uD835\uDD61','Popf':'\u2119','pound':'\xA3','pr':'\u227A','Pr':'\u2ABB','prap':'\u2AB7','prcue':'\u227C','pre':'\u2AAF','prE':'\u2AB3','prec':'\u227A','precapprox':'\u2AB7','preccurlyeq':'\u227C','Precedes':'\u227A','PrecedesEqual':'\u2AAF','PrecedesSlantEqual':'\u227C','PrecedesTilde':'\u227E','preceq':'\u2AAF','precnapprox':'\u2AB9','precneqq':'\u2AB5','precnsim':'\u22E8','precsim':'\u227E','prime':'\u2032','Prime':'\u2033','primes':'\u2119','prnap':'\u2AB9','prnE':'\u2AB5','prnsim':'\u22E8','prod':'\u220F','Product':'\u220F','profalar':'\u232E','profline':'\u2312','profsurf':'\u2313','prop':'\u221D','Proportion':'\u2237','Proportional':'\u221D','propto':'\u221D','prsim':'\u227E','prurel':'\u22B0','pscr':'\uD835\uDCC5','Pscr':'\uD835\uDCAB','psi':'\u03C8','Psi':'\u03A8','puncsp':'\u2008','qfr':'\uD835\uDD2E','Qfr':'\uD835\uDD14','qint':'\u2A0C','qopf':'\uD835\uDD62','Qopf':'\u211A','qprime':'\u2057','qscr':'\uD835\uDCC6','Qscr':'\uD835\uDCAC','quaternions':'\u210D','quatint':'\u2A16','quest':'?','questeq':'\u225F','quot':'"','QUOT':'"','rAarr':'\u21DB','race':'\u223D\u0331','racute':'\u0155','Racute':'\u0154','radic':'\u221A','raemptyv':'\u29B3','rang':'\u27E9','Rang':'\u27EB','rangd':'\u2992','range':'\u29A5','rangle':'\u27E9','raquo':'\xBB','rarr':'\u2192','rArr':'\u21D2','Rarr':'\u21A0','rarrap':'\u2975','rarrb':'\u21E5','rarrbfs':'\u2920','rarrc':'\u2933','rarrfs':'\u291E','rarrhk':'\u21AA','rarrlp':'\u21AC','rarrpl':'\u2945','rarrsim':'\u2974','rarrtl':'\u21A3','Rarrtl':'\u2916','rarrw':'\u219D','ratail':'\u291A','rAtail':'\u291C','ratio':'\u2236','rationals':'\u211A','rbarr':'\u290D','rBarr':'\u290F','RBarr':'\u2910','rbbrk':'\u2773','rbrace':'}','rbrack':']','rbrke':'\u298C','rbrksld':'\u298E','rbrkslu':'\u2990','rcaron':'\u0159','Rcaron':'\u0158','rcedil':'\u0157','Rcedil':'\u0156','rceil':'\u2309','rcub':'}','rcy':'\u0440','Rcy':'\u0420','rdca':'\u2937','rdldhar':'\u2969','rdquo':'\u201D','rdquor':'\u201D','rdsh':'\u21B3','Re':'\u211C','real':'\u211C','realine':'\u211B','realpart':'\u211C','reals':'\u211D','rect':'\u25AD','reg':'\xAE','REG':'\xAE','ReverseElement':'\u220B','ReverseEquilibrium':'\u21CB','ReverseUpEquilibrium':'\u296F','rfisht':'\u297D','rfloor':'\u230B','rfr':'\uD835\uDD2F','Rfr':'\u211C','rHar':'\u2964','rhard':'\u21C1','rharu':'\u21C0','rharul':'\u296C','rho':'\u03C1','Rho':'\u03A1','rhov':'\u03F1','RightAngleBracket':'\u27E9','rightarrow':'\u2192','Rightarrow':'\u21D2','RightArrow':'\u2192','RightArrowBar':'\u21E5','RightArrowLeftArrow':'\u21C4','rightarrowtail':'\u21A3','RightCeiling':'\u2309','RightDoubleBracket':'\u27E7','RightDownTeeVector':'\u295D','RightDownVector':'\u21C2','RightDownVectorBar':'\u2955','RightFloor':'\u230B','rightharpoondown':'\u21C1','rightharpoonup':'\u21C0','rightleftarrows':'\u21C4','rightleftharpoons':'\u21CC','rightrightarrows':'\u21C9','rightsquigarrow':'\u219D','RightTee':'\u22A2','RightTeeArrow':'\u21A6','RightTeeVector':'\u295B','rightthreetimes':'\u22CC','RightTriangle':'\u22B3','RightTriangleBar':'\u29D0','RightTriangleEqual':'\u22B5','RightUpDownVector':'\u294F','RightUpTeeVector':'\u295C','RightUpVector':'\u21BE','RightUpVectorBar':'\u2954','RightVector':'\u21C0','RightVectorBar':'\u2953','ring':'\u02DA','risingdotseq':'\u2253','rlarr':'\u21C4','rlhar':'\u21CC','rlm':'\u200F','rmoust':'\u23B1','rmoustache':'\u23B1','rnmid':'\u2AEE','roang':'\u27ED','roarr':'\u21FE','robrk':'\u27E7','ropar':'\u2986','ropf':'\uD835\uDD63','Ropf':'\u211D','roplus':'\u2A2E','rotimes':'\u2A35','RoundImplies':'\u2970','rpar':')','rpargt':'\u2994','rppolint':'\u2A12','rrarr':'\u21C9','Rrightarrow':'\u21DB','rsaquo':'\u203A','rscr':'\uD835\uDCC7','Rscr':'\u211B','rsh':'\u21B1','Rsh':'\u21B1','rsqb':']','rsquo':'\u2019','rsquor':'\u2019','rthree':'\u22CC','rtimes':'\u22CA','rtri':'\u25B9','rtrie':'\u22B5','rtrif':'\u25B8','rtriltri':'\u29CE','RuleDelayed':'\u29F4','ruluhar':'\u2968','rx':'\u211E','sacute':'\u015B','Sacute':'\u015A','sbquo':'\u201A','sc':'\u227B','Sc':'\u2ABC','scap':'\u2AB8','scaron':'\u0161','Scaron':'\u0160','sccue':'\u227D','sce':'\u2AB0','scE':'\u2AB4','scedil':'\u015F','Scedil':'\u015E','scirc':'\u015D','Scirc':'\u015C','scnap':'\u2ABA','scnE':'\u2AB6','scnsim':'\u22E9','scpolint':'\u2A13','scsim':'\u227F','scy':'\u0441','Scy':'\u0421','sdot':'\u22C5','sdotb':'\u22A1','sdote':'\u2A66','searhk':'\u2925','searr':'\u2198','seArr':'\u21D8','searrow':'\u2198','sect':'\xA7','semi':';','seswar':'\u2929','setminus':'\u2216','setmn':'\u2216','sext':'\u2736','sfr':'\uD835\uDD30','Sfr':'\uD835\uDD16','sfrown':'\u2322','sharp':'\u266F','shchcy':'\u0449','SHCHcy':'\u0429','shcy':'\u0448','SHcy':'\u0428','ShortDownArrow':'\u2193','ShortLeftArrow':'\u2190','shortmid':'\u2223','shortparallel':'\u2225','ShortRightArrow':'\u2192','ShortUpArrow':'\u2191','shy':'\xAD','sigma':'\u03C3','Sigma':'\u03A3','sigmaf':'\u03C2','sigmav':'\u03C2','sim':'\u223C','simdot':'\u2A6A','sime':'\u2243','simeq':'\u2243','simg':'\u2A9E','simgE':'\u2AA0','siml':'\u2A9D','simlE':'\u2A9F','simne':'\u2246','simplus':'\u2A24','simrarr':'\u2972','slarr':'\u2190','SmallCircle':'\u2218','smallsetminus':'\u2216','smashp':'\u2A33','smeparsl':'\u29E4','smid':'\u2223','smile':'\u2323','smt':'\u2AAA','smte':'\u2AAC','smtes':'\u2AAC\uFE00','softcy':'\u044C','SOFTcy':'\u042C','sol':'/','solb':'\u29C4','solbar':'\u233F','sopf':'\uD835\uDD64','Sopf':'\uD835\uDD4A','spades':'\u2660','spadesuit':'\u2660','spar':'\u2225','sqcap':'\u2293','sqcaps':'\u2293\uFE00','sqcup':'\u2294','sqcups':'\u2294\uFE00','Sqrt':'\u221A','sqsub':'\u228F','sqsube':'\u2291','sqsubset':'\u228F','sqsubseteq':'\u2291','sqsup':'\u2290','sqsupe':'\u2292','sqsupset':'\u2290','sqsupseteq':'\u2292','squ':'\u25A1','square':'\u25A1','Square':'\u25A1','SquareIntersection':'\u2293','SquareSubset':'\u228F','SquareSubsetEqual':'\u2291','SquareSuperset':'\u2290','SquareSupersetEqual':'\u2292','SquareUnion':'\u2294','squarf':'\u25AA','squf':'\u25AA','srarr':'\u2192','sscr':'\uD835\uDCC8','Sscr':'\uD835\uDCAE','ssetmn':'\u2216','ssmile':'\u2323','sstarf':'\u22C6','star':'\u2606','Star':'\u22C6','starf':'\u2605','straightepsilon':'\u03F5','straightphi':'\u03D5','strns':'\xAF','sub':'\u2282','Sub':'\u22D0','subdot':'\u2ABD','sube':'\u2286','subE':'\u2AC5','subedot':'\u2AC3','submult':'\u2AC1','subne':'\u228A','subnE':'\u2ACB','subplus':'\u2ABF','subrarr':'\u2979','subset':'\u2282','Subset':'\u22D0','subseteq':'\u2286','subseteqq':'\u2AC5','SubsetEqual':'\u2286','subsetneq':'\u228A','subsetneqq':'\u2ACB','subsim':'\u2AC7','subsub':'\u2AD5','subsup':'\u2AD3','succ':'\u227B','succapprox':'\u2AB8','succcurlyeq':'\u227D','Succeeds':'\u227B','SucceedsEqual':'\u2AB0','SucceedsSlantEqual':'\u227D','SucceedsTilde':'\u227F','succeq':'\u2AB0','succnapprox':'\u2ABA','succneqq':'\u2AB6','succnsim':'\u22E9','succsim':'\u227F','SuchThat':'\u220B','sum':'\u2211','Sum':'\u2211','sung':'\u266A','sup':'\u2283','Sup':'\u22D1','sup1':'\xB9','sup2':'\xB2','sup3':'\xB3','supdot':'\u2ABE','supdsub':'\u2AD8','supe':'\u2287','supE':'\u2AC6','supedot':'\u2AC4','Superset':'\u2283','SupersetEqual':'\u2287','suphsol':'\u27C9','suphsub':'\u2AD7','suplarr':'\u297B','supmult':'\u2AC2','supne':'\u228B','supnE':'\u2ACC','supplus':'\u2AC0','supset':'\u2283','Supset':'\u22D1','supseteq':'\u2287','supseteqq':'\u2AC6','supsetneq':'\u228B','supsetneqq':'\u2ACC','supsim':'\u2AC8','supsub':'\u2AD4','supsup':'\u2AD6','swarhk':'\u2926','swarr':'\u2199','swArr':'\u21D9','swarrow':'\u2199','swnwar':'\u292A','szlig':'\xDF','Tab':'\t','target':'\u2316','tau':'\u03C4','Tau':'\u03A4','tbrk':'\u23B4','tcaron':'\u0165','Tcaron':'\u0164','tcedil':'\u0163','Tcedil':'\u0162','tcy':'\u0442','Tcy':'\u0422','tdot':'\u20DB','telrec':'\u2315','tfr':'\uD835\uDD31','Tfr':'\uD835\uDD17','there4':'\u2234','therefore':'\u2234','Therefore':'\u2234','theta':'\u03B8','Theta':'\u0398','thetasym':'\u03D1','thetav':'\u03D1','thickapprox':'\u2248','thicksim':'\u223C','ThickSpace':'\u205F\u200A','thinsp':'\u2009','ThinSpace':'\u2009','thkap':'\u2248','thksim':'\u223C','thorn':'\xFE','THORN':'\xDE','tilde':'\u02DC','Tilde':'\u223C','TildeEqual':'\u2243','TildeFullEqual':'\u2245','TildeTilde':'\u2248','times':'\xD7','timesb':'\u22A0','timesbar':'\u2A31','timesd':'\u2A30','tint':'\u222D','toea':'\u2928','top':'\u22A4','topbot':'\u2336','topcir':'\u2AF1','topf':'\uD835\uDD65','Topf':'\uD835\uDD4B','topfork':'\u2ADA','tosa':'\u2929','tprime':'\u2034','trade':'\u2122','TRADE':'\u2122','triangle':'\u25B5','triangledown':'\u25BF','triangleleft':'\u25C3','trianglelefteq':'\u22B4','triangleq':'\u225C','triangleright':'\u25B9','trianglerighteq':'\u22B5','tridot':'\u25EC','trie':'\u225C','triminus':'\u2A3A','TripleDot':'\u20DB','triplus':'\u2A39','trisb':'\u29CD','tritime':'\u2A3B','trpezium':'\u23E2','tscr':'\uD835\uDCC9','Tscr':'\uD835\uDCAF','tscy':'\u0446','TScy':'\u0426','tshcy':'\u045B','TSHcy':'\u040B','tstrok':'\u0167','Tstrok':'\u0166','twixt':'\u226C','twoheadleftarrow':'\u219E','twoheadrightarrow':'\u21A0','uacute':'\xFA','Uacute':'\xDA','uarr':'\u2191','uArr':'\u21D1','Uarr':'\u219F','Uarrocir':'\u2949','ubrcy':'\u045E','Ubrcy':'\u040E','ubreve':'\u016D','Ubreve':'\u016C','ucirc':'\xFB','Ucirc':'\xDB','ucy':'\u0443','Ucy':'\u0423','udarr':'\u21C5','udblac':'\u0171','Udblac':'\u0170','udhar':'\u296E','ufisht':'\u297E','ufr':'\uD835\uDD32','Ufr':'\uD835\uDD18','ugrave':'\xF9','Ugrave':'\xD9','uHar':'\u2963','uharl':'\u21BF','uharr':'\u21BE','uhblk':'\u2580','ulcorn':'\u231C','ulcorner':'\u231C','ulcrop':'\u230F','ultri':'\u25F8','umacr':'\u016B','Umacr':'\u016A','uml':'\xA8','UnderBar':'_','UnderBrace':'\u23DF','UnderBracket':'\u23B5','UnderParenthesis':'\u23DD','Union':'\u22C3','UnionPlus':'\u228E','uogon':'\u0173','Uogon':'\u0172','uopf':'\uD835\uDD66','Uopf':'\uD835\uDD4C','uparrow':'\u2191','Uparrow':'\u21D1','UpArrow':'\u2191','UpArrowBar':'\u2912','UpArrowDownArrow':'\u21C5','updownarrow':'\u2195','Updownarrow':'\u21D5','UpDownArrow':'\u2195','UpEquilibrium':'\u296E','upharpoonleft':'\u21BF','upharpoonright':'\u21BE','uplus':'\u228E','UpperLeftArrow':'\u2196','UpperRightArrow':'\u2197','upsi':'\u03C5','Upsi':'\u03D2','upsih':'\u03D2','upsilon':'\u03C5','Upsilon':'\u03A5','UpTee':'\u22A5','UpTeeArrow':'\u21A5','upuparrows':'\u21C8','urcorn':'\u231D','urcorner':'\u231D','urcrop':'\u230E','uring':'\u016F','Uring':'\u016E','urtri':'\u25F9','uscr':'\uD835\uDCCA','Uscr':'\uD835\uDCB0','utdot':'\u22F0','utilde':'\u0169','Utilde':'\u0168','utri':'\u25B5','utrif':'\u25B4','uuarr':'\u21C8','uuml':'\xFC','Uuml':'\xDC','uwangle':'\u29A7','vangrt':'\u299C','varepsilon':'\u03F5','varkappa':'\u03F0','varnothing':'\u2205','varphi':'\u03D5','varpi':'\u03D6','varpropto':'\u221D','varr':'\u2195','vArr':'\u21D5','varrho':'\u03F1','varsigma':'\u03C2','varsubsetneq':'\u228A\uFE00','varsubsetneqq':'\u2ACB\uFE00','varsupsetneq':'\u228B\uFE00','varsupsetneqq':'\u2ACC\uFE00','vartheta':'\u03D1','vartriangleleft':'\u22B2','vartriangleright':'\u22B3','vBar':'\u2AE8','Vbar':'\u2AEB','vBarv':'\u2AE9','vcy':'\u0432','Vcy':'\u0412','vdash':'\u22A2','vDash':'\u22A8','Vdash':'\u22A9','VDash':'\u22AB','Vdashl':'\u2AE6','vee':'\u2228','Vee':'\u22C1','veebar':'\u22BB','veeeq':'\u225A','vellip':'\u22EE','verbar':'|','Verbar':'\u2016','vert':'|','Vert':'\u2016','VerticalBar':'\u2223','VerticalLine':'|','VerticalSeparator':'\u2758','VerticalTilde':'\u2240','VeryThinSpace':'\u200A','vfr':'\uD835\uDD33','Vfr':'\uD835\uDD19','vltri':'\u22B2','vnsub':'\u2282\u20D2','vnsup':'\u2283\u20D2','vopf':'\uD835\uDD67','Vopf':'\uD835\uDD4D','vprop':'\u221D','vrtri':'\u22B3','vscr':'\uD835\uDCCB','Vscr':'\uD835\uDCB1','vsubne':'\u228A\uFE00','vsubnE':'\u2ACB\uFE00','vsupne':'\u228B\uFE00','vsupnE':'\u2ACC\uFE00','Vvdash':'\u22AA','vzigzag':'\u299A','wcirc':'\u0175','Wcirc':'\u0174','wedbar':'\u2A5F','wedge':'\u2227','Wedge':'\u22C0','wedgeq':'\u2259','weierp':'\u2118','wfr':'\uD835\uDD34','Wfr':'\uD835\uDD1A','wopf':'\uD835\uDD68','Wopf':'\uD835\uDD4E','wp':'\u2118','wr':'\u2240','wreath':'\u2240','wscr':'\uD835\uDCCC','Wscr':'\uD835\uDCB2','xcap':'\u22C2','xcirc':'\u25EF','xcup':'\u22C3','xdtri':'\u25BD','xfr':'\uD835\uDD35','Xfr':'\uD835\uDD1B','xharr':'\u27F7','xhArr':'\u27FA','xi':'\u03BE','Xi':'\u039E','xlarr':'\u27F5','xlArr':'\u27F8','xmap':'\u27FC','xnis':'\u22FB','xodot':'\u2A00','xopf':'\uD835\uDD69','Xopf':'\uD835\uDD4F','xoplus':'\u2A01','xotime':'\u2A02','xrarr':'\u27F6','xrArr':'\u27F9','xscr':'\uD835\uDCCD','Xscr':'\uD835\uDCB3','xsqcup':'\u2A06','xuplus':'\u2A04','xutri':'\u25B3','xvee':'\u22C1','xwedge':'\u22C0','yacute':'\xFD','Yacute':'\xDD','yacy':'\u044F','YAcy':'\u042F','ycirc':'\u0177','Ycirc':'\u0176','ycy':'\u044B','Ycy':'\u042B','yen':'\xA5','yfr':'\uD835\uDD36','Yfr':'\uD835\uDD1C','yicy':'\u0457','YIcy':'\u0407','yopf':'\uD835\uDD6A','Yopf':'\uD835\uDD50','yscr':'\uD835\uDCCE','Yscr':'\uD835\uDCB4','yucy':'\u044E','YUcy':'\u042E','yuml':'\xFF','Yuml':'\u0178','zacute':'\u017A','Zacute':'\u0179','zcaron':'\u017E','Zcaron':'\u017D','zcy':'\u0437','Zcy':'\u0417','zdot':'\u017C','Zdot':'\u017B','zeetrf':'\u2128','ZeroWidthSpace':'\u200B','zeta':'\u03B6','Zeta':'\u0396','zfr':'\uD835\uDD37','Zfr':'\u2128','zhcy':'\u0436','ZHcy':'\u0416','zigrarr':'\u21DD','zopf':'\uD835\uDD6B','Zopf':'\u2124','zscr':'\uD835\uDCCF','Zscr':'\uD835\uDCB5','zwj':'\u200D','zwnj':'\u200C'};
var decodeMapLegacy = {'aacute':'\xE1','Aacute':'\xC1','acirc':'\xE2','Acirc':'\xC2','acute':'\xB4','aelig':'\xE6','AElig':'\xC6','agrave':'\xE0','Agrave':'\xC0','amp':'&','AMP':'&','aring':'\xE5','Aring':'\xC5','atilde':'\xE3','Atilde':'\xC3','auml':'\xE4','Auml':'\xC4','brvbar':'\xA6','ccedil':'\xE7','Ccedil':'\xC7','cedil':'\xB8','cent':'\xA2','copy':'\xA9','COPY':'\xA9','curren':'\xA4','deg':'\xB0','divide':'\xF7','eacute':'\xE9','Eacute':'\xC9','ecirc':'\xEA','Ecirc':'\xCA','egrave':'\xE8','Egrave':'\xC8','eth':'\xF0','ETH':'\xD0','euml':'\xEB','Euml':'\xCB','frac12':'\xBD','frac14':'\xBC','frac34':'\xBE','gt':'>','GT':'>','iacute':'\xED','Iacute':'\xCD','icirc':'\xEE','Icirc':'\xCE','iexcl':'\xA1','igrave':'\xEC','Igrave':'\xCC','iquest':'\xBF','iuml':'\xEF','Iuml':'\xCF','laquo':'\xAB','lt':'<','LT':'<','macr':'\xAF','micro':'\xB5','middot':'\xB7','nbsp':'\xA0','not':'\xAC','ntilde':'\xF1','Ntilde':'\xD1','oacute':'\xF3','Oacute':'\xD3','ocirc':'\xF4','Ocirc':'\xD4','ograve':'\xF2','Ograve':'\xD2','ordf':'\xAA','ordm':'\xBA','oslash':'\xF8','Oslash':'\xD8','otilde':'\xF5','Otilde':'\xD5','ouml':'\xF6','Ouml':'\xD6','para':'\xB6','plusmn':'\xB1','pound':'\xA3','quot':'"','QUOT':'"','raquo':'\xBB','reg':'\xAE','REG':'\xAE','sect':'\xA7','shy':'\xAD','sup1':'\xB9','sup2':'\xB2','sup3':'\xB3','szlig':'\xDF','thorn':'\xFE','THORN':'\xDE','times':'\xD7','uacute':'\xFA','Uacute':'\xDA','ucirc':'\xFB','Ucirc':'\xDB','ugrave':'\xF9','Ugrave':'\xD9','uml':'\xA8','uuml':'\xFC','Uuml':'\xDC','yacute':'\xFD','Yacute':'\xDD','yen':'\xA5','yuml':'\xFF'};
var decodeMapNumeric = {'0':'\uFFFD','128':'\u20AC','130':'\u201A','131':'\u0192','132':'\u201E','133':'\u2026','134':'\u2020','135':'\u2021','136':'\u02C6','137':'\u2030','138':'\u0160','139':'\u2039','140':'\u0152','142':'\u017D','145':'\u2018','146':'\u2019','147':'\u201C','148':'\u201D','149':'\u2022','150':'\u2013','151':'\u2014','152':'\u02DC','153':'\u2122','154':'\u0161','155':'\u203A','156':'\u0153','158':'\u017E','159':'\u0178'};
var invalidReferenceCodePoints = [1,2,3,4,5,6,7,8,11,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,64976,64977,64978,64979,64980,64981,64982,64983,64984,64985,64986,64987,64988,64989,64990,64991,64992,64993,64994,64995,64996,64997,64998,64999,65000,65001,65002,65003,65004,65005,65006,65007,65534,65535,131070,131071,196606,196607,262142,262143,327678,327679,393214,393215,458750,458751,524286,524287,589822,589823,655358,655359,720894,720895,786430,786431,851966,851967,917502,917503,983038,983039,1048574,1048575,1114110,1114111];
/*--------------------------------------------------------------------------*/
var stringFromCharCode = String.fromCharCode;
var object = {};
var hasOwnProperty = object.hasOwnProperty;
var has = function(object, propertyName) {
return hasOwnProperty.call(object, propertyName);
};
var contains = function(array, value) {
var index = -1;
var length = array.length;
while (++index < length) {
if (array[index] == value) {
return true;
}
}
return false;
};
var merge = function(options, defaults) {
if (!options) {
return defaults;
}
var result = {};
var key;
for (key in defaults) {
// A `hasOwnProperty` check is not needed here, since only recognized
// option names are used anyway. Any others are ignored.
result[key] = has(options, key) ? options[key] : defaults[key];
}
return result;
};
// Modified version of `ucs2encode`; see https://mths.be/punycode.
var codePointToSymbol = function(codePoint, strict) {
var output = '';
if ((codePoint >= 0xD800 && codePoint <= 0xDFFF) || codePoint > 0x10FFFF) {
// See issue #4:
// “Otherwise, if the number is in the range 0xD800 to 0xDFFF or is
// greater than 0x10FFFF, then this is a parse error. Return a U+FFFD
// REPLACEMENT CHARACTER.”
if (strict) {
parseError('character reference outside the permissible Unicode range');
}
return '\uFFFD';
}
if (has(decodeMapNumeric, codePoint)) {
if (strict) {
parseError('disallowed character reference');
}
return decodeMapNumeric[codePoint];
}
if (strict && contains(invalidReferenceCodePoints, codePoint)) {
parseError('disallowed character reference');
}
if (codePoint > 0xFFFF) {
codePoint -= 0x10000;
output += stringFromCharCode(codePoint >>> 10 & 0x3FF | 0xD800);
codePoint = 0xDC00 | codePoint & 0x3FF;
}
output += stringFromCharCode(codePoint);
return output;
};
var hexEscape = function(codePoint) {
return '&#x' + codePoint.toString(16).toUpperCase() + ';';
};
var decEscape = function(codePoint) {
return '&#' + codePoint + ';';
};
var parseError = function(message) {
throw Error('Parse error: ' + message);
};
/*--------------------------------------------------------------------------*/
var encode = function(string, options) {
options = merge(options, encode.options);
var strict = options.strict;
if (strict && regexInvalidRawCodePoint.test(string)) {
parseError('forbidden code point');
}
var encodeEverything = options.encodeEverything;
var useNamedReferences = options.useNamedReferences;
var allowUnsafeSymbols = options.allowUnsafeSymbols;
var escapeCodePoint = options.decimal ? decEscape : hexEscape;
var escapeBmpSymbol = function(symbol) {
return escapeCodePoint(symbol.charCodeAt(0));
};
if (encodeEverything) {
// Encode ASCII symbols.
string = string.replace(regexAsciiWhitelist, function(symbol) {
// Use named references if requested & possible.
if (useNamedReferences && has(encodeMap, symbol)) {
return '&' + encodeMap[symbol] + ';';
}
return escapeBmpSymbol(symbol);
});
// Shorten a few escapes that represent two symbols, of which at least one
// is within the ASCII range.
if (useNamedReferences) {
string = string
.replace(/>\u20D2/g, '>⃒')
.replace(/<\u20D2/g, '<⃒')
.replace(/fj/g, 'fj');
}
// Encode non-ASCII symbols.
if (useNamedReferences) {
// Encode non-ASCII symbols that can be replaced with a named reference.
string = string.replace(regexEncodeNonAscii, function(string) {
// Note: there is no need to check `has(encodeMap, string)` here.
return '&' + encodeMap[string] + ';';
});
}
// Note: any remaining non-ASCII symbols are handled outside of the `if`.
} else if (useNamedReferences) {
// Apply named character references.
// Encode `<>"'&` using named character references.
if (!allowUnsafeSymbols) {
string = string.replace(regexEscape, function(string) {
return '&' + encodeMap[string] + ';'; // no need to check `has()` here
});
}
// Shorten escapes that represent two symbols, of which at least one is
// `<>"'&`.
string = string
.replace(/>\u20D2/g, '>⃒')
.replace(/<\u20D2/g, '<⃒');
// Encode non-ASCII symbols that can be replaced with a named reference.
string = string.replace(regexEncodeNonAscii, function(string) {
// Note: there is no need to check `has(encodeMap, string)` here.
return '&' + encodeMap[string] + ';';
});
} else if (!allowUnsafeSymbols) {
// Encode `<>"'&` using hexadecimal escapes, now that they’re not handled
// using named character references.
string = string.replace(regexEscape, escapeBmpSymbol);
}
return string
// Encode astral symbols.
.replace(regexAstralSymbols, function($0) {
// https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
var high = $0.charCodeAt(0);
var low = $0.charCodeAt(1);
var codePoint = (high - 0xD800) * 0x400 + low - 0xDC00 + 0x10000;
return escapeCodePoint(codePoint);
})
// Encode any remaining BMP symbols that are not printable ASCII symbols
// using a hexadecimal escape.
.replace(regexBmpWhitelist, escapeBmpSymbol);
};
// Expose default options (so they can be overridden globally).
encode.options = {
'allowUnsafeSymbols': false,
'encodeEverything': false,
'strict': false,
'useNamedReferences': false,
'decimal' : false
};
var decode = function(html, options) {
options = merge(options, decode.options);
var strict = options.strict;
if (strict && regexInvalidEntity.test(html)) {
parseError('malformed character reference');
}
return html.replace(regexDecode, function($0, $1, $2, $3, $4, $5, $6, $7, $8) {
var codePoint;
var semicolon;
var decDigits;
var hexDigits;
var reference;
var next;
if ($1) {
reference = $1;
// Note: there is no need to check `has(decodeMap, reference)`.
return decodeMap[reference];
}
if ($2) {
// Decode named character references without trailing `;`, e.g. `&`.
// This is only a parse error if it gets converted to `&`, or if it is
// followed by `=` in an attribute context.
reference = $2;
next = $3;
if (next && options.isAttributeValue) {
if (strict && next == '=') {
parseError('`&` did not start a character reference');
}
return $0;
} else {
if (strict) {
parseError(
'named character reference was not terminated by a semicolon'
);
}
// Note: there is no need to check `has(decodeMapLegacy, reference)`.
return decodeMapLegacy[reference] + (next || '');
}
}
if ($4) {
// Decode decimal escapes, e.g. `𝌆`.
decDigits = $4;
semicolon = $5;
if (strict && !semicolon) {
parseError('character reference was not terminated by a semicolon');
}
codePoint = parseInt(decDigits, 10);
return codePointToSymbol(codePoint, strict);
}
if ($6) {
// Decode hexadecimal escapes, e.g. `𝌆`.
hexDigits = $6;
semicolon = $7;
if (strict && !semicolon) {
parseError('character reference was not terminated by a semicolon');
}
codePoint = parseInt(hexDigits, 16);
return codePointToSymbol(codePoint, strict);
}
// If we’re still here, `if ($7)` is implied; it’s an ambiguous
// ampersand for sure. https://mths.be/notes/ambiguous-ampersands
if (strict) {
parseError(
'named character reference was not terminated by a semicolon'
);
}
return $0;
});
};
// Expose default options (so they can be overridden globally).
decode.options = {
'isAttributeValue': false,
'strict': false
};
var escape = function(string) {
return string.replace(regexEscape, function($0) {
// Note: there is no need to check `has(escapeMap, $0)` here.
return escapeMap[$0];
});
};
/*--------------------------------------------------------------------------*/
var he = {
'version': '1.2.0',
'encode': encode,
'decode': decode,
'escape': escape,
'unescape': decode
};
// Some AMD build optimizers, like r.js, check for specific condition patterns
// like the following:
if (freeExports && !freeExports.nodeType) {
if (freeModule) { // in Node.js, io.js, or RingoJS v0.8.0+
freeModule.exports = he;
} else { // in Narwhal or RingoJS v0.7.0-
for (var key in he) {
has(he, key) && (freeExports[key] = he[key]);
}
}
} else { // in Rhino or a web browser
root.he = he;
}
}(commonjsGlobal));
});
var locales = Object.keys(files).filter(function (locale) {
return locale !== "default";
});
var __DEV__$1 = 'production' === "development";
var DEFAULT_CONFIG = {
locale: "en",
fallbackLanguages: ["en"],
availableLanguages: Object.keys(files)
};
var getLanguagePartFromCode = function getLanguagePartFromCode(code) {
if (!code || code.indexOf("-") < 0 || code.indexOf("_") < 0) {
return code;
}
return code.split(/-_/).shift();
};
var interpolate = function interpolate(source, targets) {
var interpolated = source;
var matches = source.match(/\{\{\w+}}/g);
if (matches) {
matches.map(function (match) {
var sanitized = match.replace("{{", "").replace("}}", "");
if (targets[sanitized]) {
interpolated = interpolated.replace(match, he.encode(targets[sanitized]));
}
});
}
return interpolated;
};
var getPossibleMatches = function getPossibleMatches(locale, availableLanguages) {
var possibleMatches = Array.from(availableLanguages).filter(function (lang) {
return getLanguagePartFromCode(lang).indexOf(locale) >= 0;
});
if (possibleMatches.length) {
return possibleMatches.shift();
} else if (!possibleMatches.length && __DEV__$1) {
console.warn("'".concat(locale, "' is not a supported language. Defaulting to English"));
}
return DEFAULT_CONFIG.locale;
};
function i18n(config) {
this.config = objectSpread({}, DEFAULT_CONFIG, config);
if (!this.config.availableLanguages.every(function (lang) {
var hasLocale = locales.indexOf(lang) >= 0;
if (!hasLocale && __DEV__$1) {
console.error("".concat(lang, " is missing from list of translation files. Defaulting to English."));
}
return hasLocale;
})) {
this.config.locale = DEFAULT_CONFIG.locale;
}
}
i18n.init = function (config) {
return new i18n(config);
};
i18n.prototype.setLocale = function (locale) {
this.config.locale = locale;
};
i18n.prototype.t = function (key, options) {
var language = getPossibleMatches(options && options.locale ? options.locale : this.config.locale, this.config.availableLanguages);
var localized = files[language][key];
if (!localized) {
localized = files[DEFAULT_CONFIG.locale][key] || key;
}
if (options) {
localized = interpolate(localized, options);
}
return localized;
};
var DEFAULT_CONFIG$1 = {
locale: "en",
fallbackLanguages: ["en"]
};
var translationProvider = i18n.init();
var TranslationContext = React.createContext({});
var t = translationProvider.t.bind(translationProvider);
var WrapComponent = function WrapComponent(Component, Context, config) {
return function (props) {
return React.createElement(Context.Provider, {
value: config
}, React.createElement(Component, props));
};
};
var withTranslation = function withTranslation(config) {
translationProvider.setLocale(config.locale);
function withTranslation(BaseComponent) {
var WrappedComponent = WrapComponent(BaseComponent, TranslationContext, objectSpread({}, DEFAULT_CONFIG$1, config));
hoistNonReactStatics_cjs(WrappedComponent, BaseComponent);
return WrappedComponent;
}
return withTranslation;
};
var DatePickerDialog = function DatePickerDialog(_ref) {
var title = _ref.title,
children = _ref.children,
onCancel = _ref.onCancel,
onOk = _ref.onOk,
locale = _ref.locale,
rest = objectWithoutProperties(_ref, ["title", "children", "onCancel", "onOk", "locale"]);
return React.createElement(Dialog, _extends_1({}, rest, {
"data-testid": "date-range-picker-dialog",
id: "date-range-picker"
}), React.createElement(Dialog.Header, {
title: title
}), React.createElement(Dialog.Content, null, function () {
return children;
}), React.createElement(Dialog.Footer, null, function () {
return React.createElement(React.Fragment, null, React.createElement(Button, {
variant: "primary",
onClick: onOk
}, t("OK", locale)), React.createElement(Button, {
onClick: onCancel
}, t("Cancel", locale)));
}));
};
/**
* Generic change handler.
* @param {Date} time The date object send from react-wigdets onChange handler.
* @param {boolean} start Set true for start date, false for end date.
* @param {boolean} date Set true for date, false for time.
*/
var handleChange = function handleChange(time, source) {
var date = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
var m = moment(time);
if (moment.isMoment(source) && source.diff(m)) {
if (date) {
m.set("hour", source.hours());
m.set("minute", source.minutes());
m.set("second", source.seconds());
} else {
m.set("date", source.date());
m.set("month", source.month());
m.set("year", source.year());
}
return m;
}
};
function DateRangePicker(props) {
var context = React.useContext(TranslationContext);
var _React$useState = React.useState({
start: moment(),
end: moment().add(1, "day")
}),
_React$useState2 = slicedToArray(_React$useState, 2),
range = _React$useState2[0],
setRange = _React$useState2[1];
var _React$useState3 = React.useState(false),
_React$useState4 = slicedToArray(_React$useState3, 2),
error = _React$useState4[0],
setError = _React$useState4[1];
var handleOkClick = React.useCallback(function () {
props.onOk(range);
}, [range, props.onOk]);
var handleStartChangeDate = React.useCallback(function (e) {
var newRange = objectSpread({}, range, {
start: handleChange(e, range.start)
});
setRange(newRange);
props.onRangeChange(newRange);
}, [range, props.onRangeChange]);
var handleStartChangeTime = React.useCallback(function (e) {
var newRange = objectSpread({}, range, {
start: handleChange(e, range.start, true, false)
});
setRange(newRange);
props.onRangeChange(newRange);
}, [range, props.onRangeChange]);
var handleEndChangeDate = React.useCallback(function (e) {
var newRange = objectSpread({}, range, {
end: handleChange(e, range.end, false, true)
});
setRange(newRange);
props.onRangeChange(newRange);
}, [range, props.onRangeChange]);
var handleEndChangeTime = React.useCallback(function (e) {
var newRange = objectSpread({}, range, {
end: handleChange(e, range.end, false, false)
});
setRange(newRange);
props.onRangeChange(newRange);
}, [range, props.onRangeChange]); // $FlowFixMe locale is not exported by moment type despite it being present
moment.locale(context ? context.locale : props.locale);
momentLocalizer();
var min = props.min,
max = props.max,
className = props.className,
startProps = props.startProps,
endProps = props.endProps;
var locale = context ? context.locale : props.locale;
return React.createElement(DatePickerDialog, _extends_1({}, props, {
locale: locale,
onOk: handleOkClick
}), React.createElement("div", {
className: classnames("date-range-picker", className),
"data-testid": "date-range-picker"
}, React.createElement("section", {
className: "date-range-picker__start"
}, React.createElement("p", null, t("From", locale), ":"), React.createElement(CalendarTimePicker, {
locale: locale,
rwProps: startProps,
min: min,
max: max,
value: range.start.toDate(),
onDateChange: handleStartChangeDate,
onTimeChange: handleStartChangeTime
})), React.createElement("section", {
className: "date-range-picker__end"
}, React.createElement("p", null, t("To", locale), ":"), React.createElement(CalendarTimePicker, {
locale: locale,
rwProps: endProps,
min: min,
max: max,
value: range.end.toDate(),
onDateChange: handleEndChangeDate,
onTimeChange: handleEndChangeTime
}))));
}
DateRangePicker.defaultProps = {
locale: "en",
closed: true
};
var DATE_RANGE_PICKER_TITLE = "Custom Date Range";
var ANY_TIME = "ANY_TIME";
var CUSTOM = "CUSTOM";
var LAST_WEEK = "LAST_WEEK";
var LAST_MONTH = "LAST_MONTH";
var LAST_YEAR = "LAST_YEAR";
var TODAY = "TODAY";
var dateRangeLabels = {
ANY_TIME: "Any Time",
CUSTOM: "Custom",
LAST_WEEK: "Last Week",
LAST_MONTH: "Last Month",
LAST_YEAR: "Last Year",
TODAY: "Today"
};
var options = [ANY_TIME, TODAY, LAST_WEEK, LAST_MONTH, LAST_YEAR, CUSTOM];
var DateRangeOption = React__default.memo(function (_ref) {
var active = _ref.active,
onChange = _ref.onChange,
children = _ref.children,
value = _ref.value,
rest = objectWithoutProperties(_ref, ["active", "onChange", "children", "value"]);
return React__default.createElement("div", _extends_1({
onClick: onChange,
"data-value": value,
className: classnames("menu__item", "filter__single-select__row", active ? "filter__single-select__row--active" : null)
}, rest), active ? React__default.createElement(React__default.Fragment, null, React__default.createElement("i", {
className: "filter__selected"
}), "\xA0") : null, children);
});
var getStateFromRange = function getStateFromRange(range, prevValue) {
var start = prevValue && prevValue.start;
var end = prevValue && prevValue.end;
switch (range) {
case ANY_TIME:
// TODO: Set a specific start/end date & time
start = "";
end = "";
break;
case TODAY:
start = moment().startOf("day");
end = moment().endOf("day");
break;
case LAST_WEEK:
start = moment().startOf("day").subtract(1, "weeks");
end = moment().endOf("day");
break;
case LAST_MONTH:
start = moment().startOf("day").subtract(1, "months");
end = moment().endOf("day");
break;
case LAST_YEAR:
start = moment().startOf("day").subtract(1, "years");
end = moment().endOf("day");
break;
case CUSTOM:
break;
default:
if (prevValue) {
range = prevValue.range;
start = prevValue.start;
end = prevValue.end;
}
}
if (start && moment.isMoment(start)) {
start = start.toDate();
}
if (end && moment.isMoment(end)) {
end = end.toDate();
}
return {
range: range,
start: start,
end: end
};
};
function FilterControlsDateRangePicker() {
var DateRangeFilter = function DateRangeFilter(_ref2) {
var label = _ref2.label,
value = _ref2.value,
setValue = _ref2.setValue,
onDelete = _ref2.onDelete,
initialOpen = _ref2.initialOpen;
var _React$useState = React__default.useState(initialOpen),
_React$useState2 = slicedToArray(_React$useState, 2),
isOpen = _React$useState2[0],
setIsOpen = _React$useState2[1];
var _React$useState3 = React__default.useState(""),
_React$useState4 = slicedToArray(_React$useState3, 2),
selectedRange = _React$useState4[0],
setSelectedRange = _React$useState4[1];
var _React$useState5 = React__default.useState(false),
_React$useState6 = slicedToArray(_React$useState5, 2),
isDateRangePickerOpen = _React$useState6[0],
setIsDateRangePickerOpen = _React$useState6[1];
var handleChange = React__default.useCallback(function (e) {
var range = e.target.getAttribute("data-value");
setSelectedRange(range);
if (range === CUSTOM) {
setIsDateRangePickerOpen(true);
setIsOpen(false);
} else {
setIsDateRangePickerOpen(false);
}
}, [selectedRange, setSelectedRange]);
var renderedOptions = React__default.useMemo(function () {
return options.map(function (option) {
return React__default.createElement(DateRangeOption, {
active: selectedRange === option,
key: option,
onChange: handleChange,
value: option
}, t(dateRangeLabels[option]));
});
}, [options, selectedRange, handleChange]);
var handleToggle = React__default.useCallback(function (e) {
if (!isDateRangePickerOpen) {
var newValue = getStateFromRange(selectedRange, value);
setIsOpen(!isOpen);
setSelectedRange(newValue && newValue.range);
setValue(newValue);
}
e.stopPropagation();
}, [isDateRangePickerOpen, isOpen, setIsOpen, selectedRange, setSelectedRange, value, setValue, getStateFromRange]);
var handleDateRangePickerCancel = React__default.useCallback(function () {
setIsDateRangePickerOpen(false);
setSelectedRange(value && value.range);
}, [value, setIsDateRangePickerOpen, setSelectedRange]);
return React__default.createElement(React__default.Fragment, null, React__default.createElement(Popover$1, {
key: label,
on: "click",
open: isOpen,
onOpen: handleToggle,
onClose: handleToggle,
content: React__default.createElement(Bubble, {
position: "none"
}, renderedOptions)
}, React__default.createElement(Pill, {
title: label,
hasMenu: true,
onClose: function onClose(e) {
e.stopPropagation();
onDelete(value);
}
}, React__default.createElement("strong", null, label, ": "), value && value.range === CUSTOM ? "".concat(value.start, " - ").concat(value.end) : dateRangeLabels[value && value.range])), React__default.createElement(DateRangePicker, {
closed: !isDateRangePickerOpen,
onClose: React__default.useCallback(function () {
return handleDateRangePickerCancel();
}, [value]),
onCancel: React__default.useCallback(function () {
return handleDateRangePickerCancel();
}, [value]),
onOk: React__default.useCallback(function (_ref3) {
var start = _ref3.start,
end = _ref3.end;
setIsDateRangePickerOpen(false);
setValue({
range: selectedRange,
start: start.toDate(),
end: end.toDate()
});
}, [selectedRange]),
onRangeChange: function onRangeChange() {},
draggable: false,
resizable: false,
bounds: "parent",
title: DATE_RANGE_PICKER_TITLE
}));
};
DateRangeFilter.getInitialValue = function () {
return undefined;
};
DateRangeFilter.shouldPillOpen = function (value) {
return value === DateRangeFilter.getInitialValue();
};
return DateRangeFilter;
}
var operatorLabels = {
EQUALS: "Equals",
DOES_NOT_EQUAL: "Does not equal",
LESS_THAN: "Less than",
LESS_THAN_OR_EQUAL_TO: "Less than or equal to",
GREATER_THAN: "Greater than",
GREATER_THAN_OR_EQUAL_TO: "Greater than or equal to",
BETWEEN: "Between"
};
var getOperatorList = function getOperatorList(operatorLabels) {
return Object.keys(operatorLabels).map(function (key) {
return {
text: t(operatorLabels[key]),
value: key
};
});
};
var operatorSign = {
EQUALS: "=",
DOES_NOT_EQUAL: "<>",
LESS_THAN: "<",
LESS_THAN_OR_EQUAL_TO: "<=",
GREATER_THAN: ">",
GREATER_THAN_OR_EQUAL_TO: ">=",
BETWEEN: "-",
"": ""
};
var getInputFields = function getInputFields(value, onChangeHandler, iconClickHandler) {
return React__default.createElement(Input, {
icon: "filter__dismiss link",
value: value,
onChange: function onChange(e) {
return isNumberValid(e.target.value) ? onChangeHandler(e.target.value.trim()) : onChangeHandler("");
},
onIconClick: iconClickHandler
});
};
var isNumberValid = function isNumberValid(value) {
return value.trim() !== "" && !isNaN(value);
};
function FilterControlsNumeric() {
var Numeric = function Numeric(_ref) {
var label = _ref.label,
value = _ref.value,
setValue = _ref.setValue,
onDelete = _ref.onDelete,
initialOpen = _ref.initialOpen;
var _React$useState = React__default.useState(initialOpen),
_React$useState2 = slicedToArray(_React$useState, 2),
isOpen = _React$useState2[0],
setIsOpen = _React$useState2[1];
var _React$useState3 = React__default.useState(value.filterValue),
_React$useState4 = slicedToArray(_React$useState3, 2),
filterValue = _React$useState4[0],
setFilterValue = _React$useState4[1];
var _React$useState5 = React__default.useState(value.operator || "EQUALS"),
_React$useState6 = slicedToArray(_React$useState5, 2),
operator = _React$useState6[0],
setOperator = _React$useState6[1];
var operatorList = React__default.useMemo(function () {
return getOperatorList(operatorLabels);
}, [operator, isOpen]);
var handleToggle = React__default.useCallback(function () {
setIsOpen(!isOpen);
if (isFilterValid({
operator: operator,
filterValue: filterValue
})) {
setValue({
operator: operator,
filterValue: filterValue
});
}
}, [isOpen, filterValue, operator]);
var operatorChangeHandler = React__default.useCallback(function (operator) {
setOperator(operator.value);
operator.value === "BETWEEN" ? setFilterValue(["", ""]) : setFilterValue([""]);
}, []);
var isFilterValid = React__default.useCallback(function (selectedValue) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = selectedValue.filterValue[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var _value = _step.value;
if (_value.trim() === "") {
return false;
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator["return"] != null) {
_iterator["return"]();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return true;
}, [setValue]);
var inputFields = operator === "BETWEEN" ? React__default.createElement(React__default.Fragment, null, React__default.createElement("p", null, "".concat(t("Value"), " : ")), getInputFields(filterValue[0], function (value) {
return setFilterValue([value, filterValue[1]]);
}, function () {
return setFilterValue(["", filterValue[1]]);
}), React__default.createElement("p", null, "".concat(t("And value"), " : ")), getInputFields(filterValue[1], function (value) {
return setFilterValue([filterValue[0], value]);
}, function () {
return setFilterValue([filterValue[0], ""]);
})) : React__default.createElement(React__default.Fragment, null, React__default.createElement("p", null, "".concat(t("Value"), " : ")), getInputFields(filterValue[0], function (value) {
return setFilterValue([value]);
}, function () {
return setFilterValue([""]);
}));
return React__default.createElement(Popover$1, {
key: label,
on: "click",
open: isOpen,
onOpen: handleToggle,
onClose: handleToggle,
content: React__default.createElement(Bubble, {
position: "none"
}, React__default.createElement(Dropdown, {
options: operatorList,
onChange: operatorChangeHandler,
value: operator
}), inputFields)
}, React__default.createElement(Pill, {
title: label,
hasMenu: true,
onClose: function onClose(e) {
e.stopPropagation();
onDelete(value.filterValue);
}
}, React__default.createElement("strong", null, label), ": ", value.operator === "BETWEEN" ? "".concat(value.filterValue[0], " ").concat(operatorSign[value.operator], " ").concat(value.filterValue[1]) : "".concat(operatorSign[value.operator], " ").concat(value.filterValue)));
};
Numeric.getInitialValue = function () {
return {
operator: "",
filterValue: [""]
};
};
Numeric.shouldPillOpen = function (value) {
return value.operator === "";
};
return Numeric;
}
var Controls = /*#__PURE__*/Object.freeze({
Text: FilterControlsText,
MultiSelect: FilterControlsMultiSelect,
SingleSelect: FilterControlsSingleSelect,
DateRangeFilter: FilterControlsDateRangePicker,
Numeric: FilterControlsNumeric
});
var fieldsToMap = function fieldsToMap(fields) {
return fields.reduce(function (accum, field) {
accum[field.key] = field;
return accum;
}, {});
};
function Filter$2(_ref) {
var filterState = _ref.filterState,
setFilterState = _ref.setFilterState,
fields = _ref.fields,
rest = objectWithoutProperties(_ref, ["filterState", "setFilterState", "fields"]);
var _React$useState = React__default.useState(false),
_React$useState2 = slicedToArray(_React$useState, 2),
isOpen = _React$useState2[0],
setIsOpen = _React$useState2[1];
var dispatch = function dispatch(action) {
return setFilterState(filterReducer(filterState, action));
};
var renderField = function renderField(_ref2) {
var key = _ref2.key,
label = _ref2.label,
controlType = _ref2.controlType;
return React__default.createElement("li", {
key: key,
className: "menu__item",
onClick: function onClick() {
dispatch({
type: "ADD_FIELD",
field: key,
value: controlType.getInitialValue()
});
setIsOpen(!isOpen);
}
}, label);
};
var fieldMap = fieldsToMap(fields);
return React__default.createElement(React__default.Fragment, null, React__default.createElement(Toolbar, _extends_1({
alignLeft: true
}, rest), "Filter", React__default.createElement(Toolbar.Separator, null), filterState.map(function (_ref3, index) {
var field = _ref3.field,
value = _ref3.value;
var _fieldMap$field = fieldMap[field],
controlType = _fieldMap$field.controlType,
label = _fieldMap$field.label;
return React__default.createElement(controlType, {
label: label,
value: value,
key: index,
setValue: function setValue(value) {
return dispatch({
type: "UPDATE_FIELD",
field: field,
value: value
});
},
onDelete: function onDelete(value) {
return dispatch({
type: "DELETE_FIELD",
field: field,
value: value
});
},
initialOpen: controlType.shouldPillOpen(value)
});
}), React__default.createElement(Popover$1, {
open: isOpen,
on: "click",
onOpen: function onOpen() {
return setIsOpen(true);
},
onClose: function onClose() {
return setIsOpen(false);
},
content: React__default.createElement("ul", {
className: "menu__container menu"
}, fields.filter(function (field) {
return filterState.every(function (filter) {
return filter.field !== field.key;
});
}).map(function (field) {
return renderField(field);
}))
}, React__default.createElement(IconButton, {
variant: "ghost"
}, t("Add Field"), React__default.createElement("i", {
className: "filter__add-field-icon"
})))));
}
Filter$2.Controls = Controls;
Filter$2.reducer = function () {
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var action = arguments.length > 1 ? arguments[1] : undefined;
return filterReducer(state, action);
};
function settingsReducer() {
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
density: "comfortable"
};
var _ref = arguments.length > 1 ? arguments[1] : undefined,
type = _ref.type,
key = _ref.key,
value = _ref.value;
switch (type) {
case "UPDATE_SETTING":
return defineProperty({}, key, value);
default:
return state;
}
}
function findReducer() {
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
var action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case "FIND_TEXT":
return action.text;
default:
return state;
}
}
function filterReducer$1() {
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
state: []
};
var action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case "ENABLE_FILTER":
return objectSpread({}, state, {
isEnabled: true
});
case "DISABLE_FILTER":
return objectSpread({}, state, {
isEnabled: false
});
case "UPDATE_FILTER":
return objectSpread({}, state, {
state: action.state
});
default:
return state;
}
}
function SettingsMenu(_ref) {
var store = _ref.store;
var context = React__default.useContext(TranslationContext);
var _React$useState = React__default.useState(false),
_React$useState2 = slicedToArray(_React$useState, 2),
settingsMenuOpen = _React$useState2[0],
setSettingsMenuOpen = _React$useState2[1];
var _store = slicedToArray(store, 2),
state = _store[0],
dispatch = _store[1];
var density = state.settings.density;
var SETTINGS = React__default.useMemo(function () {
return [{
label: t("Comfortable"),
value: "comfortable"
}, {
label: t("Cozy"),
value: "cozy"
}, {
label: t("Compact"),
value: "compact"
}];
}, [context]);
var updateSetting = function updateSetting(key, value) {
dispatch({
type: "UPDATE_SETTING",
key: key,
value: value
});
setSettingsMenuOpen(false);
};
return React__default.createElement(Popup, {
isOpen: settingsMenuOpen,
position: "bottom",
onClickOutside: function onClickOutside() {
return setSettingsMenuOpen(false);
},
content: React__default.createElement("ul", {
className: "menu__container menu"
}, SETTINGS.map(function (_ref2) {
var label = _ref2.label,
value = _ref2.value;
return React__default.createElement(Menu.Item, {
key: value,
onClick: function onClick() {
return updateSetting("density", value);
},
onKeyUp: function onKeyUp() {}
}, density === value ? React__default.createElement("i", {
className: "filter__selected"
}) : null, "\xA0 ".concat(label));
}))
}, React__default.createElement(Tooltip, {
content: "Table Settings",
position: "top"
}, React__default.createElement(IconButton, {
variant: "call-to-action",
onClick: function onClick() {
return setSettingsMenuOpen(!settingsMenuOpen);
}
}, React__default.createElement("i", {
className: "aicon aicon__settings",
style: {
fontSize: "15px"
}
}))));
}
function FindBox(_ref) {
var store = _ref.store;
var _store = slicedToArray(store, 2),
state = _store[0],
dispatch = _store[1];
var updateState = React__default.useCallback(function (e) {
return dispatch({
type: "FIND_TEXT",
text: e.target.value
});
}, [dispatch]);
var clearState = React__default.useCallback(function (e) {
return dispatch({
type: "FIND_TEXT",
text: ""
});
}, [dispatch]);
return React__default.createElement(Input, {
className: "toolbar__find",
placeholder: "Find...",
icon: "aicon aicon__close-solid link",
value: state.find,
onChange: updateState,
onIconClick: clearState
});
}
function SortMenu(_ref) {
var store = _ref.store,
sortModel = _ref.sortModel;
var _React$useState = React__default.useState(false),
_React$useState2 = slicedToArray(_React$useState, 2),
sortMenuOpen = _React$useState2[0],
setSortMenuOpen = _React$useState2[1];
var _store = slicedToArray(store, 2),
dispatch = _store[1];
return React__default.createElement(Popup, {
isOpen: sortMenuOpen,
position: "bottom",
onClickOutside: function onClickOutside() {
return setSortMenuOpen(false);
},
content: React__default.createElement("ul", {
className: "menu__container menu"
}, sortModel.columns.map(function (_ref2) {
var label = _ref2.label,
sortKey = _ref2.sortKey;
return React__default.createElement(Menu.Item, {
key: sortKey,
onClick: function onClick() {
return dispatch({
type: "TOGGLE_SORT_COLUMN",
id: sortKey
});
},
onKeyUp: function onKeyUp() {}
}, label);
}))
}, React__default.createElement(Tooltip, {
content: "Sort",
position: "top"
}, React__default.createElement(IconButton, {
variant: "call-to-action",
onClick: function onClick() {
return setSortMenuOpen(!sortMenuOpen);
}
}, React__default.createElement("i", {
className: "aicon aicon__sort",
style: {
fontSize: "15px"
}
}))));
}
var withToolbar = (function () {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref$settings = _ref.settings,
settingsEnabled = _ref$settings === void 0 ? true : _ref$settings,
_ref$find = _ref.find,
findEnabled = _ref$find === void 0 ? true : _ref$find,
_ref$filter = _ref.filter,
filterModel = _ref$filter === void 0 ? {
fields: []
} : _ref$filter,
_ref$sort = _ref.sort,
sortModel = _ref$sort === void 0 ? {
columns: []
} : _ref$sort;
return function withToolbar(BaseComponent) {
var Table = function Table(_ref2) {
var className = _ref2.className,
rest = objectWithoutProperties(_ref2, ["className"]);
var _rest$store = slicedToArray(rest.store, 2),
_rest$store$ = _rest$store[0],
filterState = _rest$store$.filter,
settings = _rest$store$.settings,
dispatch = _rest$store[1];
return React__default.createElement(React__default.Fragment, null, filterState && filterState.isEnabled ? React__default.createElement(Filter$2, {
className: "table-toolbar__filter-row",
fields: filterModel.fields,
filterState: filterState.state,
setFilterState: function setFilterState(newState) {
return dispatch({
type: "UPDATE_FILTER",
state: newState
});
}
}) : null, spreadProps(BaseComponent)(objectSpread({
className: classnames("table--".concat(settings.density), className)
}, rest)));
};
Table.displayName = "Table";
hoistNonReactStatics_cjs(Table, BaseComponent);
Table.Toolbar = function (_ref3) {
var store = _ref3.store,
_ref3$customBefore = _ref3.customBefore,
customBefore = _ref3$customBefore === void 0 ? null : _ref3$customBefore,
_ref3$customAfter = _ref3.customAfter,
customAfter = _ref3$customAfter === void 0 ? null : _ref3$customAfter;
var _store = slicedToArray(store, 2),
state = _store[0],
dispatch = _store[1];
var filter = state.filter;
var filterClass = "filter__icon".concat(filter.isEnabled ? " filter__icon--with-badge " : "");
return React__default.createElement(Toolbar, null, customBefore, sortModel.columns.length !== 0 ? React__default.createElement(SortMenu, {
store: store,
sortModel: sortModel
}) : null, filterModel.fields.length !== 0 ? React__default.createElement(Tooltip, {
content: t(filter.isEnabled ? "Clear" : "Filter"),
position: "top"
}, React__default.createElement(IconButton, {
variant: "call-to-action",
onClick: function onClick() {
return dispatch({
type: filter.isEnabled ? "DISABLE_FILTER" : "ENABLE_FILTER"
});
},
onKeyUp: function onKeyUp(e) {}
}, React__default.createElement("i", {
className: filterClass,
style: {
fontSize: "15px"
}
}, filter.isEnabled ? React__default.createElement("i", {
className: "filter__icon__badge"
}) : null))) : null, findEnabled ? React__default.createElement(FindBox, {
store: store
}) : null, settingsEnabled ? React__default.createElement(SettingsMenu, {
store: store
}) : null, customAfter);
};
Table.reducer = function () {
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var action = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return objectSpread({}, BaseComponent.reducer(state, action), {
settings: settingsEnabled ? settingsReducer(state.settings, action) : {
density: "comfortable"
},
find: findEnabled ? findReducer(state.find, action) : undefined,
filter: filterModel ? filterReducer$1(state.filter, action) : undefined
});
};
if (sortModel.columns.length !== 0) {
return Table.Features.withColumnSorting()(Table);
}
return Table;
};
});
var Features = /*#__PURE__*/Object.freeze({
compose: compose,
withRowActions: withRowActions,
withRowContextMenu: withRowContextMenu,
withInlineEdit: withInlineEdit,
withRowSelection: withRowSelection,
withColumnResizing: withColumnResizing,
withColumnSorting: withColumnSorting,
withSubgrid: withSubgrid,
withToolbar: withToolbar
});
function Table(_ref) {
var className = _ref.className,
_ref$component = _ref.component,
component = _ref$component === void 0 ? "table" : _ref$component,
store = _ref.store,
rest = objectWithoutProperties(_ref, ["className", "component", "store"]);
return React__default.createElement(component, objectSpread({
className: classnames("table", className)
}, rest));
}
Table.displayName = "Table";
function Header$2(_ref2) {
var className = _ref2.className,
_ref2$component = _ref2.component,
component = _ref2$component === void 0 ? "thead" : _ref2$component,
rest = objectWithoutProperties(_ref2, ["className", "component"]);
return React__default.createElement(component, objectSpread({
className: classnames("table__header", className)
}, rest));
}
Header$2.displayName = "Table.Header";
function HeaderRow(_ref3) {
var className = _ref3.className,
_ref3$component = _ref3.component,
component = _ref3$component === void 0 ? "tr" : _ref3$component,
rest = objectWithoutProperties(_ref3, ["className", "component"]);
return React__default.createElement(component, objectSpread({
className: classnames("table__header__row", className)
}, rest));
}
HeaderRow.displayName = "Table.HeaderRow";
function HeaderCell(_ref4) {
var className = _ref4.className,
_ref4$component = _ref4.component,
component = _ref4$component === void 0 ? "th" : _ref4$component,
rest = objectWithoutProperties(_ref4, ["className", "component"]);
return React__default.createElement(component, objectSpread({
className: classnames("table__header__cell", className)
}, rest));
}
HeaderCell.displayName = "Table.HeaderCell";
var Body = React__default.forwardRef(function (_ref5, ref) {
var className = _ref5.className,
_ref5$component = _ref5.component,
component = _ref5$component === void 0 ? "tbody" : _ref5$component,
rest = objectWithoutProperties(_ref5, ["className", "component"]);
return React__default.createElement(component, objectSpread({
className: classnames("table__body", className)
}, rest, {
ref: ref
}));
});
Body.displayName = "Table.Body";
function Row(_ref6) {
var className = _ref6.className,
_ref6$component = _ref6.component,
component = _ref6$component === void 0 ? "tr" : _ref6$component,
rest = objectWithoutProperties(_ref6, ["className", "component"]);
return React__default.createElement(component, objectSpread({
className: classnames("table__body__row", className)
}, rest));
}
Row.displayName = "Table.Row";
function Cell(_ref7) {
var className = _ref7.className,
children = _ref7.children,
_ref7$component = _ref7.component,
component = _ref7$component === void 0 ? "td" : _ref7$component,
rest = objectWithoutProperties(_ref7, ["className", "children", "component"]);
return React__default.createElement(component, objectSpread({
children: children ? React__default.createElement("span", {
className: "table__body__cell__content"
}, children) : null,
className: classnames("table__body__cell", className)
}, rest));
}
Cell.displayName = "Table.Cell";
Table.Header = Header$2;
Table.HeaderRow = HeaderRow;
Table.HeaderCell = HeaderCell;
Table.Body = Body;
Table.Row = Row;
Table.Cell = Cell;
Table.reducer = function () {
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return state;
};
Table.Features = Features;
var getName = function getName(name) {
if (typeof name === "string") {
return React__default.createElement("span", {
className: "roadmap__step__label"
}, name);
}
return name;
};
var getClassNameByStatus = function getClassNameByStatus(status) {
return status === "current" ? "" : "roadmap__step--".concat(status);
};
/**
* A UI only component that renders a step and it's status.
* This component should be rendered as a child of a `Roadmap` component.
*/
function RoadmapStep(props) {
return React__default.createElement("span", {
onClick: props.status === "disabled" ? null : props.onClick,
className: "roadmap__step ".concat(getClassNameByStatus(props.status)),
role: "link",
tabIndex: 0,
onKeyDown: function onKeyDown() {},
title: props.title
}, React__default.createElement("span", {
className: "roadmap__step__circle"
}, props.step || props.index + 1), props.name ? getName(props.name) : null);
}
RoadmapStep.displayName = "Roadmap.Step";
RoadmapStep.defaultProps = {
status: "disabled"
};
/**
* UI container for the roadmap steps that indicate
* which step we're on. Roadmap is typically used in Wizards.
* @version 0.2.1
*/
function Roadmap(props) {
return React__default.createElement("ol", {
className: "roadmap"
}, props.children);
}
Roadmap.displayName = "Roadmap";
Roadmap.Step = RoadmapStep;
var WizardContext = React.createContext({
isFirstStep: false,
isLastStep: false,
isSubmitting: false,
step: 0,
steps: [],
setStep: function setStep() {
return undefined;
},
visitedSteps: []
});
function shouldAllowStepChange(_ref, _ref2) {
var _ref$beforeLeave = _ref.beforeLeave,
beforeLeave = _ref$beforeLeave === void 0 ? function () {
return Promise.resolve(true);
} : _ref$beforeLeave,
_ref$isValid = _ref.isValid,
isValid = _ref$isValid === void 0 ? function () {
return Promise.resolve(true);
} : _ref$isValid;
var _ref2$beforeEnter = _ref2.beforeEnter,
beforeEnter = _ref2$beforeEnter === void 0 ? function () {
return Promise.resolve(true);
} : _ref2$beforeEnter;
var isNextStepVisited = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
return new Promise(function (resolve, reject) {
isValid = isNextStepVisited ? function () {
return Promise.resolve(true);
} : isValid;
isValid().then(function (valid) {
if (!valid) {
return resolve(false);
} else {
beforeLeave().then(function (result) {
if (!result) {
return resolve(false);
} else {
beforeEnter().then(function (result) {
return resolve(!!result);
});
}
});
}
});
});
}
function Wizard(_ref3) {
var children = _ref3.children,
_ref3$initialVisited = _ref3.initialVisited,
initialVisited = _ref3$initialVisited === void 0 ? [true] : _ref3$initialVisited,
_ref3$isSubmitting = _ref3.isSubmitting,
isSubmitting = _ref3$isSubmitting === void 0 ? false : _ref3$isSubmitting,
steps = _ref3.steps,
rest = objectWithoutProperties(_ref3, ["children", "initialVisited", "isSubmitting", "steps"]);
if (!steps || steps.length === 0) {
throw new Error("Wizard: `steps` prop cannot be empty");
}
var _React$useState = React.useState(0),
_React$useState2 = slicedToArray(_React$useState, 2),
step = _React$useState2[0],
setStep = _React$useState2[1];
var _React$useState3 = React.useState(initialVisited),
_React$useState4 = slicedToArray(_React$useState3, 2),
visitedSteps = _React$useState4[0],
setVisitedSteps = _React$useState4[1];
var handleStepChange = React.useCallback(function (nextStepIndex) {
if (nextStepIndex < 0 || nextStepIndex >= steps.length) {
throw new Error("Wizard: Attempted to access an out-of-bounds step.");
}
var currentStep = steps[step];
var nextStep = steps[nextStepIndex];
shouldAllowStepChange(currentStep, nextStep, visitedSteps[nextStepIndex]).then(function (allow) {
if (!allow) {
if (nextStepIndex < step) {
throw new Error("Wizard: beforeEnter should never return false when attempting to go backwards.");
}
return;
}
setVisitedSteps(function (prevState) {
var newArray = prevState.slice();
newArray[nextStepIndex] = true;
return newArray;
});
setStep(nextStepIndex);
});
}, [steps, step, setStep, setVisitedSteps]);
var renderProps = React.useMemo(function () {
return {
isFirstStep: step === 0,
isLastStep: step === steps.length - 1,
isSubmitting: isSubmitting,
step: step,
steps: steps,
setStep: handleStepChange,
visitedSteps: visitedSteps
};
}, [isSubmitting, step, handleStepChange, visitedSteps]);
return React.createElement(WizardContext.Provider, {
value: renderProps
}, typeof children === "function" ? children(renderProps) : children);
}
Wizard.Controls = function (_ref4) {
var renderNextOnLastStep = _ref4.renderNextOnLastStep;
var _React$useContext = React.useContext(WizardContext),
isSubmitting = _React$useContext.isSubmitting,
isLastStep = _React$useContext.isLastStep,
isFirstStep = _React$useContext.isFirstStep,
step = _React$useContext.step,
setStep = _React$useContext.setStep;
return React.createElement("span", null, React.createElement(Button, {
onClick: function onClick() {
return setStep(step - 1);
},
disabled: isFirstStep || isSubmitting
}, "< Back"), " ", isLastStep && renderNextOnLastStep ? renderNextOnLastStep : React.createElement(Button, {
onClick: function onClick() {
return setStep(step + 1);
},
disabled: isLastStep || isSubmitting,
variant: "primary"
}, "Next >"));
};
Wizard.View = function () {
var _React$useContext2 = React.useContext(WizardContext),
step = _React$useContext2.step,
steps = _React$useContext2.steps;
return steps[step].render();
};
Wizard.Roadmap = function () {
var _React$useContext3 = React.useContext(WizardContext),
steps = _React$useContext3.steps,
step = _React$useContext3.step,
setStep = _React$useContext3.setStep,
visitedSteps = _React$useContext3.visitedSteps;
var getStatus = function getStatus(idx) {
if (step === idx) {
return "current";
}
return visitedSteps[idx] ? "enabled" : "disabled";
};
return React.createElement(Roadmap, null, steps.map(function (step, idx) {
return React.createElement(Roadmap.Step, {
index: idx,
key: step.name,
name: step.name,
onClick: function onClick() {
return setStep(idx);
},
status: getStatus(idx)
});
}));
};
function PageWizard(_ref) {
var page = _ref.page,
controls = _ref.controls,
rest = objectWithoutProperties(_ref, ["page", "controls"]);
if (!page) {
throw new Error("PageWizard: `page` prop is required");
}
var _page$buttonGroup = page.buttonGroup,
buttonGroup = _page$buttonGroup === void 0 ? [] : _page$buttonGroup,
restPage = objectWithoutProperties(page, ["buttonGroup"]);
return React.createElement(Wizard, rest, React.createElement(Shell.Page, _extends_1({}, restPage, {
buttonGroup: [React.createElement(Wizard.Controls, controls)].concat(toConsumableArray(buttonGroup))
}), React.createElement("div", {
style: {
margin: "10px 20px"
}
}, React.createElement(Wizard.Roadmap, null)), React.createElement("div", {
className: "panel",
style: {
padding: "20px",
margin: "10px 20px",
marginTop: 0
}
}, React.createElement(Wizard.View, null))));
}
var ENTER = 13;
var SPACE = 32;
var Icon$2 = React.forwardRef(function (_ref, ref) {
var className = _ref.className,
component = _ref.component,
rest = objectWithoutProperties(_ref, ["className", "component"]);
var onKeyUp = null;
if (rest.onClick || rest.onKeyUp) {
onKeyUp = React.useMemo(function (e) {
return function (e) {
if (rest.onKeyUp) {
rest.onKeyUp(e);
return;
}
if ((e.keyCode === ENTER || e.keyCode === SPACE) && rest.onClick) {
rest.onClick(e);
}
};
}, [rest.onClick, rest.onKeyUp]);
}
return React.createElement(component, objectSpread({
ref: ref,
className: classnames("droplets-icon", rest.disabled ? "icon--disabled" : null, className),
tabIndex: "0",
onClick: rest.onClick,
onKeyUp: onKeyUp,
disabled: rest.disabled
}, rest.disabled ? {
"aria-disabled": true
} : {}, component !== "button" ? {
role: "button"
} : {
type: "button"
}, rest));
});
Icon$2.defaultProps = {
component: "i"
};
var hasClass_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = hasClass;
function hasClass(element, className) {
if (element.classList) return !!className && element.classList.contains(className);else return (" " + (element.className.baseVal || element.className) + " ").indexOf(" " + className + " ") !== -1;
}
module.exports = exports["default"];
});
unwrapExports(hasClass_1);
var addClass_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = addClass;
var _hasClass = interopRequireDefault(hasClass_1);
function addClass(element, className) {
if (element.classList) element.classList.add(className);else if (!(0, _hasClass.default)(element, className)) if (typeof element.className === 'string') element.className = element.className + ' ' + className;else element.setAttribute('class', (element.className && element.className.baseVal || '') + ' ' + className);
}
module.exports = exports["default"];
});
unwrapExports(addClass_1);
function replaceClassName(origClass, classToRemove) {
return origClass.replace(new RegExp('(^|\\s)' + classToRemove + '(?:\\s|$)', 'g'), '$1').replace(/\s+/g, ' ').replace(/^\s*|\s*$/g, '');
}
var removeClass = 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));
};
var CSSTransition_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var PropTypes$$1 = _interopRequireWildcard(propTypes);
var _addClass = _interopRequireDefault(addClass_1);
var _removeClass = _interopRequireDefault(removeClass);
var _react = _interopRequireDefault(React__default);
var _Transition = _interopRequireDefault(Transition_1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
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; }
var addClass = function addClass(node, classes) {
return node && classes && classes.split(' ').forEach(function (c) {
return (0, _addClass.default)(node, c);
});
};
var removeClass$$1 = function removeClass$$1(node, classes) {
return node && classes && classes.split(' ').forEach(function (c) {
return (0, _removeClass.default)(node, c);
});
};
/**
* A transition component inspired by the excellent
* [ng-animate](http://www.nganimate.org/) 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 CSSS 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**.
*/
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.onEnter = function (node, appearing) {
var _this$getClassNames = _this.getClassNames(appearing ? 'appear' : 'enter'),
className = _this$getClassNames.className;
_this.removeClasses(node, 'exit');
addClass(node, className);
if (_this.props.onEnter) {
_this.props.onEnter(node, appearing);
}
};
_this.onEntering = function (node, appearing) {
var _this$getClassNames2 = _this.getClassNames(appearing ? 'appear' : 'enter'),
activeClassName = _this$getClassNames2.activeClassName;
_this.reflowAndAddClass(node, activeClassName);
if (_this.props.onEntering) {
_this.props.onEntering(node, appearing);
}
};
_this.onEntered = function (node, appearing) {
var appearClassName = _this.getClassNames('appear').doneClassName;
var enterClassName = _this.getClassNames('enter').doneClassName;
var doneClassName = appearing ? appearClassName + " " + enterClassName : enterClassName;
_this.removeClasses(node, appearing ? 'appear' : 'enter');
addClass(node, doneClassName);
if (_this.props.onEntered) {
_this.props.onEntered(node, appearing);
}
};
_this.onExit = function (node) {
var _this$getClassNames3 = _this.getClassNames('exit'),
className = _this$getClassNames3.className;
_this.removeClasses(node, 'appear');
_this.removeClasses(node, 'enter');
addClass(node, className);
if (_this.props.onExit) {
_this.props.onExit(node);
}
};
_this.onExiting = function (node) {
var _this$getClassNames4 = _this.getClassNames('exit'),
activeClassName = _this$getClassNames4.activeClassName;
_this.reflowAndAddClass(node, activeClassName);
if (_this.props.onExiting) {
_this.props.onExiting(node);
}
};
_this.onExited = function (node) {
var _this$getClassNames5 = _this.getClassNames('exit'),
doneClassName = _this$getClassNames5.doneClassName;
_this.removeClasses(node, 'exit');
addClass(node, doneClassName);
if (_this.props.onExited) {
_this.props.onExited(node);
}
};
_this.getClassNames = function (type) {
var classNames = _this.props.classNames;
var isStringClassNames = typeof classNames === 'string';
var prefix = isStringClassNames && classNames ? classNames + '-' : '';
var className = isStringClassNames ? prefix + type : classNames[type];
var activeClassName = isStringClassNames ? className + '-active' : classNames[type + 'Active'];
var doneClassName = isStringClassNames ? className + '-done' : classNames[type + 'Done'];
return {
className: className,
activeClassName: activeClassName,
doneClassName: doneClassName
};
};
return _this;
}
var _proto = CSSTransition.prototype;
_proto.removeClasses = function removeClasses(node, type) {
var _this$getClassNames6 = this.getClassNames(type),
className = _this$getClassNames6.className,
activeClassName = _this$getClassNames6.activeClassName,
doneClassName = _this$getClassNames6.doneClassName;
className && removeClass$$1(node, className);
activeClassName && removeClass$$1(node, activeClassName);
doneClassName && removeClass$$1(node, doneClassName);
};
_proto.reflowAndAddClass = function reflowAndAddClass(node, className) {
// This is for to force a repaint,
// which is necessary in order to transition styles when adding a class name.
if (className) {
/* eslint-disable no-unused-expressions */
node && node.scrollTop;
/* eslint-enable no-unused-expressions */
addClass(node, className);
}
};
_proto.render = function render() {
var props = _extends({}, this.props);
delete props.classNames;
return _react.default.createElement(_Transition.default, _extends({}, props, {
onEnter: this.onEnter,
onEntered: this.onEntered,
onEntering: this.onEntering,
onExit: this.onExit,
onExiting: this.onExiting,
onExited: this.onExited
}));
};
return CSSTransition;
}(_react.default.Component);
CSSTransition.defaultProps = {
classNames: ''
};
CSSTransition.propTypes = {};
var _default = CSSTransition;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(CSSTransition_1);
var ReplaceTransition_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = void 0;
var _propTypes = _interopRequireDefault(propTypes);
var _react = _interopRequireDefault(React__default);
var _TransitionGroup = _interopRequireDefault(TransitionGroup_1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
/**
* The `<ReplaceTransition>` component is a specialized `Transition` component
* that animates between two children.
*
* ```jsx
* <ReplaceTransition in>
* <Fade><div>I appear first</div></Fade>
* <Fade><div>I replace the above</div></Fade>
* </ReplaceTransition>
* ```
*/
var ReplaceTransition =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(ReplaceTransition, _React$Component);
function ReplaceTransition() {
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.handleEnter = function () {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return _this.handleLifecycle('onEnter', 0, args);
};
_this.handleEntering = function () {
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
return _this.handleLifecycle('onEntering', 0, args);
};
_this.handleEntered = function () {
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
return _this.handleLifecycle('onEntered', 0, args);
};
_this.handleExit = function () {
for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
args[_key5] = arguments[_key5];
}
return _this.handleLifecycle('onExit', 1, args);
};
_this.handleExiting = function () {
for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
args[_key6] = arguments[_key6];
}
return _this.handleLifecycle('onExiting', 1, args);
};
_this.handleExited = function () {
for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
args[_key7] = arguments[_key7];
}
return _this.handleLifecycle('onExited', 1, args);
};
return _this;
}
var _proto = ReplaceTransition.prototype;
_proto.handleLifecycle = function handleLifecycle(handler, idx, originalArgs) {
var _child$props;
var children = this.props.children;
var child = _react.default.Children.toArray(children)[idx];
if (child.props[handler]) (_child$props = child.props)[handler].apply(_child$props, originalArgs);
if (this.props[handler]) this.props[handler]((0, _reactDom.findDOMNode)(this));
};
_proto.render = function render() {
var _this$props = this.props,
children = _this$props.children,
inProp = _this$props.in,
props = _objectWithoutPropertiesLoose(_this$props, ["children", "in"]);
var _React$Children$toArr = _react.default.Children.toArray(children),
first = _React$Children$toArr[0],
second = _React$Children$toArr[1];
delete props.onEnter;
delete props.onEntering;
delete props.onEntered;
delete props.onExit;
delete props.onExiting;
delete props.onExited;
return _react.default.createElement(_TransitionGroup.default, props, inProp ? _react.default.cloneElement(first, {
key: 'first',
onEnter: this.handleEnter,
onEntering: this.handleEntering,
onEntered: this.handleEntered
}) : _react.default.cloneElement(second, {
key: 'second',
onEnter: this.handleExit,
onEntering: this.handleExiting,
onEntered: this.handleExited
}));
};
return ReplaceTransition;
}(_react.default.Component);
ReplaceTransition.propTypes = {};
var _default = ReplaceTransition;
exports.default = _default;
module.exports = exports["default"];
});
unwrapExports(ReplaceTransition_1);
var reactTransitionGroup = createCommonjsModule(function (module) {
var _CSSTransition = _interopRequireDefault(CSSTransition_1);
var _ReplaceTransition = _interopRequireDefault(ReplaceTransition_1);
var _TransitionGroup = _interopRequireDefault(TransitionGroup_1);
var _Transition = _interopRequireDefault(Transition_1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
module.exports = {
Transition: _Transition.default,
TransitionGroup: _TransitionGroup.default,
ReplaceTransition: _ReplaceTransition.default,
CSSTransition: _CSSTransition.default
};
});
unwrapExports(reactTransitionGroup);
var reactTransitionGroup_1 = reactTransitionGroup.Transition;
var reactTransitionGroup_2 = reactTransitionGroup.TransitionGroup;
var reactTransitionGroup_3 = reactTransitionGroup.ReplaceTransition;
var reactTransitionGroup_4 = reactTransitionGroup.CSSTransition;
var messageBubbleIconMap = {
error: "close-solid",
success: "check",
info: "info",
warning: "warning"
};
function MessageBubble(props) {
var type = props.type,
pauseOnHover = props.pauseOnHover,
className = props.className,
dismissible = props.dismissible,
onDismiss = props.onDismiss,
onClose = props.onClose,
children = props.children,
timeout = props.timeout,
duration = props.duration,
rest = objectWithoutProperties(props, ["type", "pauseOnHover", "className", "dismissible", "onDismiss", "onClose", "children", "timeout", "duration"]);
var timer = React.useRef(null);
var _React$useState = React.useState(false),
_React$useState2 = slicedToArray(_React$useState, 2),
closed = _React$useState2[0],
setClosed = _React$useState2[1];
/**
* Handles closing the message bubble.
* @param {boolean} [force] Used by the timer to forcefully close the bubble.
*/
var handleClose = React.useCallback(function (force) {
var canClose = true;
if (typeof onClose === "function") {
canClose = onClose();
} else if (typeof onDismiss === "function") {
canClose = onDismiss();
}
if (typeof force === "boolean") {
canClose = force;
}
if (canClose !== false) {
setClosed(true);
}
}, [onClose, onDismiss, dismissible]);
var handleMouseEnter = React.useCallback(function () {
clearTimeout(timer.current);
}, [timer]);
var handleMouseLeave = React.useCallback(function () {
timer.current = setTimeout(function () {
return handleClose(true);
}, timeout);
}, [timer, setClosed, timeout]);
React.useEffect(function () {
var t$$1 = parseInt(timeout);
if (isNaN(t$$1)) {
throw new Error("timeout prop must be numeric");
}
timer.current = setTimeout(function () {
return handleClose(true);
}, t$$1); // used when the bubble is closed manually
return function () {
return clearTimeout(timer.current);
};
}, [timeout]);
return React.createElement(reactTransitionGroup_1, {
unmountOnExit: true,
mountOnEnter: true,
timeout: duration,
"in": !closed
}, function (status) {
return React.createElement("div", _extends_1({
className: classnames("messagebubble", "messagebubble--type-".concat(type), "messagebubble__animation--".concat(status), className),
onMouseEnter: pauseOnHover ? handleMouseEnter : null,
onMouseLeave: pauseOnHover ? handleMouseLeave : null,
role: type === "error" ? "alert" : "status",
"aria-live": type === "error" ? "assertive" : "polite",
"aria-atomic": "true"
}, rest), React.createElement("div", {
className: classnames("messagebubble__icon", "aicon aicon__".concat(messageBubbleIconMap[type] || messageBubbleIconMap["info"]), "messagebubble__icon--".concat(type))
}), React.createElement("div", {
className: "messagebubble__text"
}, children), dismissible ? React.createElement(IconButton, {
onClick: handleClose,
"data-testid": "message-bubble-close",
"aria-label": t("Close")
}, React.createElement("i", {
className: "messagebubble__close"
})) : null);
});
}
MessageBubble.defaultProps = {
timeout: 8000,
pauseOnHover: true,
dismissible: false,
duration: 750,
type: "info"
};
var MessageBoxContext = React.createContext({});
function MessageBox(_ref) {
var title = _ref.title,
children = _ref.children,
closed = _ref.closed,
onClose = _ref.onClose,
rest = objectWithoutProperties(_ref, ["title", "children", "closed", "onClose"]);
return React.createElement(MessageBoxContext.Provider, {
value: rest
}, React.createElement(Dialog, _extends_1({}, rest, {
closed: closed,
onClose: onClose,
className: "message-box",
draggable: false,
resizable: false
}), React.createElement(Dialog.Header, {
title: title
}), children));
}
var MessageBoxTitle = function MessageBoxTitle(_ref2) {
var children = _ref2.children,
className = _ref2.className,
rest = objectWithoutProperties(_ref2, ["children", "className"]);
var _React$useContext = React.useContext(MessageBoxContext),
type = _React$useContext.type;
return React.createElement("div", _extends_1({
className: classnames(className, "message-box__title")
}, rest), React.createElement("i", {
className: "message-box__icon message-box__icon--".concat(type)
}), React.createElement("div", {
className: "message-box__title__text"
}, children));
};
var MessageBoxDetails = function MessageBoxDetails(_ref3) {
var children = _ref3.children,
label = _ref3.label,
_ref3$collapsed = _ref3.collapsed,
collapsed = _ref3$collapsed === void 0 ? true : _ref3$collapsed;
var _React$useState = React.useState(collapsed),
_React$useState2 = slicedToArray(_React$useState, 2),
hideDetails = _React$useState2[0],
toggleDetails = _React$useState2[1];
var handleDetailsToggle = React.useCallback(function () {
return toggleDetails(!hideDetails);
}, [hideDetails, toggleDetails]);
return React.createElement(React.Fragment, null, typeof label === "function" ? React.createElement("span", {
className: "message-box__details__button"
}, label(hideDetails)) : React.createElement(IconButton, {
className: "message-box__details__button",
onClick: handleDetailsToggle
}, React.createElement("i", {
className: classnames("message-box__details__icon", hideDetails ? null : "message-box__details__icon--expanded")
}), " ", label), hideDetails ? null : React.createElement("div", {
className: "message-box__details"
}, children));
};
MessageBox.Title = MessageBoxTitle;
MessageBox.Content = function (_ref4) {
var children = _ref4.children;
return React.createElement(Dialog.Content, null, function () {
return children;
});
};
MessageBox.Footer = Dialog.Footer;
MessageBox.Details = MessageBoxDetails;
function Tabs(props) {
var vertical = props.vertical,
children = props.children,
className = props.className,
rest = objectWithoutProperties(props, ["vertical", "children", "className"]);
var classes = classnames("tabs", className, {
"tabs--vertical": vertical
});
return React.createElement("ul", _extends_1({
className: classes
}, rest), children);
}
Tabs.defaultProps = {
vertical: false
};
Tabs.Tab = function Tab(_ref) {
var children = _ref.children,
className = _ref.className,
rest = objectWithoutProperties(_ref, ["children", "className"]);
var wrapped = wrapTextNode(children);
return React.createElement("li", _extends_1({
className: classnames("tabs__tab", className)
}, rest), React.cloneElement(wrapped, {
className: classnames("tabs__tab__control", wrapped.props.className)
}));
};
var _global$1 = createCommonjsModule(function (module) {
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self
// eslint-disable-next-line no-new-func
: Function('return this')();
if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef
});
var _core = createCommonjsModule(function (module) {
var core = module.exports = { version: '2.6.5' };
if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef
});
var _core_1 = _core.version;
var _aFunction = function (it) {
if (typeof it != 'function') throw TypeError(it + ' is not a function!');
return it;
};
// optional / simple context binding
var _ctx = function (fn, that, length) {
_aFunction(fn);
if (that === undefined) return fn;
switch (length) {
case 1: return function (a) {
return fn.call(that, a);
};
case 2: return function (a, b) {
return fn.call(that, a, b);
};
case 3: return function (a, b, c) {
return fn.call(that, a, b, c);
};
}
return function (/* ...args */) {
return fn.apply(that, arguments);
};
};
var _isObject$1 = function (it) {
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
var _anObject$1 = function (it) {
if (!_isObject$1(it)) throw TypeError(it + ' is not an object!');
return it;
};
var _fails$1 = function (exec) {
try {
return !!exec();
} catch (e) {
return true;
}
};
// Thank's IE8 for his funny defineProperty
var _descriptors$1 = !_fails$1(function () {
return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
});
var document$2 = _global$1.document;
// typeof document.createElement is 'object' in old IE
var is$1 = _isObject$1(document$2) && _isObject$1(document$2.createElement);
var _domCreate$1 = function (it) {
return is$1 ? document$2.createElement(it) : {};
};
var _ie8DomDefine$1 = !_descriptors$1 && !_fails$1(function () {
return Object.defineProperty(_domCreate$1('div'), 'a', { get: function () { return 7; } }).a != 7;
});
// 7.1.1 ToPrimitive(input [, PreferredType])
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
var _toPrimitive$1 = function (it, S) {
if (!_isObject$1(it)) return it;
var fn, val;
if (S && typeof (fn = it.toString) == 'function' && !_isObject$1(val = fn.call(it))) return val;
if (typeof (fn = it.valueOf) == 'function' && !_isObject$1(val = fn.call(it))) return val;
if (!S && typeof (fn = it.toString) == 'function' && !_isObject$1(val = fn.call(it))) return val;
throw TypeError("Can't convert object to primitive value");
};
var dP$2 = Object.defineProperty;
var f$1 = _descriptors$1 ? Object.defineProperty : function defineProperty(O, P, Attributes) {
_anObject$1(O);
P = _toPrimitive$1(P, true);
_anObject$1(Attributes);
if (_ie8DomDefine$1) try {
return dP$2(O, P, Attributes);
} catch (e) { /* empty */ }
if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!');
if ('value' in Attributes) O[P] = Attributes.value;
return O;
};
var _objectDp$1 = {
f: f$1
};
var _propertyDesc = function (bitmap, value) {
return {
enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
writable: !(bitmap & 4),
value: value
};
};
var _hide = _descriptors$1 ? function (object, key, value) {
return _objectDp$1.f(object, key, _propertyDesc(1, value));
} : function (object, key, value) {
object[key] = value;
return object;
};
var hasOwnProperty$b = {}.hasOwnProperty;
var _has = function (it, key) {
return hasOwnProperty$b.call(it, key);
};
var PROTOTYPE = 'prototype';
var $export = function (type, name, source) {
var IS_FORCED = type & $export.F;
var IS_GLOBAL = type & $export.G;
var IS_STATIC = type & $export.S;
var IS_PROTO = type & $export.P;
var IS_BIND = type & $export.B;
var IS_WRAP = type & $export.W;
var exports = IS_GLOBAL ? _core : _core[name] || (_core[name] = {});
var expProto = exports[PROTOTYPE];
var target = IS_GLOBAL ? _global$1 : IS_STATIC ? _global$1[name] : (_global$1[name] || {})[PROTOTYPE];
var key, own, out;
if (IS_GLOBAL) source = name;
for (key in source) {
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
if (own && _has(exports, key)) continue;
// export native or passed
out = own ? target[key] : source[key];
// prevent global pollution for namespaces
exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
// bind timers to global for call from export context
: IS_BIND && own ? _ctx(out, _global$1)
// wrap global constructors for prevent change them in library
: IS_WRAP && target[key] == out ? (function (C) {
var F = function (a, b, c) {
if (this instanceof C) {
switch (arguments.length) {
case 0: return new C();
case 1: return new C(a);
case 2: return new C(a, b);
} return new C(a, b, c);
} return C.apply(this, arguments);
};
F[PROTOTYPE] = C[PROTOTYPE];
return F;
// make static versions for prototype methods
})(out) : IS_PROTO && typeof out == 'function' ? _ctx(Function.call, out) : out;
// export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
if (IS_PROTO) {
(exports.virtual || (exports.virtual = {}))[key] = out;
// export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
if (type & $export.R && expProto && !expProto[key]) _hide(expProto, key, out);
}
}
};
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
var _export = $export;
var toString$1 = {}.toString;
var _cof = function (it) {
return toString$1.call(it).slice(8, -1);
};
// fallback for non-array-like ES3 and non-enumerable old V8 strings
// eslint-disable-next-line no-prototype-builtins
var _iobject = Object('z').propertyIsEnumerable(0) ? Object : function (it) {
return _cof(it) == 'String' ? it.split('') : Object(it);
};
// 7.2.1 RequireObjectCoercible(argument)
var _defined = function (it) {
if (it == undefined) throw TypeError("Can't call method on " + it);
return it;
};
// to indexed object, toObject with fallback for non-array-like ES3 strings
var _toIobject = function (it) {
return _iobject(_defined(it));
};
// 7.1.4 ToInteger
var ceil = Math.ceil;
var floor = Math.floor;
var _toInteger = function (it) {
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
// 7.1.15 ToLength
var min = Math.min;
var _toLength = function (it) {
return it > 0 ? min(_toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
var max = Math.max;
var min$1 = Math.min;
var _toAbsoluteIndex = function (index, length) {
index = _toInteger(index);
return index < 0 ? max(index + length, 0) : min$1(index, length);
};
// false -> Array#indexOf
// true -> Array#includes
var _arrayIncludes = function (IS_INCLUDES) {
return function ($this, el, fromIndex) {
var O = _toIobject($this);
var length = _toLength(O.length);
var index = _toAbsoluteIndex(fromIndex, length);
var value;
// Array#includes uses SameValueZero equality algorithm
// eslint-disable-next-line no-self-compare
if (IS_INCLUDES && el != el) while (length > index) {
value = O[index++];
// eslint-disable-next-line no-self-compare
if (value != value) return true;
// Array#indexOf ignores holes, Array#includes - not
} else for (;length > index; index++) if (IS_INCLUDES || index in O) {
if (O[index] === el) return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
var _library = true;
var _shared = createCommonjsModule(function (module) {
var SHARED = '__core-js_shared__';
var store = _global$1[SHARED] || (_global$1[SHARED] = {});
(module.exports = function (key, value) {
return store[key] || (store[key] = value !== undefined ? value : {});
})('versions', []).push({
version: _core.version,
mode: _library ? 'pure' : 'global',
copyright: '© 2019 Denis Pushkarev (zloirock.ru)'
});
});
var id = 0;
var px = Math.random();
var _uid = function (key) {
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
var shared = _shared('keys');
var _sharedKey = function (key) {
return shared[key] || (shared[key] = _uid(key));
};
var arrayIndexOf = _arrayIncludes(false);
var IE_PROTO = _sharedKey('IE_PROTO');
var _objectKeysInternal = function (object, names) {
var O = _toIobject(object);
var i = 0;
var result = [];
var key;
for (key in O) if (key != IE_PROTO) _has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while (names.length > i) if (_has(O, key = names[i++])) {
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
// IE 8- don't enum bug keys
var _enumBugKeys = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var _objectKeys = Object.keys || function keys(O) {
return _objectKeysInternal(O, _enumBugKeys);
};
var f$2 = Object.getOwnPropertySymbols;
var _objectGops = {
f: f$2
};
var f$3 = {}.propertyIsEnumerable;
var _objectPie = {
f: f$3
};
// 7.1.13 ToObject(argument)
var _toObject = function (it) {
return Object(_defined(it));
};
// 19.1.2.1 Object.assign(target, source, ...)
var $assign = Object.assign;
// should work with symbols and should have deterministic property order (V8 bug)
var _objectAssign = !$assign || _fails$1(function () {
var A = {};
var B = {};
// eslint-disable-next-line no-undef
var S = Symbol();
var K = 'abcdefghijklmnopqrst';
A[S] = 7;
K.split('').forEach(function (k) { B[k] = k; });
return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
}) ? function assign(target, source) { // eslint-disable-line no-unused-vars
var T = _toObject(target);
var aLen = arguments.length;
var index = 1;
var getSymbols = _objectGops.f;
var isEnum = _objectPie.f;
while (aLen > index) {
var S = _iobject(arguments[index++]);
var keys = getSymbols ? _objectKeys(S).concat(getSymbols(S)) : _objectKeys(S);
var length = keys.length;
var j = 0;
var key;
while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key];
} return T;
} : $assign;
// 19.1.3.1 Object.assign(target, source)
_export(_export.S + _export.F, 'Object', { assign: _objectAssign });
var assign = _core.Object.assign;
var assign$1 = createCommonjsModule(function (module) {
module.exports = { "default": assign, __esModule: true };
});
unwrapExports(assign$1);
var _extends$2 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
var _assign2 = _interopRequireDefault(assign$1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _assign2.default || 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 _extends$3 = unwrapExports(_extends$2);
// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)
_export(_export.S + _export.F * !_descriptors$1, 'Object', { defineProperty: _objectDp$1.f });
var $Object = _core.Object;
var defineProperty$4 = function defineProperty(it, key, desc) {
return $Object.defineProperty(it, key, desc);
};
var defineProperty$5 = createCommonjsModule(function (module) {
module.exports = { "default": defineProperty$4, __esModule: true };
});
unwrapExports(defineProperty$5);
var defineProperty$7 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
var _defineProperty2 = _interopRequireDefault(defineProperty$5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (obj, key, value) {
if (key in obj) {
(0, _defineProperty2.default)(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
};
});
var _defineProperty$4 = unwrapExports(defineProperty$7);
var classCallCheck$2 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
});
var _classCallCheck$2 = unwrapExports(classCallCheck$2);
var createClass$2 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
var _defineProperty2 = _interopRequireDefault(defineProperty$5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = 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;
(0, _defineProperty2.default)(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
});
var _createClass$2 = unwrapExports(createClass$2);
// true -> String#at
// false -> String#codePointAt
var _stringAt = function (TO_STRING) {
return function (that, pos) {
var s = String(_defined(that));
var i = _toInteger(pos);
var l = s.length;
var a, b;
if (i < 0 || i >= l) return TO_STRING ? '' : undefined;
a = s.charCodeAt(i);
return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
? TO_STRING ? s.charAt(i) : a
: TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
};
};
var _redefine = _hide;
var _objectDps = _descriptors$1 ? Object.defineProperties : function defineProperties(O, Properties) {
_anObject$1(O);
var keys = _objectKeys(Properties);
var length = keys.length;
var i = 0;
var P;
while (length > i) _objectDp$1.f(O, P = keys[i++], Properties[P]);
return O;
};
var document$3 = _global$1.document;
var _html = document$3 && document$3.documentElement;
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var IE_PROTO$1 = _sharedKey('IE_PROTO');
var Empty = function () { /* empty */ };
var PROTOTYPE$1 = 'prototype';
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function () {
// Thrash, waste and sodomy: IE GC bug
var iframe = _domCreate$1('iframe');
var i = _enumBugKeys.length;
var lt = '<';
var gt = '>';
var iframeDocument;
iframe.style.display = 'none';
_html.appendChild(iframe);
iframe.src = 'javascript:'; // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
iframeDocument.close();
createDict = iframeDocument.F;
while (i--) delete createDict[PROTOTYPE$1][_enumBugKeys[i]];
return createDict();
};
var _objectCreate = Object.create || function create(O, Properties) {
var result;
if (O !== null) {
Empty[PROTOTYPE$1] = _anObject$1(O);
result = new Empty();
Empty[PROTOTYPE$1] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO$1] = O;
} else result = createDict();
return Properties === undefined ? result : _objectDps(result, Properties);
};
var _wks = createCommonjsModule(function (module) {
var store = _shared('wks');
var Symbol = _global$1.Symbol;
var USE_SYMBOL = typeof Symbol == 'function';
var $exports = module.exports = function (name) {
return store[name] || (store[name] =
USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : _uid)('Symbol.' + name));
};
$exports.store = store;
});
var def = _objectDp$1.f;
var TAG = _wks('toStringTag');
var _setToStringTag = function (it, tag, stat) {
if (it && !_has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag });
};
var IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
_hide(IteratorPrototype, _wks('iterator'), function () { return this; });
var _iterCreate = function (Constructor, NAME, next) {
Constructor.prototype = _objectCreate(IteratorPrototype, { next: _propertyDesc(1, next) });
_setToStringTag(Constructor, NAME + ' Iterator');
};
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var IE_PROTO$2 = _sharedKey('IE_PROTO');
var ObjectProto = Object.prototype;
var _objectGpo = Object.getPrototypeOf || function (O) {
O = _toObject(O);
if (_has(O, IE_PROTO$2)) return O[IE_PROTO$2];
if (typeof O.constructor == 'function' && O instanceof O.constructor) {
return O.constructor.prototype;
} return O instanceof Object ? ObjectProto : null;
};
var ITERATOR = _wks('iterator');
var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next`
var FF_ITERATOR = '@@iterator';
var KEYS = 'keys';
var VALUES = 'values';
var _iterDefine = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) {
_iterCreate(Constructor, NAME, next);
var getMethod = function (kind) {
if (!BUGGY && kind in proto) return proto[kind];
switch (kind) {
case KEYS: return function keys() { return new Constructor(this, kind); };
case VALUES: return function values() { return new Constructor(this, kind); };
} return function entries() { return new Constructor(this, kind); };
};
var TAG = NAME + ' Iterator';
var DEF_VALUES = DEFAULT == VALUES;
var VALUES_BUG = false;
var proto = Base.prototype;
var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT];
var $default = $native || getMethod(DEFAULT);
var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined;
var $anyNative = NAME == 'Array' ? proto.entries || $native : $native;
var methods, key, IteratorPrototype;
// Fix native
if ($anyNative) {
IteratorPrototype = _objectGpo($anyNative.call(new Base()));
if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) {
// Set @@toStringTag to native iterators
_setToStringTag(IteratorPrototype, TAG, true);
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
if (DEF_VALUES && $native && $native.name !== VALUES) {
VALUES_BUG = true;
$default = function values() { return $native.call(this); };
}
// Define iterator
if ((FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) {
_hide(proto, ITERATOR, $default);
}
if (DEFAULT) {
methods = {
values: DEF_VALUES ? $default : getMethod(VALUES),
keys: IS_SET ? $default : getMethod(KEYS),
entries: $entries
};
if (FORCED) for (key in methods) {
if (!(key in proto)) _redefine(proto, key, methods[key]);
} else _export(_export.P + _export.F * (BUGGY || VALUES_BUG), NAME, methods);
}
return methods;
};
var $at = _stringAt(true);
// 21.1.3.27 String.prototype[@@iterator]()
_iterDefine(String, 'String', function (iterated) {
this._t = String(iterated); // target
this._i = 0; // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function () {
var O = this._t;
var index = this._i;
var point;
if (index >= O.length) return { value: undefined, done: true };
point = $at(O, index);
this._i += point.length;
return { value: point, done: false };
});
var _iterStep = function (done, value) {
return { value: value, done: !!done };
};
// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
var es6_array_iterator = _iterDefine(Array, 'Array', function (iterated, kind) {
this._t = _toIobject(iterated); // target
this._i = 0; // next index
this._k = kind; // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function () {
var O = this._t;
var kind = this._k;
var index = this._i++;
if (!O || index >= O.length) {
this._t = undefined;
return _iterStep(1);
}
if (kind == 'keys') return _iterStep(0, index);
if (kind == 'values') return _iterStep(0, O[index]);
return _iterStep(0, [index, O[index]]);
}, 'values');
var TO_STRING_TAG = _wks('toStringTag');
var DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' +
'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' +
'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' +
'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' +
'TextTrackList,TouchList').split(',');
for (var i = 0; i < DOMIterables.length; i++) {
var NAME$1 = DOMIterables[i];
var Collection = _global$1[NAME$1];
var proto = Collection && Collection.prototype;
if (proto && !proto[TO_STRING_TAG]) _hide(proto, TO_STRING_TAG, NAME$1);
}
var f$4 = _wks;
var _wksExt = {
f: f$4
};
var iterator = _wksExt.f('iterator');
var iterator$1 = createCommonjsModule(function (module) {
module.exports = { "default": iterator, __esModule: true };
});
unwrapExports(iterator$1);
var _meta = createCommonjsModule(function (module) {
var META = _uid('meta');
var setDesc = _objectDp$1.f;
var id = 0;
var isExtensible = Object.isExtensible || function () {
return true;
};
var FREEZE = !_fails$1(function () {
return isExtensible(Object.preventExtensions({}));
});
var setMeta = function (it) {
setDesc(it, META, { value: {
i: 'O' + ++id, // object ID
w: {} // weak collections IDs
} });
};
var fastKey = function (it, create) {
// return primitive with prefix
if (!_isObject$1(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
if (!_has(it, META)) {
// can't set metadata to uncaught frozen object
if (!isExtensible(it)) return 'F';
// not necessary to add metadata
if (!create) return 'E';
// add missing metadata
setMeta(it);
// return object ID
} return it[META].i;
};
var getWeak = function (it, create) {
if (!_has(it, META)) {
// can't set metadata to uncaught frozen object
if (!isExtensible(it)) return true;
// not necessary to add metadata
if (!create) return false;
// add missing metadata
setMeta(it);
// return hash weak collections IDs
} return it[META].w;
};
// add metadata on freeze-family methods calling
var onFreeze = function (it) {
if (FREEZE && meta.NEED && isExtensible(it) && !_has(it, META)) setMeta(it);
return it;
};
var meta = module.exports = {
KEY: META,
NEED: false,
fastKey: fastKey,
getWeak: getWeak,
onFreeze: onFreeze
};
});
var _meta_1 = _meta.KEY;
var _meta_2 = _meta.NEED;
var _meta_3 = _meta.fastKey;
var _meta_4 = _meta.getWeak;
var _meta_5 = _meta.onFreeze;
var defineProperty$8 = _objectDp$1.f;
var _wksDefine = function (name) {
var $Symbol = _core.Symbol || (_core.Symbol = _library ? {} : _global$1.Symbol || {});
if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty$8($Symbol, name, { value: _wksExt.f(name) });
};
// all enumerable object keys, includes symbols
var _enumKeys = function (it) {
var result = _objectKeys(it);
var getSymbols = _objectGops.f;
if (getSymbols) {
var symbols = getSymbols(it);
var isEnum = _objectPie.f;
var i = 0;
var key;
while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key);
} return result;
};
// 7.2.2 IsArray(argument)
var _isArray = Array.isArray || function isArray(arg) {
return _cof(arg) == 'Array';
};
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
var hiddenKeys = _enumBugKeys.concat('length', 'prototype');
var f$5 = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
return _objectKeysInternal(O, hiddenKeys);
};
var _objectGopn = {
f: f$5
};
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var gOPN = _objectGopn.f;
var toString$2 = {}.toString;
var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
var getWindowNames = function (it) {
try {
return gOPN(it);
} catch (e) {
return windowNames.slice();
}
};
var f$6 = function getOwnPropertyNames(it) {
return windowNames && toString$2.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(_toIobject(it));
};
var _objectGopnExt = {
f: f$6
};
var gOPD = Object.getOwnPropertyDescriptor;
var f$7 = _descriptors$1 ? gOPD : function getOwnPropertyDescriptor(O, P) {
O = _toIobject(O);
P = _toPrimitive$1(P, true);
if (_ie8DomDefine$1) try {
return gOPD(O, P);
} catch (e) { /* empty */ }
if (_has(O, P)) return _propertyDesc(!_objectPie.f.call(O, P), O[P]);
};
var _objectGopd = {
f: f$7
};
// ECMAScript 6 symbols shim
var META = _meta.KEY;
var gOPD$1 = _objectGopd.f;
var dP$3 = _objectDp$1.f;
var gOPN$1 = _objectGopnExt.f;
var $Symbol = _global$1.Symbol;
var $JSON = _global$1.JSON;
var _stringify = $JSON && $JSON.stringify;
var PROTOTYPE$2 = 'prototype';
var HIDDEN = _wks('_hidden');
var TO_PRIMITIVE = _wks('toPrimitive');
var isEnum = {}.propertyIsEnumerable;
var SymbolRegistry = _shared('symbol-registry');
var AllSymbols = _shared('symbols');
var OPSymbols = _shared('op-symbols');
var ObjectProto$1 = Object[PROTOTYPE$2];
var USE_NATIVE = typeof $Symbol == 'function';
var QObject = _global$1.QObject;
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var setter = !QObject || !QObject[PROTOTYPE$2] || !QObject[PROTOTYPE$2].findChild;
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDesc = _descriptors$1 && _fails$1(function () {
return _objectCreate(dP$3({}, 'a', {
get: function () { return dP$3(this, 'a', { value: 7 }).a; }
})).a != 7;
}) ? function (it, key, D) {
var protoDesc = gOPD$1(ObjectProto$1, key);
if (protoDesc) delete ObjectProto$1[key];
dP$3(it, key, D);
if (protoDesc && it !== ObjectProto$1) dP$3(ObjectProto$1, key, protoDesc);
} : dP$3;
var wrap$1 = function (tag) {
var sym = AllSymbols[tag] = _objectCreate($Symbol[PROTOTYPE$2]);
sym._k = tag;
return sym;
};
var isSymbol$1 = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) {
return typeof it == 'symbol';
} : function (it) {
return it instanceof $Symbol;
};
var $defineProperty = function defineProperty(it, key, D) {
if (it === ObjectProto$1) $defineProperty(OPSymbols, key, D);
_anObject$1(it);
key = _toPrimitive$1(key, true);
_anObject$1(D);
if (_has(AllSymbols, key)) {
if (!D.enumerable) {
if (!_has(it, HIDDEN)) dP$3(it, HIDDEN, _propertyDesc(1, {}));
it[HIDDEN][key] = true;
} else {
if (_has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false;
D = _objectCreate(D, { enumerable: _propertyDesc(0, false) });
} return setSymbolDesc(it, key, D);
} return dP$3(it, key, D);
};
var $defineProperties = function defineProperties(it, P) {
_anObject$1(it);
var keys = _enumKeys(P = _toIobject(P));
var i = 0;
var l = keys.length;
var key;
while (l > i) $defineProperty(it, key = keys[i++], P[key]);
return it;
};
var $create = function create(it, P) {
return P === undefined ? _objectCreate(it) : $defineProperties(_objectCreate(it), P);
};
var $propertyIsEnumerable = function propertyIsEnumerable(key) {
var E = isEnum.call(this, key = _toPrimitive$1(key, true));
if (this === ObjectProto$1 && _has(AllSymbols, key) && !_has(OPSymbols, key)) return false;
return E || !_has(this, key) || !_has(AllSymbols, key) || _has(this, HIDDEN) && this[HIDDEN][key] ? E : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) {
it = _toIobject(it);
key = _toPrimitive$1(key, true);
if (it === ObjectProto$1 && _has(AllSymbols, key) && !_has(OPSymbols, key)) return;
var D = gOPD$1(it, key);
if (D && _has(AllSymbols, key) && !(_has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true;
return D;
};
var $getOwnPropertyNames = function getOwnPropertyNames(it) {
var names = gOPN$1(_toIobject(it));
var result = [];
var i = 0;
var key;
while (names.length > i) {
if (!_has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key);
} return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(it) {
var IS_OP = it === ObjectProto$1;
var names = gOPN$1(IS_OP ? OPSymbols : _toIobject(it));
var result = [];
var i = 0;
var key;
while (names.length > i) {
if (_has(AllSymbols, key = names[i++]) && (IS_OP ? _has(ObjectProto$1, key) : true)) result.push(AllSymbols[key]);
} return result;
};
// 19.4.1.1 Symbol([description])
if (!USE_NATIVE) {
$Symbol = function Symbol() {
if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!');
var tag = _uid(arguments.length > 0 ? arguments[0] : undefined);
var $set = function (value) {
if (this === ObjectProto$1) $set.call(OPSymbols, value);
if (_has(this, HIDDEN) && _has(this[HIDDEN], tag)) this[HIDDEN][tag] = false;
setSymbolDesc(this, tag, _propertyDesc(1, value));
};
if (_descriptors$1 && setter) setSymbolDesc(ObjectProto$1, tag, { configurable: true, set: $set });
return wrap$1(tag);
};
_redefine($Symbol[PROTOTYPE$2], 'toString', function toString() {
return this._k;
});
_objectGopd.f = $getOwnPropertyDescriptor;
_objectDp$1.f = $defineProperty;
_objectGopn.f = _objectGopnExt.f = $getOwnPropertyNames;
_objectPie.f = $propertyIsEnumerable;
_objectGops.f = $getOwnPropertySymbols;
if (_descriptors$1 && !_library) {
_redefine(ObjectProto$1, 'propertyIsEnumerable', $propertyIsEnumerable, true);
}
_wksExt.f = function (name) {
return wrap$1(_wks(name));
};
}
_export(_export.G + _export.W + _export.F * !USE_NATIVE, { Symbol: $Symbol });
for (var es6Symbols = (
// 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14
'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'
).split(','), j = 0; es6Symbols.length > j;)_wks(es6Symbols[j++]);
for (var wellKnownSymbols = _objectKeys(_wks.store), k = 0; wellKnownSymbols.length > k;) _wksDefine(wellKnownSymbols[k++]);
_export(_export.S + _export.F * !USE_NATIVE, 'Symbol', {
// 19.4.2.1 Symbol.for(key)
'for': function (key) {
return _has(SymbolRegistry, key += '')
? SymbolRegistry[key]
: SymbolRegistry[key] = $Symbol(key);
},
// 19.4.2.5 Symbol.keyFor(sym)
keyFor: function keyFor(sym) {
if (!isSymbol$1(sym)) throw TypeError(sym + ' is not a symbol!');
for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key;
},
useSetter: function () { setter = true; },
useSimple: function () { setter = false; }
});
_export(_export.S + _export.F * !USE_NATIVE, 'Object', {
// 19.1.2.2 Object.create(O [, Properties])
create: $create,
// 19.1.2.4 Object.defineProperty(O, P, Attributes)
defineProperty: $defineProperty,
// 19.1.2.3 Object.defineProperties(O, Properties)
defineProperties: $defineProperties,
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
// 19.1.2.7 Object.getOwnPropertyNames(O)
getOwnPropertyNames: $getOwnPropertyNames,
// 19.1.2.8 Object.getOwnPropertySymbols(O)
getOwnPropertySymbols: $getOwnPropertySymbols
});
// 24.3.2 JSON.stringify(value [, replacer [, space]])
$JSON && _export(_export.S + _export.F * (!USE_NATIVE || _fails$1(function () {
var S = $Symbol();
// MS Edge converts symbol values to JSON as {}
// WebKit converts symbol values to JSON as null
// V8 throws on boxed symbols
return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}';
})), 'JSON', {
stringify: function stringify(it) {
var args = [it];
var i = 1;
var replacer, $replacer;
while (arguments.length > i) args.push(arguments[i++]);
$replacer = replacer = args[1];
if (!_isObject$1(replacer) && it === undefined || isSymbol$1(it)) return; // IE8 returns string on undefined
if (!_isArray(replacer)) replacer = function (key, value) {
if (typeof $replacer == 'function') value = $replacer.call(this, key, value);
if (!isSymbol$1(value)) return value;
};
args[1] = replacer;
return _stringify.apply($JSON, args);
}
});
// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint)
$Symbol[PROTOTYPE$2][TO_PRIMITIVE] || _hide($Symbol[PROTOTYPE$2], TO_PRIMITIVE, $Symbol[PROTOTYPE$2].valueOf);
// 19.4.3.5 Symbol.prototype[@@toStringTag]
_setToStringTag($Symbol, 'Symbol');
// 20.2.1.9 Math[@@toStringTag]
_setToStringTag(Math, 'Math', true);
// 24.3.3 JSON[@@toStringTag]
_setToStringTag(_global$1.JSON, 'JSON', true);
_wksDefine('asyncIterator');
_wksDefine('observable');
var symbol = _core.Symbol;
var symbol$1 = createCommonjsModule(function (module) {
module.exports = { "default": symbol, __esModule: true };
});
unwrapExports(symbol$1);
var _typeof_1$1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
var _iterator2 = _interopRequireDefault(iterator$1);
var _symbol2 = _interopRequireDefault(symbol$1);
var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) {
return typeof obj === "undefined" ? "undefined" : _typeof(obj);
} : function (obj) {
return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj);
};
});
unwrapExports(_typeof_1$1);
var possibleConstructorReturn$2 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
var _typeof3 = _interopRequireDefault(_typeof_1$1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self;
};
});
var _possibleConstructorReturn$2 = unwrapExports(possibleConstructorReturn$2);
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var check = function (O, proto) {
_anObject$1(O);
if (!_isObject$1(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!");
};
var _setProto = {
set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line
function (test, buggy, set) {
try {
set = _ctx(Function.call, _objectGopd.f(Object.prototype, '__proto__').set, 2);
set(test, []);
buggy = !(test instanceof Array);
} catch (e) { buggy = true; }
return function setPrototypeOf(O, proto) {
check(O, proto);
if (buggy) O.__proto__ = proto;
else set(O, proto);
return O;
};
}({}, false) : undefined),
check: check
};
// 19.1.3.19 Object.setPrototypeOf(O, proto)
_export(_export.S, 'Object', { setPrototypeOf: _setProto.set });
var setPrototypeOf$1 = _core.Object.setPrototypeOf;
var setPrototypeOf$2 = createCommonjsModule(function (module) {
module.exports = { "default": setPrototypeOf$1, __esModule: true };
});
unwrapExports(setPrototypeOf$2);
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
_export(_export.S, 'Object', { create: _objectCreate });
var $Object$1 = _core.Object;
var create = function create(P, D) {
return $Object$1.create(P, D);
};
var create$1 = createCommonjsModule(function (module) {
module.exports = { "default": create, __esModule: true };
});
unwrapExports(create$1);
var inherits$2 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
var _setPrototypeOf2 = _interopRequireDefault(setPrototypeOf$2);
var _create2 = _interopRequireDefault(create$1);
var _typeof3 = _interopRequireDefault(_typeof_1$1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass)));
}
subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass;
};
});
var _inherits$2 = unwrapExports(inherits$2);
/**
* 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 warning$3 = function() {};
var warning_1$2 = warning$3;
function toArray(children) {
var ret = [];
React__default.Children.forEach(children, function (c) {
ret.push(c);
});
return ret;
}
/**
* Thought we still use `cloneElement` to pass `key`,
* other props can pass with context for future refactor.
*/
var treeContextTypes = {
rcTree: propTypes.shape({
root: propTypes.object,
prefixCls: propTypes.string,
selectable: propTypes.bool,
showIcon: propTypes.bool,
icon: propTypes.oneOfType([propTypes.node, propTypes.func]),
draggable: propTypes.bool,
checkable: propTypes.oneOfType([propTypes.bool, propTypes.node]),
checkStrictly: propTypes.bool,
disabled: propTypes.bool,
openTransitionName: propTypes.string,
openAnimation: propTypes.oneOfType([propTypes.string, propTypes.object]),
loadData: propTypes.func,
filterTreeNode: propTypes.func,
renderTreeNode: propTypes.func,
isKeyChecked: propTypes.func,
onNodeClick: propTypes.func,
onNodeDoubleClick: propTypes.func,
onNodeExpand: propTypes.func,
onNodeSelect: propTypes.func,
onNodeCheck: propTypes.func,
onNodeMouseEnter: propTypes.func,
onNodeMouseLeave: propTypes.func,
onNodeContextMenu: propTypes.func,
onNodeDragStart: propTypes.func,
onNodeDragEnter: propTypes.func,
onNodeDragOver: propTypes.func,
onNodeDragLeave: propTypes.func,
onNodeDragEnd: propTypes.func,
onNodeDrop: propTypes.func
// TODO: Remove this
// onBatchNodeCheck: PropTypes.func,
// onCheckConductFinished: PropTypes.func,
// Tree will store the entities when the treeNode refresh.
// User can pass the func to add more info to customize the additional info.
// processTreeEntity: PropTypes.func,
})
};
var nodeContextTypes = _extends$3({}, treeContextTypes, {
rcTreeNode: propTypes.shape({
onUpCheckConduct: propTypes.func
})
});
var objectWithoutProperties$1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.default = 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 _objectWithoutProperties$2 = unwrapExports(objectWithoutProperties$1);
var performanceNow = createCommonjsModule(function (module) {
// Generated by CoffeeScript 1.12.2
(function() {
var getNanoSeconds, hrtime, loadTime, moduleLoadTime, nodeLoadTime, upTime;
if ((typeof performance !== "undefined" && performance !== null) && performance.now) {
module.exports = function() {
return performance.now();
};
} else if ((typeof process !== "undefined" && process !== null) && process.hrtime) {
module.exports = function() {
return (getNanoSeconds() - nodeLoadTime) / 1e6;
};
hrtime = process.hrtime;
getNanoSeconds = function() {
var hr;
hr = hrtime();
return hr[0] * 1e9 + hr[1];
};
moduleLoadTime = getNanoSeconds();
upTime = process.uptime() * 1e9;
nodeLoadTime = moduleLoadTime - upTime;
} else if (Date.now) {
module.exports = function() {
return Date.now() - loadTime;
};
loadTime = Date.now();
} else {
module.exports = function() {
return new Date().getTime() - loadTime;
};
loadTime = new Date().getTime();
}
}).call(commonjsGlobal);
});
var root$1 = typeof window === 'undefined' ? commonjsGlobal : window
, vendors = ['moz', 'webkit']
, suffix = 'AnimationFrame'
, raf = root$1['request' + suffix]
, caf = root$1['cancel' + suffix] || root$1['cancelRequest' + suffix];
for(var i$1 = 0; !raf && i$1 < vendors.length; i$1++) {
raf = root$1[vendors[i$1] + 'Request' + suffix];
caf = root$1[vendors[i$1] + 'Cancel' + suffix]
|| root$1[vendors[i$1] + 'CancelRequest' + suffix];
}
// Some versions of FF have rAF but not cAF
if(!raf || !caf) {
var last = 0
, id$1 = 0
, queue = []
, frameDuration = 1000 / 60;
raf = function(callback) {
if(queue.length === 0) {
var _now = performanceNow()
, next = Math.max(0, frameDuration - (_now - last));
last = next + _now;
setTimeout(function() {
var cp = queue.slice(0);
// Clear queue here to prevent
// callbacks from appending listeners
// to the current frame's queue
queue.length = 0;
for(var i = 0; i < cp.length; i++) {
if(!cp[i].cancelled) {
try{
cp[i].callback(last);
} catch(e) {
setTimeout(function() { throw e }, 0);
}
}
}
}, Math.round(next));
}
queue.push({
handle: ++id$1,
callback: callback,
cancelled: false
});
return id$1
};
caf = function(handle) {
for(var i = 0; i < queue.length; i++) {
if(queue[i].handle === handle) {
queue[i].cancelled = true;
}
}
};
}
var raf_1 = function(fn) {
// Wrap in a new function to prevent
// `cancel` potentially being assigned
// to the native rAF function
return raf.call(root$1, fn)
};
var cancel = function() {
caf.apply(root$1, arguments);
};
var polyfill$1 = function(object) {
if (!object) {
object = root$1;
}
object.requestAnimationFrame = raf;
object.cancelAnimationFrame = caf;
};
raf_1.cancel = cancel;
raf_1.polyfill = polyfill$1;
var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
// ================= Transition =================
// Event wrapper. Copy from react source code
function makePrefixMap(styleProp, eventName) {
var prefixes = {};
prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
prefixes['Webkit' + styleProp] = 'webkit' + eventName;
prefixes['Moz' + styleProp] = 'moz' + eventName;
prefixes['ms' + styleProp] = 'MS' + eventName;
prefixes['O' + styleProp] = 'o' + eventName.toLowerCase();
return prefixes;
}
function getVendorPrefixes(domSupport, win) {
var prefixes = {
animationend: makePrefixMap('Animation', 'AnimationEnd'),
transitionend: makePrefixMap('Transition', 'TransitionEnd')
};
if (domSupport) {
if (!('AnimationEvent' in win)) {
delete prefixes.animationend.animation;
}
if (!('TransitionEvent' in win)) {
delete prefixes.transitionend.transition;
}
}
return prefixes;
}
var vendorPrefixes = getVendorPrefixes(canUseDOM, typeof window !== 'undefined' ? window : {});
var style = {};
if (canUseDOM) {
style = document.createElement('div').style;
}
var prefixedEventNames = {};
function getVendorPrefixedEventName(eventName) {
if (prefixedEventNames[eventName]) {
return prefixedEventNames[eventName];
}
var prefixMap = vendorPrefixes[eventName];
if (prefixMap) {
var stylePropList = Object.keys(prefixMap);
var len = stylePropList.length;
for (var i = 0; i < len; i += 1) {
var styleProp = stylePropList[i];
if (Object.prototype.hasOwnProperty.call(prefixMap, styleProp) && styleProp in style) {
prefixedEventNames[eventName] = prefixMap[styleProp];
return prefixedEventNames[eventName];
}
}
}
return '';
}
var animationEndName = getVendorPrefixedEventName('animationend');
var transitionEndName = getVendorPrefixedEventName('transitionend');
var supportTransition = !!(animationEndName && transitionEndName);
function getTransitionName(transitionName, transitionType) {
if (!transitionName) return null;
if (typeof transitionName === 'object') {
var type = transitionType.replace(/-\w/g, function (match) {
return match[1].toUpperCase();
});
return transitionName[type];
}
return transitionName + '-' + transitionType;
}
var STATUS_NONE = 'none';
var STATUS_APPEAR = 'appear';
var STATUS_ENTER = 'enter';
var STATUS_LEAVE = 'leave';
/**
* `transitionSupport` is used for none transition test case.
* Default we use browser transition event support check.
*/
function genCSSMotion(transitionSupport) {
function isSupportTransition(props) {
return !!(props.motionName && transitionSupport);
}
var CSSMotion = function (_React$Component) {
_inherits$2(CSSMotion, _React$Component);
function CSSMotion() {
_classCallCheck$2(this, CSSMotion);
var _this = _possibleConstructorReturn$2(this, (CSSMotion.__proto__ || Object.getPrototypeOf(CSSMotion)).call(this));
_this.onDomUpdate = function () {
var _this$state = _this.state,
status = _this$state.status,
newStatus = _this$state.newStatus;
var _this$props = _this.props,
onAppearStart = _this$props.onAppearStart,
onEnterStart = _this$props.onEnterStart,
onLeaveStart = _this$props.onLeaveStart,
onAppearActive = _this$props.onAppearActive,
onEnterActive = _this$props.onEnterActive,
onLeaveActive = _this$props.onLeaveActive,
motionAppear = _this$props.motionAppear,
motionEnter = _this$props.motionEnter,
motionLeave = _this$props.motionLeave;
if (!isSupportTransition(_this.props)) {
return;
}
// Event injection
var $ele = _reactDom.findDOMNode(_this);
if (_this.$ele !== $ele) {
_this.removeEventListener(_this.$ele);
_this.addEventListener($ele);
_this.$ele = $ele;
}
// Init status
if (newStatus && status === STATUS_APPEAR && motionAppear) {
_this.updateStatus(onAppearStart, null, null, function () {
_this.updateActiveStatus(onAppearActive, STATUS_APPEAR);
});
} else if (newStatus && status === STATUS_ENTER && motionEnter) {
_this.updateStatus(onEnterStart, null, null, function () {
_this.updateActiveStatus(onEnterActive, STATUS_ENTER);
});
} else if (newStatus && status === STATUS_LEAVE && motionLeave) {
_this.updateStatus(onLeaveStart, null, null, function () {
_this.updateActiveStatus(onLeaveActive, STATUS_LEAVE);
});
}
};
_this.onMotionEnd = function (event) {
var _this$state2 = _this.state,
status = _this$state2.status,
statusActive = _this$state2.statusActive;
var _this$props2 = _this.props,
onAppearEnd = _this$props2.onAppearEnd,
onEnterEnd = _this$props2.onEnterEnd,
onLeaveEnd = _this$props2.onLeaveEnd;
if (status === STATUS_APPEAR && statusActive) {
_this.updateStatus(onAppearEnd, { status: STATUS_NONE }, event);
} else if (status === STATUS_ENTER && statusActive) {
_this.updateStatus(onEnterEnd, { status: STATUS_NONE }, event);
} else if (status === STATUS_LEAVE && statusActive) {
_this.updateStatus(onLeaveEnd, { status: STATUS_NONE }, event);
}
};
_this.addEventListener = function ($ele) {
if (!$ele) return;
$ele.addEventListener(transitionEndName, _this.onMotionEnd);
$ele.addEventListener(animationEndName, _this.onMotionEnd);
};
_this.removeEventListener = function ($ele) {
if (!$ele) return;
$ele.removeEventListener(transitionEndName, _this.onMotionEnd);
$ele.removeEventListener(animationEndName, _this.onMotionEnd);
};
_this.updateStatus = function (styleFunc, additionalState, event, callback) {
var statusStyle = styleFunc ? styleFunc(_reactDom.findDOMNode(_this), event) : null;
if (statusStyle === false || _this._destroyed) return;
var nextStep = void 0;
if (callback) {
nextStep = function nextStep() {
_this.nextFrame(callback);
};
}
_this.setState(_extends$3({
statusStyle: typeof statusStyle === 'object' ? statusStyle : null,
newStatus: false
}, additionalState), nextStep); // Trigger before next frame & after `componentDidMount`
};
_this.updateActiveStatus = function (styleFunc, currentStatus) {
// `setState` use `postMessage` to trigger at the end of frame.
// Let's use requestAnimationFrame to update new state in next frame.
_this.nextFrame(function () {
var status = _this.state.status;
if (status !== currentStatus) return;
_this.updateStatus(styleFunc, { statusActive: true });
});
};
_this.nextFrame = function (func) {
_this.cancelNextFrame();
_this.raf = raf_1(func);
};
_this.cancelNextFrame = function () {
if (_this.raf) {
raf_1.cancel(_this.raf);
_this.raf = null;
}
};
_this.state = {
status: STATUS_NONE,
statusActive: false,
newStatus: false,
statusStyle: null
};
_this.$ele = null;
_this.raf = null;
return _this;
}
_createClass$2(CSSMotion, [{
key: 'componentDidMount',
value: function componentDidMount() {
this.onDomUpdate();
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate() {
this.onDomUpdate();
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this._destroyed = true;
this.removeEventListener(this.$ele);
this.cancelNextFrame();
}
}, {
key: 'render',
value: function render() {
var _classNames;
var _state = this.state,
status = _state.status,
statusActive = _state.statusActive,
statusStyle = _state.statusStyle;
var _props = this.props,
children = _props.children,
motionName = _props.motionName,
visible = _props.visible,
removeOnLeave = _props.removeOnLeave,
leavedClassName = _props.leavedClassName,
eventProps = _props.eventProps;
if (!children) return null;
if (status === STATUS_NONE || !isSupportTransition(this.props)) {
if (visible) {
return children(_extends$3({}, eventProps));
} else if (!removeOnLeave) {
return children(_extends$3({}, eventProps, { className: leavedClassName }));
}
return null;
}
return children(_extends$3({}, eventProps, {
className: classnames((_classNames = {}, _defineProperty$4(_classNames, getTransitionName(motionName, status), status !== STATUS_NONE), _defineProperty$4(_classNames, getTransitionName(motionName, status + '-active'), status !== STATUS_NONE && statusActive), _defineProperty$4(_classNames, motionName, typeof motionName === 'string'), _classNames)),
style: statusStyle
}));
}
}], [{
key: 'getDerivedStateFromProps',
value: function getDerivedStateFromProps(props, _ref) {
var prevProps = _ref.prevProps;
if (!isSupportTransition(props)) return {};
var visible = props.visible,
motionAppear = props.motionAppear,
motionEnter = props.motionEnter,
motionLeave = props.motionLeave,
motionLeaveImmediately = props.motionLeaveImmediately;
var newState = {
prevProps: props
};
// Appear
if (!prevProps && visible && motionAppear) {
newState.status = STATUS_APPEAR;
newState.statusActive = false;
newState.newStatus = true;
}
// Enter
if (prevProps && !prevProps.visible && visible && motionEnter) {
newState.status = STATUS_ENTER;
newState.statusActive = false;
newState.newStatus = true;
}
// Leave
if (prevProps && prevProps.visible && !visible && motionLeave || !prevProps && motionLeaveImmediately && !visible && motionLeave) {
newState.status = STATUS_LEAVE;
newState.statusActive = false;
newState.newStatus = true;
}
return newState;
}
}]);
return CSSMotion;
}(React__default.Component);
CSSMotion.propTypes = {
eventProps: propTypes.object, // Internal usage. Only pass by CSSMotionList
visible: propTypes.bool,
children: propTypes.func,
motionName: propTypes.oneOfType([propTypes.string, propTypes.object]),
motionAppear: propTypes.bool,
motionEnter: propTypes.bool,
motionLeave: propTypes.bool,
motionLeaveImmediately: propTypes.bool, // Trigger leave motion immediately
removeOnLeave: propTypes.bool,
leavedClassName: propTypes.string,
onAppearStart: propTypes.func,
onAppearActive: propTypes.func,
onAppearEnd: propTypes.func,
onEnterStart: propTypes.func,
onEnterActive: propTypes.func,
onEnterEnd: propTypes.func,
onLeaveStart: propTypes.func,
onLeaveActive: propTypes.func,
onLeaveEnd: propTypes.func
};
CSSMotion.defaultProps = {
visible: true,
motionEnter: true,
motionAppear: true,
motionLeave: true,
removeOnLeave: true
};
polyfill(CSSMotion);
return CSSMotion;
}
var CSSMotion = genCSSMotion(supportTransition);
var ICON_OPEN = 'open';
var ICON_CLOSE = 'close';
var defaultTitle = '---';
var TreeNode = function (_React$Component) {
_inherits$2(TreeNode, _React$Component);
function TreeNode(props) {
_classCallCheck$2(this, TreeNode);
var _this = _possibleConstructorReturn$2(this, (TreeNode.__proto__ || Object.getPrototypeOf(TreeNode)).call(this, props));
_initialiseProps.call(_this);
_this.state = {
dragNodeHighlight: false
};
return _this;
}
_createClass$2(TreeNode, [{
key: 'getChildContext',
value: function getChildContext() {
return _extends$3({}, this.context, {
rcTreeNode: {
// onUpCheckConduct: this.onUpCheckConduct,
}
});
}
// Isomorphic needn't load data in server side
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var eventKey = this.props.eventKey;
var registerTreeNode = this.context.rcTree.registerTreeNode;
this.syncLoadData(this.props);
registerTreeNode(eventKey, this);
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate() {
this.syncLoadData(this.props);
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
var eventKey = this.props.eventKey;
var registerTreeNode = this.context.rcTree.registerTreeNode;
registerTreeNode(eventKey, null);
}
// Disabled item still can be switch
// Drag usage
}, {
key: 'isSelectable',
value: function isSelectable() {
var selectable = this.props.selectable;
var treeSelectable = this.context.rcTree.selectable;
// Ignore when selectable is undefined or null
if (typeof selectable === 'boolean') {
return selectable;
}
return treeSelectable;
}
// Load data to avoid default expanded tree without data
// Switcher
// Checkbox
// Icon + Title
// Children list wrapped with `Animation`
}, {
key: 'render',
value: function render() {
var _classNames;
var loading = this.props.loading;
var _props = this.props,
className = _props.className,
style = _props.style,
dragOver = _props.dragOver,
dragOverGapTop = _props.dragOverGapTop,
dragOverGapBottom = _props.dragOverGapBottom,
isLeaf = _props.isLeaf,
expanded = _props.expanded,
selected = _props.selected,
checked = _props.checked,
halfChecked = _props.halfChecked,
otherProps = _objectWithoutProperties$2(_props, ['className', 'style', 'dragOver', 'dragOverGapTop', 'dragOverGapBottom', 'isLeaf', 'expanded', 'selected', 'checked', 'halfChecked']);
var _context$rcTree = this.context.rcTree,
prefixCls = _context$rcTree.prefixCls,
filterTreeNode = _context$rcTree.filterTreeNode,
draggable = _context$rcTree.draggable;
var disabled = this.isDisabled();
var dataOrAriaAttributeProps = getDataAndAria(otherProps);
return React__default.createElement(
'li',
_extends$3({
className: classnames(className, (_classNames = {}, _defineProperty$4(_classNames, prefixCls + '-treenode-disabled', disabled), _defineProperty$4(_classNames, prefixCls + '-treenode-switcher-' + (expanded ? 'open' : 'close'), !isLeaf), _defineProperty$4(_classNames, prefixCls + '-treenode-checkbox-checked', checked), _defineProperty$4(_classNames, prefixCls + '-treenode-checkbox-indeterminate', halfChecked), _defineProperty$4(_classNames, prefixCls + '-treenode-selected', selected), _defineProperty$4(_classNames, prefixCls + '-treenode-loading', loading), _defineProperty$4(_classNames, 'drag-over', !disabled && dragOver), _defineProperty$4(_classNames, 'drag-over-gap-top', !disabled && dragOverGapTop), _defineProperty$4(_classNames, 'drag-over-gap-bottom', !disabled && dragOverGapBottom), _defineProperty$4(_classNames, 'filter-node', filterTreeNode && filterTreeNode(this)), _classNames)),
style: style,
role: 'treeitem',
onDragEnter: draggable ? this.onDragEnter : undefined,
onDragOver: draggable ? this.onDragOver : undefined,
onDragLeave: draggable ? this.onDragLeave : undefined,
onDrop: draggable ? this.onDrop : undefined,
onDragEnd: draggable ? this.onDragEnd : undefined
}, dataOrAriaAttributeProps),
this.renderSwitcher(),
this.renderCheckbox(),
this.renderSelector(),
this.renderChildren()
);
}
}]);
return TreeNode;
}(React__default.Component);
TreeNode.propTypes = {
eventKey: propTypes.string, // Pass by parent `cloneElement`
prefixCls: propTypes.string,
className: propTypes.string,
style: propTypes.object,
root: propTypes.object,
onSelect: propTypes.func,
// By parent
expanded: propTypes.bool,
selected: propTypes.bool,
checked: propTypes.bool,
loaded: propTypes.bool,
loading: propTypes.bool,
halfChecked: propTypes.bool,
children: propTypes.node,
title: propTypes.node,
pos: propTypes.string,
dragOver: propTypes.bool,
dragOverGapTop: propTypes.bool,
dragOverGapBottom: propTypes.bool,
// By user
isLeaf: propTypes.bool,
checkable: propTypes.bool,
selectable: propTypes.bool,
disabled: propTypes.bool,
disableCheckbox: propTypes.bool,
icon: propTypes.oneOfType([propTypes.node, propTypes.func]),
switcherIcon: propTypes.oneOfType([propTypes.node, propTypes.func])
};
TreeNode.contextTypes = nodeContextTypes;
TreeNode.childContextTypes = nodeContextTypes;
TreeNode.defaultProps = {
title: defaultTitle
};
var _initialiseProps = function _initialiseProps() {
var _this2 = this;
this.onSelectorClick = function (e) {
// Click trigger before select/check operation
var onNodeClick = _this2.context.rcTree.onNodeClick;
onNodeClick(e, _this2);
if (_this2.isSelectable()) {
_this2.onSelect(e);
} else {
_this2.onCheck(e);
}
};
this.onSelectorDoubleClick = function (e) {
var onNodeDoubleClick = _this2.context.rcTree.onNodeDoubleClick;
onNodeDoubleClick(e, _this2);
};
this.onSelect = function (e) {
if (_this2.isDisabled()) return;
var onNodeSelect = _this2.context.rcTree.onNodeSelect;
e.preventDefault();
onNodeSelect(e, _this2);
};
this.onCheck = function (e) {
if (_this2.isDisabled()) return;
var _props2 = _this2.props,
disableCheckbox = _props2.disableCheckbox,
checked = _props2.checked;
var onNodeCheck = _this2.context.rcTree.onNodeCheck;
if (!_this2.isCheckable() || disableCheckbox) return;
e.preventDefault();
var targetChecked = !checked;
onNodeCheck(e, _this2, targetChecked);
};
this.onMouseEnter = function (e) {
var onNodeMouseEnter = _this2.context.rcTree.onNodeMouseEnter;
onNodeMouseEnter(e, _this2);
};
this.onMouseLeave = function (e) {
var onNodeMouseLeave = _this2.context.rcTree.onNodeMouseLeave;
onNodeMouseLeave(e, _this2);
};
this.onContextMenu = function (e) {
var onNodeContextMenu = _this2.context.rcTree.onNodeContextMenu;
onNodeContextMenu(e, _this2);
};
this.onDragStart = function (e) {
var onNodeDragStart = _this2.context.rcTree.onNodeDragStart;
e.stopPropagation();
_this2.setState({
dragNodeHighlight: true
});
onNodeDragStart(e, _this2);
try {
// ie throw error
// firefox-need-it
e.dataTransfer.setData('text/plain', '');
} catch (error) {
// empty
}
};
this.onDragEnter = function (e) {
var onNodeDragEnter = _this2.context.rcTree.onNodeDragEnter;
e.preventDefault();
e.stopPropagation();
onNodeDragEnter(e, _this2);
};
this.onDragOver = function (e) {
var onNodeDragOver = _this2.context.rcTree.onNodeDragOver;
e.preventDefault();
e.stopPropagation();
onNodeDragOver(e, _this2);
};
this.onDragLeave = function (e) {
var onNodeDragLeave = _this2.context.rcTree.onNodeDragLeave;
e.stopPropagation();
onNodeDragLeave(e, _this2);
};
this.onDragEnd = function (e) {
var onNodeDragEnd = _this2.context.rcTree.onNodeDragEnd;
e.stopPropagation();
_this2.setState({
dragNodeHighlight: false
});
onNodeDragEnd(e, _this2);
};
this.onDrop = function (e) {
var onNodeDrop = _this2.context.rcTree.onNodeDrop;
e.preventDefault();
e.stopPropagation();
_this2.setState({
dragNodeHighlight: false
});
onNodeDrop(e, _this2);
};
this.onExpand = function (e) {
var onNodeExpand = _this2.context.rcTree.onNodeExpand;
onNodeExpand(e, _this2);
};
this.setSelectHandle = function (node) {
_this2.selectHandle = node;
};
this.getNodeChildren = function () {
var children = _this2.props.children;
var originList = toArray(children).filter(function (node) {
return node;
});
var targetList = getNodeChildren(originList);
if (originList.length !== targetList.length) {
warnOnlyTreeNode();
}
return targetList;
};
this.getNodeState = function () {
var expanded = _this2.props.expanded;
if (_this2.isLeaf()) {
return null;
}
return expanded ? ICON_OPEN : ICON_CLOSE;
};
this.isLeaf = function () {
var _props3 = _this2.props,
isLeaf = _props3.isLeaf,
loaded = _props3.loaded;
var loadData = _this2.context.rcTree.loadData;
var hasChildren = _this2.getNodeChildren().length !== 0;
if (isLeaf === false) {
return false;
}
return isLeaf || !loadData && !hasChildren || loadData && loaded && !hasChildren;
};
this.isDisabled = function () {
var disabled = _this2.props.disabled;
var treeDisabled = _this2.context.rcTree.disabled;
// Follow the logic of Selectable
if (disabled === false) {
return false;
}
return !!(treeDisabled || disabled);
};
this.isCheckable = function () {
var checkable = _this2.props.checkable;
var treeCheckable = _this2.context.rcTree.checkable;
// Return false if tree or treeNode is not checkable
if (!treeCheckable || checkable === false) return false;
return treeCheckable;
};
this.syncLoadData = function (props) {
var expanded = props.expanded,
loading = props.loading,
loaded = props.loaded;
var _context$rcTree2 = _this2.context.rcTree,
loadData = _context$rcTree2.loadData,
onNodeLoad = _context$rcTree2.onNodeLoad;
if (loading) return;
// read from state to avoid loadData at same time
if (loadData && expanded && !_this2.isLeaf()) {
// We needn't reload data when has children in sync logic
// It's only needed in node expanded
var hasChildren = _this2.getNodeChildren().length !== 0;
if (!hasChildren && !loaded) {
onNodeLoad(_this2);
}
}
};
this.renderSwitcher = function () {
var _props4 = _this2.props,
expanded = _props4.expanded,
switcherIconFromProps = _props4.switcherIcon;
var _context$rcTree3 = _this2.context.rcTree,
prefixCls = _context$rcTree3.prefixCls,
switcherIconFromCtx = _context$rcTree3.switcherIcon;
var switcherIcon = switcherIconFromProps || switcherIconFromCtx;
if (_this2.isLeaf()) {
return React__default.createElement(
'span',
{ className: classnames(prefixCls + '-switcher', prefixCls + '-switcher-noop') },
typeof switcherIcon === 'function' ? switcherIcon(_extends$3({}, _this2.props, { isLeaf: true })) : switcherIcon
);
}
var switcherCls = classnames(prefixCls + '-switcher', prefixCls + '-switcher_' + (expanded ? ICON_OPEN : ICON_CLOSE));
return React__default.createElement(
'span',
{ onClick: _this2.onExpand, className: switcherCls },
typeof switcherIcon === 'function' ? switcherIcon(_extends$3({}, _this2.props, { isLeaf: false })) : switcherIcon
);
};
this.renderCheckbox = function () {
var _props5 = _this2.props,
checked = _props5.checked,
halfChecked = _props5.halfChecked,
disableCheckbox = _props5.disableCheckbox;
var prefixCls = _this2.context.rcTree.prefixCls;
var disabled = _this2.isDisabled();
var checkable = _this2.isCheckable();
if (!checkable) return null;
// [Legacy] Custom element should be separate with `checkable` in future
var $custom = typeof checkable !== 'boolean' ? checkable : null;
return React__default.createElement(
'span',
{
className: classnames(prefixCls + '-checkbox', checked && prefixCls + '-checkbox-checked', !checked && halfChecked && prefixCls + '-checkbox-indeterminate', (disabled || disableCheckbox) && prefixCls + '-checkbox-disabled'),
onClick: _this2.onCheck
},
$custom
);
};
this.renderIcon = function () {
var loading = _this2.props.loading;
var prefixCls = _this2.context.rcTree.prefixCls;
return React__default.createElement('span', {
className: classnames(prefixCls + '-iconEle', prefixCls + '-icon__' + (_this2.getNodeState() || 'docu'), loading && prefixCls + '-icon_loading')
});
};
this.renderSelector = function () {
var dragNodeHighlight = _this2.state.dragNodeHighlight;
var _props6 = _this2.props,
title = _props6.title,
selected = _props6.selected,
icon = _props6.icon,
loading = _props6.loading;
var _context$rcTree4 = _this2.context.rcTree,
prefixCls = _context$rcTree4.prefixCls,
showIcon = _context$rcTree4.showIcon,
treeIcon = _context$rcTree4.icon,
draggable = _context$rcTree4.draggable,
loadData = _context$rcTree4.loadData;
var disabled = _this2.isDisabled();
var wrapClass = prefixCls + '-node-content-wrapper';
// Icon - Still show loading icon when loading without showIcon
var $icon = void 0;
if (showIcon) {
var currentIcon = icon || treeIcon;
$icon = currentIcon ? React__default.createElement(
'span',
{
className: classnames(prefixCls + '-iconEle', prefixCls + '-icon__customize')
},
typeof currentIcon === 'function' ? React__default.createElement(currentIcon, _extends$3({}, _this2.props)) : currentIcon
) : _this2.renderIcon();
} else if (loadData && loading) {
$icon = _this2.renderIcon();
}
// Title
var $title = React__default.createElement(
'span',
{ className: prefixCls + '-title' },
title
);
return React__default.createElement(
'span',
{
ref: _this2.setSelectHandle,
title: typeof title === 'string' ? title : '',
className: classnames('' + wrapClass, wrapClass + '-' + (_this2.getNodeState() || 'normal'), !disabled && (selected || dragNodeHighlight) && prefixCls + '-node-selected', !disabled && draggable && 'draggable'),
draggable: !disabled && draggable || undefined,
'aria-grabbed': !disabled && draggable || undefined,
onMouseEnter: _this2.onMouseEnter,
onMouseLeave: _this2.onMouseLeave,
onContextMenu: _this2.onContextMenu,
onClick: _this2.onSelectorClick,
onDoubleClick: _this2.onSelectorDoubleClick,
onDragStart: draggable ? _this2.onDragStart : undefined
},
$icon,
$title
);
};
this.renderChildren = function () {
var _props7 = _this2.props,
expanded = _props7.expanded,
pos = _props7.pos;
var _context$rcTree5 = _this2.context.rcTree,
prefixCls = _context$rcTree5.prefixCls,
motion = _context$rcTree5.motion,
renderTreeNode = _context$rcTree5.renderTreeNode;
// Children TreeNode
var nodeList = _this2.getNodeChildren();
if (nodeList.length === 0) {
return null;
}
return React__default.createElement(
CSSMotion,
_extends$3({ visible: expanded }, motion),
function (_ref) {
var style = _ref.style,
className = _ref.className;
return React__default.createElement(
'ul',
{
className: classnames(className, prefixCls + '-child-tree', expanded && prefixCls + '-child-tree-open'),
style: style,
'data-expanded': expanded,
role: 'group'
},
mapChildren(nodeList, function (node, index) {
return renderTreeNode(node, index, pos);
})
);
}
);
};
};
TreeNode.isTreeNode = 1;
polyfill(TreeNode);
var DRAG_SIDE_RANGE = 0.25;
var DRAG_MIN_GAP = 2;
var onlyTreeNodeWarned = false;
function warnOnlyTreeNode() {
if (onlyTreeNodeWarned) return;
onlyTreeNodeWarned = true;
warning_1$2(false, 'Tree only accept TreeNode as children.');
}
function arrDel(list, value) {
var clone = list.slice();
var index = clone.indexOf(value);
if (index >= 0) {
clone.splice(index, 1);
}
return clone;
}
function arrAdd(list, value) {
var clone = list.slice();
if (clone.indexOf(value) === -1) {
clone.push(value);
}
return clone;
}
function posToArr(pos) {
return pos.split('-');
}
function getPosition$1(level, index) {
return level + '-' + index;
}
function isTreeNode(node) {
return node && node.type && node.type.isTreeNode;
}
function getNodeChildren(children) {
return toArray(children).filter(isTreeNode);
}
function isCheckDisabled(node) {
var _ref = node.props || {},
disabled = _ref.disabled,
disableCheckbox = _ref.disableCheckbox;
return !!(disabled || disableCheckbox);
}
function traverseTreeNodes(treeNodes, callback) {
function processNode(node, index, parent) {
var children = node ? node.props.children : treeNodes;
var pos = node ? getPosition$1(parent.pos, index) : 0;
// Filter children
var childList = getNodeChildren(children);
// Process node if is not root
if (node) {
var data = {
node: node,
index: index,
pos: pos,
key: node.key || pos,
parentPos: parent.node ? parent.pos : null
};
callback(data);
}
// Process children node
React.Children.forEach(childList, function (subNode, subIndex) {
processNode(subNode, subIndex, { node: node, pos: pos });
});
}
processNode(null);
}
/**
* Use `rc-util` `toArray` to get the children list which keeps the key.
* And return single node if children is only one(This can avoid `key` missing check).
*/
function mapChildren(children, func) {
var list = toArray(children).map(func);
if (list.length === 1) {
return list[0];
}
return list;
}
function getDragNodesKeys(treeNodes, node) {
var _node$props = node.props,
eventKey = _node$props.eventKey,
pos = _node$props.pos;
var dragNodesKeys = [];
traverseTreeNodes(treeNodes, function (_ref2) {
var key = _ref2.key;
dragNodesKeys.push(key);
});
dragNodesKeys.push(eventKey || pos);
return dragNodesKeys;
}
// Only used when drag, not affect SSR.
function calcDropPosition(event, treeNode) {
var clientY = event.clientY;
var _treeNode$selectHandl = treeNode.selectHandle.getBoundingClientRect(),
top = _treeNode$selectHandl.top,
bottom = _treeNode$selectHandl.bottom,
height = _treeNode$selectHandl.height;
var des = Math.max(height * DRAG_SIDE_RANGE, DRAG_MIN_GAP);
if (clientY <= top + des) {
return -1;
} else if (clientY >= bottom - des) {
return 1;
}
return 0;
}
/**
* Return selectedKeys according with multiple prop
* @param selectedKeys
* @param props
* @returns [string]
*/
function calcSelectedKeys(selectedKeys, props) {
if (!selectedKeys) return undefined;
var multiple = props.multiple;
if (multiple) {
return selectedKeys.slice();
}
if (selectedKeys.length) {
return [selectedKeys[0]];
}
return selectedKeys;
}
/**
* Since React internal will convert key to string,
* we need do this to avoid `checkStrictly` use number match
*/
function keyListToString(keyList) {
if (!keyList) return keyList;
return keyList.map(function (key) {
return String(key);
});
}
var internalProcessProps = function internalProcessProps(props) {
return props;
};
function convertDataToTree(treeData, processer) {
if (!treeData) return [];
var _ref3 = processer || {},
_ref3$processProps = _ref3.processProps,
processProps = _ref3$processProps === undefined ? internalProcessProps : _ref3$processProps;
var list = Array.isArray(treeData) ? treeData : [treeData];
return list.map(function (_ref4) {
var children = _ref4.children,
props = _objectWithoutProperties$2(_ref4, ['children']);
var childrenNodes = convertDataToTree(children, processer);
return React__default.createElement(
TreeNode,
processProps(props),
childrenNodes
);
});
}
// TODO: ========================= NEW LOGIC =========================
/**
* Calculate treeNodes entities. `processTreeEntity` is used for `rc-tree-select`
* @param treeNodes
* @param processTreeEntity User can customize the entity
*/
function convertTreeToEntities(treeNodes) {
var _ref5 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
initWrapper = _ref5.initWrapper,
processEntity = _ref5.processEntity,
onProcessFinished = _ref5.onProcessFinished;
var posEntities = {};
var keyEntities = {};
var wrapper = {
posEntities: posEntities,
keyEntities: keyEntities
};
if (initWrapper) {
wrapper = initWrapper(wrapper) || wrapper;
}
traverseTreeNodes(treeNodes, function (item) {
var node = item.node,
index = item.index,
pos = item.pos,
key = item.key,
parentPos = item.parentPos;
var entity = { node: node, index: index, key: key, pos: pos };
posEntities[pos] = entity;
keyEntities[key] = entity;
// Fill children
entity.parent = posEntities[parentPos];
if (entity.parent) {
entity.parent.children = entity.parent.children || [];
entity.parent.children.push(entity);
}
if (processEntity) {
processEntity(entity, wrapper);
}
});
if (onProcessFinished) {
onProcessFinished(wrapper);
}
return wrapper;
}
/**
* Parse `checkedKeys` to { checkedKeys, halfCheckedKeys } style
*/
function parseCheckedKeys(keys) {
if (!keys) {
return null;
}
// Convert keys to object format
var keyProps = void 0;
if (Array.isArray(keys)) {
// [Legacy] Follow the api doc
keyProps = {
checkedKeys: keys,
halfCheckedKeys: undefined
};
} else if (typeof keys === 'object') {
keyProps = {
checkedKeys: keys.checked || undefined,
halfCheckedKeys: keys.halfChecked || undefined
};
} else {
warning_1$2(false, '`checkedKeys` is not an array or an object');
return null;
}
keyProps.checkedKeys = keyListToString(keyProps.checkedKeys);
keyProps.halfCheckedKeys = keyListToString(keyProps.halfCheckedKeys);
return keyProps;
}
/**
* Conduct check state by the keyList. It will conduct up & from the provided key.
* If the conduct path reach the disabled or already checked / unchecked node will stop conduct.
* @param keyList list of keys
* @param isCheck is check the node or not
* @param keyEntities parsed by `convertTreeToEntities` function in Tree
* @param checkStatus Can pass current checked status for process (usually for uncheck operation)
* @returns {{checkedKeys: [], halfCheckedKeys: []}}
*/
function conductCheck(keyList, isCheck, keyEntities) {
var checkStatus = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var checkedKeys = {};
var halfCheckedKeys = {}; // Record the key has some child checked (include child half checked)
(checkStatus.checkedKeys || []).forEach(function (key) {
checkedKeys[key] = true;
});
(checkStatus.halfCheckedKeys || []).forEach(function (key) {
halfCheckedKeys[key] = true;
});
// Conduct up
function conductUp(key) {
if (checkedKeys[key] === isCheck) return;
var entity = keyEntities[key];
if (!entity) return;
var children = entity.children,
parent = entity.parent,
node = entity.node;
if (isCheckDisabled(node)) return;
// Check child node checked status
var everyChildChecked = true;
var someChildChecked = false; // Child checked or half checked
(children || []).filter(function (child) {
return !isCheckDisabled(child.node);
}).forEach(function (_ref6) {
var childKey = _ref6.key;
var childChecked = checkedKeys[childKey];
var childHalfChecked = halfCheckedKeys[childKey];
if (childChecked || childHalfChecked) someChildChecked = true;
if (!childChecked) everyChildChecked = false;
});
// Update checked status
if (isCheck) {
checkedKeys[key] = everyChildChecked;
} else {
checkedKeys[key] = false;
}
halfCheckedKeys[key] = someChildChecked;
if (parent) {
conductUp(parent.key);
}
}
// Conduct down
function conductDown(key) {
if (checkedKeys[key] === isCheck) return;
var entity = keyEntities[key];
if (!entity) return;
var children = entity.children,
node = entity.node;
if (isCheckDisabled(node)) return;
checkedKeys[key] = isCheck;
(children || []).forEach(function (child) {
conductDown(child.key);
});
}
function conduct(key) {
var entity = keyEntities[key];
if (!entity) {
warning_1$2(false, '\'' + key + '\' does not exist in the tree.');
return;
}
var children = entity.children,
parent = entity.parent,
node = entity.node;
checkedKeys[key] = isCheck;
if (isCheckDisabled(node)) return;
// Conduct down
(children || []).filter(function (child) {
return !isCheckDisabled(child.node);
}).forEach(function (child) {
conductDown(child.key);
});
// Conduct up
if (parent) {
conductUp(parent.key);
}
}
(keyList || []).forEach(function (key) {
conduct(key);
});
var checkedKeyList = [];
var halfCheckedKeyList = [];
// Fill checked list
Object.keys(checkedKeys).forEach(function (key) {
if (checkedKeys[key]) {
checkedKeyList.push(key);
}
});
// Fill half checked list
Object.keys(halfCheckedKeys).forEach(function (key) {
if (!checkedKeys[key] && halfCheckedKeys[key]) {
halfCheckedKeyList.push(key);
}
});
return {
checkedKeys: checkedKeyList,
halfCheckedKeys: halfCheckedKeyList
};
}
/**
* If user use `autoExpandParent` we should get the list of parent node
* @param keyList
* @param keyEntities
*/
function conductExpandParent(keyList, keyEntities) {
var expandedKeys = {};
function conductUp(key) {
if (expandedKeys[key]) return;
var entity = keyEntities[key];
if (!entity) return;
expandedKeys[key] = true;
var parent = entity.parent,
node = entity.node;
if (isCheckDisabled(node)) return;
if (parent) {
conductUp(parent.key);
}
}
(keyList || []).forEach(function (key) {
conductUp(key);
});
return Object.keys(expandedKeys);
}
/**
* Returns only the data- and aria- key/value pairs
* @param {object} props
*/
function getDataAndAria(props) {
return Object.keys(props).reduce(function (prev, key) {
if (key.substr(0, 5) === 'data-' || key.substr(0, 5) === 'aria-') {
prev[key] = props[key];
}
return prev;
}, {});
}
var Tree = function (_React$Component) {
_inherits$2(Tree, _React$Component);
function Tree(props) {
_classCallCheck$2(this, Tree);
var _this = _possibleConstructorReturn$2(this, (Tree.__proto__ || Object.getPrototypeOf(Tree)).call(this, props));
_this.onNodeDragStart = function (event, node) {
var expandedKeys = _this.state.expandedKeys;
var onDragStart = _this.props.onDragStart;
var _node$props = node.props,
eventKey = _node$props.eventKey,
children = _node$props.children;
_this.dragNode = node;
_this.setState({
dragNodesKeys: getDragNodesKeys(children, node),
expandedKeys: arrDel(expandedKeys, eventKey)
});
if (onDragStart) {
onDragStart({ event: event, node: node });
}
};
_this.onNodeDragEnter = function (event, node) {
var expandedKeys = _this.state.expandedKeys;
var onDragEnter = _this.props.onDragEnter;
var _node$props2 = node.props,
pos = _node$props2.pos,
eventKey = _node$props2.eventKey;
if (!_this.dragNode) return;
var dropPosition = calcDropPosition(event, node);
// Skip if drag node is self
if (_this.dragNode.props.eventKey === eventKey && dropPosition === 0) {
_this.setState({
dragOverNodeKey: '',
dropPosition: null
});
return;
}
// Ref: https://github.com/react-component/tree/issues/132
// Add timeout to let onDragLevel fire before onDragEnter,
// so that we can clean drag props for onDragLeave node.
// Macro task for this:
// https://html.spec.whatwg.org/multipage/webappapis.html#clean-up-after-running-script
setTimeout(function () {
// Update drag over node
_this.setState({
dragOverNodeKey: eventKey,
dropPosition: dropPosition
});
// Side effect for delay drag
if (!_this.delayedDragEnterLogic) {
_this.delayedDragEnterLogic = {};
}
Object.keys(_this.delayedDragEnterLogic).forEach(function (key) {
clearTimeout(_this.delayedDragEnterLogic[key]);
});
_this.delayedDragEnterLogic[pos] = setTimeout(function () {
var newExpandedKeys = arrAdd(expandedKeys, eventKey);
if (!('expandedKeys' in _this.props)) {
_this.setState({
expandedKeys: newExpandedKeys
});
}
if (onDragEnter) {
onDragEnter({ event: event, node: node, expandedKeys: newExpandedKeys });
}
}, 400);
}, 0);
};
_this.onNodeDragOver = function (event, node) {
var onDragOver = _this.props.onDragOver;
var eventKey = node.props.eventKey;
// Update drag position
if (_this.dragNode && eventKey === _this.state.dragOverNodeKey) {
var dropPosition = calcDropPosition(event, node);
if (dropPosition === _this.state.dropPosition) return;
_this.setState({
dropPosition: dropPosition
});
}
if (onDragOver) {
onDragOver({ event: event, node: node });
}
};
_this.onNodeDragLeave = function (event, node) {
var onDragLeave = _this.props.onDragLeave;
_this.setState({
dragOverNodeKey: ''
});
if (onDragLeave) {
onDragLeave({ event: event, node: node });
}
};
_this.onNodeDragEnd = function (event, node) {
var onDragEnd = _this.props.onDragEnd;
_this.setState({
dragOverNodeKey: ''
});
if (onDragEnd) {
onDragEnd({ event: event, node: node });
}
_this.dragNode = null;
};
_this.onNodeDrop = function (event, node) {
var _this$state = _this.state,
_this$state$dragNodes = _this$state.dragNodesKeys,
dragNodesKeys = _this$state$dragNodes === undefined ? [] : _this$state$dragNodes,
dropPosition = _this$state.dropPosition;
var onDrop = _this.props.onDrop;
var _node$props3 = node.props,
eventKey = _node$props3.eventKey,
pos = _node$props3.pos;
_this.setState({
dragOverNodeKey: ''
});
if (dragNodesKeys.indexOf(eventKey) !== -1) {
warning_1$2(false, 'Can not drop to dragNode(include it\'s children node)');
return;
}
var posArr = posToArr(pos);
var dropResult = {
event: event,
node: node,
dragNode: _this.dragNode,
dragNodesKeys: dragNodesKeys.slice(),
dropPosition: dropPosition + Number(posArr[posArr.length - 1])
};
if (dropPosition !== 0) {
dropResult.dropToGap = true;
}
if (onDrop) {
onDrop(dropResult);
}
_this.dragNode = null;
};
_this.onNodeClick = function (e, treeNode) {
var onClick = _this.props.onClick;
if (onClick) {
onClick(e, treeNode);
}
};
_this.onNodeDoubleClick = function (e, treeNode) {
var onDoubleClick = _this.props.onDoubleClick;
if (onDoubleClick) {
onDoubleClick(e, treeNode);
}
};
_this.onNodeSelect = function (e, treeNode) {
var selectedKeys = _this.state.selectedKeys;
var keyEntities = _this.state.keyEntities;
var _this$props = _this.props,
onSelect = _this$props.onSelect,
multiple = _this$props.multiple;
var _treeNode$props = treeNode.props,
selected = _treeNode$props.selected,
eventKey = _treeNode$props.eventKey;
var targetSelected = !selected;
// Update selected keys
if (!targetSelected) {
selectedKeys = arrDel(selectedKeys, eventKey);
} else if (!multiple) {
selectedKeys = [eventKey];
} else {
selectedKeys = arrAdd(selectedKeys, eventKey);
}
// [Legacy] Not found related usage in doc or upper libs
var selectedNodes = selectedKeys.map(function (key) {
var entity = keyEntities[key];
if (!entity) return null;
return entity.node;
}).filter(function (node) {
return node;
});
_this.setUncontrolledState({ selectedKeys: selectedKeys });
if (onSelect) {
var eventObj = {
event: 'select',
selected: targetSelected,
node: treeNode,
selectedNodes: selectedNodes,
nativeEvent: e.nativeEvent
};
onSelect(selectedKeys, eventObj);
}
};
_this.onNodeCheck = function (e, treeNode, checked) {
var _this$state2 = _this.state,
keyEntities = _this$state2.keyEntities,
oriCheckedKeys = _this$state2.checkedKeys,
oriHalfCheckedKeys = _this$state2.halfCheckedKeys;
var _this$props2 = _this.props,
checkStrictly = _this$props2.checkStrictly,
onCheck = _this$props2.onCheck;
var eventKey = treeNode.props.eventKey;
// Prepare trigger arguments
var checkedObj = void 0;
var eventObj = {
event: 'check',
node: treeNode,
checked: checked,
nativeEvent: e.nativeEvent
};
if (checkStrictly) {
var checkedKeys = checked ? arrAdd(oriCheckedKeys, eventKey) : arrDel(oriCheckedKeys, eventKey);
var halfCheckedKeys = arrDel(oriHalfCheckedKeys, eventKey);
checkedObj = { checked: checkedKeys, halfChecked: halfCheckedKeys };
eventObj.checkedNodes = checkedKeys.map(function (key) {
return keyEntities[key];
}).filter(function (entity) {
return entity;
}).map(function (entity) {
return entity.node;
});
_this.setUncontrolledState({ checkedKeys: checkedKeys });
} else {
var _conductCheck = conductCheck([eventKey], checked, keyEntities, {
checkedKeys: oriCheckedKeys, halfCheckedKeys: oriHalfCheckedKeys
}),
_checkedKeys = _conductCheck.checkedKeys,
_halfCheckedKeys = _conductCheck.halfCheckedKeys;
checkedObj = _checkedKeys;
// [Legacy] This is used for `rc-tree-select`
eventObj.checkedNodes = [];
eventObj.checkedNodesPositions = [];
eventObj.halfCheckedKeys = _halfCheckedKeys;
_checkedKeys.forEach(function (key) {
var entity = keyEntities[key];
if (!entity) return;
var node = entity.node,
pos = entity.pos;
eventObj.checkedNodes.push(node);
eventObj.checkedNodesPositions.push({ node: node, pos: pos });
});
_this.setUncontrolledState({
checkedKeys: _checkedKeys,
halfCheckedKeys: _halfCheckedKeys
});
}
if (onCheck) {
onCheck(checkedObj, eventObj);
}
};
_this.onNodeLoad = function (treeNode) {
return new Promise(function (resolve) {
// We need to get the latest state of loading/loaded keys
_this.setState(function (_ref) {
var _ref$loadedKeys = _ref.loadedKeys,
loadedKeys = _ref$loadedKeys === undefined ? [] : _ref$loadedKeys,
_ref$loadingKeys = _ref.loadingKeys,
loadingKeys = _ref$loadingKeys === undefined ? [] : _ref$loadingKeys;
var _this$props3 = _this.props,
loadData = _this$props3.loadData,
onLoad = _this$props3.onLoad;
var eventKey = treeNode.props.eventKey;
if (!loadData || loadedKeys.indexOf(eventKey) !== -1 || loadingKeys.indexOf(eventKey) !== -1) {
// react 15 will warn if return null
return {};
}
// Process load data
var promise = loadData(treeNode);
promise.then(function () {
var newLoadedKeys = arrAdd(_this.state.loadedKeys, eventKey);
var newLoadingKeys = arrDel(_this.state.loadingKeys, eventKey);
// onLoad should trigger before internal setState to avoid `loadData` trigger twice.
// https://github.com/ant-design/ant-design/issues/12464
if (onLoad) {
var eventObj = {
event: 'load',
node: treeNode
};
onLoad(newLoadedKeys, eventObj);
}
_this.setUncontrolledState({
loadedKeys: newLoadedKeys
});
_this.setState({
loadingKeys: newLoadingKeys
});
resolve();
});
return {
loadingKeys: arrAdd(loadingKeys, eventKey)
};
});
});
};
_this.onNodeExpand = function (e, treeNode) {
var expandedKeys = _this.state.expandedKeys;
var _this$props4 = _this.props,
onExpand = _this$props4.onExpand,
loadData = _this$props4.loadData;
var _treeNode$props2 = treeNode.props,
eventKey = _treeNode$props2.eventKey,
expanded = _treeNode$props2.expanded;
// Update selected keys
var index = expandedKeys.indexOf(eventKey);
var targetExpanded = !expanded;
warning_1$2(expanded && index !== -1 || !expanded && index === -1, 'Expand state not sync with index check');
if (targetExpanded) {
expandedKeys = arrAdd(expandedKeys, eventKey);
} else {
expandedKeys = arrDel(expandedKeys, eventKey);
}
_this.setUncontrolledState({ expandedKeys: expandedKeys });
if (onExpand) {
onExpand(expandedKeys, {
node: treeNode,
expanded: targetExpanded,
nativeEvent: e.nativeEvent
});
}
// Async Load data
if (targetExpanded && loadData) {
var loadPromise = _this.onNodeLoad(treeNode);
return loadPromise ? loadPromise.then(function () {
// [Legacy] Refresh logic
_this.setUncontrolledState({ expandedKeys: expandedKeys });
}) : null;
}
return null;
};
_this.onNodeMouseEnter = function (event, node) {
var onMouseEnter = _this.props.onMouseEnter;
if (onMouseEnter) {
onMouseEnter({ event: event, node: node });
}
};
_this.onNodeMouseLeave = function (event, node) {
var onMouseLeave = _this.props.onMouseLeave;
if (onMouseLeave) {
onMouseLeave({ event: event, node: node });
}
};
_this.onNodeContextMenu = function (event, node) {
var onRightClick = _this.props.onRightClick;
if (onRightClick) {
event.preventDefault();
onRightClick({ event: event, node: node });
}
};
_this.setUncontrolledState = function (state) {
var needSync = false;
var newState = {};
Object.keys(state).forEach(function (name) {
if (name in _this.props) return;
needSync = true;
newState[name] = state[name];
});
if (needSync) {
_this.setState(newState);
}
};
_this.registerTreeNode = function (key, node) {
if (node) {
_this.domTreeNodes[key] = node;
} else {
delete _this.domTreeNodes[key];
}
};
_this.isKeyChecked = function (key) {
var _this$state$checkedKe = _this.state.checkedKeys,
checkedKeys = _this$state$checkedKe === undefined ? [] : _this$state$checkedKe;
return checkedKeys.indexOf(key) !== -1;
};
_this.renderTreeNode = function (child, index) {
var level = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
var _this$state3 = _this.state,
keyEntities = _this$state3.keyEntities,
_this$state3$expanded = _this$state3.expandedKeys,
expandedKeys = _this$state3$expanded === undefined ? [] : _this$state3$expanded,
_this$state3$selected = _this$state3.selectedKeys,
selectedKeys = _this$state3$selected === undefined ? [] : _this$state3$selected,
_this$state3$halfChec = _this$state3.halfCheckedKeys,
halfCheckedKeys = _this$state3$halfChec === undefined ? [] : _this$state3$halfChec,
_this$state3$loadedKe = _this$state3.loadedKeys,
loadedKeys = _this$state3$loadedKe === undefined ? [] : _this$state3$loadedKe,
_this$state3$loadingK = _this$state3.loadingKeys,
loadingKeys = _this$state3$loadingK === undefined ? [] : _this$state3$loadingK,
dragOverNodeKey = _this$state3.dragOverNodeKey,
dropPosition = _this$state3.dropPosition;
var pos = getPosition$1(level, index);
var key = child.key || pos;
if (!keyEntities[key]) {
warnOnlyTreeNode();
return null;
}
return React__default.cloneElement(child, {
key: key,
eventKey: key,
expanded: expandedKeys.indexOf(key) !== -1,
selected: selectedKeys.indexOf(key) !== -1,
loaded: loadedKeys.indexOf(key) !== -1,
loading: loadingKeys.indexOf(key) !== -1,
checked: _this.isKeyChecked(key),
halfChecked: halfCheckedKeys.indexOf(key) !== -1,
pos: pos,
// [Legacy] Drag props
dragOver: dragOverNodeKey === key && dropPosition === 0,
dragOverGapTop: dragOverNodeKey === key && dropPosition === -1,
dragOverGapBottom: dragOverNodeKey === key && dropPosition === 1
});
};
_this.state = {
// TODO: Remove this eslint
posEntities: {}, // eslint-disable-line react/no-unused-state
keyEntities: {},
selectedKeys: [],
checkedKeys: [],
halfCheckedKeys: [],
loadedKeys: [],
loadingKeys: [],
treeNode: []
};
// Internal usage for `rc-tree-select`, we don't promise it will not change.
_this.domTreeNodes = {};
return _this;
}
_createClass$2(Tree, [{
key: 'getChildContext',
value: function getChildContext() {
var _props = this.props,
prefixCls = _props.prefixCls,
selectable = _props.selectable,
showIcon = _props.showIcon,
icon = _props.icon,
draggable = _props.draggable,
checkable = _props.checkable,
checkStrictly = _props.checkStrictly,
disabled = _props.disabled,
loadData = _props.loadData,
filterTreeNode = _props.filterTreeNode,
motion = _props.motion,
switcherIcon = _props.switcherIcon;
return {
rcTree: {
// root: this,
prefixCls: prefixCls,
selectable: selectable,
showIcon: showIcon,
icon: icon,
switcherIcon: switcherIcon,
draggable: draggable,
checkable: checkable,
checkStrictly: checkStrictly,
disabled: disabled,
motion: motion,
loadData: loadData,
filterTreeNode: filterTreeNode,
renderTreeNode: this.renderTreeNode,
isKeyChecked: this.isKeyChecked,
onNodeClick: this.onNodeClick,
onNodeDoubleClick: this.onNodeDoubleClick,
onNodeExpand: this.onNodeExpand,
onNodeSelect: this.onNodeSelect,
onNodeCheck: this.onNodeCheck,
onNodeLoad: this.onNodeLoad,
onNodeMouseEnter: this.onNodeMouseEnter,
onNodeMouseLeave: this.onNodeMouseLeave,
onNodeContextMenu: this.onNodeContextMenu,
onNodeDragStart: this.onNodeDragStart,
onNodeDragEnter: this.onNodeDragEnter,
onNodeDragOver: this.onNodeDragOver,
onNodeDragLeave: this.onNodeDragLeave,
onNodeDragEnd: this.onNodeDragEnd,
onNodeDrop: this.onNodeDrop,
registerTreeNode: this.registerTreeNode
}
};
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
var treeNode = this.state.treeNode;
var _props2 = this.props,
prefixCls = _props2.prefixCls,
className = _props2.className,
focusable = _props2.focusable,
style = _props2.style,
showLine = _props2.showLine,
_props2$tabIndex = _props2.tabIndex,
tabIndex = _props2$tabIndex === undefined ? 0 : _props2$tabIndex;
var domProps = getDataAndAria(this.props);
if (focusable) {
domProps.tabIndex = tabIndex;
domProps.onKeyDown = this.onKeyDown;
}
return React__default.createElement(
'ul',
_extends$3({}, domProps, {
className: classnames(prefixCls, className, _defineProperty$4({}, prefixCls + '-show-line', showLine)),
style: style,
role: 'tree',
unselectable: 'on'
}),
mapChildren(treeNode, function (node, index) {
return _this2.renderTreeNode(node, index);
})
);
}
}], [{
key: 'getDerivedStateFromProps',
value: function getDerivedStateFromProps(props, prevState) {
var prevProps = prevState.prevProps;
var newState = {
prevProps: props
};
function needSync(name) {
return !prevProps && name in props || prevProps && prevProps[name] !== props[name];
}
// ================== Tree Node ==================
var treeNode = null;
// Check if `treeData` or `children` changed and save into the state.
if (needSync('treeData')) {
treeNode = convertDataToTree(props.treeData);
} else if (needSync('children')) {
treeNode = toArray(props.children);
}
// Tree support filter function which will break the tree structure in the vdm.
// We cache the treeNodes in state so that we can return the treeNode in event trigger.
if (treeNode) {
newState.treeNode = treeNode;
// Calculate the entities data for quick match
var entitiesMap = convertTreeToEntities(treeNode);
newState.posEntities = entitiesMap.posEntities;
newState.keyEntities = entitiesMap.keyEntities;
}
var keyEntities = newState.keyEntities || prevState.keyEntities;
// ================ expandedKeys =================
if (needSync('expandedKeys') || prevProps && needSync('autoExpandParent')) {
newState.expandedKeys = props.autoExpandParent || !prevProps && props.defaultExpandParent ? conductExpandParent(props.expandedKeys, keyEntities) : props.expandedKeys;
} else if (!prevProps && props.defaultExpandAll) {
newState.expandedKeys = Object.keys(keyEntities);
} else if (!prevProps && props.defaultExpandedKeys) {
newState.expandedKeys = props.autoExpandParent || props.defaultExpandParent ? conductExpandParent(props.defaultExpandedKeys, keyEntities) : props.defaultExpandedKeys;
}
// ================ selectedKeys =================
if (props.selectable) {
if (needSync('selectedKeys')) {
newState.selectedKeys = calcSelectedKeys(props.selectedKeys, props);
} else if (!prevProps && props.defaultSelectedKeys) {
newState.selectedKeys = calcSelectedKeys(props.defaultSelectedKeys, props);
}
}
// ================= checkedKeys =================
if (props.checkable) {
var checkedKeyEntity = void 0;
if (needSync('checkedKeys')) {
checkedKeyEntity = parseCheckedKeys(props.checkedKeys) || {};
} else if (!prevProps && props.defaultCheckedKeys) {
checkedKeyEntity = parseCheckedKeys(props.defaultCheckedKeys) || {};
} else if (treeNode) {
// If treeNode changed, we also need check it
checkedKeyEntity = parseCheckedKeys(props.checkedKeys) || {
checkedKeys: prevState.checkedKeys,
halfCheckedKeys: prevState.halfCheckedKeys
};
}
if (checkedKeyEntity) {
var _checkedKeyEntity = checkedKeyEntity,
_checkedKeyEntity$che = _checkedKeyEntity.checkedKeys,
checkedKeys = _checkedKeyEntity$che === undefined ? [] : _checkedKeyEntity$che,
_checkedKeyEntity$hal = _checkedKeyEntity.halfCheckedKeys,
halfCheckedKeys = _checkedKeyEntity$hal === undefined ? [] : _checkedKeyEntity$hal;
if (!props.checkStrictly) {
var conductKeys = conductCheck(checkedKeys, true, keyEntities);
checkedKeys = conductKeys.checkedKeys;
halfCheckedKeys = conductKeys.halfCheckedKeys;
}
newState.checkedKeys = checkedKeys;
newState.halfCheckedKeys = halfCheckedKeys;
}
}
// ================= loadedKeys ==================
if (needSync('loadedKeys')) {
newState.loadedKeys = props.loadedKeys;
}
return newState;
}
/**
* [Legacy] Select handler is less small than node,
* so that this will trigger when drag enter node or select handler.
* This is a little tricky if customize css without padding.
* Better for use mouse move event to refresh drag state.
* But let's just keep it to avoid event trigger logic change.
*/
/**
* Only update the value which is not in props
*/
/**
* [Legacy] Original logic use `key` as tracking clue.
* We have to use `cloneElement` to pass `key`.
*/
}]);
return Tree;
}(React__default.Component);
Tree.propTypes = {
prefixCls: propTypes.string,
className: propTypes.string,
style: propTypes.object,
tabIndex: propTypes.oneOfType([propTypes.string, propTypes.number]),
children: propTypes.any,
treeData: propTypes.array, // Generate treeNode by children
showLine: propTypes.bool,
showIcon: propTypes.bool,
icon: propTypes.oneOfType([propTypes.node, propTypes.func]),
focusable: propTypes.bool,
selectable: propTypes.bool,
disabled: propTypes.bool,
multiple: propTypes.bool,
checkable: propTypes.oneOfType([propTypes.bool, propTypes.node]),
checkStrictly: propTypes.bool,
draggable: propTypes.bool,
defaultExpandParent: propTypes.bool,
autoExpandParent: propTypes.bool,
defaultExpandAll: propTypes.bool,
defaultExpandedKeys: propTypes.arrayOf(propTypes.string),
expandedKeys: propTypes.arrayOf(propTypes.string),
defaultCheckedKeys: propTypes.arrayOf(propTypes.string),
checkedKeys: propTypes.oneOfType([propTypes.arrayOf(propTypes.oneOfType([propTypes.string, propTypes.number])), propTypes.object]),
defaultSelectedKeys: propTypes.arrayOf(propTypes.string),
selectedKeys: propTypes.arrayOf(propTypes.string),
onClick: propTypes.func,
onDoubleClick: propTypes.func,
onExpand: propTypes.func,
onCheck: propTypes.func,
onSelect: propTypes.func,
onLoad: propTypes.func,
loadData: propTypes.func,
loadedKeys: propTypes.arrayOf(propTypes.string),
onMouseEnter: propTypes.func,
onMouseLeave: propTypes.func,
onRightClick: propTypes.func,
onDragStart: propTypes.func,
onDragEnter: propTypes.func,
onDragOver: propTypes.func,
onDragLeave: propTypes.func,
onDragEnd: propTypes.func,
onDrop: propTypes.func,
filterTreeNode: propTypes.func,
motion: propTypes.object,
switcherIcon: propTypes.oneOfType([propTypes.node, propTypes.func])
};
Tree.childContextTypes = treeContextTypes;
Tree.defaultProps = {
prefixCls: 'rc-tree',
showLine: false,
showIcon: true,
selectable: true,
multiple: false,
checkable: false,
disabled: false,
checkStrictly: false,
draggable: false,
defaultExpandParent: true,
autoExpandParent: false,
defaultExpandAll: false,
defaultExpandedKeys: [],
defaultCheckedKeys: [],
defaultSelectedKeys: []
};
polyfill(Tree);
Tree.TreeNode = TreeNode;
function Tree$1(props) {
var children = props.children,
className = props.className,
showIcons = props.showIcons,
onExpand = props.onExpand,
onSelect = props.onSelect,
onCheck = props.onCheck,
rest = objectWithoutProperties(props, ["children", "className", "showIcons", "onExpand", "onSelect", "onCheck"]);
var classes = classnames("tree", className);
return React.createElement(Tree, _extends_1({
className: classes,
showIcon: showIcons,
onExpand: onExpand,
onSelect: onSelect,
onCheck: onCheck
}, props), children);
}
Tree$1.defaultProps = {
checkable: false,
showIcons: false,
onExpand: function onExpand(expandedKeys) {},
onSelect: function onSelect(selectedKeys, info) {},
onCheck: function onCheck(checkedKeys, info) {}
};
TreeNode$1.displayName = "Tree";
function TreeNode$1(props) {
var children = props.children,
className = props.className,
rest = objectWithoutProperties(props, ["children", "className"]);
var classes = classnames("tree__node", className);
var switcherIcon = function switcherIcon(props) {
var expanded = props.expanded,
isLeaf = props.isLeaf;
if (isLeaf) {
return null;
}
var classes = classnames("tree__node__switcher", {
"tree__node__switcher--collapsed": !expanded
});
return React.createElement("span", {
className: classes
});
};
var icon = function icon(props) {
var isLeaf = props.isLeaf,
isRoot = props.isRoot;
var classes = classnames("tree__node__icon", iconClass);
var iconClass = "tree__node__icon--parent";
if (isRoot) {
iconClass = "tree__node__icon--root";
} else if (isLeaf) {
iconClass = "tree__node__icon--leaf";
}
return React.createElement("span", {
className: classes
});
};
return React.createElement(TreeNode, _extends_1({
className: classes,
switcherIcon: switcherIcon,
icon: icon
}, props), children);
}
hoistNonReactStatics_cjs(TreeNode$1, TreeNode);
TreeNode$1.defaultProps = {
isLeaf: false,
isRoot: false
};
TreeNode$1.displayName = "Tree.TreeNode";
Tree$1.TreeNode = TreeNode$1;
exports.Bubble = Bubble;
exports.Button = Button;
exports.IconButton = IconButton;
exports.Card = Card;
exports.Dialog = Dialog;
exports.Loader = Loader;
exports.Form = Form;
exports.withFormik = withFormik$1;
exports.Pagination = Pagination;
exports.Shell = Shell;
exports.Table = Table;
exports.Tooltip = Tooltip;
exports.Roadmap = Roadmap;
exports.Wizard = Wizard;
exports.PageWizard = PageWizard;
exports.Panel = Panel;
exports.Section = Section;
exports.Checkbox = Checkbox$1;
exports.Radio = Radio$1;
exports.Input = Input;
exports.Toolbar = Toolbar;
exports.Icon = Icon$2;
exports.Popup = Popup;
exports.DateRangePicker = DateRangePicker;
exports.MessageBubble = MessageBubble;
exports.MessageBox = MessageBox;
exports.Dropdown = Dropdown;
exports.Pill = Pill;
exports.Tabs = Tabs;
exports.Tree = Tree$1;
exports.Menu = Menu;
exports.Filter = Filter$2;
exports.withTranslation = withTranslation;
exports.withPortal = withPortal;
exports.Popover = Popover$1;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=droplets-core.umd.min.js.map