FIX: Preserve anchors in permalink transitions (#10421)

FIX: Preserve anchors in permalink transitions (#10421)

When visiting a permalink with an anchor (e.g. /important-link#notes) the anchor part was being dropped during redirection.

The change doesn’t have a test. Functions like scrollToPost or scrollToElement don’t have any effect in the test environment.

diff --git a/app/assets/javascripts/discourse/app/lib/url.js b/app/assets/javascripts/discourse/app/lib/url.js
index 60211f9..8ed1998 100644
--- a/app/assets/javascripts/discourse/app/lib/url.js
+++ b/app/assets/javascripts/discourse/app/lib/url.js
@@ -480,6 +480,8 @@ const DiscourseURL = EmberObject.extend({
     }
 
     transition._discourse_intercepted = true;
+    transition._discourse_anchor = elementId;
+
     const promise = transition.promise || transition;
     promise.then(() => jumpToElement(elementId));
   }
diff --git a/app/assets/javascripts/discourse/app/routes/unknown.js b/app/assets/javascripts/discourse/app/routes/unknown.js
index 28cba69..c15f30c 100644
--- a/app/assets/javascripts/discourse/app/routes/unknown.js
+++ b/app/assets/javascripts/discourse/app/routes/unknown.js
@@ -11,7 +11,18 @@ export default DiscourseRoute.extend({
       if (results.found) {
         // Avoid polluting the history stack for external links
         transition.abort();
-        DiscourseURL.routeTo(results.target_url);
+
+        let url = results.target_url;
+
+        if (transition._discourse_anchor) {
+          // Remove the anchor from the permalink if present
+          url = url.split("#")[0];
+
+          // Add the anchor from the transition
+          url += `#${transition._discourse_anchor}`;
+        }
+
+        DiscourseURL.routeTo(url);
         return "";
       } else {
         // 404 body HTML

GitHub sha: ab5df7b2

1 Like

This commit appears in #10421 which was approved by eviltrout. It was merged by CvX.