UNPKG

@chayns-components/core

Version:

A set of beautiful React components for developing your own applications with chayns.

35 lines (34 loc) 1.65 kB
const doesElementOverflow = (element, referenceHeight) => element.scrollHeight > referenceHeight; const doesElementHasOnlyText = element => { // Check if element has no child elements. if (element.children.length === 0) { // If element has text (not empty), it is only text. return element.textContent !== ''; } // Element has child elements or no text, so it's not only text. return false; }; const removeLastLeafElement = element => { // remove last element of html element where the last element is a leaf element and its content is a string const { lastElementChild, lastChild } = element; if (lastElementChild && !doesElementHasOnlyText(lastElementChild) && lastElementChild.hasChildNodes()) { removeLastLeafElement(lastElementChild); } else if (lastChild && lastChild.nodeType === Node.TEXT_NODE && lastChild.textContent && lastChild.textContent.length > 25) { lastChild.textContent = `${lastChild.textContent.substring(0, lastChild.textContent.length - 25)} ...`; } else if (lastElementChild && doesElementHasOnlyText(lastElementChild) && lastElementChild.textContent && lastElementChild.textContent.length > 25) { lastElementChild.textContent = `${lastElementChild.textContent.substring(0, lastElementChild.textContent.length - 25)} ...`; } else if (lastChild) { element.removeChild(lastChild); } else if (lastElementChild) { element.removeChild(lastElementChild); } }; export const truncateElement = (element, referenceHeight) => { while (doesElementOverflow(element, referenceHeight)) { removeLastLeafElement(element); } }; //# sourceMappingURL=truncation.js.map