diff --git a/extlink.css b/extlink.css index bb49b7f..5a2b7ee 100644 --- a/extlink.css +++ b/extlink.css @@ -37,3 +37,7 @@ svg.mailto path { extlink i { padding-left: 0.2em; } + +.extlink-nobreak { + white-space: nowrap; +} \ No newline at end of file diff --git a/extlink.js b/extlink.js index 7d57dc9..483c483 100644 --- a/extlink.js +++ b/extlink.js @@ -243,6 +243,50 @@ var length = $links_to_process.length; for (i = 0; i < length; i++) { var $link = $($links_to_process[i]); + + // Prevent appended icons from wrapping lines. + if (icon_placement === 'append') { + + // Find the last word in the link. + var lastTextNode = $link[0].lastChild; + var trailingWhitespace = false; + var parentNode = $link[0]; + while (lastTextNode) { + if (lastTextNode.lastChild) { + // Last node was not text; step down into child node. + parentNode = lastTextNode; + lastTextNode = lastTextNode.lastChild; + } else if (lastTextNode.nodeName === "#text" && parentNode.lastElementChild && lastTextNode.textContent.trim().length === 0) { + // Last node was text, but it was whitespace. Step back into previous node. + trailingWhitespace = lastTextNode; + parentNode = parentNode.lastElementChild; + lastTextNode = parentNode.lastChild; + } else { + // Last node was null or valid text. + break; + } + } + if (lastTextNode && lastTextNode.nodeName === "#text" && lastTextNode.textContent.length > 0) { + var lastText = lastTextNode.textContent; + var lastWordRegex = new RegExp(/\S+\s*$/,'g'); + var lastWord = lastText.match(lastWordRegex); + if (lastWord !== null) { + // Wrap the last word in a span. + var breakPreventer = document.createElement('span'); + breakPreventer.classList.add('extlink-nobreak'); + breakPreventer.textContent = lastWord[0]; + if (trailingWhitespace) { + breakPreventer.append(trailingWhitespace.textContent); + trailingWhitespace.textContent = ''; + } + lastTextNode.textContent = lastText.substring(0, lastText.length - lastWord[0].length); + lastTextNode.parentNode.append(breakPreventer); + // Insert the icon into the span rather than the link. + $link = $(breakPreventer); + } + } + } + if (drupalSettings.data.extlink.extUseFontAwesome) { if (class_name === drupalSettings.data.extlink.mailtoClass) { $link[icon_placement]('');