(html, opts)
| 5 | const LIST_ITEM_END_RE = /<\/li>/g; |
| 6 | const MULTIPLE_LINE_BREAKS_RE = /[\r\n]{3,}/g; |
| 7 | function getHTMLText(html, opts) { |
| 8 | if (!html) return ''; |
| 9 | const { preProcess, truncateLinks = true } = opts || {}; |
| 10 | |
| 11 | template.innerHTML = html |
| 12 | .replace(PARAGRAPH_END_RE, '</p>\n\n') |
| 13 | .replace(LIST_ITEM_END_RE, '</li>\n'); |
| 14 | |
| 15 | const content = template.content; |
| 16 | const brElements = content.querySelectorAll('br'); |
| 17 | for (let i = 0; i < brElements.length; i++) { |
| 18 | brElements[i].replaceWith('\n'); |
| 19 | } |
| 20 | |
| 21 | preProcess?.(content); |
| 22 | |
| 23 | if (truncateLinks) { |
| 24 | // MASTODON-SPECIFIC classes |
| 25 | // Remove .invisible |
| 26 | const invisibleElements = content.querySelectorAll('.invisible'); |
| 27 | for (let i = 0; i < invisibleElements.length; i++) { |
| 28 | invisibleElements[i].remove(); |
| 29 | } |
| 30 | // Add … at end of .ellipsis |
| 31 | const ellipsisElements = content.querySelectorAll('.ellipsis'); |
| 32 | for (let i = 0; i < ellipsisElements.length; i++) { |
| 33 | ellipsisElements[i].append('…'); |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | // Collect innerText from all child nodes since DocumentFragment doesn't have innerText |
| 38 | let textContent = ''; |
| 39 | for (let i = 0; i < content.childNodes.length; i++) { |
| 40 | const n = content.childNodes[i]; |
| 41 | textContent += n.innerText || n.textContent || ''; |
| 42 | } |
| 43 | |
| 44 | return textContent.replace(MULTIPLE_LINE_BREAKS_RE, '\n\n').trim(); |
| 45 | } |
| 46 | |
| 47 | export default getHTMLText; |
no outgoing calls
no test coverage detected