@wordpress/components
Version:
UI components for WordPress.
62 lines (61 loc) • 2.04 kB
JavaScript
;
Object.defineProperties(exports, {
__esModule: { value: true },
[Symbol.toStringTag]: { value: "Module" }
});
let ___utils_values_ts = require("../utils/values.cjs");
// packages/components/src/truncate/utils.ts
const TRUNCATE_ELLIPSIS = "…";
const TRUNCATE_TYPE = {
auto: "auto",
head: "head",
middle: "middle",
tail: "tail",
none: "none"
};
const TRUNCATE_DEFAULT_PROPS = {
ellipsis: "…",
ellipsizeMode: TRUNCATE_TYPE.auto,
limit: 0,
numberOfLines: 0
};
function truncateMiddle(word, headLength, tailLength, ellipsis) {
if (typeof word !== "string") return "";
const wordLength = word.length;
const frontLength = ~~headLength;
const backLength = ~~tailLength;
/* istanbul ignore next */
const truncateStr = (0, ___utils_values_ts.isValueDefined)(ellipsis) ? ellipsis : "…";
if (frontLength === 0 && backLength === 0 || frontLength >= wordLength || backLength >= wordLength || frontLength + backLength >= wordLength) return word;
else if (backLength === 0) return word.slice(0, frontLength) + truncateStr;
return word.slice(0, frontLength) + truncateStr + word.slice(wordLength - backLength);
}
function truncateContent(words = "", props) {
const { ellipsis, ellipsizeMode, limit } = {
...TRUNCATE_DEFAULT_PROPS,
...props
};
if (ellipsizeMode === TRUNCATE_TYPE.none) return words;
let truncateHead;
let truncateTail;
switch (ellipsizeMode) {
case TRUNCATE_TYPE.head:
truncateHead = 0;
truncateTail = limit;
break;
case TRUNCATE_TYPE.middle:
truncateHead = Math.floor(limit / 2);
truncateTail = Math.floor(limit / 2);
break;
default:
truncateHead = limit;
truncateTail = 0;
}
return ellipsizeMode !== TRUNCATE_TYPE.auto ? truncateMiddle(words, truncateHead, truncateTail, ellipsis) : words;
}
exports.TRUNCATE_DEFAULT_PROPS = TRUNCATE_DEFAULT_PROPS;
exports.TRUNCATE_ELLIPSIS = TRUNCATE_ELLIPSIS;
exports.TRUNCATE_TYPE = TRUNCATE_TYPE;
exports.truncateContent = truncateContent;
exports.truncateMiddle = truncateMiddle;
//# sourceMappingURL=utils.cjs.map