A platform for community discussion. Free, open, simple.
A11Y: Make chat message actions reachable by keyboard (#42636)
Krisbd29f8569372
diff --git a/frontend/discourse/select-kit/components/dropdown-select-box.js b/frontend/discourse/select-kit/components/dropdown-select-box.jsindex d1503e091c0..425315c98c6 100644--- a/frontend/discourse/select-kit/components/dropdown-select-box.js+++ b/frontend/discourse/select-kit/components/dropdown-select-box.js@@ -15,6 +15,7 @@ import { pluginApiIdentifiers, selectKitOptions } from "./select-kit";showCaret: false,customStyle: null,btnCustomClasses: null,+ headerAriaLabel: null,})@pluginApiIdentifiers(["dropdown-select-box"])export default class DropdownSelectBox extends SingleSelectComponent {diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-message-actions-desktop.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-message-actions-desktop.gjsindex 976f9464bd2..eb430de5a07 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-message-actions-desktop.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-message-actions-desktop.gjs@@ -1,48 +1,107 @@import Component from "@glimmer/component";import { cached, tracked } from "@glimmer/tracking";import { concat, hash } from "@ember/helper";-import { on } from "@ember/modifier";import { action } from "@ember/object";import { getOwner } from "@ember/owner";import didInsert from "@ember/render-modifiers/modifiers/did-insert";-import didUpdate from "@ember/render-modifiers/modifiers/did-update";-import { next } from "@ember/runloop";import { service } from "@ember/service";-import {- computePosition,- flip,- hide,- limitShift,- offset,- shift,-} from "@floating-ui/dom";+import { modifier } from "ember-modifier";import BookmarkIcon from "discourse/components/bookmark-icon";import DropdownSelectBox from "discourse/select-kit/components/dropdown-select-box";import { and } from "discourse/truth-helpers";import DButton from "discourse/ui-kit/d-button";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";+import { i18n } from "discourse-i18n";import ChatMessageReaction from "discourse/plugins/chat/discourse/components/chat-message-reaction";-import chatMessageContainer from "discourse/plugins/chat/discourse/lib/chat-message-container";import ChatMessageInteractor from "discourse/plugins/chat/discourse/lib/chat-message-interactor";-const MSG_ACTIONS_USER_INFO_VERTICAL_OFFSET = -24;-const MSG_ACTIONS_VERTICAL_OFFSET = -6;const FULL = "full";const REDUCED = "reduced";const REDUCED_WIDTH_THRESHOLD = 500;export default class ChatMessageActionsDesktop extends Component {- @service chat;@service site;@tracked size = FULL;+ // eslint-disable-next-line no-unused-vars -- `size` is taken to re-run the modifier, not read+ rovingToolbar = modifier((element, [size]) => {+ const items = () =>+ [...element.children]+ .map((child) =>+ child.matches("button, summary")+ ? child+ : child.querySelector("button, summary")+ )+ .filter((item) => item && !item.disabled);++ const setTabStop = (target) => {+ const all = items();+ const stop = all.includes(target) ? target : all[0];+ all.forEach((item) =>+ item.setAttribute("tabindex", item === stop ? "0" : "-1")+ );+ };++ const onKeyDown = (event) => {+ const all = items();+ const index = all.indexOf(document.activeElement);++ if (index === -1) {+ return;+ }++ let target;+ switch (event.key) {+ case "ArrowRight":+ target = all[(index + 1) % all.length];+ break;+ case "ArrowLeft":+ target = all[(index - 1 + all.length) % all.length];+ break;+ case "Home":+ target = all[0];+ break;+ case "End":+ target = all[all.length - 1];+ break;+ default:+ return;+ }++ event.preventDefault();+ setTabStop(target);+ target.focus();+ };++ // Re-asserted on focus: these controls re-render on their own schedule and restore+ // the tabindex they were rendered with.+ const onFocusIn = (event) => {+ if (items().includes(event.target)) {+ setTabStop(event.target);+ }+ };++ // Re-runs on a size change, which swaps the toolbar's items. Keeping the tab stop on+ // whatever holds focus stops a resize from putting a keyboard user back to the start.+ setTabStop(+ element.contains(document.activeElement) ? document.activeElement : null+ );+ element.addEventListener("keydown", onKeyDown);+ element.addEventListener("focusin", onFocusIn);++ return () => {+ element.removeEventListener("keydown", onKeyDown);+ element.removeEventListener("focusin", onFocusIn);+ };+ });+get message() {- return this.chat.activeMessage.model;+ return this.args.message;}get context() {- return this.chat.activeMessage.context;+ return this.args.context;}@cached@@ -58,8 +117,16 @@ export default class ChatMessageActionsDesktop extends Component {return this.size === FULL && this.message.channel?.isFollowing;}- get messageContainer() {- return chatMessageContainer(this.message.id, this.context);+ // A bookmark's reminder makes a useful name once one is set, but the button needs one+ // before that too — it is icon-only, so its name is all a screen reader has to go on.+ get bookmarkLabel() {+ if (!this.message.bookmark) {+ return i18n("chat.bookmark_message");+ }++ return (+ this.message.bookmark.reminderTitle || i18n("chat.bookmark_message_edit")+ );}@action@@ -69,90 +136,29 @@ export default class ChatMessageActionsDesktop extends Component {}@action- setup(element) {- const container = this.messageContainer;+ setSize(element) {+ const boundary = element.closest(".chat-messages-scroller");- if (!container) {- return;+ if (boundary) {+ this.size =+ boundary.clientWidth < REDUCED_WIDTH_THRESHOLD ? REDUCED : FULL;}-- const boundary = container.closest(".chat-messages-scroller");-- if (!boundary) {- return;- }-- this.size = boundary.clientWidth < REDUCED_WIDTH_THRESHOLD ? REDUCED : FULL;-- next(() => {- computePosition(container, element, {- placement: "top-end",- strategy: "fixed",- middleware: [- offset({- mainAxis: this.chat.activeMessage?.hideUserInfo- ? MSG_ACTIONS_VERTICAL_OFFSET- : MSG_ACTIONS_USER_INFO_VERTICAL_OFFSET,- crossAxis: -2,- }),- flip({- boundary,- fallbackPlacements: ["bottom-end"],- }),- shift({ limiter: limitShift() }),- hide({ strategy: "referenceHidden" }),- hide({ strategy: "escaped" }),- ],- }).then(({ x, y, middlewareData }) => {- const style = {- left: `${x}px`,- top: `${y}px`,- };-- if (- middlewareData.hide?.referenceHidden ||- middlewareData.hide?.escaped- ) {- style.visibility = "hidden";- style.pointerEvents = "none";- } else {- style.visibility = "visible";- style.pointerEvents = "auto";- }-- Object.assign(element.style, style);- });- });- }-- @action- redirectScroll(event) {- event.preventDefault();-- const targetElement = this.messageContainer.closest(- ".chat-messages-scroller"- );-- if (!targetElement) {- return;- }-- targetElement.scrollTop += event.deltaY;}<template>- {{#if (and this.site.desktopView this.chat.activeMessage.model.persisted)}}+ {{#if (and this.site.desktopView @message.persisted)}}<div- {{didInsert this.setup}}- {{didUpdate this.setup this.chat.activeMessage.model.id}}+ {{didInsert this.setSize}}class={{dConcatClass"chat-message-actions-container"(concat "is-size-" this.size)}}data-id={{this.message.id}}- {{on "wheel" this.redirectScroll}}><div+ role="toolbar"+ aria-label={{i18n "chat.message_actions"}}+ {{this.rovingToolbar this.size}}class={{dConcatClass"chat-message-actions"(unless@@ -162,7 +168,10 @@ export default class ChatMessageActionsDesktop extends Component {}}>{{#if this.shouldRenderFavoriteReactions}}- {{#each this.messageInteractor.emojiReactions as |reaction|}}+ {{#each+ this.messageInteractor.emojiReactions key="emoji"+ as |reaction|+ }}<ChatMessageReaction@reaction={{reaction}}@onReaction={{this.messageInteractor.react}}@@ -178,6 +187,7 @@ export default class ChatMessageActionsDesktop extends Component {@action={{this.openEmojiPicker}}@forwardEvent={{true}}@icon="discourse-emojis"+ @title="chat.react"class="btn-flat react-btn"/>{{/if}}@@ -186,7 +196,8 @@ export default class ChatMessageActionsDesktop extends Component {<DButton@action={{this.messageInteractor.toggleBookmark}}class="btn-flat bookmark-btn"- @translatedTitle={{this.message.bookmark.reminderTitle}}+ @translatedTitle={{this.bookmarkLabel}}+ @translatedAriaLabel={{this.bookmarkLabel}}><BookmarkIcon @bookmark={{this.message.bookmark}} /></DButton>@@ -213,6 +224,7 @@ export default class ChatMessageActionsDesktop extends Component {placement="left"customStyle="true"btnCustomClasses="btn-flat"+ headerAriaLabel=(i18n "chat.more_message_actions")}}@content={{this.messageInteractor.secondaryActions}}@onChange={{this.messageInteractor.handleSecondaryActions}}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-message-actions-mobile.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-message-actions-mobile.gjsindex fdcaec72e20..b7ea2e27a2b 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-message-actions-mobile.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-message-actions-mobile.gjs@@ -1,5 +1,5 @@import Component from "@glimmer/component";-import { tracked } from "@glimmer/tracking";+import { cached, tracked } from "@glimmer/tracking";import { fn } from "@ember/helper";import { on } from "@ember/modifier";import { action } from "@ember/object";@@ -32,6 +32,7 @@ export default class ChatMessageActionsMobile extends Component {return this.chat.activeMessage.context;}+ @cachedget messageInteractor() {return new ChatMessageInteractor(getOwner(this),@@ -130,7 +131,10 @@ export default class ChatMessageActionsMobile extends Component {}}<div class="main-actions">{{#if this.messageInteractor.canReact}}- {{#each this.messageInteractor.emojiReactions as |reaction|}}+ {{#each+ this.messageInteractor.emojiReactions key="emoji"+ as |reaction|+ }}<ChatMessageReaction@reaction={{reaction}}@onReaction={{this.react}}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-message-reaction.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-message-reaction.gjsindex 732fcf89e1b..f017929138f 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-message-reaction.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-message-reaction.gjs@@ -12,6 +12,7 @@ import discourseLater from "discourse/lib/later";import { emojiUnescape, emojiUrlFor } from "discourse/lib/text";import { and, eq } from "discourse/truth-helpers";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";+import { i18n } from "discourse-i18n";import ChatMessageReactionsUsers from "discourse/plugins/chat/discourse/components/chat-message-reactions-users";import { getReactionText } from "discourse/plugins/chat/discourse/lib/get-reaction-text";@@ -169,6 +170,27 @@ export default class ChatMessageReaction extends Component {return emojiUrlFor(this.args.reaction.emoji);}+ get isCountedReaction() {+ return !!(this.showCount && this.args.reaction.count);+ }++ get ariaLabel() {+ const emoji = this.args.reaction.emoji;++ if (this.isCountedReaction) {+ return i18n("chat.reactions.counted", {+ emoji,+ count: this.args.reaction.count,+ });+ }++ if (this.args.reaction.reacted) {+ return i18n("chat.reactions.remove", { emoji });+ }++ return i18n("chat.reactions.add", { emoji });+ }+@actionhandleClick(event) {event.stopPropagation();@@ -205,9 +227,15 @@ export default class ChatMessageReaction extends Component {{{this.registerReactionsUsersPopup}}type="button"title={{this.emojiString}}+ aria-label={{this.ariaLabel}}+ aria-pressed={{if+ this.isCountedReaction+ (if @reaction.reacted "true" "false")+ }}data-emoji-name={{@reaction.emoji}}+ {{! `interactive` is opt-out, as it is on the message itself: only an explicit+ false makes a reaction display-only. }}tabindex={{if (eq @interactive false) "-1" "0"}}- aria-pressed={{if @reaction.reacted "true" "false"}}aria-describedby={{if this.description this.descriptionId}}class={{dConcatClass"chat-message-reaction"diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-message.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-message.gjsindex 65c9830ec5d..67cbbfb08a5 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-message.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-message.gjs@@ -6,7 +6,7 @@ import { on } from "@ember/modifier";import { action } from "@ember/object";import { getOwner } from "@ember/owner";import willDestroy from "@ember/render-modifiers/modifiers/will-destroy";-import { cancel, schedule } from "@ember/runloop";+import { cancel, next, schedule } from "@ember/runloop";import { service } from "@ember/service";import { modifier } from "ember-modifier";import EmojiPicker from "discourse/components/emoji-picker";@@ -26,6 +26,7 @@ import ChatMessageError from "discourse/plugins/chat/discourse/components/chat/mimport ChatMessageInfo from "discourse/plugins/chat/discourse/components/chat/message/info";import ChatMessageLeftGutter from "discourse/plugins/chat/discourse/components/chat/message/left-gutter";import ChatMessageBlocks from "discourse/plugins/chat/discourse/components/chat-message/blocks";+import ChatMessageActionsDesktop from "discourse/plugins/chat/discourse/components/chat-message-actions-desktop";import ChatMessageActionsMobileModal from "discourse/plugins/chat/discourse/components/chat-message-actions-mobile";import ChatMessageInReplyToIndicator from "discourse/plugins/chat/discourse/components/chat-message-in-reply-to-indicator";import ChatMessageReaction from "discourse/plugins/chat/discourse/components/chat-message-reaction";@@ -148,6 +149,13 @@ export default class ChatMessage extends Component {);}+ get showActions() {+ return (+ this.chat.activeMessage?.model?.id === this.args.message.id &&+ this.chat.activeMessage?.context === this.args.context+ );+ }+get secondaryActionsIsExpanded() {return document.querySelector(".more-buttons.secondary-actions.is-expanded"@@ -187,6 +195,7 @@ export default class ChatMessage extends Component {cancel(this._disableMessageActionsHandler);cancel(this._makeMessageActiveHandler);cancel(this._onMouseEnterMessageDebouncedHandler);+ cancel(this._clearActiveMessageHandler);this.#teardownMentionedUsers();this.chat.activeMessage = null;}@@ -321,6 +330,57 @@ export default class ChatMessage extends Component {this._setActiveMessage();}+ @action+ onFocusIn(event) {+ if (this.site.mobileView) {+ return;+ }++ const container = event.currentTarget;++ next(() => {+ if (container.isConnected && container.contains(document.activeElement)) {+ this._setActiveMessage({ fromKeyboard: true });+ }+ });+ }++ @action+ onFocusOut(event) {+ if (this.site.mobileView) {+ return;+ }++ const container = event.currentTarget;++ // The actions render inside the message, so focus moving into them stays contained.+ if (container.contains(event.relatedTarget)) {+ return;+ }++ // Deferred for the same reason as raising them, and rechecked: `relatedTarget` is not+ // always where focus comes to rest.+ this._clearActiveMessageHandler = next(() => {+ // The emoji picker and the secondary actions menu both take focus into a portal+ // outside the message, and both are anchored to the toolbar this would unmount.+ if (+ this.interactedChatMessage.emojiPickerOpen ||+ this.secondaryActionsIsExpanded+ ) {+ return;+ }++ if (+ container.isConnected &&+ !container.contains(document.activeElement) &&+ this.chat.activeMessage?.model?.id === this.args.message.id &&+ this.chat.activeMessage?.context === this.args.context+ ) {+ this.chat.activeMessage = null;+ }+ });+ }+@actiononMouseLeave(event) {cancel(this._onMouseEnterMessageDebouncedHandler);@@ -353,8 +413,16 @@ export default class ChatMessage extends Component {this._setActiveMessage();}- _setActiveMessage() {- if (this.args.disableMouseEvents || this.args.interactive === false) {+ // `disableMouseEvents` suppresses the toolbar while the list is being scrolled with the+ // pointer. Focus is not a pointer, so the keyboard path opts out of that check.+ _setActiveMessage({ fromKeyboard = false } = {}) {+ // A pending clear from focus leaving would otherwise land after this and undo it.+ cancel(this._clearActiveMessageHandler);++ if (+ (!fromKeyboard && this.args.disableMouseEvents) ||+ this.args.interactive === false+ ) {return;}@@ -368,6 +436,15 @@ export default class ChatMessage extends Component {return;}+ // Focus moving between the message's own controls re-reports it as active. Assigning+ // a fresh hash each time invalidates what render just read from it.+ if (+ this.chat.activeMessage?.model?.id === this.args.message.id &&+ this.chat.activeMessage?.context === this.args.context+ ) {+ return;+ }+this.chat.activeMessage = {model: this.args.message,hideUserInfo: this.hideUserInfo,@@ -439,7 +516,8 @@ export default class ChatMessage extends Component {get hasActiveState() {return (this.isActive ||- this.chat.activeMessage?.model?.id === this.args.message.id+ (this.chat.activeMessage?.model?.id === this.args.message.id &&+ this.chat.activeMessage?.context === this.args.context));}@@ -561,7 +639,6 @@ export default class ChatMessage extends Component {}<template>- {{! eslint-disable ember/template-no-invalid-interactive }}{{#if this.shouldRender}}{{#if this.includeSeparator}}<ChatMessageSeparator@@ -570,6 +647,9 @@ export default class ChatMessage extends Component {/>{{/if}}+ {{! The message is not itself a control: these observe pointer and focus moving over+ it to raise its actions, and the controls they raise are the interactive parts. }}+ {{! eslint-disable-next-line ember/template-no-invalid-interactive }}<divclass={{dConcatClass"chat-message-container"@@ -600,6 +680,8 @@ export default class ChatMessage extends Component {data-id={{@message.id}}data-thread-id={{@message.thread.id}}{{willDestroy this.willDestroyMessage}}+ {{on "focusin" this.onFocusIn passive=true}}+ {{on "focusout" this.onFocusOut passive=true}}{{on "mouseenter" this.onMouseEnter passive=true}}{{on "mouseleave" this.onMouseLeave passive=true}}{{on "mousemove" this.onMouseMove passive=true}}@@ -662,6 +744,7 @@ export default class ChatMessage extends Component {@message={{@message}}@show={{not this.hideUserInfo}}@context={{@context}}+ @interactive={{@interactive}}@threadContext={{this.threadContext}}@dateMode={{@dateMode}}/>@@ -724,6 +807,13 @@ export default class ChatMessage extends Component {</div>{{/if}}{{/if}}++ {{#if this.showActions}}+ <ChatMessageActionsDesktop+ @message={{@message}}+ @context={{@context}}+ />+ {{/if}}</div>{{/if}}</template>diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-user-avatar.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-user-avatar.gjsindex 3291bd4a80a..ecbdbfc6f17 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-user-avatar.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-user-avatar.gjs@@ -43,6 +43,10 @@ export default class ChatUserAvatar extends Component {return userPath(this.args.user.username);}+ get ariaHidden() {+ return this.args.ariaHidden ?? false;+ }+get isFullPageActive() {return this.chatStateManager.isFullPageActive ? "true" : "false";}@@ -57,11 +61,16 @@ export default class ChatUserAvatar extends Component {class="chat-user-avatar__container"href={{this.userPath}}data-user-card={{@user.username}}+ aria-hidden={{if this.ariaHidden "true"}}+ tabindex={{if this.ariaHidden "-1"}}>{{this.avatar}}</a>{{else}}- <span class="chat-user-avatar__container">+ <span+ class="chat-user-avatar__container"+ aria-hidden={{if this.ariaHidden "true"}}+ >{{this.avatar}}</span>{{/if}}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message/avatar.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/message/avatar.gjsindex fa6603b2c48..63ccc3cd89b 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat/message/avatar.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat/message/avatar.gjs@@ -10,6 +10,7 @@ const Avatar = <template>@user={{@message.user}}@avatarSize="medium"@interactive={{@interactive}}+ @ariaHidden={{true}}/>{{/if}}</div>diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message/info.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/message/info.gjsindex 1f6fa8b9dd4..9aba49a2805 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat/message/info.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat/message/info.gjs@@ -77,6 +77,10 @@ export default class ChatMessageInfo extends Component {return !!this.#user?.get("status");}+ get interactive() {+ return this.args.interactive !== false;+ }+get #user() {return this.args.message?.user;}@@ -124,16 +128,26 @@ export default class ChatMessageInfo extends Component {{{i18n "chat.bot"}}</span>{{else}}+ {{! The name carries the click target rather than the wrapper: a status message+ brings its own tooltip trigger, which cannot sit inside a button. }}<span- role="button"class={{dConcatClass"chat-message-info__username"this.usernameClasses- "clickable"+ (if this.interactive "clickable")}}- data-user-card={{@message.user.username}}>- <span class="chat-message-info__username__name">{{this.name}}</span>+ {{#if this.interactive}}+ <button+ type="button"+ class="chat-message-info__username__name"+ data-user-card={{@message.user.username}}+ >{{this.name}}</button>+ {{else}}+ <span+ class="chat-message-info__username__name"+ >{{this.name}}</span>+ {{/if}}{{#if this.showStatus}}<span class="chat-message-info__status"><DUserStatusMessage @status={{@message.user.status}} />@@ -191,6 +205,20 @@ export default class ChatMessageInfo extends Component {</LinkTo>{{/if}}</div>+ {{else if+ (and this.interactive @message.user.username (not @message.isAction))+ }}+ {{! A message chained to the one above shows no author, but it still has one. Keeping+ the name rendered keeps the transcript attributable when it is being read rather than+ seen, and gives the message a control the keyboard can reach. An action message is+ excluded: it names its author in its own text. }}+ <div class="chat-message-info -author-only sr-only">+ <button+ type="button"+ class="chat-message-info__username__name"+ data-user-card={{@message.user.username}}+ >{{this.name}}</button>+ </div>{{/if}}</template>}diff --git a/plugins/chat/assets/javascripts/discourse/connectors/below-footer/chat-message-actions-desktop-outlet.gjs b/plugins/chat/assets/javascripts/discourse/connectors/below-footer/chat-message-actions-desktop-outlet.gjsdeleted file mode 100644index 828481cd253..00000000000--- a/plugins/chat/assets/javascripts/discourse/connectors/below-footer/chat-message-actions-desktop-outlet.gjs+++ /dev/null@@ -1,9 +0,0 @@-import ChatMessageActionsDesktop from "../../components/chat-message-actions-desktop";--const ChatMessageActionsDesktopOutlet = <template>- <div class="below-footer-outlet chat-message-actions-desktop-outlet">- <ChatMessageActionsDesktop />- </div>-</template>;--export default ChatMessageActionsDesktopOutlet;diff --git a/plugins/chat/assets/javascripts/discourse/lib/chat-message-interactor.js b/plugins/chat/assets/javascripts/discourse/lib/chat-message-interactor.jsindex 1841b8fb537..e5c67952ec9 100644--- a/plugins/chat/assets/javascripts/discourse/lib/chat-message-interactor.js+++ b/plugins/chat/assets/javascripts/discourse/lib/chat-message-interactor.js@@ -1,4 +1,4 @@-import { tracked } from "@glimmer/tracking";+import { cached, tracked } from "@glimmer/tracking";import { action } from "@ember/object";import { getOwner, setOwner } from "@ember/owner";import { service } from "@ember/service";@@ -52,6 +52,9 @@ export default class ChatMessageInteractor {@tracked message = null;@tracked context = null;+ #quickReactionEmojis;+ #placeholderReactions = new Map();+constructor(owner, message, context) {setOwner(this, owner);@@ -59,7 +62,24 @@ export default class ChatMessageInteractor {this.context = context;}+ // Reacting re-sorts the frequency-ordered quick reactions, so the emoji are resolved+ // once and held: the controls must not move under a user who is still interacting+ // with them. An interactor is built per open actions menu, which scopes the freeze.+ get quickReactionEmojis() {+ this.#quickReactionEmojis ??= this.#computeQuickReactionEmojis();+ return this.#quickReactionEmojis;+ }++ @cachedget emojiReactions() {+ return this.quickReactionEmojis.map(+ (emoji) =>+ this.message.reactions.find((reaction) => reaction.emoji === emoji) ||+ this.#placeholderReaction(emoji)+ );+ }++ #computeQuickReactionEmojis() {const userQuickReactionsCustom = ((this.currentUser.user_option.chat_quick_reaction_type === "custom" &&this.currentUser.user_option.chat_quick_reactions_custom) ||@@ -92,12 +112,20 @@ export default class ChatMessageInteractor {return allReactionsInOrder.indexOf(item) === index;}).filter(Boolean)- .slice(0, 3)- .map(- (emoji) =>- this.message.reactions.find((reaction) => reaction.emoji === emoji) ||- ChatMessageReactionModel.create({ emoji })- );+ .slice(0, 3);+ }++ // An emoji with no reaction yet still needs a model to render against, and it has to+ // keep its identity across re-renders or the control it backs is torn down.+ #placeholderReaction(emoji) {+ let reaction = this.#placeholderReactions.get(emoji);++ if (!reaction) {+ reaction = ChatMessageReactionModel.create({ emoji });+ this.#placeholderReactions.set(emoji, reaction);+ }++ return reaction;}get pane() {diff --git a/plugins/chat/assets/stylesheets/common/base-common.scss b/plugins/chat/assets/stylesheets/common/base-common.scssindex 8d091ce7c06..e735f0478f3 100644--- a/plugins/chat/assets/stylesheets/common/base-common.scss+++ b/plugins/chat/assets/stylesheets/common/base-common.scss@@ -146,6 +146,14 @@ html.ios-device.has-full-page-chat body #main-outlet {.chat-message-container {display: grid;+ position: relative;++ // A chained message's author stays clipped while focused, so the message shows where+ // focus is on its behalf.+ &:has(.chat-message-info.-author-only :focus-visible) {+ outline: 2px solid var(--tertiary);+ outline-offset: -2px;+ }&.-selectable {grid-template-columns: 1.5em 1fr;diff --git a/plugins/chat/assets/stylesheets/common/chat-message-actions.scss b/plugins/chat/assets/stylesheets/common/chat-message-actions.scssindex e3361cce84c..7146f642264 100644--- a/plugins/chat/assets/stylesheets/common/chat-message-actions.scss+++ b/plugins/chat/assets/stylesheets/common/chat-message-actions.scss@@ -1,26 +1,21 @@-.chat-message-actions-desktop-anchor {- position: relative;- z-index: z("dropdown");-}-.chat-message-actions-container {@include unselectable;- position: fixed;+ position: absolute;width: max-content;- top: 0;- left: 0;+ right: var(--space-2);+ top: -0.75em;z-index: z("composer", "content");- // dynamically overridden by the component- visibility: hidden;- pointer-events: none;+ .-user-info-hidden & {+ top: -0.25em;+ }&.is-size-full {- padding-left: 60px !important; /* for easier mouse movement to the element */+ padding-left: 60px; /* for easier mouse movement to the element */}&.is-size-reduced {- padding-left: 20px !important; /* for easier mouse movement to the element */+ padding-left: 20px; /* for easier mouse movement to the element */}}@@ -28,6 +23,11 @@border-radius: var(--d-border-radius);display: flex;+ :is(button, summary):focus-visible {+ @include default-focus;+ z-index: 2;+ }+.link-to-message-btn {.d-icon {transition: all 0.25s ease-in-out;@@ -53,7 +53,7 @@pointer-events: none;}- &:focus {+ &:focus-visible {.d-icon {color: var(--primary);}@@ -93,9 +93,8 @@border-top-left-radius: 0;border-bottom-left-radius: 0;- &:focus {- border-color: var(--primary-300);- border-left-color: transparent;+ &:focus-visible {+ background: var(--primary-low);.select-kit-header-wrapper .d-icon {color: var(--primary);@@ -150,11 +149,6 @@padding: 0.5em 0;width: 2.5em;- &:focus {- background: var(--primary-low);- outline: none;- }-&:first-child {border-left-color: var(--primary-300);border-top-left-radius: var(--d-border-radius);@@ -164,10 +158,6 @@&.reacted {border-left-color: var(--tertiary-medium);z-index: 1;-- &:focus {- background: var(--tertiary-low);- }}.emoji {diff --git a/plugins/chat/assets/stylesheets/common/chat-message-info.scss b/plugins/chat/assets/stylesheets/common/chat-message-info.scssindex fa07a4b2acf..abde0f7303f 100644--- a/plugins/chat/assets/stylesheets/common/chat-message-info.scss+++ b/plugins/chat/assets/stylesheets/common/chat-message-info.scss@@ -11,6 +11,10 @@}}+// The author of a chained message, carried for readers who cannot see that it belongs to+// the message above. `sr-only` clips it rather than removing it, so it stays focusable —+// it is left clipped even then, since revealing it would cover the message. The message+// takes the focus indicator in its place (see `.chat-message-container`)..chat-message-info__username {display: inline-flex;align-items: baseline;@@ -29,6 +33,13 @@@include ellipsis;max-width: 180px;+ padding: 0;+ border: none;+ background: none;+ font-size: inherit;+ font-family: inherit;+ line-height: inherit;+ cursor: pointer;}.chat-message-info__bot-indicator {diff --git a/plugins/chat/assets/stylesheets/mixins/chat-reaction.scss b/plugins/chat/assets/stylesheets/mixins/chat-reaction.scssindex f01901c4989..85461a4d50c 100644--- a/plugins/chat/assets/stylesheets/mixins/chat-reaction.scss+++ b/plugins/chat/assets/stylesheets/mixins/chat-reaction.scss@@ -18,20 +18,18 @@background: var(--tertiary-very-low);color: var(--tertiary-hover);+ &:focus-visible,&:hover {background: var(--tertiary-low);}}&:not(.reacted) {+ &:focus-visible,&:hover {background: var(--primary-low);border-color: var(--primary-low-mid);}-- &:focus {- background: none;- }}.emoji {diff --git a/plugins/chat/config/locales/client.en.yml b/plugins/chat/config/locales/client.en.ymlindex 818843b73ba..4c9cd0efc06 100644--- a/plugins/chat/config/locales/client.en.yml+++ b/plugins/chat/config/locales/client.en.yml@@ -313,6 +313,8 @@ en:remove_upload: "Remove file"react: "React with emoji"reply: "Reply"+ message_actions: "Message actions"+ more_message_actions: "More message actions"edit: "Edit"copy_link: "Copy link"copy_text: "Copy text"@@ -539,6 +541,11 @@ en:message_in_channel: "Channel"reactions:+ add: "React with %{emoji}"+ remove: "Remove your %{emoji} reaction"+ counted:+ one: "%{emoji} reaction, %{count} person"+ other: "%{emoji} reaction, %{count} people"only_you: "<span>You reacted with </span>:%{emoji}:"you_and_single_user: "<span>You and %{username} reacted with </span>:%{emoji}:"you_and_multiple_users: "<span>You, %{commaSeparatedUsernames} and %{username} reacted with </span>:%{emoji}:"diff --git a/plugins/chat/spec/system/keyboard_message_actions_spec.rb b/plugins/chat/spec/system/keyboard_message_actions_spec.rbnew file mode 100644index 00000000000..dbfb482fb70--- /dev/null+++ b/plugins/chat/spec/system/keyboard_message_actions_spec.rb@@ -0,0 +1,188 @@+# frozen_string_literal: true++RSpec.describe "Chat | keyboard access to message actions" do+ fab!(:current_user, :user)+ fab!(:channel_1, :chat_channel)+ fab!(:message_1) { Fabricate(:chat_message, chat_channel: channel_1) }+ fab!(:message_2) { Fabricate(:chat_message, chat_channel: channel_1) }++ let(:chat_page) { PageObjects::Pages::Chat.new }+ let(:channel_page) { PageObjects::Pages::ChatChannel.new }+ let(:drawer_page) { PageObjects::Pages::ChatDrawer.new }++ before do+ chat_system_bootstrap+ channel_1.add(current_user)+ sign_in(current_user)+ end++ def focused+ page.evaluate_script(<<~JS)+ (() => {+ const active = document.activeElement;+ if (!active) {+ return {};+ }+ const message = active.closest(".chat-message-container");+ return {+ messageId: message && message.dataset.id,+ inActions: !!active.closest(".chat-message-actions"),+ };+ })()+ JS+ end++ # sibling reaction buttons are indistinguishable by class, so position is what tells us+ # focus actually moved+ def focused_position+ page.evaluate_script(<<~JS)+ Array.from(+ document.querySelectorAll(".chat-message-actions > *")+ ).findIndex(+ (item) => item === document.activeElement || item.contains(document.activeElement)+ )+ JS+ end++ def focus_author(message)+ page.execute_script(<<~JS)+ document+ .querySelector(".chat-message-container[data-id='#{message.id}'] .chat-message-info__username__name")+ .focus()+ JS+ end++ it "reaches a message's actions by tabbing on from the message" do+ chat_page.visit_channel(channel_1)+ expect(channel_page.message_by_id(message_1.id)).to be_present++ focus_author(message_1)++ # focus raises the actions the pointer gets by hovering, and they render inside the+ # message, so tabbing on walks into them rather than skipping to the next message+ expect(page).to have_css(+ ".chat-message-container[data-id='#{message_1.id}'] .chat-message-actions",+ )++ reached = false+ 6.times do+ page.send_keys(:tab)+ current = focused+ expect(current["messageId"]).to eq(message_1.id.to_s)++ if current["inActions"]+ reached = true+ break+ end+ end++ expect(reached).to eq(true)+ end++ it "keeps a single set of actions on the page" do+ chat_page.visit_channel(channel_1)+ expect(channel_page.message_by_id(message_2.id)).to be_present++ focus_author(message_1)+ expect(page).to have_css(".chat-message-actions", count: 1)++ focus_author(message_2)+ expect(page).to have_css(+ ".chat-message-container[data-id='#{message_2.id}'] .chat-message-actions",+ )+ expect(page).to have_css(".chat-message-actions", count: 1)+ end++ it "names every action, since they are all icon-only" do+ chat_page.visit_channel(channel_1)+ expect(channel_page.message_by_id(message_1.id)).to be_present++ focus_author(message_1)+ expect(page).to have_css(".chat-message-actions")++ expect(page).to have_css(+ ".chat-message-actions[role='toolbar'][aria-label='#{I18n.t("js.chat.message_actions")}']",+ )+ expect(page).to have_css(".react-btn[title='#{I18n.t("js.chat.react")}']")+ expect(page).to have_css(".reply-btn[title='#{I18n.t("js.chat.reply")}']")+ expect(page).to have_css(".bookmark-btn[aria-label='#{I18n.t("js.chat.bookmark_message")}']")+ expect(page).to have_css(+ ".more-buttons [aria-label='#{I18n.t("js.chat.more_message_actions")}']",+ )+ end++ it "announces the author once, and lets a keyboard reach them" do+ chat_page.visit_channel(channel_1)+ expect(channel_page.message_by_id(message_1.id)).to be_present++ # the avatar link's own name is the username it sits beside, so it would be announced+ # twice and cost a tab stop reaching the same place+ expect(page).to have_css(+ ".chat-message-container[data-id='#{message_1.id}'] .chat-user-avatar__container[aria-hidden='true'][tabindex='-1']",+ )+ expect(page).to have_css(+ ".chat-message-container[data-id='#{message_1.id}'] button.chat-message-info__username__name",+ )++ # the message itself is not a control, so it is not announced as one and does not+ # read out its actions as part of its own text+ expect(page).to have_no_css(".chat-message-container[tabindex]")+ end++ it "costs one tab stop, with arrows moving along it" do+ chat_page.visit_channel(channel_1)+ expect(channel_page.message_by_id(message_1.id)).to be_present++ focus_author(message_1)+ expect(page).to have_css(".chat-message-actions")++ # a toolbar is a single stop, not one per button+ expect(page).to have_css(".chat-message-actions [tabindex='0']", count: 1)++ tabbable =+ page.evaluate_script(+ "document.querySelectorAll(\".chat-message-actions [tabindex='0'], .chat-message-actions [tabindex]:not([tabindex='-1'])\").length",+ )+ expect(tabbable).to eq(1)++ page.execute_script("document.querySelector(\".chat-message-actions [tabindex='0']\").focus()")+ expect(focused_position).to eq(0)++ page.send_keys(:right)+ expect(focused_position).to eq(1)+ expect(focused["inActions"]).to eq(true)++ page.send_keys(:left)+ expect(focused_position).to eq(0)+ end++ it "keeps its tab stop in a pane too narrow for the favourite reactions" do+ chat_page.prefers_drawer+ visit("/")+ chat_page.open_from_header+ drawer_page.open_channel(channel_1)+ expect(page).to have_css(".chat-drawer .chat-message-container[data-id='#{message_1.id}']")++ page.execute_script(<<~JS)+ document+ .querySelector(".chat-drawer .chat-message-container[data-id='#{message_1.id}'] .chat-message-info__username__name")+ .focus()+ JS++ expect(page).to have_css(".chat-message-actions-container.is-size-reduced")++ # the reduced pane drops the favourite reactions, which is where the tab stop starts+ expect(page).to have_css(".chat-message-actions [tabindex='0']", count: 1)+ end++ it "drops the actions once focus leaves the message" do+ chat_page.visit_channel(channel_1)+ expect(channel_page.message_by_id(message_1.id)).to be_present++ focus_author(message_1)+ expect(page).to have_css(".chat-message-actions")++ page.execute_script("document.querySelector('.chat-composer__input').focus()")+ expect(page).to have_no_css(".chat-message-actions")+ end+enddiff --git a/plugins/chat/test/javascripts/components/chat-message-info-test.gjs b/plugins/chat/test/javascripts/components/chat-message-info-test.gjsindex 657a0925726..095726a9529 100644--- a/plugins/chat/test/javascripts/components/chat-message-info-test.gjs+++ b/plugins/chat/test/javascripts/components/chat-message-info-test.gjs@@ -40,6 +40,58 @@ module("Component | ChatMessageInfo", function (hooks) {.hasText(this.message.user.username);});+ test("the username is a control a keyboard can reach", async function (assert) {+ this.message = new ChatFabricators(getOwner(this)).message({+ user: { username: "discobot" },+ });++ await render(+ <template><Info @message={{this.message}} @show={{true}} /></template>+ );++ assert.dom(".chat-message-info__username__name").hasTagName("button");+ assert+ .dom(".chat-message-info__username__name")+ .hasAttribute("data-user-card", "discobot");+ assert.dom(".chat-message-info__username").doesNotHaveAttribute("role");+ });++ test("the username is display-only where the message is not interactive", async function (assert) {+ this.message = new ChatFabricators(getOwner(this)).message({+ user: { username: "discobot" },+ });++ await render(+ <template>+ <Info @message={{this.message}} @show={{true}} @interactive={{false}} />+ </template>+ );++ assert.dom(".chat-message-info__username__name").hasTagName("span");+ assert.dom(".chat-message-info__username__name").hasText("discobot");+ assert+ .dom(".chat-message-info__username__name")+ .doesNotHaveAttribute("data-user-card");+ });++ test("a chained message adds no author control where it is not interactive", async function (assert) {+ this.message = new ChatFabricators(getOwner(this)).message({+ user: { username: "discobot" },+ });++ await render(+ <template>+ <Info+ @message={{this.message}}+ @show={{false}}+ @interactive={{false}}+ />+ </template>+ );++ assert.dom(".chat-message-info.-author-only").doesNotExist();+ });+test("date", async function (assert) {this.message = new ChatFabricators(getOwner(this)).message({user: { username: "discobot" },diff --git a/plugins/chat/test/javascripts/components/chat-message-reaction-test.gjs b/plugins/chat/test/javascripts/components/chat-message-reaction-test.gjsindex aae9d7d293d..a8096cd8550 100644--- a/plugins/chat/test/javascripts/components/chat-message-reaction-test.gjs+++ b/plugins/chat/test/javascripts/components/chat-message-reaction-test.gjs@@ -5,6 +5,7 @@ import { module, test } from "qunit";import DMenus from "discourse/float-kit/components/d-menus";import { setupRenderingTest } from "discourse/tests/helpers/component-test";import pretender, { response } from "discourse/tests/helpers/create-pretender";+import { i18n } from "discourse-i18n";import ChatMessageReaction from "discourse/plugins/chat/discourse/components/chat-message-reaction";import ChatFabricators from "discourse/plugins/chat/discourse/lib/fabricators";@@ -107,11 +108,46 @@ module("Component | ChatMessageReaction", function (hooks) {.doesNotExist("leaving the reaction closes it again");});- test("reports whether the current user reacted", async function (assert) {+ test("names itself as a reaction rather than just an emoji", async function (assert) {await render(<template>- <ChatMessageReaction @reaction={{hash emoji="heart" reacted=true}} />- <ChatMessageReaction @reaction={{hash emoji="+1" reacted=false}} />+ <ChatMessageReaction @reaction={{hash emoji="heart" count=3}} />+ </template>+ );++ assert+ .dom(".chat-message-reaction")+ .hasAria(+ "label",+ i18n("chat.reactions.counted", { emoji: "heart", count: 3 }),+ "a counted reaction is named by what it stands for"+ );+ });++ test("names itself by its action where it is only a way to react", async function (assert) {+ await render(+ <template>+ <ChatMessageReaction+ @reaction={{hash emoji="heart"}}+ @showCount={{false}}+ />+ </template>+ );++ assert+ .dom(".chat-message-reaction")+ .hasAria("label", i18n("chat.reactions.add", { emoji: "heart" }));+ });++ test("reports whether the reaction is the current user's", async function (assert) {+ await render(+ <template>+ <ChatMessageReaction+ @reaction={{hash emoji="heart" count=1 reacted=true}}+ />+ <ChatMessageReaction+ @reaction={{hash emoji="+1" count=1 reacted=false}}+ /></template>);@@ -123,6 +159,28 @@ module("Component | ChatMessageReaction", function (hooks) {.hasAria("pressed", "false", "one they have not added is not pressed");});+ test("is not a toggle where it is only a way to react", async function (assert) {+ await render(+ <template>+ <ChatMessageReaction+ @reaction={{hash emoji="heart" reacted=true}}+ @showCount={{false}}+ />+ </template>+ );++ // named for its action, so announcing a pressed state on top of that describes+ // neither the control nor its effect+ assert.dom(".chat-message-reaction").doesNotHaveAria("pressed");+ assert+ .dom(".chat-message-reaction")+ .hasAria(+ "label",+ i18n("chat.reactions.remove", { emoji: "heart" }),+ "and the action it names is the one it performs"+ );+ });+test("describes who reacted, without folding them into the name", async function (assert) {const reaction = {emoji: "heart",diff --git a/plugins/chat/test/javascripts/unit/lib/chat-message-interactor-test.js b/plugins/chat/test/javascripts/unit/lib/chat-message-interactor-test.jsindex 1cc0d30be65..2f96611bed1 100644--- a/plugins/chat/test/javascripts/unit/lib/chat-message-interactor-test.js+++ b/plugins/chat/test/javascripts/unit/lib/chat-message-interactor-test.js@@ -136,6 +136,42 @@ module("Unit | chat-message-interactor", function (hooks) {);});+ test("emojiReactions keeps its order once read", function (assert) {+ assert.deepEqual(+ this.messageInteractor.emojiReactions.map((r) => r.emoji),+ ["+1", "heart", "tada"]+ );++ this.emojiStore.trackEmojiForContext("butterfly", "chat");++ assert.deepEqual(+ this.messageInteractor.emojiReactions.map((r) => r.emoji),+ ["+1", "heart", "tada"],+ "reacting does not reorder the controls under the user"+ );+ });++ test("emojiReactions keeps the identity of the models it did not change", function (assert) {+ const before = this.messageInteractor.emojiReactions;++ this.messageInteractor.message.react(+ "+1",+ "add",+ this.currentUser,+ this.currentUser.id+ );++ const after = this.messageInteractor.emojiReactions;++ assert.notStrictEqual(+ after[0],+ before[0],+ "the reacted emoji gets a model"+ );+ assert.strictEqual(after[1], before[1], "heart is the same model");+ assert.strictEqual(after[2], before[2], "tada is the same model");+ });+test("canRestoreMessage allows moderators to restore deleted messages", function (assert) {updateCurrentUser({ admin: false, moderator: false, staff: false });diff --git a/plugins/discourse-events/assets/stylesheets/common/livestream.scss b/plugins/discourse-events/assets/stylesheets/common/livestream.scssindex a78e26a3150..c96c5839ef1 100644--- a/plugins/discourse-events/assets/stylesheets/common/livestream.scss+++ b/plugins/discourse-events/assets/stylesheets/common/livestream.scss@@ -317,12 +317,3 @@ body.discourse-calendar-livestream-zoom-full {display: none;}}--// we need to raise the z-index of the actions outlet-// so they appear above the modal-.livestream-chat-modal-active {- .chat-message-actions-desktop-outlet {- position: relative;- z-index: z("max");- }-}