A platform for community discussion. Free, open, simple.
DEV: Extend the FloatKit menu surface and settle its positioning (#42376)
Sérgio Saquetim2f70686a3fe4
diff --git a/frontend/discourse/float-kit/components/d-float-body.gts b/frontend/discourse/float-kit/components/d-float-body.gtsindex eea32d97833..ceeedfda920 100644--- a/frontend/discourse/float-kit/components/d-float-body.gts+++ b/frontend/discourse/float-kit/components/d-float-body.gts@@ -80,6 +80,22 @@ export default class DFloatBody extends Component<DFloatBodySignature> {};});+ get contentAriaLabelledby(): string | null | undefined {+ if (this.#hasPresentationalRole) {+ return;+ }++ return this.args.instance.id;+ }++ /**+ * `presentation` prohibits an accessible name outright, and `none` is its synonym, so a+ * container in either role must not be labelled by its trigger.+ */+ get #hasPresentationalRole() {+ return this.args.role === "none" || this.args.role === "presentation";+ }+get supportsCloseOnClickOutside() {return this.options.closeOnClickOutside;}@@ -118,7 +134,6 @@ export default class DFloatBody extends Component<DFloatBodySignature> {@inline={{@inline}}@portalOutletElement={{@instance.portalOutletElement}}>- {{! eslint-disable-next-line ember/template-no-unsupported-role-attributes }}<divclass={{dConcatClass@mainClass@@ -127,8 +142,7 @@ export default class DFloatBody extends Component<DFloatBodySignature> {}}data-identifier={{this.options.identifier}}data-content- aria-labelledby={{@instance.id}}- aria-expanded={{if @instance.expanded "true" "false"}}+ aria-labelledby={{this.contentAriaLabelledby}}role={{@role}}{{FloatKitApplyFloatingUi this.trigger this.options @instance}}{{this.trapInteractionPropagation}}diff --git a/frontend/discourse/float-kit/components/d-headless-menu.gts b/frontend/discourse/float-kit/components/d-headless-menu.gtsindex 94ada097d59..a534f780549 100644--- a/frontend/discourse/float-kit/components/d-headless-menu.gts+++ b/frontend/discourse/float-kit/components/d-headless-menu.gts@@ -25,7 +25,7 @@ const DHeadlessMenu: TemplateOnlyComponent<DHeadlessMenuSignature> = <template>@trapTab={{@menu.options.trapTab}}@mainClass="fk-d-menu"@innerClass="fk-d-menu__inner-content"- @role="dialog"+ @role={{@menu.options.contentRole}}@inline={{@inline}}/></template>;diff --git a/frontend/discourse/float-kit/components/d-inline-float.gts b/frontend/discourse/float-kit/components/d-inline-float.gtsindex 7b6cefed799..050ce5f24ee 100644--- a/frontend/discourse/float-kit/components/d-inline-float.gts+++ b/frontend/discourse/float-kit/components/d-inline-float.gts@@ -1,10 +1,8 @@-import Component from "@glimmer/component";+import type { TemplateOnlyComponent } from "@ember/component/template-only";import { concat } from "@ember/helper";-import { service } from "@ember/service";import DFloatBody from "discourse/float-kit/components/d-float-body";import type FloatKitInstance from "discourse/float-kit/lib/float-kit-instance";-import type Site from "discourse/models/site";-import { and } from "discourse/truth-helpers";+import FloatKitNotifyPositioned from "discourse/float-kit/modifiers/notify-positioned";import DModal from "discourse/ui-kit/d-modal";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";@@ -39,51 +37,50 @@ interface DInlineFloatSignature {* and `DHeadlessTooltip`); the declarative components render their own body* inline instead.*/-export default class DInlineFloat extends Component<DInlineFloatSignature> {- @service declare site: Site;-- <template>- {{#if @instance.expanded}}- {{#if (and this.site.mobileView @instance.options.modalForMobile)}}- <DModal- @closeModal={{@instance.close}}- @hideHeader={{true}}- data-identifier={{@instance.options.identifier}}- data-content- class={{dConcatClass- "fk-d-menu-modal"- (concat @instance.options.identifier "-content")- }}- >- {{#if @instance.options.component}}- <@instance.options.component- @data={{@instance.options.data}}- @close={{@instance.close}}- />- {{else}}- {{@instance.options.content}}- {{/if}}- </DModal>- {{else}}- <DFloatBody- @instance={{@instance}}- @trapTab={{@trapTab}}- @mainClass={{@mainClass}}- @innerClass={{@innerClass}}- @role={{@role}}- @portalOutletElement={{@instance.portalOutletElement}}- @inline={{@inline}}- >- {{#if @instance.options.component}}- <@instance.options.component- @data={{@instance.options.data}}- @close={{@instance.close}}- />- {{else}}- {{@instance.options.content}}- {{/if}}- </DFloatBody>- {{/if}}+const DInlineFloat: TemplateOnlyComponent<DInlineFloatSignature> = <template>+ {{#if @instance.expanded}}+ {{#if @instance.renderInModal}}+ <DModal+ @closeModal={{@instance.close}}+ @hideHeader={{true}}+ data-identifier={{@instance.options.identifier}}+ data-content+ class={{dConcatClass+ "fk-d-menu-modal"+ (concat @instance.options.identifier "-content")+ }}+ {{FloatKitNotifyPositioned @instance}}+ >+ {{#if @instance.options.component}}+ <@instance.options.component+ @data={{@instance.options.data}}+ @close={{@instance.close}}+ />+ {{else}}+ {{@instance.options.content}}+ {{/if}}+ </DModal>+ {{else}}+ <DFloatBody+ @instance={{@instance}}+ @trapTab={{@trapTab}}+ @mainClass={{@mainClass}}+ @innerClass={{@innerClass}}+ @role={{@role}}+ @portalOutletElement={{@instance.portalOutletElement}}+ @inline={{@inline}}+ >+ {{#if @instance.options.component}}+ <@instance.options.component+ @data={{@instance.options.data}}+ @close={{@instance.close}}+ />+ {{else}}+ {{@instance.options.content}}+ {{/if}}+ </DFloatBody>{{/if}}- </template>-}+ {{/if}}+</template>;++export default DInlineFloat;diff --git a/frontend/discourse/float-kit/components/d-menu.gts b/frontend/discourse/float-kit/components/d-menu.gtsindex 5fabb9291b9..8af5b007927 100644--- a/frontend/discourse/float-kit/components/d-menu.gts+++ b/frontend/discourse/float-kit/components/d-menu.gts@@ -3,7 +3,6 @@ import { concat } from "@ember/helper";import { on } from "@ember/modifier";import { action } from "@ember/object";import { getOwner } from "@ember/owner";-import { service } from "@ember/service";import { type ComponentLike } from "@glint/template";import curryComponent from "ember-curry-component";import { modifier } from "ember-modifier";@@ -14,9 +13,8 @@ import {type MenuOptions,} from "discourse/float-kit/lib/constants";import DMenuInstance from "discourse/float-kit/lib/d-menu-instance";+import FloatKitNotifyPositioned from "discourse/float-kit/modifiers/notify-positioned";import { isTesting } from "discourse/lib/environment";-import type Site from "discourse/models/site";-import { and } from "discourse/truth-helpers";import DButton from "discourse/ui-kit/d-button";import DModal from "discourse/ui-kit/d-modal";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";@@ -31,6 +29,16 @@ export interface DMenuComponentArgs<Data = unknown> {/** The `@data` passed to the menu. */data?: Data;++ /** Whether the menu is currently open — reflects the live instance state. */+ expanded: boolean;++ /**+ * Whether the menu is disabled — reflects the live instance state. A custom+ * `@triggerComponent` does not receive `@disabled` itself, so this is how it renders a+ * disabled affordance for the veto that `<DMenu>` is already applying.+ */+ disabled: boolean;}// The subset of arguments that mirror a menu's option bag. Built as a@@ -77,7 +85,18 @@ interface DMenuSignature<Data = unknown> {/** The title for the default trigger button. */title?: string;- /** Whether the default trigger button is disabled. */+ /**+ * Disables the menu: the default trigger button renders disabled, and — for any trigger,+ * including a custom `@triggerComponent` — a trigger event (click/focus/hover/hold) no longer+ * opens the menu. It does not touch the trigger's focusability or ARIA; that stays the+ * caller's concern. A custom trigger reads the state back through `componentArgs.disabled`.+ *+ * Becoming disabled while open also closes the menu, since a disabled control must not keep+ * an interactive overlay live. Where focus lands afterwards follows from the trigger: the+ * default button is natively `disabled`, which no element can hold focus while being, so+ * focus falls to the document. A caller that needs focus preserved supplies a trigger that+ * stays focusable — the close refocuses it.+ */disabled?: boolean;/** Whether the default trigger button shows a loading state. */@@ -106,8 +125,6 @@ interface DMenuSignature<Data = unknown> {export default class DMenu<Data = unknown> extends Component<DMenuSignature<Data>> {- @service declare site: Site;-menuInstance = new DMenuInstance(getOwner(this)!, {...this.allowedProperties,autoUpdate: true,@@ -131,6 +148,19 @@ export default class DMenu<Data = unknown> extends Component<};});+ // Keeps the instance's open-veto in sync with `@disabled` reactively. The instance wires its+ // trigger listeners once (at registration), so the disabled state cannot ride in through the+ // one-time options snapshot; this re-runs whenever `@disabled` changes and gates the open.+ // Becoming disabled while open also closes the menu — a disabled control must not keep an+ // already-open overlay live (its content would stay interactive).+ syncDisabled = modifier((_element: HTMLElement, [disabled]: [boolean?]) => {+ const value = disabled ?? false;+ this.menuInstance.disabled = value;+ if (value && this.menuInstance.expanded) {+ this.menuInstance.close();+ }+ });+#body: HTMLElement | null = null;@action@@ -168,10 +198,19 @@ export default class DMenu<Data = unknown> extends Component<}get componentArgs(): DMenuComponentArgs<Data> {+ const instance = this.menuInstance;return {- close: this.menuInstance.close,- show: this.menuInstance.show,+ close: instance.close,+ show: instance.show,data: this.options.data as Data,+ // Getters (not snapshots) so a consumer reading these subscribes to the live tracked+ // state and re-renders as it changes, without churning this object.+ get expanded() {+ return instance.expanded;+ },+ get disabled() {+ return instance.disabled;+ },};}@@ -221,6 +260,7 @@ export default class DMenu<Data = unknown> extends Component<<template><this.triggerComponent{{this.registerTrigger}}+ {{this.syncDisabled @disabled}}class={{dConcatClass"fk-d-menu__trigger"(if this.menuInstance.expanded "-expanded")@@ -242,7 +282,7 @@ export default class DMenu<Data = unknown> extends Component<</this.triggerComponent>{{#if this.menuInstance.expanded}}- {{#if (and this.site.mobileView this.options.modalForMobile)}}+ {{#if this.menuInstance.renderInModal}}<DModal@closeModal={{this.menuInstance.close}}@hideHeader={{true}}@@ -256,6 +296,7 @@ export default class DMenu<Data = unknown> extends Component<@inline={{(isTesting)}}data-identifier={{this.options.identifier}}data-content+ {{FloatKitNotifyPositioned this.menuInstance}}><div class="fk-d-menu-modal__grip" aria-hidden="true"></div>{{#if (has-block)}}@@ -282,7 +323,7 @@ export default class DMenu<Data = unknown> extends Component<@contentClass}}@innerClass="fk-d-menu__inner-content"- @role="dialog"+ @role={{this.options.contentRole}}@inline={{this.options.inline}}{{this.registerFloatBody}}>diff --git a/frontend/discourse/float-kit/components/d-tooltip.gts b/frontend/discourse/float-kit/components/d-tooltip.gtsindex 2021c98c561..eec6db839f7 100644--- a/frontend/discourse/float-kit/components/d-tooltip.gts+++ b/frontend/discourse/float-kit/components/d-tooltip.gts@@ -23,6 +23,9 @@ export interface DTooltipComponentArgs<Data = unknown> {/** The `@data` passed to the tooltip. */data?: Data;++ /** Whether the tooltip is currently open — reflects the live instance state. */+ expanded: boolean;}// The subset of arguments that mirror a tooltip's option bag. Built as a@@ -102,9 +105,15 @@ export default class DTooltip<Data = unknown> extends Component<}get componentArgs(): DTooltipComponentArgs<Data> {+ const instance = this.tooltipInstance;return {close: this.tooltip.close,data: this.options.data as Data,+ // A getter (not a snapshot) so a consumer reading `expanded` subscribes to the+ // live tracked state and re-renders on open/close, without churning this object.+ get expanded() {+ return instance.expanded;+ },};}diff --git a/frontend/discourse/float-kit/lib/constants.ts b/frontend/discourse/float-kit/lib/constants.tsindex b9059e83b2e..6bb8fb81bd1 100644--- a/frontend/discourse/float-kit/lib/constants.ts+++ b/frontend/discourse/float-kit/lib/constants.ts@@ -47,6 +47,15 @@ export type FloatUiPlacement = (typeof FLOAT_UI_PLACEMENTS)[number];export type VisibilityOptimizer =(typeof VISIBILITY_OPTIMIZERS)[keyof typeof VISIBILITY_OPTIMIZERS];+/**+ * The ARIA roles a float's content element may carry: `dialog` for a panel that owns widgets of+ * its own, and the two presentational values for a container that must not sit between a control+ * and the elements it references. Deliberately closed — a role outside this set has not been+ * reconciled with the ARIA the content emits (see `DFloatBody`), so widening it is a decision to+ * make here rather than at a call site.+ */+export type FloatContentRole = "dialog" | "none" | "presentation";+/*** A relayed lifecycle or trigger callback (`onShow`, `onClose`, `beforeTrigger`, …).* These are handed straight to consumers that pass functions of varying arity and@@ -117,8 +126,13 @@ export interface TooltipOptions {/** Whether FloatKit attaches the trigger event listeners itself, rather than the caller driving it through the service API. */listeners: boolean;- /** The maximum width of the content, in pixels. */- maxWidth: number;+ /**+ * The maximum width of the content: a number in pixels, or any CSS `max-width` value. Pass+ * `"none"` alongside `matchTriggerWidth` — the two are both applied inline, so a numeric cap+ * silently wins over the matched width and a trigger wider than the cap gets a narrower+ * overlay.+ */+ maxWidth: number | string;/** Passed as the `@data` argument to a `component` rendered as the content. */data: unknown;@@ -156,6 +170,24 @@ export interface TooltipOptions {/** Called after the float shows. */onShow: FloatCallback | null;+ /**+ * Called with the float's content element once it has been placed.+ *+ * Positioning is what gives a float its size, and it resolves asynchronously — so content+ * that renders from a measurement of itself computes that measurement against a float that+ * has no size yet. Such content re-measures here rather than waiting for a resize to be+ * observed, which happens on the browser's schedule and is not guaranteed to be prompt.+ *+ * This fires on every placement, not once per open: with `autoUpdate` on (the default) an+ * ancestor scroll, an element resize or a layout shift each reposition the float and call+ * back. A callback that re-renders from its own measurement therefore has to reach a fixed+ * point, since a size change it causes is itself a reposition trigger.+ *+ * A menu that renders as a mobile modal has no placement to compute and never repositions.+ * It calls back once, after the modal is inserted, with the modal element.+ */+ onPositioned: FloatCallback | null;+/** Called with the float instance when it is created, so callers can control it programmatically. */onRegisterApi: FloatCallback | null;@@ -164,11 +196,18 @@ export interface TooltipOptions {}/**- * The options for a menu: every tooltip option plus the menu-only extras (focus- * management, the mobile modal, identifier grouping, and the class/width overrides+ * The options for a menu: every tooltip option plus the menu-only extras (the content role,+ * focus management, the mobile modal, identifier grouping, and the class/width overrides* the menu template forwards to its trigger and content).*/export interface MenuOptions extends TooltipOptions {+ /**+ * The ARIA role for the content element. `dialog` suits a panel that holds its own widgets.+ * A popup that is only a list should pass `none`, so the container does not sit between the+ * control and the items its `aria-activedescendant` points at.+ */+ contentRole: FloatContentRole;+/** Whether to focus the content when the menu opens. */autofocus: boolean;@@ -313,6 +352,7 @@ export const TOOLTIP: { options: TooltipOptions; portalOutletId: string } = {trapTab: true,onClose: null,onShow: null,+ onPositioned: null,onRegisterApi: null,portalOutletElement: null,},@@ -344,8 +384,10 @@ export const MENU: { options: MenuOptions; portalOutletId: string } = {fallbackPlacements: FLOAT_UI_PLACEMENTS,autoUpdate: true,trapTab: true,+ contentRole: "dialog",onClose: null,onShow: null,+ onPositioned: null,onRegisterApi: null,modalForMobile: false,inline: null,diff --git a/frontend/discourse/float-kit/lib/d-menu-instance.ts b/frontend/discourse/float-kit/lib/d-menu-instance.tsindex 02a4f6e88c2..7cd65f90c7e 100644--- a/frontend/discourse/float-kit/lib/d-menu-instance.ts+++ b/frontend/discourse/float-kit/lib/d-menu-instance.ts@@ -13,7 +13,6 @@ import {import FloatKitInstance from "discourse/float-kit/lib/float-kit-instance";import type MenuService from "discourse/float-kit/services/menu";import { animateClosing } from "discourse/lib/animation-utils";-import type Site from "discourse/models/site";import type ModalService from "discourse/services/modal";/**@@ -25,12 +24,19 @@ import type ModalService from "discourse/services/modal";*/export default class DMenuInstance extends FloatKitInstance {@service declare menu: MenuService;- @service declare site: Site;@service declare modal: ModalService;/** Whether the menu is currently open. */@tracked expanded = false;+ /**+ * Whether the trigger is disabled. While true, a trigger event (click/focus/hover/hold) does+ * not open the menu — the single reactive veto for every listener the base wires once at+ * registration. `<DMenu>` keeps this in sync with its `@disabled` argument; it does not touch+ * focusability or the trigger's own ARIA, which stay the caller's concern.+ */+ @tracked disabled = false;+/*** Whether the menu's trigger is managed outside the `<DMenu />` component. It* is set when the menu is created through the `menu` service, where the@@ -88,7 +94,7 @@ export default class DMenuInstance extends FloatKitInstance {await animateClosing(this.content);- if (this.site.mobileView && this.options.modalForMobile && this.expanded) {+ if (this.renderInModal && this.expanded) {await this.modal.close();}@@ -141,9 +147,22 @@ export default class DMenuInstance extends FloatKitInstance {@actionasync onTrigger(event: Event) {+ // Consume the trigger event even when disabled, so a disabled trigger inside a clickable+ // ancestor doesn't fall through and activate it — an enabled trigger would have consumed it.event.stopPropagation();+ if (this.disabled) {+ this.openedByDelayedHover = false;+ return;+ }+await this.options.beforeTrigger?.(this);++ if (this.disabled) {+ this.openedByDelayedHover = false;+ return;+ }+await this.show();}diff --git a/frontend/discourse/float-kit/lib/float-kit-instance.ts b/frontend/discourse/float-kit/lib/float-kit-instance.tsindex 656bd935326..c7f3752b2da 100644--- a/frontend/discourse/float-kit/lib/float-kit-instance.ts+++ b/frontend/discourse/float-kit/lib/float-kit-instance.ts@@ -26,6 +26,17 @@ function cancelEvent(event: Event) {* orchestrates (`options`, `trigger`, `expanded`, and the trigger/pointer actions).*/export default abstract class FloatKitInstance {+ /**+ * The single source of truth for the float-kit modal decision: does a float with this+ * `modalForMobile` option render as a mobile modal (an `aria-modal` dialog) instead of an+ * inline popover? Exposed as a static so the instance-less caller+ * (`menu.shouldRenderInModal`, which decides before an instance exists) resolves through the+ * exact same formula and can't drift from what a float actually renders.+ */+ static resolveRenderInModal(site: Site, modalForMobile?: boolean): boolean {+ return site.mobileView && !!modalForMobile;+ }+@service declare site: Site;@tracked id: string | null = null;@@ -51,6 +62,14 @@ export default abstract class FloatKitInstance {declare openedByDelayedHover: boolean;+ /** Whether THIS instance renders in a mobile modal (see {@link resolveRenderInModal}). */+ get renderInModal(): boolean {+ return FloatKitInstance.resolveRenderInModal(+ this.site,+ this.options.modalForMobile+ );+ }+/*** The trigger narrowed to a real element, or `null` when it is a virtual reference.* The listener, focus, and containment logic all go through this so a virtual triggerdiff --git a/frontend/discourse/float-kit/lib/update-position.ts b/frontend/discourse/float-kit/lib/update-position.tsindex baf2edbb962..6b0d887f042 100644--- a/frontend/discourse/float-kit/lib/update-position.ts+++ b/frontend/discourse/float-kit/lib/update-position.ts@@ -60,6 +60,12 @@ export interface PositioningOptions {content: HTMLElement,result: ComputePositionReturn & { arrowElement?: HTMLElement }) => void;++ /**+ * Called each time a position has been applied — so once per call, and once per `autoUpdate`+ * reposition. See `TooltipOptions.onPositioned`.+ */+ onPositioned?: ((content: HTMLElement) => void) | null;}interface DetectOverflowOptions {@@ -110,6 +116,10 @@ export async function updatePosition(} else {applyComputedPosition(content, result, arrowElement);}++ // After the position is applied, so a consumer that renders from its own size measures a+ // float that already has one.+ options.onPositioned?.(content);}function buildMiddleware(diff --git a/frontend/discourse/float-kit/modifiers/apply-floating-ui.ts b/frontend/discourse/float-kit/modifiers/apply-floating-ui.tsindex 7300214149b..7e0540a2ec6 100644--- a/frontend/discourse/float-kit/modifiers/apply-floating-ui.ts+++ b/frontend/discourse/float-kit/modifiers/apply-floating-ui.ts@@ -1,5 +1,6 @@import { registerDestructor } from "@ember/destroyable";import type Owner from "@ember/owner";+import { waitForPromise } from "@ember/test-waiters";import { autoUpdate } from "@floating-ui/dom";import Modifier, { type ArgsFor } from "ember-modifier";import type { FloatKitTrigger } from "discourse/float-kit/lib/constants";@@ -68,10 +69,12 @@ export default class FloatKitApplyFloatingUi extends Modifier<FloatKitApplyFloatreturn;}- await updatePosition(- this.instance.trigger,- this.instance.content,- this.options+ // Positioning is what finally gives a float its size, and it resolves off a promise the+ // test runtime cannot see. Without this, `settled()` returns while the float is still+ // unpositioned, so a test reads it at zero size — and anything that measures the float to+ // decide what to render, such as a virtualized list, computes an empty window from it.+ await waitForPromise(+ updatePosition(this.instance.trigger, this.instance.content, this.options));}diff --git a/frontend/discourse/float-kit/modifiers/notify-positioned.ts b/frontend/discourse/float-kit/modifiers/notify-positioned.tsnew file mode 100644index 00000000000..d3bff6d43a9--- /dev/null+++ b/frontend/discourse/float-kit/modifiers/notify-positioned.ts@@ -0,0 +1,22 @@+import { cancel, schedule } from "@ember/runloop";+import { modifier } from "ember-modifier";+import type FloatKitInstance from "discourse/float-kit/lib/float-kit-instance";++/**+ * Reports a float as positioned for the render path that has no positioning step: the mobile+ * modal, which the browser lays out itself instead of going through `updatePosition`.+ *+ * A positioned float fires `onPositioned` from `updatePosition`, once per placement. A modal has+ * no placement to compute and never repositions, so the equivalent moment is the render after it+ * is inserted — the first point at which its content has a size to measure. Scheduled on the+ * runloop so `settled()` covers it.+ */+export default modifier(+ (element: HTMLElement, [instance]: [FloatKitInstance]) => {+ const timer = schedule("afterRender", () =>+ instance.options.onPositioned?.(element)+ );++ return () => cancel(timer);+ }+);diff --git a/frontend/discourse/float-kit/services/menu.ts b/frontend/discourse/float-kit/services/menu.tsindex 7a8aeadca2f..0b3d54f5f6f 100644--- a/frontend/discourse/float-kit/services/menu.ts+++ b/frontend/discourse/float-kit/services/menu.ts@@ -2,12 +2,14 @@ import { action } from "@ember/object";import { getOwner } from "@ember/owner";import { trackedSet } from "@ember/reactive/collections";import { schedule } from "@ember/runloop";-import Service from "@ember/service";+import Service, { service } from "@ember/service";import type {FloatKitTrigger,MenuOptions,} from "discourse/float-kit/lib/constants";import DMenuInstance from "discourse/float-kit/lib/d-menu-instance";+import FloatKitInstance from "discourse/float-kit/lib/float-kit-instance";+import type Site from "discourse/models/site";/*** The service that shows menus imperatively, outside the `<DMenu />` component.@@ -17,8 +19,22 @@ import DMenuInstance from "discourse/float-kit/lib/d-menu-instance";* and content directly.*/export default class Menu extends Service {+ @service declare site: Site;+registeredMenus = trackedSet<DMenuInstance>();+ /**+ * Whether a menu with the given `modalForMobile` option renders as a mobile modal (an+ * `aria-modal` dialog) rather than an inline popover. This is the instance-less accessor a+ * caller uses before a menu exists; it delegates to the shared formula in+ * {@link FloatKitInstance.resolveRenderInModal}, so it can't drift from what `<DMenu>` renders.+ *+ * @param modalForMobile - the menu's `@modalForMobile` option.+ */+ shouldRenderInModal(modalForMobile?: boolean): boolean {+ return FloatKitInstance.resolveRenderInModal(this.site, modalForMobile);+ }+/*** Render a menu.*diff --git a/frontend/discourse/tests/integration/components/float-kit/apply-floating-ui-test.gjs b/frontend/discourse/tests/integration/components/float-kit/apply-floating-ui-test.gjsnew file mode 100644index 00000000000..296f5a26680--- /dev/null+++ b/frontend/discourse/tests/integration/components/float-kit/apply-floating-ui-test.gjs@@ -0,0 +1,82 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { action } from "@ember/object";+import didInsert from "@ember/render-modifiers/modifiers/did-insert";+import { render } from "@ember/test-helpers";+import { getPendingWaiterState } from "@ember/test-waiters";+import { module, test } from "qunit";+import applyFloatingUi from "discourse/float-kit/modifiers/apply-floating-ui";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";++// The waiter `waitForPromise` registers under. Asserting on this name rather than on "some+// waiter is pending" keeps the test from passing because of unrelated pending work.+const PROMISE_WAITER = "@ember/test-waiters:promise-waiter";++module(+ "Integration | Modifier | FloatKit | apply-floating-ui",+ function (hooks) {+ setupRenderingTest(hooks);++ // A float's size comes from positioning, which resolves off a promise. If that promise is+ // outside test settledness, `settled()` returns while the float is still unpositioned and a+ // test reads it at zero size — which is how a virtualized listbox inside a menu came to+ // render an empty window under assertion.+ //+ // Timing cannot be asserted directly without making the test machine-speed dependent, so+ // this pins the invariant instead: at a moment when positioning is definitely still in+ // flight, the promise must be registered with the waiter system. `updatePosition` invokes+ // the `computePosition` option after floating-ui resolves but before it resolves itself,+ // which is exactly such a moment.+ test("positioning is part of test settledness", async function (assert) {+ let waiterPendingDuringPositioning = null;++ class Host extends Component {+ @tracked instance = null;++ options = {+ computePosition: () => {+ waiterPendingDuringPositioning =+ PROMISE_WAITER in getPendingWaiterState().waiters;+ },+ };++ @action+ captureTrigger(element) {+ // Stands in for a FloatKitInstance: the modifier reads `trigger` and+ // `triggerElement`, and assigns `content` itself.+ this.instance = {+ trigger: element,+ triggerElement: element,+ content: null,+ };+ }++ <template>+ <div {{didInsert this.captureTrigger}}></div>++ {{#if this.instance}}+ <div+ {{applyFloatingUi+ this.instance.trigger+ this.options+ this.instance+ }}+ ></div>+ {{/if}}+ </template>+ }++ await render(<template><Host /></template>);++ assert.notStrictEqual(+ waiterPendingDuringPositioning,+ null,+ "positioning ran, so the assertion below observed a real in-flight moment"+ );+ assert.true(+ waiterPendingDuringPositioning,+ "the positioning promise is registered with the waiter system while in flight, so settled() cannot resolve ahead of it"+ );+ });+ }+);diff --git a/frontend/discourse/tests/integration/components/float-kit/d-menu-test.gjs b/frontend/discourse/tests/integration/components/float-kit/d-menu-test.gjsindex 31b55753f11..0f63852fbec 100644--- a/frontend/discourse/tests/integration/components/float-kit/d-menu-test.gjs+++ b/frontend/discourse/tests/integration/components/float-kit/d-menu-test.gjs@@ -1,17 +1,24 @@import { array, hash } from "@ember/helper";+import { on } from "@ember/modifier";import { getOwner } from "@ember/owner";import didInsert from "@ember/render-modifiers/modifiers/did-insert";import willDestroy from "@ember/render-modifiers/modifiers/will-destroy";import {click,+ find,+ focus,render,+ rerender,settled,triggerEvent,triggerKeyEvent,} from "@ember/test-helpers";import { module, test } from "qunit";+import ModalContainer from "discourse/components/modal-container";import DDefaultToast from "discourse/float-kit/components/d-default-toast";import DMenu from "discourse/float-kit/components/d-menu";+import DMenus from "discourse/float-kit/components/d-menus";+import DTooltips from "discourse/float-kit/components/d-tooltips";import DMenuInstance from "discourse/float-kit/lib/d-menu-instance";import { forceMobile } from "discourse/lib/mobile";import { setupRenderingTest } from "discourse/tests/helpers/component-test";@@ -87,6 +94,124 @@ module("Integration | Component | FloatKit | DMenu", function (hooks) {assert.dom(".fk-d-menu-modal[data-identifier='foo']").hasText("content");});+ test("DMenu uses a modal while DTooltip stays inline on mobile", async function (assert) {+ forceMobile();++ await render(+ <template>+ <div class="menu-trigger"></div>+ <div class="tooltip-trigger"></div>+ <DMenus />+ <DTooltips />+ <ModalContainer />+ </template>+ );++ const menu = await getOwner(this)+ .lookup("service:menu")+ .show(find(".menu-trigger"), {+ content: "menu content",+ identifier: "mobile-menu",+ modalForMobile: true,+ });+ const tooltip = await getOwner(this)+ .lookup("service:tooltip")+ .show(find(".tooltip-trigger"), {+ content: "tooltip content",+ identifier: "mobile-tooltip",+ });+ await settled();++ assert.true(menu.renderInModal, "the menu instance selects the modal path");+ assert.false(+ tooltip.renderInModal,+ "the tooltip instance keeps the default inline path"+ );+ assert+ .dom(".fk-d-menu-modal")+ .hasText("menu content", "the menu renders in a modal");+ assert+ .dom(".fk-d-tooltip__content[data-identifier='mobile-tooltip']")+ .hasText("tooltip content", "the tooltip renders as an inline float");+ });++ test("menu.shouldRenderInModal decides without an instance", async function (assert) {+ forceMobile();++ await render(<template><DMenus /></template>);+ const menu = getOwner(this).lookup("service:menu");++ assert.true(+ menu.shouldRenderInModal(true),+ "mobile plus modalForMobile renders in a modal"+ );+ assert.false(+ menu.shouldRenderInModal(false),+ "mobile alone does not render in a modal"+ );+ assert.false(+ menu.shouldRenderInModal(),+ "an omitted option does not render in a modal"+ );+ });++ test("@onPositioned fires with the content once the float is positioned", async function (assert) {+ const positioned = [];+ this.onPositioned = (element) => positioned.push(element);++ await render(+ <template>+ <DMenu+ @inline={{true}}+ @label="label"+ @content="content"+ @onPositioned={{this.onPositioned}}+ />+ </template>+ );++ assert.strictEqual(+ positioned.length,+ 0,+ "nothing is positioned while the menu is closed"+ );++ await open();++ assert.true(positioned.length > 0, "opening positions the float");+ assert.dom(positioned[0]).hasClass("fk-d-menu", "the content is passed");+ });++ test("@onPositioned fires when the menu renders as a mobile modal", async function (assert) {+ forceMobile();++ const positioned = [];+ this.onPositioned = (element) => positioned.push(element);++ await render(+ <template>+ <DMenu+ @inline={{true}}+ @modalForMobile={{true}}+ @label="label"+ @content="content"+ @onPositioned={{this.onPositioned}}+ />+ </template>+ );+ await open();++ assert.dom(".fk-d-menu-modal").exists("the menu renders as a modal");+ assert.strictEqual(+ positioned.length,+ 1,+ "the modal path reports once, since a modal does not reposition"+ );+ assert+ .dom(positioned[0])+ .hasClass("d-modal", "the modal element is passed");+ });+test("@modalForMobile - swipe down to close", async function (assert) {forceMobile();@@ -244,6 +369,57 @@ module("Integration | Component | FloatKit | DMenu", function (hooks) {await open();assert.dom(".fk-d-menu").hasAttribute("role", "dialog");+ assert+ .dom(".fk-d-menu")+ .doesNotHaveAttribute(+ "aria-expanded",+ "the content carries no expanded state — no role it takes supports one, it could only ever be true while rendered, and the trigger already carries it"+ );+ });++ test("@contentRole none removes container semantics", async function (assert) {+ await render(+ <template>+ <DMenu @contentRole="none" @inline={{true}} @label="label" />+ </template>+ );++ await open();++ assert+ .dom(".fk-d-menu")+ .hasAttribute("role", "none", "the requested role is rendered");+ assert+ .dom(".fk-d-menu")+ .doesNotHaveAttribute(+ "aria-labelledby",+ "the presentational container has no accessible name"+ );+ assert+ .dom(".fk-d-menu")+ .doesNotHaveAttribute(+ "aria-expanded",+ "the presentational container has no ARIA state"+ );+ });++ test("service-created menus use @contentRole", async function (assert) {+ await render(+ <template>+ <div class="menu-trigger"></div>+ <DMenus />+ </template>+ );++ await getOwner(this).lookup("service:menu").show(find(".menu-trigger"), {+ content: "content",+ contentRole: "none",+ });+ await settled();++ assert+ .dom(".fk-d-menu")+ .hasAttribute("role", "none", "the service option reaches the menu body");});test("@component", async function (assert) {@@ -370,6 +546,58 @@ module("Integration | Component | FloatKit | DMenu", function (hooks) {assert.dom(".fk-d-menu").doesNotExist();});+ test("trigger expanded argument reflects the open state", async function (assert) {+ await render(+ <template>+ <DMenu @inline={{true}}>+ <:trigger as |args|>+ <span class="expanded-flag">{{if+ args.expanded+ "open"+ "closed"+ }}</span>+ </:trigger>+ <:content>content</:content>+ </DMenu>+ </template>+ );++ assert+ .dom(".expanded-flag")+ .hasText("closed", "expanded is false when closed");++ await open();+ assert+ .dom(".expanded-flag")+ .hasText("open", "expanded flips to true on open");+ });++ test("trigger disabled argument reflects the disabled state", async function (assert) {+ this.disabled = false;++ await render(+ <template>+ <DMenu @disabled={{this.disabled}} @inline={{true}}>+ <:trigger as |args|>+ <span class="disabled-flag">{{if args.disabled "off" "on"}}</span>+ </:trigger>+ <:content>content</:content>+ </DMenu>+ </template>+ );++ assert.dom(".disabled-flag").hasText("on", "disabled is false by default");++ this.set("disabled", true);+ await rerender();+ assert+ .dom(".disabled-flag")+ .hasText(+ "off",+ "a custom trigger sees the veto it cannot read from @disabled"+ );+ });+test("@autofocus", async function (assert) {await render(<template>@@ -627,6 +855,187 @@ module("Integration | Component | FloatKit | DMenu", function (hooks) {assert.dom("span.fk-d-menu__trigger").exists();});+ test("@disabled blocks a custom trigger and updates reactively", async function (assert) {+ this.disabled = true;++ await render(+ <template>+ <DMenu+ @disabled={{this.disabled}}+ @inline={{true}}+ @triggerComponent={{dElement "div"}}+ @content="content"+ />+ </template>+ );++ await click(".fk-d-menu__trigger");+ assert+ .dom(".fk-d-menu")+ .doesNotExist("a custom trigger cannot open while disabled");++ this.set("disabled", false);+ await click(".fk-d-menu__trigger");+ assert+ .dom(".fk-d-menu")+ .exists("clearing disabled after mount restores trigger opening");++ this.set("disabled", true);+ await settled();+ assert+ .dom(".fk-d-menu")+ .doesNotExist("setting disabled closes an open menu");++ await click(".fk-d-menu__trigger");+ assert+ .dom(".fk-d-menu")+ .doesNotExist("setting disabled after mount re-gates trigger opening");+ });++ test("@disabled blocks the default button trigger", async function (assert) {+ await render(+ <template>+ <DMenu+ @disabled={{true}}+ @inline={{true}}+ @label="label"+ @content="content"+ />+ </template>+ );++ assert+ .dom(".fk-d-menu__trigger")+ .isDisabled("the default trigger retains its native disabled state");++ find(".fk-d-menu__trigger").dispatchEvent(+ new MouseEvent("click", { bubbles: true })+ );+ await settled();+ assert+ .dom(".fk-d-menu")+ .doesNotExist("the default trigger cannot open while disabled");+ });++ test("disabled delayed-hover does not swallow the first click after re-enabling", async function (assert) {+ this.disabled = true;++ await render(+ <template>+ <DMenu+ @disabled={{this.disabled}}+ @inline={{true}}+ @triggerComponent={{dElement "div"}}+ @triggers={{array "delayed-hover" "click"}}+ @content="content"+ />+ </template>+ );++ triggerEvent(".fk-d-menu__trigger", "pointerenter");+ await settled();+ assert+ .dom(".fk-d-menu")+ .doesNotExist("disabled vetoes the delayed-hover open");++ this.set("disabled", false);+ await click(".fk-d-menu__trigger");+ assert+ .dom(".fk-d-menu")+ .exists("the first click after re-enabling opens the menu");+ });++ test("disabling during beforeTrigger vetoes the pending open", async function (assert) {+ this.disabled = false;+ this.beforeTrigger = () =>+ new Promise((resolve) => (this.resolveBeforeTrigger = resolve));++ await render(+ <template>+ <DMenu+ @beforeTrigger={{this.beforeTrigger}}+ @disabled={{this.disabled}}+ @inline={{true}}+ @triggerComponent={{dElement "div"}}+ @content="content"+ />+ </template>+ );++ find(".fk-d-menu__trigger").dispatchEvent(+ new MouseEvent("click", { bubbles: true })+ );+ this.set("disabled", true);+ await rerender();+ this.resolveBeforeTrigger();+ await settled();++ assert+ .dom(".fk-d-menu")+ .doesNotExist(+ "a pending trigger cannot open after the menu becomes disabled"+ );+ });++ test("disabling an open menu returns focus to a trigger that stays focusable", async function (assert) {+ this.disabled = false;++ await render(+ <template>+ <DMenu+ @disabled={{this.disabled}}+ @inline={{true}}+ @triggerComponent={{dElement "div"}}+ tabindex="0"+ >+ <:content><input class="menu-input" /></:content>+ </DMenu>+ </template>+ );++ await click(".fk-d-menu__trigger");+ await focus(".menu-input");+ assert.dom(".menu-input").isFocused("focus moved into the open menu");++ this.set("disabled", true);+ await settled();++ assert.dom(".fk-d-menu").doesNotExist("becoming disabled closed the menu");+ assert+ .dom(".fk-d-menu__trigger")+ .isFocused(+ "the close hands focus back, so a caller that keeps its trigger focusable does not lose it"+ );+ });++ test("a disabled trigger still consumes its click (does not fall through to a clickable ancestor)", async function (assert) {+ let ancestorClicks = 0;+ const onAncestorClick = () => ancestorClicks++;++ await render(+ <template>+ {{! eslint-disable ember/template-no-invalid-interactive }}+ <div {{on "click" onAncestorClick}}>+ <DMenu+ @disabled={{true}}+ @inline={{true}}+ @triggerComponent={{dElement "div"}}+ @content="content"+ />+ </div>+ </template>+ );++ await click(".fk-d-menu__trigger");++ assert.dom(".fk-d-menu").doesNotExist("the disabled menu does not open");+ assert.strictEqual(+ ancestorClicks,+ 0,+ "the disabled trigger consumes the click instead of activating its ancestor"+ );+ });+test("@matchTriggerWidth", async function (assert) {await render(<template>diff --git a/frontend/discourse/tests/integration/components/float-kit/d-tooltip-test.gjs b/frontend/discourse/tests/integration/components/float-kit/d-tooltip-test.gjsindex f78795435c6..26a3a152466 100644--- a/frontend/discourse/tests/integration/components/float-kit/d-tooltip-test.gjs+++ b/frontend/discourse/tests/integration/components/float-kit/d-tooltip-test.gjs@@ -162,6 +162,33 @@ module("Integration | Component | FloatKit | DTooltip", function (hooks) {assert.dom(".fk-d-tooltip__trigger").hasText("label");});+ test("trigger expanded argument reflects the open state", async function (assert) {+ await render(+ <template>+ <DTooltip @inline={{true}}>+ <:trigger as |args|>+ <span class="expanded-flag">{{if+ args.expanded+ "open"+ "closed"+ }}</span>+ </:trigger>+ <:content>content</:content>+ </DTooltip>+ </template>+ );++ assert+ .dom(".expanded-flag")+ .hasText("closed", "expanded is false when closed");++ await hover();++ assert+ .dom(".expanded-flag")+ .hasText("open", "expanded flips to true on open");+ });+test("<:content>", async function (assert) {await render(<template>