A platform for community discussion. Free, open, simple.
FIX: Properly open threads when clicking nested notifications (#39890)
Mark VanLandinghamaa31d18494cf
diff --git a/app/services/nested_topic/show_context.rb b/app/services/nested_topic/show_context.rbindex bbce52d7291..8e1c44d3d62 100644--- a/app/services/nested_topic/show_context.rb+++ b/app/services/nested_topic/show_context.rb@@ -30,6 +30,7 @@ class NestedTopic::ShowContextstep :expand_reply_treesstep :prepare_postsstep :serialize_context+ step :attach_suggested_and_relatedprivate@@ -158,4 +159,11 @@ class NestedTopic::ShowContextmessage_bus_last_id: topic_view.message_bus_last_id,}end++ # Context view has no pagination, so this always runs — parallel to the+ # final page in NestedTopic::ListRoots, where the same step is gated on+ # has_more_roots=false.+ def attach_suggested_and_related(serializer:, response:)+ response.merge!(serializer.serialize_suggested_and_related)+ endenddiff --git a/frontend/discourse/app/components/nested/context-view.gjs b/frontend/discourse/app/components/nested/context-view.gjsindex b739cb54060..07fc45b6ce6 100644--- a/frontend/discourse/app/components/nested/context-view.gjs+++ b/frontend/discourse/app/components/nested/context-view.gjs@@ -2,10 +2,15 @@ import Component from "@glimmer/component";import { tracked } from "@glimmer/tracking";import { array, fn } from "@ember/helper";import { action } from "@ember/object";+import didInsert from "@ember/render-modifiers/modifiers/did-insert";+import didUpdate from "@ember/render-modifiers/modifiers/did-update";import { cancel, next, schedule } from "@ember/runloop";import { service } from "@ember/service";import DButton from "discourse/components/d-button";+import MoreTopics from "discourse/components/more-topics";+import PluginOutlet from "discourse/components/plugin-outlet";import icon from "discourse/helpers/d-icon";+import lazyHash from "discourse/helpers/lazy-hash";import getURL from "discourse/lib/get-url";import PostStreamViewportTracker from "discourse/modifiers/post-stream-viewport-tracker";import { or } from "discourse/truth-helpers";@@ -17,6 +22,7 @@ import NestedPost from "./post";import NestedSortSelector from "./sort-selector";export default class NestedContextView extends Component {+ @service appEvents;@service currentUser;@service header;@service screenTrack;@@ -33,9 +39,7 @@ export default class NestedContextView extends Component {constructor() {super(...arguments);- // Use next() so this runs after RouteScrollManager's next() callback,- // which otherwise resets scroll position on route transitions.- this.#nextTimer = next(this, this.#scrollToTarget);+ this.appEvents.on("nested:scroll-to-target", this, this.scheduleScroll);}willDestroy() {@@ -44,9 +48,21 @@ export default class NestedContextView extends Component {cancel(this.#nextTimer);cancel(this.#retryTimer);clearTimeout(this.#highlightTimer);+ this.appEvents.off("nested:scroll-to-target", this, this.scheduleScroll);this.viewportTracker.destroy();}+ // next() runs after RouteScrollManager's own next() callback, so our+ // scroll wins. Fresh attempt counter per invocation.+ @action+ scheduleScroll() {+ cancel(this.#nextTimer);+ cancel(this.#retryTimer);+ clearTimeout(this.#highlightTimer);+ this.#scrollAttempts = 0;+ this.#nextTimer = next(this, this.#scrollToTarget);+ }+get flatViewUrl() {return getURL(`/t/${this.args.topic.slug}/${this.args.topic.id}?flat=1`);}@@ -76,8 +92,7 @@ export default class NestedContextView extends Component {}target.scrollIntoView({ behavior: "smooth", block: "center" });} else if (this.#scrollAttempts < this.#maxScrollAttempts) {- // Element may not be in the DOM yet (async child rendering).- // Retry after the next render cycle.+ // Target may not be in the DOM yet (async child rendering).this.#scrollAttempts++;this.#retryTimer = schedule("afterRender", this, this.#scrollToTarget);}@@ -89,9 +104,25 @@ export default class NestedContextView extends Component {this.cloakBelow = below;}+ // Only collapse when the chain is just the target — otherwise the target+ // is the chain leaf and collapsing would hide the very thing the context+ // view exists to surface.+ get effectiveCollapseFromDepth() {+ if (!this.args.collapseReplies) {+ return null;+ }+ const chainRootPostNumber = this.args.contextChain?.post?.post_number;+ if (chainRootPostNumber !== this.args.targetPostNumber) {+ return null;+ }+ return 1;+ }+<template><divclass="nested-view nested-context-view"+ {{didInsert this.scheduleScroll}}+ {{didUpdate this.scheduleScroll @targetPostNumber @contextChain.post.id}}{{this.viewportTracker.setupeyeline=falseheaderOffset=this.header.headerOffset@@ -171,9 +202,9 @@ export default class NestedContextView extends Component {{{#if @contextChain}}<div class="nested-context-view__chain">- {{! Use each+key to force full component recreation when the chain root changes,- e.g. navigating from context=0 to full ancestor view }}- {{#each (array @contextChain) key="post.id" as |chainRoot|}}+ {{! _renderKey changes every fetch — forces NestedPost rebuild+ when chains share a root. See routes/nested.js. }}+ {{#each (array @contextChain) key="_renderKey" as |chainRoot|}}<NestedPost@post={{chainRoot.post}}@children={{chainRoot.children}}@@ -193,12 +224,26 @@ export default class NestedContextView extends Component {@getCloakingData={{this.viewportTracker.getCloakingData}}@cloakAbove={{this.cloakAbove}}@cloakBelow={{this.cloakBelow}}- @collapseFromDepth={{if @collapseReplies 1}}+ @collapseFromDepth={{this.effectiveCollapseFromDepth}}/>{{/each}}</div>{{/if}}+ <PluginOutlet+ @name="topic-above-suggested"+ @connectorTagName="div"+ @outletArgs={{lazyHash model=@topic}}+ />++ <MoreTopics @topic={{@topic}} />++ <PluginOutlet+ @name="topic-below-suggested"+ @connectorTagName="div"+ @outletArgs={{lazyHash model=@topic}}+ />+<NestedFloatingActions@topic={{@topic}}@replyAction={{fn @replyToPost @opPost 0}}diff --git a/frontend/discourse/app/lib/url.js b/frontend/discourse/app/lib/url.jsindex 8a86e0d1bd4..2bb2487c7a4 100644--- a/frontend/discourse/app/lib/url.js+++ b/frontend/discourse/app/lib/url.js@@ -15,6 +15,7 @@ import Session from "discourse/models/session";const rewrites = [];export const TOPIC_URL_REGEXP = /\/t\/([^\/]*[^\d\/][^\/]*)\/(\d+)\/?(\d+)?/;+const NESTED_URL_REGEXP = /^\/n\/([^\/]+)\/(\d+)(?:\/(\d+))?/;// We can add links here that have server side responses but not client side.const SERVER_SIDE_ONLY = [@@ -289,6 +290,14 @@ class DiscourseURL extends EmberObject {return;}+ if (oldPath === path && NESTED_URL_REGEXP.test(path)) {+ // The nested context view caches its scroll target in the+ // component's lifecycle, so a plain refresh() wouldn't re-trigger+ // it. Fire an event the view listens for instead.+ this.appEvents.trigger("nested:scroll-to-target");+ return;+ }+if (oldPath === path || this.refreshedHomepage(oldPath, path)) {// If navigating to the same path, refresh the routethis.routerService.refresh();diff --git a/frontend/discourse/app/routes/nested.js b/frontend/discourse/app/routes/nested.jsindex 13738305198..b8dc4080765 100644--- a/frontend/discourse/app/routes/nested.js+++ b/frontend/discourse/app/routes/nested.js@@ -196,17 +196,15 @@ export default class NestedRoute extends Route {// Suggested/related are piggybacked at top-level on whichever// response has has_more_roots=false — here, a short topic that// fits in one page; otherwise they arrive via loadMoreRoots.- if (data.suggested_topics !== undefined) {- topic.suggested_topics = data.suggested_topics;- }- if (data.related_topics !== undefined) {- topic.related_topics = data.related_topics;- }- if (data.related_messages !== undefined) {- topic.related_messages = data.related_messages;- }- if (data.suggested_group_name !== undefined) {- topic.suggested_group_name = data.suggested_group_name;+ for (const key of [+ "suggested_topics",+ "related_topics",+ "related_messages",+ "suggested_group_name",+ ]) {+ if (data[key] !== undefined) {+ topic[key] = data[key];+ }}const assignTopic = (postData) => {@@ -248,6 +246,17 @@ export default class NestedRoute extends Route {const topic = this.store.createRecord("topic", data.topic);topic.set("is_nested_view", true);+ for (const key of [+ "suggested_topics",+ "related_topics",+ "related_messages",+ "suggested_group_name",+ ]) {+ if (data[key] !== undefined) {+ topic[key] = data[key];+ }+ }+const assignTopic = (postData) => {const post = this.store.createRecord("post", postData);post.topic = topic;@@ -262,13 +271,18 @@ export default class NestedRoute extends Route {const hasParentContext = targetReplyTo && targetReplyTo !== 1;const noAncestors = ancestors.length === 0 && hasParentContext;- // Build nested chain: ancestor[0] -> ancestor[1] -> ... -> target- // When context=0 (no ancestors), target becomes the chain root at depth 0.+ // Nest ancestors outermost-first so target ends up as the chain leaf.let chainTip = targetNode;for (let i = ancestors.length - 1; i >= 0; i--) {chainTip = { post: ancestors[i], children: [chainTip] };}+ // Force full NestedPost rebuild on every fetch: NestedPostChildren reads+ // @preloadedChildren only in its constructor, so without a fresh key the+ // inner cascade keeps rendering the previous target when two context+ // views share a chain root.+ chainTip._renderKey = crypto.randomUUID();+return {topic,opPost,diff --git a/frontend/discourse/app/routes/topic/from-params.js b/frontend/discourse/app/routes/topic/from-params.jsindex 529e929831e..3f34ea0a720 100644--- a/frontend/discourse/app/routes/topic/from-params.js+++ b/frontend/discourse/app/routes/topic/from-params.js@@ -10,6 +10,7 @@ import DiscourseRoute from "discourse/routes/discourse";// This route is used for retrieving a topic based on paramsexport default class TopicFromParams extends DiscourseRoute {+ @service appEvents;@service composer;@service header;@service router;@@ -62,7 +63,16 @@ export default class TopicFromParams extends DiscourseRoute {topic.set("_forcedFlat", true);} else {const postNumber = model.nearPost;- if (postNumber && postNumber > 1) {+ const targetsPost = postNumber && postNumber > 1;+ const alreadyOnTarget = this.#alreadyOnNestedTarget(topic, postNumber);++ // Re-route into the nested view. When alreadyOnTarget is true+ // this is a no-op transition that keeps the URL where it is;+ // when false it becomes a real route change. Either way we+ // must call it so we don't end up landing on /t/... — leaving+ // afterModel without a redirect would let the topic route's+ // setupController run.+ if (targetsPost) {this.router.replaceWith("nestedPost",topic.slug,@@ -72,6 +82,12 @@ export default class TopicFromParams extends DiscourseRoute {} else {this.router.replaceWith("nested", topic.slug, topic.id);}++ if (alreadyOnTarget) {+ // No transition will fire — nudge the context view to+ // re-scroll/highlight the target post.+ this.appEvents.trigger("nested:scroll-to-target");+ }return;}}@@ -153,6 +169,21 @@ export default class TopicFromParams extends DiscourseRoute {}}+ #alreadyOnNestedTarget(topic, postNumber) {+ const currentParams = this.router.currentRoute?.params;+ if (!currentParams || String(currentParams.topic_id) !== String(topic.id)) {+ return false;+ }+ const currentRoute = this.router.currentRouteName;+ if (postNumber && postNumber > 1) {+ return (+ currentRoute === "nestedPost" &&+ String(currentParams.post_number) === String(postNumber)+ );+ }+ return currentRoute === "nested";+ }+@actionwillTransition(transition) {this.controllerFor("topic").set("previousURL", document.location.pathname);diff --git a/lib/nested_replies/post_tree_serializer.rb b/lib/nested_replies/post_tree_serializer.rbindex 6a243d870cd..7d2d23d5614 100644--- a/lib/nested_replies/post_tree_serializer.rb+++ b/lib/nested_replies/post_tree_serializer.rb@@ -17,19 +17,19 @@ module NestedReplies].freezedef serialize_topic- serializer = TopicViewSerializer.new(@topic_view, scope: @guardian, root: false)- json = serializer.as_json- json[:has_activity_log] = activity_log_present?- json.except(:post_stream, :timeline_lookup, :user_badges, *SUGGESTED_AND_RELATED_KEYS)+ topic_view_json.merge(has_activity_log: activity_log_present?).except(+ :post_stream,+ :timeline_lookup,+ :user_badges,+ *SUGGESTED_AND_RELATED_KEYS,+ )end# Produces the suggested/related payload we piggyback on whichever# response has has_more_roots=false — mirroring how the flat view# ships suggested_topics on the final /t/:id/posts.json chunk.def serialize_suggested_and_related- serializer = TopicViewSerializer.new(@topic_view, scope: @guardian, root: false)- json = serializer.as_json- json.slice(*SUGGESTED_AND_RELATED_KEYS)+ topic_view_json.slice(*SUGGESTED_AND_RELATED_KEYS)enddef serialize_post(post, reply_counts, descendant_counts = {})@@ -83,6 +83,11 @@ module NestedRepliesprivate+ def topic_view_json+ @topic_view_json ||=+ TopicViewSerializer.new(@topic_view, scope: @guardian, root: false).as_json+ end+# Filters mirror Guardian#can_see_post? so the boolean does not leak# the existence of small_actions/whispers the user cannot see.def activity_log_present?diff --git a/spec/services/nested_topic/show_context_spec.rb b/spec/services/nested_topic/show_context_spec.rbindex 7c10d3a1057..2a11a30f08d 100644--- a/spec/services/nested_topic/show_context_spec.rb+++ b/spec/services/nested_topic/show_context_spec.rb@@ -72,6 +72,19 @@ RSpec.describe NestedTopic::ShowContext doendend+ context "with suggested/related payload" do+ # The context view has no pagination, so the suggested/related keys+ # must always ride along with the response — mirrors the final-page+ # behavior in NestedTopic::ListRoots.+ fab!(:other_topic) { Fabricate(:post).topic }++ it "attaches suggested/related keys to the response" do+ response = result[:response]+ expect(response).to include(:suggested_topics)+ expect(response[:suggested_topics].map(&:id)).to include(other_topic.id)+ end+ end+context "with context_depth set to 0" dolet(:params) { { target_post_number: target.post_number, sort: "top", context_depth: 0 } }diff --git a/spec/system/nested_collapse_replies_spec.rb b/spec/system/nested_collapse_replies_spec.rbindex 558a933cfcd..b1afd465e81 100644--- a/spec/system/nested_collapse_replies_spec.rb+++ b/spec/system/nested_collapse_replies_spec.rb@@ -62,5 +62,23 @@ RSpec.describe "Nested view collapse_replies URL param" do# button on the depth-1 reply.expect(nested_view).to have_no_post(reply_to_reply)end++ # collapse_replies is a "consolidated bucket parent" affordance: it+ # makes sense when the chain root IS the target (hide bucketed+ # replies behind a button). When the target is *below* the chain+ # root, applying collapseFromDepth=1 would hide the target itself,+ # defeating the whole point of the context view. The+ # effectiveCollapseFromDepth getter in context-view.gjs ignores+ # collapse_replies in that case.+ it "ignores collapse_replies and shows the target when the chain has ancestors" do+ page.visit("/n/#{topic.slug}/#{topic.id}/#{reply_to_reply.post_number}?collapse_replies=true")++ expect(nested_view).to have_context_view++ # Full chain renders: root → reply_to_root → reply_to_reply (target).+ expect(nested_view).to have_post(root_post)+ expect(nested_view).to have_post(reply_to_root)+ expect(nested_view).to have_post(reply_to_reply)+ endendenddiff --git a/spec/system/nested_context_view_spec.rb b/spec/system/nested_context_view_spec.rbindex d8f2b1cbe37..4d5443c1153 100644--- a/spec/system/nested_context_view_spec.rb+++ b/spec/system/nested_context_view_spec.rb@@ -197,6 +197,67 @@ RSpec.describe "Nested context view" doendend+ describe "in-route navigation between context views" do+ # Navigating context A → context B in-app (without a full page reload)+ # keeps the same controller/component mounted. When the two chains+ # share a root ancestor, the chain root <NestedPost> would be reused+ # by Glimmer (same post.id key) and its <NestedPostChildren> only+ # reads @preloadedChildren in its constructor — so without a forced+ # rebuild, the inner cascade keeps rendering the *previous* target's+ # chain. routes/nested.js stamps a per-fetch _renderKey on the chain+ # to force a full recreation; these specs guard that.+ it "rebuilds the chain so the new target is visible" do+ nested_view.visit_nested_context(topic, post_number: chain_posts[2].post_number)+ expect(nested_view).to have_post(chain_posts[2])++ nested_view.route_to_nested_context(topic, post_number: chain_posts[4].post_number)++ expect(page).to have_current_path(+ %r{/n/#{Regexp.escape(topic.slug)}/#{topic.id}/#{chain_posts[4].post_number}\b},+ )+ expect(nested_view).to have_post(chain_posts[4])+ expect(nested_view).to have_post(chain_posts[3])+ expect(nested_view).to have_post(chain_posts[0])+ end++ it "re-fires the highlight pulse on the new target after navigation" do+ nested_view.visit_nested_context(topic, post_number: chain_posts[2].post_number)+ expect(nested_view).to have_highlighted_post(chain_posts[2])++ nested_view.route_to_nested_context(topic, post_number: chain_posts[4].post_number)++ expect(nested_view).to have_highlighted_post(chain_posts[4])+ end++ # Notifications produce /t/slug/id/N URLs; topic/from-params.js+ # detects is_nested_view and redirects to /n/.../N. When N is the+ # post we're already viewing, the redirect is a no-op transition —+ # we still need the URL to stay on /n/ (not leak to /t/) and the+ # target to re-highlight via the nested:scroll-to-target appEvent.+ it "keeps the URL on /n/ and re-highlights when /t/ is routed to the post we're already on" do+ nested_view.visit_nested_context(topic, post_number: chain_posts[2].post_number)+ expect(nested_view).to have_highlighted_post(chain_posts[2])++ nested_view.route_to_topic_post(topic, post_number: chain_posts[2].post_number)++ expect(page).to have_current_path(+ %r{/n/#{Regexp.escape(topic.slug)}/#{topic.id}/#{chain_posts[2].post_number}\b},+ )+ expect(nested_view).to have_highlighted_post(chain_posts[2])+ end+ end++ describe "suggested topics" do+ fab!(:other_topic) { Fabricate(:post).topic }++ it "renders suggested topics below the chain" do+ nested_view.visit_nested_context(topic, post_number: chain_posts[2].post_number)++ expect(nested_view).to have_suggested_topics+ expect(nested_view).to have_suggested_topic(other_topic)+ end+ end+describe "replying in context view" doit "stays in nested view after replying" donested_view.visit_nested_context(topic, post_number: chain_posts[1].post_number)diff --git a/spec/system/page_objects/pages/nested_view.rb b/spec/system/page_objects/pages/nested_view.rbindex 565b43f4c42..d5fd345a6d1 100644--- a/spec/system/page_objects/pages/nested_view.rb+++ b/spec/system/page_objects/pages/nested_view.rb@@ -15,6 +15,27 @@ module PageObjectsselfend+ # In-app navigation via DiscourseURL.routeTo — exercises the same+ # routing code path a notification or in-page link click would,+ # rather than doing a full page reload like visit_nested_context.+ # Use this when the test needs to verify behavior that depends on+ # the existing nested controller/components staying mounted across+ # the transition.+ def route_to(path)+ page.execute_script(%(require("discourse/lib/url").default.routeTo(#{path.to_json});))+ self+ end++ def route_to_nested_context(topic, post_number:, query: nil)+ path = "/n/#{topic.slug}/#{topic.id}/#{post_number}"+ path += "?#{query}" if query+ route_to(path)+ end++ def route_to_topic_post(topic, post_number:)+ route_to("/t/#{topic.slug}/#{topic.id}/#{post_number}")+ end+# ── Root view assertions ──────────────────────────────────────def has_nested_view?