"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.ELLIPSIS_PLACE_TYPES = void 0;
var _react = _interopRequireWildcard(require("react"));
var _reactDom = require("react-dom");
var _classnames = _interopRequireDefault(require("classnames"));
var _useDebounce = require("../hooks/use-debounce");
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
const ELLIPSIS_PLACE_TYPES = exports.ELLIPSIS_PLACE_TYPES = {
  MIDDLE: 'middle',
  END: 'end'
};
const ellipsisPlace = {
  middle: 50,
  end: 100
};
const sizeTolerance = {
  max: 4,
  // 4px,
  tolerance: 0.02 // 2%
};
const getSizeTolerance = value => {
  const currentTolerance = value * sizeTolerance.tolerance;
  return currentTolerance <= sizeTolerance.max ? Math.round(currentTolerance) : sizeTolerance.max;
};
const truncateString = (text, ellipsisString, truncateAt, parent = 0, children = 0) => {
  const textLength = text.length;
  const percentage = ellipsisPlace[truncateAt];
  if (textLength === 0) {
    return '';
  }
  if (children <= parent) {
    return text;
  }
  // Recheck for tolerance
  if (children - getSizeTolerance(children) <= parent) {
    return text;
  }

  // get number of chars that related truncatedAt coefficient which will fit in the container
  const charIndex = size => Math.floor((textLength - ellipsisString.length) * size / children);

  // slice from first char till portioned text. We always need leaving the first char in a small container
  const left = text.slice(0, Math.max(1, charIndex(parent * (percentage / 100))));
  const right = text.slice(textLength - charIndex(parent * ((100 - percentage) / 100)), textLength);
  return `${left}${ellipsisString}${right}`;
};
/**
 * Component that truncates long text in the middle or end.
 * 🚨 NOTE ➡️: max-width & min-width for a parent element is required for proper work. 🚨
 * */
const TruncateString = ({
  text = '',
  ellipsisString = '...',
  truncateAt = ELLIPSIS_PLACE_TYPES.MIDDLE,
  className = null,
  testId = ''
}) => {
  const [truncatedString, setTruncatedString] = (0, _react.useState)(null);
  const [isTruncating, setTruncating] = (0, _react.useState)(false);
  const parentRef = (0, _react.useRef)(null);
  const textRef = (0, _react.useRef)(null);
  let timer;
  const handleResize = (0, _useDebounce.useDebounce)(() => {
    (0, _reactDom.flushSync)(() => {
      setTruncating(true);
    });
    const truncated = truncateString(text, ellipsisString, truncateAt, parentRef.current?.offsetWidth, textRef.current?.offsetWidth);
    (0, _reactDom.flushSync)(() => {
      setTruncatedString(truncated);
      setTruncating(false);
    });
  }, 100);
  (0, _react.useEffect)(() => {
    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
      clearTimeout(timer);
    };
  }, [text]);
  (0, _react.useLayoutEffect)(() => {
    setTruncating(true);
    // use native timeout because we do not change scope and don't want to trigger digest
    timer = setTimeout(() => {
      const truncated = truncateString(text, ellipsisString, truncateAt, parentRef.current?.offsetWidth, textRef.current?.offsetWidth);
      setTruncatedString(truncated);
      (0, _reactDom.flushSync)(() => {
        setTruncatedString(truncated);
        setTruncating(false);
      });
    }, 0);
  }, [text]);
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
    ref: parentRef,
    className: (0, _classnames.default)('truncate-string', className),
    "test-id": testId,
    children: [isTruncating && /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
      className: "original-text",
      ref: textRef,
      children: text
    }), !isTruncating && /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
      ref: textRef,
      children: truncatedString
    })]
  });
};
var _default = exports.default = TruncateString;