Skip to content

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

DEV: Standardise keyboard shortcut display with formatShortcut and DShortcut (#42938)

Sérgio Saquetimcffa8feb1dfb
diff --git a/app/assets/stylesheets/common/base/sidebar.scss b/app/assets/stylesheets/common/base/sidebar.scss
index 520341d38d1..d2d13f8ebef 100644
--- a/app/assets/stylesheets/common/base/sidebar.scss
+++ b/app/assets/stylesheets/common/base/sidebar.scss
@@ -558,10 +558,7 @@
}
&__shortcut-hint {
- min-width: 26px;
- padding: 0.25em 0.5em;
- font-size: var(--font-down-3);
- color: var(--d-sidebar-link-color);
+ margin-right: var(--space-2);
}
}
diff --git a/app/assets/stylesheets/common/components/keyboard_shortcuts.scss b/app/assets/stylesheets/common/components/keyboard_shortcuts.scss
index 5d06c98f3b8..e0e83b5d834 100644
--- a/app/assets/stylesheets/common/components/keyboard_shortcuts.scss
+++ b/app/assets/stylesheets/common/components/keyboard_shortcuts.scss
@@ -81,10 +81,6 @@
outline: none;
}
- kbd:first-child {
- margin-left: 0;
- }
-
@for $i from 1 through 25 {
.span-#{$i} {
grid-row-end: span $i;
@@ -113,28 +109,9 @@
text-align: right;
white-space: nowrap;
- span {
- border-radius: 3px;
- display: inline-flex;
- padding: 2px 1px 4px;
- }
-
- span:first-child {
- margin-right: 0;
- }
-
- span:last-child {
- margin-left: auto;
- }
-
.delimiter-newline {
- display: revert;
+ display: block;
text-align: right;
}
}
-
- kbd {
- font-family: var(--d-font-family--monospace);
- font-weight: bold;
- }
}
diff --git a/app/assets/stylesheets/common/toolbar-popup-menu-options.scss b/app/assets/stylesheets/common/toolbar-popup-menu-options.scss
index 8c2cb1f0738..2e0cd7b1d97 100644
--- a/app/assets/stylesheets/common/toolbar-popup-menu-options.scss
+++ b/app/assets/stylesheets/common/toolbar-popup-menu-options.scss
@@ -53,20 +53,6 @@
.discourse-touch & {
z-index: z("mobile-composer");
}
-
- .shortcut {
- line-height: 1;
- vertical-align: middle;
-
- &.--apple {
- letter-spacing: 0.25em;
- padding-right: 0.35em;
- }
-
- @include viewport.until(sm) {
- display: none;
- }
- }
}
.fk-d-menu[class*="toolbar-menu"] .dropdown-menu__header {
@@ -76,40 +62,23 @@
}
.toolbar-menu__options-content,
-.toolbar-menu__list-content,
-.toolbar-menu__heading-content {
+.toolbar-menu__heading-content,
+.toolbar-menu__list-content {
.dropdown-menu {
.btn {
+ // The label is block content, so the button counts as icon-only and
+ // drops the gap after its icon; restore the labelled-button gap.
+ &.no-text .d-icon {
+ margin-right: 0.45em;
+ }
+
&.--active {
.d-button-label__active-icon {
visibility: visible;
margin-left: auto;
}
}
- }
-
- .d-button-label {
- display: flex;
- flex: 1;
- justify-content: space-between;
- align-items: center;
- min-width: 0; // shrink if needed
-
- &__active-icon {
- visibility: hidden;
- }
-
- .shortcut {
- margin-left: var(--space-4);
- }
- }
- }
-}
-.toolbar-menu__heading-content,
-.toolbar-menu__list-content {
- .dropdown-menu {
- .btn {
&:hover,
&:focus,
&:focus-visible {
@@ -125,10 +94,11 @@
.d-button-label {
position: relative;
- flex-grow: 1;
+ flex: 1;
display: flex;
align-items: center;
gap: var(--space-4);
+ min-width: 0; // shrink if needed
&__active-icon {
visibility: hidden;
@@ -144,8 +114,10 @@
top: 50%;
transform: translateY(-50%);
display: none;
- margin: 0;
- font-size: var(--font-down-1-rem);
+
+ &.--always-visible {
+ display: block;
+ }
}
}
}
diff --git a/app/assets/stylesheets/common/ui-kit/_index.scss b/app/assets/stylesheets/common/ui-kit/_index.scss
index 408240ad4ba..fcc37145fb3 100644
--- a/app/assets/stylesheets/common/ui-kit/_index.scss
+++ b/app/assets/stylesheets/common/ui-kit/_index.scss
@@ -6,3 +6,4 @@
@import "d-pointer-drag";
@import "d-resize-separator";
@import "d-drag-and-drop";
+@import "d-shortcut";
diff --git a/app/assets/stylesheets/common/ui-kit/d-shortcut.scss b/app/assets/stylesheets/common/ui-kit/d-shortcut.scss
new file mode 100644
index 00000000000..b9ba28b1cb4
--- /dev/null
+++ b/app/assets/stylesheets/common/ui-kit/d-shortcut.scss
@@ -0,0 +1,56 @@
+/* The one look for every displayed shortcut: a single chip around the whole
+ combination, keys separated by a gap. Both selectors reset everything the
+ app-wide `kbd` rule sets and outrank a surface's own `kbd` rule. */
+
+kbd.d-shortcut {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 0;
+ flex: none;
+ box-sizing: border-box;
+ min-width: 0;
+ margin: 0;
+ padding: var(--space-half) var(--space-2);
+ border: 0;
+ border-radius: var(--d-border-radius);
+ background: var(--primary-low);
+ color: var(--primary-high);
+ font-family: var(--font-family);
+ font-size: var(--font-down-1);
+ font-weight: 600;
+ line-height: var(--line-height-medium);
+ vertical-align: middle;
+ white-space: nowrap;
+}
+
+.btn > .d-shortcut {
+ margin-left: var(--space-2);
+}
+
+.d-shortcut .d-shortcut__key {
+ display: inline;
+ gap: 0;
+ flex: none;
+ box-sizing: border-box;
+ min-width: 0;
+ margin: 0;
+ padding: 0;
+ border: 0;
+ border-radius: 0;
+ background: none;
+ color: inherit;
+ font: inherit;
+ line-height: inherit;
+}
+
+/* Keys are spaced out, except that modifier glyphs run together (⌘⇧ D). The
+ chip is always left-to-right, so the gap is logical rather than physical. */
+
+.d-shortcut .d-shortcut__key + .d-shortcut__key {
+ margin-inline-start: var(--space-2);
+}
+
+.d-shortcut .d-shortcut__key--glyph + .d-shortcut__key--glyph {
+ margin-inline-start: 0;
+}
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 99e40e38a95..5b70c1f299c 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -3274,6 +3274,36 @@ en:
ctrl: "Ctrl"
alt: "Alt"
enter: "Enter"
+ command: "Command"
+ option: "Option"
+ control: "Control"
+ arrow_up: "Up arrow"
+ arrow_down: "Down arrow"
+ arrow_left: "Left arrow"
+ arrow_right: "Right arrow"
+ period: "Period"
+ comma: "Comma"
+ slash: "Slash"
+ backslash: "Backslash"
+ question_mark: "Question mark"
+ exclamation_mark: "Exclamation mark"
+ hash: "Hash"
+ equals: "Equals"
+ minus: "Minus"
+ plus: "Plus"
+ semicolon: "Semicolon"
+ apostrophe: "Apostrophe"
+ backquote: "Backquote"
+ left_bracket: "Left bracket"
+ right_bracket: "Right bracket"
+ space: "Space"
+ tab: "Tab"
+ backspace: "Backspace"
+ delete: "Delete"
+ home: "Home"
+ end: "End"
+ page_up: "Page up"
+ page_down: "Page down"
conditional_loading_section:
loading: Loading…
@@ -3569,7 +3599,7 @@ en:
create_whisper: "Whisper"
create_shared_draft: "Create Shared Draft"
edit_shared_draft: "Edit Shared Draft"
- title: "Or press %{modifier}Enter"
+ submit_shortcut_title: "Or press %{shortcut}"
save_and_close: "Save and close"
discard: "Discard"
cancel_edit: "Cancel edit"
@@ -3598,6 +3628,8 @@ en:
switch_to_markdown: "Switch to standard Markdown editor (%{keyboardShortcut})"
switch_to_rich_text: "Switch to new rich text editor (%{keyboardShortcut})"
+ switch_to_markdown_no_shortcut: "Switch to standard Markdown editor"
+ switch_to_rich_text_no_shortcut: "Switch to new rich text editor"
quote_post_title: "Quote whole post"
bold_label: "B"
bold_title: "Strong"
@@ -3992,7 +4024,6 @@ en:
in: "filters by metadata (e.g. in:title, in:personal, in:pinned)"
status: "filters by topic status"
full_search: "launches full page search"
- full_search_key: "%{modifier} + Enter"
me: "shows only your posts"
advanced:
@@ -5851,12 +5882,8 @@ en:
keyboard_shortcuts_help:
search_label: "Search shortcuts"
search_placeholder: "Search for a shortcut by description or key combination"
- shortcut_key_delimiter_comma: ", "
- shortcut_key_delimiter_plus: "+"
shortcut_delimiter_or: "%{shortcut1} or %{shortcut2}"
shortcut_delimiter_slash: "%{shortcut1}/%{shortcut2}"
- shortcut_delimiter_space: "%{shortcut1} %{shortcut2}"
- shortcut_delimiter_newline: "%{shortcut1}<br>%{shortcut2}"
title: "Keyboard Shortcuts"
short_title: "Shortcuts"
search_ctrl_f_tip: "To search across this entire forum, press <kbd>/</kbd>"
@@ -7042,7 +7069,8 @@ en:
header_description: "Configure search settings including logging and tokenization for Chinese and Japanese languages"
search_everything:
title: "Search"
- header_description: "Find anything in the admin interface here. You can filter the results below, and your preferences will be remembered. To open this search anywhere in the admin interface, press %{shortcutHTML}."
+ header_description: "Find anything in the admin interface here. You can filter the results below, and your preferences will be remembered."
+ header_shortcut: "To open this search anywhere in the admin interface, press %{shortcutHTML}."
security:
title: "Security"
header_description: "Configure security settings, including two-factor authentication, moderator privileges, and content security policies"
diff --git a/frontend/discourse/admin/controllers/admin-search/index.js b/frontend/discourse/admin/controllers/admin-search/index.js
index 4bd71a0ac97..acfbd5ea603 100644
--- a/frontend/discourse/admin/controllers/admin-search/index.js
+++ b/frontend/discourse/admin/controllers/admin-search/index.js
@@ -1,11 +1,27 @@
import Controller from "@ember/controller";
-import { translateModKey } from "discourse/lib/utilities";
-import { PLATFORM_KEY_MODIFIER } from "discourse/services/keyboard-shortcuts";
+import { service } from "@ember/service";
+import { formatShortcut } from "discourse/lib/shortcut-format";
+import { i18n } from "discourse-i18n";
export default class AdminSearchIndexController extends Controller {
+ @service capabilities;
+
queryParams = ["filter"];
- get shortcutHTML() {
- return `<kbd>${translateModKey(PLATFORM_KEY_MODIFIER)}</kbd> <kbd>/</kbd>`;
+ /** The page description, mentioning the shortcut only where there is a keyboard to press it. */
+ get description() {
+ const description = i18n(
+ "admin.config.search_everything.header_description"
+ );
+
+ if (!this.capabilities.hasKeyboard) {
+ return description;
+ }
+
+ const shortcutHTML = formatShortcut("mod+/")
+ .keys.map((key) => `<kbd>${key.label}</kbd>`)
+ .join(" ");
+
+ return `${description} ${i18n("admin.config.search_everything.header_shortcut", { shortcutHTML })}`;
}
}
diff --git a/frontend/discourse/admin/templates/admin-search/index.gjs b/frontend/discourse/admin/templates/admin-search/index.gjs
index 6f064ea831e..e1dd51d0eb9 100644
--- a/frontend/discourse/admin/templates/admin-search/index.gjs
+++ b/frontend/discourse/admin/templates/admin-search/index.gjs
@@ -6,10 +6,7 @@ import { i18n } from "discourse-i18n";
export default <template>
<DPageHeader
@titleLabel={{i18n "admin.config.search_everything.title"}}
- @descriptionLabel={{i18n
- "admin.config.search_everything.header_description"
- }}
+ @descriptionLabel={{@controller.description}}
@shouldDisplay={{true}}
>
<:breadcrumbs>
diff --git a/frontend/discourse/app/components/composer-save-button.gjs b/frontend/discourse/app/components/composer-save-button.gjs
index f918c55489f..ad26c0bd3ba 100644
--- a/frontend/discourse/app/components/composer-save-button.gjs
+++ b/frontend/discourse/app/components/composer-save-button.gjs
@@ -1,13 +1,23 @@
import Component from "@glimmer/component";
+import { service } from "@ember/service";
+import { formatShortcut } from "discourse/lib/shortcut-format";
import { applyValueTransformer } from "discourse/lib/transformer";
-import { translateModKey } from "discourse/lib/utilities";
import DButton from "discourse/ui-kit/d-button";
import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
import { i18n } from "discourse-i18n";
export default class ComposerSaveButton extends Component {
+ @service capabilities;
+
+ shortcut = formatShortcut("mod+enter");
+
get translatedTitle() {
- return i18n("composer.title", { modifier: translateModKey("Meta+") });
+ if (!this.capabilities.hasKeyboard) {
+ return;
+ }
+ return i18n("composer.submit_shortcut_title", {
+ shortcut: this.shortcut.label,
+ });
}
get label() {
@@ -16,14 +26,14 @@ export default class ComposerSaveButton extends Component {
<template>
<DButton
+ class={{dConcatClass "btn-primary create" (if @disableSubmit "disabled")}}
+ aria-keyshortcuts={{if this.capabilities.hasKeyboard this.shortcut.aria}}
+ ...attributes
@action={{@action}}
- @label={{this.label}}
+ @forwardEvent={{@forwardEvent}}
@icon={{@icon}}
+ @label={{this.label}}
@translatedTitle={{this.translatedTitle}}
- @forwardEvent={{@forwardEvent}}
- class={{dConcatClass "btn-primary create" (if @disableSubmit "disabled")}}
- aria-keyshortcuts={{translateModKey "Meta+Enter" "+"}}
- ...attributes
/>
</template>
}
diff --git a/frontend/discourse/app/components/composer/toggle-switch.gjs b/frontend/discourse/app/components/composer/toggle-switch.gjs
index 0c5d2a7e9eb..64429d2506f 100644
--- a/frontend/discourse/app/components/composer/toggle-switch.gjs
+++ b/frontend/discourse/app/components/composer/toggle-switch.gjs
@@ -1,12 +1,17 @@
import Component from "@glimmer/component";
import { on } from "@ember/modifier";
import { action } from "@ember/object";
-import { translateModKey } from "discourse/lib/utilities";
+import { service } from "@ember/service";
+import { formatShortcut } from "discourse/lib/shortcut-format";
import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
import dIcon from "discourse/ui-kit/helpers/d-icon";
import { i18n } from "discourse-i18n";
export default class ComposerToggleSwitch extends Component {
+ @service capabilities;
+
+ shortcut = formatShortcut("ctrl+m");
+
@action
mouseDown(event) {
if (this.args.preventFocus) {
@@ -25,23 +30,13 @@ export default class ComposerToggleSwitch extends Component {
}
get label() {
- if (this.args.state) {
- return i18n("composer.switch_to_markdown", {
- keyboardShortcut: this.keyboardShortcut,
- });
- } else {
- return i18n("composer.switch_to_rich_text", {
- keyboardShortcut: this.keyboardShortcut,
- });
+ const key = this.args.state
+ ? "composer.switch_to_markdown"
+ : "composer.switch_to_rich_text";
+ if (!this.capabilities.hasKeyboard) {
+ return i18n(`${key}_no_shortcut`);
}
- }
-
- get keyboardShortcut() {
- return `${translateModKey("ctrl")} M`;
- }
-
- get ariaKeyshortcuts() {
- return this.keyboardShortcut.replace(/ /g, "+");
+ return i18n(key, { keyboardShortcut: this.shortcut.label });
}
<template>
@@ -56,12 +51,12 @@ export default class ComposerToggleSwitch extends Component {
disabled={{@disabled}}
aria-checked={{if @state "true" "false"}}
aria-label={{this.label}}
- aria-keyshortcuts={{this.ariaKeyshortcuts}}
+ aria-keyshortcuts={{if this.capabilities.hasKeyboard this.shortcut.aria}}
title={{this.label}}
- {{on "mousedown" this.mouseDown}}
- {{on "keydown" this.handleKeydown}}
data-rich-editor={{@state}}
...attributes
+ {{on "mousedown" this.mouseDown}}
+ {{on "keydown" this.handleKeydown}}
>
<span class="composer-toggle-switch__slider">
<span
diff --git a/frontend/discourse/app/components/composer/toolbar-buttons.gjs b/frontend/discourse/app/components/composer/toolbar-buttons.gjs
index fa25c3bc1f3..5ec4de524bf 100644
--- a/frontend/discourse/app/components/composer/toolbar-buttons.gjs
+++ b/frontend/discourse/app/components/composer/toolbar-buttons.gjs
@@ -3,6 +3,7 @@ import { action } from "@ember/object";
import ToolbarPopupMenuOptions from "discourse/components/toolbar-popup-menu-options";
import { eq } from "discourse/truth-helpers";
import DButton from "discourse/ui-kit/d-button";
+import DShortcut from "discourse/ui-kit/d-shortcut";
import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
export default class ComposerToolbarButtons extends Component {
@@ -29,6 +30,15 @@ export default class ComposerToolbarButtons extends Component {
return this.args.rovingButtonBar || this.args.data.rovingButtonBar;
}
+ /** The title with the drawn shortcut appended, when one is shown. */
+ @action
+ titleFor(button, shortcutLabel) {
+ if (!shortcutLabel || button.hideShortcutInTitle) {
+ return button.title;
+ }
+ return `${button.title} (${shortcutLabel})`;
+ }
+
@action
isButtonActive(button) {
const state = this.args.data.context?.textManipulation?.state || {};
@@ -59,26 +69,28 @@ export default class ComposerToolbarButtons extends Component {
}}
/>
{{else}}
- <DButton
- @href={{button.href}}
- @action={{unless button.href button.action}}
- @translatedTitle={{button.title}}
- @label={{button.label}}
- @translatedLabel={{button.translatedLabel}}
- @disabled={{button.disabled}}
- @icon={{button.icon}}
- @preventFocus={{button.preventFocus}}
- @onKeyDown={{this.rovingButtonBar}}
- aria-keyshortcuts={{button.ariaKeyshortcuts}}
- tabindex={{this.tabIndex button}}
- class={{dConcatClass
- "toolbar__button"
- button.className
- (if (this.isButtonActive button) "--active")
- }}
- rel={{if button.href "noopener noreferrer"}}
- target={{if button.href "_blank"}}
- />
+ <DShortcut @keys={{button.shortcutKeys}} as |shortcut|>
+ <DButton
+ class={{dConcatClass
+ "toolbar__button"
+ button.className
+ (if (this.isButtonActive button) "--active")
+ }}
+ aria-keyshortcuts={{shortcut.aria}}
+ tabindex={{this.tabIndex button}}
+ rel={{if button.href "noopener noreferrer"}}
+ target={{if button.href "_blank"}}
+ @action={{unless button.href button.action}}
+ @disabled={{button.disabled}}
+ @href={{button.href}}
+ @icon={{button.icon}}
+ @label={{button.label}}
+ @onKeyDown={{this.rovingButtonBar}}
+ @preventFocus={{button.preventFocus}}
+ @translatedLabel={{button.translatedLabel}}
+ @translatedTitle={{this.titleFor button shortcut.label}}
+ />
+ </DShortcut>
{{/if}}
{{/if}}
{{/each}}
diff --git a/frontend/discourse/app/components/fast-edit.gjs b/frontend/discourse/app/components/fast-edit.gjs
index e9b86275e55..37d60e341aa 100644
--- a/frontend/discourse/app/components/fast-edit.gjs
+++ b/frontend/discourse/app/components/fast-edit.gjs
@@ -2,23 +2,33 @@ import Component from "@glimmer/component";
import { tracked } from "@glimmer/tracking";
import { on } from "@ember/modifier";
import { action } from "@ember/object";
+import { service } from "@ember/service";
import PluginOutlet from "discourse/components/plugin-outlet";
import lazyHash from "discourse/helpers/lazy-hash";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import { translateModKey } from "discourse/lib/utilities";
+import { formatShortcut } from "discourse/lib/shortcut-format";
import preventScrollOnFocus from "discourse/modifiers/prevent-scroll-on-focus";
import DButton from "discourse/ui-kit/d-button";
import dAutoFocus from "discourse/ui-kit/modifiers/d-auto-focus";
import { i18n } from "discourse-i18n";
export default class FastEdit extends Component {
+ @service capabilities;
+
@tracked isSaving = false;
@tracked value = this.args.newValue || this.args.initialValue;
- buttonTitle = i18n("composer.title", {
- modifier: translateModKey("Meta+"),
- });
+ shortcut = formatShortcut("mod+enter");
+
+ get buttonTitle() {
+ if (!this.capabilities.hasKeyboard) {
+ return;
+ }
+ return i18n("composer.submit_shortcut_title", {
+ shortcut: this.shortcut.label,
+ });
+ }
get disabled() {
return this.value === this.args.initialValue;
@@ -83,12 +93,16 @@ export default class FastEdit extends Component {
<div class="fast-edit-container__footer">
<DButton
class="btn-small btn-primary save-fast-edit"
+ aria-keyshortcuts={{if
+ this.capabilities.hasKeyboard
+ this.shortcut.aria
+ }}
@action={{this.save}}
+ @disabled={{this.disabled}}
@icon="pencil"
+ @isLoading={{this.isSaving}}
@label="composer.save_edit"
@translatedTitle={{this.buttonTitle}}
- @isLoading={{this.isSaving}}
- @disabled={{this.disabled}}
/>
<PluginOutlet
diff --git a/frontend/discourse/app/components/modal/keyboard-shortcuts-help.gjs b/frontend/discourse/app/components/modal/keyboard-shortcuts-help.gjs
index 452509d4603..84fd83d8b3c 100644
--- a/frontend/discourse/app/components/modal/keyboard-shortcuts-help.gjs
+++ b/frontend/discourse/app/components/modal/keyboard-shortcuts-help.gjs
@@ -4,117 +4,83 @@ import { concat } from "@ember/helper";
import { action } from "@ember/object";
import { service } from "@ember/service";
import { trustHTML } from "@ember/template";
-import { translateModKey } from "discourse/lib/utilities";
+import { formatShortcut } from "discourse/lib/shortcut-format";
+import { capabilities } from "discourse/services/capabilities";
import { extraKeyboardShortcutsHelp } from "discourse/services/keyboard-shortcuts";
+import { eq } from "discourse/truth-helpers";
import DFilterInput from "discourse/ui-kit/d-filter-input";
+import DInterpolatedTranslation from "discourse/ui-kit/d-interpolated-translation";
import DModal from "discourse/ui-kit/d-modal";
+import DShortcut from "discourse/ui-kit/d-shortcut";
import { i18n } from "discourse-i18n";
const KEY = "keyboard_shortcuts_help";
-const SHIFT = i18n("shortcut_modifier_key.shift");
-const ALT = translateModKey("Alt");
-const META = translateModKey("Meta");
-const CTRL = i18n("shortcut_modifier_key.ctrl");
-const ENTER = i18n("shortcut_modifier_key.enter");
-const ESC = i18n("shortcut_modifier_key.esc");
-const COMMA = i18n(`${KEY}.shortcut_key_delimiter_comma`);
-const translationForExtraShortcuts = {
- shift: SHIFT,
- alt: ALT,
- meta: META,
- ctrl: CTRL,
- enter: ENTER,
- esc: ESC,
- comma: COMMA,
-};
-
-const SEARCH_ALIASES = new Map();
-function addSearchAlias(key, aliasKey) {
- // Some platforms render distinct keys (e.g. Meta and Ctrl) with the same
- // string. Merge aliases so both semantic names remain searchable.
- const alias = i18n(`${KEY}.search_aliases.${aliasKey}`);
- const existing = SEARCH_ALIASES.get(key);
- SEARCH_ALIASES.set(key, existing ? `${existing} ${alias}` : alias);
-}
-addSearchAlias(SHIFT, "shift");
-addSearchAlias(ALT, "alt");
-addSearchAlias(META, "meta");
-addSearchAlias(CTRL, "ctrl");
-addSearchAlias(ENTER, "enter");
-addSearchAlias(ESC, "esc");
+const SHIFT = "shift";
+const ALT = "alt";
+const META = "mod";
+const CTRL = "ctrl";
+const ENTER = "enter";
+const ESC = "esc";
-function buildHTML(keys1, keys2, shortcutsDelimiter) {
- const allKeys = [keys1, keys2]
- .filter((keys) => keys.length !== 0)
- .map((keys) =>
- keys
- .map((key) => {
- // Turns e.g. c into C and esc into Esc
- key = key.charAt(0).toUpperCase() + key.slice(1);
- return `<kbd>${key}</kbd>`;
- })
- .join(" ")
- )
- .map((keys) =>
- shortcutsDelimiter !== "space" && shortcutsDelimiter !== "newline"
- ? wrapInSpan(keys, shortcutsDelimiter)
- : keys
- );
+/** The search alias set(s) a canonical key contributes to the filter index. */
+const SEARCH_ALIAS_KEYS = {
+ Shift: ["shift"],
+ Alt: ["alt"],
+ Meta: ["meta"],
+ Control: ["ctrl"],
+ Enter: ["enter"],
+ Escape: ["esc"],
+};
- const [shortcut1, shortcut2] = allKeys;
+function searchAliases(key) {
+ const aliasKeys = [...(SEARCH_ALIAS_KEYS[key] ?? [])];
- if (allKeys.length === 1) {
- return shortcut1;
- } else if (shortcutsDelimiter === "or") {
- return i18n(`${KEY}.shortcut_delimiter_or`, { shortcut1, shortcut2 });
- } else if (shortcutsDelimiter === "slash") {
- return i18n(`${KEY}.shortcut_delimiter_slash`, { shortcut1, shortcut2 });
- } else if (shortcutsDelimiter === "space") {
- return wrapInSpan(
- i18n(`${KEY}.shortcut_delimiter_space`, { shortcut1, shortcut2 }),
- shortcutsDelimiter
- );
- } else if (shortcutsDelimiter === "newline") {
- return wrapInSpan(
- i18n(`${KEY}.shortcut_delimiter_newline`, {
- shortcut1,
- shortcut2,
- }),
- shortcutsDelimiter
- );
+ // Where the platform modifier draws as Control, the semantic names of both
+ // keys must stay searchable, since a user may type either.
+ if (key === "Control" && !capabilities.isApple) {
+ aliasKeys.push("meta");
}
-}
-function wrapInSpan(shortcut, delimiter) {
- return `<span class="delimiter-${delimiter}" dir="ltr">${shortcut}</span>`;
+ return aliasKeys.map((aliasKey) => i18n(`${KEY}.search_aliases.${aliasKey}`));
}
function buildSearchText(keys) {
- return keys
- .flatMap((k) => {
- const alias = SEARCH_ALIASES.get(k);
- return alias ? [k, alias] : [k];
- })
+ return formatShortcut(keys.join("+"))
+ .keys.flatMap((key) => [
+ key.label,
+ key.name !== key.label ? key.name : null,
+ ...searchAliases(key.key),
+ ])
+ .filter(Boolean)
.join(" ");
}
+/** How two key groups of one help entry relate; anything else falls back to "or". */
+const SHORTCUT_DELIMITERS = ["or", "slash", "space", "newline"];
+
function buildShortcut(
key,
{ keys1 = [], keys2 = [], shortcutsDelimiter = "or" }
) {
+ const groups = [keys1, keys2].filter((keys) => keys.length > 0);
+ const delimiter = SHORTCUT_DELIMITERS.includes(shortcutsDelimiter)
+ ? shortcutsDelimiter
+ : "or";
+
// "space"/"newline" mean keys1 then keys2 are pressed in sequence — one
// searchable combination. "or"/"slash" mean alternatives — each group
// searched independently so tokens can't span alternatives
// (e.g. "ctrl /" must not match a "/ or Ctrl+Alt+F" shortcut).
- const isSequence =
- shortcutsDelimiter === "space" || shortcutsDelimiter === "newline";
+ const isSequence = delimiter === "space" || delimiter === "newline";
const shortcutTexts = isSequence
- ? [buildSearchText([...keys1, ...keys2])]
- : [keys1, keys2].filter((keys) => keys.length > 0).map(buildSearchText);
+ ? [buildSearchText(groups.flat())]
+ : groups.map(buildSearchText);
return {
- shortcut: buildHTML(keys1, keys2, shortcutsDelimiter),
+ keys1: groups[0]?.join("+"),
+ keys2: groups[1]?.join("+"),
+ delimiter,
shortcutTexts,
description: i18n(`${KEY}.${key}`, { shortcut: "" }).trim(),
};
@@ -335,15 +301,15 @@ export default class KeyboardShortcutsHelp extends Component {
search_menu: {
shortcuts: {
prev_next: buildShortcut("search_menu.prev_next", {
- keys1: ["&uarr;"],
- keys2: ["&darr;"],
+ keys1: ["up"],
+ keys2: ["down"],
shortcutsDelimiter: "slash",
}),
insert_url: buildShortcut("search_menu.insert_url", {
keys1: ["a"],
}),
full_page_search: buildShortcut("search_menu.full_page_search", {
- keys1: [META, "Enter"],
+ keys1: [META, ENTER],
}),
},
},
@@ -355,12 +321,12 @@ export default class KeyboardShortcutsHelp extends Component {
keys1: [META, "/"],
}),
admin_search_prev_next: buildShortcut("admin.search_prev_next", {
- keys1: ["&uarr;"],
- keys2: ["&darr;"],
+ keys1: ["up"],
+ keys2: ["down"],
shortcutsDelimiter: "slash",
}),
admin_search_full_page: buildShortcut("admin.search_full_page", {
- keys1: ["Enter"],
+ keys1: [ENTER],
}),
},
};
@@ -435,7 +401,7 @@ export default class KeyboardShortcutsHelp extends Component {
shortcuts[category].shortcuts[help.name] = buildShortcut(
help.name,
- this._transformExtraDefinition(help.definition)
+ help.definition
);
});
}
@@ -449,37 +415,6 @@ export default class KeyboardShortcutsHelp extends Component {
}
}
- _transformExtraDefinition(definition) {
- if (definition.keys1) {
- definition.keys1 = definition.keys1.map((key) =>
- this._translateKeys(key)
- );
- }
- if (definition.keys2) {
- definition.keys2 = definition.keys2.map((key) =>
- this._translateKeys(key)
- );
- }
- if (definition.keysDelimiter) {
- definition.keysDelimiter = this._translateKeys(definition.keysDelimiter);
- }
- if (definition.shortcutsDelimiter) {
- definition.shortcutsDelimiter = this._translateKeys(
- definition.shortcutsDelimiter
- );
- }
- return definition;
- }
-
- _translateKeys(string) {
- for (const [matcher, replacement] of Object.entries(
- translationForExtraShortcuts
- )) {
- string = string.replace(matcher, replacement);
- }
- return string;
- }
-
_buildJumpToSection() {
const shortcuts = {
home: buildShortcut("jump_to.home", { keys1: ["g", "h"] }),
@@ -553,9 +488,57 @@ export default class KeyboardShortcutsHelp extends Component {
<td class="shortcut-description">{{trustHTML
pair.description
}}</td>
- <td class="shortcut-key">{{trustHTML
- pair.shortcut
- }}</td>
+ <td class="shortcut-key">
+ {{#if pair.keys2}}
+ {{#if (eq pair.delimiter "space")}}
+ <span class="delimiter-space" dir="ltr">
+ <DShortcut
+ @always={{true}}
+ @keys={{pair.keys1}}
+ />
+ <DShortcut
+ @always={{true}}
+ @keys={{pair.keys2}}
+ />
+ </span>
+ {{else if (eq pair.delimiter "newline")}}
+ <span class="delimiter-newline" dir="ltr">
+ <DShortcut
+ @always={{true}}
+ @keys={{pair.keys1}}
+ />
+ <br />
+ <DShortcut
+ @always={{true}}
+ @keys={{pair.keys2}}
+ />
+ </span>
+ {{else}}
+ <DInterpolatedTranslation
+ @key={{concat
+ "keyboard_shortcuts_help.shortcut_delimiter_"
+ pair.delimiter
+ }}
+ as |Placeholder|
+ >
+ <Placeholder @name="shortcut1">
+ <DShortcut
+ @always={{true}}
+ @keys={{pair.keys1}}
+ />
+ </Placeholder>
+ <Placeholder @name="shortcut2">
+ <DShortcut
+ @always={{true}}
+ @keys={{pair.keys2}}
+ />
+ </Placeholder>
+ </DInterpolatedTranslation>
+ {{/if}}
+ {{else}}
+ <DShortcut @always={{true}} @keys={{pair.keys1}} />
+ {{/if}}
+ </td>
</tr>
{{/each-in}}
</tbody>
diff --git a/frontend/discourse/app/components/search-menu/results/random-quick-tip.gjs b/frontend/discourse/app/components/search-menu/results/random-quick-tip.gjs
index 2c571105245..f0d4d322453 100644
--- a/frontend/discourse/app/components/search-menu/results/random-quick-tip.gjs
+++ b/frontend/discourse/app/components/search-menu/results/random-quick-tip.gjs
@@ -2,6 +2,7 @@ import Component from "@glimmer/component";
import { on } from "@ember/modifier";
import { action } from "@ember/object";
import { service } from "@ember/service";
+import DShortcut from "discourse/ui-kit/d-shortcut";
import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
import { i18n } from "discourse-i18n";
@@ -27,7 +28,7 @@ const DEFAULT_QUICK_TIPS = [
clickable: true,
},
{
- label: i18n("search.tips.full_search_key", { modifier: "Ctrl" }),
+ shortcut: "mod+enter",
description: i18n("search.tips.full_search"),
},
{
@@ -55,11 +56,18 @@ export function removeDefaultQuickSearchRandomTips() {
resetQuickSearchRandomTips();
export default class RandomQuickTip extends Component {
+ @service capabilities;
@service search;
constructor() {
super(...arguments);
- this.randomTip = QUICK_TIPS[Math.floor(Math.random() * QUICK_TIPS.length)];
+ // A tip about a key combination is no help without a keyboard to press
+ // it. The pick is made once per instance, so a keyboard noticed later
+ // shows up on the next open.
+ const tips = QUICK_TIPS.filter(
+ (tip) => !tip.shortcut || this.capabilities.hasKeyboard
+ );
+ this.randomTip = tips[Math.floor(Math.random() * tips.length)];
}
@action
@@ -83,7 +91,11 @@ export default class RandomQuickTip extends Component {
{{on "click" this.tipSelected}}
aria-describedby="tip-description"
>
- {{this.randomTip.label}}
+ {{#if this.randomTip.shortcut}}
+ <DShortcut @keys={{this.randomTip.shortcut}} />
+ {{else}}
+ {{this.randomTip.label}}
+ {{/if}}
</button>
<span id="tip-description">
diff --git a/frontend/discourse/app/components/sidebar/search.gjs b/frontend/discourse/app/components/sidebar/search.gjs
index 9312e1a6c26..169df29b102 100644
--- a/frontend/discourse/app/components/sidebar/search.gjs
+++ b/frontend/discourse/app/components/sidebar/search.gjs
@@ -2,8 +2,8 @@ import Component from "@glimmer/component";
import { on } from "@ember/modifier";
import { action } from "@ember/object";
import { service } from "@ember/service";
-import { translateModKey } from "discourse/lib/utilities";
import DButton from "discourse/ui-kit/d-button";
+import DShortcut from "discourse/ui-kit/d-shortcut";
import { i18n } from "discourse-i18n";
export default class Search extends Component {
@@ -13,10 +13,6 @@ export default class Search extends Component {
return this.sidebarState.currentPanel.searchable;
}
- get sidebarShortcutCombo() {
- return `${translateModKey("Meta")} /`;
- }
-
@action
onClick(event) {
event?.preventDefault();
@@ -32,17 +28,18 @@ export default class Search extends Component {
@icon="magnifying-glass"
class="btn-transparent sidebar-search__icon"
/>
- {{! eslint-disable ember/template-no-pointer-down-event-binding }}
- <input
- {{on "mousedown" this.onClick}}
- placeholder={{i18n "sidebar.search"}}
- type="text"
- enterkeyhint="done"
- class="sidebar-search__input"
- />
- <span
- class="sidebar-search__shortcut-hint"
- >{{this.sidebarShortcutCombo}}</span>
+ <DShortcut @keys="mod+/" as |shortcut|>
+ {{! eslint-disable ember/template-no-pointer-down-event-binding }}
+ <input
+ placeholder={{i18n "sidebar.search"}}
+ type="text"
+ enterkeyhint="done"
+ class="sidebar-search__input"
+ aria-keyshortcuts={{shortcut.aria}}
+ {{on "mousedown" this.onClick}}
+ />
+ <shortcut.Kbd class="sidebar-search__shortcut-hint" />
+ </DShortcut>
</div>
</div>
{{/if}}
diff --git a/frontend/discourse/app/components/toolbar-popup-menu-options.gjs b/frontend/discourse/app/components/toolbar-popup-menu-options.gjs
index 248b1dc2e9c..9dd9a03875a 100644
--- a/frontend/discourse/app/components/toolbar-popup-menu-options.gjs
+++ b/frontend/discourse/app/components/toolbar-popup-menu-options.gjs
@@ -2,14 +2,12 @@ import Component from "@glimmer/component";
import { array, concat, fn } from "@ember/helper";
import { action } from "@ember/object";
import { service } from "@ember/service";
-import { trustHTML } from "@ember/template";
import { modifier } from "ember-modifier";
import DMenu from "discourse/float-kit/components/d-menu";
-import { iconHTML } from "discourse/lib/icon-library";
-import { translateModKey } from "discourse/lib/utilities";
-import { PLATFORM_KEY_MODIFIER } from "discourse/services/keyboard-shortcuts";
+import { formatShortcut } from "discourse/lib/shortcut-format";
import DButton from "discourse/ui-kit/d-button";
import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import DShortcut from "discourse/ui-kit/d-shortcut";
import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
import dIcon from "discourse/ui-kit/helpers/d-icon";
import { i18n } from "discourse-i18n";
@@ -66,76 +64,49 @@ export default class ToolbarPopupMenuOptions extends Component {
#convertMenuOption(content) {
if (content.condition !== false) {
- const label = this.#calculateLabel(content);
- const title = this.#calculateTitle(content);
+ const shortcutKeys = content.shortcut
+ ? `mod+${content.shortcut}`
+ : undefined;
+ const labelText = this.#calculateLabelText(content);
+ const title = this.#calculateTitle(content, labelText, shortcutKeys);
return Object.defineProperties(
{},
- Object.getOwnPropertyDescriptors({ ...content, label, title })
+ Object.getOwnPropertyDescriptors({
+ ...content,
+ labelText,
+ title,
+ shortcutKeys,
+ })
);
}
}
- #calculateTitle(content) {
- if (content.label && !content.title && !content.translatedTitle) {
- return this.#calculateLabel(content, { textOnly: true });
- }
-
- if (!content.translatedTitle && !content.title) {
- return;
- }
-
- const title = content.translatedTitle
- ? content.translatedTitle
- : i18n(content.title);
-
- if (content.shortcut) {
- return `${title} (${translateModKey(
- PLATFORM_KEY_MODIFIER + "+" + content.shortcut
- )})`;
- }
-
- return title;
- }
-
- #calculateLabel(content, opts = {}) {
+ #calculateLabelText(content) {
if (!content.label && !content.translatedLabel) {
return;
}
- const label = content.translatedLabel
+ return content.translatedLabel
? content.translatedLabel
: i18n(content.label);
+ }
- if (opts.textOnly) {
- if (content.shortcut) {
- return `${label} (${translateModKey(
- PLATFORM_KEY_MODIFIER + "+" + content.shortcut
- )})`;
- }
-
- return label;
- }
-
- let htmlLabel = `<span class="d-button-label__text">${label}</span>`;
- if (content.shortcut) {
- const separator = this.capabilities.isApple ? "" : " ";
- const platformClass = this.capabilities.isApple ? "--apple" : "";
- htmlLabel += ` <kbd class="shortcut ${platformClass} ${
- content.alwaysShowShortcut ? "--always-visible" : ""
- }">${translateModKey(
- PLATFORM_KEY_MODIFIER + "+" + content.shortcut,
- separator
- )}</kbd>`;
- }
+ /**
+ * A labelled row draws its shortcut, so its title carries none; an
+ * icon-only row has nowhere else to show it.
+ */
+ #calculateTitle(content, labelText, shortcutKeys) {
+ const title = content.translatedTitle
+ ? content.translatedTitle
+ : content.title
+ ? i18n(content.title)
+ : labelText;
- if (content.showActiveIcon) {
- htmlLabel += iconHTML("check", {
- class: "d-button-label__active-icon",
- });
+ if (labelText || !shortcutKeys || !this.capabilities.hasKeyboard) {
+ return title;
}
-
- return trustHTML(htmlLabel);
+ return `${title} (${formatShortcut(shortcutKeys).label})`;
}
get convertedContent() {
@@ -202,15 +173,33 @@ export default class ToolbarPopupMenuOptions extends Component {
{{/if}}
{{#each this.convertedContent as |option|}}
<dropdown.item>
- <DButton
- @translatedLabel={{option.label}}
- @translatedTitle={{option.title}}
- @icon={{this.getIcon option}}
- @action={{fn this.onSelect option}}
- data-name={{option.name}}
- class={{dConcatClass (if (this.getActive option) "--active")}}
- aria-keyshortcuts={{option.ariaKeyshortcuts}}
- />
+ <DShortcut @keys={{option.shortcutKeys}} as |shortcut|>
+ <DButton
+ class={{dConcatClass (if (this.getActive option) "--active")}}
+ data-name={{option.name}}
+ aria-keyshortcuts={{shortcut.aria}}
+ @action={{fn this.onSelect option}}
+ @icon={{this.getIcon option}}
+ @translatedTitle={{option.title}}
+ >
+ {{#if option.labelText}}
+ <span class="d-button-label">
+ <span class="d-button-label__text">
+ {{option.labelText}}
+ </span>
+ <shortcut.Kbd
+ class={{dConcatClass
+ "shortcut"
+ (if option.alwaysShowShortcut "--always-visible")
+ }}
+ />
+ {{#if option.showActiveIcon}}
+ {{dIcon "check" class="d-button-label__active-icon"}}
+ {{/if}}
+ </span>
+ {{/if}}
+ </DButton>
+ </DShortcut>
</dropdown.item>
{{/each}}
</DDropdownMenu>
diff --git a/frontend/discourse/app/controllers/preferences/interface.js b/frontend/discourse/app/controllers/preferences/interface.js
index 485e35d9e25..b4e154f77dc 100644
--- a/frontend/discourse/app/controllers/preferences/interface.js
+++ b/frontend/discourse/app/controllers/preferences/interface.js
@@ -16,6 +16,7 @@ import {
} from "discourse/lib/constants";
import { normalizeUnderstoodLanguages } from "discourse/lib/content-localization";
import { deepEqual } from "discourse/lib/object";
+import { formatShortcut } from "discourse/lib/shortcut-format";
import {
currentThemeId,
listThemes,
@@ -25,10 +26,8 @@ import { applyValueTransformer } from "discourse/lib/transformer";
import {
setDefaultHomepage,
siteDefaultHomepage,
- translateModKey,
} from "discourse/lib/utilities";
import { AUTO_DELETE_PREFERENCES } from "discourse/models/bookmark";
-import { PLATFORM_KEY_MODIFIER } from "discourse/services/keyboard-shortcuts";
import { i18n } from "discourse-i18n";
// same as UserOption::HOMEPAGES
@@ -174,7 +173,7 @@ export default class InterfaceController extends Controller {
},
{
name: i18n("user.send_shortcut.meta_enter", {
- meta_key: translateModKey(PLATFORM_KEY_MODIFIER),
+ meta_key: formatShortcut("mod").label,
}),
value: SEND_SHORTCUT_META_ENTER,
},
diff --git a/frontend/discourse/app/lib/composer/toolbar.ts b/frontend/discourse/app/lib/composer/toolbar.ts
index bba9a7e7507..9394f94f792 100644
--- a/frontend/discourse/app/lib/composer/toolbar.ts
+++ b/frontend/discourse/app/lib/composer/toolbar.ts
@@ -1,5 +1,4 @@
import { customPopupMenuOptions } from "discourse/lib/composer/custom-popup-menu-options";
-import { translateModKey } from "discourse/lib/utilities";
import { waitForClosedKeyboard } from "discourse/lib/wait-for-keyboard";
import type Site from "discourse/models/site";
import type { CapabilitiesService } from "discourse/services/capabilities";
@@ -69,8 +68,8 @@ export interface PopupMenuOption {
translatedTitle?: string;
/** Keyboard shortcut that invokes the option. */
shortcut?: string;
- /** Shortcut exposed to assistive technology. */
- ariaKeyshortcuts?: string;
+ /** The shortcut in binding spelling (`mod+b`), for display and announcement. */
+ shortcutKeys?: string;
/** Whether the option is available. */
condition: boolean | (() => boolean);
/** Whether the active option displays its status icon. */
@@ -121,8 +120,8 @@ export interface ToolbarButton {
title: string;
/** Keyboard shortcut that invokes the button. */
shortcut?: string;
- /** Shortcut exposed to assistive technology. */
- ariaKeyshortcuts?: string;
+ /** The shortcut in binding spelling (`mod+b`), for display and announcement. */
+ shortcutKeys?: string;
/** Whether the button is inserted at the beginning of its group. */
unshift?: boolean;
/** Reports whether the button matches the editor state. */
@@ -244,30 +243,19 @@ export class ToolbarBase {
};
// Main button shortcut bindings and title text.
+ // The shortcut suffix is added where the button renders, since it is
+ // shown only when a keyboard is likely.
const title = i18n(buttonAttrs.title || `composer.${buttonAttrs.id}_title`);
+ createdButton.title = title;
if (buttonAttrs.shortcut) {
- const shortcutKeyTranslated = translateModKey(
- buttonAttrs.shortcut.length === 1
- ? buttonAttrs.shortcut.toUpperCase()
- : buttonAttrs.shortcut
- );
- const shortcutTitle = `${translateModKey(
- PLATFORM_KEY_MODIFIER + " "
- )}${shortcutKeyTranslated}`;
-
- if (buttonAttrs.hideShortcutInTitle) {
- createdButton.title = title;
- } else {
- createdButton.title = `${title} (${shortcutTitle})`;
- }
+ createdButton.shortcutKeys = `mod+${buttonAttrs.shortcut}`;
+ createdButton.hideShortcutInTitle = buttonAttrs.hideShortcutInTitle;
// These shortcuts are actually bound in the keymap inside
// components/d-editor.gjs
this.shortcuts[
`${PLATFORM_KEY_MODIFIER}+${buttonAttrs.shortcut}`.toLowerCase()
] = createdButton;
-
- createdButton.ariaKeyshortcuts = shortcutTitle.replace(/\s/g, "+");
} else {
createdButton.title = title;
}
@@ -280,22 +268,13 @@ export class ToolbarBase {
buttonAttrs.popupMenu.options()?.forEach((option) => {
if (option.shortcut) {
- const shortcutKeyTranslated = translateModKey(
- option.shortcut.length === 1
- ? option.shortcut.toUpperCase()
- : option.shortcut
- );
- const shortcutTitle = `${translateModKey(
- PLATFORM_KEY_MODIFIER + " "
- )}${shortcutKeyTranslated}`;
+ option.shortcutKeys = `mod+${option.shortcut}`;
// These shortcuts are actually bound in the keymap inside
// components/d-editor.gjs
this.shortcuts[
`${PLATFORM_KEY_MODIFIER}+${option.shortcut}`.toLowerCase()
] = option;
-
- option.ariaKeyshortcuts = shortcutTitle.replace(/\s/g, "+");
}
});
}
diff --git a/frontend/discourse/app/lib/shortcut-format.ts b/frontend/discourse/app/lib/shortcut-format.ts
new file mode 100644
index 00000000000..5f9d1b4ad34
--- /dev/null
+++ b/frontend/discourse/app/lib/shortcut-format.ts
@@ -0,0 +1,244 @@
+import { capabilities } from "discourse/services/capabilities";
+import { i18n } from "discourse-i18n";
+
+/** One key of a formatted shortcut. */
+export interface ShortcutKey {
+ /**
+ * A canonical key name, matching `KeyboardEvent.key` except for `Space`:
+ * `Meta`, `Control`, `Alt`, `Shift`, `Enter`, `ArrowUp`, `B`, `/`.
+ */
+ key: string;
+ /** The drawn text: `⌘` on Apple platforms and `Ctrl` elsewhere, `↑`, `Enter`, `B`. */
+ label: string;
+ /**
+ * The text assistive technology should read for the drawn form. Differs from
+ * `label` when `label` is a glyph or punctuation, in which case it is the
+ * localized spelled-out name (`Command`, `Up arrow`, `Period`).
+ */
+ name: string;
+ /** Whether `label` is a modifier or arrow glyph, which run together when drawn. */
+ glyph: boolean;
+}
+
+/** Both forms of one shortcut, derived from a single spelling. */
+export interface FormattedShortcut {
+ keys: ShortcutKey[];
+ /** The drawn labels joined with a space: `⌘ Enter` / `Ctrl Enter`. */
+ label: string;
+ /**
+ * The `aria-keyshortcuts` value: the keys' spoken names joined with `+`, in
+ * the user's language, since readers speak the attribute verbatim and the
+ * operating system's own menus are read that way (`Command+Shift+Ponto` in
+ * Brazilian Portuguese). `Command+Enter` on Apple platforms and `Ctrl+Enter`
+ * elsewhere in English. Undefined when there are no keys, so a template
+ * binding omits the attribute rather than emitting an empty one.
+ *
+ * This intentionally uses localized spoken names instead of the canonical
+ * key tokens: screen readers can announce `Meta` literally and omit
+ * punctuation such as `.`, while localized names are spoken correctly. Do
+ * not switch this to `ShortcutKey.key` without testing the spoken output.
+ */
+ aria: string | undefined;
+}
+
+type Modifier = "mod" | "Control" | "Alt" | "Shift";
+
+/**
+ * Modifier spellings accepted on input. `mod` and its synonyms resolve to the
+ * platform's primary modifier; `ctrl` stays a literal Control key everywhere.
+ */
+const MODIFIER_ALIASES: Record<string, Modifier> = {
+ mod: "mod",
+ meta: "mod",
+ command: "mod",
+ cmd: "mod",
+ super: "mod",
+ win: "mod",
+ ctrl: "Control",
+ control: "Control",
+ alt: "Alt",
+ option: "Alt",
+ shift: "Shift",
+};
+
+/** Non-modifier spellings accepted on input, mapped to their canonical name. */
+const NAMED_KEYS: Record<string, string> = {
+ enter: "Enter",
+ return: "Enter",
+ esc: "Escape",
+ escape: "Escape",
+ space: "Space",
+ tab: "Tab",
+ backspace: "Backspace",
+ del: "Delete",
+ delete: "Delete",
+ home: "Home",
+ end: "End",
+ pageup: "PageUp",
+ pagedown: "PageDown",
+ plus: "+",
+ comma: ",",
+ up: "ArrowUp",
+ arrowup: "ArrowUp",
+ down: "ArrowDown",
+ arrowdown: "ArrowDown",
+ left: "ArrowLeft",
+ arrowleft: "ArrowLeft",
+ right: "ArrowRight",
+ arrowright: "ArrowRight",
+ "&uarr;": "ArrowUp",
+ "&darr;": "ArrowDown",
+ "&larr;": "ArrowLeft",
+ "&rarr;": "ArrowRight",
+};
+
+/** Keys drawn as a glyph on every platform, with the i18n key of their spoken name. */
+const UNIVERSAL_GLYPHS: Record<string, { label: string; name: string }> = {
+ ArrowUp: { label: "↑", name: "shortcut_modifier_key.arrow_up" },
+ ArrowDown: { label: "↓", name: "shortcut_modifier_key.arrow_down" },
+ ArrowLeft: { label: "←", name: "shortcut_modifier_key.arrow_left" },
+ ArrowRight: { label: "→", name: "shortcut_modifier_key.arrow_right" },
+};
+
+/** Modifiers drawn as a glyph on Apple platforms only. */
+const APPLE_GLYPHS: Record<string, { label: string; name: string }> = {
+ Meta: { label: "⌘", name: "shortcut_modifier_key.command" },
+ Alt: { label: "⌥", name: "shortcut_modifier_key.option" },
+ Control: { label: "⌃", name: "shortcut_modifier_key.control" },
+ Shift: { label: "⇧", name: "shortcut_modifier_key.shift" },
+};
+
+/**
+ * The i18n key of each punctuation key's spoken name. Screen readers apply
+ * their punctuation verbosity to `aria-keyshortcuts` and drop a lone `.` or `,`
+ * at the default level, so the announced form names the key, in the user's
+ * language, the way the operating system's own menus are read.
+ */
+const SPOKEN_PUNCTUATION: Record<string, string> = {
+ ".": "shortcut_modifier_key.period",
+ ",": "shortcut_modifier_key.comma",
+ "/": "shortcut_modifier_key.slash",
+ "\\": "shortcut_modifier_key.backslash",
+ "?": "shortcut_modifier_key.question_mark",
+ "!": "shortcut_modifier_key.exclamation_mark",
+ "#": "shortcut_modifier_key.hash",
+ "=": "shortcut_modifier_key.equals",
+ "-": "shortcut_modifier_key.minus",
+ "+": "shortcut_modifier_key.plus",
+ ";": "shortcut_modifier_key.semicolon",
+ "'": "shortcut_modifier_key.apostrophe",
+ "`": "shortcut_modifier_key.backquote",
+ "[": "shortcut_modifier_key.left_bracket",
+ "]": "shortcut_modifier_key.right_bracket",
+};
+
+/**
+ * The order modifiers are listed in, whatever order the binding spells them:
+ * Apple's guidelines fix Control, Option, Shift, Command, and the same order
+ * matches the usual Ctrl, Alt, Shift elsewhere.
+ */
+const MODIFIER_ORDER = ["Control", "Alt", "Shift", "Meta"];
+
+/** Keys drawn as a localized word rather than their canonical name. */
+const WORD_KEYS: Record<string, string> = {
+ Control: "shortcut_modifier_key.ctrl",
+ Alt: "shortcut_modifier_key.alt",
+ Shift: "shortcut_modifier_key.shift",
+ Enter: "shortcut_modifier_key.enter",
+ Escape: "shortcut_modifier_key.esc",
+ Space: "shortcut_modifier_key.space",
+ Tab: "shortcut_modifier_key.tab",
+ Backspace: "shortcut_modifier_key.backspace",
+ Delete: "shortcut_modifier_key.delete",
+ Home: "shortcut_modifier_key.home",
+ End: "shortcut_modifier_key.end",
+ PageUp: "shortcut_modifier_key.page_up",
+ PageDown: "shortcut_modifier_key.page_down",
+};
+
+function canonicalKey(token: string, isApple: boolean): string {
+ const modifier = MODIFIER_ALIASES[token];
+ if (modifier === "mod") {
+ return isApple ? "Meta" : "Control";
+ }
+ if (modifier) {
+ return modifier;
+ }
+
+ const named = NAMED_KEYS[token];
+ if (named) {
+ return named;
+ }
+
+ // Only ASCII letters are case-folded: other scripts can expand to several
+ // characters under `toUpperCase` (`ß` becomes `SS`), which would no longer
+ // name one key.
+ if (token.length === 1) {
+ return token.replace(/^[a-z]$/, (letter) => letter.toUpperCase());
+ }
+
+ return token.replace(/^[a-z]/, (letter) => letter.toUpperCase());
+}
+
+function describeKey(key: string, isApple: boolean): ShortcutKey {
+ const glyph = UNIVERSAL_GLYPHS[key] ?? (isApple ? APPLE_GLYPHS[key] : null);
+ if (glyph) {
+ return { key, label: glyph.label, name: i18n(glyph.name), glyph: true };
+ }
+
+ const punctuation = SPOKEN_PUNCTUATION[key];
+ if (punctuation) {
+ return { key, label: key, name: i18n(punctuation), glyph: false };
+ }
+
+ const word = WORD_KEYS[key];
+ const label = word ? i18n(word) : key;
+ return { key, label, name: label, glyph: false };
+}
+
+/**
+ * Formats a keyboard shortcut for display and announcement from one spelling.
+ *
+ * The input uses the same spelling as key bindings: `+`-joined, case-insensitive,
+ * with `mod` for the platform's primary modifier (`mod+enter`, `ctrl+alt+f`,
+ * `shift+b`, `up`). Both outputs derive from it, so a call site cannot draw one
+ * shortcut and announce another. Modifiers come out in the platform's
+ * conventional order, so `mod+shift+d` renders as `⇧⌘ D` on Apple platforms and
+ * `Ctrl Shift D` elsewhere.
+ *
+ * @example
+ * ```js
+ * const { label, aria } = formatShortcut("mod+b");
+ * // Apple: label "⌘ B", aria "Command+B"
+ * // Others: label "Ctrl B", aria "Ctrl+B"
+ * ```
+ */
+export function formatShortcut(keys?: string | null): FormattedShortcut {
+ const { isApple } = capabilities;
+ // Same rule as the key binding library: a doubled separator or a bare `+`
+ // names the plus key itself.
+ const spelling = (keys ?? "").trim().replace(/\+\+/g, "+plus");
+ const tokens = spelling === "+" ? ["plus"] : spelling.split("+");
+ const canonical = [
+ ...new Set(
+ tokens
+ .map((token) => token.trim().toLowerCase())
+ .filter(Boolean)
+ .map((token) => canonicalKey(token, isApple))
+ ),
+ ];
+
+ const modifiers = canonical
+ .filter((key) => MODIFIER_ORDER.includes(key))
+ .sort((a, b) => MODIFIER_ORDER.indexOf(a) - MODIFIER_ORDER.indexOf(b));
+ const others = canonical.filter((key) => !MODIFIER_ORDER.includes(key));
+ const parsed = [...modifiers, ...others].map((key) =>
+ describeKey(key, isApple)
+ );
+
+ return {
+ keys: parsed,
+ label: parsed.map((key) => key.label).join(" "),
+ aria: parsed.length ? parsed.map((key) => key.name).join("+") : undefined,
+ };
+}
diff --git a/frontend/discourse/app/lib/utilities.js b/frontend/discourse/app/lib/utilities.js
index 5e6e0ec6c41..b52f648145b 100644
--- a/frontend/discourse/app/lib/utilities.js
+++ b/frontend/discourse/app/lib/utilities.js
@@ -534,6 +534,12 @@ export async function inCodeBlock(text, pos) {
return CODE_TOKEN_TYPES.includes(type);
}
+/**
+ * Replaces modifier names in a shortcut string with their platform spelling.
+ *
+ * @deprecated Use `formatShortcut` from `discourse/lib/shortcut-format`, which
+ * produces the drawn form and the `aria-keyshortcuts` value from one spelling.
+ */
export function translateModKey(string, separator = " ") {
const { isApple } = capabilities;
// Apple device users are used to glyphs for shortcut keys
diff --git a/frontend/discourse/app/services/capabilities.js b/frontend/discourse/app/services/capabilities.js
index 80792b66212..9f38c931289 100644
--- a/frontend/discourse/app/services/capabilities.js
+++ b/frontend/discourse/app/services/capabilities.js
@@ -1,3 +1,4 @@
+import { tracked } from "@glimmer/tracking";
import deprecated from "discourse/lib/deprecated";
import { isRailsTesting, isTesting } from "discourse/lib/environment";
import { getOwnerWithFallback } from "discourse/lib/get-owner";
@@ -10,6 +11,37 @@ const APPLE_USER_AGENT_DATA_PLATFORM = /macOS/;
const ua = navigator.userAgent;
const anyPointerCoarseQuery = new TrackedMediaQuery("(any-pointer: coarse)");
+/**
+ * The primary pointer, not `any-pointer`: a phone with stylus support reports
+ * a fine pointer among its inputs while its primary pointer stays coarse.
+ */
+const finePointerQuery = new TrackedMediaQuery("(pointer: fine)");
+
+/**
+ * Keys an on-screen keyboard never sends: a keydown for one of them proves a
+ * physical keyboard.
+ */
+const PHYSICAL_KEYBOARD_KEYS = new Set(["Meta", "Control", "Alt", "Tab"]);
+
+/**
+ * Tracked state lives here rather than on the capabilities class, which mixes
+ * private members with what would otherwise be a decorated field.
+ */
+class KeyboardEvidence {
+ @tracked seen = false;
+}
+
+const keyboardEvidence = new KeyboardEvidence();
+
+/** Forgets any keyboard use seen so far; for test isolation. */
+export function resetKeyboardEvidence() {
+ keyboardEvidence.seen = false;
+}
+
+/** Records that a physical keyboard has been used. */
+export function noteKeyboardEvidence() {
+ keyboardEvidence.seen = true;
+}
let siteInitialized = false;
@@ -121,6 +153,27 @@ class _Capabilities {
#isMobileDevice =
Mobile.mobileForced || (ua.includes("Mobile") && !ua.includes("iPad"));
+ #noteKeyboardEvent = (event) => {
+ if (keyboardEvidence.seen || event.isComposing) {
+ return;
+ }
+
+ if (
+ PHYSICAL_KEYBOARD_KEYS.has(event.key) ||
+ event.metaKey ||
+ event.ctrlKey ||
+ event.altKey
+ ) {
+ noteKeyboardEvidence();
+ }
+ };
+
+ constructor() {
+ document.addEventListener("keydown", this.#noteKeyboardEvent, {
+ capture: true,
+ passive: true,
+ });
+ }
get isMobileDevice() {
return this.#isMobileDevice;
@@ -130,6 +183,22 @@ class _Capabilities {
return anyPointerCoarseQuery.matches;
}
+ /**
+ * Whether the device is likely to have a physical keyboard, so keyboard
+ * shortcuts are worth showing. There is no direct signal for this, so it is
+ * inferred: a fine primary pointer (mouse or trackpad) implies a desktop-class
+ * setup, and a keydown for a key on-screen keyboards never send proves one
+ * for the rest of the session.
+ */
+ get hasKeyboard() {
+ return finePointerQuery.matches || keyboardEvidence.seen;
+ }
+
+ /** Whether a keydown only a physical keyboard sends has been seen. */
+ get hasKeyboardEvidence() {
+ return keyboardEvidence.seen;
+ }
+
get userHasBeenActive() {
return (
!("userActivation" in navigator) || navigator.userActivation.hasBeenActive
diff --git a/frontend/discourse/app/services/keyboard-shortcuts.js b/frontend/discourse/app/services/keyboard-shortcuts.js
index 24128d8bd95..71f6e7029ac 100644
--- a/frontend/discourse/app/services/keyboard-shortcuts.js
+++ b/frontend/discourse/app/services/keyboard-shortcuts.js
@@ -45,11 +45,13 @@ export function clearExtraKeyboardShortcutHelp() {
export { extraKeyboardShortcutsHelp as extraKeyboardShortcutsHelp };
-export const PLATFORM_KEY_MODIFIER = /Mac|iPod|iPhone|iPad/.test(
- navigator.platform
-)
- ? "meta"
- : "ctrl";
+/**
+ * The binding name of the platform's primary modifier key, as used in key
+ * combos such as `${PLATFORM_KEY_MODIFIER}+k`. Derived from the same platform
+ * test that drives shortcut display, so a binding and its drawn form cannot
+ * disagree on which key is primary.
+ */
+export const PLATFORM_KEY_MODIFIER = capabilities.isApple ? "meta" : "ctrl";
const NESTED_POST_CONTENT_SELECTOR = [
":scope > .nested-post__main > .nested-post__article",
@@ -294,9 +296,11 @@ export default class KeyboardShortcutLib extends Service {
* {
* category: String,
* name: String,
- * definition: (See function `buildShortcut` in
- * frontend/discourse/app/controllers/keyboard-shortcuts-help.js
- * for definition structure)
+ * definition: {
+ * keys1: ["mod", "shift", "d"], // key spellings, as for bindings
+ * keys2: ["alt", "&uarr;"], // optional second group
+ * shortcutsDelimiter: "or", // or | slash | space | newline
+ * }
* }
*
* - click - allows to provide a selector on which a click event
diff --git a/frontend/discourse/app/ui-kit/d-shortcut.gts b/frontend/discourse/app/ui-kit/d-shortcut.gts
new file mode 100644
index 00000000000..ba49e287b50
--- /dev/null
+++ b/frontend/discourse/app/ui-kit/d-shortcut.gts
@@ -0,0 +1,162 @@
+import Component from "@glimmer/component";
+import { cached } from "@glimmer/tracking";
+import type { TOC } from "@ember/component/template-only";
+import { getOwner } from "@ember/owner";
+import type { WithBoundArgs } from "@glint/template";
+import curryComponent from "ember-curry-component";
+import {
+ formatShortcut,
+ type FormattedShortcut,
+ type ShortcutKey,
+} from "discourse/lib/shortcut-format";
+import { capabilities } from "discourse/services/capabilities";
+import { notEq } from "discourse/truth-helpers";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+
+interface KbdSignature {
+ Args: {
+ keys: ShortcutKey[];
+ /** Hide from assistive technology, for a chip beside an element that announces the shortcut itself. */
+ hidden?: boolean;
+ };
+ Element: HTMLElement;
+}
+
+/**
+ * The drawn form: one `<kbd>` per key inside a `<kbd>` for the combination.
+ * A key drawn as a glyph or as punctuation also carries its spelled-out name
+ * for assistive technology, hidden visually, so `⌘` is read as "Command" and
+ * `.` as "Period" rather than as a symbol name or nothing.
+ */
+const Kbd: TOC<KbdSignature> = <template>
+ {{#if @keys.length}}
+ <kbd
+ class="d-shortcut"
+ dir="ltr"
+ aria-hidden={{if @hidden "true"}}
+ ...attributes
+ >
+ {{#each @keys key="key" as |key|}}
+ <kbd
+ class={{dConcatClass
+ "d-shortcut__key"
+ (if key.glyph "d-shortcut__key--glyph")
+ }}
+ >
+ {{#if (notEq key.name key.label)}}
+ <span aria-hidden="true">{{key.label}}</span>
+ <span class="sr-only">{{key.name}}</span>
+ {{else}}
+ {{key.label}}
+ {{/if}}
+ </kbd>
+ {{/each}}
+ </kbd>
+ {{/if}}
+</template>;
+
+/** What the block form yields: both forms of the shortcut, from one spelling. */
+export interface DShortcutParts extends FormattedShortcut {
+ /**
+ * The drawn form, pre-bound to the same keys and hidden from assistive
+ * technology, since the element carrying `aria` announces the shortcut.
+ * Accepts `...attributes`.
+ */
+ Kbd: WithBoundArgs<typeof Kbd, "keys" | "hidden">;
+}
+
+interface DShortcutSignature {
+ Args: {
+ /**
+ * The shortcut in binding spelling: `+`-joined, case-insensitive, with
+ * `mod` for the platform's primary modifier (`mod+enter`, `ctrl+alt+f`).
+ * With none, the block form yields `aria: undefined` and a `Kbd` that
+ * renders nothing, so a wrapper can be unconditional.
+ */
+ keys?: string | null;
+ /**
+ * Show the shortcut even where no physical keyboard is detected. For
+ * surfaces whose purpose is the keys themselves, such as the shortcuts
+ * help modal; everywhere else a device without a keyboard gets neither the
+ * drawn nor the announced form.
+ */
+ always?: boolean;
+ };
+ Blocks: {
+ default: [DShortcutParts];
+ };
+ Element: HTMLElement;
+}
+
+/**
+ * Displays a keyboard shortcut, and announces it, from one spelling.
+ *
+ * Without a block it draws the shortcut as keycaps:
+ *
+ * ```gjs
+ * <DShortcut @keys="mod+/" class="sidebar-search__shortcut-hint" />
+ * ```
+ *
+ * With a block it renders no element of its own and instead yields both forms
+ * (`aria`, `label`, `keys`, and a bound `Kbd` component), so the element the
+ * shortcut activates and the drawn keycaps beside it cannot disagree:
+ *
+ * ```gjs
+ * <DShortcut @keys="mod+enter" as |shortcut|>
+ * <DButton @action={{@save}} aria-keyshortcuts={{shortcut.aria}}>
+ * {{i18n "composer.save"}}
+ * <shortcut.Kbd />
+ * </DButton>
+ * </DShortcut>
+ * ```
+ *
+ * Where no physical keyboard is detected (`capabilities.hasKeyboard`) both
+ * modes produce nothing: no chip, and `aria` undefined so the activator
+ * announces no shortcut. `@always` opts out of that for surfaces that document
+ * the keys.
+ *
+ * `aria-keyshortcuts` is never set by the component itself: it belongs on the
+ * element that reacts to the keys, which only the caller knows. The yielded
+ * `Kbd` is hidden from assistive technology for the same reason: the activator
+ * announces the shortcut, and a readable chip inside it would fold the key
+ * names into its accessible name. Attributes on the block-form invocation are
+ * dropped, since nothing is rendered to carry them; put them on `shortcut.Kbd`.
+ */
+export default class DShortcut extends Component<DShortcutSignature> {
+ /**
+ * Both forms of the shortcut, or the empty result where the device has no
+ * keyboard to press them on. Recomputed when `@keys` or that changes.
+ */
+ @cached
+ get formatted(): FormattedShortcut {
+ const shown = this.args.always || capabilities.hasKeyboard;
+ return formatShortcut(shown ? this.args.keys : undefined);
+ }
+
+ /**
+ * The yielded forms plus the bound `Kbd`. Cached so a rerender hands the
+ * block the same component class rather than a freshly curried one, which
+ * would tear the keycaps down and rebuild them.
+ */
+ @cached
+ get parts(): DShortcutParts {
+ const formatted = this.formatted;
+
+ return {
+ ...formatted,
+ Kbd: curryComponent(
+ Kbd,
+ { keys: formatted.keys, hidden: true },
+ getOwner(this)!
+ ),
+ };
+ }
+
+ <template>
+ {{#if (has-block)}}
+ {{yield this.parts}}
+ {{else}}
+ <Kbd @keys={{this.formatted.keys}} ...attributes />
+ {{/if}}
+ </template>
+}
diff --git a/frontend/discourse/tests/acceptance/composer-test.js b/frontend/discourse/tests/acceptance/composer-test.js
index 1fe27a57f38..c5c180a3118 100644
--- a/frontend/discourse/tests/acceptance/composer-test.js
+++ b/frontend/discourse/tests/acceptance/composer-test.js
@@ -18,10 +18,10 @@ import LinkLookup from "discourse/lib/link-lookup";
import { cloneJSON } from "discourse/lib/object";
import { headerOffset } from "discourse/lib/offset-calculator";
import { withPluginApi } from "discourse/lib/plugin-api";
-import { translateModKey } from "discourse/lib/utilities";
+import { formatShortcut } from "discourse/lib/shortcut-format";
import Composer, { CREATE_TOPIC } from "discourse/models/composer";
import Draft from "discourse/models/draft";
-import { PLATFORM_KEY_MODIFIER } from "discourse/services/keyboard-shortcuts";
+import { capabilities } from "discourse/services/capabilities";
import TopicFixtures from "discourse/tests/fixtures/topic";
import pretender, { response } from "discourse/tests/helpers/create-pretender";
import {
@@ -1940,6 +1940,62 @@ acceptance(`composer buttons API`, function (needs) {
});
});
+ test("gate: toolbar and save button titles carry the shortcut with a keyboard", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click(".post-controls button.reply");
+
+ const bold = formatShortcut("mod+b");
+ assert
+ .dom(".toolbar__button.bold")
+ .hasAttribute("title", `${i18n("composer.bold_title")} (${bold.label})`)
+ .hasAttribute("aria-keyshortcuts", bold.aria);
+ assert.dom(".save-or-cancel .create").hasAttribute(
+ "title",
+ i18n("composer.submit_shortcut_title", {
+ shortcut: formatShortcut("mod+enter").label,
+ })
+ );
+ });
+
+ test("gate: toolbar and save button titles drop the shortcut without a keyboard", async function (assert) {
+ sinon.stub(capabilities, "hasKeyboard").get(() => false);
+
+ await visit("/t/internationalization-localization/280");
+ await click(".post-controls button.reply");
+
+ assert
+ .dom(".toolbar__button.bold")
+ .hasAttribute("title", i18n("composer.bold_title"))
+ .doesNotHaveAttribute("aria-keyshortcuts");
+ assert
+ .dom(".save-or-cancel .create")
+ .doesNotHaveAttribute("title")
+ .doesNotHaveAttribute("aria-keyshortcuts");
+ });
+
+ test("gate: an option without a label keeps the shortcut in its title", async function (assert) {
+ withPluginApi((api) => {
+ api.addComposerToolbarPopupMenuOption({
+ action: () => {},
+ shortcut: "alt+b",
+ icon: "far-bold",
+ name: "icon-only",
+ title: "some_title",
+ });
+ });
+
+ await visit("/t/internationalization-localization/280");
+ await click(".post-controls button.reply");
+ await click(".toolbar-menu__options-trigger");
+
+ const shortcut = formatShortcut("mod+alt+b");
+ assert
+ .dom("[data-name='icon-only']")
+ .hasAttribute("title", `${i18n("some_title")} (${shortcut.label})`)
+ .hasAttribute("aria-keyshortcuts", shortcut.aria);
+ assert.dom("[data-name='icon-only'] .d-shortcut").doesNotExist();
+ });
+
test("buttons can support a shortcut", async function (assert) {
withPluginApi((api) => {
api.addComposerToolbarPopupMenuOption({
@@ -1976,21 +2032,37 @@ acceptance(`composer buttons API`, function (needs) {
await click(".toolbar-menu__options-trigger");
+ const shortcut = formatShortcut("mod+alt+b");
const row = find("[data-name='bold']");
assert
.dom(row)
.hasAttribute(
"title",
- i18n("some_title") +
- ` (${translateModKey(PLATFORM_KEY_MODIFIER + " alt b")})`,
- "shows the title with shortcut"
+ i18n("some_title"),
+ "keeps the shortcut out of the title, since the row draws and announces it"
);
assert
.dom(row)
+ .hasAttribute(
+ "aria-keyshortcuts",
+ shortcut.aria,
+ "announces the shortcut in its localized spoken form"
+ );
+ assert
+ .dom(".d-button-label__text", row)
+ .hasText(i18n("some_label"), "shows the label");
+ assert
+ .dom(".d-shortcut__key", row)
+ .exists({ count: shortcut.keys.length }, "draws one keycap per key");
+ assert
+ .dom(".d-shortcut", row)
.hasText(
- i18n("some_label") +
- ` ${translateModKey(PLATFORM_KEY_MODIFIER + " alt b")}`,
- "shows the label with shortcut"
+ shortcut.keys
+ .map((key) =>
+ key.name === key.label ? key.label : `${key.label} ${key.name}`
+ )
+ .join(" "),
+ "draws each key with its spoken name"
);
});
diff --git a/frontend/discourse/tests/acceptance/fast-edit-test.js b/frontend/discourse/tests/acceptance/fast-edit-test.js
index e78e4ff02b8..5f8c2ae4a2f 100644
--- a/frontend/discourse/tests/acceptance/fast-edit-test.js
+++ b/frontend/discourse/tests/acceptance/fast-edit-test.js
@@ -6,13 +6,17 @@ import {
visit,
} from "@ember/test-helpers";
import { test } from "qunit";
+import sinon from "sinon";
import { cloneJSON } from "discourse/lib/object";
+import { formatShortcut } from "discourse/lib/shortcut-format";
+import { capabilities } from "discourse/services/capabilities";
import postFixtures from "discourse/tests/fixtures/post";
import {
acceptance,
metaModifier,
selectText,
} from "discourse/tests/helpers/qunit-helpers";
+import { i18n } from "discourse-i18n";
acceptance("Fast Edit", function (needs) {
needs.user();
@@ -137,4 +141,28 @@ acceptance("Fast Edit", function (needs) {
assert.dom("#fast-edit-input").exists();
});
+
+ test("gate: the save button names the shortcut only with a keyboard", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await selectText("#post_1 .cooked p");
+ await click(".quote-button .quote-edit-label");
+
+ assert.dom(".save-fast-edit").hasAttribute(
+ "title",
+ i18n("composer.submit_shortcut_title", {
+ shortcut: formatShortcut("mod+enter").label,
+ })
+ );
+
+ sinon.stub(capabilities, "hasKeyboard").get(() => false);
+ await visit("/");
+ await visit("/t/internationalization-localization/280");
+ await selectText("#post_1 .cooked p");
+ await click(".quote-button .quote-edit-label");
+
+ assert
+ .dom(".save-fast-edit")
+ .doesNotHaveAttribute("title")
+ .doesNotHaveAttribute("aria-keyshortcuts");
+ });
});
diff --git a/frontend/discourse/tests/acceptance/plugin-keyboard-shortcut-test.js b/frontend/discourse/tests/acceptance/plugin-keyboard-shortcut-test.js
index bb04dffc273..cbee05f0f47 100644
--- a/frontend/discourse/tests/acceptance/plugin-keyboard-shortcut-test.js
+++ b/frontend/discourse/tests/acceptance/plugin-keyboard-shortcut-test.js
@@ -4,6 +4,7 @@ import { test } from "qunit";
import sinon from "sinon";
import { withPluginApi } from "discourse/lib/plugin-api";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+import { i18n } from "discourse-i18n";
acceptance("Plugin Keyboard Shortcuts - Logged In", function (needs) {
needs.user();
@@ -66,6 +67,114 @@ acceptance("Plugin Keyboard Shortcuts - Anonymous", function () {
assert.dom(".shortcut-category-new_category tbody tr").exists({ count: 1 });
});
+ test("help modal: draws entity arrow keys as glyphs with spoken names", async function (assert) {
+ withPluginApi((api) => {
+ api.addKeyboardShortcut("alt+up", () => {}, {
+ help: {
+ category: "new_category",
+ name: "new_category.test",
+ definition: {
+ keys1: ["alt", "&uarr;"],
+ keys2: ["alt", "&darr;"],
+ shortcutsDelimiter: "slash",
+ },
+ },
+ });
+ });
+ await visit("/");
+ await triggerKeyEvent(document, "keypress", "?".charCodeAt(0));
+
+ const cell = ".shortcut-category-new_category .shortcut-key";
+ assert.dom(`${cell} .d-shortcut__key--glyph [aria-hidden]`, null).exists();
+ assert
+ .dom(
+ `${cell} .d-shortcut:nth-of-type(1) .d-shortcut__key:last-child [aria-hidden]`
+ )
+ .hasText("↑");
+ assert
+ .dom(
+ `${cell} .d-shortcut:nth-of-type(1) .d-shortcut__key:last-child .sr-only`
+ )
+ .hasText(i18n("shortcut_modifier_key.arrow_up"));
+ assert.dom(cell).doesNotIncludeText("&uarr;");
+ });
+
+ test("help modal: draws a literal plus key", async function (assert) {
+ withPluginApi((api) => {
+ api.addKeyboardShortcut("shift++", () => {}, {
+ help: {
+ category: "new_category",
+ name: "new_category.test",
+ definition: { keys1: ["shift", "+"] },
+ },
+ });
+ });
+ await visit("/");
+ await triggerKeyEvent(document, "keypress", "?".charCodeAt(0));
+
+ assert
+ .dom(".shortcut-category-new_category .d-shortcut__key")
+ .exists({ count: 2 });
+ assert
+ .dom(
+ ".shortcut-category-new_category .d-shortcut__key:last-child [aria-hidden]"
+ )
+ .hasText("+");
+ });
+
+ test("help modal: breaks a newline delimiter onto two lines", async function (assert) {
+ withPluginApi((api) => {
+ api.addKeyboardShortcut("j", () => {}, {
+ help: {
+ category: "new_category",
+ name: "new_category.test",
+ definition: {
+ keys1: ["j"],
+ keys2: ["k"],
+ shortcutsDelimiter: "newline",
+ },
+ },
+ });
+ });
+ await visit("/");
+ await triggerKeyEvent(document, "keypress", "?".charCodeAt(0));
+
+ assert
+ .dom(".shortcut-category-new_category .delimiter-newline > br")
+ .exists({ count: 1 });
+ assert
+ .dom(".shortcut-category-new_category .delimiter-newline .d-shortcut")
+ .exists({ count: 2 });
+ });
+
+ test("help modal: falls back to the or delimiter for an unknown one", async function (assert) {
+ withPluginApi((api) => {
+ api.addKeyboardShortcut("j", () => {}, {
+ help: {
+ category: "new_category",
+ name: "new_category.test",
+ definition: {
+ keys1: ["j"],
+ keys2: ["k"],
+ shortcutsDelimiter: "comma",
+ },
+ },
+ });
+ });
+ await visit("/");
+ await triggerKeyEvent(document, "keypress", "?".charCodeAt(0));
+
+ const cell = ".shortcut-category-new_category .shortcut-key";
+ assert.dom(`${cell} .d-shortcut`).exists({ count: 2 });
+ assert.dom(cell).doesNotIncludeText("[en.");
+ assert.dom(cell).hasText(
+ i18n("keyboard_shortcuts_help.shortcut_delimiter_or", {
+ shortcut1: "J",
+ shortcut2: "K",
+ })
+ );
+ });
+
test("a plugin can add a shortcut to and existing category in the shortcut help modal", async function (assert) {
await visit("/");
await triggerKeyEvent(document, "keypress", "?".charCodeAt(0));
diff --git a/frontend/discourse/tests/helpers/qunit-helpers.js b/frontend/discourse/tests/helpers/qunit-helpers.js
index 8b2b113268e..956342943cb 100644
--- a/frontend/discourse/tests/helpers/qunit-helpers.js
+++ b/frontend/discourse/tests/helpers/qunit-helpers.js
@@ -97,6 +97,7 @@ import { clearAddedTrackedTopicProperties } from "discourse/models/topic";
import User from "discourse/models/user";
import { clearResolverOptions } from "discourse/resolver";
import { enableClearA11yAnnouncementsInTests } from "discourse/services/a11y";
+import { noteKeyboardEvidence } from "discourse/services/capabilities";
import {
clearDisabledDefaultKeyboardBindings,
clearExtraKeyboardShortcutHelp,
@@ -217,6 +218,7 @@ export function testCleanup(container, app) {
User.resetCurrent();
resetMobile();
+ noteKeyboardEvidence();
resetAdditionalReportModes();
resetAdminDashboardReportRenderers();
resetAdminDashboardSections();
diff --git a/frontend/discourse/tests/integration/components/composer/toggle-switch-test.gjs b/frontend/discourse/tests/integration/components/composer/toggle-switch-test.gjs
new file mode 100644
index 00000000000..d8ee649a9ed
--- /dev/null
+++ b/frontend/discourse/tests/integration/components/composer/toggle-switch-test.gjs
@@ -0,0 +1,39 @@
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import ToggleSwitch from "discourse/components/composer/toggle-switch";
+import { formatShortcut } from "discourse/lib/shortcut-format";
+import { capabilities } from "discourse/services/capabilities";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import { i18n } from "discourse-i18n";
+
+module("Integration | Component | composer/toggle-switch", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("gate: names the shortcut in its label only with a keyboard", async function (assert) {
+ const shortcut = formatShortcut("ctrl+m");
+
+ await render(<template><ToggleSwitch @state={{true}} /></template>);
+
+ assert
+ .dom(".composer-toggle-switch")
+ .hasAttribute(
+ "aria-label",
+ i18n("composer.switch_to_markdown", {
+ keyboardShortcut: shortcut.label,
+ })
+ )
+ .hasAttribute("aria-keyshortcuts", shortcut.aria);
+
+ sinon.stub(capabilities, "hasKeyboard").get(() => false);
+ await render(<template><ToggleSwitch @state={{true}} /></template>);
+
+ assert
+ .dom(".composer-toggle-switch")
+ .hasAttribute(
+ "aria-label",
+ i18n("composer.switch_to_markdown_no_shortcut")
+ )
+ .doesNotHaveAttribute("aria-keyshortcuts");
+ });
+});
diff --git a/frontend/discourse/tests/integration/ui-kit/d-shortcut-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-shortcut-test.gjs
new file mode 100644
index 00000000000..e99c1c54feb
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-shortcut-test.gjs
@@ -0,0 +1,192 @@
+import { find, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import { capabilities } from "discourse/services/capabilities";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import DShortcut from "discourse/ui-kit/d-shortcut";
+import { i18n } from "discourse-i18n";
+
+module("Integration | ui-kit | DShortcut", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("draws one keycap per key inside a combination", async function (assert) {
+ sinon.stub(capabilities, "isApple").value(false);
+
+ await render(<template><DShortcut @keys="mod+shift+b" /></template>);
+
+ assert
+ .dom("kbd.d-shortcut")
+ .exists({ count: 1 })
+ .hasAttribute("dir", "ltr")
+ .doesNotHaveAttribute("aria-hidden", "readable when it is the content");
+ assert.dom(".d-shortcut > kbd.d-shortcut__key").exists({ count: 3 });
+ assert
+ .dom(".d-shortcut__key:nth-child(1)")
+ .hasText(i18n("shortcut_modifier_key.ctrl"));
+ assert.dom(".d-shortcut__key:nth-child(3)").hasText("B");
+ });
+
+ test("gives a glyph a visually hidden spoken name", async function (assert) {
+ sinon.stub(capabilities, "isApple").value(true);
+
+ await render(<template><DShortcut @keys="mod+b" /></template>);
+
+ const command = document.querySelector(".d-shortcut__key:nth-child(1)");
+ assert.dom(command).hasClass("d-shortcut__key--glyph");
+ assert.dom("[aria-hidden='true']", command).hasText("⌘");
+ assert
+ .dom(".sr-only", command)
+ .hasText(i18n("shortcut_modifier_key.command"));
+
+ const letter = document.querySelector(".d-shortcut__key:nth-child(2)");
+ assert.dom(letter).doesNotHaveClass("d-shortcut__key--glyph");
+ assert.dom(".sr-only", letter).doesNotExist();
+ assert.dom(letter).hasText("B");
+ });
+
+ test("forwards attributes to the combination element", async function (assert) {
+ await render(
+ <template>
+ <DShortcut class="my-hint" data-test-hint="yes" @keys="mod+k" />
+ </template>
+ );
+
+ assert.dom("kbd.d-shortcut.my-hint").hasAttribute("data-test-hint", "yes");
+ });
+
+ test("shows nothing without a physical keyboard, unless told to always", async function (assert) {
+ sinon.stub(capabilities, "hasKeyboard").get(() => false);
+
+ await render(
+ <template>
+ <DShortcut @keys="mod+k" class="gated" />
+ <DShortcut @keys="mod+k" @always={{true}} class="documented" />
+ <DShortcut @keys="mod+enter" as |shortcut|>
+ <button type="button" aria-keyshortcuts={{shortcut.aria}}>
+ Save
+ <shortcut.Kbd />
+ </button>
+ </DShortcut>
+ </template>
+ );
+
+ assert.dom("kbd.gated").doesNotExist();
+ assert.dom("kbd.documented .d-shortcut__key").exists({ count: 2 });
+ assert.dom("button").doesNotHaveAttribute("aria-keyshortcuts");
+ assert.dom("button kbd").doesNotExist();
+ });
+
+ test("renders nothing without keys", async function (assert) {
+ await render(<template><DShortcut /></template>);
+
+ assert.dom("kbd").doesNotExist();
+ });
+
+ test("yields both forms and a bound keycap component to a block", async function (assert) {
+ sinon.stub(capabilities, "isApple").value(true);
+
+ await render(
+ <template>
+ <DShortcut @keys="mod+enter" as |shortcut|>
+ <button
+ type="button"
+ aria-keyshortcuts={{shortcut.aria}}
+ data-label={{shortcut.label}}
+ >
+ Save
+ <shortcut.Kbd class="inside" />
+ </button>
+ </DShortcut>
+ </template>
+ );
+
+ assert.dom("button").hasAttribute("aria-keyshortcuts", "Command+Enter");
+ assert
+ .dom("button > kbd.d-shortcut")
+ .hasAttribute("aria-hidden", "true", "the activator announces it");
+ assert
+ .dom("button")
+ .hasAttribute("data-label", `⌘ ${i18n("shortcut_modifier_key.enter")}`);
+ assert.dom("button > kbd.d-shortcut.inside").exists({ count: 1 });
+ assert.dom("button > kbd .d-shortcut__key").exists({ count: 2 });
+ assert.dom("kbd").exists({ count: 3 }, "no wrapper element of its own");
+ });
+
+ test("yields an undefined announcement and an empty keycap without keys", async function (assert) {
+ await render(
+ <template>
+ <DShortcut as |shortcut|>
+ <button type="button" aria-keyshortcuts={{shortcut.aria}}>
+ Save
+ <shortcut.Kbd />
+ </button>
+ </DShortcut>
+ </template>
+ );
+
+ assert.dom("button").doesNotHaveAttribute("aria-keyshortcuts");
+ assert.dom("kbd").doesNotExist();
+ });
+
+ test("edge: renders punctuation with its spoken name", async function (assert) {
+ await render(<template><DShortcut @keys="?" /></template>);
+
+ const key = find(".d-shortcut__key");
+ assert.dom(key).exists("the punctuation key renders");
+ assert
+ .dom(key)
+ .doesNotHaveClass(
+ "d-shortcut__key--glyph",
+ "punctuation is not styled as a glyph"
+ );
+ assert
+ .dom("span[aria-hidden='true']", key)
+ .hasText("?", "the visible span contains the punctuation label");
+ assert
+ .dom(".sr-only", key)
+ .hasText(
+ i18n("shortcut_modifier_key.question_mark"),
+ "the hidden span contains the localized spoken name"
+ );
+ });
+
+ test("edge: distinguishes glyph and punctuation keycaps", async function (assert) {
+ sinon.stub(capabilities, "isApple").value(true);
+
+ await render(<template><DShortcut @keys="mod+." /></template>);
+
+ assert
+ .dom(".d-shortcut__key:nth-child(1)")
+ .hasClass(
+ "d-shortcut__key--glyph",
+ "the Apple modifier is styled as a glyph"
+ );
+ const period = find(".d-shortcut__key:nth-child(2)");
+ assert
+ .dom(period)
+ .doesNotHaveClass(
+ "d-shortcut__key--glyph",
+ "the punctuation key is not styled as a glyph"
+ );
+ assert
+ .dom(".sr-only", period)
+ .hasText(
+ i18n("shortcut_modifier_key.period"),
+ "the punctuation key retains its spoken name"
+ );
+ });
+
+ test("edge: renders a letter key as plain text", async function (assert) {
+ await render(<template><DShortcut @keys="b" /></template>);
+
+ const key = find(".d-shortcut__key");
+ assert.dom(key).hasText("B", "the keycap contains the capitalized letter");
+ assert
+ .dom(key)
+ .doesNotHaveClass(
+ "d-shortcut__key--glyph",
+ "the letter is not styled as a glyph"
+ );
+ assert.dom("span", key).doesNotExist("the letter has no nested spans");
+ });
+});
diff --git a/frontend/discourse/tests/setup-tests.js b/frontend/discourse/tests/setup-tests.js
index b0b10dd4ab0..b8b8fe9514d 100644
--- a/frontend/discourse/tests/setup-tests.js
+++ b/frontend/discourse/tests/setup-tests.js
@@ -1,4 +1,5 @@
/* eslint-disable simple-import-sort/imports */
+import { noteKeyboardEvidence } from "discourse/services/capabilities";
import Application from "discourse/app";
import "./loader-shims";
import "discourse/static/markdown-it";
@@ -232,6 +233,11 @@ export default async function setupTests(config) {
await loadSprites(setupData.svgSpritePath, "fontawesome");
+ // Shortcuts render only when a keyboard is likely; assume one before the
+ // first test, and after each test in testCleanup, so rendering does not
+ // depend on the test browser's pointer.
+ noteKeyboardEvidence();
+
let app;
QUnit.testStart(async function (ctx) {
let settings = resetSettings();
diff --git a/frontend/discourse/tests/unit/lib/shortcut-format-test.js b/frontend/discourse/tests/unit/lib/shortcut-format-test.js
new file mode 100644
index 00000000000..5fec11ebfaa
--- /dev/null
+++ b/frontend/discourse/tests/unit/lib/shortcut-format-test.js
@@ -0,0 +1,577 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import { formatShortcut } from "discourse/lib/shortcut-format";
+import { capabilities } from "discourse/services/capabilities";
+import { i18n } from "discourse-i18n";
+
+module("Unit | Lib | shortcut-format", function (hooks) {
+ setupTest(hooks);
+
+ test("formats mod as Command on Apple platforms", function (assert) {
+ sinon.stub(capabilities, "isApple").value(true);
+
+ assert.deepEqual(
+ formatShortcut("mod"),
+ {
+ keys: [
+ {
+ key: "Meta",
+ label: "⌘",
+ name: i18n("shortcut_modifier_key.command"),
+ glyph: true,
+ },
+ ],
+ label: "⌘",
+ aria: "Command",
+ },
+ "mod uses the Apple platform modifier"
+ );
+ });
+
+ test("formats mod as Control on non-Apple platforms", function (assert) {
+ sinon.stub(capabilities, "isApple").value(false);
+
+ const ctrl = i18n("shortcut_modifier_key.ctrl");
+
+ assert.deepEqual(
+ formatShortcut("mod"),
+ {
+ keys: [{ key: "Control", label: ctrl, name: ctrl, glyph: false }],
+ label: ctrl,
+ aria: ctrl,
+ },
+ "mod uses the non-Apple platform modifier"
+ );
+ });
+
+ test("treats every mod alias like mod on Apple platforms", function (assert) {
+ sinon.stub(capabilities, "isApple").value(true);
+
+ for (const alias of ["mod", "meta", "command", "cmd", "super", "win"]) {
+ assert.deepEqual(
+ formatShortcut(alias),
+ {
+ keys: [
+ {
+ key: "Meta",
+ label: "⌘",
+ name: i18n("shortcut_modifier_key.command"),
+ glyph: true,
+ },
+ ],
+ label: "⌘",
+ aria: "Command",
+ },
+ `${alias} resolves to Command`
+ );
+ }
+ });
+
+ test("treats every mod alias like mod on non-Apple platforms", function (assert) {
+ sinon.stub(capabilities, "isApple").value(false);
+
+ const ctrl = i18n("shortcut_modifier_key.ctrl");
+
+ for (const alias of ["mod", "meta", "command", "cmd", "super", "win"]) {
+ assert.deepEqual(
+ formatShortcut(alias),
+ {
+ keys: [{ key: "Control", label: ctrl, name: ctrl, glyph: false }],
+ label: ctrl,
+ aria: ctrl,
+ },
+ `${alias} resolves to Control`
+ );
+ }
+ });
+
+ test("keeps ctrl as Control with a glyph on Apple platforms", function (assert) {
+ sinon.stub(capabilities, "isApple").value(true);
+
+ assert.deepEqual(
+ formatShortcut("ctrl"),
+ {
+ keys: [
+ {
+ key: "Control",
+ label: "⌃",
+ name: i18n("shortcut_modifier_key.control"),
+ glyph: true,
+ },
+ ],
+ label: "⌃",
+ aria: "Control",
+ },
+ "ctrl remains Control rather than becoming Meta"
+ );
+ });
+
+ test("keeps ctrl as Control with a localized label on non-Apple platforms", function (assert) {
+ sinon.stub(capabilities, "isApple").value(false);
+
+ const ctrl = i18n("shortcut_modifier_key.ctrl");
+
+ assert.deepEqual(
+ formatShortcut("ctrl"),
+ {
+ keys: [{ key: "Control", label: ctrl, name: ctrl, glyph: false }],
+ label: ctrl,
+ aria: ctrl,
+ },
+ "the non-glyph Control name exactly matches its label"
+ );
+ });
+
+ test("distinguishes ctrl+m from mod+m on Apple platforms", function (assert) {
+ sinon.stub(capabilities, "isApple").value(true);
+
+ assert.deepEqual(
+ formatShortcut("ctrl+m"),
+ {
+ keys: [
+ {
+ key: "Control",
+ label: "⌃",
+ name: i18n("shortcut_modifier_key.control"),
+ glyph: true,
+ },
+ { key: "M", label: "M", name: "M", glyph: false },
+ ],
+ label: "⌃ M",
+ aria: "Control+M",
+ },
+ "ctrl+m uses Control"
+ );
+ assert.deepEqual(
+ formatShortcut("mod+m"),
+ {
+ keys: [
+ {
+ key: "Meta",
+ label: "⌘",
+ name: i18n("shortcut_modifier_key.command"),
+ glyph: true,
+ },
+ { key: "M", label: "M", name: "M", glyph: false },
+ ],
+ label: "⌘ M",
+ aria: "Command+M",
+ },
+ "mod+m uses Meta"
+ );
+ });
+
+ test("formats Alt, Option, and Shift on Apple platforms", function (assert) {
+ sinon.stub(capabilities, "isApple").value(true);
+
+ assert.deepEqual(
+ formatShortcut("alt+option+shift"),
+ {
+ keys: [
+ {
+ key: "Alt",
+ label: "⌥",
+ name: i18n("shortcut_modifier_key.option"),
+ glyph: true,
+ },
+ {
+ key: "Shift",
+ label: "⇧",
+ name: i18n("shortcut_modifier_key.shift"),
+ glyph: true,
+ },
+ ],
+ label: "⌥ ⇧",
+ aria: "Option+Shift",
+ },
+ "Apple modifiers use glyph labels and localized spoken names"
+ );
+ });
+
+ test("formats Alt, Option, and Shift on non-Apple platforms", function (assert) {
+ sinon.stub(capabilities, "isApple").value(false);
+
+ const alt = i18n("shortcut_modifier_key.alt");
+ const shift = i18n("shortcut_modifier_key.shift");
+
+ assert.deepEqual(
+ formatShortcut("alt+option+shift"),
+ {
+ keys: [
+ { key: "Alt", label: alt, name: alt, glyph: false },
+ { key: "Shift", label: shift, name: shift, glyph: false },
+ ],
+ label: `${alt} ${shift}`,
+ aria: `${alt}+${shift}`,
+ },
+ "non-Apple modifiers are all words"
+ );
+ });
+
+ test("ignores case and surrounding whitespace", function (assert) {
+ sinon.stub(capabilities, "isApple").value(true);
+
+ assert.deepEqual(
+ formatShortcut(" MOD + Enter "),
+ {
+ keys: [
+ {
+ key: "Meta",
+ label: "⌘",
+ name: i18n("shortcut_modifier_key.command"),
+ glyph: true,
+ },
+ {
+ key: "Enter",
+ label: i18n("shortcut_modifier_key.enter"),
+ name: i18n("shortcut_modifier_key.enter"),
+ glyph: false,
+ },
+ ],
+ label: `⌘ ${i18n("shortcut_modifier_key.enter")}`,
+ aria: "Command+Enter",
+ },
+ "tokens are normalized before formatting"
+ );
+ });
+
+ test("normalizes named key aliases", function (assert) {
+ sinon.stub(capabilities, "isApple").value(false);
+
+ const enter = i18n("shortcut_modifier_key.enter");
+ const esc = i18n("shortcut_modifier_key.esc");
+ const space = i18n("shortcut_modifier_key.space");
+ const tab = i18n("shortcut_modifier_key.tab");
+ const backspace = i18n("shortcut_modifier_key.backspace");
+ const del = i18n("shortcut_modifier_key.delete");
+ const home = i18n("shortcut_modifier_key.home");
+ const end = i18n("shortcut_modifier_key.end");
+ const pageUp = i18n("shortcut_modifier_key.page_up");
+ const pageDown = i18n("shortcut_modifier_key.page_down");
+
+ assert.deepEqual(
+ formatShortcut(
+ "enter+return+esc+escape+space+tab+backspace+del+delete+home+end+pageup+pagedown"
+ ),
+ {
+ keys: [
+ { key: "Enter", label: enter, name: enter, glyph: false },
+ { key: "Escape", label: esc, name: esc, glyph: false },
+ { key: "Space", label: space, name: space, glyph: false },
+ { key: "Tab", label: tab, name: tab, glyph: false },
+ {
+ key: "Backspace",
+ label: backspace,
+ name: backspace,
+ glyph: false,
+ },
+ { key: "Delete", label: del, name: del, glyph: false },
+ { key: "Home", label: home, name: home, glyph: false },
+ { key: "End", label: end, name: end, glyph: false },
+ { key: "PageUp", label: pageUp, name: pageUp, glyph: false },
+ { key: "PageDown", label: pageDown, name: pageDown, glyph: false },
+ ],
+ label: `${enter} ${esc} ${space} ${tab} ${backspace} ${del} ${home} ${end} ${pageUp} ${pageDown}`,
+ aria: `${enter}+${esc}+${space}+${tab}+${backspace}+${del}+${home}+${end}+${pageUp}+${pageDown}`,
+ },
+ "named aliases use canonical key names in input order"
+ );
+ });
+
+ test("normalizes comma to the comma key", function (assert) {
+ sinon.stub(capabilities, "isApple").value(false);
+
+ assert.deepEqual(formatShortcut("mod+comma").keys[1], {
+ key: ",",
+ label: ",",
+ name: i18n("shortcut_modifier_key.comma"),
+ glyph: false,
+ });
+ assert.strictEqual(
+ formatShortcut("mod+comma").aria,
+ `${i18n("shortcut_modifier_key.ctrl")}+${i18n("shortcut_modifier_key.comma")}`
+ );
+ });
+
+ test("formats word-form arrow keys as glyphs with spoken names", function (assert) {
+ sinon.stub(capabilities, "isApple").value(false);
+
+ assert.deepEqual(
+ formatShortcut("up+down+left+right"),
+ {
+ keys: [
+ {
+ key: "ArrowUp",
+ label: "↑",
+ name: i18n("shortcut_modifier_key.arrow_up"),
+ glyph: true,
+ },
+ {
+ key: "ArrowDown",
+ label: "↓",
+ name: i18n("shortcut_modifier_key.arrow_down"),
+ glyph: true,
+ },
+ {
+ key: "ArrowLeft",
+ label: "←",
+ name: i18n("shortcut_modifier_key.arrow_left"),
+ glyph: true,
+ },
+ {
+ key: "ArrowRight",
+ label: "→",
+ name: i18n("shortcut_modifier_key.arrow_right"),
+ glyph: true,
+ },
+ ],
+ label: "↑ ↓ ← →",
+ aria: `${i18n("shortcut_modifier_key.arrow_up")}+${i18n("shortcut_modifier_key.arrow_down")}+${i18n("shortcut_modifier_key.arrow_left")}+${i18n("shortcut_modifier_key.arrow_right")}`,
+ },
+ "arrow glyph labels differ from their localized spoken names"
+ );
+ });
+
+ test("normalizes HTML entity arrow keys", function (assert) {
+ sinon.stub(capabilities, "isApple").value(true);
+
+ assert.deepEqual(
+ formatShortcut("&uarr;+&darr;+&larr;+&rarr;"),
+ {
+ keys: [
+ {
+ key: "ArrowUp",
+ label: "↑",
+ name: i18n("shortcut_modifier_key.arrow_up"),
+ glyph: true,
+ },
+ {
+ key: "ArrowDown",
+ label: "↓",
+ name: i18n("shortcut_modifier_key.arrow_down"),
+ glyph: true,
+ },
+ {
+ key: "ArrowLeft",
+ label: "←",
+ name: i18n("shortcut_modifier_key.arrow_left"),
+ glyph: true,
+ },
+ {
+ key: "ArrowRight",
+ label: "→",
+ name: i18n("shortcut_modifier_key.arrow_right"),
+ glyph: true,
+ },
+ ],
+ label: "↑ ↓ ← →",
+ aria: `${i18n("shortcut_modifier_key.arrow_up")}+${i18n("shortcut_modifier_key.arrow_down")}+${i18n("shortcut_modifier_key.arrow_left")}+${i18n("shortcut_modifier_key.arrow_right")}`,
+ },
+ "HTML entities map to canonical arrow keys"
+ );
+ });
+
+ test("returns an empty formatted shortcut for empty inputs", function (assert) {
+ sinon.stub(capabilities, "isApple").value(false);
+
+ for (const input of [undefined, null, ""]) {
+ assert.deepEqual(
+ formatShortcut(input),
+ { keys: [], label: "", aria: undefined },
+ `${String(input)} produces no keys`
+ );
+ }
+ });
+
+ test("uppercases single characters and capitalizes unknown words", function (assert) {
+ sinon.stub(capabilities, "isApple").value(false);
+
+ assert.deepEqual(
+ formatShortcut("b+/+MEDIA"),
+ {
+ keys: [
+ { key: "B", label: "B", name: "B", glyph: false },
+ {
+ key: "/",
+ label: "/",
+ name: i18n("shortcut_modifier_key.slash"),
+ glyph: false,
+ },
+ { key: "Media", label: "Media", name: "Media", glyph: false },
+ ],
+ label: "B / Media",
+ aria: `B+${i18n("shortcut_modifier_key.slash")}+Media`,
+ },
+ "non-glyph names exactly match their normalized labels"
+ );
+ });
+
+ test("orders modifiers by platform convention and spells punctuation when announcing", function (assert) {
+ sinon.stub(capabilities, "isApple").value(true);
+
+ assert.deepEqual(
+ formatShortcut("mod+shift+."),
+ {
+ keys: [
+ {
+ key: "Shift",
+ label: "⇧",
+ name: i18n("shortcut_modifier_key.shift"),
+ glyph: true,
+ },
+ {
+ key: "Meta",
+ label: "⌘",
+ name: i18n("shortcut_modifier_key.command"),
+ glyph: true,
+ },
+ {
+ key: ".",
+ label: ".",
+ name: i18n("shortcut_modifier_key.period"),
+ glyph: false,
+ },
+ ],
+ label: "⇧ ⌘ .",
+ aria: `${i18n("shortcut_modifier_key.shift")}+${i18n("shortcut_modifier_key.command")}+${i18n("shortcut_modifier_key.period")}`,
+ },
+ "Shift precedes Command, and the announced form names the period"
+ );
+
+ sinon.stub(capabilities, "isApple").value(false);
+
+ assert.strictEqual(
+ formatShortcut("shift+alt+mod+/").aria,
+ `${i18n("shortcut_modifier_key.ctrl")}+${i18n("shortcut_modifier_key.alt")}+${i18n("shortcut_modifier_key.shift")}+${i18n("shortcut_modifier_key.slash")}`,
+ "non-Apple order is Control, Alt, Shift"
+ );
+ });
+
+ test("edge: parses bare and doubled-separator plus keys", function (assert) {
+ sinon.stub(capabilities, "isApple").value(true);
+
+ const plus = i18n("shortcut_modifier_key.plus");
+
+ assert.deepEqual(
+ formatShortcut("+"),
+ {
+ keys: [{ key: "+", label: "+", name: plus, glyph: false }],
+ label: "+",
+ aria: plus,
+ },
+ "a bare separator names the plus key"
+ );
+ assert.deepEqual(
+ formatShortcut("mod++"),
+ {
+ keys: [
+ {
+ key: "Meta",
+ label: "⌘",
+ name: i18n("shortcut_modifier_key.command"),
+ glyph: true,
+ },
+ { key: "+", label: "+", name: plus, glyph: false },
+ ],
+ label: "⌘ +",
+ aria: `${i18n("shortcut_modifier_key.command")}+${plus}`,
+ },
+ "a doubled separator names plus after a modifier"
+ );
+ assert.deepEqual(
+ formatShortcut("shift+plus").keys,
+ [
+ {
+ key: "Shift",
+ label: "⇧",
+ name: i18n("shortcut_modifier_key.shift"),
+ glyph: true,
+ },
+ { key: "+", label: "+", name: plus, glyph: false },
+ ],
+ "the named alias also names the plus key"
+ );
+ });
+
+ test("edge: accepts canonical arrow names", function (assert) {
+ sinon.stub(capabilities, "isApple").value(false);
+
+ for (const [canonical, alias] of [
+ ["arrowup", "up"],
+ ["arrowdown", "down"],
+ ["arrowleft", "left"],
+ ["arrowright", "right"],
+ ]) {
+ assert.deepEqual(
+ formatShortcut(canonical),
+ formatShortcut(alias),
+ `${canonical} behaves like ${alias}`
+ );
+ }
+ });
+
+ test("edge: removes duplicate canonical keys", function (assert) {
+ sinon.stub(capabilities, "isApple").value(false);
+
+ const ctrl = i18n("shortcut_modifier_key.ctrl");
+ const expected = {
+ keys: [
+ { key: "Control", label: ctrl, name: ctrl, glyph: false },
+ { key: "A", label: "A", name: "A", glyph: false },
+ ],
+ label: `${ctrl} A`,
+ aria: `${ctrl}+A`,
+ };
+
+ assert.deepEqual(
+ formatShortcut("ctrl+ctrl+a"),
+ expected,
+ "an identical token is kept once"
+ );
+ assert.deepEqual(
+ formatShortcut("mod+ctrl+a"),
+ expected,
+ "different aliases resolving to Control are kept once"
+ );
+ });
+
+ test("edge: preserves non-ASCII single-character keys", function (assert) {
+ sinon.stub(capabilities, "isApple").value(false);
+
+ for (const character of ["ç", "ß"]) {
+ assert.deepEqual(
+ formatShortcut(character).keys[0],
+ {
+ key: character,
+ label: character,
+ name: character,
+ glyph: false,
+ },
+ `${character} remains one non-glyph key`
+ );
+ }
+ });
+
+ test("edge: gives punctuation localized spoken names", function (assert) {
+ sinon.stub(capabilities, "isApple").value(false);
+
+ for (const [key, name] of [
+ ["?", "question_mark"],
+ [".", "period"],
+ [",", "comma"],
+ ["/", "slash"],
+ ]) {
+ assert.deepEqual(
+ formatShortcut(key).keys[0],
+ {
+ key,
+ label: key,
+ name: i18n(`shortcut_modifier_key.${name}`),
+ glyph: false,
+ },
+ `${key} has a localized spoken name without being a glyph`
+ );
+ }
+ });
+});
diff --git a/frontend/discourse/tests/unit/services/capabilities-keyboard-test.js b/frontend/discourse/tests/unit/services/capabilities-keyboard-test.js
new file mode 100644
index 00000000000..ff540dc95ca
--- /dev/null
+++ b/frontend/discourse/tests/unit/services/capabilities-keyboard-test.js
@@ -0,0 +1,27 @@
+import { module, test } from "qunit";
+import {
+ capabilities,
+ noteKeyboardEvidence,
+ resetKeyboardEvidence,
+} from "discourse/services/capabilities";
+
+module("Unit | Service | capabilities | keyboard evidence", function () {
+ test("gate: a keydown is remembered as evidence until reset", function (assert) {
+ resetKeyboardEvidence();
+ assert.false(capabilities.hasKeyboardEvidence, "reset clears it");
+
+ document.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab" }));
+ assert.true(capabilities.hasKeyboardEvidence, "a Tab press is evidence");
+
+ resetKeyboardEvidence();
+ noteKeyboardEvidence();
+ assert.true(capabilities.hasKeyboardEvidence, "noted directly");
+ });
+
+ test("gate: every test starts with a keyboard assumed present", function (assert) {
+ // The previous test may have reset the evidence; each test starts fresh
+ // with it set, so shortcut rendering is deterministic regardless of the
+ // browser's pointer.
+ assert.true(capabilities.hasKeyboardEvidence);
+ });
+});
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-helper-options-list.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-helper-options-list.gjs
index 6ef783468dc..47874cf4288 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-helper-options-list.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-helper-options-list.gjs
@@ -1,48 +1,46 @@
-import Component from "@glimmer/component";
import { fn } from "@ember/helper";
-import { service } from "@ember/service";
-import { translateModKey } from "discourse/lib/utilities";
-import { PLATFORM_KEY_MODIFIER } from "discourse/services/keyboard-shortcuts";
import { and, eq } from "discourse/truth-helpers";
import DButton from "discourse/ui-kit/d-button";
+import DShortcut from "discourse/ui-kit/d-shortcut";
import AiHelperCustomPrompt from "../components/ai-helper-custom-prompt";
-export default class AiHelperOptionsList extends Component {
- @service site;
-
- get showShortcut() {
- return this.site.desktopView && this.args.shortcutVisible;
- }
-
- get shortcut() {
- return translateModKey(`${PLATFORM_KEY_MODIFIER} alt p`);
- }
-
- <template>
- <ul class="ai-helper-options">
- {{#each @options as |option|}}
- {{#if (eq option.name "custom_prompt")}}
- <AiHelperCustomPrompt
- @value={{@customPromptValue}}
- @promptArgs={{option}}
- @submit={{@performAction}}
- />
- {{else}}
- <li data-name={{option.translated_name}} data-value={{option.name}}>
+const AiHelperOptionsList = <template>
+ <ul class="ai-helper-options">
+ {{#each @options key="name" as |option|}}
+ {{#if (eq option.name "custom_prompt")}}
+ <AiHelperCustomPrompt
+ @value={{@customPromptValue}}
+ @promptArgs={{option}}
+ @submit={{@performAction}}
+ />
+ {{else if (and (eq option.name "proofread") @shortcutVisible)}}
+ <li data-name={{option.translated_name}} data-value={{option.name}}>
+ <DShortcut @keys="mod+alt+p" as |shortcut|>
<DButton
+ class="ai-helper-options__button"
+ data-name={{option.name}}
+ aria-keyshortcuts={{shortcut.aria}}
+ @action={{fn @performAction option}}
@icon={{option.icon}}
@translatedLabel={{option.translated_name}}
- @action={{fn @performAction option}}
- data-name={{option.name}}
- class="ai-helper-options__button"
>
- {{#if (and (eq option.name "proofread") this.showShortcut)}}
- <kbd class="shortcut">{{this.shortcut}}</kbd>
- {{/if}}
+ <shortcut.Kbd class="shortcut" />
</DButton>
- </li>
- {{/if}}
- {{/each}}
- </ul>
- </template>
-}
+ </DShortcut>
+ </li>
+ {{else}}
+ <li data-name={{option.translated_name}} data-value={{option.name}}>
+ <DButton
+ class="ai-helper-options__button"
+ data-name={{option.name}}
+ @action={{fn @performAction option}}
+ @icon={{option.icon}}
+ @translatedLabel={{option.translated_name}}
+ />
+ </li>
+ {{/if}}
+ {{/each}}
+ </ul>
+</template>;
+
+export default AiHelperOptionsList;
diff --git a/plugins/discourse-ai/assets/stylesheets/modules/ai-helper/common/ai-helper.scss b/plugins/discourse-ai/assets/stylesheets/modules/ai-helper/common/ai-helper.scss
index 706e3025e5d..ad8a5ecfa0d 100644
--- a/plugins/discourse-ai/assets/stylesheets/modules/ai-helper/common/ai-helper.scss
+++ b/plugins/discourse-ai/assets/stylesheets/modules/ai-helper/common/ai-helper.scss
@@ -466,10 +466,6 @@
align-items: center;
.shortcut {
- border: none;
- background: none;
- font-size: var(--font-down-1);
- color: var(--primary-low-mid);
margin-left: auto;
}
}
diff --git a/plugins/discourse-details/test/javascripts/acceptance/details-button-test.js b/plugins/discourse-details/test/javascripts/acceptance/details-button-test.js
index 0ac8273a560..01a8cc79963 100644
--- a/plugins/discourse-details/test/javascripts/acceptance/details-button-test.js
+++ b/plugins/discourse-details/test/javascripts/acceptance/details-button-test.js
@@ -6,8 +6,7 @@ import {
visit,
} from "@ember/test-helpers";
import { test } from "qunit";
-import { translateModKey } from "discourse/lib/utilities";
-import { PLATFORM_KEY_MODIFIER } from "discourse/services/keyboard-shortcuts";
+import { formatShortcut } from "discourse/lib/shortcut-format";
import {
acceptance,
metaModifier,
@@ -156,13 +155,13 @@ acceptance("Details Button", function (needs) {
await click(".toolbar-menu__options-trigger");
- const separator = PLATFORM_KEY_MODIFIER === "meta" ? "" : " ";
+ const shortcut = formatShortcut("mod+shift+d");
assert
- .dom("[data-name='details'] kbd")
- .hasText(
- translateModKey(`${PLATFORM_KEY_MODIFIER}+Shift+D`, separator),
- "shows the platform-specific shortcut"
- );
+ .dom("[data-name='details'] .d-shortcut__key")
+ .exists({ count: shortcut.keys.length }, "draws one keycap per key");
+ assert
+ .dom("[data-name='details']")
+ .hasAttribute("aria-keyshortcuts", shortcut.aria);
});
test("keyboard shortcut inserts a details block in the rich text editor", async function (assert) {
diff --git a/plugins/discourse-local-dates/spec/system/toolbar_shortcut_spec.rb b/plugins/discourse-local-dates/spec/system/toolbar_shortcut_spec.rb
new file mode 100644
index 00000000000..91764ef53ad
--- /dev/null
+++ b/plugins/discourse-local-dates/spec/system/toolbar_shortcut_spec.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+RSpec.describe "Local dates toolbar shortcut" do
+ fab!(:current_user, :admin)
+
+ let(:composer) { PageObjects::Components::Composer.new }
+
+ before { sign_in(current_user) }
+
+ it "shows the shortcut without hovering the menu row" do
+ visit "/"
+ find("#create-topic").click
+ expect(composer).to be_opened
+
+ find(".toolbar-menu__options-trigger").click
+
+ expect(page).to have_css(
+ ".toolbar-menu__options-content [data-name='local-dates'] .d-shortcut",
+ visible: :visible,
+ )
+ end
+end
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/controls.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/controls.gjs
index bcbc139f855..177977a5a34 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/controls.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/controls.gjs
@@ -1,39 +1,48 @@
import DTooltip from "discourse/float-kit/components/d-tooltip";
-import { translateModKey } from "discourse/lib/utilities";
import { not } from "discourse/truth-helpers";
import DButton from "discourse/ui-kit/d-button";
+import DShortcut from "discourse/ui-kit/d-shortcut";
import { i18n } from "discourse-i18n";
-function undoTitle() {
- return `${i18n("discourse_workflows.canvas.undo")} [${translateModKey("Meta+Z")}]`;
-}
-
-function redoTitle() {
- return `${i18n("discourse_workflows.canvas.redo")} [${translateModKey("Meta+Y")}]`;
+function titleWithShortcut(key, label) {
+ const title = i18n(`discourse_workflows.canvas.${key}`);
+ return label ? `${title} [${label}]` : title;
}
export default <template>
<div class="workflows-canvas__controls">
- <DTooltip @identifier="workflow-canvas-undo" @content={{(undoTitle)}}>
- <:trigger>
- <DButton
- @action={{@onUndo}}
- @icon="arrow-rotate-left"
- @disabled={{not @canUndo}}
- class="btn-flat btn-small"
- />
- </:trigger>
- </DTooltip>
- <DTooltip @identifier="workflow-canvas-redo" @content={{(redoTitle)}}>
- <:trigger>
- <DButton
- @action={{@onRedo}}
- @icon="arrow-rotate-right"
- @disabled={{not @canRedo}}
- class="btn-flat btn-small"
- />
- </:trigger>
- </DTooltip>
+ <DShortcut @keys="mod+z" as |shortcut|>
+ <DTooltip
+ @identifier="workflow-canvas-undo"
+ @content={{titleWithShortcut "undo" shortcut.label}}
+ >
+ <:trigger>
+ <DButton
+ class="btn-flat btn-small"
+ aria-keyshortcuts={{shortcut.aria}}
+ @action={{@onUndo}}
+ @disabled={{not @canUndo}}
+ @icon="arrow-rotate-left"
+ />
+ </:trigger>
+ </DTooltip>
+ </DShortcut>
+ <DShortcut @keys="mod+y" as |shortcut|>
+ <DTooltip
+ @identifier="workflow-canvas-redo"
+ @content={{titleWithShortcut "redo" shortcut.label}}
+ >
+ <:trigger>
+ <DButton
+ class="btn-flat btn-small"
+ aria-keyshortcuts={{shortcut.aria}}
+ @action={{@onRedo}}
+ @disabled={{not @canRedo}}
+ @icon="arrow-rotate-right"
+ />
+ </:trigger>
+ </DTooltip>
+ </DShortcut>
<DTooltip
@identifier="workflow-canvas-zoom-out"
@content={{i18n "discourse_workflows.canvas.zoom_out"}}
diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/atoms/shortcut/block.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/atoms/shortcut/block.gjs
new file mode 100644
index 00000000000..7f8b5329831
--- /dev/null
+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/atoms/shortcut/block.gjs
@@ -0,0 +1,15 @@
+import DButton from "discourse/ui-kit/d-button";
+import DShortcut from "discourse/ui-kit/d-shortcut";
+
+export default <template>
+ <DShortcut @always={{true}} @keys="mod+b" as |shortcut|>
+ <DButton
+ class="btn-default"
+ aria-keyshortcuts={{shortcut.aria}}
+ @icon="bold"
+ @translatedLabel="Bold"
+ >
+ <shortcut.Kbd />
+ </DButton>
+ </DShortcut>
+</template>
diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/atoms/shortcut/keyboard-gate.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/atoms/shortcut/keyboard-gate.gjs
new file mode 100644
index 00000000000..17562cb5c27
--- /dev/null
+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/atoms/shortcut/keyboard-gate.gjs
@@ -0,0 +1,21 @@
+import Component from "@glimmer/component";
+import { service } from "@ember/service";
+import DShortcut from "discourse/ui-kit/d-shortcut";
+
+export default class KeyboardGateExample extends Component {
+ @service capabilities;
+
+ <template>
+ <p>
+ <code>capabilities.hasKeyboard</code>
+ is currently
+ <strong class="styleguide-example__result">
+ {{if this.capabilities.hasKeyboard "true" "false"}}
+ </strong>
+ </p>
+ <p>Default: <DShortcut @keys="mod+k" /></p>
+ <p>With
+ <code>@always</code>:
+ <DShortcut @always={{true}} @keys="mod+k" /></p>
+ </template>
+}
diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/atoms/shortcut/keycaps.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/atoms/shortcut/keycaps.gjs
new file mode 100644
index 00000000000..53b9af84571
--- /dev/null
+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/atoms/shortcut/keycaps.gjs
@@ -0,0 +1,9 @@
+import DShortcut from "discourse/ui-kit/d-shortcut";
+
+export default <template>
+ <p><DShortcut @always={{true}} @keys="mod+enter" /></p>
+ <p><DShortcut @always={{true}} @keys="mod+shift+d" /></p>
+ <p><DShortcut @always={{true}} @keys="ctrl+alt+f" /></p>
+ <p><DShortcut @always={{true}} @keys="shift+up" /></p>
+ <p><DShortcut @always={{true}} @keys="esc" /></p>
+</template>
diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/atoms/shortcut/spellings.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/atoms/shortcut/spellings.gjs
new file mode 100644
index 00000000000..882da2b5400
--- /dev/null
+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/atoms/shortcut/spellings.gjs
@@ -0,0 +1,45 @@
+import Component from "@glimmer/component";
+import { formatShortcut } from "discourse/lib/shortcut-format";
+import DShortcut from "discourse/ui-kit/d-shortcut";
+
+const SPELLINGS = [
+ "mod+k",
+ "meta+shift+d",
+ "ctrl+m",
+ "cmd+alt+1",
+ "shift+up",
+ "&darr;",
+ "mod+.",
+ "mod+plus",
+ "g+h",
+];
+
+export default class SpellingsExample extends Component {
+ get rows() {
+ return SPELLINGS.map((spelling) => ({
+ spelling,
+ announced: formatShortcut(spelling).aria,
+ }));
+ }
+
+ <template>
+ <table class="styleguide-shortcut-spellings">
+ <thead>
+ <tr>
+ <th>Spelling</th>
+ <th>Drawn</th>
+ <th>Announced</th>
+ </tr>
+ </thead>
+ <tbody>
+ {{#each this.rows key="spelling" as |row|}}
+ <tr>
+ <td><code>{{row.spelling}}</code></td>
+ <td><DShortcut @always={{true}} @keys={{row.spelling}} /></td>
+ <td><code>{{row.announced}}</code></td>
+ </tr>
+ {{/each}}
+ </tbody>
+ </table>
+ </template>
+}
diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/atoms/shortcut/string-form.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/atoms/shortcut/string-form.gjs
new file mode 100644
index 00000000000..c2d0fa0c1c8
--- /dev/null
+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/atoms/shortcut/string-form.gjs
@@ -0,0 +1,21 @@
+import Component from "@glimmer/component";
+import { formatShortcut } from "discourse/lib/shortcut-format";
+import DButton from "discourse/ui-kit/d-button";
+
+export default class StringFormExample extends Component {
+ shortcut = formatShortcut("mod+enter");
+
+ get title() {
+ return `Save (${this.shortcut.label})`;
+ }
+
+ <template>
+ <DButton
+ class="btn-primary"
+ aria-keyshortcuts={{this.shortcut.aria}}
+ @icon="check"
+ @translatedLabel="Save"
+ @translatedTitle={{this.title}}
+ />
+ </template>
+}
diff --git a/plugins/styleguide/assets/javascripts/discourse/components/sections/atoms/11-shortcut.gjs b/plugins/styleguide/assets/javascripts/discourse/components/sections/atoms/11-shortcut.gjs
new file mode 100644
index 00000000000..e98d6ecbfdf
--- /dev/null
+++ b/plugins/styleguide/assets/javascripts/discourse/components/sections/atoms/11-shortcut.gjs
@@ -0,0 +1,70 @@
+import { concat } from "@ember/helper";
+import { i18n } from "discourse-i18n";
+import StyleguideExample from "discourse/plugins/styleguide/discourse/components/styleguide-example";
+import BlockExample from "../../examples/atoms/shortcut/block";
+import blockSource from "../../examples/atoms/shortcut/block?source=file";
+import KeyboardGateExample from "../../examples/atoms/shortcut/keyboard-gate";
+import keyboardGateSource from "../../examples/atoms/shortcut/keyboard-gate?source=file";
+import KeycapsExample from "../../examples/atoms/shortcut/keycaps";
+import keycapsSource from "../../examples/atoms/shortcut/keycaps?source=file";
+import SpellingsExample from "../../examples/atoms/shortcut/spellings";
+import spellingsSource from "../../examples/atoms/shortcut/spellings?source=file";
+import StringFormExample from "../../examples/atoms/shortcut/string-form";
+import stringFormSource from "../../examples/atoms/shortcut/string-form?source=file";
+
+const KEY = "styleguide.sections.shortcut";
+
+export default <template>
+ <p class="section-description">
+ {{i18n (concat KEY ".description")}}
+ </p>
+
+ <StyleguideExample
+ @title={{i18n (concat KEY ".keycaps_example")}}
+ @description={{i18n (concat KEY ".keycaps_description")}}
+ @note={{i18n (concat KEY ".keycaps_note")}}
+ @kind="component"
+ @code={{keycapsSource}}
+ >
+ <KeycapsExample />
+ </StyleguideExample>
+
+ <StyleguideExample
+ @title={{i18n (concat KEY ".block_example")}}
+ @description={{i18n (concat KEY ".block_description")}}
+ @tryThis={{i18n (concat KEY ".block_try_this")}}
+ @note={{i18n (concat KEY ".block_note")}}
+ @kind="component"
+ @code={{blockSource}}
+ >
+ <BlockExample />
+ </StyleguideExample>
+
+ <StyleguideExample
+ @title={{i18n (concat KEY ".string_form_example")}}
+ @description={{i18n (concat KEY ".string_form_description")}}
+ @tryThis={{i18n (concat KEY ".string_form_try_this")}}
+ @code={{stringFormSource}}
+ >
+ <StringFormExample />
+ </StyleguideExample>
+
+ <StyleguideExample
+ @title={{i18n (concat KEY ".spellings_example")}}
+ @description={{i18n (concat KEY ".spellings_description")}}
+ @note={{i18n (concat KEY ".spellings_note")}}
+ @code={{spellingsSource}}
+ >
+ <SpellingsExample />
+ </StyleguideExample>
+
+ <StyleguideExample
+ @title={{i18n (concat KEY ".keyboard_gate_example")}}
+ @description={{i18n (concat KEY ".keyboard_gate_description")}}
+ @tryThis={{i18n (concat KEY ".keyboard_gate_try_this")}}
+ @note={{i18n (concat KEY ".keyboard_gate_note")}}
+ @code={{keyboardGateSource}}
+ >
+ <KeyboardGateExample />
+ </StyleguideExample>
+</template>
diff --git a/plugins/styleguide/assets/javascripts/discourse/components/sections/organisms/docked-composer.gjs b/plugins/styleguide/assets/javascripts/discourse/components/sections/organisms/docked-composer.gjs
index 05fa611edfc..c6559f31716 100644
--- a/plugins/styleguide/assets/javascripts/discourse/components/sections/organisms/docked-composer.gjs
+++ b/plugins/styleguide/assets/javascripts/discourse/components/sections/organisms/docked-composer.gjs
@@ -16,7 +16,7 @@ export default class DockedComposerSection extends Component {
@tracked resizable = true;
@tracked disabled = false;
@tracked placeholder = i18n("composer.reply_placeholder");
- submitTitle = "composer.title";
+ submitTitle = "composer.reply";
@action
toggleResizable() {
diff --git a/plugins/styleguide/assets/javascripts/discourse/lib/styleguide.js b/plugins/styleguide/assets/javascripts/discourse/lib/styleguide.js
index 0744eeafc47..f2dd54bc566 100644
--- a/plugins/styleguide/assets/javascripts/discourse/lib/styleguide.js
+++ b/plugins/styleguide/assets/javascripts/discourse/lib/styleguide.js
@@ -9,6 +9,7 @@ import otp from "../components/sections/atoms/07-otp";
import dateTimeInputs from "../components/sections/atoms/08-date-time-inputs";
import dropdowns from "../components/sections/atoms/09-dropdowns";
import topicLink from "../components/sections/atoms/10-topic-link-status";
+import shortcut from "../components/sections/atoms/11-shortcut";
import breadCrumbs from "../components/sections/molecules/bread-crumbs";
import categories from "../components/sections/molecules/categories";
import charCounter from "../components/sections/molecules/char-counter";
@@ -66,6 +67,7 @@ const SECTIONS = [
{ component: dateTimeInputs, category: "atoms", id: "date-time-inputs" },
{ component: dropdowns, category: "atoms", id: "dropdowns" },
{ component: topicLink, category: "atoms", id: "topic-link" },
+ { component: shortcut, category: "atoms", id: "shortcut" },
{
component: segmentedControl,
category: "atoms",
diff --git a/plugins/styleguide/assets/stylesheets/styleguide.scss b/plugins/styleguide/assets/stylesheets/styleguide.scss
index 96fb5e934d2..b8ec188f3da 100644
--- a/plugins/styleguide/assets/stylesheets/styleguide.scss
+++ b/plugins/styleguide/assets/stylesheets/styleguide.scss
@@ -758,3 +758,10 @@
}
}
}
+
+.styleguide-shortcut-spellings {
+ th,
+ td {
+ padding: var(--space-1) var(--space-4) var(--space-1) 0;
+ }
+}
diff --git a/plugins/styleguide/config/locales/client.en.yml b/plugins/styleguide/config/locales/client.en.yml
index 7d99d1ef1c4..16e95842d53 100644
--- a/plugins/styleguide/config/locales/client.en.yml
+++ b/plugins/styleguide/config/locales/client.en.yml
@@ -276,6 +276,26 @@ en:
title: "Spinners"
otp:
title: "OTP"
+ shortcut:
+ title: "Shortcut"
+ description: "One way to show a keyboard shortcut and announce it. formatShortcut turns the spelling key bindings use into a drawn label and an aria-keyshortcuts value; DShortcut draws it as a chip and, given a block, yields both forms so an element cannot draw one shortcut and announce another."
+ keycaps_example: "Drawing a shortcut"
+ keycaps_description: "`<DShortcut @keys>` draws one chip per shortcut. Spell the keys the way a binding does: `+`-joined, any case, with `mod` for the platform's primary modifier. Modifiers are listed in the platform's own order whatever the spelling, glyph modifiers run together, and every other key keeps a gap."
+ keycaps_note: "On Apple platforms modifiers draw as glyphs (`⌘⇧ D`); elsewhere they draw as words (`Ctrl Shift D`). Each glyph carries a visually hidden spoken name, so the chip reads as \"Command Shift D\" when it is content in its own right."
+ block_example: "Announcing on the element that reacts"
+ block_description: "`aria-keyshortcuts` belongs on the element the keys activate, which only the caller knows. Given a block, `DShortcut` renders no element of its own and yields `aria`, `label`, `keys` and a bound `Kbd`, so the button's announcement and the chip beside it come from one spelling. The yielded chip is hidden from assistive technology, since the button announces the shortcut itself."
+ block_try_this: "Focus the button with a screen reader running: it reads its name once, then the shortcut from the attribute, never the chip."
+ block_note: "The announced form is localized and spoken, not the ARIA token list: readers speak the attribute verbatim, so it says `Command+B` on a Mac and `Ctrl+B` elsewhere, and names punctuation (`Period`, `Slash`) that readers would otherwise drop."
+ string_form_example: "Where only a string fits"
+ string_form_description: "A `title`, an `aria-label` or a select option cannot hold an element. Call `formatShortcut` directly and use `.label` for the text and `.aria` for the attribute; one call, one spelling, both forms."
+ string_form_try_this: "Hover the button for the tooltip; focus it with a screen reader for the announcement."
+ spellings_example: "Spellings and their two forms"
+ spellings_description: "What each input resolves to. `mod`, `meta`, `command` and `cmd` all mean the primary modifier; `ctrl` stays the Control key on every platform; `plus` names the `+` key; arrow words and their HTML entities both draw as arrows."
+ spellings_note: "Only the announced column changes with the interface language; the drawn column changes with the platform."
+ keyboard_gate_example: "Only where there is a keyboard"
+ keyboard_gate_description: "A shortcut is noise on a phone. `capabilities.hasKeyboard` infers a physical keyboard from a fine primary pointer, or from a keydown an on-screen keyboard never sends, and `DShortcut` draws and announces nothing without it. `@always` opts out, for surfaces that exist to document the keys."
+ keyboard_gate_try_this: "Open this page on a phone: the default chip disappears while the `@always` one stays. Pair a keyboard and press a modifier key, and the default chip appears without a reload."
+ keyboard_gate_note: "Every shortcut on the site is gated except the keyboard shortcuts help modal and this page."
empty_state:
title: "Empty State"
tooltips:
diff --git a/plugins/styleguide/spec/system/shortcut_spec.rb b/plugins/styleguide/spec/system/shortcut_spec.rb
new file mode 100644
index 00000000000..82ab0d06ff5
--- /dev/null
+++ b/plugins/styleguide/spec/system/shortcut_spec.rb
@@ -0,0 +1,31 @@
+# frozen_string_literal: true
+
+RSpec.describe "Styleguide shortcut page" do
+ include ThemeScreenshotMarker
+
+ fab!(:admin)
+
+ before do
+ SiteSetting.styleguide_enabled = true
+ sign_in(admin)
+ end
+
+ it "documents the component in the styleguide" do
+ visit "/styleguide/atoms/shortcut"
+
+ %w[keycaps block string_form spellings keyboard_gate].each do |card|
+ expect(page).to have_css(
+ ".styleguide-example__title",
+ text: I18n.t("js.styleguide.sections.shortcut.#{card}_example"),
+ )
+ end
+ expect(page).to have_css(".styleguide-shortcut-spellings tbody tr .d-shortcut", count: 9)
+ expect(page).to have_css(".styleguide-example__result", text: "true")
+ expect(page).to have_css("[aria-keyshortcuts]", minimum: 2)
+
+ if ENV["TAKE_SCREENSHOTS"] == "1"
+ page.scroll_to(find(".styleguide-shortcut-spellings"), align: :center)
+ end
+ screenshot_marker(label: "shortcut-styleguide", only: :desktop)
+ end
+end
diff --git a/plugins/styleguide/spec/system/smoke_test_spec.rb b/plugins/styleguide/spec/system/smoke_test_spec.rb
index b520a7166a9..f1083acd455 100644
--- a/plugins/styleguide/spec/system/smoke_test_spec.rb
+++ b/plugins/styleguide/spec/system/smoke_test_spec.rb
@@ -23,6 +23,7 @@ RSpec.describe "Styleguide Smoke Test" do
{ href: "/atoms/dropdowns", title: "Dropdowns" },
{ href: "/atoms/topic-link", title: "Topic Link and Status" },
{ href: "/atoms/segmented-control", title: "Segmented Control (Button toggle group)" },
+ { href: "/atoms/shortcut", title: "Shortcut" },
],
"molecules" => [
{ href: "/molecules/bread-crumbs", title: "Bread Crumbs" },
diff --git a/spec/system/keyboard_shortcut_display_spec.rb b/spec/system/keyboard_shortcut_display_spec.rb
new file mode 100644
index 00000000000..0f61b3122ef
--- /dev/null
+++ b/spec/system/keyboard_shortcut_display_spec.rb
@@ -0,0 +1,72 @@
+# frozen_string_literal: true
+
+RSpec.describe "Keyboard shortcut display" do
+ include ThemeScreenshotMarker
+
+ fab!(:current_user, :admin)
+
+ let(:composer) { PageObjects::Components::Composer.new }
+
+ before { sign_in(current_user) }
+
+ it "draws every shortcut in the help modal as keycaps" do
+ visit "/"
+ page.send_keys("?")
+
+ expect(page).to have_css(".keyboard-shortcuts-modal .d-shortcut__key")
+ expect(page).to have_no_css(
+ ".keyboard-shortcuts-modal .shortcut-key kbd:not(.d-shortcut, .d-shortcut__key)",
+ )
+
+ screenshot_marker(label: "shortcut-help-modal")
+ end
+
+ it "keeps the gap between keys in a right-to-left locale" do
+ SiteSetting.default_locale = "ar"
+
+ visit "/"
+ page.send_keys("?")
+
+ second_key =
+ find(".keyboard-shortcuts-modal .d-shortcut__key + .d-shortcut__key", match: :first)
+ margin = page.evaluate_script("getComputedStyle(arguments[0]).marginLeft", second_key)
+
+ expect(margin).not_to eq("0px")
+ end
+
+ it "draws the shortcut of a composer menu option as keycaps" do
+ visit "/"
+ find("#create-topic").click
+ expect(composer).to be_opened
+
+ find(".toolbar-menu__heading-trigger").click
+ row = find(".toolbar-menu__heading-content [data-name='heading-small']")
+ row.hover
+
+ expect(row).to have_css(".d-shortcut__key", visible: :all)
+ expect(row["aria-keyshortcuts"]).to match(/(Command|Ctrl)\+/)
+
+ screenshot_marker(label: "shortcut-composer-menu", only: :desktop)
+ end
+
+ it "keeps the gap between an option icon and its label" do
+ visit "/"
+ find("#create-topic").click
+ expect(composer).to be_opened
+
+ find(".toolbar-menu__options-trigger").click
+ icon = find(".toolbar-menu__options-content [data-name='toggle-spreadsheet'] .d-icon")
+ margin = page.evaluate_script("getComputedStyle(arguments[0]).marginRight", icon)
+
+ expect(margin).not_to eq("0px")
+ end
+
+ it "draws the admin sidebar search hint as keycaps" do
+ visit "/admin"
+
+ expect(page).to have_css(".sidebar-search__shortcut-hint.d-shortcut .d-shortcut__key", count: 2)
+ expect(find(".sidebar-search__input")["aria-keyshortcuts"]).to match(/(Command|Ctrl)\+/)
+
+ screenshot_marker(label: "shortcut-sidebar-hint", only: :desktop)
+ end
+end