From 352e72ef9223bf41e496cfabef2a4213d58eb3dd Mon Sep 17 00:00:00 2001 From: Eli Young Date: Mon, 2 Apr 2018 14:38:05 -0700 Subject: [PATCH] Improve link anchor wrapping When URLs are wrapped in anchor tags, we reparent the text nodes from the DOM to the new anchor node in order to prevent CodeMirror from getting confused and hiding the cursor when it's inside the URL. Additionally, we apply the cm-string class to the anchor tag to keep the style the same. We also only apply the cm-string-link class to the surrounding span tag when links are not wrapped in anchor tags in order to avoid triggering the custom link behavior by accident. Finally, we put an event listener on the anchor tags that prevents the contextmenu event from bubbling to CodeMirror's handler in order to restore the expected behavior of context menus for links. --- extension/src/json-viewer/highlighter.js | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/extension/src/json-viewer/highlighter.js b/extension/src/json-viewer/highlighter.js index ff7b1d86..77f60b53 100644 --- a/extension/src/json-viewer/highlighter.js +++ b/extension/src/json-viewer/highlighter.js @@ -89,15 +89,26 @@ Highlighter.prototype = { if (text.match(URL_PATTERN) && self.clickableUrls()) { var decodedText = self.decodeText(text); elements.forEach(function(node) { - node.classList.add("cm-string-link"); - node.setAttribute("data-url", decodedText); if (self.wrapLinkWithAnchorTag()) { var linkTag = document.createElement("a"); linkTag.href = decodedText; linkTag.setAttribute('target', '_blank') - linkTag.innerHTML = decodedText; - node.innerHTML = ""; + linkTag.classList.add("cm-string"); + + // reparent the child nodes to preserve the cursor when editing + node.childNodes.forEach(function(child) { + linkTag.appendChild(child); + }); + + // block CodeMirror's contextmenu handler + linkTag.addEventListener("contextmenu", function(e) { + if (e.bubbles) e.cancelBubble = true; + }); + node.appendChild(linkTag); + } else { + node.classList.add("cm-string-link"); + node.setAttribute("data-url", decodedText); } }); }