Skip to content

A platform for community discussion. Free, open, simple.

A11Y: improve focus when navigating to a specific post (#44200)

Kris93a0f72f4b45
diff --git a/frontend/discourse/app/components/discourse-topic.js b/frontend/discourse/app/components/discourse-topic.js
index 9fb51aa03f5..91945618f68 100644
--- a/frontend/discourse/app/components/discourse-topic.js
+++ b/frontend/discourse/app/components/discourse-topic.js
@@ -2,14 +2,12 @@
import Component from "@ember/component";
import { computed, set } from "@ember/object";
import { getOwner } from "@ember/owner";
-import { schedule, scheduleOnce } from "@ember/runloop";
+import { schedule } from "@ember/runloop";
import { service } from "@ember/service";
-import { isBlank } from "@ember/utils";
import { classNameBindings } from "@ember-decorators/component";
import { observes } from "@ember-decorators/object";
import ClickTrack from "discourse/lib/click-track";
import { bind } from "discourse/lib/decorators";
-import { highlightPost } from "discourse/lib/utilities";
@classNameBindings(
"multiSelect",
@@ -28,7 +26,6 @@ export default class DiscourseTopic extends Component {
init() {
super.init(...arguments);
this.appEvents.on("discourse:focus-changed", this, "gotFocus");
- this.appEvents.on("post:highlight", this, "_highlightPost");
}
willDestroy() {
@@ -36,7 +33,6 @@ export default class DiscourseTopic extends Component {
// this happens after route exit, stuff could have trickled in
this.appEvents.off("discourse:focus-changed", this, "gotFocus");
- this.appEvents.off("post:highlight", this, "_highlightPost");
}
@computed("topic.userFilters")
@@ -106,12 +102,6 @@ export default class DiscourseTopic extends Component {
}
}
- _highlightPost(postNumber, options = {}) {
- if (isBlank(options.jump) || options.jump !== false) {
- scheduleOnce("afterRender", null, highlightPost, postNumber);
- }
- }
-
@bind
_trackLinkClick(event) {
if (event.target.closest(".cooked a, a.track-link")) {
diff --git a/frontend/discourse/app/components/post-stream.gjs b/frontend/discourse/app/components/post-stream.gjs
index 4accbbf0672..801fb3f3252 100644
--- a/frontend/discourse/app/components/post-stream.gjs
+++ b/frontend/discourse/app/components/post-stream.gjs
@@ -4,6 +4,7 @@ import { concat, fn, get, hash } from "@ember/helper";
import { action } from "@ember/object";
import { next, schedule } from "@ember/runloop";
import { service } from "@ember/service";
+import { modifier } from "ember-modifier";
import PluginOutlet from "discourse/components/plugin-outlet";
import PostFilteredNotice from "discourse/components/post/filtered-notice";
import lazyHash from "discourse/helpers/lazy-hash";
@@ -38,6 +39,26 @@ export default class PostStream extends Component {
viewportTracker = new PostStreamViewportTracker();
+ /**
+ * Focuses the post requested via `PostStream#focusPostOnRender` once its
+ * content exists, which may be several renders after the request.
+ */
+ focusWhenRendered = modifier((element, [postNumber, cloaked, target]) => {
+ if (cloaked || target?.done || target?.postNumber !== postNumber) {
+ return;
+ }
+
+ const body = element.querySelector(".topic-body, .small-action-desc");
+ if (!body) {
+ return;
+ }
+
+ target.done = true;
+ body.setAttribute("tabindex", "0");
+ // jumpToPost owns scrolling; letting focus scroll too makes the page jump
+ body.focus({ preventScroll: true });
+ });
+
constructor() {
super(...arguments);
@@ -390,6 +411,11 @@ export default class PostStream extends Component {
@unlockPost={{fn @unlockPost post}}
@updateTopicPageQueryParams={{@updateTopicPageQueryParams}}
{{this.viewportTracker.registerPost post}}
+ {{this.focusWhenRendered
+ post.post_number
+ cloakingData.active
+ @postStream.focusTarget
+ }}
/>
{{/let}}
diff --git a/frontend/discourse/app/components/user-tip.gjs b/frontend/discourse/app/components/user-tip.gjs
index 30f964e02a2..be4f7734e98 100644
--- a/frontend/discourse/app/components/user-tip.gjs
+++ b/frontend/discourse/app/components/user-tip.gjs
@@ -45,6 +45,9 @@ export default class UserTip extends Component {
instance = new DTooltipInstance(getOwner(this), {
identifier: "user-tip",
interactive: true,
+ // tips appear unprompted, so taking focus would pull keyboard and
+ // screen reader users away from where they are
+ autofocus: false,
closeOnScroll: false,
closeOnClickOutside: true,
placement: this.args.placement,
diff --git a/frontend/discourse/app/controllers/topic.js b/frontend/discourse/app/controllers/topic.js
index dcc736b63dd..75fbdf3391b 100644
--- a/frontend/discourse/app/controllers/topic.js
+++ b/frontend/discourse/app/controllers/topic.js
@@ -146,6 +146,7 @@ export default class TopicController extends Controller {
init() {
super.init(...arguments);
+ this.appEvents.on("post:highlight", this, "_highlightPost");
this.appEvents.on("post:show-revision", this, "_showRevision");
this.appEvents.on("post:created", this, () =>
this._removeDeleteOnOwnerReplyBookmarks()
@@ -154,6 +155,7 @@ export default class TopicController extends Controller {
willDestroy() {
super.willDestroy(...arguments);
+ this.appEvents.off("post:highlight", this, "_highlightPost");
this.appEvents.off("post:show-revision", this, "_showRevision");
}
@@ -1907,6 +1909,12 @@ export default class TopicController extends Controller {
}
}
+ _highlightPost(postNumber, options = {}) {
+ if (options.jump !== false) {
+ this.model?.postStream?.focusPostOnRender(postNumber);
+ }
+ }
+
_showRevision(postNumber, revision) {
const post = this.model.get("postStream").postForPostNumber(postNumber);
diff --git a/frontend/discourse/app/instance-initializers/clean-dom-on-route-change.js b/frontend/discourse/app/instance-initializers/clean-dom-on-route-change.js
index f9b02205652..35717d483b3 100644
--- a/frontend/discourse/app/instance-initializers/clean-dom-on-route-change.js
+++ b/frontend/discourse/app/instance-initializers/clean-dom-on-route-change.js
@@ -1,5 +1,7 @@
import { scheduleOnce } from "@ember/runloop";
+let focusedBeforeTransition;
+
function _clean(transition) {
if (window.MiniProfiler && transition.from) {
window.MiniProfiler.pageTransition();
@@ -17,11 +19,16 @@ function _clean(transition) {
// Close PhotoSwipe
window.pswp?.close();
- // Remove any link focus
+ // Remove focus from the link that triggered navigation, but keep focus the
+ // new page set deliberately (e.g. on a linked post)
const { activeElement } = document;
- if (activeElement && !activeElement.classList.contains("no-blur")) {
+ if (
+ activeElement === focusedBeforeTransition &&
+ !activeElement.classList.contains("no-blur")
+ ) {
activeElement.blur();
}
+ focusedBeforeTransition = null;
this.lookup("route:application").send("closeModal");
@@ -35,6 +42,10 @@ export default {
initialize(owner) {
const router = owner.lookup("service:router");
+ router.on("routeWillChange", () => {
+ focusedBeforeTransition = document.activeElement;
+ });
+
router.on("routeDidChange", (transition) => {
if (transition.isAborted) {
return;
diff --git a/frontend/discourse/app/models/post-stream.js b/frontend/discourse/app/models/post-stream.js
index ac5d30c879d..641bf663852 100644
--- a/frontend/discourse/app/models/post-stream.js
+++ b/frontend/discourse/app/models/post-stream.js
@@ -16,7 +16,6 @@ import { deepMerge } from "discourse/lib/object";
import { autoTrackedArray } from "discourse/lib/tracked-tools";
import { applyBehaviorTransformer } from "discourse/lib/transformer";
import DiscourseURL from "discourse/lib/url";
-import { highlightPost } from "discourse/lib/utilities";
import RestModel from "discourse/models/rest";
import { loadTopicView } from "discourse/models/topic";
import { i18n } from "discourse-i18n";
@@ -74,6 +73,12 @@ export default class PostStream extends RestModel {
filterRepliesToPostNumber =
parseInt(this.topic.replies_to_post_number, 10) || false;
@tracked filterUpwardsPostID = false;
+
+ /**
+ * Post awaiting focus once rendered. A fresh object per request, so the
+ * renderer can mark it `done` without writing tracked state mid-render.
+ */
+ @tracked focusTarget = null;
@tracked gaps;
@tracked isMegaTopic;
@tracked lastId;
@@ -292,6 +297,19 @@ export default class PostStream extends RestModel {
return Object.values(this._identityMap).filter(Boolean);
}
+ /**
+ * Moves focus to a post once it is rendered, so keyboard and screen reader
+ * users continue from there. The first post is skipped, as the page start
+ * already leads to it.
+ *
+ * @param {number} postNumber
+ */
+ focusPostOnRender(postNumber) {
+ if (postNumber > 1) {
+ this.focusTarget = { postNumber, done: false };
+ }
+ }
+
cancelFilter() {
this.streamFilters.mixedHiddenPosts = false;
@@ -347,8 +365,7 @@ export default class PostStream extends RestModel {
: null;
DiscourseURL.jumpToPost(postNumber, { originalTopOffset });
-
- schedule("afterRender", () => highlightPost(postNumber));
+ this.focusPostOnRender(postNumber);
});
}
@@ -364,8 +381,7 @@ export default class PostStream extends RestModel {
if (this.posts?.length > 1) {
const postNumber = this.posts[1].post_number;
DiscourseURL.jumpToPost(postNumber, { skipIfOnScreen: true });
-
- schedule("afterRender", () => highlightPost(postNumber));
+ this.focusPostOnRender(postNumber);
}
});
}
diff --git a/spec/system/topic_post_focus_spec.rb b/spec/system/topic_post_focus_spec.rb
new file mode 100644
index 00000000000..4bfddf674ba
--- /dev/null
+++ b/spec/system/topic_post_focus_spec.rb
@@ -0,0 +1,41 @@
+# frozen_string_literal: true
+
+describe "Focusing the target post when opening a topic" do
+ fab!(:topic)
+ fab!(:posts) { Fabricate.times(30, :post, topic:) }
+ fab!(:target_post) { posts[19] }
+
+ it "focuses the post when the page is loaded at that post" do
+ visit(target_post.url)
+
+ expect(page).to have_css("#post_#{target_post.post_number} .topic-body:focus")
+ end
+
+ it "focuses the post when following a link to it from another topic" do
+ linking_post = Fabricate(:post, raw: "See #{Discourse.base_url}#{target_post.url}")
+ visit(linking_post.topic.url)
+
+ find("#post_1 .cooked a[href*='/t/']").click
+
+ expect(page).to have_css("#post_#{target_post.post_number} .topic-body:focus")
+ end
+
+ it "focuses the post when following a link to it within the same topic" do
+ posts[0].update!(raw: "See #{Discourse.base_url}#{target_post.url}")
+ posts[0].rebake!
+ visit(topic.url)
+
+ find("#post_1 .cooked a[href*='/t/']").click
+
+ expect(page).to have_css("#post_#{target_post.post_number} .topic-body:focus")
+ end
+
+ it "keeps focus on the post when a user tip appears" do
+ SiteSetting.enable_user_tips = true
+ sign_in(Fabricate(:user))
+ visit(target_post.url)
+
+ expect(PageObjects::Components::Tooltips.new("user-tip")).to be_present
+ expect(page).to have_css("#post_#{target_post.post_number} .topic-body:focus")
+ end
+end