Skip to content

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

DEV: Convert FloatKit to TypeScript (#41633)

Sérgio Saquetimcd78b6bd8baf
diff --git a/frontend/discourse/app/ui-kit/d-icon-grid-picker/index.gjs b/frontend/discourse/app/ui-kit/d-icon-grid-picker/index.gjs
index c6a5ab7c84e..df3fd0f2a9f 100644
--- a/frontend/discourse/app/ui-kit/d-icon-grid-picker/index.gjs
+++ b/frontend/discourse/app/ui-kit/d-icon-grid-picker/index.gjs
@@ -18,7 +18,7 @@ import { i18n } from "discourse-i18n";
* @property {object} Args
*
* @property {string} Args.value - The currently selected icon ID.
- * @property {Function} Args.onChange - Called with the selected icon ID when an icon is picked.
+ * @property {(iconId: string | null) => void} Args.onChange - Called with the selected icon ID when an icon is picked, or `null` when the selection is cleared.
* @property {string[]} [Args.favorites] - Icon IDs to display in a pinned favorites row above the grid.
* @property {boolean} [Args.showSelectedName] - When true, the selected icon's name is shown
* alongside the icon in both the trigger button and the favorites chip. Adds a
@@ -41,8 +41,8 @@ import { i18n } from "discourse-i18n";
* Defaults to "d_icon_grid_picker.clear".
* @property {boolean} [Args.modalForMobile] - Whether to show as a modal on mobile. Defaults to true.
* @property {boolean} [Args.inline] - When true, renders the menu inline instead of floating.
- * @property {Function} [Args.onShow] - Called when the picker menu is opened.
- * @property {Function} [Args.onClose] - Called when the picker menu is closed.
+ * @property {import("discourse/float-kit/lib/constants").FloatCallback} [Args.onShow] - Called when the picker menu is opened.
+ * @property {import("discourse/float-kit/lib/constants").FloatCallback} [Args.onClose] - Called when the picker menu is closed.
*/
/**
diff --git a/frontend/discourse/float-kit/components/d-button-tooltip.gjs b/frontend/discourse/float-kit/components/d-button-tooltip.gjs
deleted file mode 100644
index 34b871153ff..00000000000
--- a/frontend/discourse/float-kit/components/d-button-tooltip.gjs
+++ /dev/null
@@ -1,8 +0,0 @@
-const DButtonTooltip = <template>
- <div class="fk-d-button-tooltip" ...attributes>
- {{yield to="button"}}
- {{yield to="tooltip"}}
- </div>
-</template>;
-
-export default DButtonTooltip;
diff --git a/frontend/discourse/float-kit/components/d-button-tooltip.gts b/frontend/discourse/float-kit/components/d-button-tooltip.gts
new file mode 100644
index 00000000000..714b8b3d8ea
--- /dev/null
+++ b/frontend/discourse/float-kit/components/d-button-tooltip.gts
@@ -0,0 +1,31 @@
+import type { TemplateOnlyComponent } from "@ember/component/template-only";
+
+interface DButtonTooltipSignature {
+ Element: HTMLDivElement;
+ Blocks: {
+ /** The action button, rendered first. */
+ button: [];
+
+ /**
+ * The tooltip trigger rendered next to the button, typically a
+ * `<DTooltip />`. It is often shown conditionally, e.g. an info icon that
+ * appears only while the button is disabled to explain why.
+ */
+ tooltip: [];
+ };
+}
+
+/**
+ * Lays out an action button beside a tooltip trigger so the two sit inline
+ * together, sharing a single wrapper. This keeps a button and an adjacent
+ * explanatory tooltip aligned without the caller styling the pairing itself.
+ */
+const DButtonTooltip: TemplateOnlyComponent<DButtonTooltipSignature> =
+ <template>
+ <div class="fk-d-button-tooltip" ...attributes>
+ {{yield to="button"}}
+ {{yield to="tooltip"}}
+ </div>
+ </template>;
+
+export default DButtonTooltip;
diff --git a/frontend/discourse/float-kit/components/d-default-toast.gjs b/frontend/discourse/float-kit/components/d-default-toast.gts
similarity index 76%
rename from frontend/discourse/float-kit/components/d-default-toast.gjs
rename to frontend/discourse/float-kit/components/d-default-toast.gts
index 5316ca759e8..87bda48c239 100644
--- a/frontend/discourse/float-kit/components/d-default-toast.gjs
+++ b/frontend/discourse/float-kit/components/d-default-toast.gts
@@ -1,12 +1,25 @@
+import type { TemplateOnlyComponent } from "@ember/component/template-only";
import { concat, fn, hash } from "@ember/helper";
import didInsert from "@ember/render-modifiers/modifiers/did-insert";
import { trustHTML } from "@ember/template";
+import type { ToastComponentArgs } from "discourse/float-kit/lib/constants";
import { or } from "discourse/truth-helpers";
import DButton from "discourse/ui-kit/d-button";
import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
import dIcon from "discourse/ui-kit/helpers/d-icon";
-const DDefaultToast = <template>
+interface DDefaultToastSignature {
+ Element: HTMLDivElement;
+ Args: ToastComponentArgs;
+}
+
+/**
+ * The default component rendered inside a toast when the caller does not supply
+ * one. It lays out the toast's icon, title, message, and action buttons from
+ * `@data`, an optional auto-close progress bar, and a close button, applying the
+ * theme in `@data.theme` (e.g. `"success"` or `"error"`).
+ */
+const DDefaultToast: TemplateOnlyComponent<DDefaultToastSignature> = <template>
<div
class={{dConcatClass
"fk-d-default-toast"
diff --git a/frontend/discourse/float-kit/components/d-float-body.gjs b/frontend/discourse/float-kit/components/d-float-body.gts
similarity index 67%
rename from frontend/discourse/float-kit/components/d-float-body.gjs
rename to frontend/discourse/float-kit/components/d-float-body.gts
index 915e132629f..eea32d97833 100644
--- a/frontend/discourse/float-kit/components/d-float-body.gjs
+++ b/frontend/discourse/float-kit/components/d-float-body.gts
@@ -3,6 +3,7 @@ import { fn, hash } from "@ember/helper";
import { trustHTML } from "@ember/template";
import { modifier as modifierFn } from "ember-modifier";
import DFloatPortal from "discourse/float-kit/components/d-float-portal";
+import type FloatKitInstance from "discourse/float-kit/lib/float-kit-instance";
import { getScrollParent } from "discourse/float-kit/lib/get-scroll-parent";
import FloatKitApplyFloatingUi from "discourse/float-kit/modifiers/apply-floating-ui";
import FloatKitCloseOnEscape from "discourse/float-kit/modifiers/close-on-escape";
@@ -10,9 +11,50 @@ 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";
-export default class DFloatBody extends Component {
+interface DFloatBodySignature {
+ Element: HTMLDivElement;
+ Args: {
+ /** The float instance this body renders. */
+ instance: FloatKitInstance;
+
+ /** Whether to render in place instead of into the portal outlet. */
+ inline?: boolean | null;
+
+ /** A class added to the outer float element. */
+ mainClass?: string;
+
+ /** A class added to the inner content element. */
+ innerClass?: string;
+
+ /** The ARIA role for the content. */
+ role?: string;
+
+ /** Whether to trap Tab focus within the content. */
+ trapTab?: boolean;
+
+ /**
+ * The element to render into. Some callers forward this even though the body
+ * reads `@instance.portalOutletElement`.
+ */
+ portalOutletElement?: HTMLElement | null;
+ };
+ Blocks: {
+ /** The float content, rendered inside the positioned element. */
+ default: [];
+ };
+}
+
+/**
+ * The shared content body that both menus and tooltips render through. It
+ * portals the content (see `DFloatPortal`), positions it against the trigger
+ * with floating-ui, and wires the dismissal and focus behaviors the instance
+ * asks for in its options: close on click-outside, Escape, or scroll, and a Tab
+ * focus trap. It reads all of that from `@instance`, so callers only supply the
+ * instance plus a few presentational overrides.
+ */
+export default class DFloatBody extends Component<DFloatBodySignature> {
closeOnScroll = modifierFn(() => {
- const firstScrollParent = getScrollParent(this.trigger);
+ const firstScrollParent = getScrollParent(this.trigger)!;
const handler = () => {
this.args.instance.close();
@@ -25,8 +67,8 @@ export default class DFloatBody extends Component {
};
});
- trapInteractionPropagation = modifierFn((element) => {
- const handler = (event) => {
+ trapInteractionPropagation = modifierFn((element: HTMLElement) => {
+ const handler = (event: Event) => {
event.stopPropagation();
};
diff --git a/frontend/discourse/float-kit/components/d-float-portal.gjs b/frontend/discourse/float-kit/components/d-float-portal.gjs
deleted file mode 100644
index 6ba9ab93e9d..00000000000
--- a/frontend/discourse/float-kit/components/d-float-portal.gjs
+++ /dev/null
@@ -1,18 +0,0 @@
-import Component from "@glimmer/component";
-import { isTesting } from "discourse/lib/environment";
-
-export default class DFloatPortal extends Component {
- get inline() {
- return this.args.inline ?? isTesting();
- }
-
- <template>
- {{~#if this.inline}}
- {{yield}}
- {{else}}
- {{#in-element @portalOutletElement insertBefore=null}}
- {{yield}}
- {{/in-element}}
- {{/if~}}
- </template>
-}
diff --git a/frontend/discourse/float-kit/components/d-float-portal.gts b/frontend/discourse/float-kit/components/d-float-portal.gts
new file mode 100644
index 00000000000..f4147092528
--- /dev/null
+++ b/frontend/discourse/float-kit/components/d-float-portal.gts
@@ -0,0 +1,39 @@
+import Component from "@glimmer/component";
+import { isTesting } from "discourse/lib/environment";
+
+interface DFloatPortalSignature {
+ Args: {
+ /** Whether to render in place instead of into the portal outlet. */
+ inline?: boolean | null;
+
+ /** The element to render into, instead of the default portal outlet. */
+ portalOutletElement?: HTMLElement | null;
+ };
+ Blocks: {
+ /** The content to render in place or teleport into the portal outlet. */
+ default: [];
+ };
+}
+
+/**
+ * The lowest-level teleport primitive shared by every float. It either renders
+ * its content in place or moves it (via `{{in-element}}`) into a portal outlet
+ * mounted near the document root, so the content escapes any `overflow` clipping
+ * or stacking context of its trigger. Rendering is forced in place under tests,
+ * where there is no portal outlet to teleport into.
+ */
+export default class DFloatPortal extends Component<DFloatPortalSignature> {
+ get inline() {
+ return this.args.inline ?? isTesting();
+ }
+
+ <template>
+ {{~#if this.inline}}
+ {{yield}}
+ {{else}}
+ {{#in-element @portalOutletElement insertBefore=null}}
+ {{yield}}
+ {{/in-element}}
+ {{/if~}}
+ </template>
+}
diff --git a/frontend/discourse/float-kit/components/d-headless-menu.gjs b/frontend/discourse/float-kit/components/d-headless-menu.gjs
deleted file mode 100644
index 0e8d27527c3..00000000000
--- a/frontend/discourse/float-kit/components/d-headless-menu.gjs
+++ /dev/null
@@ -1,14 +0,0 @@
-import DInlineFloat from "discourse/float-kit/components/d-inline-float";
-
-const DHeadlessMenu = <template>
- <DInlineFloat
- @instance={{@menu}}
- @trapTab={{@menu.options.trapTab}}
- @mainClass="fk-d-menu"
- @innerClass="fk-d-menu__inner-content"
- @role="dialog"
- @inline={{@inline}}
- />
-</template>;
-
-export default DHeadlessMenu;
diff --git a/frontend/discourse/float-kit/components/d-headless-menu.gts b/frontend/discourse/float-kit/components/d-headless-menu.gts
new file mode 100644
index 00000000000..94ada097d59
--- /dev/null
+++ b/frontend/discourse/float-kit/components/d-headless-menu.gts
@@ -0,0 +1,33 @@
+import type { TemplateOnlyComponent } from "@ember/component/template-only";
+import DInlineFloat from "discourse/float-kit/components/d-inline-float";
+import type DMenuInstance from "discourse/float-kit/lib/d-menu-instance";
+
+interface DHeadlessMenuSignature {
+ Args: {
+ /** The menu instance to render. */
+ menu: DMenuInstance;
+
+ /** Whether to render in place instead of into the portal outlet. */
+ inline?: boolean | null;
+ };
+}
+
+/**
+ * Renders a menu instance created through the `menu` service, whose trigger
+ * lives elsewhere in the DOM rather than being owned by this component. It is
+ * mounted once by `DMenus` at the app root, which iterates every registered
+ * menu with a detached trigger. Compare `DMenu`, the declarative component that
+ * owns both its trigger and its instance.
+ */
+const DHeadlessMenu: TemplateOnlyComponent<DHeadlessMenuSignature> = <template>
+ <DInlineFloat
+ @instance={{@menu}}
+ @trapTab={{@menu.options.trapTab}}
+ @mainClass="fk-d-menu"
+ @innerClass="fk-d-menu__inner-content"
+ @role="dialog"
+ @inline={{@inline}}
+ />
+</template>;
+
+export default DHeadlessMenu;
diff --git a/frontend/discourse/float-kit/components/d-headless-tooltip.gjs b/frontend/discourse/float-kit/components/d-headless-tooltip.gjs
deleted file mode 100644
index ebf8897544f..00000000000
--- a/frontend/discourse/float-kit/components/d-headless-tooltip.gjs
+++ /dev/null
@@ -1,15 +0,0 @@
-import DInlineFloat from "discourse/float-kit/components/d-inline-float";
-import { and } from "discourse/truth-helpers";
-
-const DHeadlessTooltip = <template>
- <DInlineFloat
- @instance={{@tooltip}}
- @trapTab={{and @tooltip.options.interactive @tooltip.options.trapTab}}
- @mainClass="fk-d-tooltip__content"
- @innerClass="fk-d-tooltip__inner-content"
- @role="tooltip"
- @inline={{@inline}}
- />
-</template>;
-
-export default DHeadlessTooltip;
diff --git a/frontend/discourse/float-kit/components/d-headless-tooltip.gts b/frontend/discourse/float-kit/components/d-headless-tooltip.gts
new file mode 100644
index 00000000000..2393c8b1214
--- /dev/null
+++ b/frontend/discourse/float-kit/components/d-headless-tooltip.gts
@@ -0,0 +1,35 @@
+import type { TemplateOnlyComponent } from "@ember/component/template-only";
+import DInlineFloat from "discourse/float-kit/components/d-inline-float";
+import type DTooltipInstance from "discourse/float-kit/lib/d-tooltip-instance";
+import { and } from "discourse/truth-helpers";
+
+interface DHeadlessTooltipSignature {
+ Args: {
+ /** The tooltip instance to render. */
+ tooltip: DTooltipInstance;
+
+ /** Whether to render in place instead of into the portal outlet. */
+ inline?: boolean | null;
+ };
+}
+
+/**
+ * Renders a tooltip instance created through the `tooltip` service, whose
+ * trigger lives elsewhere in the DOM rather than being owned by this component.
+ * It is mounted once by `DTooltips` at the app root, which iterates every
+ * registered tooltip with a detached trigger. Compare `DTooltip`, the
+ * declarative component that owns both its trigger and its instance.
+ */
+const DHeadlessTooltip: TemplateOnlyComponent<DHeadlessTooltipSignature> =
+ <template>
+ <DInlineFloat
+ @instance={{@tooltip}}
+ @trapTab={{and @tooltip.options.interactive @tooltip.options.trapTab}}
+ @mainClass="fk-d-tooltip__content"
+ @innerClass="fk-d-tooltip__inner-content"
+ @role="tooltip"
+ @inline={{@inline}}
+ />
+ </template>;
+
+export default DHeadlessTooltip;
diff --git a/frontend/discourse/float-kit/components/d-inline-float.gjs b/frontend/discourse/float-kit/components/d-inline-float.gts
similarity index 57%
rename from frontend/discourse/float-kit/components/d-inline-float.gjs
rename to frontend/discourse/float-kit/components/d-inline-float.gts
index c9182ad0a4b..7b6cefed799 100644
--- a/frontend/discourse/float-kit/components/d-inline-float.gjs
+++ b/frontend/discourse/float-kit/components/d-inline-float.gts
@@ -2,12 +2,45 @@ import Component from "@glimmer/component";
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 DModal from "discourse/ui-kit/d-modal";
import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
-export default class DInlineFloat extends Component {
- @service site;
+interface DInlineFloatSignature {
+ Args: {
+ /** The float instance to render. */
+ instance: FloatKitInstance;
+
+ /** Whether to trap Tab focus within the content. */
+ trapTab?: boolean;
+
+ /** A class added to the outer float element. */
+ mainClass?: string;
+
+ /** A class added to the inner content element. */
+ innerClass?: string;
+
+ /** The ARIA role for the content. */
+ role?: string;
+
+ /** Whether to render in place instead of into the portal outlet. */
+ inline?: boolean | null;
+ };
+}
+
+/**
+ * Renders an already-created float instance, choosing how to present it: a
+ * full-screen modal on mobile when the instance opts into `modalForMobile`, and
+ * otherwise the standard positioned body (see `DFloatBody`). It only renders
+ * while the instance is expanded. This is the render path for floats created
+ * through the service API, whose trigger lives elsewhere (see `DHeadlessMenu`
+ * 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}}
diff --git a/frontend/discourse/float-kit/components/d-menu.gjs b/frontend/discourse/float-kit/components/d-menu.gjs
deleted file mode 100644
index 3989b9be965..00000000000
--- a/frontend/discourse/float-kit/components/d-menu.gjs
+++ /dev/null
@@ -1,205 +0,0 @@
-import Component from "@glimmer/component";
-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 curryComponent from "ember-curry-component";
-import { modifier } from "ember-modifier";
-import DFloatBody from "discourse/float-kit/components/d-float-body";
-import { MENU } from "discourse/float-kit/lib/constants";
-import DMenuInstance from "discourse/float-kit/lib/d-menu-instance";
-import { isTesting } from "discourse/lib/environment";
-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";
-
-export default class DMenu extends Component {
- @service site;
-
- menuInstance = new DMenuInstance(getOwner(this), {
- ...this.allowedProperties,
- autoUpdate: true,
- listeners: true,
- });
-
- registerTrigger = modifier((domElement) => {
- this.menuInstance.trigger = domElement;
- this.options.onRegisterApi?.(this.menuInstance);
-
- return () => {
- this.menuInstance.destroy();
- };
- });
-
- registerFloatBody = modifier((domElement) => {
- this.body = domElement;
-
- return () => {
- this.body = null;
- };
- });
-
- @action
- teardownFloatBody() {
- this.body = null;
- }
-
- @action
- forwardTabToContent(event) {
- // 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) {
- return parentHandlerResult;
- }
-
- if (event.key === "Tab") {
- event.preventDefault();
-
- const firstFocusable = this.body.querySelector(
- 'button, a, input:not([type="hidden"]), select, textarea, [tabindex]:not([tabindex="-1"])'
- );
-
- firstFocusable?.focus() || this.body.focus();
- return true;
- }
-
- return parentHandlerResult;
- }
-
- get options() {
- return this.menuInstance?.options ?? {};
- }
-
- get componentArgs() {
- return {
- close: this.menuInstance.close,
- show: this.menuInstance.show,
- data: this.options.data,
- };
- }
-
- get triggerComponent() {
- const instance = this;
- const baseArguments = {
- get icon() {
- return instance.args.icon;
- },
- get translatedLabel() {
- return instance.args.label;
- },
- get translatedAriaLabel() {
- return instance.args.ariaLabel;
- },
- get translatedTitle() {
- return instance.args.title;
- },
- get disabled() {
- return instance.args.disabled;
- },
- get isLoading() {
- return instance.args.isLoading;
- },
- };
-
- return (
- this.args.triggerComponent ||
- curryComponent(DButton, baseArguments, getOwner(this))
- );
- }
-
- get allowedProperties() {
- const properties = {};
- for (const [key, value] of Object.entries(MENU.options)) {
- properties[key] = this.args[key] ?? value;
- }
- return properties;
- }
-
- <template>
- <this.triggerComponent
- {{this.registerTrigger}}
- class={{dConcatClass
- "fk-d-menu__trigger"
- (if this.menuInstance.expanded "-expanded")
- (concat this.options.identifier "-trigger")
- @triggerClass
- @class
- }}
- id={{this.menuInstance.id}}
- data-identifier={{this.options.identifier}}
- data-trigger
- aria-expanded={{if this.menuInstance.expanded "true" "false"}}
- {{on "keydown" this.forwardTabToContent}}
- @componentArgs={{this.componentArgs}}
- ...attributes
- >
- {{#if (has-block "trigger")}}
- {{yield this.componentArgs to="trigger"}}
- {{/if}}
- </this.triggerComponent>
-
- {{#if this.menuInstance.expanded}}
- {{#if (and this.site.mobileView this.options.modalForMobile)}}
- <DModal
- @closeModal={{this.menuInstance.close}}
- @hideHeader={{true}}
- @autofocus={{this.options.autofocus}}
- class={{dConcatClass
- "fk-d-menu-modal"
- (concat this.options.identifier "-content")
- @contentClass
- @class
- }}
- @inline={{(isTesting)}}
- data-identifier={{this.options.identifier}}
- data-content
- >
- <div class="fk-d-menu-modal__grip" aria-hidden="true"></div>
- {{#if (has-block)}}
- {{yield this.componentArgs}}
- {{else if (has-block "content")}}
- {{yield this.componentArgs to="content"}}
- {{else if this.options.component}}
- <this.options.component
- @data={{this.options.data}}
- @close={{this.menuInstance.close}}
- />
- {{else if this.options.content}}
- {{this.options.content}}
- {{/if}}
- </DModal>
- {{else}}
- <DFloatBody
- @instance={{this.menuInstance}}
- @trapTab={{this.options.trapTab}}
- @mainClass={{dConcatClass
- "fk-d-menu"
- (concat this.options.identifier "-content")
- @class
- @contentClass
- }}
- @innerClass="fk-d-menu__inner-content"
- @role="dialog"
- @inline={{this.options.inline}}
- {{this.registerFloatBody}}
- >
- {{#if (has-block)}}
- {{yield this.componentArgs}}
- {{else if (has-block "content")}}
- {{yield this.componentArgs to="content"}}
- {{else if this.options.component}}
- <this.options.component
- @data={{this.options.data}}
- @close={{this.menuInstance.close}}
- />
- {{else if this.options.content}}
- {{this.options.content}}
- {{/if}}
- </DFloatBody>
- {{/if}}
- {{/if}}
- </template>
-}
diff --git a/frontend/discourse/float-kit/components/d-menu.gts b/frontend/discourse/float-kit/components/d-menu.gts
new file mode 100644
index 00000000000..5fabb9291b9
--- /dev/null
+++ b/frontend/discourse/float-kit/components/d-menu.gts
@@ -0,0 +1,305 @@
+import Component from "@glimmer/component";
+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";
+import DFloatBody from "discourse/float-kit/components/d-float-body";
+import {
+ type FloatCallback,
+ MENU,
+ type MenuOptions,
+} from "discourse/float-kit/lib/constants";
+import DMenuInstance from "discourse/float-kit/lib/d-menu-instance";
+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";
+
+/** The object yielded to each of the menu's blocks and passed to a rendered component. */
+export interface DMenuComponentArgs<Data = unknown> {
+ /** Closes the menu. */
+ close: FloatCallback;
+
+ /** Opens the menu. */
+ show: FloatCallback;
+
+ /** The `@data` passed to the menu. */
+ data?: Data;
+}
+
+// The subset of arguments that mirror a menu's option bag. Built as a
+// `Partial<Omit<…>>` over `MenuOptions` (defined in `constants.ts`), so the
+// arguments track the options automatically: a field added there is accepted here
+// for free, with no second list to keep in sync. The three omitted fields are
+// re-declared to narrow their generic `MenuOptions` types (`data: unknown`, a
+// `Data`-agnostic `component`, `onRegisterApi: FloatCallback | null`) to the
+// component's `Data` and the concrete `DMenuInstance`.
+type DMenuOptionArgs<Data> = Partial<
+ Omit<MenuOptions, "data" | "component" | "onRegisterApi">
+> & {
+ /** The data passed to the content block and rendered component. */
+ data?: Data;
+
+ /** A component rendered as the content; it receives the `@data` and `@close` arguments. */
+ component?: ComponentLike<{ Args: { data?: Data; close?: FloatCallback } }>;
+
+ /** Called with the menu instance when it is created, so callers can control it programmatically. */
+ onRegisterApi?: (instance: DMenuInstance) => void;
+};
+
+interface DMenuSignature<Data = unknown> {
+ Element: HTMLElement;
+ Args: DMenuOptionArgs<Data> & {
+ // Arguments the component reads directly and forwards to the trigger button;
+ // these are not keys of `MENU.options`.
+
+ /** Called on keydown on the default trigger button. */
+ onKeydown?: (event: KeyboardEvent) => unknown;
+
+ /** A component rendered as the trigger, instead of the default button. */
+ triggerComponent?: ComponentLike;
+
+ /** The icon ID for the default trigger button. */
+ icon?: string;
+
+ /** The label for the default trigger button. */
+ label?: string;
+
+ /** The aria-label for the default trigger button. */
+ ariaLabel?: string;
+
+ /** The title for the default trigger button. */
+ title?: string;
+
+ /** Whether the default trigger button is disabled. */
+ disabled?: boolean;
+
+ /** Whether the default trigger button shows a loading state. */
+ isLoading?: boolean;
+ };
+ Blocks: {
+ /** The menu content; takes precedence over the `content` block. Yields the menu api. */
+ default: [DMenuComponentArgs<Data>];
+
+ /** Rendered as the trigger, replacing the default button. Yields the menu api. */
+ trigger: [DMenuComponentArgs<Data>];
+
+ /** The menu content, used when no default block is given. Yields the menu api. */
+ content: [DMenuComponentArgs<Data>];
+ };
+}
+
+/**
+ * The declarative menu component: it renders a trigger (the default button, a
+ * supplied `triggerComponent`, or a `trigger` block) and, while open, the menu
+ * content in a positioned float. It creates and owns its own `DMenuInstance`,
+ * populating the instance options from its arguments, so a template can drop in
+ * a menu without touching the `menu` service. For a menu whose trigger is
+ * managed separately through that service, see `DHeadlessMenu`.
+ */
+export default class DMenu<Data = unknown> extends Component<
+ DMenuSignature<Data>
+> {
+ @service declare site: Site;
+
+ menuInstance = new DMenuInstance(getOwner(this)!, {
+ ...this.allowedProperties,
+ autoUpdate: true,
+ listeners: true,
+ } as Partial<MenuOptions>);
+
+ registerTrigger = modifier((domElement: HTMLElement) => {
+ this.menuInstance.trigger = domElement;
+ this.options.onRegisterApi?.(this.menuInstance);
+
+ return () => {
+ this.menuInstance.destroy();
+ };
+ });
+
+ registerFloatBody = modifier((domElement: HTMLElement) => {
+ this.#body = domElement;
+
+ return () => {
+ this.#body = null;
+ };
+ });
+
+ #body: HTMLElement | null = null;
+
+ @action
+ teardownFloatBody() {
+ this.#body = null;
+ }
+
+ @action
+ forwardTabToContent(event: KeyboardEvent) {
+ // 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) {
+ return parentHandlerResult;
+ }
+
+ if (event.key === "Tab") {
+ event.preventDefault();
+
+ const firstFocusable = this.#body.querySelector<HTMLElement>(
+ 'button, a, input:not([type="hidden"]), select, textarea, [tabindex]:not([tabindex="-1"])'
+ );
+
+ firstFocusable?.focus();
+ this.#body.focus();
+
+ return true;
+ }
+
+ return parentHandlerResult;
+ }
+
+ get options(): MenuOptions {
+ return this.menuInstance?.options ?? ({} as MenuOptions);
+ }
+
+ get componentArgs(): DMenuComponentArgs<Data> {
+ return {
+ close: this.menuInstance.close,
+ show: this.menuInstance.show,
+ data: this.options.data as Data,
+ };
+ }
+
+ get triggerComponent() {
+ const args = this.args;
+ const baseArguments = {
+ get icon() {
+ return args.icon;
+ },
+ get translatedLabel() {
+ return args.label;
+ },
+ get translatedAriaLabel() {
+ return args.ariaLabel;
+ },
+ get translatedTitle() {
+ return args.title;
+ },
+ get disabled() {
+ return args.disabled;
+ },
+ get isLoading() {
+ return args.isLoading;
+ },
+ };
+
+ // The template forwards `@componentArgs` plus element attributes and a modifier that
+ // the concrete trigger component (the default `DButton`, or a consumer-supplied one)
+ // does not declare but honors at runtime, so the result is cast to a component type
+ // describing that passthrough.
+ return (this.args.triggerComponent ||
+ curryComponent(DButton, baseArguments, getOwner(this))) as ComponentLike<{
+ Element: HTMLElement;
+ Args: { componentArgs?: DMenuComponentArgs<Data> };
+ Blocks: { default: [] };
+ }>;
+ }
+
+ 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;
+ }
+ return properties;
+ }
+
+ <template>
+ <this.triggerComponent
+ {{this.registerTrigger}}
+ class={{dConcatClass
+ "fk-d-menu__trigger"
+ (if this.menuInstance.expanded "-expanded")
+ (concat this.options.identifier "-trigger")
+ @triggerClass
+ @class
+ }}
+ id={{this.menuInstance.id}}
+ data-identifier={{this.options.identifier}}
+ data-trigger
+ aria-expanded={{if this.menuInstance.expanded "true" "false"}}
+ {{on "keydown" this.forwardTabToContent}}
+ @componentArgs={{this.componentArgs}}
+ ...attributes
+ >
+ {{#if (has-block "trigger")}}
+ {{yield this.componentArgs to="trigger"}}
+ {{/if}}
+ </this.triggerComponent>
+
+ {{#if this.menuInstance.expanded}}
+ {{#if (and this.site.mobileView this.options.modalForMobile)}}
+ <DModal
+ @closeModal={{this.menuInstance.close}}
+ @hideHeader={{true}}
+ @autofocus={{this.options.autofocus}}
+ class={{dConcatClass
+ "fk-d-menu-modal"
+ (concat this.options.identifier "-content")
+ @contentClass
+ @class
+ }}
+ @inline={{(isTesting)}}
+ data-identifier={{this.options.identifier}}
+ data-content
+ >
+ <div class="fk-d-menu-modal__grip" aria-hidden="true"></div>
+ {{#if (has-block)}}
+ {{yield this.componentArgs}}
+ {{else if (has-block "content")}}
+ {{yield this.componentArgs to="content"}}
+ {{else if this.options.component}}
+ <this.options.component
+ @data={{this.options.data}}
+ @close={{this.menuInstance.close}}
+ />
+ {{else if this.options.content}}
+ {{this.options.content}}
+ {{/if}}
+ </DModal>
+ {{else}}
+ <DFloatBody
+ @instance={{this.menuInstance}}
+ @trapTab={{this.options.trapTab}}
+ @mainClass={{dConcatClass
+ "fk-d-menu"
+ (concat this.options.identifier "-content")
+ @class
+ @contentClass
+ }}
+ @innerClass="fk-d-menu__inner-content"
+ @role="dialog"
+ @inline={{this.options.inline}}
+ {{this.registerFloatBody}}
+ >
+ {{#if (has-block)}}
+ {{yield this.componentArgs}}
+ {{else if (has-block "content")}}
+ {{yield this.componentArgs to="content"}}
+ {{else if this.options.component}}
+ <this.options.component
+ @data={{this.options.data}}
+ @close={{this.menuInstance.close}}
+ />
+ {{else if this.options.content}}
+ {{this.options.content}}
+ {{/if}}
+ </DFloatBody>
+ {{/if}}
+ {{/if}}
+ </template>
+}
diff --git a/frontend/discourse/float-kit/components/d-menus.gjs b/frontend/discourse/float-kit/components/d-menus.gts
similarity index 51%
rename from frontend/discourse/float-kit/components/d-menus.gjs
rename to frontend/discourse/float-kit/components/d-menus.gts
index da86993af3e..aff115d387a 100644
--- a/frontend/discourse/float-kit/components/d-menus.gjs
+++ b/frontend/discourse/float-kit/components/d-menus.gts
@@ -1,9 +1,16 @@
import Component from "@glimmer/component";
import { service } from "@ember/service";
import DHeadlessMenu from "discourse/float-kit/components/d-headless-menu";
+import type MenuService from "discourse/float-kit/services/menu";
+/**
+ * The app-root host for service-driven menus, mounted once. It provides the
+ * portal outlet that menus teleport their content into, and renders a
+ * `DHeadlessMenu` for every menu registered with the `menu` service whose
+ * trigger is detached (i.e. created through the service rather than by `DMenu`).
+ */
export default class DMenus extends Component {
- @service menu;
+ @service declare menu: MenuService;
<template>
<div id="d-menu-portals"></div>
diff --git a/frontend/discourse/float-kit/components/d-popover.gjs b/frontend/discourse/float-kit/components/d-popover.gjs
deleted file mode 100644
index 9915391b6a3..00000000000
--- a/frontend/discourse/float-kit/components/d-popover.gjs
+++ /dev/null
@@ -1,38 +0,0 @@
-import Component from "@glimmer/component";
-import { service } from "@ember/service";
-import { modifier } from "ember-modifier";
-import deprecated from "discourse/lib/deprecated";
-
-export default class DPopover extends Component {
- @service tooltip;
-
- registerDTooltip = modifier((element) => {
- deprecated(
- "`<DPopover />` is deprecated. Use `<DTooltip />` or the `tooltip` service instead.",
- { id: "discourse.d-popover" }
- );
-
- const trigger = element.children[0];
- const content = element.children[1];
-
- if (!trigger || !content) {
- return;
- }
-
- const instance = this.tooltip.register(trigger, {
- content,
- });
-
- content.remove();
-
- return () => {
- instance.destroy();
- };
- });
-
- <template>
- <div style="display:inline-flex;" {{this.registerDTooltip}}>
- {{yield}}
- </div>
- </template>
-}
diff --git a/frontend/discourse/float-kit/components/d-popover.gts b/frontend/discourse/float-kit/components/d-popover.gts
new file mode 100644
index 00000000000..55a43615165
--- /dev/null
+++ b/frontend/discourse/float-kit/components/d-popover.gts
@@ -0,0 +1,55 @@
+import Component from "@glimmer/component";
+import { service } from "@ember/service";
+import { modifier } from "ember-modifier";
+import type TooltipService from "discourse/float-kit/services/tooltip";
+import deprecated from "discourse/lib/deprecated";
+
+interface DPopoverSignature {
+ Blocks: {
+ /** The trigger followed by the popover content. */
+ default: [];
+ };
+}
+
+/**
+ * A legacy wrapper that turns its first child into a tooltip trigger and its
+ * second child into that tooltip's content, registering the pair through the
+ * `tooltip` service. It exists only for backwards compatibility.
+ *
+ * @deprecated Use `<DTooltip />` or the `tooltip` service instead.
+ */
+export default class DPopover extends Component<DPopoverSignature> {
+ @service declare tooltip: TooltipService;
+
+ registerDTooltip = modifier((element: HTMLElement) => {
+ deprecated(
+ "`<DPopover />` is deprecated. Use `<DTooltip />` or the `tooltip` service instead.",
+ { id: "discourse.d-popover" }
+ );
+
+ const trigger = element.children[0];
+ const content = element.children[1];
+
+ if (!trigger || !content) {
+ return;
+ }
+
+ // The deprecated popover hands the tooltip a detached DOM node as its content,
+ // which the option bag types as a renderable `string`; cast at this boundary.
+ const instance = this.tooltip.register(trigger, {
+ content: content as unknown as string,
+ });
+
+ content.remove();
+
+ return () => {
+ instance.destroy();
+ };
+ });
+
+ <template>
+ <div style="display:inline-flex;" {{this.registerDTooltip}}>
+ {{yield}}
+ </div>
+ </template>
+}
diff --git a/frontend/discourse/float-kit/components/d-toast.gjs b/frontend/discourse/float-kit/components/d-toast.gts
similarity index 70%
rename from frontend/discourse/float-kit/components/d-toast.gjs
rename to frontend/discourse/float-kit/components/d-toast.gts
index b39901f4540..d45eb5fbd93 100644
--- a/frontend/discourse/float-kit/components/d-toast.gjs
+++ b/frontend/discourse/float-kit/components/d-toast.gts
@@ -1,25 +1,40 @@
import Component from "@glimmer/component";
import { tracked } from "@glimmer/tracking";
import { action } from "@ember/object";
+import type DToastInstance from "discourse/float-kit/lib/d-toast-instance";
import autoCloseToast from "discourse/float-kit/modifiers/auto-close-toast";
import deprecated from "discourse/lib/deprecated";
import { getMaxAnimationTimeMs } from "discourse/lib/swipe-events";
import { and } from "discourse/truth-helpers";
import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
-import dSwipe from "discourse/ui-kit/modifiers/d-swipe";
+import dSwipe, { type SwipeState } from "discourse/ui-kit/modifiers/d-swipe";
const VELOCITY_THRESHOLD = -1.2;
-export default class DToast extends Component {
- @tracked progressBar;
+interface DToastSignature {
+ Args: {
+ /** The toast instance to render. */
+ toast: DToastInstance;
+ };
+}
+
+/**
+ * Renders a single active toast instance and owns its interactive behavior:
+ * swipe-up to dismiss and, when the instance enables auto-close, a progress bar
+ * that counts down to closing. The visible body is the instance's configured
+ * component (`DDefaultToast` by default). It is mounted once per active toast by
+ * `DToasts`, which iterates the `toasts` service.
+ */
+export default class DToast extends Component<DToastSignature> {
+ @tracked progressBar?: HTMLElement;
@action
- registerProgressBar(element) {
+ registerProgressBar(element: HTMLElement) {
this.progressBar = element;
}
@action
- async didSwipe(state) {
+ async didSwipe(state: SwipeState) {
if (state.deltaY >= 0) {
this.#animateWrapperPosition(state.element, 0);
return;
@@ -33,7 +48,7 @@ export default class DToast extends Component {
}
@action
- async didEndSwipe(state) {
+ async didEndSwipe(state: SwipeState) {
if (state.velocityY < VELOCITY_THRESHOLD) {
await this.#close(state.element);
} else {
@@ -41,24 +56,6 @@ export default class DToast extends Component {
}
}
- async #close(element) {
- await this.#closeWrapperAnimation(element);
- this.args.toast.close();
- }
-
- async #closeWrapperAnimation(element) {
- await element.animate([{ transform: "translateY(-150px)" }], {
- fill: "forwards",
- duration: getMaxAnimationTimeMs(),
- }).finished;
- }
-
- async #animateWrapperPosition(element, position) {
- await element.animate([{ transform: `translateY(${position}px)` }], {
- fill: "forwards",
- }).finished;
- }
-
get duration() {
const duration = this.args.toast.options.duration;
@@ -76,10 +73,27 @@ export default class DToast extends Component {
}
}
+ async #close(element: HTMLElement) {
+ await this.#closeWrapperAnimation(element);
+ this.args.toast.close();
+ }
+
+ async #closeWrapperAnimation(element: HTMLElement) {
+ await element.animate([{ transform: "translateY(-150px)" }], {
+ fill: "forwards",
+ duration: getMaxAnimationTimeMs(),
+ }).finished;
+ }
+
+ async #animateWrapperPosition(element: HTMLElement, position: number) {
+ await element.animate([{ transform: `translateY(${position}px)` }], {
+ fill: "forwards",
+ }).finished;
+ }
+
<template>
<output
role={{if @toast.options.autoClose "status" "log"}}
- key={{@toast.id}}
class={{dConcatClass "fk-d-toast" @toast.options.class}}
{{autoCloseToast
diff --git a/frontend/discourse/float-kit/components/d-toasts.gjs b/frontend/discourse/float-kit/components/d-toasts.gts
similarity index 57%
rename from frontend/discourse/float-kit/components/d-toasts.gjs
rename to frontend/discourse/float-kit/components/d-toasts.gts
index 29149199a4f..24603d3d87a 100644
--- a/frontend/discourse/float-kit/components/d-toasts.gjs
+++ b/frontend/discourse/float-kit/components/d-toasts.gts
@@ -1,9 +1,14 @@
import Component from "@glimmer/component";
import { service } from "@ember/service";
import DToast from "discourse/float-kit/components/d-toast";
+import type ToastsService from "discourse/float-kit/services/toasts";
+/**
+ * The app-root host for toasts, mounted once. It renders a `DToast` for every
+ * toast currently active in the `toasts` service, stacked in a fixed container.
+ */
export default class DToasts extends Component {
- @service toasts;
+ @service declare toasts: ToastsService;
<template>
<section class="fk-d-toasts">
diff --git a/frontend/discourse/float-kit/components/d-tooltip.gjs b/frontend/discourse/float-kit/components/d-tooltip.gjs
deleted file mode 100644
index 632215afcd8..00000000000
--- a/frontend/discourse/float-kit/components/d-tooltip.gjs
+++ /dev/null
@@ -1,105 +0,0 @@
-import Component from "@glimmer/component";
-import { concat } from "@ember/helper";
-import { getOwner } from "@ember/owner";
-import { service } from "@ember/service";
-import { modifier } from "ember-modifier";
-import DFloatBody from "discourse/float-kit/components/d-float-body";
-import { TOOLTIP } from "discourse/float-kit/lib/constants";
-import DTooltipInstance from "discourse/float-kit/lib/d-tooltip-instance";
-import { and } from "discourse/truth-helpers";
-import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
-import dIcon from "discourse/ui-kit/helpers/d-icon";
-
-export default class DTooltip extends Component {
- @service tooltip;
-
- tooltipInstance = new DTooltipInstance(getOwner(this), {
- ...this.allowedProperties,
- autoUpdate: true,
- listeners: true,
- });
-
- registerTrigger = modifier((element) => {
- this.tooltipInstance.trigger = element;
- this.options.onRegisterApi?.(this.tooltipInstance);
-
- return () => {
- this.tooltipInstance.destroy();
- };
- });
-
- get options() {
- return this.tooltipInstance?.options;
- }
-
- get componentArgs() {
- return {
- close: this.tooltip.close,
- data: this.options.data,
- };
- }
-
- get allowedProperties() {
- const properties = {};
- for (const [key, value] of Object.entries(TOOLTIP.options)) {
- properties[key] = this.args[key] ?? value;
- }
- return properties;
- }
-
- <template>
- <span
- {{this.registerTrigger this.allowedProperties}}
- class={{dConcatClass
- "fk-d-tooltip__trigger"
- (if this.tooltipInstance.expanded "-expanded")
- }}
- role="button"
- id={{this.tooltipInstance.id}}
- data-identifier={{this.options.identifier}}
- data-trigger
- aria-expanded={{if this.tooltipInstance.expanded "true" "false"}}
- ...attributes
- >
- <span class="fk-d-tooltip__trigger-container">
- {{~#if (has-block "trigger")~}}
- {{yield this.componentArgs to="trigger"}}
- {{~else~}}
- {{#if @icon}}
- <span class="fk-d-tooltip__icon">
- {{~dIcon @icon~}}
- </span>
- {{/if}}
- {{#if @label}}
- <span class="fk-d-tooltip__label">{{@label}}</span>
- {{/if}}
- {{~/if~}}
- </span></span>
- {{~#if this.tooltipInstance.expanded~}}
- <DFloatBody
- @instance={{this.tooltipInstance}}
- @trapTab={{and this.options.interactive this.options.trapTab}}
- @mainClass={{dConcatClass
- "fk-d-tooltip__content"
- (concat this.options.identifier "-content")
- }}
- @innerClass="fk-d-tooltip__inner-content"
- @role="tooltip"
- @inline={{this.options.inline}}
- >
- {{#if (has-block)}}
- {{yield this.componentArgs}}
- {{else if (has-block "content")}}
- {{yield this.componentArgs to="content"}}
- {{else if this.options.component}}
- <this.options.component
- @data={{this.options.data}}
- @close={{this.tooltipInstance.close}}
- />
- {{else if this.options.content}}
- {{this.options.content}}
- {{/if}}
- </DFloatBody>
- {{~/if~}}
- </template>
-}
diff --git a/frontend/discourse/float-kit/components/d-tooltip.gts b/frontend/discourse/float-kit/components/d-tooltip.gts
new file mode 100644
index 00000000000..2021c98c561
--- /dev/null
+++ b/frontend/discourse/float-kit/components/d-tooltip.gts
@@ -0,0 +1,174 @@
+import Component from "@glimmer/component";
+import { concat } from "@ember/helper";
+import { getOwner } from "@ember/owner";
+import { service } from "@ember/service";
+import { type ComponentLike } from "@glint/template";
+import { modifier } from "ember-modifier";
+import DFloatBody from "discourse/float-kit/components/d-float-body";
+import {
+ type FloatCallback,
+ TOOLTIP,
+ type TooltipOptions,
+} from "discourse/float-kit/lib/constants";
+import DTooltipInstance from "discourse/float-kit/lib/d-tooltip-instance";
+import type TooltipService from "discourse/float-kit/services/tooltip";
+import { and } from "discourse/truth-helpers";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+
+/** The object yielded to each of the tooltip's blocks. */
+export interface DTooltipComponentArgs<Data = unknown> {
+ /** Closes the tooltip. */
+ close: FloatCallback;
+
+ /** The `@data` passed to the tooltip. */
+ data?: Data;
+}
+
+// The subset of arguments that mirror a tooltip's option bag. Built as a
+// `Partial<Omit<…>>` over `TooltipOptions` (defined in `constants.ts`), so the
+// arguments track the options automatically: a field added there is accepted here
+// for free, with no second list to keep in sync. The three omitted fields are
+// re-declared to narrow their generic `TooltipOptions` types (`data: unknown`, a
+// `Data`-agnostic `component`, `onRegisterApi: FloatCallback | null`) to the
+// component's `Data` and the concrete `DTooltipInstance`.
+type DTooltipOptionArgs<Data> = Partial<
+ Omit<TooltipOptions, "data" | "component" | "onRegisterApi">
+> & {
+ /** The data passed to the content block and rendered component. */
+ data?: Data;
+
+ /** A component rendered as the content; it receives the `@data` and `@close` arguments. */
+ component?: ComponentLike<{ Args: { data?: Data; close?: FloatCallback } }>;
+
+ /** Called with the tooltip instance when it is created, so callers can control it programmatically. */
+ onRegisterApi?: (instance: DTooltipInstance) => void;
+};
+
+interface DTooltipSignature<Data = unknown> {
+ Element: HTMLSpanElement;
+ Args: DTooltipOptionArgs<Data> & {
+ // Arguments the component reads directly and forwards to the trigger button;
+ // these are not keys of `TOOLTIP.options`.
+
+ /** The icon ID for the default trigger button. */
+ icon?: string;
+
+ /** The label for the default trigger button. */
+ label?: string;
+ };
+ Blocks: {
+ /** The tooltip content; takes precedence over the `content` block. Yields the tooltip api. */
+ default: [DTooltipComponentArgs<Data>];
+
+ /** Rendered as the trigger, replacing the default button. Yields the tooltip api. */
+ trigger: [DTooltipComponentArgs<Data>];
+
+ /** The tooltip content, used when no default block is given. Yields the tooltip api. */
+ content: [DTooltipComponentArgs<Data>];
+ };
+}
+
+/**
+ * The declarative tooltip component: it renders a trigger (an icon and/or label
+ * by default, or a `trigger` block) and, while open, the tooltip content in a
+ * positioned float. It creates and owns its own `DTooltipInstance`, populating
+ * the instance options from its arguments, so a template can drop in a tooltip
+ * without touching the `tooltip` service. For a tooltip whose trigger is managed
+ * separately through that service, see `DHeadlessTooltip`.
+ */
+export default class DTooltip<Data = unknown> extends Component<
+ DTooltipSignature<Data>
+> {
+ @service declare tooltip: TooltipService;
+
+ tooltipInstance = new DTooltipInstance(getOwner(this)!, {
+ ...this.allowedProperties,
+ autoUpdate: true,
+ listeners: true,
+ } as Partial<TooltipOptions>);
+
+ registerTrigger = modifier((element: HTMLElement) => {
+ this.tooltipInstance.trigger = element;
+ this.options.onRegisterApi?.(this.tooltipInstance);
+
+ return () => {
+ this.tooltipInstance.destroy();
+ };
+ });
+
+ get options(): TooltipOptions {
+ return this.tooltipInstance?.options;
+ }
+
+ get componentArgs(): DTooltipComponentArgs<Data> {
+ return {
+ close: this.tooltip.close,
+ data: this.options.data as Data,
+ };
+ }
+
+ get allowedProperties() {
+ const properties: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(TOOLTIP.options)) {
+ properties[key] = (this.args as Record<string, unknown>)[key] ?? value;
+ }
+ return properties;
+ }
+
+ <template>
+ <span
+ {{this.registerTrigger this.allowedProperties}}
+ class={{dConcatClass
+ "fk-d-tooltip__trigger"
+ (if this.tooltipInstance.expanded "-expanded")
+ }}
+ role="button"
+ id={{this.tooltipInstance.id}}
+ data-identifier={{this.options.identifier}}
+ data-trigger
+ aria-expanded={{if this.tooltipInstance.expanded "true" "false"}}
+ ...attributes
+ >
+ <span class="fk-d-tooltip__trigger-container">
+ {{~#if (has-block "trigger")~}}
+ {{yield this.componentArgs to="trigger"}}
+ {{~else~}}
+ {{#if @icon}}
+ <span class="fk-d-tooltip__icon">
+ {{~dIcon @icon~}}
+ </span>
+ {{/if}}
+ {{#if @label}}
+ <span class="fk-d-tooltip__label">{{@label}}</span>
+ {{/if}}
+ {{~/if~}}
+ </span></span>
+ {{~#if this.tooltipInstance.expanded~}}
+ <DFloatBody
+ @instance={{this.tooltipInstance}}
+ @trapTab={{and this.options.interactive this.options.trapTab}}
+ @mainClass={{dConcatClass
+ "fk-d-tooltip__content"
+ (concat this.options.identifier "-content")
+ }}
+ @innerClass="fk-d-tooltip__inner-content"
+ @role="tooltip"
+ @inline={{this.options.inline}}
+ >
+ {{#if (has-block)}}
+ {{yield this.componentArgs}}
+ {{else if (has-block "content")}}
+ {{yield this.componentArgs to="content"}}
+ {{else if this.options.component}}
+ <this.options.component
+ @data={{this.options.data}}
+ @close={{this.tooltipInstance.close}}
+ />
+ {{else if this.options.content}}
+ {{this.options.content}}
+ {{/if}}
+ </DFloatBody>
+ {{~/if~}}
+ </template>
+}
diff --git a/frontend/discourse/float-kit/components/d-tooltips.gjs b/frontend/discourse/float-kit/components/d-tooltips.gts
similarity index 51%
rename from frontend/discourse/float-kit/components/d-tooltips.gjs
rename to frontend/discourse/float-kit/components/d-tooltips.gts
index 0642ebd9fb7..45e8c8d9bde 100644
--- a/frontend/discourse/float-kit/components/d-tooltips.gjs
+++ b/frontend/discourse/float-kit/components/d-tooltips.gts
@@ -1,9 +1,17 @@
import Component from "@glimmer/component";
import { service } from "@ember/service";
import DHeadlessTooltip from "discourse/float-kit/components/d-headless-tooltip";
+import type TooltipService from "discourse/float-kit/services/tooltip";
+/**
+ * The app-root host for service-driven tooltips, mounted once. It provides the
+ * portal outlet that tooltips teleport their content into, and renders a
+ * `DHeadlessTooltip` for every tooltip registered with the `tooltip` service
+ * whose trigger is detached (i.e. created through the service rather than by
+ * `DTooltip`).
+ */
export default class DTooltips extends Component {
- @service tooltip;
+ @service declare tooltip: TooltipService;
<template>
<div id="d-tooltip-portals"></div>
diff --git a/frontend/discourse/float-kit/lib/constants.js b/frontend/discourse/float-kit/lib/constants.js
deleted file mode 100644
index 2f05121c8f8..00000000000
--- a/frontend/discourse/float-kit/lib/constants.js
+++ /dev/null
@@ -1,108 +0,0 @@
-export const FLOAT_UI_PLACEMENTS = [
- "top",
- "top-start",
- "top-end",
- "right",
- "right-start",
- "right-end",
- "bottom",
- "bottom-start",
- "bottom-end",
- "left",
- "left-start",
- "left-end",
-];
-
-export const VISIBILITY_OPTIMIZERS = {
- FLIP: "flip",
- AUTO_PLACEMENT: "autoPlacement",
- NONE: "none",
-};
-
-export const TOOLTIP = {
- options: {
- animated: true,
- arrow: true,
- beforeTrigger: null,
- closeOnClickOutside: true,
- closeOnEscape: true,
- closeOnScroll: true,
- component: null,
- content: null,
- identifier: null,
- inline: null,
- interactive: false,
- listeners: false,
- maxWidth: 350,
- data: null,
- offset: 10,
- triggers: { mobile: ["click"], desktop: ["hover", "click"] },
- untriggers: { mobile: ["click"], desktop: ["hover", "click"] },
- placement: "top",
- shiftBeforeVisibilityOptimizer: false,
- visibilityOptimizer: VISIBILITY_OPTIMIZERS.FLIP,
- fallbackPlacements: FLOAT_UI_PLACEMENTS,
- autoUpdate: true,
- trapTab: true,
- onClose: null,
- onShow: null,
- onRegisterApi: null,
- portalOutletElement: null,
- },
- portalOutletId: "d-tooltip-portal-outlet",
-};
-
-export const MENU = {
- options: {
- animated: true,
- arrow: false,
- autofocus: false,
- beforeTrigger: null,
- closeOnEscape: true,
- closeOnClickOutside: true,
- closeOnScroll: false,
- component: null,
- content: null,
- identifier: null,
- interactive: true,
- listeners: false,
- maxWidth: 400,
- data: null,
- offset: 10,
- triggers: ["click"],
- untriggers: ["click"],
- placement: "bottom-start",
- shiftBeforeVisibilityOptimizer: false,
- visibilityOptimizer: VISIBILITY_OPTIMIZERS.FLIP,
- fallbackPlacements: FLOAT_UI_PLACEMENTS,
- autoUpdate: true,
- trapTab: true,
- onClose: null,
- onShow: null,
- onRegisterApi: null,
- modalForMobile: false,
- inline: null,
- groupIdentifier: null,
- parentIdentifier: null,
- triggerClass: null,
- contentClass: null,
- class: null,
- matchTriggerMinWidth: false,
- matchTriggerWidth: false,
- portalOutletElement: null,
- },
- portalOutletId: "d-menu-portal-outlet",
-};
-
-import DDefaultToast from "discourse/float-kit/components/d-default-toast";
-
-export const TOAST = {
- options: {
- autoClose: true,
- autoUpdate: { ancestorScroll: false },
- duration: "short",
- component: DDefaultToast,
- showProgressBar: false,
- views: ["desktop", "mobile"],
- },
-};
diff --git a/frontend/discourse/float-kit/lib/constants.ts b/frontend/discourse/float-kit/lib/constants.ts
new file mode 100644
index 00000000000..b9059e83b2e
--- /dev/null
+++ b/frontend/discourse/float-kit/lib/constants.ts
@@ -0,0 +1,373 @@
+import type { AutoUpdateOptions, ReferenceElement } from "@floating-ui/dom";
+import { type ComponentLike } from "@glint/template";
+import DDefaultToast from "discourse/float-kit/components/d-default-toast";
+
+/**
+ * The placements floating-ui may position a float at, ordered by preference. Kept
+ * `as const` so consumers can derive the exact string-literal union (see
+ * `FloatUiPlacement`) instead of a loose `string`.
+ */
+export const FLOAT_UI_PLACEMENTS = [
+ "top",
+ "top-start",
+ "top-end",
+ "right",
+ "right-start",
+ "right-end",
+ "bottom",
+ "bottom-start",
+ "bottom-end",
+ "left",
+ "left-start",
+ "left-end",
+] as const;
+
+/**
+ * The strategies that keep a float on screen when its preferred placement would
+ * overflow. `FLIP` flips to the opposite side, `AUTO_PLACEMENT` picks the best fit,
+ * and `NONE` disables the optimizer entirely.
+ */
+export const VISIBILITY_OPTIMIZERS = {
+ FLIP: "flip",
+ AUTO_PLACEMENT: "autoPlacement",
+ NONE: "none",
+} as const;
+
+/**
+ * The reference a float is anchored to: either a real element or a virtual one — any
+ * object implementing `getBoundingClientRect` (floating-ui's `ReferenceElement`). The
+ * listener and focus code only runs against real elements (see `triggerElement`).
+ */
+export type FloatKitTrigger = ReferenceElement;
+
+/** One of the placements in `FLOAT_UI_PLACEMENTS`. */
+export type FloatUiPlacement = (typeof FLOAT_UI_PLACEMENTS)[number];
+
+/** One of the visibility-optimizer identifiers in `VISIBILITY_OPTIMIZERS`. */
+export type VisibilityOptimizer =
+ (typeof VISIBILITY_OPTIMIZERS)[keyof typeof VISIBILITY_OPTIMIZERS];
+
+/**
+ * A relayed lifecycle or trigger callback (`onShow`, `onClose`, `beforeTrigger`, …).
+ * These are handed straight to consumers that pass functions of varying arity and
+ * return type, so the signature is deliberately broad-but-real: it accepts any
+ * function, still documents intent, and type-checks the internal call — unlike the
+ * bare `Function` type (which yields an unchecked `any` and trips lint).
+ */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any -- a relay callback must accept consumer functions of any argument shape; `unknown[]` would reject them.
+export type FloatCallback = (...args: any[]) => void;
+
+/**
+ * The events that open (or close) a float. Either a single list applied on every
+ * viewport, or a split of `mobile`/`desktop` lists resolved against the current view.
+ */
+export type FloatTriggers = string[] | { mobile: string[]; desktop: string[] };
+
+/**
+ * The full set of options shared by menus and tooltips, after a consumer's partial
+ * options have been merged over the defaults below. This is the source of truth for
+ * the corresponding component arguments; every field is always present on an
+ * instance because the defaults populate it.
+ */
+export interface TooltipOptions {
+ /** Whether to animate the float as it opens and closes. */
+ animated: boolean;
+
+ /** Whether to render a directional arrow pointing at the trigger. */
+ arrow: boolean;
+
+ /** Read by the shared float body to decide whether to focus it; menus set it, tooltips leave it unset. */
+ autofocus?: boolean;
+
+ /** Read by the shared inline float to render as a modal on mobile; menus set it, tooltips leave it unset. */
+ modalForMobile?: boolean;
+
+ /** Called just before the float is shown. */
+ beforeTrigger: FloatCallback | null;
+
+ /** Whether a click outside the float closes it. */
+ closeOnClickOutside: boolean;
+
+ /** Whether pressing Escape closes the float. */
+ closeOnEscape: boolean;
+
+ /** Whether scrolling closes the float. */
+ closeOnScroll: boolean;
+
+ /** A component rendered as the content; it receives the `@data` and `@close` arguments. */
+ component: ComponentLike<{
+ Args: { data?: unknown; close?: FloatCallback };
+ }> | null;
+
+ /** The content rendered when neither a block nor a `component` is provided. */
+ content: string | null;
+
+ /**
+ * Sets a `data-identifier` attribute on both the trigger and the content. Several
+ * floats may share an identifier, but only one per identifier is open at a time.
+ */
+ identifier: string | null;
+
+ /** Improves positioning for a trigger that spans multiple lines. */
+ inline: boolean | null;
+
+ /** Whether the content stays open while the pointer moves into it, so it can be interacted with. */
+ interactive: boolean;
+
+ /** 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;
+
+ /** Passed as the `@data` argument to a `component` rendered as the content. */
+ data: unknown;
+
+ /** Displaces the content from its trigger, in pixels. */
+ offset: number;
+
+ /** The events that open the float. */
+ triggers: FloatTriggers;
+
+ /** The events that close the float. */
+ untriggers: FloatTriggers;
+
+ /** The preferred placement of the float relative to its trigger. */
+ placement: FloatUiPlacement;
+
+ /** Whether to shift the float into view before running the visibility optimizer, rather than after. */
+ shiftBeforeVisibilityOptimizer: boolean;
+
+ /** The strategy that keeps the float on screen when its preferred placement would overflow. */
+ visibilityOptimizer: VisibilityOptimizer;
+
+ /** The placements to try, in order, when the preferred one does not fit. */
+ fallbackPlacements: readonly FloatUiPlacement[];
+
+ /** Whether to reposition automatically as the trigger or viewport changes; an object passes floating-ui `autoUpdate` options. */
+ autoUpdate: boolean | AutoUpdateOptions;
+
+ /** Whether to trap Tab focus within the content. */
+ trapTab: boolean;
+
+ /** Called after the float closes. */
+ onClose: FloatCallback | null;
+
+ /** Called after the float shows. */
+ onShow: FloatCallback | null;
+
+ /** Called with the float instance when it is created, so callers can control it programmatically. */
+ onRegisterApi: FloatCallback | null;
+
+ /** The element to render the content into, instead of the default portal outlet. */
+ portalOutletElement: HTMLElement | null;
+}
+
+/**
+ * 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 menu template forwards to its trigger and content).
+ */
+export interface MenuOptions extends TooltipOptions {
+ /** Whether to focus the content when the menu opens. */
+ autofocus: boolean;
+
+ /** Whether the menu renders as a modal on mobile. */
+ modalForMobile: boolean;
+
+ /** Only one menu per group identifier is open at a time. */
+ groupIdentifier: string | null;
+
+ /** The identifier of the parent menu, for nested menus. */
+ parentIdentifier: string | null;
+
+ /** A class added to the trigger. */
+ triggerClass: string | null;
+
+ /** A class added to the content. */
+ contentClass: string | null;
+
+ /** A class added to both the trigger and the content. */
+ class: string | null;
+
+ /** Whether to set the content's min-width to the trigger's width. */
+ matchTriggerMinWidth: boolean;
+
+ /** Whether to set the content's width to the trigger's width. */
+ matchTriggerWidth: boolean;
+}
+
+/** One action button rendered by the default toast. */
+export interface ToastAction {
+ /** Called when the button is clicked, receiving the toast data and a close function. */
+ action?: (args: { data?: ToastData; close?: FloatCallback }) => void;
+
+ /** The icon ID for the button. */
+ icon?: string;
+
+ /** The label for the button. */
+ label?: string;
+
+ /** A class added to the button. */
+ class?: string;
+}
+
+/**
+ * The `@data` passed to a toast component. The default toast reads these fields;
+ * custom components may add their own (hence the index signature).
+ */
+export interface ToastData {
+ /** A theme name applied to the toast (e.g. `"success"`, `"error"`). */
+ theme?: string;
+
+ /** The icon ID shown in the toast. */
+ icon?: string;
+
+ /** The toast title. */
+ title?: string;
+
+ /** The toast message. */
+ message?: string;
+
+ /** Whether `message` is trusted HTML rather than plain text. */
+ isHtmlMessage?: boolean;
+
+ /** The action buttons shown in the toast. */
+ actions?: ToastAction[];
+
+ [key: string]: unknown;
+}
+
+/** The arguments a toast component receives (the default is `DDefaultToast`). */
+export interface ToastComponentArgs {
+ /** The data to render in the toast. */
+ data?: ToastData;
+
+ /** Closes the toast. */
+ close?: FloatCallback;
+
+ /** Whether to show a progress bar counting down to auto-close. */
+ showProgressBar?: boolean;
+
+ /** Registers the progress-bar element so the auto-close modifier can animate it. */
+ onRegisterProgressBar?: (element: HTMLElement) => void;
+}
+
+/** The signature of a toast component (the default is `DDefaultToast`). */
+export type ToastComponent = ComponentLike<{
+ Element: HTMLElement;
+ Args: ToastComponentArgs;
+}>;
+
+/** The options for a toast, after merging over the defaults below. */
+export interface ToastOptions {
+ /** Whether the toast closes automatically after `duration`. */
+ autoClose: boolean;
+
+ /** Whether to reposition automatically; an object passes floating-ui `autoUpdate` options. */
+ autoUpdate: boolean | AutoUpdateOptions;
+
+ /** How long the toast stays open: a preset (`"short"`/`"long"`) or a number of milliseconds. */
+ duration: "short" | "long" | number;
+
+ /** The component rendered as the toast body. */
+ component: ToastComponent;
+
+ /** Whether to show a progress bar counting down to auto-close. */
+ showProgressBar: boolean;
+
+ /** The viewports the toast is shown on. */
+ views: Array<"desktop" | "mobile">;
+
+ /** The `@data` passed to the toast component. */
+ data?: ToastData;
+
+ /** A class added to the toast element. */
+ class?: string;
+}
+
+export const TOOLTIP: { options: TooltipOptions; portalOutletId: string } = {
+ options: {
+ animated: true,
+ arrow: true,
+ beforeTrigger: null,
+ closeOnClickOutside: true,
+ closeOnEscape: true,
+ closeOnScroll: true,
+ component: null,
+ content: null,
+ identifier: null,
+ inline: null,
+ interactive: false,
+ listeners: false,
+ maxWidth: 350,
+ data: null,
+ offset: 10,
+ triggers: { mobile: ["click"], desktop: ["hover", "click"] },
+ untriggers: { mobile: ["click"], desktop: ["hover", "click"] },
+ placement: "top",
+ shiftBeforeVisibilityOptimizer: false,
+ visibilityOptimizer: VISIBILITY_OPTIMIZERS.FLIP,
+ fallbackPlacements: FLOAT_UI_PLACEMENTS,
+ autoUpdate: true,
+ trapTab: true,
+ onClose: null,
+ onShow: null,
+ onRegisterApi: null,
+ portalOutletElement: null,
+ },
+ portalOutletId: "d-tooltip-portal-outlet",
+};
+
+export const MENU: { options: MenuOptions; portalOutletId: string } = {
+ options: {
+ animated: true,
+ arrow: false,
+ autofocus: false,
+ beforeTrigger: null,
+ closeOnEscape: true,
+ closeOnClickOutside: true,
+ closeOnScroll: false,
+ component: null,
+ content: null,
+ identifier: null,
+ interactive: true,
+ listeners: false,
+ maxWidth: 400,
+ data: null,
+ offset: 10,
+ triggers: ["click"],
+ untriggers: ["click"],
+ placement: "bottom-start",
+ shiftBeforeVisibilityOptimizer: false,
+ visibilityOptimizer: VISIBILITY_OPTIMIZERS.FLIP,
+ fallbackPlacements: FLOAT_UI_PLACEMENTS,
+ autoUpdate: true,
+ trapTab: true,
+ onClose: null,
+ onShow: null,
+ onRegisterApi: null,
+ modalForMobile: false,
+ inline: null,
+ groupIdentifier: null,
+ parentIdentifier: null,
+ triggerClass: null,
+ contentClass: null,
+ class: null,
+ matchTriggerMinWidth: false,
+ matchTriggerWidth: false,
+ portalOutletElement: null,
+ },
+ portalOutletId: "d-menu-portal-outlet",
+};
+
+export const TOAST: { options: ToastOptions } = {
+ options: {
+ autoClose: true,
+ autoUpdate: { ancestorScroll: false },
+ duration: "short",
+ component: DDefaultToast,
+ showProgressBar: false,
+ views: ["desktop", "mobile"],
+ },
+};
diff --git a/frontend/discourse/float-kit/lib/d-menu-instance.js b/frontend/discourse/float-kit/lib/d-menu-instance.ts
similarity index 51%
rename from frontend/discourse/float-kit/lib/d-menu-instance.js
rename to frontend/discourse/float-kit/lib/d-menu-instance.ts
index 1b5b4900145..02a4f6e88c2 100644
--- a/frontend/discourse/float-kit/lib/d-menu-instance.js
+++ b/frontend/discourse/float-kit/lib/d-menu-instance.ts
@@ -1,42 +1,55 @@
import { tracked } from "@glimmer/tracking";
+import { isDestroying } from "@ember/destroyable";
import { action } from "@ember/object";
import { guidFor } from "@ember/object/internals";
-import { getOwner, setOwner } from "@ember/owner";
+import Owner, { getOwner, setOwner } from "@ember/owner";
import { cancel } from "@ember/runloop";
import { service } from "@ember/service";
-import { MENU } from "discourse/float-kit/lib/constants";
+import {
+ type FloatKitTrigger,
+ MENU,
+ type MenuOptions,
+} from "discourse/float-kit/lib/constants";
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";
+
+/**
+ * The concrete float instance backing a menu. It holds the menu's options,
+ * open/close state, and portal outlet, and implements the trigger and lifecycle
+ * hooks that `FloatKitInstance` orchestrates. A menu refocuses its trigger when
+ * it closes and, on mobile, closes through the modal service when it was shown
+ * as a modal.
+ */
export default class DMenuInstance extends FloatKitInstance {
- @service menu;
- @service site;
- @service modal;
+ @service declare menu: MenuService;
+ @service declare site: Site;
+ @service declare modal: ModalService;
- /**
- * Indicates whether the menu is expanded or not.
- * @property {boolean} expanded - Tracks the state of menu expansion, initially set to false.
- */
+ /** Whether the menu is currently open. */
@tracked expanded = false;
/**
- * Specifies whether the trigger for opening/closing the menu is detached from the menu itself.
- * This is the case when a menu is trigger programmatically instead of through the <DMenu /> component.
- * @property {boolean} detachedTrigger - Tracks whether the trigger is detached, initially set to 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
+ * trigger and content live in separate parts of the DOM and are rendered by
+ * `DHeadlessMenu` rather than by `DMenu`.
*/
@tracked detachedTrigger = false;
/**
- * Configuration options for the DMenuInstance.
- * @property {Object} options - Options object that configures the menu behavior and display.
+ * The merged menu options: the defaults from `MENU.options` with the caller's
+ * overrides applied in the constructor.
*/
- @tracked options;
- @tracked portalOutletOverrideElement;
+ @tracked options: MenuOptions;
+ @tracked portalOutletOverrideElement?: HTMLElement | null;
- @tracked _trigger;
+ @tracked _trigger: FloatKitTrigger;
- constructor(owner, options = {}) {
- super(...arguments);
+ constructor(owner: Owner, options: Partial<MenuOptions> = {}) {
+ super();
setOwner(this, owner);
this.options = { ...MENU.options, ...options };
@@ -54,9 +67,10 @@ export default class DMenuInstance extends FloatKitInstance {
return this._trigger;
}
- set trigger(element) {
+ set trigger(element: FloatKitTrigger) {
this._trigger = element;
- this.id = element.id || guidFor(element);
+ this.id =
+ (element instanceof HTMLElement && element.id) || guidFor(element);
this.setupListeners();
}
@@ -68,7 +82,7 @@ export default class DMenuInstance extends FloatKitInstance {
async close(options = { focusTrigger: true }) {
this.openedByDelayedHover = false;
- if (getOwner(this).isDestroying) {
+ if (isDestroying(getOwner(this)!)) {
return;
}
@@ -81,21 +95,21 @@ export default class DMenuInstance extends FloatKitInstance {
await this.menu.close(this);
if (options.focusTrigger) {
- this.trigger?.focus?.();
+ this.triggerElement?.focus();
}
- await super.close(...arguments);
+ await super.close(options);
}
@action
async show() {
- await super.show(...arguments);
+ await super.show();
await this.menu.show(this);
}
@action
- async onPointerMove(event) {
- if (this.expanded && this.trigger.contains(event.target)) {
+ async onPointerMove(event: PointerEvent) {
+ if (this.expanded && this.triggerElement?.contains(event.target as Node)) {
return;
}
@@ -103,7 +117,7 @@ export default class DMenuInstance extends FloatKitInstance {
}
@action
- async onClick(event) {
+ async onClick(event: MouseEvent) {
cancel(this.delayedHoverTimeout);
if (this.openedByDelayedHover) {
@@ -119,14 +133,14 @@ export default class DMenuInstance extends FloatKitInstance {
}
@action
- async onPointerLeave(event) {
+ async onPointerLeave(event: PointerEvent) {
if (this.untriggers.includes("hover")) {
await this.onUntrigger(event);
}
}
@action
- async onTrigger(event) {
+ async onTrigger(event: Event) {
event.stopPropagation();
await this.options.beforeTrigger?.(this);
@@ -134,7 +148,7 @@ export default class DMenuInstance extends FloatKitInstance {
}
@action
- async onUntrigger(event) {
+ async onUntrigger(event: Event) {
event.stopPropagation();
await this.close();
diff --git a/frontend/discourse/float-kit/lib/d-toast-instance.js b/frontend/discourse/float-kit/lib/d-toast-instance.js
deleted file mode 100644
index 7373c6c2c5a..00000000000
--- a/frontend/discourse/float-kit/lib/d-toast-instance.js
+++ /dev/null
@@ -1,29 +0,0 @@
-import { action } from "@ember/object";
-import { setOwner } from "@ember/owner";
-import { service } from "@ember/service";
-import { TOAST } from "discourse/float-kit/lib/constants";
-import dUniqueId from "discourse/ui-kit/helpers/d-unique-id";
-
-export default class DToastInstance {
- @service site;
- @service toasts;
-
- options = null;
- id = dUniqueId();
-
- constructor(owner, options = {}) {
- setOwner(this, owner);
- this.options = { ...TOAST.options, ...options };
- }
-
- @action
- close() {
- this.toasts.close(this);
- }
-
- get isValidForView() {
- return this.options.views.includes(
- this.site.desktopView ? "desktop" : "mobile"
- );
- }
-}
diff --git a/frontend/discourse/float-kit/lib/d-toast-instance.ts b/frontend/discourse/float-kit/lib/d-toast-instance.ts
new file mode 100644
index 00000000000..32eed161514
--- /dev/null
+++ b/frontend/discourse/float-kit/lib/d-toast-instance.ts
@@ -0,0 +1,37 @@
+import { action } from "@ember/object";
+import Owner, { setOwner } from "@ember/owner";
+import { service } from "@ember/service";
+import { TOAST, type ToastOptions } from "discourse/float-kit/lib/constants";
+import type ToastsService from "discourse/float-kit/services/toasts";
+import type Site from "discourse/models/site";
+import dUniqueId from "discourse/ui-kit/helpers/d-unique-id";
+
+/**
+ * The instance backing a single toast: its merged options and a stable id used
+ * to track and dismiss it. Unlike a menu or tooltip a toast has no trigger — it
+ * is shown imperatively through the `toasts` service — so this does not extend
+ * `FloatKitInstance`.
+ */
+export default class DToastInstance {
+ @service declare site: Site;
+ @service declare toasts: ToastsService;
+
+ options: ToastOptions;
+ id = dUniqueId();
+
+ constructor(owner: Owner, options: Partial<ToastOptions> = {}) {
+ setOwner(this, owner);
+ this.options = { ...TOAST.options, ...options };
+ }
+
+ @action
+ close() {
+ this.toasts.close(this);
+ }
+
+ get isValidForView() {
+ return this.options.views.includes(
+ this.site.desktopView ? "desktop" : "mobile"
+ );
+ }
+}
diff --git a/frontend/discourse/float-kit/lib/d-tooltip-instance.js b/frontend/discourse/float-kit/lib/d-tooltip-instance.js
deleted file mode 100644
index 297d5319f16..00000000000
--- a/frontend/discourse/float-kit/lib/d-tooltip-instance.js
+++ /dev/null
@@ -1,126 +0,0 @@
-import { tracked } from "@glimmer/tracking";
-import { action } from "@ember/object";
-import { guidFor } from "@ember/object/internals";
-import { setOwner } from "@ember/owner";
-import { cancel } from "@ember/runloop";
-import { service } from "@ember/service";
-import { TOOLTIP } from "discourse/float-kit/lib/constants";
-import FloatKitInstance from "discourse/float-kit/lib/float-kit-instance";
-
-export default class DTooltipInstance extends FloatKitInstance {
- @service tooltip;
-
- /**
- * Indicates whether the tooltip is expanded or not.
- * @property {boolean} expanded - Tracks the state of tooltip expansion, initially set to false.
- */
- @tracked expanded = false;
-
- /**
- * Specifies whether the trigger for opening/closing the tooltip is detached from the tooltip itself.
- * This is the case when a tooltip is trigger programmatically instead of through the <DTooltip /> component.
- * @property {boolean} detachedTrigger - Tracks whether the trigger is detached, initially set to false.
- */
- @tracked detachedTrigger = false;
-
- /**
- * Configuration options for the DTooltipInstance.
- * @property {Object} options - Options object that configures the tooltip behavior and display.
- */
- @tracked options;
- @tracked portalOutletOverrideElement;
-
- @tracked _trigger;
-
- constructor(owner, options = {}) {
- super(...arguments);
-
- setOwner(this, owner);
- this.options = { ...TOOLTIP.options, ...options };
- this.portalOutletOverrideElement = options.portalOutletElement;
- }
-
- get trigger() {
- return this._trigger;
- }
-
- set trigger(element) {
- this._trigger = element;
- this.id = element.id || guidFor(element);
- this.setupListeners();
- }
-
- get portalOutletElement() {
- return (
- this.portalOutletOverrideElement ||
- document.getElementById("d-tooltip-portals")
- );
- }
-
- @action
- async show() {
- await this.tooltip.show(this);
- await super.show(...arguments);
- }
-
- @action
- async close() {
- this.openedByDelayedHover = false;
- await this.tooltip.close(this);
-
- await super.close(...arguments);
- }
-
- @action
- async onPointerMove(event) {
- if (
- this.expanded &&
- this.trigger.contains(event.target) &&
- event.pointerType !== "touch"
- ) {
- return;
- }
-
- await this.onTrigger(event);
- }
-
- @action
- async onClick(event) {
- cancel(this.delayedHoverTimeout);
-
- if (this.openedByDelayedHover) {
- this.openedByDelayedHover = false;
- return;
- }
-
- if (this.expanded && this.untriggers.includes("click")) {
- return await this.onUntrigger(event);
- }
-
- await this.onTrigger(event);
- }
-
- @action
- async onPointerLeave(event) {
- if (this.untriggers.includes("hover")) {
- await this.onUntrigger(event);
- }
- }
-
- @action
- async onTrigger() {
- await this.options.beforeTrigger?.(this);
- await this.show();
- }
-
- @action
- async onUntrigger() {
- await this.close();
- }
-
- @action
- destroy() {
- this.close();
- this.tearDownListeners();
- }
-}
diff --git a/frontend/discourse/float-kit/lib/d-tooltip-instance.ts b/frontend/discourse/float-kit/lib/d-tooltip-instance.ts
new file mode 100644
index 00000000000..0e8c9950160
--- /dev/null
+++ b/frontend/discourse/float-kit/lib/d-tooltip-instance.ts
@@ -0,0 +1,139 @@
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import { guidFor } from "@ember/object/internals";
+import Owner, { setOwner } from "@ember/owner";
+import { cancel } from "@ember/runloop";
+import { service } from "@ember/service";
+import {
+ type FloatKitTrigger,
+ TOOLTIP,
+ type TooltipOptions,
+} from "discourse/float-kit/lib/constants";
+import FloatKitInstance from "discourse/float-kit/lib/float-kit-instance";
+import type TooltipService from "discourse/float-kit/services/tooltip";
+
+/**
+ * The concrete float instance backing a tooltip. It holds the tooltip's options,
+ * open/close state, and portal outlet, and implements the trigger and lifecycle
+ * hooks that `FloatKitInstance` orchestrates.
+ */
+export default class DTooltipInstance extends FloatKitInstance {
+ @service declare tooltip: TooltipService;
+
+ /** Whether the tooltip is currently open. */
+ @tracked expanded = false;
+
+ /**
+ * Whether the tooltip's trigger is managed outside the `<DTooltip />`
+ * component. It is set when the tooltip is created through the `tooltip`
+ * service, where the trigger and content live in separate parts of the DOM
+ * and are rendered by `DHeadlessTooltip` rather than by `DTooltip`.
+ */
+ @tracked detachedTrigger = false;
+
+ /**
+ * The merged tooltip options: the defaults from `TOOLTIP.options` with the
+ * caller's overrides applied in the constructor.
+ */
+ @tracked options: TooltipOptions;
+ @tracked portalOutletOverrideElement?: HTMLElement | null;
+
+ @tracked _trigger: FloatKitTrigger;
+
+ constructor(owner: Owner, options: Partial<TooltipOptions> = {}) {
+ super();
+
+ setOwner(this, owner);
+ this.options = { ...TOOLTIP.options, ...options };
+ this.portalOutletOverrideElement = options.portalOutletElement;
+ }
+
+ get trigger() {
+ return this._trigger;
+ }
+
+ set trigger(element: FloatKitTrigger) {
+ this._trigger = element;
+ this.id =
+ (element instanceof HTMLElement && element.id) || guidFor(element);
+ this.setupListeners();
+ }
+
+ get portalOutletElement() {
+ return (
+ this.portalOutletOverrideElement ||
+ document.getElementById("d-tooltip-portals")
+ );
+ }
+
+ @action
+ async show() {
+ await this.tooltip.show(this);
+ await super.show();
+ }
+
+ @action
+ async close() {
+ this.openedByDelayedHover = false;
+ await this.tooltip.close(this);
+
+ await super.close();
+ }
+
+ @action
+ async onPointerMove(event: PointerEvent) {
+ if (
+ this.expanded &&
+ this.triggerElement?.contains(event.target as Node) &&
+ event.pointerType !== "touch"
+ ) {
+ return;
+ }
+
+ await this.onTrigger(event);
+ }
+
+ @action
+ async onClick(event: MouseEvent) {
+ cancel(this.delayedHoverTimeout);
+
+ if (this.openedByDelayedHover) {
+ this.openedByDelayedHover = false;
+ return;
+ }
+
+ if (this.expanded && this.untriggers.includes("click")) {
+ return await this.onUntrigger(event);
+ }
+
+ await this.onTrigger(event);
+ }
+
+ @action
+ async onPointerLeave(event: PointerEvent) {
+ if (this.untriggers.includes("hover")) {
+ await this.onUntrigger(event);
+ }
+ }
+
+ @action
+ // the trigger event is relayed in from the base and shared actions but, unlike a
+ // menu, a tooltip does not stop its propagation, so the argument is unused here.
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ async onTrigger(_event?: Event) {
+ await this.options.beforeTrigger?.(this);
+ await this.show();
+ }
+
+ @action
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ async onUntrigger(_event?: Event) {
+ await this.close();
+ }
+
+ @action
+ destroy() {
+ this.close();
+ this.tearDownListeners();
+ }
+}
diff --git a/frontend/discourse/float-kit/lib/float-kit-instance.js b/frontend/discourse/float-kit/lib/float-kit-instance.js
deleted file mode 100644
index c8a04807c84..00000000000
--- a/frontend/discourse/float-kit/lib/float-kit-instance.js
+++ /dev/null
@@ -1,280 +0,0 @@
-import { tracked } from "@glimmer/tracking";
-import { action } from "@ember/object";
-import { cancel } from "@ember/runloop";
-import { service } from "@ember/service";
-import { bind } from "discourse/lib/decorators";
-import { makeArray } from "discourse/lib/helpers";
-import discourseLater from "discourse/lib/later";
-
-const TOUCH_OPTIONS = { passive: true, capture: true };
-
-function cancelEvent(event) {
- event.preventDefault();
- event.stopImmediatePropagation();
-}
-
-export default class FloatKitInstance {
- @service site;
-
- @tracked id = null;
-
- @action
- async show() {
- await this.options.onShow?.();
- }
-
- @action
- async close() {
- await this.options.onClose?.();
- }
-
- @action
- async onFocus(event) {
- await this.onTrigger(event);
- }
-
- @action
- async onBlur(event) {
- await this.onTrigger(event);
- }
-
- @action
- async onFocusIn(event) {
- await this.onTrigger(event);
- }
-
- @action
- async onFocusOut(event) {
- await this.onTrigger(event);
- }
-
- @action
- trapPointerDown(event) {
- // this is done to avoid trigger on click outside when you click on your own trigger
- // given trigger and content are not in the same div, we can't just check if target is
- // inside the menu
- if (this.shouldTrapPointerDown) {
- event.stopPropagation();
- }
- }
-
- @action
- onTouchStart(event) {
- if (event.touches.length > 1) {
- this.onTouchCancel();
- return;
- }
-
- event.stopPropagation();
-
- this.trigger.addEventListener(
- "touchmove",
- this.onTouchCancel,
- TOUCH_OPTIONS
- );
- this.trigger.addEventListener(
- "touchcancel",
- this.onTouchCancel,
- TOUCH_OPTIONS
- );
- this.trigger.addEventListener(
- "touchend",
- this.onTouchCancel,
- TOUCH_OPTIONS
- );
- this.touchTimeout = discourseLater(() => {
- if (this.isDestroying || this.isDestroyed) {
- return;
- }
-
- this.trigger.addEventListener("touchend", cancelEvent, {
- once: true,
- capture: true,
- });
-
- this.onTrigger(event);
- }, 500);
- }
-
- @action
- onDelayedHoverEnter(event) {
- cancel(this.delayedHoverTimeout);
- this.delayedHoverTimeout = discourseLater(() => {
- if (this.expanded) {
- return;
- }
- this.openedByDelayedHover = true;
- this.onTrigger(event);
- }, 250);
- }
-
- @action
- onDelayedHoverLeave() {
- cancel(this.delayedHoverTimeout);
- }
-
- @bind
- onTouchCancel() {
- cancel(this.touchTimeout);
-
- this.trigger.removeEventListener("touchmove", this.onTouchCancel);
- this.trigger.removeEventListener("touchend", this.onTouchCancel);
- this.trigger.removeEventListener("touchcancel", this.onTouchCancel);
- }
-
- tearDownListeners() {
- if (typeof this.trigger.addEventListener === "function") {
- this.trigger.removeEventListener("pointerdown", this.trapPointerDown);
- }
-
- if (!this.options?.listeners) {
- return;
- }
-
- makeArray(this.triggers)
- .filter(Boolean)
- .forEach((trigger) => {
- switch (trigger) {
- case "hold":
- this.trigger.removeEventListener("touchstart", this.onTouchStart);
- break;
- case "focus":
- this.trigger.removeEventListener("focus", this.onFocus);
- this.trigger.removeEventListener("blur", this.onBlur);
- break;
- case "focusin":
- this.trigger.removeEventListener("focusin", this.onFocusIn);
- this.trigger.removeEventListener("focusout", this.onFocusOut);
- break;
- case "hover":
- this.trigger.removeEventListener("pointermove", this.onPointerMove);
- if (!this.options.interactive) {
- this.trigger.removeEventListener(
- "pointerleave",
- this.onPointerLeave
- );
- }
-
- break;
- case "delayed-hover":
- cancel(this.delayedHoverTimeout);
- this.trigger.removeEventListener(
- "pointerenter",
- this.onDelayedHoverEnter
- );
- this.trigger.removeEventListener(
- "pointerleave",
- this.onDelayedHoverLeave
- );
- break;
- case "click":
- this.trigger.removeEventListener("click", this.onClick);
- break;
- }
- });
-
- cancel(this.touchTimeout);
- }
-
- setupListeners() {
- if (typeof this.trigger.addEventListener === "function") {
- this.trigger.addEventListener("pointerdown", this.trapPointerDown);
- }
-
- if (!this.options?.listeners) {
- return;
- }
-
- makeArray(this.triggers)
- .filter(Boolean)
- .forEach((trigger) => {
- switch (trigger) {
- case "hold":
- this.trigger.addEventListener(
- "touchstart",
- this.onTouchStart,
- TOUCH_OPTIONS
- );
- break;
- case "focus":
- this.trigger.addEventListener("focus", this.onFocus, {
- passive: true,
- });
- this.trigger.addEventListener("blur", this.onBlur, {
- passive: true,
- });
- break;
- case "focusin":
- this.trigger.addEventListener("focusin", this.onFocusIn, {
- passive: true,
- });
- this.trigger.addEventListener("focusout", this.onFocusOut, {
- passive: true,
- });
- break;
- case "hover":
- this.trigger.addEventListener("pointermove", this.onPointerMove, {
- passive: true,
- });
- if (!this.options.interactive) {
- this.trigger.addEventListener(
- "pointerleave",
- this.onPointerLeave,
- {
- passive: true,
- }
- );
- }
-
- break;
- case "delayed-hover":
- this.trigger.addEventListener(
- "pointerenter",
- this.onDelayedHoverEnter,
- { passive: true }
- );
- this.trigger.addEventListener(
- "pointerleave",
- this.onDelayedHoverLeave,
- { passive: true }
- );
- break;
- case "click":
- this.trigger.addEventListener("click", this.onClick, {
- passive: true,
- });
- break;
- }
- });
- }
-
- get triggers() {
- if (
- typeof this.options.triggers === "object" &&
- !Array.isArray(this.options.triggers)
- ) {
- return this.site.mobileView
- ? (this.options.triggers.mobile ?? ["click"])
- : (this.options.triggers.desktop ?? ["click"]);
- }
-
- return this.options.triggers ?? ["click"];
- }
-
- get untriggers() {
- if (
- typeof this.options.untriggers === "object" &&
- !Array.isArray(this.options.untriggers)
- ) {
- return this.site.mobileView
- ? (this.options.untriggers.mobile ?? ["click"])
- : (this.options.untriggers.desktop ?? ["click"]);
- }
-
- return this.options.untriggers ?? ["click"];
- }
-
- get shouldTrapPointerDown() {
- return true;
- }
-}
diff --git a/frontend/discourse/float-kit/lib/float-kit-instance.ts b/frontend/discourse/float-kit/lib/float-kit-instance.ts
new file mode 100644
index 00000000000..656bd935326
--- /dev/null
+++ b/frontend/discourse/float-kit/lib/float-kit-instance.ts
@@ -0,0 +1,320 @@
+import { tracked } from "@glimmer/tracking";
+import { isDestroyed, isDestroying } from "@ember/destroyable";
+import { action } from "@ember/object";
+import { cancel } from "@ember/runloop";
+import { service } from "@ember/service";
+import type {
+ FloatKitTrigger,
+ TooltipOptions,
+} from "discourse/float-kit/lib/constants";
+import { bind } from "discourse/lib/decorators";
+import { makeArray } from "discourse/lib/helpers";
+import discourseLater from "discourse/lib/later";
+import type Site from "discourse/models/site";
+
+const TOUCH_OPTIONS = { passive: true, capture: true } as const;
+
+function cancelEvent(event: Event) {
+ event.preventDefault();
+ event.stopImmediatePropagation();
+}
+
+/**
+ * The behavior shared by every anchored float (menus and tooltips): the trigger's
+ * event listeners, the touch/hover trigger handling, and the `show`/`close`
+ * lifecycle hooks. Subclasses supply the concrete state and actions this base
+ * orchestrates (`options`, `trigger`, `expanded`, and the trigger/pointer actions).
+ */
+export default abstract class FloatKitInstance {
+ @service declare site: Site;
+
+ @tracked id: string | null = null;
+
+ /** The merged options bag; a menu or tooltip subclass narrows the exact shape. */
+ abstract options: TooltipOptions;
+
+ /**
+ * The reference the float is anchored to — a real element, or a virtual one when the
+ * float is positioned programmatically. Use `triggerElement` for element-only work.
+ */
+ abstract trigger: FloatKitTrigger;
+
+ /** Whether the float is currently open. */
+ abstract expanded: boolean;
+
+ /** The rendered float body, assigned by the `apply-floating-ui` modifier. */
+ declare content: HTMLElement;
+
+ declare touchTimeout: ReturnType<typeof discourseLater>;
+
+ declare delayedHoverTimeout: ReturnType<typeof discourseLater>;
+
+ declare openedByDelayedHover: boolean;
+
+ /**
+ * 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 trigger
+ * is a no-op rather than a runtime error.
+ */
+ get triggerElement(): HTMLElement | null {
+ return this.trigger instanceof HTMLElement ? this.trigger : null;
+ }
+
+ /** The element the rendered float body is portalled into. */
+ abstract get portalOutletElement(): HTMLElement | null;
+
+ abstract onClick(event: MouseEvent): Promise<void>;
+ abstract onPointerMove(event: PointerEvent): Promise<void>;
+ abstract onPointerLeave(event: PointerEvent): Promise<void>;
+ abstract onTrigger(event?: Event): Promise<void>;
+
+ @action
+ async show() {
+ await this.options.onShow?.();
+ }
+
+ @action
+ // `options` is part of the shared close contract (a menu uses it to decide whether to
+ // refocus its trigger); the base close has no trigger to refocus, so it ignores it.
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ async close(options?: { focusTrigger?: boolean }) {
+ await this.options.onClose?.();
+ }
+
+ @action
+ async onFocus(event: FocusEvent) {
+ await this.onTrigger(event);
+ }
+
+ @action
+ async onBlur(event: FocusEvent) {
+ await this.onTrigger(event);
+ }
+
+ @action
+ async onFocusIn(event: FocusEvent) {
+ await this.onTrigger(event);
+ }
+
+ @action
+ async onFocusOut(event: FocusEvent) {
+ await this.onTrigger(event);
+ }
+
+ @action
+ trapPointerDown(event: PointerEvent) {
+ // this is done to avoid trigger on click outside when you click on your own trigger
+ // given trigger and content are not in the same div, we can't just check if target is
+ // inside the menu
+ if (this.shouldTrapPointerDown) {
+ event.stopPropagation();
+ }
+ }
+
+ @action
+ onTouchStart(event: TouchEvent) {
+ if (event.touches.length > 1) {
+ this.onTouchCancel();
+ return;
+ }
+
+ event.stopPropagation();
+
+ const element = this.triggerElement;
+ if (!element) {
+ return;
+ }
+
+ element.addEventListener("touchmove", this.onTouchCancel, TOUCH_OPTIONS);
+ element.addEventListener("touchcancel", this.onTouchCancel, TOUCH_OPTIONS);
+ element.addEventListener("touchend", this.onTouchCancel, TOUCH_OPTIONS);
+ this.touchTimeout = discourseLater(() => {
+ if (isDestroying(this) || isDestroyed(this)) {
+ return;
+ }
+
+ element.addEventListener("touchend", cancelEvent, {
+ once: true,
+ capture: true,
+ });
+
+ this.onTrigger(event);
+ }, 500);
+ }
+
+ @action
+ onDelayedHoverEnter(event: PointerEvent) {
+ cancel(this.delayedHoverTimeout);
+ this.delayedHoverTimeout = discourseLater(() => {
+ if (this.expanded) {
+ return;
+ }
+ this.openedByDelayedHover = true;
+ this.onTrigger(event);
+ }, 250);
+ }
+
+ @action
+ onDelayedHoverLeave() {
+ cancel(this.delayedHoverTimeout);
+ }
+
+ @bind
+ onTouchCancel() {
+ cancel(this.touchTimeout);
+
+ const element = this.triggerElement;
+ if (!element) {
+ return;
+ }
+
+ element.removeEventListener("touchmove", this.onTouchCancel);
+ element.removeEventListener("touchend", this.onTouchCancel);
+ element.removeEventListener("touchcancel", this.onTouchCancel);
+ }
+
+ tearDownListeners() {
+ const element = this.triggerElement;
+ if (element) {
+ element.removeEventListener("pointerdown", this.trapPointerDown);
+ }
+
+ if (!this.options?.listeners || !element) {
+ return;
+ }
+
+ makeArray(this.triggers)
+ .filter(Boolean)
+ .forEach((trigger) => {
+ switch (trigger) {
+ case "hold":
+ element.removeEventListener("touchstart", this.onTouchStart);
+ break;
+ case "focus":
+ element.removeEventListener("focus", this.onFocus);
+ element.removeEventListener("blur", this.onBlur);
+ break;
+ case "focusin":
+ element.removeEventListener("focusin", this.onFocusIn);
+ element.removeEventListener("focusout", this.onFocusOut);
+ break;
+ case "hover":
+ element.removeEventListener("pointermove", this.onPointerMove);
+ if (!this.options.interactive) {
+ element.removeEventListener("pointerleave", this.onPointerLeave);
+ }
+
+ break;
+ case "delayed-hover":
+ cancel(this.delayedHoverTimeout);
+ element.removeEventListener(
+ "pointerenter",
+ this.onDelayedHoverEnter
+ );
+ element.removeEventListener(
+ "pointerleave",
+ this.onDelayedHoverLeave
+ );
+ break;
+ case "click":
+ element.removeEventListener("click", this.onClick);
+ break;
+ }
+ });
+
+ cancel(this.touchTimeout);
+ }
+
+ setupListeners() {
+ const element = this.triggerElement;
+ if (element) {
+ element.addEventListener("pointerdown", this.trapPointerDown);
+ }
+
+ if (!this.options?.listeners || !element) {
+ return;
+ }
+
+ makeArray(this.triggers)
+ .filter(Boolean)
+ .forEach((trigger) => {
+ switch (trigger) {
+ case "hold":
+ element.addEventListener(
+ "touchstart",
+ this.onTouchStart,
+ TOUCH_OPTIONS
+ );
+ break;
+ case "focus":
+ element.addEventListener("focus", this.onFocus, {
+ passive: true,
+ });
+ element.addEventListener("blur", this.onBlur, {
+ passive: true,
+ });
+ break;
+ case "focusin":
+ element.addEventListener("focusin", this.onFocusIn, {
+ passive: true,
+ });
+ element.addEventListener("focusout", this.onFocusOut, {
+ passive: true,
+ });
+ break;
+ case "hover":
+ element.addEventListener("pointermove", this.onPointerMove, {
+ passive: true,
+ });
+ if (!this.options.interactive) {
+ element.addEventListener("pointerleave", this.onPointerLeave, {
+ passive: true,
+ });
+ }
+
+ break;
+ case "delayed-hover":
+ element.addEventListener("pointerenter", this.onDelayedHoverEnter, {
+ passive: true,
+ });
+ element.addEventListener("pointerleave", this.onDelayedHoverLeave, {
+ passive: true,
+ });
+ break;
+ case "click":
+ element.addEventListener("click", this.onClick, {
+ passive: true,
+ });
+ break;
+ }
+ });
+ }
+
+ get triggers(): string[] {
+ const triggers = this.options.triggers;
+
+ if (typeof triggers === "object" && !Array.isArray(triggers)) {
+ return this.site.mobileView
+ ? (triggers.mobile ?? ["click"])
+ : (triggers.desktop ?? ["click"]);
+ }
+
+ return triggers ?? ["click"];
+ }
+
+ get untriggers(): string[] {
+ const untriggers = this.options.untriggers;
+
+ if (typeof untriggers === "object" && !Array.isArray(untriggers)) {
+ return this.site.mobileView
+ ? (untriggers.mobile ?? ["click"])
+ : (untriggers.desktop ?? ["click"]);
+ }
+
+ return untriggers ?? ["click"];
+ }
+
+ get shouldTrapPointerDown() {
+ return true;
+ }
+}
diff --git a/frontend/discourse/float-kit/lib/get-scroll-parent.js b/frontend/discourse/float-kit/lib/get-scroll-parent.js
deleted file mode 100644
index d0de893ac0c..00000000000
--- a/frontend/discourse/float-kit/lib/get-scroll-parent.js
+++ /dev/null
@@ -1,13 +0,0 @@
-export function getScrollParent(node) {
- const isElement = node instanceof HTMLElement;
- const overflowY = isElement && window.getComputedStyle(node).overflowY;
- const isScrollable = overflowY !== "visible" && overflowY !== "hidden";
-
- if (!node || node === document.documentElement) {
- return null;
- } else if (isScrollable && node.scrollHeight >= node.clientHeight) {
- return node;
- }
-
- return getScrollParent(node.parentNode) || window;
-}
diff --git a/frontend/discourse/float-kit/lib/get-scroll-parent.ts b/frontend/discourse/float-kit/lib/get-scroll-parent.ts
new file mode 100644
index 00000000000..6bccd6c45c0
--- /dev/null
+++ b/frontend/discourse/float-kit/lib/get-scroll-parent.ts
@@ -0,0 +1,22 @@
+import type { VirtualElement } from "@floating-ui/dom";
+
+export function getScrollParent(
+ node: Node | VirtualElement | null
+): HTMLElement | Window | null {
+ const isElement = node instanceof HTMLElement;
+ const overflowY = isElement && window.getComputedStyle(node).overflowY;
+ const isScrollable = overflowY !== "visible" && overflowY !== "hidden";
+
+ if (!node || node === document.documentElement) {
+ return null;
+ } else if (
+ isScrollable &&
+ (node as HTMLElement).scrollHeight >= (node as HTMLElement).clientHeight
+ ) {
+ return node as HTMLElement;
+ }
+
+ // A virtual reference has no `parentNode`, so this recurses into the `?? window`
+ // fallback for it, matching the untyped original.
+ return getScrollParent((node as Node).parentNode) || window;
+}
diff --git a/frontend/discourse/float-kit/lib/update-position.js b/frontend/discourse/float-kit/lib/update-position.ts
similarity index 58%
rename from frontend/discourse/float-kit/lib/update-position.js
rename to frontend/discourse/float-kit/lib/update-position.ts
index 4c502698b26..baf2edbb962 100644
--- a/frontend/discourse/float-kit/lib/update-position.js
+++ b/frontend/discourse/float-kit/lib/update-position.ts
@@ -1,29 +1,87 @@
import {
arrow,
autoPlacement,
+ type AutoUpdateOptions,
+ type Boundary,
computePosition,
+ type ComputePositionReturn,
flip,
hide,
inline,
limitShift,
+ type MiddlewareState,
offset,
+ type Padding,
+ type Placement,
shift,
size,
+ type Strategy,
} from "@floating-ui/dom";
import {
FLOAT_UI_PLACEMENTS,
+ type FloatKitTrigger,
+ type FloatUiPlacement,
VISIBILITY_OPTIMIZERS,
+ type VisibilityOptimizer,
} from "discourse/float-kit/lib/constants";
import domFromString from "discourse/lib/dom-from-string";
import { isTesting } from "discourse/lib/environment";
import { iconHTML } from "discourse/lib/icon-library";
import { headerOffset } from "discourse/lib/offset-calculator";
+/**
+ * The positioning-related subset of a float's options that `updatePosition` reads.
+ * Menu/tooltip instances pass their full options bag here; every field is optional
+ * because programmatic callers supply only the ones they need and the rest fall back
+ * to floating-ui defaults. `placement` additionally accepts the sentinel `"center"`,
+ * which centers the float over its trigger instead of anchoring to an edge.
+ */
+export interface PositioningOptions {
+ placement?: FloatUiPlacement | "center";
+ strategy?: Strategy;
+ autoUpdate?: boolean | AutoUpdateOptions;
+ offset?: number;
+ inline?: boolean | null;
+ arrow?: boolean;
+ hide?: boolean;
+ padding?: Padding;
+ boundary?: Boundary;
+ visibilityOptimizer?: VisibilityOptimizer;
+ shiftBeforeVisibilityOptimizer?: boolean;
+ allowedPlacements?: readonly FloatUiPlacement[];
+ fallbackPlacements?: readonly FloatUiPlacement[];
+ limitShift?: Parameters<typeof limitShift>[0];
+ crossAxisShift?: boolean;
+ matchTriggerWidth?: boolean;
+ matchTriggerMinWidth?: boolean;
+ constrainHeightToViewport?: boolean;
+ minHeight?: number;
+ computePosition?: (
+ content: HTMLElement,
+ result: ComputePositionReturn & { arrowElement?: HTMLElement }
+ ) => void;
+}
+
+interface DetectOverflowOptions {
+ padding: Padding;
+ boundary?: Boundary;
+}
+
+/** The state floating-ui hands to a `size` middleware's `apply` callback. */
+type SizeApplyState = MiddlewareState & {
+ availableWidth: number;
+ availableHeight: number;
+};
+
const centerOffset = offset(({ rects }) => {
return -rects.reference.height / 2 - rects.floating.height / 2;
});
-export async function updatePosition(trigger, content, options) {
+export async function updatePosition(
+ trigger: FloatKitTrigger,
+ content: HTMLElement,
+ options: PositioningOptions
+): Promise<void> {
const padding = getPadding(options);
const detectOverflowOptions = buildDetectOverflowOptions(options, padding);
const centered = isCenteredPlacement(options);
@@ -37,7 +95,9 @@ export async function updatePosition(trigger, content, options) {
content.dataset.strategy = options.strategy || "absolute";
const result = await computePosition(trigger, content, {
- placement: centered ? "bottom" : options.placement,
+ // `options.placement` may be the `"center"` sentinel, but that path is handled
+ // by `centered` above, so anything reaching floating-ui is a real placement.
+ placement: (centered ? "bottom" : options.placement) as Placement,
strategy: options.strategy || "absolute",
middleware,
});
@@ -52,7 +112,11 @@ export async function updatePosition(trigger, content, options) {
}
}
-function buildMiddleware(options, content, detectOverflowOptions) {
+function buildMiddleware(
+ options: PositioningOptions,
+ content: HTMLElement,
+ detectOverflowOptions: DetectOverflowOptions
+) {
const middleware = [];
const centered = isCenteredPlacement(options);
@@ -83,7 +147,7 @@ function buildMiddleware(options, content, detectOverflowOptions) {
}
}
- let arrowElement;
+ let arrowElement: HTMLElement | undefined;
if (options.arrow) {
arrowElement = ensureArrowElement(content);
middleware.push(arrow({ element: arrowElement }));
@@ -109,7 +173,11 @@ function buildMiddleware(options, content, detectOverflowOptions) {
return { middleware, arrowElement };
}
-function applyComputedPosition(content, result, arrowElement) {
+function applyComputedPosition(
+ content: HTMLElement,
+ result: ComputePositionReturn,
+ arrowElement: HTMLElement | undefined
+) {
const { x, y, placement, middlewareData } = result;
content.dataset.placement = placement;
@@ -131,7 +199,7 @@ function applyComputedPosition(content, result, arrowElement) {
}
}
-function getPadding(options) {
+function getPadding(options: PositioningOptions): Padding {
return (
options.padding ?? {
top: headerOffset(),
@@ -142,29 +210,35 @@ function getPadding(options) {
);
}
-function buildDetectOverflowOptions(options, padding) {
+function buildDetectOverflowOptions(
+ options: PositioningOptions,
+ padding: Padding
+): DetectOverflowOptions {
return {
padding: isTesting() ? 0 : padding,
boundary: options.boundary,
};
}
-function isCenteredPlacement(options) {
+function isCenteredPlacement(options: PositioningOptions): boolean {
return options.placement === "center";
}
-function ensureArrowElement(content) {
- let arrowElement = content.querySelector(".arrow");
+function ensureArrowElement(content: HTMLElement): HTMLElement {
+ let arrowElement = content.querySelector<HTMLElement>(".arrow");
if (!arrowElement) {
arrowElement = domFromString(
iconHTML("tippy-rounded-arrow", { class: "arrow" })
- )[0];
+ )[0] as HTMLElement;
content.appendChild(arrowElement);
}
return arrowElement;
}
-function buildVisibilityOptimizerMiddleware(options, detectOverflowOptions) {
+function buildVisibilityOptimizerMiddleware(
+ options: PositioningOptions,
+ detectOverflowOptions: DetectOverflowOptions
+) {
const visibilityOptimizer =
options.visibilityOptimizer ?? VISIBILITY_OPTIMIZERS.FLIP;
@@ -174,19 +248,24 @@ function buildVisibilityOptimizerMiddleware(options, detectOverflowOptions) {
if (visibilityOptimizer === VISIBILITY_OPTIMIZERS.AUTO_PLACEMENT) {
return autoPlacement({
- allowedPlacements: options.allowedPlacements ?? FLOAT_UI_PLACEMENTS,
+ allowedPlacements: (options.allowedPlacements ??
+ FLOAT_UI_PLACEMENTS) as Placement[],
...detectOverflowOptions,
});
}
return flip({
- fallbackPlacements: options.fallbackPlacements ?? FLOAT_UI_PLACEMENTS,
+ fallbackPlacements: (options.fallbackPlacements ??
+ FLOAT_UI_PLACEMENTS) as Placement[],
...detectOverflowOptions,
});
}
-function buildShiftMiddleware(options, detectOverflowOptions) {
- let limiter;
+function buildShiftMiddleware(
+ options: PositioningOptions,
+ detectOverflowOptions: DetectOverflowOptions
+) {
+ let limiter: ReturnType<typeof limitShift> | undefined;
if (options.limitShift) {
limiter = limitShift(options.limitShift);
}
@@ -200,11 +279,11 @@ function buildShiftMiddleware(options, detectOverflowOptions) {
});
}
-function buildMatchSizeMiddleware(options) {
+function buildMatchSizeMiddleware(options: PositioningOptions) {
if (options.matchTriggerWidth || options.matchTriggerMinWidth) {
return size({
- apply({ rects, elements }) {
- const styleProps = {};
+ apply({ rects, elements }: SizeApplyState) {
+ const styleProps: Record<string, string> = {};
const widthValue = `${rects.reference.width}px`;
if (options.matchTriggerWidth) {
@@ -223,15 +302,18 @@ function buildMatchSizeMiddleware(options) {
return null;
}
-function buildConstrainHeightMiddleware(options, detectOverflowOptions) {
+function buildConstrainHeightMiddleware(
+ options: PositioningOptions,
+ detectOverflowOptions: DetectOverflowOptions
+) {
if (!options.constrainHeightToViewport) {
return null;
}
return size({
- apply({ availableHeight, elements }) {
+ apply({ availableHeight, elements }: SizeApplyState) {
const max = Math.max(50, (availableHeight ?? 0) - 4);
- const inner = elements.floating.querySelector(
+ const inner = elements.floating.querySelector<HTMLElement>(
".fk-d-menu__inner-content"
);
diff --git a/frontend/discourse/float-kit/modifiers/apply-floating-ui.js b/frontend/discourse/float-kit/modifiers/apply-floating-ui.js
deleted file mode 100644
index bf7c340a1b3..00000000000
--- a/frontend/discourse/float-kit/modifiers/apply-floating-ui.js
+++ /dev/null
@@ -1,48 +0,0 @@
-import { registerDestructor } from "@ember/destroyable";
-import { autoUpdate } from "@floating-ui/dom";
-import Modifier from "ember-modifier";
-import { updatePosition } from "discourse/float-kit/lib/update-position";
-import { bind } from "discourse/lib/decorators";
-
-export default class FloatKitApplyFloatingUi extends Modifier {
- constructor(owner, args) {
- super(owner, args);
- registerDestructor(this, (instance) => instance.teardown());
- }
-
- modify(element, [trigger, options, instance]) {
- instance.content = element;
- this.instance = instance;
- this.options = options ?? {};
-
- if (this.options.autoUpdate) {
- this.cleanup = autoUpdate(
- trigger,
- element,
- this.update,
- typeof this.options.autoUpdate === "object"
- ? this.options.autoUpdate
- : {}
- );
- } else {
- this.update();
- }
- }
-
- @bind
- async update() {
- if (this.instance.trigger?.isConnected === false) {
- return;
- }
-
- await updatePosition(
- this.instance.trigger,
- this.instance.content,
- this.options
- );
- }
-
- teardown() {
- this.cleanup?.();
- }
-}
diff --git a/frontend/discourse/float-kit/modifiers/apply-floating-ui.ts b/frontend/discourse/float-kit/modifiers/apply-floating-ui.ts
new file mode 100644
index 00000000000..7300214149b
--- /dev/null
+++ b/frontend/discourse/float-kit/modifiers/apply-floating-ui.ts
@@ -0,0 +1,81 @@
+import { registerDestructor } from "@ember/destroyable";
+import type Owner from "@ember/owner";
+import { autoUpdate } from "@floating-ui/dom";
+import Modifier, { type ArgsFor } from "ember-modifier";
+import type { FloatKitTrigger } from "discourse/float-kit/lib/constants";
+import type FloatKitInstance from "discourse/float-kit/lib/float-kit-instance";
+import {
+ type PositioningOptions,
+ updatePosition,
+} from "discourse/float-kit/lib/update-position";
+import { bind } from "discourse/lib/decorators";
+
+interface FloatKitApplyFloatingUiSignature {
+ Element: HTMLElement;
+ Args: {
+ Positional: [
+ /** The reference the float is anchored to. */
+ trigger: FloatKitTrigger,
+
+ /** The positioning options, or `undefined` to use the defaults. */
+ options: PositioningOptions | undefined,
+
+ /** The float instance being positioned. */
+ instance: FloatKitInstance,
+ ];
+ };
+}
+
+export default class FloatKitApplyFloatingUi extends Modifier<FloatKitApplyFloatingUiSignature> {
+ declare instance: FloatKitInstance;
+ declare options: PositioningOptions;
+ declare cleanup?: () => void;
+
+ constructor(owner: Owner, args: ArgsFor<FloatKitApplyFloatingUiSignature>) {
+ super(owner, args);
+ registerDestructor(this, (instance) => instance.teardown());
+ }
+
+ modify(
+ element: HTMLElement,
+ [
+ trigger,
+ options,
+ instance,
+ ]: FloatKitApplyFloatingUiSignature["Args"]["Positional"]
+ ) {
+ instance.content = element;
+ this.instance = instance;
+ this.options = options ?? {};
+
+ if (this.options.autoUpdate) {
+ this.cleanup = autoUpdate(
+ trigger,
+ element,
+ this.update,
+ typeof this.options.autoUpdate === "object"
+ ? this.options.autoUpdate
+ : {}
+ );
+ } else {
+ this.update();
+ }
+ }
+
+ @bind
+ async update() {
+ if (this.instance.triggerElement?.isConnected === false) {
+ return;
+ }
+
+ await updatePosition(
+ this.instance.trigger,
+ this.instance.content,
+ this.options
+ );
+ }
+
+ teardown() {
+ this.cleanup?.();
+ }
+}
diff --git a/frontend/discourse/float-kit/modifiers/auto-close-toast.js b/frontend/discourse/float-kit/modifiers/auto-close-toast.ts
similarity index 57%
rename from frontend/discourse/float-kit/modifiers/auto-close-toast.js
rename to frontend/discourse/float-kit/modifiers/auto-close-toast.ts
index cf02699f2fe..b992485b993 100644
--- a/frontend/discourse/float-kit/modifiers/auto-close-toast.js
+++ b/frontend/discourse/float-kit/modifiers/auto-close-toast.ts
@@ -1,28 +1,58 @@
import { registerDestructor } from "@ember/destroyable";
+import type Owner from "@ember/owner";
import { cancel } from "@ember/runloop";
-import Modifier from "ember-modifier";
+import Modifier, { type ArgsFor } from "ember-modifier";
import { bind } from "discourse/lib/decorators";
import discourseLater from "discourse/lib/later";
const CSS_TRANSITION_DELAY_MS = 300;
const TRANSITION_CLASS = "-fade-out";
-export default class AutoCloseToast extends Modifier {
- element;
- close;
- duration;
- transitionLaterHandler;
- closeLaterHandler;
- progressBar;
- progressAnimation;
- enabled;
-
- constructor(owner, args) {
+interface AutoCloseToastSignature {
+ Element: HTMLElement;
+ Args: {
+ Named: {
+ /** Closes the toast. */
+ close: () => void;
+
+ /** How long the toast stays open before auto-closing, in milliseconds. */
+ duration: number;
+
+ /** The progress-bar element to animate down over `duration`. */
+ progressBar?: HTMLElement | null;
+
+ /** Whether auto-close is active. */
+ enabled?: boolean;
+ };
+ };
+}
+
+export default class AutoCloseToast extends Modifier<AutoCloseToastSignature> {
+ declare element: HTMLElement;
+ declare close: () => void;
+ declare duration: number;
+ declare timeRemaining: number;
+ declare transitionLaterHandler: ReturnType<typeof discourseLater>;
+ declare closeLaterHandler: ReturnType<typeof discourseLater>;
+ declare progressBar: HTMLElement | null;
+ declare progressAnimation: Animation | null;
+ declare enabled: boolean;
+
+ constructor(owner: Owner, args: ArgsFor<AutoCloseToastSignature>) {
super(owner, args);
registerDestructor(this, (instance) => instance.cleanup());
}
- modify(element, _, { close, duration, progressBar, enabled }) {
+ modify(
+ element: HTMLElement,
+ _: [],
+ {
+ close,
+ duration,
+ progressBar,
+ enabled,
+ }: AutoCloseToastSignature["Args"]["Named"]
+ ) {
if (enabled === false) {
this.enabled = false;
return;
@@ -32,7 +62,7 @@ export default class AutoCloseToast extends Modifier {
this.close = close;
this.duration = duration;
this.timeRemaining = duration;
- this.progressBar = progressBar;
+ this.progressBar = progressBar ?? null;
this.element.addEventListener("touchstart", this.stopTimer, {
passive: true,
once: true,
@@ -74,7 +104,7 @@ export default class AutoCloseToast extends Modifier {
if (this.progressAnimation) {
this.progressAnimation.play();
- this.progressBar.style.opacity = 1;
+ this.progressBar.style.opacity = "1";
return;
}
@@ -94,8 +124,11 @@ export default class AutoCloseToast extends Modifier {
}
this.progressAnimation.pause();
- this.progressBar.style.opacity = 0.5;
- this.timeRemaining = this.duration - this.progressAnimation.currentTime;
+ // `progressAnimation` only exists once `progressBar` was set, and `cleanup`
+ // pauses before clearing it, so the bar is always present here.
+ this.progressBar!.style.opacity = "0.5";
+ this.timeRemaining =
+ this.duration - (this.progressAnimation.currentTime as number);
}
cleanup() {
diff --git a/frontend/discourse/float-kit/modifiers/close-on-escape.js b/frontend/discourse/float-kit/modifiers/close-on-escape.js
deleted file mode 100644
index 2b649f1fd89..00000000000
--- a/frontend/discourse/float-kit/modifiers/close-on-escape.js
+++ /dev/null
@@ -1,30 +0,0 @@
-import { registerDestructor } from "@ember/destroyable";
-import Modifier from "ember-modifier";
-import { bind } from "discourse/lib/decorators";
-
-export default class FloatKitCloseOnEscape extends Modifier {
- constructor(owner, args) {
- super(owner, args);
- registerDestructor(this, (instance) => instance.cleanup());
- }
-
- modify(element, [closeFn]) {
- this.closeFn = closeFn;
- this.element = element;
-
- document.addEventListener("keydown", this.check, { capture: true });
- }
-
- @bind
- check(event) {
- if (event.key === "Escape") {
- event.stopPropagation();
- event.preventDefault();
- this.closeFn();
- }
- }
-
- cleanup() {
- document.removeEventListener("keydown", this.check, { capture: true });
- }
-}
diff --git a/frontend/discourse/float-kit/modifiers/close-on-escape.ts b/frontend/discourse/float-kit/modifiers/close-on-escape.ts
new file mode 100644
index 00000000000..bca8c3dfaf1
--- /dev/null
+++ b/frontend/discourse/float-kit/modifiers/close-on-escape.ts
@@ -0,0 +1,47 @@
+import { registerDestructor } from "@ember/destroyable";
+import type Owner from "@ember/owner";
+import Modifier, { type ArgsFor } from "ember-modifier";
+import { bind } from "discourse/lib/decorators";
+
+interface FloatKitCloseOnEscapeSignature {
+ Element: HTMLElement;
+ Args: {
+ Positional: [
+ /** Called when Escape is pressed. */
+ close: () => void,
+ ];
+ };
+}
+
+export default class FloatKitCloseOnEscape extends Modifier<FloatKitCloseOnEscapeSignature> {
+ declare closeFn: () => void;
+ declare element: HTMLElement;
+
+ constructor(owner: Owner, args: ArgsFor<FloatKitCloseOnEscapeSignature>) {
+ super(owner, args);
+ registerDestructor(this, (instance) => instance.cleanup());
+ }
+
+ modify(
+ element: HTMLElement,
+ [closeFn]: FloatKitCloseOnEscapeSignature["Args"]["Positional"]
+ ) {
+ this.closeFn = closeFn;
+ this.element = element;
+
+ document.addEventListener("keydown", this.check, { capture: true });
+ }
+
+ @bind
+ check(event: KeyboardEvent) {
+ if (event.key === "Escape") {
+ event.stopPropagation();
+ event.preventDefault();
+ this.closeFn();
+ }
+ }
+
+ cleanup() {
+ document.removeEventListener("keydown", this.check, { capture: true });
+ }
+}
diff --git a/frontend/discourse/float-kit/services/internal-tooltip.js b/frontend/discourse/float-kit/services/internal-tooltip.ts
similarity index 78%
rename from frontend/discourse/float-kit/services/internal-tooltip.js
rename to frontend/discourse/float-kit/services/internal-tooltip.ts
index 7db1b15356a..2c0dde2779a 100644
--- a/frontend/discourse/float-kit/services/internal-tooltip.js
+++ b/frontend/discourse/float-kit/services/internal-tooltip.ts
@@ -1,5 +1,6 @@
import { tracked } from "@glimmer/tracking";
import Service from "@ember/service";
+import type DTooltipInstance from "discourse/float-kit/lib/d-tooltip-instance";
/*
This service holds the current tooltip displayed when using <DTooltip> component.
@@ -8,5 +9,5 @@ import Service from "@ember/service";
we end up with a detached element in the DOM and unexpected behavior.
*/
export default class InternalTooltip extends Service {
- @tracked activeTooltip;
+ @tracked activeTooltip?: DTooltipInstance;
}
diff --git a/frontend/discourse/float-kit/services/menu.js b/frontend/discourse/float-kit/services/menu.js
deleted file mode 100644
index e36b125da00..00000000000
--- a/frontend/discourse/float-kit/services/menu.js
+++ /dev/null
@@ -1,145 +0,0 @@
-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 DMenuInstance from "discourse/float-kit/lib/d-menu-instance";
-
-export default class Menu extends Service {
- registeredMenus = trackedSet();
-
- /**
- * Render a menu
- *
- * @param {Element | DMenuInstance}
- * - trigger - the element that triggered the menu, can also be an object implementing `getBoundingClientRect`
- * - menu - an instance of a menu
- * @param {Object} [options] - options
- * @param {String | Element | Component} [options.content] - Specifies the content of the menu
- * @param {Integer} [options.maxWidth] - Specifies the maximum width of the content
- * @param {Object} [options.data] - An object which will be passed as the `@data` argument when content is a `Component`
- * @param {Boolean} [options.arrow] - Determines if the menu has an arrow
- * @param {Boolean} [options.offset] - Displaces the content from its reference trigger in pixels
- * @param {String} [options.identifier] - Add a data-identifier attribute to the trigger and the content, multiple menus can have the same identifier,
- * only one menu with the same identifier can be open at a time
- * @param {String} [options.groupIdentifier] - Only one menu with the same groupIdentifier can be open at a time
- * @param {Boolean} [options.inline] - Improves positioning for trigger that spans over multiple lines
- *
- * @returns {Promise<DMenuInstance | undefined>}
- */
- @action
- async show() {
- let instance;
-
- if (arguments[0] instanceof DMenuInstance) {
- instance = arguments[0];
-
- if (instance.expanded) {
- return;
- }
- } else {
- instance = [...this.registeredMenus].find(
- (registeredMenu) => registeredMenu.trigger === arguments[0]
- );
-
- instance ??= this.newInstance(arguments[0], arguments[1]);
- }
-
- if (instance.options.identifier || instance.options.groupIdentifier) {
- for (const registeredMenu of this.registeredMenus) {
- if (
- ((instance.options.identifier &&
- registeredMenu.options.identifier ===
- instance.options.identifier) ||
- (instance.options.groupIdentifier &&
- registeredMenu.options.groupIdentifier ===
- instance.options.groupIdentifier)) &&
- registeredMenu !== instance
- ) {
- await this.close(registeredMenu);
- }
- }
- }
-
- if (instance.expanded) {
- await this.close(instance);
- return;
- }
-
- if (!this.registeredMenus.has(instance)) {
- this.registeredMenus.add(instance);
- }
-
- instance.expanded = true;
-
- await new Promise((resolve) => schedule("afterRender", resolve));
-
- return instance;
- }
-
- newInstance(trigger, options) {
- const instance = new DMenuInstance(getOwner(this), options);
- instance.trigger = trigger;
- instance.detachedTrigger = true;
-
- return instance;
- }
-
- /**
- * Returns an existing menu by its identifier if found
- *
- * @param {String} identifier - the menu identifier to retrieve
- *
- * @returns {DMenuInstance | undefined}
- */
- getByIdentifier(identifier) {
- return [...this.registeredMenus].find(
- (registeredMenu) => registeredMenu.options.identifier === identifier
- );
- }
-
- /**
- * Closes the given menu
- *
- * @param {DMenuInstance | String} [menu | identifier] - the menu to close, can accept an instance or an identifier
- */
- @action
- async close(menu) {
- if (typeof menu === "string") {
- menu = [...this.registeredMenus].find(
- (registeredMenu) => registeredMenu.options.identifier === menu
- );
- }
-
- if (!menu) {
- return;
- }
-
- menu.expanded = false;
-
- if (this.registeredMenus.has(menu)) {
- this.registeredMenus.delete(menu);
- }
-
- await new Promise((resolve) => schedule("afterRender", resolve));
- }
-
- /**
- * Register event listeners on a trigger to show a menu
- *
- * @param {Element} trigger - the element that triggered the menu, can also be an object implementing `getBoundingClientRect`
- * @param {Object} [options] - @see `show`
- *
- * @returns {DMenuInstance} An instance of the menu
- */
- @action
- register(trigger, options = {}) {
- const instance = new DMenuInstance(getOwner(this), {
- ...options,
- listeners: true,
- });
- instance.trigger = trigger;
- instance.detachedTrigger = true;
- return instance;
- }
-}
diff --git a/frontend/discourse/float-kit/services/menu.ts b/frontend/discourse/float-kit/services/menu.ts
new file mode 100644
index 00000000000..7a8aeadca2f
--- /dev/null
+++ b/frontend/discourse/float-kit/services/menu.ts
@@ -0,0 +1,165 @@
+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 type {
+ FloatKitTrigger,
+ MenuOptions,
+} from "discourse/float-kit/lib/constants";
+import DMenuInstance from "discourse/float-kit/lib/d-menu-instance";
+
+/**
+ * The service that shows menus imperatively, outside the `<DMenu />` component.
+ * It tracks every registered menu, enforces that only one menu per `identifier`
+ * or `groupIdentifier` is open at a time, and exposes the set that `DMenus`
+ * renders at the app root. Prefer `<DMenu />` when a template can own the trigger
+ * and content directly.
+ */
+export default class Menu extends Service {
+ registeredMenus = trackedSet<DMenuInstance>();
+
+ /**
+ * Render a menu.
+ *
+ * @param triggerOrInstance - the element that triggered the menu (may also be an
+ * object implementing `getBoundingClientRect`), or an existing menu instance.
+ * @param options - the menu options; each field is documented on {@link MenuOptions}.
+ *
+ * @returns the shown menu instance, or `undefined` when the call is a no-op.
+ */
+ @action
+ async show(
+ triggerOrInstance: FloatKitTrigger | DMenuInstance,
+ options?: Partial<MenuOptions>
+ ) {
+ let instance: DMenuInstance | undefined;
+
+ if (triggerOrInstance instanceof DMenuInstance) {
+ instance = triggerOrInstance;
+
+ if (instance.expanded) {
+ return;
+ }
+ } else {
+ instance = [...this.registeredMenus].find(
+ (registeredMenu) => registeredMenu.trigger === triggerOrInstance
+ );
+
+ instance ??= this.newInstance(triggerOrInstance, options);
+ }
+
+ if (instance.options.identifier || instance.options.groupIdentifier) {
+ for (const registeredMenu of this.registeredMenus) {
+ if (
+ ((instance.options.identifier &&
+ registeredMenu.options.identifier ===
+ instance.options.identifier) ||
+ (instance.options.groupIdentifier &&
+ registeredMenu.options.groupIdentifier ===
+ instance.options.groupIdentifier)) &&
+ registeredMenu !== instance
+ ) {
+ await this.close(registeredMenu);
+ }
+ }
+ }
+
+ if (instance.expanded) {
+ await this.close(instance);
+ return;
+ }
+
+ if (!this.registeredMenus.has(instance)) {
+ this.registeredMenus.add(instance);
+ }
+
+ instance.expanded = true;
+
+ await new Promise((resolve) =>
+ // cast away resolve's value parameter: `schedule`'s typed rest args would
+ // otherwise demand it be passed here, and the afterRender queue calls it with none.
+ schedule("afterRender", resolve as () => void)
+ );
+
+ return instance;
+ }
+
+ /**
+ * Creates a menu instance with a detached trigger, without showing it.
+ *
+ * @param trigger - the element the menu is anchored to (may also be an object
+ * implementing `getBoundingClientRect`).
+ * @param options - the menu options; each field is documented on {@link MenuOptions}.
+ *
+ * @returns the created menu instance.
+ */
+ newInstance(trigger: FloatKitTrigger, options?: Partial<MenuOptions>) {
+ const instance = new DMenuInstance(getOwner(this)!, options);
+ instance.trigger = trigger;
+ instance.detachedTrigger = true;
+
+ return instance;
+ }
+
+ /**
+ * Returns an existing menu by its identifier if found.
+ *
+ * @param identifier - the menu identifier to retrieve.
+ */
+ getByIdentifier(identifier: string) {
+ return [...this.registeredMenus].find(
+ (registeredMenu) => registeredMenu.options.identifier === identifier
+ );
+ }
+
+ /**
+ * Closes the given menu.
+ *
+ * @param menu - the menu to close, either an instance or an identifier.
+ */
+ @action
+ async close(menu?: DMenuInstance | string) {
+ if (typeof menu === "string") {
+ menu = [...this.registeredMenus].find(
+ (registeredMenu) => registeredMenu.options.identifier === menu
+ );
+ }
+
+ if (!menu) {
+ return;
+ }
+
+ menu.expanded = false;
+
+ if (this.registeredMenus.has(menu)) {
+ this.registeredMenus.delete(menu);
+ }
+
+ await new Promise((resolve) =>
+ // cast away resolve's value parameter: `schedule`'s typed rest args would
+ // otherwise demand it be passed here, and the afterRender queue calls it with none.
+ schedule("afterRender", resolve as () => void)
+ );
+ }
+
+ /**
+ * Registers event listeners on a trigger to show a menu.
+ *
+ * @param trigger - the element that triggered the menu (may also be an object
+ * implementing `getBoundingClientRect`).
+ * @param options - see `show`.
+ *
+ * @returns the created menu instance.
+ */
+ @action
+ register(trigger: FloatKitTrigger, options: Partial<MenuOptions> = {}) {
+ const instance = new DMenuInstance(getOwner(this)!, {
+ ...options,
+ listeners: true,
+ });
+ instance.trigger = trigger;
+ instance.detachedTrigger = true;
+ return instance;
+ }
+}
diff --git a/frontend/discourse/float-kit/services/toasts.js b/frontend/discourse/float-kit/services/toasts.js
deleted file mode 100644
index 6c6987c971b..00000000000
--- a/frontend/discourse/float-kit/services/toasts.js
+++ /dev/null
@@ -1,121 +0,0 @@
-import { tracked } from "@glimmer/tracking";
-import { action } from "@ember/object";
-import { getOwner } from "@ember/owner";
-import { trackedArray } from "@ember/reactive/collections";
-import Service from "@ember/service";
-import DDefaultToast from "discourse/float-kit/components/d-default-toast";
-import DToastInstance from "discourse/float-kit/lib/d-toast-instance";
-
-export default class Toasts extends Service {
- @tracked activeToasts = trackedArray();
-
- /**
- * Render a toast
- *
- * @param {Object} [options] - options passed to the toast component as `@toast` argument
- * @param {String} [options.duration] - The duration (ms) of the toast, will be closed after this time
- * @param {Boolean} [options.autoClose=true] - When true, the toast will autoClose after the duration
- * @param {ComponentClass} [options.component] - A component to render, will use `DDefaultToast` if not provided
- * @param {String} [options.class] - A class added to the d-toast element
- * @param {Object} [options.data] - An object which will be passed as the `@data` argument to the component
- *
- * @returns {DToastInstance} - a toast instance
- */
- @action
- show(options = {}) {
- const instance = new DToastInstance(getOwner(this), {
- component: DDefaultToast,
- ...options,
- });
-
- if (instance.isValidForView) {
- this.activeToasts.push(instance);
- }
-
- return instance;
- }
-
- /**
- * Render a DDefaultToast toast with the default theme
- *
- * @param {Object} [options] - @see show
- *
- * @returns {DToastInstance} - a toast instance
- */
- @action
- default(options = {}) {
- options.data.theme = "default";
-
- return this.show(options);
- }
-
- /**
- * Render a DDefaultToast toast with the success theme
- *
- * @param {Object} [options] - @see show
- *
- * @returns {DToastInstance} - a toast instance
- */
- @action
- success(options = {}) {
- options.data.theme = "success";
- options.data.icon ??= "check";
-
- return this.show(options);
- }
-
- /**
- * Render a DDefaultToast toast with the error theme
- *
- * @param {Object} [options] - @see show
- *
- * @returns {DToastInstance} - a toast instance
- */
- @action
- error(options = {}) {
- options.data.theme = "error";
- options.data.icon ??= "triangle-exclamation";
-
- return this.show(options);
- }
-
- /**
- * Render a DDefaultToast toast with the warning theme
- *
- * @param {Object} [options] - @see show
- *
- * @returns {DToastInstance} - a toast instance
- */
- @action
- warning(options = {}) {
- options.data.theme = "warning";
- options.data.icon ??= "circle-exclamation";
-
- return this.show(options);
- }
-
- /**
- * Render a DDefaultToast toast with the info theme
- *
- * @param {Object} [options] - @see show
- *
- * @returns {DToastInstance} - a toast instance
- */
- @action
- info(options = {}) {
- options.data.theme = "info";
- options.data.icon ??= "circle-info";
-
- return this.show(options);
- }
-
- /**
- * Close a toast. Any object containing a valid `id` property can be used as a toast parameter.
- */
- @action
- close(toast) {
- this.activeToasts = trackedArray(
- this.activeToasts.filter((activeToast) => activeToast.id !== toast.id)
- );
- }
-}
diff --git a/frontend/discourse/float-kit/services/toasts.ts b/frontend/discourse/float-kit/services/toasts.ts
new file mode 100644
index 00000000000..f5a32382df1
--- /dev/null
+++ b/frontend/discourse/float-kit/services/toasts.ts
@@ -0,0 +1,122 @@
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import { getOwner } from "@ember/owner";
+import { trackedArray } from "@ember/reactive/collections";
+import Service from "@ember/service";
+import DDefaultToast from "discourse/float-kit/components/d-default-toast";
+import type {
+ ToastData,
+ ToastOptions,
+} from "discourse/float-kit/lib/constants";
+import DToastInstance from "discourse/float-kit/lib/d-toast-instance";
+
+/** The options accepted by the themed convenience methods, which require `data`. */
+type ThemedToastOptions = Partial<ToastOptions> & { data: ToastData };
+
+/**
+ * The service that shows and dismisses toasts. Toasts are always created
+ * imperatively — there is no declarative component — so call `show` with a
+ * custom body component, or a themed helper such as `success`/`error` that
+ * renders the default body. It holds the list of active toasts that `DToasts`
+ * renders at the app root.
+ */
+export default class Toasts extends Service {
+ @tracked activeToasts = trackedArray<DToastInstance>();
+
+ /**
+ * Render a toast.
+ *
+ * @param options - options passed to the toast component as its `@toast` argument;
+ * each field is documented on {@link ToastOptions}. When no `component` is given,
+ * `DDefaultToast` is used.
+ *
+ * @returns the created toast instance.
+ */
+ @action
+ show(options: Partial<ToastOptions> = {}) {
+ const instance = new DToastInstance(getOwner(this)!, {
+ component: DDefaultToast,
+ ...options,
+ });
+
+ if (instance.isValidForView) {
+ this.activeToasts.push(instance);
+ }
+
+ return instance;
+ }
+
+ /**
+ * Render a `DDefaultToast` with the default theme.
+ *
+ * @param options - see `show`.
+ */
+ @action
+ default(options: ThemedToastOptions) {
+ options.data.theme = "default";
+
+ return this.show(options);
+ }
+
+ /**
+ * Render a `DDefaultToast` with the success theme.
+ *
+ * @param options - see `show`.
+ */
+ @action
+ success(options: ThemedToastOptions) {
+ options.data.theme = "success";
+ options.data.icon ??= "check";
+
+ return this.show(options);
+ }
+
+ /**
+ * Render a `DDefaultToast` with the error theme.
+ *
+ * @param options - see `show`.
+ */
+ @action
+ error(options: ThemedToastOptions) {
+ options.data.theme = "error";
+ options.data.icon ??= "triangle-exclamation";
+
+ return this.show(options);
+ }
+
+ /**
+ * Render a `DDefaultToast` with the warning theme.
+ *
+ * @param options - see `show`.
+ */
+ @action
+ warning(options: ThemedToastOptions) {
+ options.data.theme = "warning";
+ options.data.icon ??= "circle-exclamation";
+
+ return this.show(options);
+ }
+
+ /**
+ * Render a `DDefaultToast` with the info theme.
+ *
+ * @param options - see `show`.
+ */
+ @action
+ info(options: ThemedToastOptions) {
+ options.data.theme = "info";
+ options.data.icon ??= "circle-info";
+
+ return this.show(options);
+ }
+
+ /**
+ * Close a toast. Any object with a valid `id` property can be used.
+ */
+ @action
+ close(toast: Pick<DToastInstance, "id">) {
+ this.activeToasts = trackedArray(
+ this.activeToasts.filter((activeToast) => activeToast.id !== toast.id)
+ );
+ }
+}
diff --git a/frontend/discourse/float-kit/services/tooltip.js b/frontend/discourse/float-kit/services/tooltip.js
deleted file mode 100644
index 15e62575e39..00000000000
--- a/frontend/discourse/float-kit/services/tooltip.js
+++ /dev/null
@@ -1,119 +0,0 @@
-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 DTooltipInstance from "discourse/float-kit/lib/d-tooltip-instance";
-
-export default class Tooltip extends Service {
- registeredTooltips = trackedSet();
-
- /**
- * Render a tooltip
- *
- * @param {Element | DTooltipInstance}
- * - trigger - the element that triggered the tooltip, can also be an object implementing `getBoundingClientRect`
- * - tooltip - an instance of a tooltip
- * @param {Object} [options] - options, if trigger given as first argument
- * @param {String | Element | Component} [options.content] - Specifies the content of the tooltip
- * @param {Integer} [options.maxWidth] - Specifies the maximum width of the content
- * @param {Object} [options.data] - An object which will be passed as the `@data` argument when content is a `Component`
- * @param {Boolean} [options.arrow] - Determines if the tooltip has an arrow
- * @param {Boolean} [options.offset] - Displaces the content from its reference trigger in pixels
- * @param {String} [options.identifier] - Add a data-identifier attribute to the trigger and the content
- * @param {Boolean} [options.inline] - Improves positioning for trigger that spans over multiple lines
- *
- * @returns {Promise<DTooltipInstance | undefined>}
- */
- @action
- async show() {
- let instance;
-
- if (arguments[0] instanceof DTooltipInstance) {
- instance = arguments[0];
-
- if (instance.expanded) {
- return;
- }
- } else {
- instance = [...this.registeredTooltips].find(
- (registeredTooltips) => registeredTooltips.trigger === arguments[0]
- );
- if (!instance) {
- instance = new DTooltipInstance(getOwner(this), arguments[1]);
- instance.trigger = arguments[0];
- instance.detachedTrigger = true;
- }
- }
-
- if (instance.options.identifier) {
- for (const tooltip of this.registeredTooltips) {
- if (
- tooltip.options.identifier === instance.options.identifier &&
- tooltip !== instance
- ) {
- await this.close(tooltip);
- }
- }
- }
-
- if (instance.expanded) {
- await this.close(instance);
- return;
- }
-
- if (!this.registeredTooltips.has(instance)) {
- this.registeredTooltips.add(instance);
- }
-
- instance.expanded = true;
-
- await new Promise((resolve) => schedule("afterRender", resolve));
-
- return instance;
- }
-
- /**
- * Closes the given tooltip
- * @param {DTooltipInstance | String} [tooltip | identifier] - the tooltip to close, can accept an instance or an identifier
- */
- @action
- async close(tooltip) {
- if (typeof tooltip === "string") {
- tooltip = [...this.registeredTooltips].find(
- (registeredTooltip) => registeredTooltip.options.identifier === tooltip
- );
- }
-
- if (!tooltip) {
- return;
- }
-
- tooltip.expanded = false;
-
- if (this.registeredTooltips.has(tooltip)) {
- this.registeredTooltips.delete(tooltip);
- }
-
- await new Promise((resolve) => schedule("afterRender", resolve));
- }
-
- /**
- * Register event listeners on a trigger to show a tooltip
- *
- * @param {Element} trigger - the element that triggered the tooltip, can also be an object implementing `getBoundingClientRect`
- * @param {Object} [options] - @see `show`
- *
- * @returns {DTooltipInstance} An instance of the tooltip
- */
- @action
- register(trigger, options = {}) {
- const instance = new DTooltipInstance(getOwner(this), {
- ...options,
- listeners: true,
- });
- instance.trigger = trigger;
- instance.detachedTrigger = true;
- return instance;
- }
-}
diff --git a/frontend/discourse/float-kit/services/tooltip.ts b/frontend/discourse/float-kit/services/tooltip.ts
new file mode 100644
index 00000000000..2cf3c547f87
--- /dev/null
+++ b/frontend/discourse/float-kit/services/tooltip.ts
@@ -0,0 +1,133 @@
+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 type {
+ FloatKitTrigger,
+ TooltipOptions,
+} from "discourse/float-kit/lib/constants";
+import DTooltipInstance from "discourse/float-kit/lib/d-tooltip-instance";
+
+/**
+ * The service that shows tooltips imperatively, outside the `<DTooltip />`
+ * component. It tracks every registered tooltip, enforces that only one tooltip
+ * per `identifier` is open at a time, and exposes the set that `DTooltips`
+ * renders at the app root. Prefer `<DTooltip />` when a template can own the
+ * trigger and content directly.
+ */
+export default class Tooltip extends Service {
+ registeredTooltips = trackedSet<DTooltipInstance>();
+
+ /**
+ * Render a tooltip.
+ *
+ * @param triggerOrInstance - the element that triggered the tooltip (may also be an
+ * object implementing `getBoundingClientRect`), or an existing tooltip instance.
+ * @param options - the tooltip options; each field is documented on {@link TooltipOptions}.
+ *
+ * @returns the shown tooltip instance, or `undefined` when the call is a no-op.
+ */
+ @action
+ async show(
+ triggerOrInstance: FloatKitTrigger | DTooltipInstance,
+ options?: Partial<TooltipOptions>
+ ) {
+ let instance: DTooltipInstance | undefined;
+
+ if (triggerOrInstance instanceof DTooltipInstance) {
+ instance = triggerOrInstance;
+
+ if (instance.expanded) {
+ return;
+ }
+ } else {
+ instance = [...this.registeredTooltips].find(
+ (registeredTooltips) => registeredTooltips.trigger === triggerOrInstance
+ );
+ if (!instance) {
+ instance = new DTooltipInstance(getOwner(this)!, options);
+ instance.trigger = triggerOrInstance;
+ instance.detachedTrigger = true;
+ }
+ }
+
+ if (instance.options.identifier) {
+ for (const tooltip of this.registeredTooltips) {
+ if (
+ tooltip.options.identifier === instance.options.identifier &&
+ tooltip !== instance
+ ) {
+ await this.close(tooltip);
+ }
+ }
+ }
+
+ if (instance.expanded) {
+ await this.close(instance);
+ return;
+ }
+
+ if (!this.registeredTooltips.has(instance)) {
+ this.registeredTooltips.add(instance);
+ }
+
+ instance.expanded = true;
+
+ await new Promise((resolve) =>
+ // cast away resolve's value parameter: `schedule`'s typed rest args would
+ // otherwise demand it be passed here, and the afterRender queue calls it with none.
+ schedule("afterRender", resolve as () => void)
+ );
+
+ return instance;
+ }
+
+ /**
+ * Closes the given tooltip.
+ *
+ * @param tooltip - the tooltip to close, either an instance or an identifier.
+ */
+ @action
+ async close(tooltip?: DTooltipInstance | string) {
+ if (typeof tooltip === "string") {
+ tooltip = [...this.registeredTooltips].find(
+ (registeredTooltip) => registeredTooltip.options.identifier === tooltip
+ );
+ }
+
+ if (!tooltip) {
+ return;
+ }
+
+ tooltip.expanded = false;
+
+ if (this.registeredTooltips.has(tooltip)) {
+ this.registeredTooltips.delete(tooltip);
+ }
+
+ await new Promise((resolve) =>
+ schedule("afterRender", resolve as () => void)
+ );
+ }
+
+ /**
+ * Registers event listeners on a trigger to show a tooltip.
+ *
+ * @param trigger - the element that triggered the tooltip (may also be an object
+ * implementing `getBoundingClientRect`).
+ * @param options - see `show`.
+ *
+ * @returns the created tooltip instance.
+ */
+ @action
+ register(trigger: FloatKitTrigger, options: Partial<TooltipOptions> = {}) {
+ const instance = new DTooltipInstance(getOwner(this)!, {
+ ...options,
+ listeners: true,
+ });
+ instance.trigger = trigger;
+ instance.detachedTrigger = true;
+ return instance;
+ }
+}