@bigbinary/neetoui
Version:
neetoUI drives the experience at all neeto products
435 lines (425 loc) • 19.2 kB
JavaScript
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _classCallCheck from '@babel/runtime/helpers/classCallCheck';
import _createClass from '@babel/runtime/helpers/createClass';
import { preprocessForSerialization } from '@bigbinary/neeto-cist';
import { stringify } from 'qs';
import { equals, complement, toPairs, pipe, omit, isEmpty } from 'ramda';
import { e as enTranslations } from './en-CIkXIYyl.js';
import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import pureDayjs from 'dayjs';
import localeData from 'dayjs/plugin/localeData';
import utc from 'dayjs/plugin/utc';
import weekday from 'dayjs/plugin/weekday';
import weekOfYear from 'dayjs/plugin/weekOfYear';
function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$1(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
var typeToPos = {
year: 0,
month: 1,
day: 2,
hour: 3,
minute: 4,
second: 5
};
var dateTimeFormatDefaults = {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit"
};
// Cache time-zone lookups from Intl.DateTimeFormat,
// as it is a *very* slow method.
var dtfCache = {};
var getDateTimeFormat = function getDateTimeFormat(timezone) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var timeZoneName = options.timeZoneName || "short";
var key = "".concat(timezone, "|").concat(timeZoneName);
var dtf = dtfCache[key];
if (!dtf) {
dtf = new Intl.DateTimeFormat("en-US", _objectSpread$1(_objectSpread$1({}, dateTimeFormatDefaults), {}, {
hour12: false,
timeZone: timezone,
timeZoneName: timeZoneName
}));
dtfCache[key] = dtf;
}
return dtf;
};
var localeStringifierCache = {};
var getLocaleStringifier = function getLocaleStringifier(timezone) {
var localeStringifier = localeStringifierCache[timezone];
if (!localeStringifier) {
localeStringifier = new Intl.DateTimeFormat("en-US", _objectSpread$1(_objectSpread$1({}, dateTimeFormatDefaults), {}, {
timeZone: timezone
}));
localeStringifierCache[timezone] = localeStringifier;
}
return localeStringifier;
};
// eslint-disable-next-line no-unused-vars
var timezone = (function (o, c, d) {
var defaultTimezone;
var makeFormatParts = function makeFormatParts(timestamp, timezone) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var date = new Date(timestamp);
var dtf = getDateTimeFormat(timezone, options);
return dtf.formatToParts(date);
};
var tzOffset = function tzOffset(timestamp, timezone) {
var formatResult = makeFormatParts(timestamp, timezone);
var filled = [];
for (var i = 0; i < formatResult.length; i += 1) {
var _formatResult$i = formatResult[i],
type = _formatResult$i.type,
value = _formatResult$i.value;
var pos = typeToPos[type];
if (pos >= 0) {
filled[pos] = parseInt(value, 10);
}
}
var hour = filled[3];
// Workaround for the same behavior in different node version
// https://github.com/nodejs/node/issues/33027
/* istanbul ignore next */
var fixedHour = hour === 24 ? 0 : hour;
var utcString = "".concat(filled[0], "-").concat(filled[1], "-").concat(filled[2], " ").concat(fixedHour, ":").concat(filled[4], ":").concat(filled[5], ":000");
var utcTs = d.utc(utcString).valueOf();
var asTS = Number(timestamp);
var over = asTS % 1000;
asTS -= over;
return (utcTs - asTS) / (60 * 1000);
};
// find the right offset a given local time. The o input is our guess, which determines which
// offset we'll pick in ambiguous cases (e.g. there are two 3 AMs b/c Fallback DST)
// https://github.com/moment/luxon/blob/master/src/datetime.js#L76
var fixOffset = function fixOffset(localTS, o0, tz) {
// Our UTC time is just a guess because our offset is just a guess
var utcGuess = localTS - o0 * 60 * 1000;
// Test whether the zone matches the offset for this ts
var o2 = tzOffset(utcGuess, tz);
// If so, offset didn't change and we're done
if (o0 === o2) {
return [utcGuess, o0];
}
// If not, change the ts by the difference in the offset
utcGuess -= (o2 - o0) * 60 * 1000;
// If that gives us the local time we want, we're done
var o3 = tzOffset(utcGuess, tz);
if (o2 === o3) {
return [utcGuess, o2];
}
// If it's different, we're in a hole time.
// The offset has changed, but the we don't adjust the time
return [localTS - Math.min(o2, o3) * 60 * 1000, Math.max(o2, o3)];
};
var proto = c.prototype;
// eslint-disable-next-line default-param-last
proto.tz = function () {
var timezone = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultTimezone;
var keepLocalTime = arguments.length > 1 ? arguments[1] : undefined;
var oldOffset = this.utcOffset();
var date = this.toDate();
var target = getLocaleStringifier(timezone).format(date);
var diff = Math.round((date - new Date(target)) / 1000 / 60);
var ins = d(target).$set("millisecond", this.$ms).utcOffset(-Math.round(date.getTimezoneOffset() / 15) * 15 - diff, true);
if (keepLocalTime) {
var newOffset = ins.utcOffset();
ins = ins.add(oldOffset - newOffset, "minute");
}
ins.$x.$timezone = timezone;
return ins;
};
proto.offsetName = function (type) {
// type: short(default) / long
var zone = this.$x.$timezone || d.tz.guess();
var result = makeFormatParts(this.valueOf(), zone, {
timeZoneName: type
}).find(function (m) {
return m.type.toLowerCase() === "timezonename";
});
return result && result.value;
};
var oldStartOf = proto.startOf;
proto.startOf = function (units, startOf) {
if (!this.$x || !this.$x.$timezone) {
return oldStartOf.call(this, units, startOf);
}
var withoutTz = d(this.format("YYYY-MM-DD HH:mm:ss:SSS"));
var startOfWithoutTz = oldStartOf.call(withoutTz, units, startOf);
return startOfWithoutTz.tz(this.$x.$timezone, true);
};
d.tz = function (input, arg1, arg2) {
var parseFormat = arg2 && arg1;
var timezone = arg2 || arg1 || defaultTimezone;
var previousOffset = tzOffset(Number(d()), timezone);
if (typeof input !== "string") {
// timestamp number || js Date || Day.js
return d(input).tz(timezone);
}
var localTs = d.utc(input, parseFormat).valueOf();
var _fixOffset = fixOffset(localTs, previousOffset, timezone),
_fixOffset2 = _slicedToArray(_fixOffset, 2),
targetTs = _fixOffset2[0],
targetOffset = _fixOffset2[1];
var ins = d(targetTs).utcOffset(targetOffset);
ins.$x.$timezone = timezone;
return ins;
};
d.tz.guess = function () {
return Intl.DateTimeFormat().resolvedOptions().timeZone;
};
d.tz.setDefault = function (timezone) {
defaultTimezone = timezone;
};
});
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
pureDayjs.extend(weekOfYear);
pureDayjs.extend(weekday);
pureDayjs.extend(localeData);
pureDayjs.extend(utc);
pureDayjs.extend(timezone);
var LRUCache = /*#__PURE__*/function () {
function LRUCache(limit) {
_classCallCheck(this, LRUCache);
this.limit = limit;
this.cache = new Map();
}
_createClass(LRUCache, [{
key: "get",
value: function get(key) {
var value = this.cache.get(key);
this.cache["delete"](key);
this.cache.set(key, value);
return value;
}
}, {
key: "set",
value: function set(key, value) {
if (this.cache.size >= this.limit) {
var oldestKey = this.cache.keys().next().value;
this.cache["delete"](oldestKey);
}
this.cache.set(key, value);
}
}, {
key: "has",
value: function has(key) {
return this.cache.has(key);
}
}]);
return LRUCache;
}();
var hasTimezone = function hasTimezone(dateString) {
var timezoneRegex = /Z|[+-]\d{2}:\d{2}$|[+-]\d{4}$|GMT([+-]\d{4})?$/;
return timezoneRegex.test(dateString);
};
var cache = new LRUCache(1000);
var dayjs = function dayjs() {
var _args$;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var cacheKey = JSON.stringify(args);
if (cache.has(cacheKey) && args[0] !== undefined) return cache.get(cacheKey);
var userTimezone = pureDayjs.tz().$x.$timezone;
var browserTimezone = pureDayjs.tz.guess();
var timezone = userTimezone || browserTimezone;
if (userTimezone === browserTimezone || userTimezone === undefined) {
var _result = pureDayjs.apply(void 0, args);
if (args[0] !== undefined) cache.set(cacheKey, _result);
return _result;
}
if (args.length > 0 && (typeof args[0] === "string" || args[0] === null)) {
var pureDayjsArgs = args.slice(0, Math.min(args.length, 2));
if (hasTimezone(args[0])) {
args[0] = pureDayjs.apply(void 0, _toConsumableArray(pureDayjsArgs));
} else {
args[0] = pureDayjs.apply(void 0, _toConsumableArray(pureDayjsArgs)).format("YYYY-MM-DD HH:mm:ss");
args[1] = "YYYY-MM-DD HH:mm:ss";
}
}
if (((_args$ = args[0]) === null || _args$ === void 0 ? void 0 : _args$.toString()) === "Invalid Date") {
var _result2 = pureDayjs.apply(void 0, args);
if (args[0] !== undefined) cache.set(cacheKey, _result2);
return _result2;
}
var result = args.length === 2 ? pureDayjs.tz.apply(pureDayjs, args.concat([timezone])) : pureDayjs.tz.apply(pureDayjs, args);
if (args[0] !== undefined) cache.set(cacheKey, result);
return result;
};
Object.assign(dayjs, _objectSpread({}, pureDayjs));
var getEnTranslationValue = function getEnTranslationValue(translationKey) {
return translationKey.split(".").reduce(function (acc, key) {
return acc[key];
}, enTranslations);
};
var getScrollbarWidth = function getScrollbarWidth() {
var _parentDiv$parentNode;
var parentDiv = document.createElement("div");
parentDiv.style.visibility = "hidden";
parentDiv.style.overflow = "scroll";
document.body.appendChild(parentDiv);
var childDiv = document.createElement("div");
parentDiv.appendChild(childDiv);
var scrollbarWidth = parentDiv.offsetWidth - childDiv.offsetWidth;
parentDiv === null || parentDiv === void 0 || (_parentDiv$parentNode = parentDiv.parentNode) === null || _parentDiv$parentNode === void 0 || _parentDiv$parentNode.removeChild(parentDiv);
return scrollbarWidth;
};
var getTimezoneAppliedDateTime = function getTimezoneAppliedDateTime(inputDateTime) {
if (!inputDateTime) return null;
var timezoneAppliedDateTime = function timezoneAppliedDateTime(date) {
return dayjs(date.format("YYYY-MM-DD HH:mm:ss"));
};
return Array.isArray(inputDateTime) ? inputDateTime.map(timezoneAppliedDateTime) : timezoneAppliedDateTime(inputDateTime);
};
var noop = function noop() {};
var hyphenize = function hyphenize(input) {
var fallbackString = "nui";
if (typeof input === "number") return String(input);
if (input && typeof input === "string" && input.replace) {
return input.replace(/[\s_]/g, "-").replace(/([a-z])([A-Z])/g, "$1-$2").replace(/-+/g, "-").toLowerCase();
}
return fallbackString;
};
var convertToDayjsObjects = function convertToDayjsObjects(value) {
return value instanceof Array ? value.map(function (date) {
return date ? dayjs(date) : date;
}) : value && dayjs(value);
};
var UniqueArray = /*#__PURE__*/function () {
function UniqueArray() {
_classCallCheck(this, UniqueArray);
this.array = [];
}
_createClass(UniqueArray, [{
key: "add",
value: function add(item) {
if (this.array.some(equals(item))) return false;
this.array.push(item);
return true;
}
}, {
key: "remove",
value: function remove(item) {
this.array = this.array.filter(complement(equals(item)));
}
}]);
return UniqueArray;
}();
var trapFocusOnFocusableElements = function trapFocusOnFocusableElements(ref) {
var _ref$current, _ref$current2;
var focusableElements = 'button,[href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
var firstFocusableElement = ref === null || ref === void 0 || (_ref$current = ref.current) === null || _ref$current === void 0 ? void 0 : _ref$current.querySelectorAll(focusableElements)[0];
var focusableContent = ref === null || ref === void 0 || (_ref$current2 = ref.current) === null || _ref$current2 === void 0 ? void 0 : _ref$current2.querySelectorAll(focusableElements);
var lastFocusableElement = focusableContent[(focusableContent === null || focusableContent === void 0 ? void 0 : focusableContent.length) - 1];
var onKeyDown = function onKeyDown(e) {
var isTabPressed = e.key === "Tab" || e.keyCode === 9;
if (!isTabPressed) {
return;
}
if (e.shiftKey) {
if (document.activeElement === firstFocusableElement) {
lastFocusableElement.focus();
e.preventDefault();
}
} else {
if (document.activeElement === lastFocusableElement) {
firstFocusableElement.focus();
e.preventDefault();
}
}
};
document.addEventListener("keydown", onKeyDown);
return function () {
return document.removeEventListener("keydown", onKeyDown);
};
};
var focusFirstFocusableElement = function focusFirstFocusableElement(ref) {
var _ref$current3;
var focusableElements = 'button,[href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
var firstFocusableElement = ref === null || ref === void 0 || (_ref$current3 = ref.current) === null || _ref$current3 === void 0 ? void 0 : _ref$current3.querySelectorAll(focusableElements)[0];
firstFocusableElement === null || firstFocusableElement === void 0 || firstFocusableElement.focus();
};
var hideScrollAndAddMargin = function hideScrollAndAddMargin() {
if (!document.body) return;
var scrollbarWidth = getScrollbarWidth();
document.body.style.overflow = "hidden";
document.body.style.marginRight = "".concat(scrollbarWidth, "px");
};
var showScrollAndRemoveMargin = function showScrollAndRemoveMargin() {
if (!document.body) return;
document.body.style.overflow = "auto";
document.body.style.marginRight = "0px";
};
var ANT_DESIGN_GLOBAL_TOKEN_OVERRIDES = {
colorBgContainer: "rgb(var(--neeto-ui-white))",
colorBorder: "rgb(var(--neeto-ui-gray-300))",
colorBorderSecondary: "rgb(var(--neeto-ui-gray-200))",
colorFillAlter: "rgb(var(--neeto-ui-gray-100))",
colorFillContent: "rgb(var(--neeto-ui-gray-100))",
colorFillSecondary: "rgb(var(--neeto-ui-gray-100))",
colorIcon: "rgb(var(--neeto-ui-gray-700))",
colorIconHover: "rgb(var(--neeto-ui-gray-800))",
colorLink: "rgb(var(--neeto-ui-primary-500))",
colorLinkActive: "rgb(var(--neeto-ui-primary-800))",
colorLinkHover: "rgb(var(--neeto-ui-primary-600))",
colorPrimary: "rgb(var(--neeto-ui-primary-500))",
colorSplit: "rgb(var(--neeto-ui-gray-100))",
colorText: "rgb(var(--neeto-ui-gray-800))",
colorTextDescription: "rgb(var(--neeto-ui-gray-700))",
colorTextDisabled: "rgb(var(--neeto-ui-gray-600))",
colorTextHeading: "rgb(var(--neeto-ui-black))",
colorTextPlaceholder: "rgb(var(--neeto-ui-gray-500))",
controlItemBgActive: "rgb(var(--neeto-ui-primary-100))",
controlItemBgActiveHover: "rgb(var(--neeto-ui-pastel-purple))",
controlItemBgHover: "rgb(var(--neeto-ui-gray-100))"
};
var buildUrl = function buildUrl(route, params) {
var placeHolders = [];
toPairs(params).forEach(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
key = _ref2[0],
value = _ref2[1];
if (!route.includes(":".concat(key))) return;
placeHolders.push(key);
route = route.replace(":".concat(key), encodeURIComponent(value));
});
var queryParams = pipe(omit(placeHolders), preprocessForSerialization, stringify)(params);
return isEmpty(queryParams) ? route : "".concat(route, "?").concat(queryParams);
};
var getLocale = function getLocale(i18n, t, translationKey) {
if (isEmpty(i18n)) return getEnTranslationValue(translationKey);
return i18n.exists(translationKey) ? t(translationKey) : getEnTranslationValue(translationKey);
};
var setToLocalStorage = function setToLocalStorage(key, value) {
try {
// eslint-disable-next-line @bigbinary/neeto/no-local-storage
localStorage.setItem(key, JSON.stringify(value));
} catch (_unused) {
// localStorage access can fail due to private browsing mode or storage restrictions
}
};
var removeFromLocalStorage = function removeFromLocalStorage(key) {
try {
// eslint-disable-next-line @bigbinary/neeto/no-local-storage
localStorage.removeItem(key);
} catch (_unused2) {
// localStorage access can fail due to private browsing mode or storage restrictions
}
};
var getFromLocalStorage = function getFromLocalStorage(key, defaultValue) {
try {
// eslint-disable-next-line @bigbinary/neeto/no-local-storage
var storedValue = localStorage.getItem(key);
return storedValue ? JSON.parse(storedValue) : defaultValue;
} catch (_unused3) {
// localStorage access can fail due to private browsing mode or storage restrictions
return defaultValue;
}
};
export { ANT_DESIGN_GLOBAL_TOKEN_OVERRIDES as A, UniqueArray as U, getFromLocalStorage as a, buildUrl as b, convertToDayjsObjects as c, dayjs as d, getTimezoneAppliedDateTime as e, hideScrollAndAddMargin as f, getLocale as g, hyphenize as h, showScrollAndRemoveMargin as i, focusFirstFocusableElement as j, noop as n, removeFromLocalStorage as r, setToLocalStorage as s, trapFocusOnFocusableElements as t };
//# sourceMappingURL=index-Dxaw6gl9.js.map