From 6fb4f5722abfcc4d3c6cf0c697f3b405e74f6962 Mon Sep 17 00:00:00 2001 From: rdbsolutions Date: Thu, 30 Jan 2025 14:11:17 +0000 Subject: [PATCH] rep defect 42, questionnaire defect 67, enf defect 16 --- components/utils/index.js | 57 +++++++++++++++++++++++++++------------ 1 file changed, 40 insertions(+), 17 deletions(-) diff --git a/components/utils/index.js b/components/utils/index.js index 296d8f4d..954d662a 100644 --- a/components/utils/index.js +++ b/components/utils/index.js @@ -561,14 +561,23 @@ export const updateLinks = (jsonObj) => { // Find all text nodes in the document const walk = (node) => { if (node.nodeType === Node.TEXT_NODE) { - // Check if the text node contains a URL (simple check for a URL pattern) const urlRegex = /(?:https?:\/\/)?(?:www\.)?([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})(\/[^\s]*)?/g; let match; + let currentText = node.textContent; + let lastIndex = 0; + let newNodeContent = []; - // Process the text node if it contains a URL - while ((match = urlRegex.exec(node.textContent)) !== null) { - // Construct the full URL by adding the protocol if missing, and the domain and path + // Process all URLs found in the current text node + while ((match = urlRegex.exec(currentText)) !== null) { + // Before the URL + if (match.index > lastIndex) { + newNodeContent.push( + currentText.slice(lastIndex, match.index) + ); + } + + // Construct the full URL (default to https://) let fullUrl = match[0]; if ( !fullUrl.startsWith("http://") && @@ -577,21 +586,35 @@ export const updateLinks = (jsonObj) => { fullUrl = `https://${match[1]}${match[2] || ""}`; // Default to https } - // Check if the match is already inside an tag, if so, skip it - if (node.parentNode.tagName !== "A") { - const anchor = document.createElement("a"); - anchor.href = fullUrl; - anchor.textContent = match[0]; + // Create the anchor element + const anchor = document.createElement("a"); + anchor.href = fullUrl; + anchor.textContent = match[0]; + anchor.setAttribute("rel", "noopener noreferrer"); - // Add rel="noopener noreferrer" for security - anchor.setAttribute("rel", "noopener noreferrer"); + // Add the anchor tag to the node content + newNodeContent.push(anchor); - // Replace the URL with the anchor element in the text node - const range = document.createRange(); - range.selectNodeContents(node); - range.deleteContents(); - range.insertNode(anchor); - } + // Update the last index processed + lastIndex = urlRegex.lastIndex; + } + + // Add the remaining text after the last URL + if (lastIndex < currentText.length) { + newNodeContent.push(currentText.slice(lastIndex)); + } + + // If there were any replacements, update the text node + if (newNodeContent.length > 0) { + const fragment = document.createDocumentFragment(); + newNodeContent.forEach((item) => { + if (typeof item === "string") { + fragment.appendChild(document.createTextNode(item)); + } else { + fragment.appendChild(item); + } + }); + node.parentNode.replaceChild(fragment, node); } }