UNPKG

react-truncate-inside

Version:

React component for adding an ellipsis to the middle of a line of text.

111 lines (110 loc) 6.83 kB
"use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var React = _interopRequireWildcard(require("react")); var _useCanvas = _interopRequireDefault(require("./useCanvas")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } 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) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } /** * <b>Truncate</b> truncates text based on a given width. The component takes in a few props, including the text to be truncated, the width of the container, the number of characters to offset the truncated text, and the ellipsis to be used. */ function Truncate(props) { var text = props.text, _props$width = props.width, width = _props$width === void 0 ? 0 : _props$width, _props$offset = props.offset, offset = _props$offset === void 0 ? 8 : _props$offset, _props$ellipsis = props.ellipsis, ellipsis = _props$ellipsis === void 0 ? '...' : _props$ellipsis; var _React$useState = React.useState(0), _React$useState2 = _slicedToArray(_React$useState, 2), targetWidth = _React$useState2[0], setTargetWidth = _React$useState2[1]; var _React$useState3 = React.useState(false), _React$useState4 = _slicedToArray(_React$useState3, 2), shouldTruncate = _React$useState4[0], setShouldTruncate = _React$useState4[1]; var _React$useState5 = React.useState(false), _React$useState6 = _slicedToArray(_React$useState5, 2), truncated = _React$useState6[0], setTruncated = _React$useState6[1]; var containerRef = React.useRef(null); var canvas = (0, _useCanvas["default"])(); var setupCanvas = React.useCallback(function () { if (!containerRef.current) return; var style = window.getComputedStyle(containerRef.current); var font = [style['font-weight'], style['font-style'], style['font-size'], style['font-family']].join(' '); canvas.font = font; }, [canvas]); var calcTargetWidth = React.useCallback(function () { var targetW; if (width) { targetW = width; } else { var _containerRef$current; targetW = (_containerRef$current = containerRef.current) === null || _containerRef$current === void 0 ? void 0 : _containerRef$current.getBoundingClientRect().width; } setTargetWidth(targetW); var measureWidth = canvas.measureText(text).width; setShouldTruncate(targetW < measureWidth); setTruncated(true); }, [canvas, text, width]); React.useEffect(function () { setupCanvas(); calcTargetWidth(); }, [calcTargetWidth, setupCanvas]); React.useEffect(function () { var oB = new ResizeObserver(function (entries) { if (entries.length > 0) { calcTargetWidth(); } }); if (containerRef.current) { oB.observe(containerRef.current); } return function () { oB.disconnect(); }; }, [calcTargetWidth]); var calculatedText = React.useMemo(function () { if (!shouldTruncate) return text; var len = text.length; var tail = text.slice(len - offset, len); var head; var end = len - offset; var start = 0; while (start < end - 1) { var curr = Math.floor((end - start) / 2 + start); head = text.slice(0, curr); if (canvas.measureText(head + ellipsis + tail).width < targetWidth) { start = curr; } else { end = curr; } } head = text.slice(0, start || 1); return head + ellipsis + tail; }, [canvas, ellipsis, offset, shouldTruncate, targetWidth, text]); return /*#__PURE__*/React.createElement("div", { ref: containerRef, style: { width: width || '100%', whiteSpace: 'nowrap' } }, truncated ? calculatedText : calculatedText); } var _default = Truncate; exports["default"] = _default;