All Downloads are FREE. Search and download functionalities are using the official Maven repository.

package.cjs.utils.general.js Maven / Gradle / Ivy

Go to download

A package encapsulating common code across neeto projects including initializers, utility functions, common components and hooks and so on.

There is a newer version: 4.12.3
Show newest version
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.withEventTargetValue = exports.toLocale = exports.simulateApiCall = exports.showThumbsUpToastr = exports.setToLocalStorage = exports.removeFromLocalStorage = exports.parseQueryParams = exports.joinHyphenCase = exports.hyphenize = exports.getSubdomain = exports.getQueryParams = exports.getFromLocalStorage = exports.debounce = exports.copyToClipboard = exports.buildUrl = void 0;
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _i18next = _interopRequireDefault(require("i18next"));
var _neetoCist = require("@bigbinary/neeto-cist");
var _Toastr = _interopRequireDefault(require("@bigbinary/neetoui/Toastr"));
var _qs = require("qs");
var _ramda = require("ramda");
var _this = void 0;
var _excluded = ["toCamelCase"];
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) { (0, _defineProperty2["default"])(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; }
var toCamelCasedString = function toCamelCasedString(string) {
  return string.replace(/[_-]+(\w)/g, function (_, nextChar) {
    return nextChar.toUpperCase();
  });
};
var withEventTargetValue = /*#__PURE__*/(0, _ramda.curry)(function (func, event) {
  return func(event.target.value);
});
exports.withEventTargetValue = withEventTargetValue;
var getSubdomain = function getSubdomain() {
  var host = window.location.host;
  var parts = host.split(".");
  return parts.length >= 3 ? parts[0] : "";
};
exports.getSubdomain = getSubdomain;
var simulateApiCall = function simulateApiCall(result, error) {
  var errorProbability = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0.1;
  var delay = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : (0, _neetoCist.getRandomInt)(350, 1000);
  return new Promise(function (resolve, reject) {
    return setTimeout(function () {
      var defaultErrorObj = {
        success: false,
        notice: _i18next["default"].t("neetoCommons.notice.errorOccurred")
      };
      Math.random() < errorProbability ? reject(_objectSpread(_objectSpread({}, defaultErrorObj), error)) : resolve(result);
    }, delay);
  });
};
exports.simulateApiCall = simulateApiCall;
var copyToClipboard = /*#__PURE__*/function () {
  var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(text) {
    var _ref2,
      _ref2$showToastr,
      showToastr,
      _ref2$message,
      message,
      textArea,
      isCopied,
      _args = arguments;
    return _regenerator["default"].wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          _ref2 = _args.length > 1 && _args[1] !== undefined ? _args[1] : {}, _ref2$showToastr = _ref2.showToastr, showToastr = _ref2$showToastr === void 0 ? true : _ref2$showToastr, _ref2$message = _ref2.message, message = _ref2$message === void 0 ? _i18next["default"].t("neetoCommons.toastr.success.copiedToClipboard") : _ref2$message;
          _context.prev = 1;
          _context.next = 4;
          return navigator.clipboard.writeText(text);
        case 4:
          showToastr && _Toastr["default"].success(message);
          _context.next = 28;
          break;
        case 7:
          _context.prev = 7;
          _context.t0 = _context["catch"](1);
          _context.prev = 9;
          textArea = document.createElement("textarea");
          textArea.value = text;
          textArea.style.top = "0";
          textArea.style.left = "0";
          textArea.style.position = "fixed";
          document.body.appendChild(textArea);
          textArea.focus();
          textArea.select();
          isCopied = document.execCommand("copy");
          document.body.removeChild(textArea);
          if (isCopied) {
            _context.next = 22;
            break;
          }
          throw new Error(_i18next["default"].t("neetoCommons.copyToClipboard.failed"));
        case 22:
          showToastr && _Toastr["default"].success(message);
          _context.next = 28;
          break;
        case 25:
          _context.prev = 25;
          _context.t1 = _context["catch"](9);
          _Toastr["default"].error(_context.t1);
        case 28:
        case "end":
          return _context.stop();
      }
    }, _callee, null, [[1, 7], [9, 25]]);
  }));
  return function copyToClipboard(_x) {
    return _ref.apply(this, arguments);
  };
}();
exports.copyToClipboard = copyToClipboard;
var buildUrl = function buildUrl(route, params) {
  var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var placeHolders = [];
  var _options$toSnakeCase = options.toSnakeCase,
    toSnakeCase = _options$toSnakeCase === void 0 ? true : _options$toSnakeCase;
  (0, _ramda.toPairs)(params).forEach(function (_ref3) {
    var _ref4 = (0, _slicedToArray2["default"])(_ref3, 2),
      key = _ref4[0],
      value = _ref4[1];
    if (!route.includes(":".concat(key))) return;
    placeHolders.push(key);
    route = route.replace(":".concat(key), encodeURIComponent(value));
  });
  var keyTransformer = toSnakeCase ? _neetoCist.camelToSnakeCase : _ramda.identity;
  var transformObjectKeys = function transformObjectKeys(params) {
    return (0, _neetoCist.transformObjectDeep)(params, function (key, value) {
      return [keyTransformer(key), value];
    }, function (object) {
      return typeof (object === null || object === void 0 ? void 0 : object.toJSON) === "function" ? object.toJSON() : object;
    });
  };
  var queryParams = (0, _ramda.pipe)((0, _ramda.omit)(placeHolders), transformObjectKeys, _qs.stringify)(params);
  return (0, _ramda.isEmpty)(queryParams) ? route : "".concat(route, "?").concat(queryParams);
};
exports.buildUrl = buildUrl;
var toLocale = function toLocale(number) {
  var _window$globalProps, _window$globalProps$u;
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
  return Number(number).toLocaleString(((_window$globalProps = window.globalProps) === null || _window$globalProps === void 0 ? void 0 : (_window$globalProps$u = _window$globalProps.user) === null || _window$globalProps$u === void 0 ? void 0 : _window$globalProps$u.locale) || navigator.language || navigator.languages[0], options);
};
exports.toLocale = toLocale;
var parseQueryParams = function parseQueryParams(search) {
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var _options$toCamelCase = options.toCamelCase,
    toCamelCase = _options$toCamelCase === void 0 ? true : _options$toCamelCase,
    qsOptions = (0, _objectWithoutProperties2["default"])(options, _excluded);
  var params = (0, _qs.parse)(search, _objectSpread({
    ignoreQueryPrefix: true
  }, qsOptions));
  if (toCamelCase) {
    var pairedParams = (0, _ramda.toPairs)(params);
    params = {};
    pairedParams.forEach(function (_ref5) {
      var _ref6 = (0, _slicedToArray2["default"])(_ref5, 2),
        key = _ref6[0],
        value = _ref6[1];
      var camelCasedKey = toCamelCasedString(key);
      params[camelCasedKey] = value;
    });
  }
  return params;
};
exports.parseQueryParams = parseQueryParams;
var getQueryParams = function getQueryParams(options) {
  return parseQueryParams(location.search, options);
};
exports.getQueryParams = getQueryParams;
var joinHyphenCase = function joinHyphenCase() {
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
    args[_key] = arguments[_key];
  }
  return args.join(" ").replace(/\s+/g, "-").toLowerCase();
};
exports.joinHyphenCase = joinHyphenCase;
var hyphenize = function hyphenize(value) {
  var fallbackString = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
  if (typeof value === "number") return String(value);
  if (value && typeof value === "string" && value.replace) {
    return value.replace(/[\s_]/g, "-").replace(/([a-z])([A-Z])/g, "$1-$2").replace(/-+/g, "-").toLowerCase();
  }
  return fallbackString;
};
exports.hyphenize = hyphenize;
var debounce = function debounce(func) {
  var delay = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 350;
  var timer;
  return function () {
    for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
      args[_key2] = arguments[_key2];
    }
    clearTimeout(timer);
    timer = setTimeout(function () {
      return func.apply(_this, args);
    }, delay);
  };
};
exports.debounce = debounce;
var getFromLocalStorage = function getFromLocalStorage(key) {
  try {
    // eslint-disable-next-line @bigbinary/neeto/no-local-storage
    return JSON.parse(localStorage.getItem(key));
  } catch (_unused2) {
    return null;
  }
};
exports.getFromLocalStorage = getFromLocalStorage;
var setToLocalStorage = function setToLocalStorage(key, value) {
  return (
    // eslint-disable-next-line @bigbinary/neeto/no-local-storage
    localStorage.setItem(key, JSON.stringify(value))
  );
};

// eslint-disable-next-line @bigbinary/neeto/no-local-storage
exports.setToLocalStorage = setToLocalStorage;
var removeFromLocalStorage = function removeFromLocalStorage(key) {
  return localStorage.removeItem(key);
};
exports.removeFromLocalStorage = removeFromLocalStorage;
var showThumbsUpToastr = function showThumbsUpToastr() {
  return _Toastr["default"].success("", {
    icon: "👍",
    className: "w-20"
  });
};
exports.showThumbsUpToastr = showThumbsUpToastr;
//# sourceMappingURL=general.js.map




© 2015 - 2024 Weber Informatics LLC | Privacy Policy