A platform for community discussion. Free, open, simple.
A11Y: live announcements and optional sounds for chat messages (#41213)
Kris0284e0a2a5e5
diff --git a/app/models/user_option.rb b/app/models/user_option.rbindex e8e2cff0787..457bdc96871 100644--- a/app/models/user_option.rb+++ b/app/models/user_option.rb@@ -269,9 +269,11 @@ end# auto_track_topics_after_msecs :integer# automatically_unpin_topics :boolean default(TRUE), not null# bookmark_auto_delete_preference :integer default(3), not null+# chat_announce_new_messages :boolean default(TRUE), not null# chat_email_frequency :integer default("when_away"), not null# chat_enabled :boolean default(TRUE), not null# chat_header_indicator_preference :integer default("all_new"), not null+# chat_new_message_sound :boolean default(FALSE), not null# chat_quick_reaction_type :integer default("frequent"), not null# chat_quick_reactions_custom :string# chat_send_shortcut :integer default("enter"), not nulldiff --git a/db/structure.sql b/db/structure.sqlindex 7f5af1ee526..e58d74df8cb 100644--- a/db/structure.sql+++ b/db/structure.sql@@ -11437,7 +11437,9 @@ CREATE TABLE public.user_options (discourse_rewind_enabled boolean DEFAULT true NOT NULL,notify_on_solved boolean DEFAULT true NOT NULL,show_original_content boolean DEFAULT false NOT NULL,- enable_upcoming_change_available_notifications boolean DEFAULT true NOT NULL+ enable_upcoming_change_available_notifications boolean DEFAULT true NOT NULL,+ chat_announce_new_messages boolean DEFAULT true NOT NULL,+ chat_new_message_sound boolean DEFAULT false NOT NULL);@@ -22419,6 +22421,7 @@ INSERT INTO "schema_migrations" (version) VALUES('20260629022603'),('20260626055145'),('20260624140945'),+('20260623201925'),('20260623090824'),('20260623052745'),('20260622201006'),diff --git a/migrations/tooling/config/schema/intermediate_db/ignored.rb b/migrations/tooling/config/schema/intermediate_db/ignored.rbindex d432d25c1bc..f8ae0657803 100644--- a/migrations/tooling/config/schema/intermediate_db/ignored.rb+++ b/migrations/tooling/config/schema/intermediate_db/ignored.rb@@ -168,6 +168,7 @@ Migrations::Tooling::Schema.ignored do:bookmarks,:browser_pageview_event_scores,:browser_pageview_events,+ :browser_pageview_session_engagements,:custom_emojis,:developers,:directory_columns,diff --git a/migrations/tooling/config/schema/plugin_manifest.yml b/migrations/tooling/config/schema/plugin_manifest.ymlindex 944c807ffa2..95faf61c1d8 100644--- a/migrations/tooling/config/schema/plugin_manifest.yml+++ b/migrations/tooling/config/schema/plugin_manifest.yml@@ -34,9 +34,11 @@ plugins:- user_chat_thread_membershipscolumns:user_options:+ - chat_announce_new_messages- chat_email_frequency- chat_enabled- chat_header_indicator_preference+ - chat_new_message_sound- chat_quick_reaction_type- chat_quick_reactions_custom- chat_send_shortcut@@ -216,10 +218,10 @@ plugins:columns: {}plugin_checksums:automation: e69972690991bc04d92b2d161aac8921- chat: eed419ab29ae9cb0a73a32c0e7be9d6c+ chat: 93de6fd994b8fbd1a3921c3deacd1d7adiscourse-adplugin: 9e52419decf1099c5bc301a90e6cc91adiscourse-affiliate: '08c6e1a851441a082e9be9ddddc63910'- discourse-ai: b003fddae4787fa026ad65139e982da1+ discourse-ai: 3063169bf8303c6c3f944391e3e42142discourse-assign: 7a7a36e8ac0214e8a6aca1a1ed9899aadiscourse-cakeday: a5bb91366c8dc8d267088eb0c2679187discourse-calendar: 07aa9951f5fde7daf03be9edfbda4decdiff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjsindex 34165836129..64a0c0e43a2 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs@@ -49,6 +49,7 @@ export default class ChatChannel extends Component {@service capabilities;@service chatApi;@service chatChannelsManager;+ @service chatNewMessageAnnouncer;@service chatDraftsManager;@service chatStateManager;@service chatChannelScrollPositions;@@ -188,6 +189,13 @@ export default class ChatChannel extends Component {onNewMessage(message) {const isOwnMessage = message.user.id === this.currentUser.id;+ if (!isOwnMessage) {+ this.chatNewMessageAnnouncer.notify(message, {+ visible: this.paneState.isDocumentVisible,+ active: this.paneState.isActiveReader,+ });+ }+this.paneState.handleIncomingMessage({scroller: this.scroller,shouldAutoScroll: this.paneState.shouldAutoScrollIncomingMessage({diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-thread.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-thread.gjsindex 32e70f85941..2ffa2480ac6 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-thread.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-thread.gjs@@ -46,6 +46,7 @@ export default class ChatThread extends Component {@service capabilities;@service chatApi;@service chatDraftsManager;+ @service chatNewMessageAnnouncer;@service chatThreadComposer;@service chatThreadPane;@service dialog;@@ -360,6 +361,13 @@ export default class ChatThread extends Component {onNewMessage(message) {const isOwnMessage = message.user.id === this.currentUser.id;+ if (!isOwnMessage) {+ this.chatNewMessageAnnouncer.notify(message, {+ visible: this.paneState.isDocumentVisible,+ active: this.paneState.isActiveReader,+ });+ }+this.paneState.handleIncomingMessage({scroller: this.scroller,shouldAutoScroll: this.paneState.shouldAutoScrollIncomingMessage({diff --git a/plugins/chat/assets/javascripts/discourse/initializers/chat-user-options.js b/plugins/chat/assets/javascripts/discourse/initializers/chat-user-options.jsindex dfcc2efa623..8e7943c7949 100644--- a/plugins/chat/assets/javascripts/discourse/initializers/chat-user-options.js+++ b/plugins/chat/assets/javascripts/discourse/initializers/chat-user-options.js@@ -9,6 +9,8 @@ export default {if (chat_enabled) {// Chat settings+ api.addSaveableUserOption("chat_announce_new_messages");+ api.addSaveableUserOption("chat_new_message_sound");api.addSaveableUserOption("chat_enabled");api.addSaveableUserOption("chat_header_indicator_preference");api.addSaveableUserOption("chat_quick_reaction_type");diff --git a/plugins/chat/assets/javascripts/discourse/lib/chat-constants.js b/plugins/chat/assets/javascripts/discourse/lib/chat-constants.jsindex 0630e5826f1..e2af398161b 100644--- a/plugins/chat/assets/javascripts/discourse/lib/chat-constants.js+++ b/plugins/chat/assets/javascripts/discourse/lib/chat-constants.js@@ -18,6 +18,8 @@ export const INDICATOR_PREFERENCES = {};export const CHAT_ATTRS = ["chat_enabled",+ "chat_announce_new_messages",+ "chat_new_message_sound","only_chat_push_notifications","ignore_channel_wide_mention","show_thread_title_prompts",diff --git a/plugins/chat/assets/javascripts/discourse/lib/chat-message-announcement.js b/plugins/chat/assets/javascripts/discourse/lib/chat-message-announcement.jsnew file mode 100644index 00000000000..68479572def--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/lib/chat-message-announcement.js@@ -0,0 +1,44 @@+import { isImage } from "discourse/lib/uploads";+import { i18n } from "discourse-i18n";++// strip tags AND decode entities, so the screen reader doesn't read literal "&" / "…"+function bodyText(message) {+ const text = message.excerpt || message.message || "";+ const parsed = new DOMParser().parseFromString(text, "text/html");+ return (parsed.body.textContent || "").replace(/\s+/g, " ").trim();+}++export function messageAnnouncementText(message) {+ const username = message.user?.username;+ const uploads = message.uploads ?? [];++ if (uploads.length > 0) {+ const count = uploads.length;+ const isImages = uploads.every((upload) =>+ isImage(upload.original_filename)+ );++ const caption = (message.message || "").trim() ? bodyText(message) : "";++ if (caption) {+ return i18n(+ isImages+ ? "chat.screen_reader.new_message_with_image"+ : "chat.screen_reader.new_message_with_attachment",+ { username, message: caption, count }+ );+ }++ return i18n(+ isImages+ ? "chat.screen_reader.new_image"+ : "chat.screen_reader.new_attachment",+ { username, count }+ );+ }++ return i18n("chat.screen_reader.new_message", {+ username,+ message: bodyText(message),+ });+}diff --git a/plugins/chat/assets/javascripts/discourse/services/chat-audio-manager.js b/plugins/chat/assets/javascripts/discourse/services/chat-audio-manager.jsindex 7b29b2875a8..355de136487 100644--- a/plugins/chat/assets/javascripts/discourse/services/chat-audio-manager.js+++ b/plugins/chat/assets/javascripts/discourse/services/chat-audio-manager.js@@ -9,7 +9,7 @@ export const CHAT_SOUNDS = {ethereal: {},};-const DEFAULT_SOUND_NAME = "classic";+export const DEFAULT_SOUND_NAME = "classic";const THROTTLE_TIME = 3000; // 3 secondsconst MIN_GAIN = 0.001;diff --git a/plugins/chat/assets/javascripts/discourse/services/chat-new-message-announcer.js b/plugins/chat/assets/javascripts/discourse/services/chat-new-message-announcer.jsnew file mode 100644index 00000000000..e746a167ea2--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/services/chat-new-message-announcer.js@@ -0,0 +1,95 @@+import { cancel } from "@ember/runloop";+import Service, { service } from "@ember/service";+import discourseLater from "discourse/lib/later";+import { i18n } from "discourse-i18n";+import { messageAnnouncementText } from "discourse/plugins/chat/discourse/lib/chat-message-announcement";+import { DEFAULT_SOUND_NAME } from "discourse/plugins/chat/discourse/services/chat-audio-manager";++// a burst is summarized rather than overwriting the shared live region message by message+const ANNOUNCEMENT_INTERVAL_MS = 1000;++// minimum gap between new-message sounds to avoid flooding+const NEW_MESSAGE_SOUND_INTERVAL_MS = 2000;++export default class ChatNewMessageAnnouncer extends Service {+ @service a11y;+ @service chatAudioManager;+ @service currentUser;++ #pendingAnnouncements = [];+ #announcementTimer = null;+ #lastMessageSoundAt = 0;++ willDestroy() {+ super.willDestroy(...arguments);+ cancel(this.#announcementTimer);+ this.#pendingAnnouncements = [];+ }++ notify(message, { visible, active } = {}) {+ if (+ message.hidden ||+ this.currentUser?.ignored_users?.includes(message.user?.username)+ ) {+ return;+ }++ this.#maybeAnnounce(message, visible);+ this.#maybePlaySound(active);+ }++ #maybeAnnounce(message, visible) {+ if (+ !visible ||+ !this.currentUser?.user_option?.chat_announce_new_messages+ ) {+ return;+ }++ this.#pendingAnnouncements.push(message);+ this.#announcementTimer ??= discourseLater(+ this,+ this.#flushAnnouncements,+ ANNOUNCEMENT_INTERVAL_MS+ );+ }++ #flushAnnouncements() {+ this.#announcementTimer = null;++ const messages = this.#pendingAnnouncements;+ this.#pendingAnnouncements = [];++ if (messages.length === 0) {+ return;+ }++ const announcement =+ messages.length === 1+ ? messageAnnouncementText(messages[0])+ : i18n("chat.screen_reader.new_messages", { count: messages.length });++ this.a11y.announce(announcement, "polite");+ }++ #maybePlaySound(active) {+ if (+ !active ||+ !this.currentUser?.user_option?.chat_new_message_sound ||+ this.currentUser.isInDoNotDisturb()+ ) {+ return;+ }++ const now = Date.now();+ if (now - this.#lastMessageSoundAt < NEW_MESSAGE_SOUND_INTERVAL_MS) {+ return;+ }+ this.#lastMessageSoundAt = now;++ // fall back to the default when no sound is selected.+ const sound = this.currentUser.chat_sound || DEFAULT_SOUND_NAME;+ // throttle false so this doesn't consume the shared chat-audio throttle+ this.chatAudioManager.play(sound, { throttle: false });+ }+}diff --git a/plugins/chat/assets/javascripts/discourse/templates/preferences/chat.gjs b/plugins/chat/assets/javascripts/discourse/templates/preferences/chat.gjsindex f7b159135fa..2a02efd9a79 100644--- a/plugins/chat/assets/javascripts/discourse/templates/preferences/chat.gjs+++ b/plugins/chat/assets/javascripts/discourse/templates/preferences/chat.gjs@@ -121,6 +121,8 @@ export default class Chat extends Component {chat_quick_reactions_custom: emojis,only_chat_push_notifications: userOption.only_chat_push_notifications,ignore_channel_wide_mention: userOption.ignore_channel_wide_mention,+ chat_announce_new_messages: userOption.chat_announce_new_messages,+ chat_new_message_sound: userOption.chat_new_message_sound,chat_sound: normalizeChatSoundName(userOption.chat_sound),chat_header_indicator_preference:userOption.chat_header_indicator_preference,@@ -308,6 +310,26 @@ export default class Chat extends Component {</field.Control></form.Field></form.Section>+ <form.Section @title={{i18n "chat.accessibility_title"}}>+ <form.Field+ @title={{i18n "chat.announce_new_messages.title"}}+ @name="chat_announce_new_messages"+ @format="large"+ @type="checkbox"+ as |field|+ >+ <field.Control @value={{field.value}} />+ </form.Field>+ <form.Field+ @title={{i18n "chat.new_message_sound.title"}}+ @name="chat_new_message_sound"+ @format="large"+ @type="checkbox"+ as |field|+ >+ <field.Control @value={{field.value}} />+ </form.Field>+ </form.Section><div class="save-controls"><form.Submit />{{#if this.saved}}diff --git a/plugins/chat/config/locales/client.en.yml b/plugins/chat/config/locales/client.en.ymlindex 51275bf023c..00ccace9b9d 100644--- a/plugins/chat/config/locales/client.en.yml+++ b/plugins/chat/config/locales/client.en.yml@@ -262,6 +262,24 @@ en:composer: "Chat composer"channels_list: "Chat channels list"+ screen_reader:+ new_message: "%{username}: %{message}"+ new_messages:+ one: "%{count} new message"+ other: "%{count} new messages"+ new_image:+ one: "%{username} sent an image"+ other: "%{username} sent %{count} images"+ new_attachment:+ one: "%{username} sent an attachment"+ other: "%{username} sent %{count} attachments"+ new_message_with_image:+ one: "%{username}: %{message} (with an image)"+ other: "%{username}: %{message} (with %{count} images)"+ new_message_with_attachment:+ one: "%{username}: %{message} (with an attachment)"+ other: "%{username}: %{message} (with %{count} attachments)"+no_direct_message_channels: "You have not joined any direct messages yet!"no_direct_message_channels_cta: "Start a conversation"no_public_channels: "You have not joined any channels yet!"@@ -271,8 +289,13 @@ en:only_chat_push_notifications:title: "Only send chat push notifications"personalization_title: "Personalization"+ accessibility_title: "Accessibility"ignore_channel_wide_mention:title: "Ignore channel-wide mentions"+ announce_new_messages:+ title: "Announce new messages to screen readers"+ new_message_sound:+ title: "Play sounds for new messages while chat is in the foreground"show_thread_title_prompts:title: "Show thread title prompts"description: "Show prompts to set a title for new threads"diff --git a/plugins/chat/db/migrate/20260623201925_add_chat_announce_new_messages_to_user_options.rb b/plugins/chat/db/migrate/20260623201925_add_chat_announce_new_messages_to_user_options.rbnew file mode 100644index 00000000000..5017a952395--- /dev/null+++ b/plugins/chat/db/migrate/20260623201925_add_chat_announce_new_messages_to_user_options.rb@@ -0,0 +1,7 @@+# frozen_string_literal: true+class AddChatAnnounceNewMessagesToUserOptions < ActiveRecord::Migration[8.0]+ def change+ add_column :user_options, :chat_announce_new_messages, :boolean, default: true, null: false+ add_column :user_options, :chat_new_message_sound, :boolean, default: false, null: false+ end+enddiff --git a/plugins/chat/lib/chat/user_option_extension.rb b/plugins/chat/lib/chat/user_option_extension.rbindex 212c01b52f2..d2322f7e2e5 100644--- a/plugins/chat/lib/chat/user_option_extension.rb+++ b/plugins/chat/lib/chat/user_option_extension.rb@@ -51,6 +51,14 @@ module Chatbase.attribute :show_thread_title_prompts, :boolean, default: trueend+ if !base.method_defined?(:chat_announce_new_messages?)+ base.attribute :chat_announce_new_messages, :boolean, default: true+ end++ if !base.method_defined?(:chat_new_message_sound?)+ base.attribute :chat_new_message_sound, :boolean, default: false+ end+if !base.method_defined?(:chat_quick_reaction_type_frequent?)base.enum :chat_quick_reaction_type, { frequent: 0, custom: 1 }, prefix: trueenddiff --git a/plugins/chat/plugin.rb b/plugins/chat/plugin.rbindex ef7f06f0d0f..fb95365468d 100644--- a/plugins/chat/plugin.rb+++ b/plugins/chat/plugin.rb@@ -90,6 +90,8 @@ after_initialize doUserUpdater::OPTION_ATTR.push(:chat_sound)UserUpdater::OPTION_ATTR.push(:ignore_channel_wide_mention)UserUpdater::OPTION_ATTR.push(:show_thread_title_prompts)+ UserUpdater::OPTION_ATTR.push(:chat_announce_new_messages)+ UserUpdater::OPTION_ATTR.push(:chat_new_message_sound)UserUpdater::OPTION_ATTR.push(:chat_email_frequency)UserUpdater::OPTION_ATTR.push(:chat_header_indicator_preference)UserUpdater::OPTION_ATTR.push(:chat_separate_sidebar_mode)@@ -304,6 +306,16 @@ after_initialize doobject.show_thread_title_promptsend+ add_to_serializer(:user_option, :chat_announce_new_messages) { object.chat_announce_new_messages }++ add_to_serializer(:current_user_option, :chat_announce_new_messages) do+ object.chat_announce_new_messages+ end++ add_to_serializer(:user_option, :chat_new_message_sound) { object.chat_new_message_sound }++ add_to_serializer(:current_user_option, :chat_new_message_sound) { object.chat_new_message_sound }+add_to_serializer(:user_option, :chat_email_frequency) { object.chat_email_frequency }add_to_serializer(:user_option, :chat_header_indicator_preference) dodiff --git a/plugins/chat/spec/models/user_option_spec.rb b/plugins/chat/spec/models/user_option_spec.rbindex 8a622a3b476..8f5b9eea12f 100644--- a/plugins/chat/spec/models/user_option_spec.rb+++ b/plugins/chat/spec/models/user_option_spec.rb@@ -11,6 +11,16 @@ RSpec.describe UserOption doexpect(described_class.new.show_thread_title_prompts).to eq(true)endend+ describe "#chat_announce_new_messages" do+ it "defaults to true" do+ expect(described_class.new.chat_announce_new_messages).to eq(true)+ end+ end+ describe "#chat_new_message_sound" do+ it "defaults to false" do+ expect(described_class.new.chat_new_message_sound).to eq(false)+ end+ enddescribe "#chat_quick_reaction_type" doit "is present with frequent as default" doexpect(described_class.new.chat_quick_reaction_type).to eq("frequent")diff --git a/plugins/chat/test/javascripts/components/chat-channel-announcements-test.gjs b/plugins/chat/test/javascripts/components/chat-channel-announcements-test.gjsnew file mode 100644index 00000000000..1764c077825--- /dev/null+++ b/plugins/chat/test/javascripts/components/chat-channel-announcements-test.gjs@@ -0,0 +1,213 @@+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,+ enableClearA11yAnnouncementsInTests,+} from "discourse/services/a11y";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import { publishToMessageBus } from "discourse/tests/helpers/qunit-helpers";+import ChatChannel from "discourse/plugins/chat/discourse/components/chat-channel";+import ChatFabricators from "discourse/plugins/chat/discourse/lib/fabricators";++module(+ "Component | ChatChannel | screen reader announcements",+ function (hooks) {+ setupRenderingTest(hooks);++ const channelId = 1;++ hooks.beforeEach(function () {+ // Keep announcements in the live region so we can assert on them.+ disableClearA11yAnnouncementsInTests();++ pretender.get(`/chat/api/channels/1/messages`, () =>+ response({ messages: [], meta: { can_delete_self: true } })+ );+ pretender.get(`/chat/api/me/channels`, () =>+ response({ direct_message_channels: [], public_channels: [] })+ );++ this.currentUser = getOwner(this).lookup("service:current-user");+ this.currentUser.id = 1;+ this.currentUser.set("user_option", { chat_announce_new_messages: true });++ this.channel = new ChatFabricators(getOwner(this)).channel({+ id: channelId,+ currentUserMembership: { following: true },+ meta: { can_join_chat_channel: false },+ });+ });++ hooks.afterEach(function () {+ enableClearA11yAnnouncementsInTests();+ });++ function publishSentMessage(overrides = {}) {+ return publishToMessageBus(`/chat/${channelId}`, {+ type: "sent",+ chat_message: {+ id: 2138,+ message: "Hello there",+ cooked: "<p>Hello there</p>",+ excerpt: "Hello there",+ created_at: "2023-05-18T16:07:59.588Z",+ available_flags: [],+ chat_channel_id: channelId,+ user: { id: 2, username: "otheruser" },+ uploads: [],+ ...overrides,+ },+ });+ }++ test("announces incoming messages from other users", async function (assert) {+ await render(+ <template>+ <ChatChannel @channel={{this.channel}} />+ <A11yLiveRegions />+ </template>+ );++ await publishSentMessage();++ assert+ .dom("#a11y-announcements-polite")+ .hasText("otheruser: Hello there");+ });++ test("does not announce the current user's own messages", async function (assert) {+ await render(+ <template>+ <ChatChannel @channel={{this.channel}} />+ <A11yLiveRegions />+ </template>+ );++ await publishSentMessage({+ user: { id: this.currentUser.id, username: this.currentUser.username },+ });++ assert.dom("#a11y-announcements-polite").hasNoText();+ });++ test("does not announce messages from ignored users", async function (assert) {+ this.currentUser.ignored_users = ["otheruser"];++ await render(+ <template>+ <ChatChannel @channel={{this.channel}} />+ <A11yLiveRegions />+ </template>+ );++ await publishSentMessage();++ assert.dom("#a11y-announcements-polite").hasNoText();+ });++ test("does not announce hidden messages", async function (assert) {+ await render(+ <template>+ <ChatChannel @channel={{this.channel}} />+ <A11yLiveRegions />+ </template>+ );++ await publishSentMessage({ hidden: true });++ assert.dom("#a11y-announcements-polite").hasNoText();+ });++ test("announces an image-only message as an image", async function (assert) {+ await render(+ <template>+ <ChatChannel @channel={{this.channel}} />+ <A11yLiveRegions />+ </template>+ );++ await publishSentMessage({+ message: "",+ excerpt: "photo.png",+ uploads: [{ id: 1, original_filename: "photo.png" }],+ });++ assert+ .dom("#a11y-announcements-polite")+ .hasText("otheruser sent an image");+ });++ test("announces a non-image upload as an attachment", async function (assert) {+ await render(+ <template>+ <ChatChannel @channel={{this.channel}} />+ <A11yLiveRegions />+ </template>+ );++ await publishSentMessage({+ message: "",+ excerpt: "report.pdf",+ uploads: [{ id: 1, original_filename: "report.pdf" }],+ });++ assert+ .dom("#a11y-announcements-polite")+ .hasText("otheruser sent an attachment");+ });++ test("announces a caption together with its image", async function (assert) {+ await render(+ <template>+ <ChatChannel @channel={{this.channel}} />+ <A11yLiveRegions />+ </template>+ );++ await publishSentMessage({+ message: "Look at this",+ excerpt: "Look at this",+ uploads: [{ id: 1, original_filename: "photo.png" }],+ });++ assert+ .dom("#a11y-announcements-polite")+ .hasText("otheruser: Look at this (with an image)");+ });++ test("does not announce when the user has opted out", async function (assert) {+ this.currentUser.set("user_option", {+ chat_announce_new_messages: false,+ });++ await render(+ <template>+ <ChatChannel @channel={{this.channel}} />+ <A11yLiveRegions />+ </template>+ );++ await publishSentMessage();++ assert.dom("#a11y-announcements-polite").hasNoText();+ });++ test("coalesces a burst of messages into a single summary", async function (assert) {+ await render(+ <template>+ <ChatChannel @channel={{this.channel}} />+ <A11yLiveRegions />+ </template>+ );++ const first = publishSentMessage({ id: 10, message: "First" });+ const second = publishSentMessage({ id: 11, message: "Second" });+ await Promise.all([first, second]);++ assert.dom("#a11y-announcements-polite").hasText("2 new messages");+ });+ }+);diff --git a/plugins/chat/test/javascripts/unit/lib/chat-message-announcement-test.js b/plugins/chat/test/javascripts/unit/lib/chat-message-announcement-test.jsnew file mode 100644index 00000000000..7f55638e12f--- /dev/null+++ b/plugins/chat/test/javascripts/unit/lib/chat-message-announcement-test.js@@ -0,0 +1,81 @@+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import { messageAnnouncementText } from "discourse/plugins/chat/discourse/lib/chat-message-announcement";++function message(overrides = {}) {+ return {+ user: { username: "alice" },+ message: "",+ excerpt: "",+ uploads: [],+ ...overrides,+ };+}++module("Unit | Lib | chat-message-announcement", function (hooks) {+ setupTest(hooks);++ test("text message reads sender and text", function (assert) {+ assert.strictEqual(+ messageAnnouncementText(message({ message: "hello", excerpt: "hello" })),+ "alice: hello"+ );+ });++ test("decodes HTML entities from the excerpt", function (assert) {+ assert.strictEqual(+ messageAnnouncementText(+ message({ message: "you & me", excerpt: "you & me" })+ ),+ "alice: you & me"+ );+ });++ test("image-only message is announced as an image", function (assert) {+ assert.strictEqual(+ messageAnnouncementText(+ message({+ excerpt: "photo.png",+ uploads: [{ original_filename: "photo.png" }],+ })+ ),+ "alice sent an image"+ );+ });++ test("multiple images are counted", function (assert) {+ assert.strictEqual(+ messageAnnouncementText(+ message({+ uploads: [+ { original_filename: "a.png" },+ { original_filename: "b.jpg" },+ ],+ })+ ),+ "alice sent 2 images"+ );+ });++ test("a non-image upload is announced as an attachment", function (assert) {+ assert.strictEqual(+ messageAnnouncementText(+ message({ uploads: [{ original_filename: "report.pdf" }] })+ ),+ "alice sent an attachment"+ );+ });++ test("a caption is read together with its image", function (assert) {+ assert.strictEqual(+ messageAnnouncementText(+ message({+ message: "look at this",+ excerpt: "look at this",+ uploads: [{ original_filename: "photo.png" }],+ })+ ),+ "alice: look at this (with an image)"+ );+ });+});