"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.createSimpleFunctional = createSimpleFunctional;
exports.directiveConfig = directiveConfig;
exports.addOnceEventListener = addOnceEventListener;
exports.addPassiveEventListener = addPassiveEventListener;
exports.getNestedValue = getNestedValue;
exports.deepEqual = deepEqual;
exports.getObjectValueByPath = getObjectValueByPath;
exports.getPropertyFromItem = getPropertyFromItem;
exports.createRange = createRange;
exports.getZIndex = getZIndex;
exports.filterObjectOnKeys = filterObjectOnKeys;
exports.convertToUnit = convertToUnit;
exports.kebabCase = kebabCase;
exports.isObject = isObject;
exports.remapInternalIcon = remapInternalIcon;
exports.keys = keys;
exports.arrayDiff = arrayDiff;
exports.upperFirst = upperFirst;
exports.groupItems = groupItems;
exports.wrapInArray = wrapInArray;
exports.sortItems = sortItems;
exports.defaultFilter = defaultFilter;
exports.searchItems = searchItems;
exports.getSlotType = getSlotType;
exports.debounce = debounce;
exports.throttle = throttle;
exports.getPrefixedScopedSlots = getPrefixedScopedSlots;
exports.getSlot = getSlot;
exports.clamp = clamp;
exports.padEnd = padEnd;
exports.chunk = chunk;
exports.humanReadableFileSize = humanReadableFileSize;
exports.camelizeObjectKeys = camelizeObjectKeys;
exports.mergeDeep = mergeDeep;
exports.fillArray = fillArray;
exports.composedPath = composedPath;
exports.camelize = exports.keyCodes = exports.passiveSupported = void 0;

var _vue = _interopRequireDefault(require("vue"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; 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 _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function createSimpleFunctional(c) {
  var el = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'div';
  var name = arguments.length > 2 ? arguments[2] : undefined;
  return _vue.default.extend({
    name: name || c.replace(/__/g, '-'),
    functional: true,
    props: {
      tag: {
        type: String,
        default: el
      }
    },
    render: function render(h, _ref) {
      var data = _ref.data,
          props = _ref.props,
          children = _ref.children;
      data.staticClass = "".concat(c, " ").concat(data.staticClass || '').trim();
      return h(props.tag, data, children);
    }
  });
}

function directiveConfig(binding) {
  var defaults = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  return _objectSpread(_objectSpread(_objectSpread({}, defaults), binding.modifiers), {}, {
    value: binding.arg
  }, binding.value || {});
}

function addOnceEventListener(el, eventName, cb) {
  var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;

  var once = function once(event) {
    cb(event);
    el.removeEventListener(eventName, once, options);
  };

  el.addEventListener(eventName, once, options);
}

var passiveSupported = false;
exports.passiveSupported = passiveSupported;

try {
  if (typeof window !== 'undefined') {
    var testListenerOpts = Object.defineProperty({}, 'passive', {
      get: function get() {
        exports.passiveSupported = passiveSupported = true;
      }
    });
    window.addEventListener('testListener', testListenerOpts, testListenerOpts);
    window.removeEventListener('testListener', testListenerOpts, testListenerOpts);
  }
} catch (e) {
  console.warn(e);
}
/* eslint-disable-line no-console */


function addPassiveEventListener(el, event, cb, options) {
  el.addEventListener(event, cb, passiveSupported ? options : false);
}

function getNestedValue(obj, path, fallback) {
  var last = path.length - 1;
  if (last < 0) return obj === undefined ? fallback : obj;

  for (var i = 0; i < last; i++) {
    if (obj == null) {
      return fallback;
    }

    obj = obj[path[i]];
  }

  if (obj == null) return fallback;
  return obj[path[last]] === undefined ? fallback : obj[path[last]];
}

function deepEqual(a, b) {
  if (a === b) return true;

  if (a instanceof Date && b instanceof Date && a.getTime() !== b.getTime()) {
    // If the values are Date, compare them as timestamps
    return false;
  }

  if (a !== Object(a) || b !== Object(b)) {
    // If the values aren't objects, they were already checked for equality
    return false;
  }

  var props = Object.keys(a);

  if (props.length !== Object.keys(b).length) {
    // Different number of props, don't bother to check
    return false;
  }

  return props.every(function (p) {
    return deepEqual(a[p], b[p]);
  });
}

function getObjectValueByPath(obj, path, fallback) {
  // credit: http://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key#comment55278413_6491621
  if (obj == null || !path || typeof path !== 'string') return fallback;
  if (obj[path] !== undefined) return obj[path];
  path = path.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties

  path = path.replace(/^\./, ''); // strip a leading dot

  return getNestedValue(obj, path.split('.'), fallback);
}

function getPropertyFromItem(item, property, fallback) {
  if (property == null) return item === undefined ? fallback : item;
  if (item !== Object(item)) return fallback === undefined ? item : fallback;
  if (typeof property === 'string') return getObjectValueByPath(item, property, fallback);
  if (Array.isArray(property)) return getNestedValue(item, property, fallback);
  if (typeof property !== 'function') return fallback;
  var value = property(item, fallback);
  return typeof value === 'undefined' ? fallback : value;
}

function createRange(length) {
  return Array.from({
    length: length
  }, function (v, k) {
    return k;
  });
}

function getZIndex(el) {
  if (!el || el.nodeType !== Node.ELEMENT_NODE) return 0;
  var index = +window.getComputedStyle(el).getPropertyValue('z-index');
  if (!index) return getZIndex(el.parentNode);
  return index;
}

function filterObjectOnKeys(obj, keys) {
  var filtered = {};

  for (var i = 0; i < keys.length; i++) {
    var key = keys[i];

    if (typeof obj[key] !== 'undefined') {
      filtered[key] = obj[key];
    }
  }

  return filtered;
}

function convertToUnit(str) {
  var unit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'px';

  if (str == null || str === '') {
    return undefined;
  } else if (isNaN(+str)) {
    return String(str);
  } else {
    return "".concat(Number(str)).concat(unit);
  }
}

function kebabCase(str) {
  return (str || '').replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
}

function isObject(obj) {
  return obj !== null && _typeof(obj) === 'object';
} // KeyboardEvent.keyCode aliases


var keyCodes = Object.freeze({
  enter: 13,
  tab: 9,
  delete: 46,
  esc: 27,
  space: 32,
  up: 38,
  down: 40,
  left: 37,
  right: 39,
  end: 35,
  home: 36,
  del: 46,
  backspace: 8,
  insert: 45,
  pageup: 33,
  pagedown: 34,
  shift: 16
});
/**
 * This remaps internal names like '$cancel' or '$ifrontui.icons.cancel'
 * to the current name or component for that icon.
 */

exports.keyCodes = keyCodes;

function remapInternalIcon(vm, iconName) {
  // Look for custom component in the configuration
  var component = vm.$ifrontui.icons.component; // Look for overrides

  if (iconName.startsWith('$')) {
    // Get the target icon name
    var iconPath = "$ifrontui.icons.values.".concat(iconName.split('$').pop().split('.').pop()); // Now look up icon indirection name,
    // e.g. '$ifrontui.icons.values.cancel'

    var override = getObjectValueByPath(vm, iconPath, iconName);
    if (typeof override === 'string') iconName = override;else return override;
  }

  if (component == null) {
    return iconName;
  }

  return {
    component: component,
    props: {
      icon: iconName
    }
  };
}

function keys(o) {
  return Object.keys(o);
}
/**
 * Camelize a hyphen-delimited string.
 */


var camelizeRE = /-(\w)/g;

var camelize = function camelize(str) {
  return str.replace(camelizeRE, function (_, c) {
    return c ? c.toUpperCase() : '';
  });
};
/**
 * Returns the set difference of B and A, i.e. the set of elements in B but not in A
 */


exports.camelize = camelize;

function arrayDiff(a, b) {
  var diff = [];

  for (var i = 0; i < b.length; i++) {
    if (a.indexOf(b[i]) < 0) diff.push(b[i]);
  }

  return diff;
}
/**
 * Makes the first character of a string uppercase
 */


function upperFirst(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

function groupItems(items, groupBy, groupDesc) {
  var key = groupBy[0];
  var groups = [];
  var current;

  for (var i = 0; i < items.length; i++) {
    var item = items[i];
    var val = getObjectValueByPath(item, key, null);

    if (current !== val) {
      current = val;
      groups.push({
        name: val !== null && val !== void 0 ? val : '',
        items: []
      });
    }

    groups[groups.length - 1].items.push(item);
  }

  return groups;
}

function wrapInArray(v) {
  return v != null ? Array.isArray(v) ? v : [v] : [];
}

function sortItems(items, sortBy, sortDesc, locale, customSorters) {
  if (sortBy === null || !sortBy.length) return items;
  var stringCollator = new Intl.Collator(locale, {
    sensitivity: 'accent',
    usage: 'sort'
  });
  return items.sort(function (a, b) {
    for (var i = 0; i < sortBy.length; i++) {
      var sortKey = sortBy[i];
      var sortA = getObjectValueByPath(a, sortKey);
      var sortB = getObjectValueByPath(b, sortKey);

      if (sortDesc[i]) {
        var _ref2 = [sortB, sortA];
        sortA = _ref2[0];
        sortB = _ref2[1];
      }

      if (customSorters && customSorters[sortKey]) {
        var customResult = customSorters[sortKey](sortA, sortB);
        if (!customResult) continue;
        return customResult;
      } // Check if both cannot be evaluated


      if (sortA === null && sortB === null) {
        continue;
      } // Dates should be compared numerically


      if (sortA instanceof Date && sortB instanceof Date) {
        return sortA.getTime() - sortB.getTime();
      }

      var _map = [sortA, sortB].map(function (s) {
        return (s || '').toString().toLocaleLowerCase();
      });

      var _map2 = _slicedToArray(_map, 2);

      sortA = _map2[0];
      sortB = _map2[1];

      if (sortA !== sortB) {
        if (!isNaN(sortA) && !isNaN(sortB)) return Number(sortA) - Number(sortB);
        return stringCollator.compare(sortA, sortB);
      }
    }

    return 0;
  });
}

function defaultFilter(value, search, item) {
  return value != null && search != null && typeof value !== 'boolean' && value.toString().toLocaleLowerCase().indexOf(search.toLocaleLowerCase()) !== -1;
}

function searchItems(items, search) {
  if (!search) return items;
  search = search.toString().toLowerCase();
  if (search.trim() === '') return items;
  return items.filter(function (item) {
    return Object.keys(item).some(function (key) {
      return defaultFilter(getObjectValueByPath(item, key), search, item);
    });
  });
}
/**
 * Returns:
 *  - 'normal' for old style slots - `<template slot="default">`
 *  - 'scoped' for old style scoped slots (`<template slot="default" slot-scope="data">`) or bound v-slot (`#default="data"`)
 *  - 'v-slot' for unbound v-slot (`#default`) - only if the third param is true, otherwise counts as scoped
 */


function getSlotType(vm, name, split) {
  if (vm.$slots.hasOwnProperty(name) && vm.$scopedSlots.hasOwnProperty(name) && vm.$scopedSlots[name].name) {
    return split ? 'v-slot' : 'scoped';
  }

  if (vm.$slots.hasOwnProperty(name)) return 'normal';
  if (vm.$scopedSlots.hasOwnProperty(name)) return 'scoped';
}

function debounce(fn, delay) {
  var timeoutId = 0;
  return function () {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    clearTimeout(timeoutId);
    timeoutId = setTimeout(function () {
      return fn.apply(void 0, args);
    }, delay);
  };
}

function throttle(fn, limit) {
  var throttling = false;
  return function () {
    if (!throttling) {
      throttling = true;
      setTimeout(function () {
        return throttling = false;
      }, limit);
      return fn.apply(void 0, arguments);
    }
  };
}

function getPrefixedScopedSlots(prefix, scopedSlots) {
  return Object.keys(scopedSlots).filter(function (k) {
    return k.startsWith(prefix);
  }).reduce(function (obj, k) {
    obj[k.replace(prefix, '')] = scopedSlots[k];
    return obj;
  }, {});
}

function getSlot(vm) {
  var name = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'default';
  var data = arguments.length > 2 ? arguments[2] : undefined;
  var optional = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  var kebabName = kebabCase(name);

  if (vm.$scopedSlots.hasOwnProperty(name)) {
    return vm.$scopedSlots[name](data instanceof Function ? data() : data);
  } else if (vm.$scopedSlots.hasOwnProperty(kebabName)) {
    return vm.$scopedSlots[kebabName](data instanceof Function ? data() : data);
  } else if (vm.$slots.hasOwnProperty(name) && (!data || optional)) {
    return vm.$slots[name];
  } else if (vm.$slots.hasOwnProperty(kebabName) && (!data || optional)) {
    return vm.$slots[kebabName];
  }

  return undefined;
}

function clamp(value) {
  var min = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var max = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
  return Math.max(min, Math.min(max, value));
}

function padEnd(str, length) {
  var char = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '0';
  return str + char.repeat(Math.max(0, length - str.length));
}

function chunk(str) {
  var size = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
  var chunked = [];
  var index = 0;

  while (index < str.length) {
    chunked.push(str.substr(index, size));
    index += size;
  }

  return chunked;
}

function humanReadableFileSize(bytes) {
  var binary = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  var base = binary ? 1024 : 1000;

  if (bytes < base) {
    return "".concat(bytes, " B");
  }

  var prefix = binary ? ['Ki', 'Mi', 'Gi'] : ['k', 'M', 'G'];
  var unit = -1;

  while (Math.abs(bytes) >= base && unit < prefix.length - 1) {
    bytes /= base;
    ++unit;
  }

  return "".concat(bytes.toFixed(1), " ").concat(prefix[unit], "B");
}

function camelizeObjectKeys(obj) {
  if (!obj) return {};
  return Object.keys(obj).reduce(function (o, key) {
    o[camelize(key)] = obj[key];
    return o;
  }, {});
}

function mergeDeep() {
  var source = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var target = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

  for (var key in target) {
    var sourceProperty = source[key];
    var targetProperty = target[key]; // Only continue deep merging if
    // both properties are objects

    if (isObject(sourceProperty) && isObject(targetProperty)) {
      source[key] = mergeDeep(sourceProperty, targetProperty);
      continue;
    }

    source[key] = targetProperty;
  }

  return source;
}

function fillArray(length, obj) {
  return Array(length).fill(obj);
}
/**  Polyfill for Event.prototype.composedPath */


function composedPath(e) {
  if (e.composedPath) return e.composedPath();
  var path = [];
  var el = e.target;

  while (el) {
    path.push(el);

    if (el.tagName === 'HTML') {
      path.push(document);
      path.push(window);
      return path;
    }

    el = el.parentElement;
  }

  return path;
}
//# sourceMappingURL=helpers.js.map