|
| 1 | +import { EventHandler } from "./bootstrap-helper"; |
| 2 | + |
| 3 | +function initCardBodies() { |
| 4 | + |
| 5 | + const cardBodies = document.querySelectorAll('.card-body'); |
| 6 | + cardBodies.forEach((cardBody, index) => { |
| 7 | + const paragraph = cardBody.querySelector('div p'); |
| 8 | + const originalText = paragraph.textContent; |
| 9 | + const style = window.getComputedStyle(cardBody); |
| 10 | + const lineClamp = parseInt(style.webkitLineClamp || style.lineClamp); |
| 11 | + const lineHeight = parseFloat(style.lineHeight); |
| 12 | + const fontSize = parseFloat(style.fontSize); |
| 13 | + const actualLineHeight = isNaN(lineHeight) ? parseFloat(style.lineHeight) * fontSize : lineHeight; |
| 14 | + const maxHeight = lineClamp * actualLineHeight; |
| 15 | + |
| 16 | + if (paragraph.offsetHeight >= maxHeight) { |
| 17 | + let visibleText = ''; |
| 18 | + const words = originalText.split(' '); |
| 19 | + let visibleWordCount = 0; |
| 20 | + let tempText = ''; |
| 21 | + while (visibleWordCount < words.length && getTextHeight(tempText + (tempText ? ' ' : '') + words[visibleWordCount], paragraph) <= maxHeight) { |
| 22 | + tempText += (tempText ? ' ' : '') + words[visibleWordCount]; |
| 23 | + visibleWordCount++; |
| 24 | + } |
| 25 | + visibleText = tempText + '...'; |
| 26 | + |
| 27 | + const visibleTextElementId = `visible-text-${Math.random().toString(36).substring(7)}`; |
| 28 | + const visibleTextElement = document.createElement('div'); |
| 29 | + visibleTextElement.id = visibleTextElementId; |
| 30 | + visibleTextElement.textContent = visibleText; |
| 31 | + visibleTextElement.style.position = 'absolute'; |
| 32 | + visibleTextElement.style.left = '-9999px'; |
| 33 | + visibleTextElement.style.top = '-9999px'; |
| 34 | + visibleTextElement.setAttribute('aria-hidden', 'true'); |
| 35 | + |
| 36 | + cardBody.appendChild(visibleTextElement); |
| 37 | + |
| 38 | + paragraph.setAttribute('aria-describedby', visibleTextElementId); |
| 39 | + } |
| 40 | + }); |
| 41 | + |
| 42 | + |
| 43 | +}; |
| 44 | + |
| 45 | +function getTextHeight(text, element) { |
| 46 | + const tempElement = document.createElement(element.tagName); |
| 47 | + tempElement.style.font = window.getComputedStyle(element).font; |
| 48 | + tempElement.style.width = window.getComputedStyle(element).width; |
| 49 | + tempElement.style.whiteSpace = 'pre-wrap'; |
| 50 | + tempElement.textContent = text; |
| 51 | + document.body.appendChild(tempElement); |
| 52 | + const height = tempElement.offsetHeight; |
| 53 | + document.body.removeChild(tempElement); |
| 54 | + return height; |
| 55 | +} |
| 56 | + |
| 57 | +EventHandler.on(window, 'load.uds.card-bodies', initCardBodies); |
| 58 | + |
| 59 | +export { initCardBodies }; |
0 commit comments