Skip to content

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

A11Y: Improve accessibility in the post-stream; fix navigation (#35730)

Sérgio Saquetimf33f336e1f2c
diff --git a/app/assets/stylesheets/common/base/discourse.scss b/app/assets/stylesheets/common/base/discourse.scss
index 659bc98c327..2464bca15b3 100644
--- a/app/assets/stylesheets/common/base/discourse.scss
+++ b/app/assets/stylesheets/common/base/discourse.scss
@@ -1021,8 +1021,10 @@ form {
}
}
+#skip-links__container a,
a#user-nav-skip-link,
-a#skip-link {
+a#skip-link,
+.skip-link {
padding: var(--space-1) var(--space-2);
position: fixed;
top: -50px;
@@ -1036,6 +1038,10 @@ a#skip-link {
top: 0;
transition: top 0.15s ease-in;
}
+
+ &:visited {
+ color: var(--secondary);
+ }
}
.scroll-lock {
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 3765b833d8a..8bd2806329b 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -305,6 +305,12 @@ en:
topic_admin_menu: "topic actions"
skip_to_main_content: "Skip to main content"
+ skip_links_label: "Skip navigation links"
+ skip_to_post: "Skip to post %{post_number}"
+ skip_to_where_you_left_off: "Skip to where you left off (post %{post_number})"
+ skip_to_where_you_left_off_last: "Skip to where you left off (last reply, post %{post_number})"
+ skip_to_last_reply: "Skip to last reply"
+ skip_to_top: "Skip to top"
skip_user_nav: "Skip to profile content"
emails_are_disabled: "All outgoing email has been globally disabled by an administrator. No email notifications of any kind will be sent."
@@ -4112,6 +4118,7 @@ en:
actions: "Bulk actions"
post:
+ accessible_heading: "post by %{username} %{date}"
confirm_delete: "Are you sure you want to delete this post?"
quote_reply: "Quote"
quote_reply_shortcut: "Quote (or press q)"
@@ -4135,8 +4142,13 @@ en:
deleted_by_author_simple: "(post deleted by author)"
collapse: "collapse"
load_more_replies: "load more replies"
+ load_more_posts_above: "Load more posts above"
+ load_more_posts_below: "Load more posts below"
sr_collapse_replies: "Collapse embedded replies"
sr_load_more_replies: "Load more embedded replies"
+ loading_more_posts_above: "Loading more posts above..."
+ loading_more_posts_below: "Loading more posts below..."
+ loading_complete: "Loading complete"
sr_date: "Post date"
sr_expand_replies:
one: "This post has %{count} reply"
diff --git a/frontend/discourse/app/components/a11y/live-regions.gjs b/frontend/discourse/app/components/a11y/live-regions.gjs
new file mode 100644
index 00000000000..d4df9b906c6
--- /dev/null
+++ b/frontend/discourse/app/components/a11y/live-regions.gjs
@@ -0,0 +1,27 @@
+import Component from "@glimmer/component";
+import { service } from "@ember/service";
+
+export default class A11yLiveRegions extends Component {
+ @service a11y;
+
+ <template>
+ <div
+ id="a11y-announcements-polite"
+ class="sr-only"
+ role="status"
+ aria-live="polite"
+ aria-atomic="true"
+ >
+ {{this.a11y.politeMessage}}
+ </div>
+ <div
+ id="a11y-announcements-assertive"
+ class="sr-only"
+ role="alert"
+ aria-live="assertive"
+ aria-atomic="true"
+ >
+ {{this.a11y.assertiveMessage}}
+ </div>
+ </template>
+}
diff --git a/frontend/discourse/app/components/a11y/skip-links.gjs b/frontend/discourse/app/components/a11y/skip-links.gjs
new file mode 100644
index 00000000000..93809555e1e
--- /dev/null
+++ b/frontend/discourse/app/components/a11y/skip-links.gjs
@@ -0,0 +1,40 @@
+import Component from "@glimmer/component";
+import { service } from "@ember/service";
+import { i18n } from "discourse-i18n";
+
+class A11ySkipLinksContainer extends Component {
+ @service a11y;
+
+ <template>
+ {{#if this.a11y.showSkipLinks}}
+ <div
+ id="skip-links__container"
+ class="skip-links"
+ aria-label={{i18n "skip_links_label"}}
+ >
+ <div>
+ {{! wrapper used to render the skip links }}
+ </div>
+ <a href="#main-container" class="skip-link">
+ {{i18n "skip_to_main_content"}}
+ </a>
+ </div>
+ {{/if}}
+ </template>
+}
+
+export default class A11ySkipLinks extends Component {
+ static Container = A11ySkipLinksContainer;
+
+ @service a11y;
+
+ wrapperElement = document.querySelector("#skip-links__container > div");
+
+ <template>
+ {{#if this.a11y.showSkipLinks}}
+ {{#in-element this.wrapperElement insertAfter=null}}
+ {{yield}}
+ {{/in-element}}
+ {{/if}}
+ </template>
+}
diff --git a/frontend/discourse/app/components/post-stream.gjs b/frontend/discourse/app/components/post-stream.gjs
index c900eb62d11..7bf8a6e2da5 100644
--- a/frontend/discourse/app/components/post-stream.gjs
+++ b/frontend/discourse/app/components/post-stream.gjs
@@ -6,7 +6,6 @@ import { next, schedule } from "@ember/runloop";
import { service } from "@ember/service";
import { and, eq, not } from "truth-helpers";
import ConditionalLoadingSpinner from "discourse/components/conditional-loading-spinner";
-import LoadMore from "discourse/components/load-more";
import PluginOutlet from "discourse/components/plugin-outlet";
import PostFilteredNotice from "discourse/components/post/filtered-notice";
import concatClass from "discourse/helpers/concat-class";
@@ -17,6 +16,7 @@ import { Placeholder } from "discourse/models/post-stream";
import PostStreamViewportTracker from "discourse/modifiers/post-stream-viewport-tracker";
import Post from "./post";
import PostGap from "./post/gap";
+import PostLoadMoreAccessible from "./post/load-more-accessible";
import PostPlaceholder from "./post/placeholder";
import PostSmallAction from "./post/small-action";
import PostTimeGap from "./post/time-gap";
@@ -80,6 +80,14 @@ export default class PostStream extends Component {
return this.posts.at(-1);
}
+ @cached
+ get existingPostNumbers() {
+ return this.posts
+ .filter((post) => !this.isPlaceholder(post))
+ .map((post) => post.post_number)
+ .filter((num) => !isNaN(num));
+ }
+
@cached
get postTuples() {
const posts = this.posts;
@@ -247,7 +255,15 @@ export default class PostStream extends Component {
}}
>
{{#if (and (not @postStream.loadingAbove) @postStream.canPrependMore)}}
- <LoadMore @action={{fn this.loadMoreAbove this.firstAvailablePost}} />
+ <PostLoadMoreAccessible
+ @action={{fn this.loadMoreAbove this.firstAvailablePost}}
+ @canLoadMore={{@postStream.canPrependMore}}
+ @direction="above"
+ @existingPostNumbers={{this.existingPostNumbers}}
+ @firstAvailablePost={{this.firstAvailablePost}}
+ @lastAvailablePost={{this.lastAvailablePost}}
+ @postStream={{@postStream}}
+ />
{{/if}}
{{#each this.postTuples key="post.id" as |tuple index|}}
@@ -280,16 +296,19 @@ export default class PostStream extends Component {
post above=this.cloakAbove below=this.cloakBelow
)
(eq this.keyboardSelectedPostNumber post.post_number)
- as |PostComponent cloakingData keyboardSelected|
+ (concat "post_" post.post_number)
+ as |PostComponent cloakingData keyboardSelected postId|
}}
<PostComponent
- id={{concat "post_" post.post_number}}
+ id={{postId}}
class={{concatClass
(if cloakingData.active "post-stream--cloaked")
(if keyboardSelected "selected")
}}
style={{cloakingData.style}}
@cloaked={{cloakingData.active}}
+ {{! template-lint-disable no-duplicate-id }}
+ @elementId={{postId}}
@post={{post}}
@prevPost={{previousPost}}
@nextPost={{nextPost}}
@@ -354,7 +373,15 @@ export default class PostStream extends Component {
{{#unless @postStream.loadingBelow}}
{{#if @postStream.canAppendMore}}
- <LoadMore @action={{fn this.loadMoreBelow this.lastAvailablePost}} />
+ <PostLoadMoreAccessible
+ @action={{fn this.loadMoreBelow this.lastAvailablePost}}
+ @canLoadMore={{@postStream.canAppendMore}}
+ @direction="below"
+ @existingPostNumbers={{this.existingPostNumbers}}
+ @firstAvailablePost={{this.firstAvailablePost}}
+ @lastAvailablePost={{this.lastAvailablePost}}
+ @postStream={{@postStream}}
+ />
{{else}}
<div
class="post-stream__bottom-boundary"
diff --git a/frontend/discourse/app/components/post.gjs b/frontend/discourse/app/components/post.gjs
index 4e32a90840e..61b73571c2c 100644
--- a/frontend/discourse/app/components/post.gjs
+++ b/frontend/discourse/app/components/post.gjs
@@ -12,6 +12,7 @@ import { and, eq, not, or } from "truth-helpers";
import DButton from "discourse/components/d-button";
import ShareTopicModal from "discourse/components/modal/share-topic";
import PluginOutlet from "discourse/components/plugin-outlet";
+import PostA11yHeading from "discourse/components/post/a11y-heading";
import PostActionsSummary from "discourse/components/post/actions-summary";
import PostAvatar from "discourse/components/post/avatar";
import PostCookedHtml from "discourse/components/post/cooked-html";
@@ -25,6 +26,7 @@ import TopicMap from "discourse/components/topic-map";
import concatClass from "discourse/helpers/concat-class";
import lazyHash from "discourse/helpers/lazy-hash";
import { isTesting } from "discourse/lib/environment";
+import { relativeAge } from "discourse/lib/formatter";
import getURL, { getAbsoluteURL } from "discourse/lib/get-url";
import postActionFeedback from "discourse/lib/post-action-feedback";
import { nativeShare } from "discourse/lib/pwa-utils";
@@ -37,6 +39,7 @@ import { clipboardCopy } from "discourse/lib/utilities";
import { i18n } from "discourse-i18n";
export default class Post extends Component {
+ @service a11y;
@service appEvents;
@service capabilities;
@service currentUser;
@@ -118,10 +121,6 @@ export default class Post extends Component {
return this.repliesAbove?.isResolved && this.repliesAbove.value.length > 0;
}
- get id() {
- return `post_${this.args.post.post_number}`;
- }
-
get isFromCurrentUser() {
return this.currentUser && this.currentUser.id === this.args.post.user_id;
}
@@ -150,6 +149,22 @@ export default class Post extends Component {
return this.args.height ? `${this.args.height}px` : null;
}
+ get a11yHeadingText() {
+ // a11y.autoUpdatingRelativeDateRef is consumed to force the heading text to be auto-updated
+ const date =
+ this.a11y.autoUpdatingRelativeDateRef && this.args.post.displayDate
+ ? relativeAge(new Date(this.args.post.displayDate), {
+ format: "medium-with-ago-and-on",
+ wrapInSpan: false,
+ })
+ : "";
+
+ return i18n("post.accessible_heading", {
+ username: this.args.post.username,
+ date,
+ });
+ }
+
get repliesShown() {
return this.filteredRepliesView
? this.filteredRepliesShown
@@ -424,8 +439,9 @@ export default class Post extends Component {
we need to only set it in the `div` when the post is cloaked.
This is not ideal, but the post-stream component sets the `id` for the children to ensure
all cloaked items can be referenced and we need to override it }}
- id={{if @cloaked (concat "post_" @post.post_number)}}
+ id={{if @cloaked @elementId}}
>
+ <PostA11yHeading @post={{@post}} @text={{this.a11yHeadingText}} />
{{#unless @cloaked}}
{{#let
(lazyHash
@@ -442,7 +458,7 @@ export default class Post extends Component {
}}
<PluginOutlet @name="post-article" @outletArgs={{postOutletArgs}}>
<article
- id={{this.id}}
+ id={{@elementId}}
class={{concatClass
"boxed"
"onscreen-post"
@@ -456,11 +472,7 @@ export default class Post extends Component {
(if @post.via_email "post--via-email via-email")
this.additionalArticleClasses
}}
- aria-label={{i18n
- "share.post"
- }}
- role="region"
+ aria-labelledby={{concat "post-heading-" @post.post_number}}
data-post-id={{@post.id}}
data-topic-id={{@post.topicId}}
data-user-id={{@post.user_id}}
diff --git a/frontend/discourse/app/components/post/a11y-heading.gjs b/frontend/discourse/app/components/post/a11y-heading.gjs
new file mode 100644
index 00000000000..c3f14e0bc48
--- /dev/null
+++ b/frontend/discourse/app/components/post/a11y-heading.gjs
@@ -0,0 +1,14 @@
+import { concat } from "@ember/helper";
+
+const PostA11yHeading = <template>
+ <h2
+ ...attributes
+ aria-hidden="false"
+ class="sr-only"
+ id={{concat "post-heading-" @post.post_number}}
+ >
+ {{@text}}
+ </h2>
+</template>;
+
+export default PostA11yHeading;
diff --git a/frontend/discourse/app/components/post/load-more-accessible.gjs b/frontend/discourse/app/components/post/load-more-accessible.gjs
new file mode 100644
index 00000000000..1ce43742beb
--- /dev/null
+++ b/frontend/discourse/app/components/post/load-more-accessible.gjs
@@ -0,0 +1,72 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import LoadMore from "discourse/components/load-more";
+import { i18n } from "discourse-i18n";
+
+export default class PostLoadMoreAccessible extends Component {
+ @service a11y;
+
+ @tracked loading = false;
+
+ get canLoadMore() {
+ return this.args.canLoadMore ?? true;
+ }
+
+ get direction() {
+ return this.args.direction || "below";
+ }
+
+ get enabled() {
+ return this.args.enabled ?? true;
+ }
+
+ get label() {
+ if (this.loading) {
+ this.direction === "above"
+ ? "post.loading_more_posts_above"
+ : "post.loading_more_posts_below";
+ }
+
+ return i18n(
+ this.direction === "above"
+ ? "post.load_more_posts_above"
+ : "post.load_more_posts_below"
+ );
+ }
+
+ @action
+ async handleLoadAndAnnouncement() {
+ if (!this.enabled || !this.canLoadMore || this.loading) {
+ return;
+ }
+
+ try {
+ this.loading = true;
+
+ this.a11y.announce(i18n(`post.loading_more_${this.direction}`), "polite");
+ await this.args.action();
+ this.a11y.announce(i18n("post.loading_complete"), "polite");
+ } finally {
+ this.loading = false;
+ }
+ }
+
+ <template>
+ <LoadMore
+ @action={{this.handleLoadAndAnnouncement}}
+ @enabled={{this.enabled}}
+ />
+
+ {{! Screen reader accessible heading for navigation-based loading }}
+ <div class="post-stream-load-more-accessible sr-only">
+ <h2
+ class="post-stream-load-more-accessible__heading"
+ id="post-stream-load-more-heading__{{this.direction}}"
+ >
+ {{this.label}}
+ </h2>
+ </div>
+ </template>
+}
diff --git a/frontend/discourse/app/components/post/meta-data.gjs b/frontend/discourse/app/components/post/meta-data.gjs
index ea606812ad5..3659622fa1a 100644
--- a/frontend/discourse/app/components/post/meta-data.gjs
+++ b/frontend/discourse/app/components/post/meta-data.gjs
@@ -99,7 +99,7 @@ export default class PostMetaData extends Component {
}
<template>
- <div class="topic-meta-data" role="heading" aria-level="2">
+ <div class="topic-meta-data">
{{#if this.shouldDisplayPosterName}}
<PostMetaDataPosterName @post={{@post}} />
{{/if}}
diff --git a/frontend/discourse/app/components/post/meta-data/date.gjs b/frontend/discourse/app/components/post/meta-data/date.gjs
index b5189984d97..e7dee092ad0 100644
--- a/frontend/discourse/app/components/post/meta-data/date.gjs
+++ b/frontend/discourse/app/components/post/meta-data/date.gjs
@@ -11,14 +11,6 @@ import { i18n } from "discourse-i18n";
export default class PostMetaDataDate extends Component {
@service modal;
- get date() {
- if (this.args.post.wiki && this.args.post.last_wiki_edit) {
- return this.args.post.last_wiki_edit;
- } else {
- return this.args.post.created_at;
- }
- }
-
@action
showShareModal(evt) {
evt.preventDefault();
@@ -42,7 +34,7 @@ export default class PostMetaDataDate extends Component {
title={{i18n "post.sr_date"}}
{{on "click" this.showShareModal}}
>
- <RelativeDate @date={{this.date}} />
+ <RelativeDate @date={{@post.displayDate}} />
</a>
</div>
</template>
diff --git a/frontend/discourse/app/components/post/small-action.gjs b/frontend/discourse/app/components/post/small-action.gjs
index 12df73772ff..e07f554c462 100644
--- a/frontend/discourse/app/components/post/small-action.gjs
+++ b/frontend/discourse/app/components/post/small-action.gjs
@@ -1,5 +1,7 @@
import Component from "@glimmer/component";
import { cached } from "@glimmer/tracking";
+import { concat } from "@ember/helper";
+import { service } from "@ember/service";
import { htmlSafe } from "@ember/template";
import { TrackedMap } from "@ember-compat/tracked-built-ins";
import DButton from "discourse/components/d-button";
@@ -7,11 +9,12 @@ import PostCookedHtml from "discourse/components/post/cooked-html";
import UserAvatar from "discourse/components/user-avatar";
import concatClass from "discourse/helpers/concat-class";
import icon from "discourse/helpers/d-icon";
-import { autoUpdatingRelativeAge } from "discourse/lib/formatter";
+import { autoUpdatingRelativeAge, relativeAge } from "discourse/lib/formatter";
import getURL from "discourse/lib/get-url";
import { applyValueTransformer } from "discourse/lib/transformer";
import { userPath } from "discourse/lib/url";
import { i18n } from "discourse-i18n";
+import PostA11yHeading from "./a11y-heading";
// TODO (glimmer-post-stream) remove the export after removing the legacy widget code
export const GROUP_ACTION_CODES = ["invited_group", "removed_group"];
@@ -54,6 +57,8 @@ export function resetGroupPostSmallActionCodes() {
}
export default class PostSmallAction extends Component {
+ @service a11y;
+
decoratorState = new TrackedMap();
@cached
@@ -79,6 +84,23 @@ export default class PostSmallAction extends Component {
return new Date(this.args.post.created_at);
}
+ get a11yHeadingText() {
+ // plain text version for screen reader headings
+ // a11y.autoUpdatingRelativeDateRef is consumed to force the heading text to be auto-updated
+ const when =
+ this.a11y.autoUpdatingRelativeDateRef && this.createdAt
+ ? relativeAge(this.createdAt, {
+ format: "medium-with-ago-and-on",
+ wrapInSpan: false,
+ })
+ : "";
+
+ const who = this.who ? `@${this.who}` : "";
+
+ // TODO (a11y) some i18n strings have HTML embedded in them. We need to strip
+ return i18n(`action_codes.${this.code}`, { who, when, path: this.path });
+ }
+
get description() {
const when = this.createdAt
? autoUpdatingRelativeAge(this.createdAt, {
@@ -129,87 +151,97 @@ export default class PostSmallAction extends Component {
}
<template>
- <article
+ <div
...attributes
- class={{unless
- @cloaked
- (concatClass
- "small-action"
- "onscreen-post"
- (if @post.deleted "deleted")
- this.additionalClasses
- )
- }}
- aria-label={{i18n
- "share.post"
- }}
- role="region"
+ {{! The component is wrapped in a `div` and sets the same `id` below in the `article` tag,
+ we need to only set it in the `div` when the post is cloaked.
+ This is not ideal, but the post-stream component sets the `id` for the children to ensure
+ all cloaked items can be referenced and we need to override it }}
data-post-number={{@post.post_number}}
+ id={{if @cloaked @elementId}}
>
+ <PostA11yHeading @post={{@post}} @text={{this.a11yHeadingText}} />
{{#unless @cloaked}}
- <div class="topic-avatar">
- {{icon this.icon}}
- </div>
- <div class="small-action-desc">
- <div class="small-action-contents" role="heading" aria-level="2">
- <UserAvatar
- @ariaHidden={{false}}
- @size="small"
- @user={{@post.user}}
- />
- {{#if this.CustomComponent}}
- <this.CustomComponent
- @code={{this.code}}
- @post={{@post}}
- @createdAt={{this.createdAt}}
- @path={{this.path}}
- @who={{this.who}}
- />
- {{else}}
- <p>{{htmlSafe this.description}}</p>
- {{/if}}
+ <article
+ id={{@elementId}}
+ class={{unless
+ @cloaked
+ (concatClass
+ "small-action"
+ "onscreen-post"
+ (if @post.deleted "deleted")
+ this.additionalClasses
+ )
+ }}
+ aria-labelledby={{concat "post-heading-" @post.post_number}}
+ data-post-id={{@post.id}}
+ data-topic-id={{@post.topicId}}
+ data-user-id={{@post.user_id}}
+ >
+ <div class="topic-avatar">
+ {{icon this.icon}}
</div>
- <div class="small-action-buttons">
- {{#if @post.canRecover}}
- <DButton
- class="btn-flat small-action-recover"
- @icon="arrow-rotate-left"
- @action={{@recoverPost}}
- @title="post.controls.undelete"
- />
- {{else if @post.can_edit}}
- <DButton
- class="btn-flat small-action-edit"
- @icon="pencil"
- @action={{@editPost}}
- @title="post.controls.edit"
- />
- {{/if}}
- {{#if @post.canDelete}}
- <DButton
- class="btn-flat btn-danger small-action-delete"
- @icon="trash-can"
- @action={{@deletePost}}
- @title="post.controls.delete"
+ <div class="small-action-desc">
+ <div class="small-action-contents">
+ <UserAvatar
+ @ariaHidden={{false}}
+ @size="small"
+ @user={{@post.user}}
/>
- {{/if}}
- </div>
- {{#unless this.CustomComponent}}
- {{#if @post.cooked}}
- <div class="small-action-custom-message">
- <PostCookedHtml
+ {{#if this.CustomComponent}}
+ <this.CustomComponent
+ @code={{this.code}}
@post={{@post}}
- @decoratorState={{this.decoratorState}}
- @highlightTerm={{@highlightTerm}}
- @streamElement={{@streamElement}}
+ @createdAt={{this.createdAt}}
+ @path={{this.path}}
+ @who={{this.who}}
+ />
+ {{else}}
+ {{! aria-hidden is set to true because the a11y heading text is
+ almost the same as the description}}
+ <p aria-hidden="true">{{htmlSafe this.description}}</p>
+ {{/if}}
+ </div>
+ <div class="small-action-buttons">
+ {{#if @post.canRecover}}
+ <DButton
+ class="btn-flat small-action-recover"
+ @icon="arrow-rotate-left"
+ @action={{@recoverPost}}
+ @title="post.controls.undelete"
+ />
+ {{else if @post.can_edit}}
+ <DButton
+ class="btn-flat small-action-edit"
+ @icon="pencil"
+ @action={{@editPost}}
+ @title="post.controls.edit"
/>
- </div>
- {{/if}}
- {{/unless}}
- </div>
+ {{/if}}
+ {{#if @post.canDelete}}
+ <DButton
+ class="btn-flat btn-danger small-action-delete"
+ @icon="trash-can"
+ @action={{@deletePost}}
+ @title="post.controls.delete"
+ />
+ {{/if}}
+ </div>
+ {{#unless this.CustomComponent}}
+ {{#if @post.cooked}}
+ <div class="small-action-custom-message">
+ <PostCookedHtml
+ @post={{@post}}
+ @decoratorState={{this.decoratorState}}
+ @highlightTerm={{@highlightTerm}}
+ @streamElement={{@streamElement}}
+ />
+ </div>
+ {{/if}}
+ {{/unless}}
+ </div>
+ </article>
{{/unless}}
- </article>
+ </div>
</template>
}
diff --git a/frontend/discourse/app/components/topic-skip-links.gjs b/frontend/discourse/app/components/topic-skip-links.gjs
new file mode 100644
index 00000000000..29c5beb2502
--- /dev/null
+++ b/frontend/discourse/app/components/topic-skip-links.gjs
@@ -0,0 +1,210 @@
+import Component from "@glimmer/component";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { cancel, later, schedule } from "@ember/runloop";
+import A11ySkipLinks from "discourse/components/a11y/skip-links";
+import discourseDebounce from "discourse/lib/debounce";
+import { i18n } from "discourse-i18n";
+import { forceFocus } from "../lib/dom-utils";
+
+class TopicSkipLinks extends Component {
+ #mutationObserver;
+ #pendingFocusAttempt;
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.#cleanupObserver();
+ }
+
+ get showTopicSkipLinks() {
+ return this.args.topic?.last_read_post_number > 0;
+ }
+
+ get resumePostNumber() {
+ if (this.args.topic.last_read_post_number > 1) {
+ return this.args.topic.last_read_post_number;
+ }
+
+ return null;
+ }
+
+ get lastPostNumber() {
+ return (
+ this.args.topic.highest_post_number || this.args.topic.posts_count || null
+ );
+ }
+
+ get resumeIsLastReply() {
+ const resumePostNumber = this.args.topic.last_read_post_number;
+ const lastPostNumber =
+ this.args.topic.highest_post_number || this.args.topic.posts_count;
+
+ return (
+ resumePostNumber && lastPostNumber && resumePostNumber >= lastPostNumber
+ );
+ }
+
+ get topicHasMultiplePosts() {
+ const postsCount = this.args.topic.posts_count;
+ return postsCount && postsCount > 1;
+ }
+
+ @action
+ async focusSelector(selector, timeout = 3000) {
+ this.#cleanupObserver();
+
+ if (!selector) {
+ return;
+ }
+
+ try {
+ await this.#waitForSelectorWithTimeout(selector, timeout);
+ this.#tryFocusSelector(selector);
+ } finally {
+ this.#cleanupObserver();
+ }
+ }
+
+ #tryFocusSelector(selector) {
+ const element = document.querySelector(selector);
+ if (element) {
+ forceFocus(element);
+ return true;
+ }
+ return false;
+ }
+
+ #waitForSelectorWithTimeout(selector, timeout) {
+ return new Promise((resolve) => {
+ let timeoutTimer;
+
+ const cleanupAndResolve = () => {
+ if (timeoutTimer) {
+ cancel(timeoutTimer);
+ }
+ this.#mutationObserver?.disconnect();
+ resolve();
+ };
+
+ timeoutTimer = later(cleanupAndResolve, timeout);
+
+ this.#mutationObserver = new MutationObserver(() => {
+ this.#pendingFocusAttempt = discourseDebounce(
+ this,
+ () => {
+ if (document.querySelector(selector)) {
+ cleanupAndResolve();
+ }
+ },
+ 200
+ );
+ });
+
+ this.#mutationObserver.observe(document, {
+ childList: true,
+ subtree: true,
+ attributes: true,
+ });
+ });
+ }
+
+ #cleanupObserver() {
+ this.#mutationObserver?.disconnect();
+ this.#mutationObserver = null;
+
+ if (this.#pendingFocusAttempt) {
+ cancel(this.#pendingFocusAttempt);
+ }
+ }
+
+ <template>
+ <A11ySkipLinks>
+ {{#if this.showTopicSkipLinks}}
+ {{#if this.resumePostNumber}}
+ {{#if this.resumeIsLastReply}}
+ <SkipTo
+ @topic={{@topic}}
+ @postNumber={{this.resumePostNumber}}
+ @onClick={{this.focusSelector}}
+ >
+ {{i18n
+ "skip_to_where_you_left_off_last"
+ post_number=this.resumePostNumber
+ }}
+ </SkipTo>
+ {{else}}
+ <SkipTo
+ @topic={{@topic}}
+ @postNumber={{this.resumePostNumber}}
+ @onClick={{this.focusSelector}}
+ >
+ {{i18n
+ "skip_to_where_you_left_off"
+ post_number=this.resumePostNumber
+ }}
+ </SkipTo>
+ {{#if this.topicHasMultiplePosts}}
+ <SkipTo
+ @topic={{@topic}}
+ @postNumber={{this.lastPostNumber}}
+ @onClick={{this.focusSelector}}
+ >
+ {{i18n "skip_to_last_reply"}}
+ </SkipTo>
+ {{/if}}
+ {{/if}}
+ {{else}}
+ {{#if this.topicHasMultiplePosts}}
+ <SkipTo
+ @topic={{@topic}}
+ @postNumber={{this.lastPostNumber}}
+ @onClick={{this.focusSelector}}
+ >
+ {{i18n "skip_to_last_reply"}}
+ </SkipTo>
+ {{/if}}
+ {{/if}}
+ {{#if this.topicHasMultiplePosts}}
+ <SkipTo
+ @topic={{@topic}}
+ @postNumber="1"
+ @onClick={{this.focusSelector}}
+ >
+ {{i18n "skip_to_top"}}
+ </SkipTo>
+ {{/if}}
+ {{/if}}
+ </A11ySkipLinks>
+ </template>
+}
+
+class SkipTo extends Component {
+ get url() {
+ return `${this.args.topic.url}/${this.args.postNumber}`;
+ }
+
+ @action
+ async handleSkipToPost() {
+ let focusSelector;
+
+ if (Number(this.args.postNumber) === 1) {
+ focusSelector = "#topic-title h1";
+ } else {
+ focusSelector = `[data-post-number="${this.args.postNumber}"] .post__body`;
+ }
+
+ schedule("afterRender", () => {
+ this.args.onClick(focusSelector);
+ });
+ }
+
+ <template>
+ {{#if @postNumber}}
+ <a href={{this.url}} {{on "click" this.handleSkipToPost}}>
+ {{yield}}
+ </a>
+ {{/if}}
+ </template>
+}
+
+export default TopicSkipLinks;
diff --git a/frontend/discourse/app/controllers/application.js b/frontend/discourse/app/controllers/application.js
index 9170c66153d..2dc514bfcb3 100644
--- a/frontend/discourse/app/controllers/application.js
+++ b/frontend/discourse/app/controllers/application.js
@@ -11,9 +11,9 @@ import { isTesting } from "discourse/lib/environment";
const HIDE_SIDEBAR_KEY = "sidebar-hidden";
export default class ApplicationController extends Controller {
+ @service footer;
// eslint-disable-next-line discourse/no-unused-services
@service router; // used in the route template
- @service footer;
@service sidebarState;
queryParams = [{ navigationMenuQueryParamOverride: "navigation_menu" }];
@@ -22,7 +22,6 @@ export default class ApplicationController extends Controller {
sidebarDisabledRouteOverride = false;
navigationMenuQueryParamOverride = null;
showSiteHeader = true;
- showSkipToContent = true;
@tracked _showSidebar;
diff --git a/frontend/discourse/app/controllers/topic.js b/frontend/discourse/app/controllers/topic.js
index d5eedc8fc42..7e130643b75 100644
--- a/frontend/discourse/app/controllers/topic.js
+++ b/frontend/discourse/app/controllers/topic.js
@@ -64,17 +64,19 @@ export function registerCustomPostMessageCallback(type, callback) {
}
export default class TopicController extends Controller {
+ @service appEvents;
@service composer;
+ @service currentUser;
@service dialog;
@service documentTitle;
- @service screenTrack;
+
+ @service header; // used in the template
+ @service languageNameLookup;
@service modal;
- @service currentUser;
@service router;
- @service siteSettings;
+ @service screenTrack;
@service site;
- @service appEvents;
- @service languageNameLookup;
+ @service siteSettings;
@tracked model;
@@ -136,6 +138,10 @@ export default class TopicController extends Controller {
});
}
+ get titleIsVisibleOnHeader() {
+ return !this.header.mainTopicTitleVisible;
+ }
+
updateQueryParams() {
const filters = this.get("model.postStream.streamFilters");
@@ -547,7 +553,7 @@ export default class TopicController extends Controller {
// Called when the topmost visible post on the page changes.
@action
- topVisibleChanged(event) {
+ async topVisibleChanged(event) {
const { post, refresh } = event;
if (!post) {
return;
@@ -561,13 +567,13 @@ export default class TopicController extends Controller {
}
if (firstLoadedPost && firstLoadedPost === post) {
- postStream.prependMore().then(() => refresh?.());
+ await postStream.prependMore();
+ refresh?.();
}
}
- // Called the bottommost visible post on the page changes.
@action
- bottomVisibleChanged(event) {
+ async bottomVisibleChanged(event) {
const { post, refresh } = event;
const postStream = this.get("model.postStream");
@@ -578,9 +584,7 @@ export default class TopicController extends Controller {
lastLoadedPost === post &&
postStream.get("canAppendMore")
) {
- // TODO (glimmer-post-stream) the Glimmer Post stream doesn't pass a refresh function
- postStream.appendMore().then(() => refresh?.());
- // show loading stuff
+ await postStream.appendMore();
// TODO (glimmer-post-stream) the Glimmer Post stream doesn't pass a refresh function
refresh?.();
}
diff --git a/frontend/discourse/app/helpers/boolean-string.js b/frontend/discourse/app/helpers/boolean-string.js
new file mode 100644
index 00000000000..a121d2c7e74
--- /dev/null
+++ b/frontend/discourse/app/helpers/boolean-string.js
@@ -0,0 +1,28 @@
+/**
+ * Converts a boolean value to its string representation ("true" or "false").
+ * When omitFalse is true (default), falsy values return undefined instead of "false".
+ *
+ * @param {boolean} value - The boolean value to convert
+ * @param {Object} [opts={ omitFalse: true }] - Options object
+ * @param {boolean} [opts.omitFalse=true] - When true, falsy values return undefined instead of "false"
+ * @returns {string|undefined} Returns "true" for truthy values, "false" for falsy values (unless omitted)
+ *
+ * @example
+ * // Returns "true"
+ * booleanString(true);
+ *
+ * @example
+ * // Returns undefined (with default options)
+ * booleanString(false);
+ *
+ * @example
+ * // Returns "false"
+ * booleanString(false, { omitFalse: false });
+ */
+export default function booleanString(value, opts = { omitFalse: true }) {
+ if (opts.omitFalse && !value) {
+ return;
+ }
+
+ return value ? "true" : "false";
+}
diff --git a/frontend/discourse/app/instance-initializers/relative-ages.js b/frontend/discourse/app/instance-initializers/relative-ages.js
index 33b823aa0a8..685de02d995 100644
--- a/frontend/discourse/app/instance-initializers/relative-ages.js
+++ b/frontend/discourse/app/instance-initializers/relative-ages.js
@@ -1,10 +1,14 @@
import { updateRelativeAge } from "discourse/lib/formatter";
+import { getOwnerWithFallback } from "discourse/lib/get-owner";
// Updates the relative ages of dates on the screen.
export default {
initialize() {
this._interval = setInterval(function () {
updateRelativeAge(document.querySelectorAll(".relative-date"));
+ getOwnerWithFallback(this).lookup(
+ "service:a11y"
+ ).autoUpdatingRelativeDateRef = new Date();
}, 60 * 1000);
},
diff --git a/frontend/discourse/app/lib/dom-utils.js b/frontend/discourse/app/lib/dom-utils.js
index 20e83bf6ffb..2b30f09ae21 100644
--- a/frontend/discourse/app/lib/dom-utils.js
+++ b/frontend/discourse/app/lib/dom-utils.js
@@ -1,3 +1,84 @@
+/**
+ * Forces focus on a DOM element by making it focusable if it isn't already.
+ * This function temporarily adds a tabindex attribute if necessary and removes it
+ * when the element loses focus.
+ *
+ * @param {HTMLElement} element - The DOM element to force focus on
+ * @throws {TypeError} If element is not a valid DOM element
+ * @example
+ * // Make a div focusable and focus it
+ * const div = document.querySelector('#myDiv');
+ * forceFocus(div);
+ *
+ * @example
+ * // Focus an element that's already focusable (like an input)
+ * const input = document.querySelector('input');
+ * forceFocus(input);
+ */
+export function forceFocus(element) {
+ // Validate input
+ if (!element || !(element instanceof Element)) {
+ throw new TypeError("forceFocus requires a valid DOM element");
+ }
+
+ // Check if element is naturally focusable or has tabindex
+ const isNaturallyFocusable = isElementNaturallyFocusable(element);
+ const hasTabindex = element.getAttribute("tabindex") !== null;
+ const isFocusable = isNaturallyFocusable || hasTabindex;
+
+ if (!isFocusable) {
+ // force the attribute to be -1 so that the element is focusable
+ element.setAttribute("tabindex", "-1");
+ }
+
+ element.focus();
+
+ if (!isFocusable) {
+ element.addEventListener(
+ "blur",
+ () => {
+ // Only remove if we added it and it hasn't been changed
+ if (element.getAttribute("tabindex") === "-1") {
+ element.removeAttribute("tabindex");
+ }
+ },
+ {
+ once: true,
+ passive: true,
+ capture: true,
+ }
+ );
+ }
+}
+
+/**
+ * Checks if an element is naturally focusable without tabindex
+ * @param {Element} element - The element to check
+ * @returns {boolean} True if element is naturally focusable
+ */
+function isElementNaturallyFocusable(element) {
+ const tagName = element.tagName.toLowerCase();
+
+ // Check for naturally focusable elements
+ if (["input", "textarea", "select", "button"].includes(tagName)) {
+ return !element.disabled;
+ }
+
+ if (tagName === "a" || tagName === "area") {
+ return element.hasAttribute("href");
+ }
+
+ if (["iframe", "object", "embed"].includes(tagName)) {
+ return true;
+ }
+
+ if (element.hasAttribute("contenteditable")) {
+ return element.getAttribute("contenteditable") !== "false";
+ }
+
+ return false;
+}
+
function offset(element) {
// note that getBoundingClientRect forces a reflow.
// When used in critical performance conditions
diff --git a/frontend/discourse/app/models/post.js b/frontend/discourse/app/models/post.js
index 566bc5bc8ea..1ab1a1c9262 100644
--- a/frontend/discourse/app/models/post.js
+++ b/frontend/discourse/app/models/post.js
@@ -812,4 +812,12 @@ export default class Post extends RestModel {
};
});
}
+
+ get displayDate() {
+ if (this.wiki && this.last_wiki_edit) {
+ return this.last_wiki_edit;
+ } else {
+ return this.created_at;
+ }
+ }
}
diff --git a/frontend/discourse/app/routes/wizard.js b/frontend/discourse/app/routes/wizard.js
index 369d462c3e5..4134a80bece 100644
--- a/frontend/discourse/app/routes/wizard.js
+++ b/frontend/discourse/app/routes/wizard.js
@@ -1,7 +1,10 @@
import Route from "@ember/routing/route";
+import { service } from "@ember/service";
import Wizard from "discourse/static/wizard/models/wizard";
export default class WizardRoute extends Route {
+ @service a11y;
+
model() {
return Wizard.load();
}
@@ -14,8 +17,9 @@ export default class WizardRoute extends Route {
this.controllerFor("application").setProperties({
showTop: false,
showSiteHeader: false,
- showSkipToContent: false,
});
+
+ this.a11y.showSkipLinks = false;
}
deactivate() {
@@ -26,7 +30,8 @@ export default class WizardRoute extends Route {
this.controllerFor("application").setProperties({
showTop: true,
showSiteHeader: true,
- showSkipToContent: true,
});
+
+ this.a11y.showSkipLinks = true;
}
}
diff --git a/frontend/discourse/app/services/a11y.js b/frontend/discourse/app/services/a11y.js
new file mode 100644
index 00000000000..4b20b56be72
--- /dev/null
+++ b/frontend/discourse/app/services/a11y.js
@@ -0,0 +1,208 @@
+import { tracked } from "@glimmer/tracking";
+import { cancel } from "@ember/runloop";
+import Service from "@ember/service";
+import { TrackedMap } from "@ember-compat/tracked-built-ins";
+import { isRailsTesting, isTesting } from "discourse/lib/environment";
+import discourseLater from "discourse/lib/later";
+
+let clearAnnouncements = true;
+
+/**
+ * Reset announcements auto-clear functionality by enabling it.
+ * When enabled, announcements will automatically clear after their configured delay.
+ *
+ * This function only works in test environments (Qunit and Rails).
+ * Used to restore default behavior where announcements auto-clear.
+ *
+ * USE ONLY FOR TESTING PURPOSES
+
+ * @returns {void}
+ */
+export function enableClearA11yAnnouncementsInTests() {
+ if (isTesting() || isRailsTesting()) {
+ clearAnnouncements = true;
+ }
+}
+
+/**
+ * Disable announcements auto-clear functionality.
+ * When disabled, announcements will remain visible until manually cleared.
+ *
+ * This function only works in test environments (Qunit and Rails).
+ * Useful for testing that announcements persist for expected duration.
+ *
+ * USE ONLY FOR TESTING PURPOSES
+ *
+ * @returns {void}
+ */
+export function disableClearA11yAnnouncementsInTests() {
+ if (isTesting() || isRailsTesting()) {
+ clearAnnouncements = false;
+ }
+}
+
+/**
+ * @class A11yService
+ *
+ * Accessibility service that handles screen reader announcements and skip links.
+ *
+ * Key features:
+ * - Makes screen reader announcements using ARIA live regions with polite/assertive modes
+ * - Manages skip links for keyboard navigation
+ * - Uses tracked state for reactive announcements
+ * - Automatically cleans up announcements after configurable delay
+ * - Provides both polite and assertive announcement levels
+ *
+ * @example
+ * // Polite announcement that clears after 2 seconds
+ * a11y.announce("Page loaded", "polite", 2000);
+ *
+ * // Assertive immediate announcement
+ * a11y.announce("Error occurred", "assertive", 1000);
+ */
+export default class A11y extends Service {
+ /**
+ * Flag to control visibility of skip links for keyboard navigation
+ * @type {boolean}
+ */
+ @tracked showSkipLinks = true;
+
+ /**
+ * Reference date used to determine if relative dates need to be updated.
+ * When this value changes, all relative dates consuming this value will be re-rendered.
+ * @type {Date}
+ */
+ @tracked autoUpdatingRelativeDateRef = new Date();
+
+ #state = new (class {
+ /**
+ * Map of screen reader announcements by type
+ * @type {TrackedMap<string, string>}
+ */
+ #messages = new TrackedMap();
+
+ /**
+ * Map of announcement clear timers by type
+ * @type {TrackedMap<string, EmberRunTimer>}
+ */
+ #timers = new TrackedMap();
+
+ /**
+ * Sets an announcement message with auto-clearing
+ * @param {'polite'|'assertive'} type - Type of announcement
+ * @param {string} message - Message to announce
+ * @param {number} clearDelay - Delay in ms before clearing
+ */
+ setMessage(type, message, clearDelay) {
+ if (message === "") {
+ this.#messages.delete(type);
+ this.#scheduleClear(type, 0);
+ return;
+ }
+
+ this.#messages.set(type, message);
+
+ if (clearAnnouncements) {
+ this.#scheduleClear(type, clearDelay);
+ }
+ }
+
+ /**
+ * Gets the current announcement message of specified type
+ * @param {'polite'|'assertive'} type - Type of announcement to get
+ * @returns {string|undefined} The announcement message if exists
+ */
+ getMessage(type) {
+ return this.#messages.get(type);
+ }
+
+ /**
+ * Clears all announcement clear timers
+ */
+ clearTimers() {
+ this.#timers.forEach((timer) => {
+ if (timer) {
+ cancel(timer);
+ }
+ });
+ this.#timers.clear();
+ }
+
+ /**
+ * Schedule clearing of an announcement after delay
+ * @param {'polite'|'assertive'} type - Type of announcement to clear
+ * @param {number} clearDelay - Delay in ms before clearing
+ */
+ #scheduleClear(type, clearDelay) {
+ const pendingTimer = this.#timers.get(type);
+ if (pendingTimer) {
+ cancel(pendingTimer);
+ this.#timers.delete(type);
+ }
+
+ if (clearDelay > 0) {
+ this.#timers.set(
+ type,
+ discourseLater(() => {
+ this.#messages.delete(type);
+ this.#timers.delete(type);
+ }, clearDelay)
+ );
+ }
+ }
+ })();
+
+ /**
+ * Cleanup timers when service is destroyed
+ */
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.#state.clearTimers();
+ }
+
+ /**
+ * Gets the current assertive announcement message
+ * @type {string|undefined}
+ */
+ get assertiveMessage() {
+ return this.#state.getMessage("assertive");
+ }
+
+ /**
+ * Gets the current polite announcement message
+ * @type {string|undefined}
+ */
+ get politeMessage() {
+ return this.#state.getMessage("polite");
+ }
+
+ /**
+ * Announce a message to screen readers
+ * @param {string} message - The message to announce
+ * @param {'polite'|'assertive'} type - The announcement type
+ * @param {number} clearDelay - Delay in ms before clearing the message
+ * @throws {TypeError} If message is not a string
+ * @throws {Error} If clearDelay is not positive or type is invalid
+ */
+ announce(message, type = "polite", clearDelay = 2000) {
+ if (typeof message !== "string") {
+ throw new TypeError("The announced message must be a string");
+ }
+
+ clearDelay = Math.max(0, Number(clearDelay) || 0);
+ if (clearDelay <= 0) {
+ throw new Error("The clearDelay must be a positive number");
+ }
+
+ switch (type) {
+ case "assertive":
+ case "polite":
+ this.#state.setMessage(type, message.trim(), clearDelay);
+ break;
+ default:
+ throw new Error(
+ `Invalid announcement type: ${type}. Expected 'polite' or 'assertive'.`
+ );
+ }
+ }
+}
diff --git a/frontend/discourse/app/templates/application.gjs b/frontend/discourse/app/templates/application.gjs
index 4c50678dcfa..753d02ebc6a 100644
--- a/frontend/discourse/app/templates/application.gjs
+++ b/frontend/discourse/app/templates/application.gjs
@@ -1,6 +1,8 @@
import didInsert from "@ember/render-modifiers/modifiers/did-insert";
import DialogHolder from "dialog-holder/components/dialog-holder";
import { and, eq } from "truth-helpers";
+import A11yLiveRegions from "discourse/components/a11y/live-regions";
+import A11ySkipLinks from "discourse/components/a11y/skip-links";
import CardContainer from "discourse/components/card-container";
import ComposerContainer from "discourse/components/composer-container";
import CustomHtml from "discourse/components/custom-html";
@@ -26,7 +28,6 @@ import TopicEntrance from "discourse/components/topic-entrance";
import WelcomeBanner from "discourse/components/welcome-banner";
import lazyHash from "discourse/helpers/lazy-hash";
import routeAction from "discourse/helpers/route-action";
-import { i18n } from "discourse-i18n";
import DMenus from "float-kit/components/d-menus";
import DToasts from "float-kit/components/d-toasts";
import DTooltips from "float-kit/components/d-tooltips";
@@ -36,11 +37,8 @@ export default <template>
<DVirtualHeight />
<DiscourseRoot {{didInsert @controller.trackDiscoursePainted}}>
- {{#if @controller.showSkipToContent}}
- <a href="#main-container" id="skip-link">{{i18n
- "skip_to_main_content"
- }}</a>
- {{/if}}
+ <A11ySkipLinks.Container />
+
<DDocument />
<PageLoadingSlider />
<PluginOutlet
@@ -175,4 +173,6 @@ export default <template>
<DMenus />
<DTooltips />
<DToasts />
+
+ <A11yLiveRegions />
</template>
diff --git a/frontend/discourse/app/templates/topic.gjs b/frontend/discourse/app/templates/topic.gjs
index 282715405b9..71f2bbc09af 100644
--- a/frontend/discourse/app/templates/topic.gjs
+++ b/frontend/discourse/app/templates/topic.gjs
@@ -32,6 +32,7 @@ import TopicLocalizedContentToggle from "discourse/components/topic-localized-co
import TopicMap from "discourse/components/topic-map/index";
import TopicNavigation from "discourse/components/topic-navigation";
import TopicProgress from "discourse/components/topic-progress";
+import TopicSkipLinks from "discourse/components/topic-skip-links";
import TopicStatus from "discourse/components/topic-status";
import TopicTimeline from "discourse/components/topic-timeline";
import TopicTimerInfo from "discourse/components/topic-timer-info";
@@ -46,6 +47,7 @@ import autoFocus from "discourse/modifiers/auto-focus";
import { i18n } from "discourse-i18n";
import CategoryChooser from "select-kit/components/category-chooser";
import MiniTagChooser from "select-kit/components/mini-tag-chooser";
+import booleanString from "../helpers/boolean-string";
export default <template>
{{#let @controller.model.postStream as |postStream|}}
@@ -60,6 +62,10 @@ export default <template>
@topic={{@controller.model}}
@hasScrolled={{@controller.hasScrolled}}
>
+ <TopicSkipLinks
+ @postStream={{@controller.model.postStream}}
+ @topic={{@controller.model}}
+ />
{{#if @controller.model}}
<AddCategoryTagClasses
@category={{@controller.model.category}}
@@ -201,7 +207,12 @@ export default <template>
</div>
{{else}}
- <h1 data-topic-id={{@controller.model.id}}>
+ <h1
+ data-topic-id={{@controller.model.id}}
+ {{! Prevent duplicating the topic title heading on screen readers when the header is displaying the title
+ in the header }}
+ aria-hidden={{booleanString @controller.titleIsVisibleOnHeader}}
+ >
{{#unless @controller.model.is_warning}}
{{#if @controller.canSendPms}}
<PrivateMessageGlyph
diff --git a/frontend/discourse/tests/acceptance/topic-timeline-test.js b/frontend/discourse/tests/acceptance/topic-timeline-test.js
index afb3116a320..0d25e8abde0 100644
--- a/frontend/discourse/tests/acceptance/topic-timeline-test.js
+++ b/frontend/discourse/tests/acceptance/topic-timeline-test.js
@@ -356,12 +356,10 @@ acceptance("Glimmer Topic Timeline", function (needs) {
test("selecting now-date navigates you to the last post", async function (assert) {
await visit("/t/internationalization-localization/280/1");
+
await click(".timeline-date-wrapper .now-date");
- assert.strictEqual(
- currentURL(),
- "/t/internationalization-localization/280/11",
- "navigates to the latest post"
- );
+
+ assert.dom("[data-post-number='11']").exists();
});
test("clicking the timeline padding updates the position", async function (assert) {
diff --git a/frontend/discourse/tests/helpers/qunit-helpers.js b/frontend/discourse/tests/helpers/qunit-helpers.js
index 75b95b8c7f0..ca979b823b5 100644
--- a/frontend/discourse/tests/helpers/qunit-helpers.js
+++ b/frontend/discourse/tests/helpers/qunit-helpers.js
@@ -93,6 +93,7 @@ import { resetLastEditNotificationClick } from "discourse/models/post-stream";
import Site from "discourse/models/site";
import User from "discourse/models/user";
import { clearResolverOptions } from "discourse/resolver";
+import { enableClearA11yAnnouncementsInTests } from "discourse/services/a11y";
import sessionFixtures from "discourse/tests/fixtures/session-fixtures";
import siteFixtures from "discourse/tests/fixtures/site-fixtures";
import {
@@ -271,6 +272,7 @@ export function testCleanup(container, app) {
resetGroupPostSmallActionCodes();
resetPostSmallActionClassesCallbacks();
resetPostClassesCallback();
+ enableClearA11yAnnouncementsInTests();
}
function cleanupCssGeneratorTags() {
diff --git a/frontend/discourse/tests/integration/components/a11y/live-regions-test.gjs b/frontend/discourse/tests/integration/components/a11y/live-regions-test.gjs
new file mode 100644
index 00000000000..850a846c55e
--- /dev/null
+++ b/frontend/discourse/tests/integration/components/a11y/live-regions-test.gjs
@@ -0,0 +1,63 @@
+import { getOwner } from "@ember/owner";
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import A11yLiveRegions from "discourse/components/a11y/live-regions";
+import { disableClearA11yAnnouncementsInTests } from "discourse/services/a11y";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+
+module("Integration | Component | a11y/live-regions", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("renders polite and assertive live regions", async function (assert) {
+ await render(<template><A11yLiveRegions /></template>);
+
+ assert
+ .dom("#a11y-announcements-polite")
+ .exists("polite announcements element exists");
+ assert
+ .dom("#a11y-announcements-assertive")
+ .exists("assertive announcements element exists");
+
+ assert.dom("#a11y-announcements-polite").hasAttribute("role", "status");
+ assert
+ .dom("#a11y-announcements-polite")
+ .hasAttribute("aria-live", "polite");
+ assert
+ .dom("#a11y-announcements-polite")
+ .hasAttribute("aria-atomic", "true");
+
+ assert.dom("#a11y-announcements-assertive").hasAttribute("role", "alert");
+ assert
+ .dom("#a11y-announcements-assertive")
+ .hasAttribute("aria-live", "assertive");
+ assert
+ .dom("#a11y-announcements-assertive")
+ .hasAttribute("aria-atomic", "true");
+ });
+
+ test("displays assertive messages", async function (assert) {
+ disableClearA11yAnnouncementsInTests();
+
+ const a11y = getOwner(this).lookup("service:a11y");
+ a11y.announce("Test assertive message", "assertive", 500);
+
+ await render(<template><A11yLiveRegions /></template>);
+
+ assert
+ .dom("#a11y-announcements-assertive")
+ .hasText("Test assertive message", "displays assertive message");
+ });
+
+ test("displays polite messages", async function (assert) {
+ disableClearA11yAnnouncementsInTests();
+
+ const a11y = getOwner(this).lookup("service:a11y");
+ a11y.announce("Test polite message", "polite", 500);
+
+ await render(<template><A11yLiveRegions /></template>);
+
+ assert
+ .dom("#a11y-announcements-polite")
+ .hasText("Test polite message", "displays polite message");
+ });
+});
diff --git a/frontend/discourse/tests/integration/components/post/post-test.gjs b/frontend/discourse/tests/integration/components/post/post-test.gjs
index 4edf1967890..f4b9ca536f1 100644
--- a/frontend/discourse/tests/integration/components/post/post-test.gjs
+++ b/frontend/discourse/tests/integration/components/post/post-test.gjs
@@ -809,4 +809,74 @@ module("Integration | Component | Post", function (hooks) {
assert.dom(".show-more-actions").doesNotExist();
});
+
+ test("a11y heading is rendered when post is cloaked", async function (assert) {
+ // TODO (glimmer-post-stream) remove the outer div when the post-stream widget is converted to a Glimmer component
+ await render(
+ <template>
+ <div class="topic-post glimmer-post-stream">
+ <Post @post={{this.post}} @cloaked={{true}} />
+ </div>
+ <DMenus />
+ </template>
+ );
+
+ assert
+ .dom("h2.sr-only")
+ .exists("accessibility heading exists when the post is cloaked");
+ assert
+ .dom("h2.sr-only")
+ .hasAttribute(
+ "id",
+ `post-heading-${this.post.post_number}`,
+ "heading has correct id based on post number"
+ );
+ });
+
+ test("article is properly labeled by a11y heading", async function (assert) {
+ await renderComponent(this.post);
+
+ const expectedAriaLabelledBy = `post-heading-${this.post.post_number}`;
+
+ assert
+ .dom("article.onscreen-post")
+ .hasAttribute(
+ "aria-labelledby",
+ expectedAriaLabelledBy,
+ "article is labeled by the accessibility heading"
+ );
+ });
+
+ test("a11y heading id is unique for different post numbers", async function (assert) {
+ const post1 = this.store.createRecord("post", {
+ id: 100,
+ post_number: 1,
+ topic: this.post.topic,
+ username: "user1",
+ created_at: new Date(),
+ });
+
+ const post2 = this.store.createRecord("post", {
+ id: 200,
+ post_number: 2,
+ topic: this.post.topic,
+ username: "user2",
+ created_at: new Date(),
+ });
+
+ // Render both posts
+ // TODO (glimmer-post-stream) remove the outer div when the post-stream widget is converted to a Glimmer component
+ await render(
+ <template>
+ <div class="topic-post glimmer-post-stream">
+ <Post @post={{post1}} />
+ <Post @post={{post2}} />
+ </div>
+ <DMenus />
+ </template>
+ );
+
+ assert.dom("#post-heading-1").exists("first post heading has correct id");
+ assert.dom("#post-heading-2").exists("second post heading has correct id");
+ });
});
diff --git a/frontend/discourse/tests/integration/components/post/small-action-test.gjs b/frontend/discourse/tests/integration/components/post/small-action-test.gjs
index a06bf83fef5..b2222781f94 100644
--- a/frontend/discourse/tests/integration/components/post/small-action-test.gjs
+++ b/frontend/discourse/tests/integration/components/post/small-action-test.gjs
@@ -229,4 +229,77 @@ module("Integration | Component | Post | PostSmallAction", function (hooks) {
.dom(".small-action-desc .small-action-recover")
.exists("adds the recover small action button");
});
+
+ test("a11y heading is rendered even when small action is cloaked", async function (assert) {
+ await render(
+ <template>
+ <PostSmallAction @post={{this.post}} @cloaked={{true}} />
+ </template>
+ );
+
+ assert
+ .dom("h2.sr-only")
+ .exists("accessibility heading exists even when cloaked");
+ assert
+ .dom("h2.sr-only")
+ .hasAttribute(
+ "id",
+ `post-heading-${this.post.post_number}`,
+ "heading has correct id when cloaked"
+ );
+
+ // The main content should not be rendered when cloaked
+ assert
+ .dom("article .small-action-desc")
+ .doesNotExist("main content is not rendered when cloaked");
+ assert
+ .dom("article .topic-avatar")
+ .doesNotExist("avatar icon is not rendered when cloaked");
+ });
+
+ test("article is properly labeled by a11y heading", async function (assert) {
+ await renderComponent(this.post);
+
+ const expectedAriaLabelledBy = `post-heading-${this.post.post_number}`;
+
+ assert
+ .dom("article.small-action")
+ .hasAttribute(
+ "aria-labelledby",
+ expectedAriaLabelledBy,
+ "article is labeled by the accessibility heading"
+ );
+ });
+
+ test("a11y heading id is unique for different post numbers", async function (assert) {
+ const store = getOwner(this).lookup("service:store");
+ const topic = store.createRecord("topic", { id: 1 });
+
+ const post1 = store.createRecord("post", {
+ id: 100,
+ post_number: 1,
+ topic,
+ action_code: "open_topic",
+ created_at: "2025-09-23T16:10:28.695Z",
+ });
+
+ const post2 = store.createRecord("post", {
+ id: 200,
+ post_number: 2,
+ topic,
+ action_code: "closed.enabled",
+ created_at: "2025-09-23T16:10:28.695Z",
+ });
+
+ // Render both posts
+ await render(
+ <template>
+ <PostSmallAction @post={{post1}} />
+ <PostSmallAction @post={{post2}} />
+ </template>
+ );
+
+ assert.dom("#post-heading-1").exists("first post heading has correct id");
+ assert.dom("#post-heading-2").exists("second post heading has correct id");
+ });
});