Skip to content

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

DEV: Return a portaled float to the tab order beside its trigger (#42565)

Sérgio Saquetim4f7a129735dc
diff --git a/frontend/discourse/float-kit/components/d-float-body.gts b/frontend/discourse/float-kit/components/d-float-body.gts
index 3118ca7d739..f0093beca22 100644
--- a/frontend/discourse/float-kit/components/d-float-body.gts
+++ b/frontend/discourse/float-kit/components/d-float-body.gts
@@ -1,4 +1,5 @@
import Component from "@glimmer/component";
+import { assert } from "@ember/debug";
import { fn, hash } from "@ember/helper";
import { trustHTML } from "@ember/template";
import { modifier as modifierFn } from "ember-modifier";
@@ -8,6 +9,7 @@ import { getScrollParent } from "discourse/float-kit/lib/get-scroll-parent";
import { horizontalViewportInset } from "discourse/float-kit/lib/update-position";
import FloatKitApplyFloatingUi from "discourse/float-kit/modifiers/apply-floating-ui";
import FloatKitCloseOnEscape from "discourse/float-kit/modifiers/close-on-escape";
+import FloatKitTabOrderInline from "discourse/float-kit/modifiers/tab-order-inline";
import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
import dCloseOnClickOutside from "discourse/ui-kit/modifiers/d-close-on-click-outside";
import dTrapTab from "discourse/ui-kit/modifiers/d-trap-tab";
@@ -33,6 +35,17 @@ interface DFloatBodySignature {
/** Whether to trap Tab focus within the content. */
trapTab?: boolean;
+ /**
+ * Whether the content should take part in the tab sequence as if it were rendered inline
+ * after the trigger, rather than at the portal's position in the document: Tab leads into its
+ * controls from the trigger, and off the end of them it dismisses the float and continues
+ * from the trigger.
+ *
+ * The non-containing alternative to `trapTab`, for a float that is dismissable but whose
+ * content holds focus. See `FloatKitTabOrderInline`.
+ */
+ inlineTabOrder?: boolean;
+
/**
* The element to render into. Some callers forward this even though the body
* reads `@instance.portalOutletElement`.
@@ -140,6 +153,22 @@ export default class DFloatBody extends Component<DFloatBodySignature> {
return this.args.role === "none" || this.args.role === "presentation";
}
+ /**
+ * Whether to repair the tab order, asserting first that containment was not ALSO asked for.
+ *
+ * The two are alternatives, and the conflict is otherwise silent and one-sided: `dTrapTab` is
+ * applied first below, so its `preventDefault` lands before the tab-order handler runs, and the
+ * float traps focus while its author believes they configured the opposite.
+ */
+ get inlineTabOrder() {
+ assert(
+ "float-kit: `trapTab` and `inlineTabOrder` are alternatives — the first contains focus, the second deliberately lets it leave. Setting both keeps the trap and silently ignores the tab-order repair.",
+ !(this.args.trapTab && this.args.inlineTabOrder)
+ );
+
+ return this.args.inlineTabOrder;
+ }
+
get supportsCloseOnClickOutside() {
return this.options.closeOnClickOutside;
}
@@ -195,6 +224,14 @@ export default class DFloatBody extends Component<DFloatBodySignature> {
{{FloatKitApplyFloatingUi this.trigger this.options @instance}}
{{this.trapInteractionPropagation}}
{{(if @trapTab (modifier dTrapTab autofocus=this.options.autofocus))}}
+ {{(if
+ this.inlineTabOrder
+ (modifier
+ FloatKitTabOrderInline
+ @instance.triggerElement
+ (fn @instance.close (hash focusTrigger=false))
+ )
+ )}}
{{(if
this.supportsCloseOnClickOutside
(modifier
diff --git a/frontend/discourse/float-kit/components/d-headless-menu.gts b/frontend/discourse/float-kit/components/d-headless-menu.gts
index a534f780549..ef82cc0370b 100644
--- a/frontend/discourse/float-kit/components/d-headless-menu.gts
+++ b/frontend/discourse/float-kit/components/d-headless-menu.gts
@@ -23,6 +23,7 @@ const DHeadlessMenu: TemplateOnlyComponent<DHeadlessMenuSignature> = <template>
<DInlineFloat
@instance={{@menu}}
@trapTab={{@menu.options.trapTab}}
+ @inlineTabOrder={{@menu.options.inlineTabOrder}}
@mainClass="fk-d-menu"
@innerClass="fk-d-menu__inner-content"
@role={{@menu.options.contentRole}}
diff --git a/frontend/discourse/float-kit/components/d-inline-float.gts b/frontend/discourse/float-kit/components/d-inline-float.gts
index 050ce5f24ee..c722575ab22 100644
--- a/frontend/discourse/float-kit/components/d-inline-float.gts
+++ b/frontend/discourse/float-kit/components/d-inline-float.gts
@@ -14,6 +14,12 @@ interface DInlineFloatSignature {
/** Whether to trap Tab focus within the content. */
trapTab?: boolean;
+ /**
+ * Whether the content takes part in the tab sequence as if rendered inline after the trigger.
+ * The non-containing alternative to `trapTab`; the two are mutually exclusive.
+ */
+ inlineTabOrder?: boolean;
+
/** A class added to the outer float element. */
mainClass?: string;
@@ -64,6 +70,7 @@ const DInlineFloat: TemplateOnlyComponent<DInlineFloatSignature> = <template>
<DFloatBody
@instance={{@instance}}
@trapTab={{@trapTab}}
+ @inlineTabOrder={{@inlineTabOrder}}
@mainClass={{@mainClass}}
@innerClass={{@innerClass}}
@role={{@role}}
diff --git a/frontend/discourse/float-kit/components/d-menu.gts b/frontend/discourse/float-kit/components/d-menu.gts
index fe7698ef1c6..5ee19ded897 100644
--- a/frontend/discourse/float-kit/components/d-menu.gts
+++ b/frontend/discourse/float-kit/components/d-menu.gts
@@ -173,7 +173,10 @@ export default class DMenu<Data = unknown> extends Component<
// need to call the parent handler to allow arrow key navigation to siblings in toolbar contexts
const parentHandlerResult = this.args.onKeydown?.(event);
- if (!this.#body) {
+ // Inline ordering owns Tab on the trigger, in the capture phase, and decides whether the
+ // panel is entered. Pulling focus into the body here would override a decision to pass over
+ // a panel that offers no stop.
+ if (!this.#body || this.options.inlineTabOrder) {
return parentHandlerResult;
}
@@ -249,10 +252,20 @@ export default class DMenu<Data = unknown> extends Component<
}>;
}
+ /**
+ * Filling the gaps with defaults here would produce the same merged options, but it would erase
+ * the difference between "left unset" and "explicitly set to the default", which the instance
+ * needs in order to let one option imply another.
+ *
+ * @returns Only the options the caller supplied, keyed as in `MENU.options`.
+ */
get allowedProperties() {
const properties: Record<string, unknown> = {};
- for (const [key, value] of Object.entries(MENU.options)) {
- properties[key] = (this.args as Record<string, unknown>)[key] ?? value;
+ for (const key of Object.keys(MENU.options)) {
+ const value = (this.args as Record<string, unknown>)[key];
+ if (value != null) {
+ properties[key] = value;
+ }
}
return properties;
}
@@ -316,6 +329,7 @@ export default class DMenu<Data = unknown> extends Component<
<DFloatBody
@instance={{this.menuInstance}}
@trapTab={{this.options.trapTab}}
+ @inlineTabOrder={{this.options.inlineTabOrder}}
@mainClass={{dConcatClass
"fk-d-menu"
(concat this.options.identifier "-content")
diff --git a/frontend/discourse/float-kit/lib/constants.ts b/frontend/discourse/float-kit/lib/constants.ts
index 94f939b42b4..125c45ffcf9 100644
--- a/frontend/discourse/float-kit/lib/constants.ts
+++ b/frontend/discourse/float-kit/lib/constants.ts
@@ -217,6 +217,25 @@ export interface MenuOptions extends TooltipOptions {
/** Whether to focus the content when the menu opens. */
autofocus: boolean;
+ /**
+ * Whether the menu takes part in the tab sequence as if it were rendered inline after its
+ * trigger, rather than at the portal's position in the document. Tab leads into the menu's own
+ * controls from the trigger, and off the end of them it closes the menu and continues from the
+ * trigger.
+ *
+ * The non-containing alternative to `trapTab`, for a menu that is dismissable but whose content
+ * holds focus. Setting it turns `trapTab` off on its own, so the two never have to be passed
+ * together; a caller that asks for the trap explicitly gets an assertion instead, since only a
+ * contradiction remains. The trap is also what applies `autofocus`, so a menu using this option
+ * opens with focus still on the trigger, which is where tabbing into the content starts from.
+ *
+ * A menu with nothing focusable in it is unaffected in either direction, so this is safe to set
+ * on a menu that only sometimes renders a control. It does not reach a menu that also sets
+ * `modalForMobile`, which on mobile renders as a real `aria-modal` dialog that owns its own
+ * containment.
+ */
+ inlineTabOrder: boolean;
+
/** Whether the menu renders as a modal on mobile. */
modalForMobile: boolean;
@@ -392,6 +411,7 @@ export const MENU: { options: MenuOptions; portalOutletId: string } = {
fallbackPlacements: FLOAT_UI_PLACEMENTS,
autoUpdate: true,
trapTab: true,
+ inlineTabOrder: false,
contentRole: "dialog",
onClose: null,
onShow: null,
diff --git a/frontend/discourse/float-kit/lib/d-menu-instance.ts b/frontend/discourse/float-kit/lib/d-menu-instance.ts
index 8b1bae49f0f..2f71652eb04 100644
--- a/frontend/discourse/float-kit/lib/d-menu-instance.ts
+++ b/frontend/discourse/float-kit/lib/d-menu-instance.ts
@@ -58,7 +58,17 @@ export default class DMenuInstance extends FloatKitInstance {
super();
setOwner(this, owner);
- this.options = { ...MENU.options, ...options };
+
+ const merged = { ...MENU.options, ...options };
+
+ // `trapTab` defaults to true and the two are alternatives, so inline ordering has to switch
+ // it off itself or every caller would carry a second flag. An explicit `trapTab: true` is
+ // left alone for `DFloatBody` to assert on rather than resolved silently here.
+ if (options.inlineTabOrder && options.trapTab === undefined) {
+ merged.trapTab = false;
+ }
+
+ this.options = merged;
this.portalOutletOverrideElement = options.portalOutletElement;
}
diff --git a/frontend/discourse/float-kit/lib/tab-order.ts b/frontend/discourse/float-kit/lib/tab-order.ts
new file mode 100644
index 00000000000..6af10e77130
--- /dev/null
+++ b/frontend/discourse/float-kit/lib/tab-order.ts
@@ -0,0 +1,233 @@
+/**
+ * Tab-order queries for a panel that has been portaled away from its trigger.
+ *
+ * Sequential focus follows document order, so moving a panel out of its trigger's subtree moves
+ * where Tab goes when focus leaves it: to whatever follows the portal, rather than to whatever
+ * follows the control the reader is actually using. These helpers name the stop the reader
+ * expected so a component can put focus there itself.
+ *
+ * The enumeration is only as truthful as the DOM allows. A browser with keyboard-focusable
+ * scrollers adopts a scroll container as a tab stop without marking it, while iframe and shadow
+ * focus scopes do not expose their internal key events or stops here. A surface relying on these
+ * helpers must avoid those focus scopes and suppress adopted scrollers with `tabindex="-1"`.
+ */
+
+/** Elements that can take sequential focus when their current state permits it. */
+const TAB_STOP_SELECTOR = [
+ "a[href]",
+ "area[href]",
+ "button",
+ "input:not([type='hidden'])",
+ "select",
+ "textarea",
+ "summary",
+ "iframe",
+ "audio[controls]",
+ "video[controls]",
+ "[contenteditable]:not([contenteditable='false'])",
+ "[tabindex]",
+].join(", ");
+
+interface TabStopsOptions {
+ ignore?: HTMLElement | null;
+}
+
+/**
+ * The state shared by one enumeration. The caches matter because the tabbability test forces
+ * layout and resolving a radio group queries its whole tree, both repeatedly within one scan.
+ * A scan is created per public call and thrown away with it, so no answer can outlive the DOM
+ * it was measured against.
+ */
+interface TabStopScan {
+ ignore?: HTMLElement | null;
+ tabbable: Map<HTMLElement, boolean>;
+ radios: Map<Node, HTMLInputElement[]>;
+}
+
+function createScan(ignore?: HTMLElement | null): TabStopScan {
+ return { ignore, tabbable: new Map(), radios: new Map() };
+}
+
+function isIgnored(element: HTMLElement, ignore?: HTMLElement | null) {
+ return Boolean(ignore && (element === ignore || ignore.contains(element)));
+}
+
+function computeTabbable(element: HTMLElement): boolean {
+ if (element.tabIndex < 0 || element.matches(":disabled")) {
+ return false;
+ }
+ if (element.closest("[inert]")) {
+ return false;
+ }
+
+ const visibility = getComputedStyle(element).visibility;
+ if (visibility === "hidden" || visibility === "collapse") {
+ return false;
+ }
+
+ return Boolean(
+ element.offsetWidth ||
+ element.offsetHeight ||
+ element.getClientRects().length
+ );
+}
+
+/** Whether `element` can actually be reached by sequential focus right now. */
+function isTabbable(element: HTMLElement, scan: TabStopScan): boolean {
+ const cached = scan.tabbable.get(element);
+ if (cached !== undefined) {
+ return cached;
+ }
+
+ const tabbable = computeTabbable(element);
+ scan.tabbable.set(element, tabbable);
+ return tabbable;
+}
+
+function radiosWithin(
+ tree: Document | ShadowRoot,
+ scan: TabStopScan
+): HTMLInputElement[] {
+ const cached = scan.radios.get(tree);
+ if (cached) {
+ return cached;
+ }
+
+ const radios = Array.from(
+ tree.querySelectorAll<HTMLInputElement>("input[type='radio']")
+ );
+ scan.radios.set(tree, radios);
+ return radios;
+}
+
+function radioGroupRepresentative(
+ radio: HTMLInputElement,
+ scan: TabStopScan
+): HTMLInputElement | null {
+ if (!radio.name) {
+ return radio;
+ }
+
+ const tree = radio.getRootNode();
+ if (!(tree instanceof Document || tree instanceof ShadowRoot)) {
+ return radio;
+ }
+
+ const members = radiosWithin(tree, scan).filter(
+ (member) =>
+ member.name === radio.name &&
+ member.form === radio.form &&
+ !isIgnored(member, scan.ignore) &&
+ isTabbable(member, scan)
+ );
+
+ return members.find((member) => member.checked) ?? members[0] ?? null;
+}
+
+function isRadio(element: HTMLElement): element is HTMLInputElement {
+ return (
+ element instanceof HTMLInputElement &&
+ element.type.toLowerCase() === "radio"
+ );
+}
+
+function compareTabOrder(
+ left: { element: HTMLElement; documentIndex: number },
+ right: { element: HTMLElement; documentIndex: number }
+) {
+ const leftPositive = left.element.tabIndex > 0;
+ const rightPositive = right.element.tabIndex > 0;
+
+ if (leftPositive !== rightPositive) {
+ return leftPositive ? -1 : 1;
+ }
+ if (leftPositive && left.element.tabIndex !== right.element.tabIndex) {
+ return left.element.tabIndex - right.element.tabIndex;
+ }
+ return left.documentIndex - right.documentIndex;
+}
+
+/**
+ * The tab stops inside `root`, in a native-like local sequence. `root` itself is included when it
+ * is a stop. Positive tabindex values are ordered within this local segment; portaling cannot
+ * reproduce their global position without changing the surrounding page's tab order as well.
+ */
+export function tabStopsWithin(
+ root: HTMLElement,
+ { ignore }: TabStopsOptions = {}
+): HTMLElement[] {
+ return collectTabStops(root, createScan(ignore));
+}
+
+function collectTabStops(root: HTMLElement, scan: TabStopScan): HTMLElement[] {
+ const found = Array.from(
+ root.querySelectorAll<HTMLElement>(TAB_STOP_SELECTOR)
+ );
+ const all = root.matches(TAB_STOP_SELECTOR) ? [root, ...found] : found;
+
+ return all
+ .filter(
+ (element) =>
+ !isIgnored(element, scan.ignore) &&
+ isTabbable(element, scan) &&
+ (!isRadio(element) ||
+ radioGroupRepresentative(element, scan) === element)
+ )
+ .map((element, documentIndex) => ({ element, documentIndex }))
+ .sort(compareTabOrder)
+ .map(({ element }) => element);
+}
+
+function isBefore(left: HTMLElement, right: HTMLElement) {
+ const position = left.compareDocumentPosition(right);
+ return (
+ position === Node.DOCUMENT_POSITION_FOLLOWING ||
+ position ===
+ Node.DOCUMENT_POSITION_FOLLOWING + Node.DOCUMENT_POSITION_CONTAINED_BY
+ );
+}
+
+/**
+ * The local tab stop just before or after `anchor`.
+ *
+ * By default the search covers the page. `root` narrows it to a panel, and `ignore` excludes a
+ * portaled panel while finding the page stop beside its trigger. When programmatic focus rests on
+ * a non-candidate, DOM position determines the next candidate in the requested direction.
+ */
+export function adjacentTabStop(
+ anchor: HTMLElement,
+ {
+ forward,
+ ignore,
+ root = document.body,
+ }: {
+ forward: boolean;
+ ignore?: HTMLElement | null;
+ root?: HTMLElement;
+ }
+): HTMLElement | null {
+ // One scan for the whole query, so resolving the anchor's own group below reuses what
+ // enumerating the stops already measured instead of walking the tree a second time.
+ const scan = createScan(ignore);
+ let stops = collectTabStops(root, scan);
+ const index = stops.indexOf(anchor);
+
+ if (index !== -1) {
+ return stops[forward ? index + 1 : index - 1] ?? null;
+ }
+
+ if (isRadio(anchor)) {
+ const representative = radioGroupRepresentative(anchor, scan);
+ // Script can focus another member of an unchecked group, but Tab leaves the group from there
+ // instead of visiting the representative that sequential entry would use.
+ if (representative && !representative.checked) {
+ stops = stops.filter((stop) => stop !== representative);
+ }
+ }
+
+ const candidates = stops.filter((stop) =>
+ forward ? isBefore(anchor, stop) : isBefore(stop, anchor)
+ );
+
+ return (forward ? candidates[0] : candidates.at(-1)) ?? null;
+}
diff --git a/frontend/discourse/float-kit/modifiers/tab-order-inline.ts b/frontend/discourse/float-kit/modifiers/tab-order-inline.ts
new file mode 100644
index 00000000000..6e8401c15ae
--- /dev/null
+++ b/frontend/discourse/float-kit/modifiers/tab-order-inline.ts
@@ -0,0 +1,184 @@
+import { registerDestructor } from "@ember/destroyable";
+import type Owner from "@ember/owner";
+import Modifier, { type ArgsFor } from "ember-modifier";
+import {
+ adjacentTabStop,
+ tabStopsWithin,
+} from "discourse/float-kit/lib/tab-order";
+import { bind } from "discourse/lib/decorators";
+
+interface FloatKitTabOrderInlineSignature {
+ Element: HTMLElement;
+ Args: {
+ Positional: [
+ /** The trigger the float hangs from, whose place in the page Tab should follow. */
+ trigger: HTMLElement | null | undefined,
+ /** Dismisses the float once focus has left it. */
+ close: () => void,
+ ];
+ };
+}
+
+/**
+ * Gives a float's content the tab order it would have had if it were rendered inline, directly
+ * after its trigger.
+ *
+ * A float is portaled out of its trigger's subtree, and sequential focus follows document order,
+ * so the portal's position in the document — not the trigger's — is what Tab actually follows.
+ * That breaks the sequence in both directions: Tab off the end of the float's controls lands
+ * wherever the portal sits, and the float's own controls are never reached at all, since nothing
+ * leads into them from the trigger. Both halves are repaired here:
+ *
+ * - **Into** the float: a forward Tab at the trigger's last stop moves to the float's first stop,
+ * when it has one. A float offering nothing focusable is left alone, so Tab passes over it and
+ * out of the widget — which is what a plain listbox wants, since its rows are reached with the
+ * arrow keys rather than by tabbing.
+ * - **Out of** the float: a Tab that would step off the end of the float's own stops dismisses it
+ * and continues from the TRIGGER. Forward that is the stop after the trigger; backward it is
+ * the trigger's own last stop, which is where the reader came in.
+ *
+ * The float is treated as one logical segment beside the trigger. Every Tab within the segment is
+ * handled from a freshly computed local sequence, so dynamic controls, radio groups, and positive
+ * tabindex values cannot make the browser and the edge check disagree.
+ *
+ * This is the alternative to `trapTab`, not a companion to it. Containment suits a float that is
+ * genuinely modal — a real `aria-modal` dialog, which owns the screen until dismissed — and
+ * strands a reader anywhere else, since a non-modal float shows nothing to say that Tab has
+ * stopped meaning "move on".
+ *
+ * A float that also holds a scroll container should keep it out of the tab sequence with an
+ * explicit `tabindex="-1"`: a browser that adopts scrollers as tab stops does so invisibly, so
+ * such an element consumes a Tab press while being absent from the enumerations below.
+ */
+export default class FloatKitTabOrderInline extends Modifier<FloatKitTabOrderInlineSignature> {
+ #close?: () => void;
+ #content?: HTMLElement;
+ #departing = false;
+ #trigger: HTMLElement | null = null;
+
+ constructor(owner: Owner, args: ArgsFor<FloatKitTabOrderInlineSignature>) {
+ super(owner, args);
+ registerDestructor(this, () => this.#cleanup());
+ }
+
+ modify(
+ element: HTMLElement,
+ [trigger, close]: FloatKitTabOrderInlineSignature["Args"]["Positional"]
+ ) {
+ this.#content = element;
+ this.#close = close;
+
+ element.removeEventListener("keydown", this.handleContentKeydown);
+ element.addEventListener("keydown", this.handleContentKeydown);
+
+ // The trigger listener lives exactly as long as this modifier, which lives as long as the
+ // float's content — so it is bound only while the float is open, which is the only time
+ // entering it is meaningful. Rebound rather than assumed stable, since `modify` re-runs
+ // whenever the trigger argument changes.
+ //
+ // CAPTURE phase, because a control inside the trigger may stop Tab from bubbling. When the
+ // panel has a stop, inline ordering is authoritative and intentionally precedes consumer
+ // bubbling handlers. With no panel stop, the event continues untouched.
+ this.#trigger?.removeEventListener(
+ "keydown",
+ this.handleTriggerKeydown,
+ true
+ );
+ this.#trigger = trigger ?? null;
+ this.#trigger?.addEventListener("keydown", this.handleTriggerKeydown, true);
+ }
+
+ /** Forward Tab at the trigger's last stop enters the float, when the float has a stop to offer. */
+ @bind
+ handleTriggerKeydown(event: KeyboardEvent) {
+ if (
+ event.key !== "Tab" ||
+ event.shiftKey ||
+ event.isComposing ||
+ event.defaultPrevented ||
+ this.#departing
+ ) {
+ return;
+ }
+
+ const content = this.#content;
+ const trigger = this.#trigger;
+ if (!content || !trigger) {
+ return;
+ }
+
+ // Backward is deliberately not handled: the stop before the trigger is already the previous
+ // element in the page, which is what a native Shift+Tab reaches.
+ const triggerStops = tabStopsWithin(trigger);
+ const lastTriggerStop = triggerStops.at(-1);
+ if (!lastTriggerStop || document.activeElement !== lastTriggerStop) {
+ return;
+ }
+
+ const contentStops = tabStopsWithin(content);
+ if (!contentStops.length) {
+ return;
+ }
+
+ event.preventDefault();
+ contentStops[0].focus();
+ }
+
+ /** Moves within the float's logical segment, or leaves it from the trigger's page position. */
+ @bind
+ handleContentKeydown(event: KeyboardEvent) {
+ if (
+ event.key !== "Tab" ||
+ event.isComposing ||
+ event.defaultPrevented ||
+ this.#departing
+ ) {
+ return;
+ }
+
+ const content = this.#content;
+ const trigger = this.#trigger;
+ if (!content || !trigger) {
+ return;
+ }
+
+ const forward = !event.shiftKey;
+ const active = document.activeElement;
+ if (!(active instanceof HTMLElement)) {
+ return;
+ }
+
+ const internalTarget = adjacentTabStop(active, { forward, root: content });
+ if (internalTarget) {
+ event.preventDefault();
+ internalTarget.focus();
+ return;
+ }
+
+ const triggerAnchor = tabStopsWithin(trigger).at(-1);
+ const target = forward
+ ? triggerAnchor &&
+ adjacentTabStop(triggerAnchor, { forward: true, ignore: content })
+ : triggerAnchor;
+
+ this.#departing = true;
+ if (target) {
+ event.preventDefault();
+ }
+
+ // Focus BEFORE dismissing. Dismissal unmounts the content and would drop focus to `<body>`,
+ // and it may settle asynchronously, so moving focus afterwards races the teardown instead of
+ // replacing it.
+ target?.focus();
+ this.#close?.();
+ }
+
+ #cleanup() {
+ this.#content?.removeEventListener("keydown", this.handleContentKeydown);
+ this.#trigger?.removeEventListener(
+ "keydown",
+ this.handleTriggerKeydown,
+ true
+ );
+ }
+}
diff --git a/frontend/discourse/tests/integration/components/float-kit/tab-order-inline-test.gjs b/frontend/discourse/tests/integration/components/float-kit/tab-order-inline-test.gjs
new file mode 100644
index 00000000000..a34d4effcbd
--- /dev/null
+++ b/frontend/discourse/tests/integration/components/float-kit/tab-order-inline-test.gjs
@@ -0,0 +1,686 @@
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import {
+ click,
+ find,
+ focus,
+ render,
+ settled,
+ setupOnerror,
+ tab,
+} from "@ember/test-helpers";
+import { module, test } from "qunit";
+import DMenu from "discourse/float-kit/components/d-menu";
+import {
+ adjacentTabStop,
+ tabStopsWithin,
+} from "discourse/float-kit/lib/tab-order";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import dElement from "discourse/ui-kit/helpers/d-element";
+
+/**
+ * `inlineTabOrder` only means anything when the content is portaled away from its trigger, and
+ * float-kit renders floats IN PLACE under tests (`DFloatPortal`, `@inline ?? isTesting()`). So
+ * every case here forces the portal on with `@inline={{false}}` and points it at an outlet placed
+ * away from the trigger, reproducing the real arrangement, where the portal's position is not the
+ * trigger's, and where native Tab out of the panel would therefore land in the wrong place.
+ *
+ * The outlet usually sits LAST in the document, so DOM order is trigger → neighbour → portal. One
+ * case moves it BETWEEN the two instead, which is the only arrangement where the panel is itself
+ * the next stop after the trigger, and so the only one that can pin that the search for that stop
+ * excludes the panel.
+ *
+ * Each menu waits on `{{#if this.outlet}}`: the outlet element only exists after its own insert
+ * hook runs, and `{{#in-element}}` rejects a nullish destination. The menu still renders in its
+ * template position.
+ *
+ * The `tab()` helper dispatches a cancelable, bubbling `keydown` and moves focus only when the
+ * default is not prevented, so the modifier's handling is exercised rather than bypassed.
+ *
+ * What it CANNOT exercise is a browser adopting a scroll container as a tab stop: `tab()` picks
+ * candidates by `tabIndex >= 0`, and an adopted scroller reports `-1` exactly like one that opted
+ * out. A surface using this option must opt such a scroller out explicitly with `tabindex="-1"`.
+ */
+module(
+ "Integration | Modifier | FloatKit | tab-order-inline",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ // Identity by id, so a failure names the element that actually holds focus.
+ const activeId = () =>
+ document.activeElement?.id ||
+ document.activeElement?.className ||
+ "<none>";
+
+ hooks.beforeEach(function () {
+ this.setOutlet = (element) => this.set("outlet", element);
+ });
+
+ test("Tab enters the float's own controls, then leaves for the trigger's neighbour", async function (assert) {
+ await render(
+ <template>
+ {{#if this.outlet}}
+ <DMenu
+ @inline={{false}}
+ @inlineTabOrder={{true}}
+ @label="trigger"
+ @portalOutletElement={{this.outlet}}
+ >
+ <:content>
+ <button type="button" id="in-panel" class="in-panel">panel
+ action</button>
+ </:content>
+ </DMenu>
+ {{/if}}
+ <button
+ type="button"
+ id="after-trigger"
+ class="after-trigger"
+ >after</button>
+ <div id="outlet" {{didInsert this.setOutlet}}></div>
+ </template>
+ );
+
+ await click(".fk-d-menu__trigger");
+ assert
+ .dom("#outlet .in-panel")
+ .exists("the panel really is portaled out");
+
+ // Into the panel. Native order would send this to `.after-trigger`, since the outlet sits
+ // beyond it in the document.
+ await tab();
+ assert.strictEqual(
+ activeId(),
+ "in-panel",
+ "Tab from the trigger enters the panel's control"
+ );
+
+ // Off the end of the panel's controls: back to the field's place in the page.
+ await tab();
+ assert.strictEqual(
+ activeId(),
+ "after-trigger",
+ "Tab off the last panel control resumes after the TRIGGER, not after the portal"
+ );
+ assert
+ .dom("#outlet .in-panel")
+ .doesNotExist("leaving the panel also dismisses it");
+ });
+
+ test("the option alone is enough, without turning containment off by hand", async function (assert) {
+ await render(
+ <template>
+ {{#if this.outlet}}
+ <DMenu
+ @inline={{false}}
+ @inlineTabOrder={{true}}
+ @label="trigger"
+ @portalOutletElement={{this.outlet}}
+ >
+ <:content>
+ <button type="button" id="in-panel">panel action</button>
+ </:content>
+ </DMenu>
+ {{/if}}
+ <button type="button" id="after-trigger">after</button>
+ <div id="outlet" {{didInsert this.setOutlet}}></div>
+ </template>
+ );
+
+ await click(".fk-d-menu__trigger");
+
+ // A menu traps Tab by default, so the option has to be enough on its own: requiring the
+ // trap to be switched off too would make every call site carry a second flag.
+ await tab();
+ assert
+ .dom("#in-panel")
+ .isFocused(
+ "Tab enters the panel without the trap being switched off too"
+ );
+
+ await tab();
+ assert
+ .dom("#after-trigger")
+ .isFocused("and leaving it still resumes beside the trigger");
+ });
+
+ test("Tab visits every panel control before the float is left", async function (assert) {
+ await render(
+ <template>
+ {{#if this.outlet}}
+ <DMenu
+ @inline={{false}}
+ @inlineTabOrder={{true}}
+ @label="trigger"
+ @portalOutletElement={{this.outlet}}
+ >
+ <:content>
+ <input id="panel-filter" aria-label="filter" />
+ <button type="button" id="panel-action">panel action</button>
+ </:content>
+ </DMenu>
+ {{/if}}
+ <button type="button" id="after-trigger">after</button>
+ <div id="outlet" {{didInsert this.setOutlet}}></div>
+ </template>
+ );
+
+ await click(".fk-d-menu__trigger");
+
+ await tab();
+ assert
+ .dom("#panel-filter")
+ .isFocused("Tab enters at the panel's first stop");
+
+ // Movement WITHIN the panel: the modifier drives it from its own local sequence rather than
+ // leaving it to the browser, so a second control must be reached before the float is left.
+ await tab();
+ assert
+ .dom("#panel-action")
+ .isFocused("Tab reaches the panel's next control instead of leaving");
+
+ await tab({ backwards: true });
+ assert
+ .dom("#panel-filter")
+ .isFocused("Shift+Tab moves back within the panel");
+
+ await tab();
+ await tab();
+ assert
+ .dom("#after-trigger")
+ .isFocused("only the stop past the LAST control leaves the panel");
+ assert
+ .dom("#panel-action")
+ .doesNotExist("and leaving it dismisses the float");
+ });
+
+ test("the forward exit steps over the panel to reach the trigger's neighbour", async function (assert) {
+ await render(
+ <template>
+ {{#if this.outlet}}
+ <DMenu
+ @inline={{false}}
+ @inlineTabOrder={{true}}
+ @label="trigger"
+ @portalOutletElement={{this.outlet}}
+ >
+ <:content>
+ <button type="button" id="in-panel">panel action</button>
+ </:content>
+ </DMenu>
+ {{/if}}
+ {{! The outlet sits BETWEEN the trigger and its neighbour, so the panel's own control is
+ the next stop in document order. Searching the page for the stop after the trigger
+ has to exclude the panel, or the forward exit lands back inside the float it is
+ dismissing. }}
+ <div id="outlet" {{didInsert this.setOutlet}}></div>
+ <button type="button" id="after-trigger">after</button>
+ </template>
+ );
+
+ await click(".fk-d-menu__trigger");
+ await tab();
+ assert
+ .dom("#in-panel")
+ .isFocused("Tab from the trigger enters the panel");
+
+ await tab();
+ assert
+ .dom("#after-trigger")
+ .isFocused(
+ "the panel is not a candidate for the stop after the trigger"
+ );
+ assert.dom("#in-panel").doesNotExist("the float is dismissed on the way");
+ });
+
+ test("a non-focusable trigger wrapper resumes from its last stop", async function (assert) {
+ await render(
+ <template>
+ {{#if this.outlet}}
+ <DMenu
+ @inline={{false}}
+ @inlineTabOrder={{true}}
+ @triggerComponent={{dElement "div"}}
+ @portalOutletElement={{this.outlet}}
+ >
+ <:trigger>
+ <input id="trigger-input" aria-label="trigger" />
+ </:trigger>
+ <:content>
+ <button type="button" id="in-panel">panel action</button>
+ </:content>
+ </DMenu>
+ {{/if}}
+ <button type="button" id="after-trigger">after</button>
+ <div id="outlet" {{didInsert this.setOutlet}}></div>
+ </template>
+ );
+
+ await click(".fk-d-menu__trigger");
+ await focus("#trigger-input");
+ await tab();
+ assert.dom("#in-panel").isFocused("the trigger input enters the panel");
+
+ await tab();
+ assert
+ .dom("#after-trigger")
+ .isFocused("forward exit resumes after the trigger wrapper");
+ assert.dom("#in-panel").doesNotExist("forward exit dismisses the panel");
+ });
+
+ test("a compound trigger finishes its own tab sequence before entering the panel", async function (assert) {
+ await render(
+ <template>
+ <button type="button" id="before-trigger">before</button>
+ {{#if this.outlet}}
+ <DMenu
+ @inline={{false}}
+ @inlineTabOrder={{true}}
+ @triggerComponent={{dElement "div"}}
+ @portalOutletElement={{this.outlet}}
+ >
+ <:trigger>
+ <input id="trigger-first" aria-label="first trigger control" />
+ <button type="button" id="trigger-last">last trigger control</button>
+ </:trigger>
+ <:content>
+ <button type="button" id="in-panel">panel action</button>
+ </:content>
+ </DMenu>
+ {{/if}}
+ <button type="button" id="after-trigger">after</button>
+ <div id="outlet" {{didInsert this.setOutlet}}></div>
+ </template>
+ );
+
+ await click(".fk-d-menu__trigger");
+ await focus("#trigger-first");
+ await tab();
+ assert
+ .dom("#trigger-last")
+ .isFocused("Tab from an early trigger stop stays in the trigger");
+
+ await tab();
+ assert
+ .dom("#in-panel")
+ .isFocused("Tab from the trigger's last stop enters the panel");
+
+ await tab({ backwards: true });
+ assert
+ .dom("#trigger-last")
+ .isFocused("backward panel exit returns to the trigger's last stop");
+
+ await click(".fk-d-menu__trigger");
+ await focus("#trigger-first");
+ await tab({ backwards: true });
+ assert
+ .dom("#before-trigger")
+ .isFocused(
+ "Shift+Tab from the trigger follows the page's backward order"
+ );
+ });
+
+ test("Shift+Tab out of the float returns to the trigger", async function (assert) {
+ await render(
+ <template>
+ {{#if this.outlet}}
+ <DMenu
+ @inline={{false}}
+ @inlineTabOrder={{true}}
+ @label="trigger"
+ @portalOutletElement={{this.outlet}}
+ >
+ <:content>
+ <button type="button" id="in-panel" class="in-panel">panel
+ action</button>
+ </:content>
+ </DMenu>
+ {{/if}}
+ <div id="outlet" {{didInsert this.setOutlet}}></div>
+ </template>
+ );
+
+ await click(".fk-d-menu__trigger");
+ await tab();
+ assert.strictEqual(activeId(), "in-panel");
+
+ await tab({ backwards: true });
+ assert
+ .dom(".fk-d-menu__trigger")
+ .isFocused(
+ "backwards off the first panel control is the trigger, where the reader came in"
+ );
+ });
+
+ test("a float with nothing focusable is passed over", async function (assert) {
+ await render(
+ <template>
+ {{#if this.outlet}}
+ <DMenu
+ @inline={{false}}
+ @inlineTabOrder={{true}}
+ @label="trigger"
+ @portalOutletElement={{this.outlet}}
+ >
+ <:content>
+ <p class="in-panel">nothing to focus here</p>
+ </:content>
+ </DMenu>
+ {{/if}}
+ <button
+ type="button"
+ id="after-trigger"
+ class="after-trigger"
+ >after</button>
+ <div id="outlet" {{didInsert this.setOutlet}}></div>
+ </template>
+ );
+
+ await click(".fk-d-menu__trigger");
+ assert.dom("#outlet .in-panel").exists();
+
+ // The fall-through path: a panel that is only a list must never pull focus in, since its
+ // rows are reached with the arrow keys rather than by tabbing.
+ await tab();
+ assert
+ .dom("#after-trigger")
+ .isFocused("Tab passes a float that offers no stop of its own");
+ });
+
+ test("asserts when containment is asked for as well", async function (assert) {
+ let fired = false;
+ setupOnerror((error) => {
+ fired = true;
+ assert.true(
+ error.message.includes("alternatives"),
+ "the assertion says the two options are alternatives"
+ );
+ });
+
+ await render(
+ <template>
+ {{#if this.outlet}}
+ <DMenu
+ @inline={{false}}
+ @trapTab={{true}}
+ @inlineTabOrder={{true}}
+ @label="trigger"
+ @portalOutletElement={{this.outlet}}
+ >
+ <:content>
+ <button type="button" id="in-panel">panel action</button>
+ </:content>
+ </DMenu>
+ {{/if}}
+ <div id="outlet" {{didInsert this.setOutlet}}></div>
+ </template>
+ );
+
+ await click(".fk-d-menu__trigger");
+
+ // Also pins that the template reads the GETTER rather than the argument: routed around it,
+ // the conflict would go back to being silent, with the trap quietly winning.
+ assert.true(fired, "the conflicting configuration asserts");
+ });
+
+ test("without the option, Tab out of the float does not come back to the trigger", async function (assert) {
+ await render(
+ <template>
+ {{#if this.outlet}}
+ <DMenu
+ @inline={{false}}
+ @trapTab={{false}}
+ @label="trigger"
+ @portalOutletElement={{this.outlet}}
+ >
+ <:content>
+ <button type="button" id="in-panel" class="in-panel">panel
+ action</button>
+ </:content>
+ </DMenu>
+ {{/if}}
+ <button
+ type="button"
+ id="after-trigger"
+ class="after-trigger"
+ >after</button>
+ <div id="outlet" {{didInsert this.setOutlet}}></div>
+ </template>
+ );
+
+ await click(".fk-d-menu__trigger");
+
+ // Focus a panel control directly rather than tabbing to it: DMenu has its own older
+ // `forwardTabToContent`, which pulls focus into the body on Tab whenever a body exists, so
+ // the INTO direction is not a clean contrast. The OUT direction is.
+ await click("#in-panel");
+ assert.strictEqual(activeId(), "in-panel");
+
+ // The defect the option exists to fix, pinned so it cannot quietly become a no-op. Native
+ // order continues from the PORTAL, which is last in the document, so the field's neighbour
+ // is never reached.
+ await tab();
+ assert
+ .dom(".after-trigger")
+ .isNotFocused(
+ "without the repair, leaving the panel does not resume beside the trigger"
+ );
+ });
+
+ test("tab stops honor disabled fieldset semantics", async function (assert) {
+ await render(
+ <template>
+ <div id="root">
+ <fieldset disabled>
+ <legend><button id="first-legend">first legend</button></legend>
+ <button id="fieldset-control">disabled control</button>
+ <legend><button id="second-legend">second legend</button></legend>
+ </fieldset>
+ <button id="after-fieldset">after</button>
+ </div>
+ </template>
+ );
+
+ assert.deepEqual(
+ tabStopsWithin(find("#root")).map((element) => element.id),
+ ["first-legend", "after-fieldset"],
+ "only the first legend escapes a disabled fieldset"
+ );
+ });
+
+ test("tab stops use the checked radio as the group's single stop", async function (assert) {
+ await render(
+ <template>
+ <input
+ id="checked-outside"
+ type="radio"
+ name="outside-group"
+ checked
+ />
+ <div id="root">
+ <input id="unchecked" type="radio" name="group" />
+ <input id="checked" type="radio" name="group" checked />
+ <input id="unchecked-after" type="radio" name="group" />
+ <input
+ id="suppressed-by-outside"
+ type="radio"
+ name="outside-group"
+ />
+ </div>
+ </template>
+ );
+
+ assert.deepEqual(
+ tabStopsWithin(find("#root")).map((element) => element.id),
+ ["checked"],
+ "radio membership is resolved across the full document group"
+ );
+ });
+
+ test("unchecked radio groups keep one stop and exit from a programmatically focused member", async function (assert) {
+ await render(
+ <template>
+ <div id="root">
+ <button id="before-radios">before</button>
+ <input id="first-radio" type="radio" name="group" />
+ <input id="focused-radio" type="radio" name="group" />
+ <button id="after-radios">after</button>
+ <form id="form-a">
+ <input id="form-a-radio" type="radio" name="shared" />
+ </form>
+ <form id="form-b">
+ <input id="form-b-radio" type="radio" name="shared" />
+ </form>
+ </div>
+ </template>
+ );
+
+ const root = find("#root");
+ const focusedRadio = find("#focused-radio");
+
+ assert.deepEqual(
+ tabStopsWithin(root).map((element) => element.id),
+ [
+ "before-radios",
+ "first-radio",
+ "after-radios",
+ "form-a-radio",
+ "form-b-radio",
+ ],
+ "an unchecked group exposes its first member, while separate forms expose one each"
+ );
+ assert.strictEqual(
+ adjacentTabStop(focusedRadio, { forward: false, root })?.id,
+ "before-radios",
+ "Shift+Tab exits an unchecked group from a programmatically focused non-stop"
+ );
+ assert.strictEqual(
+ adjacentTabStop(focusedRadio, { forward: true, root })?.id,
+ "after-radios",
+ "Tab exits an unchecked group from a programmatically focused non-stop"
+ );
+ });
+
+ test("tab stops sort positive tabindex before the regular sequence", async function (assert) {
+ await render(
+ <template>
+ <div id="root">
+ <button id="regular-first">regular first</button>
+ <button id="positive-two" tabindex="2">positive two</button>
+ <button id="positive-one-a" tabindex="1">positive one a</button>
+ <button id="positive-one-b" tabindex="1">positive one b</button>
+ <button id="regular-last">regular last</button>
+ </div>
+ </template>
+ );
+
+ assert.deepEqual(
+ tabStopsWithin(find("#root")).map((element) => element.id),
+ [
+ "positive-one-a",
+ "positive-one-b",
+ "positive-two",
+ "regular-first",
+ "regular-last",
+ ],
+ "positive values are ascending and ties retain document order"
+ );
+ });
+
+ test("tab stops drop an ignored subtree and the stops inside it", async function (assert) {
+ await render(
+ <template>
+ <div id="root">
+ <button id="before-panel">before</button>
+ <div id="panel">
+ <input id="panel-filter" aria-label="filter" />
+ <button id="panel-action">panel action</button>
+ </div>
+ <button id="after-panel">after</button>
+ </div>
+ </template>
+ );
+
+ const root = find("#root");
+ const panel = find("#panel");
+
+ assert.deepEqual(
+ tabStopsWithin(root, { ignore: panel }).map((element) => element.id),
+ ["before-panel", "after-panel"],
+ "the ignored element and its descendants are both excluded"
+ );
+ assert.strictEqual(
+ adjacentTabStop(find("#before-panel"), {
+ forward: true,
+ ignore: panel,
+ root,
+ })?.id,
+ "after-panel",
+ "the stop after an anchor skips the ignored subtree entirely"
+ );
+ });
+
+ test("each call re-measures instead of answering from an earlier one", async function (assert) {
+ await render(
+ <template>
+ {{! Names unique to this test: group membership is resolved by querying the whole
+ document, so a name shared with another fixture would make the two depend on
+ teardown order. }}
+ <div id="root">
+ <button id="rescan-control">control</button>
+ <input id="rescan-first-radio" type="radio" name="rescan-group" />
+ {{#if this.showLateRadio}}
+ <input
+ id="rescan-late-radio"
+ type="radio"
+ name="rescan-group"
+ checked
+ />
+ {{/if}}
+ </div>
+ </template>
+ );
+
+ const root = find("#root");
+
+ assert.deepEqual(
+ tabStopsWithin(root).map((element) => element.id),
+ ["rescan-control", "rescan-first-radio"],
+ "the unchecked group starts out represented by its first member"
+ );
+
+ // Both answers above are measured, not derived: tabbability comes from live layout and
+ // state, and a group's representative from the radios present at the time. Reusing either
+ // measurement past the call that took it would report the DOM as it used to be.
+ find("#rescan-control").tabIndex = -1;
+ this.set("showLateRadio", true);
+ await settled();
+
+ assert.deepEqual(
+ tabStopsWithin(root).map((element) => element.id),
+ ["rescan-late-radio"],
+ "the opted-out control is gone and the newly checked radio represents the group"
+ );
+ });
+
+ test("tab stops follow keyboard visibility rather than the accessibility tree", async function (assert) {
+ await render(
+ <template>
+ <div id="root">
+ <button id="aria-hidden" aria-hidden="true">aria hidden</button>
+ <button id="transparent" style="opacity: 0">transparent</button>
+ <button id="visibility-hidden" style="visibility: hidden">visibility
+ hidden</button>
+ <button id="display-none" style="display: none">display none</button>
+ <div inert><button id="inert">inert</button></div>
+ </div>
+ </template>
+ );
+
+ assert.deepEqual(
+ tabStopsWithin(find("#root")).map((element) => element.id),
+ ["aria-hidden", "transparent"],
+ "ARIA and opacity do not remove focus, while CSS visibility and inertness do"
+ );
+ });
+ }
+);