From 5d4a43abb181ae4fd63d2365210ea4949f10012e Mon Sep 17 00:00:00 2001 From: Hsieh Chin Fan Date: Mon, 14 Oct 2024 14:47:04 +0800 Subject: feat: improve GeoLink generation * Stop searching pattern by linkify, Add links with geo URI scheme by async function instead * Search text nodes with patterns, and replace them with links * Add checker for valid degree/meter coordinated * Add query string "xy" anyway --- src/utils.mjs | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) (limited to 'src/utils.mjs') diff --git a/src/utils.mjs b/src/utils.mjs index d408b3d..1fe3ce5 100644 --- a/src/utils.mjs +++ b/src/utils.mjs @@ -133,3 +133,47 @@ export const insideParent = (childElement, parentElement) => { childRect.bottom > parentRect.top + offset ) } + +/** + * replaceTextNodes. + * @description Search current nodes by pattern, and replace them by new node + * @todo refactor to smaller methods + * @param {HTMLElement} element + * @param {RegExp} pattern + * @param {Function} newNode - Create new node by each result of String.prototype.matchAll + */ +export const replaceTextNodes = ( + element, + pattern, + newNode = (match) => { + const link = document.createElement('a') + link.textContent(match.at(0)) + return link + }, +) => { + const nodeIterator = document.createNodeIterator( + element, + window.NodeFilter.SHOW_TEXT, + node => node.textContent.match(pattern) + ? window.NodeFilter.FILTER_ACCEPT + : window.NodeFilter.FILTER_REJECT, + ) + + let node = nodeIterator.nextNode() + while (node) { + let index = 0 + for (const match of node.textContent.matchAll(pattern)) { + const text = node.textContent.slice(index, match.index) + index = match.index + match.at(0).length + node.parentElement.insertBefore(document.createTextNode(text), node) + node.parentElement.insertBefore(newNode(match), node) + } + if (index < node.textContent.length) { + const text = node.textContent.slice(index) + node.parentElement.insertBefore(document.createTextNode(text), node) + } + + node.parentElement.removeChild(node) + node = nodeIterator.nextNode() + } +} -- cgit v1.2.3-70-g09d2