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

package.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
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
var _this = this;
var _excluded = ["toCamelCase"];
import _regeneratorRuntime from "@babel/runtime/regenerator";
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
import i18next from "i18next";
import { camelToSnakeCase, getRandomInt, transformObjectDeep } from "@bigbinary/neeto-cist";
import Toastr from "@bigbinary/neetoui/Toastr";
import { parse, stringify } from "qs";
import { identity, curry, isEmpty, omit, pipe, toPairs } from "ramda";
var toCamelCasedString = function toCamelCasedString(string) {
  return string.replace(/[_-]+(\w)/g, function (_, nextChar) {
    return nextChar.toUpperCase();
  });
};
export var withEventTargetValue = /*#__PURE__*/curry(function (func, event) {
  return func(event.target.value);
});
export var getSubdomain = function getSubdomain() {
  var host = window.location.host;
  var parts = host.split(".");
  return parts.length >= 3 ? parts[0] : "";
};
export 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] : getRandomInt(350, 1000);
  return new Promise(function (resolve, reject) {
    return setTimeout(function () {
      var defaultErrorObj = {
        success: false,
        notice: i18next.t("neetoCommons.notice.errorOccurred")
      };
      Math.random() < errorProbability ? reject(_objectSpread(_objectSpread({}, defaultErrorObj), error)) : resolve(result);
    }, delay);
  });
};
export var copyToClipboard = /*#__PURE__*/function () {
  var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(text) {
    var _ref2,
      _ref2$showToastr,
      showToastr,
      _ref2$message,
      message,
      textArea,
      isCopied,
      _args = arguments;
    return _regeneratorRuntime.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.t("neetoCommons.toastr.success.copiedToClipboard") : _ref2$message;
          _context.prev = 1;
          _context.next = 4;
          return navigator.clipboard.writeText(text);
        case 4:
          showToastr && Toastr.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.t("neetoCommons.copyToClipboard.failed"));
        case 22:
          showToastr && Toastr.success(message);
          _context.next = 28;
          break;
        case 25:
          _context.prev = 25;
          _context.t1 = _context["catch"](9);
          Toastr.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);
  };
}();
export 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;
  toPairs(params).forEach(function (_ref3) {
    var _ref4 = _slicedToArray(_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 ? camelToSnakeCase : identity;
  var transformObjectKeys = function transformObjectKeys(params) {
    return 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 = pipe(omit(placeHolders), transformObjectKeys, stringify)(params);
  return isEmpty(queryParams) ? route : "".concat(route, "?").concat(queryParams);
};
export 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);
};
export 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 = _objectWithoutProperties(options, _excluded);
  var params = parse(search, _objectSpread({
    ignoreQueryPrefix: true
  }, qsOptions));
  if (toCamelCase) {
    var pairedParams = toPairs(params);
    params = {};
    pairedParams.forEach(function (_ref5) {
      var _ref6 = _slicedToArray(_ref5, 2),
        key = _ref6[0],
        value = _ref6[1];
      var camelCasedKey = toCamelCasedString(key);
      params[camelCasedKey] = value;
    });
  }
  return params;
};
export var getQueryParams = function getQueryParams(options) {
  return parseQueryParams(location.search, options);
};
export 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();
};
export 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;
};
export 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);
  };
};
export 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;
  }
};
export 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
export var removeFromLocalStorage = function removeFromLocalStorage(key) {
  return localStorage.removeItem(key);
};
export var showThumbsUpToastr = function showThumbsUpToastr() {
  return Toastr.success("", {
    icon: "👍",
    className: "w-20"
  });
};
//# sourceMappingURL=general.js.map




© 2015 - 2024 Weber Informatics LLC | Privacy Policy