Skip to content

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

DEV: Convert the d-modal component to TypeScript (#41678)

Sérgio Saquetimb1daf27d84d5
diff --git a/frontend/discourse/app/services/app-events.js b/frontend/discourse/app/services/app-events.js
deleted file mode 100644
index 8f9c4282a61..00000000000
--- a/frontend/discourse/app/services/app-events.js
+++ /dev/null
@@ -1,4 +0,0 @@
-import Evented from "@ember/object/evented";
-import Service from "@ember/service";
-
-export default class AppEvents extends Service.extend(Evented) {}
diff --git a/frontend/discourse/app/services/app-events.ts b/frontend/discourse/app/services/app-events.ts
new file mode 100644
index 00000000000..9190fa05763
--- /dev/null
+++ b/frontend/discourse/app/services/app-events.ts
@@ -0,0 +1,14 @@
+import Evented from "@ember/object/evented";
+import Service from "@ember/service";
+
+// `Service.extend(Evented)` mixes the Evented methods (`on`, `off`, `one`, `trigger`, `has`)
+// in at runtime, but Ember's `.extend` typing does not surface them. Merging an interface of
+// the same name adds them to the class type — the standard Ember pattern for a
+// mixin-augmented service, hence the suppressed declaration-merging lint rules.
+// eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging
+interface AppEvents extends Evented {}
+
+// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
+class AppEvents extends Service.extend(Evented) {}
+
+export default AppEvents;
diff --git a/frontend/discourse/app/services/capabilities.js b/frontend/discourse/app/services/capabilities.js
index 8c46cb81dac..00255085ca5 100644
--- a/frontend/discourse/app/services/capabilities.js
+++ b/frontend/discourse/app/services/capabilities.js
@@ -14,7 +14,7 @@ const anyPointerCoarseQuery = new TrackedMediaQuery("(any-pointer: coarse)");
let siteInitialized = false;
/**
- * @typedef {_Capabilities} Capabilities
+ * @typedef {_Capabilities} CapabilitiesService
*/
class _Capabilities {
isAndroid = ua.includes("Android");
diff --git a/frontend/discourse/app/ui-kit/d-conditional-in-element.gjs b/frontend/discourse/app/ui-kit/d-conditional-in-element.gjs
deleted file mode 100644
index 28e743dade0..00000000000
--- a/frontend/discourse/app/ui-kit/d-conditional-in-element.gjs
+++ /dev/null
@@ -1,13 +0,0 @@
-const DConditionalInElement = <template>
- {{#if @inline}}
- {{yield}}
- {{else if @element}}
- {{#if @append}}
- {{#in-element @element insertBefore=null}}{{yield}}{{/in-element}}
- {{else}}
- {{#in-element @element}}{{yield}}{{/in-element}}
- {{/if}}
- {{/if}}
-</template>;
-
-export default DConditionalInElement;
diff --git a/frontend/discourse/app/ui-kit/d-conditional-in-element.gts b/frontend/discourse/app/ui-kit/d-conditional-in-element.gts
new file mode 100644
index 00000000000..a6b522df0c1
--- /dev/null
+++ b/frontend/discourse/app/ui-kit/d-conditional-in-element.gts
@@ -0,0 +1,33 @@
+import type { TemplateOnlyComponent } from "@ember/component/template-only";
+
+interface DConditionalInElementSignature {
+ Args: {
+ /** The element to render the content into, when not inline. */
+ element?: Element | null;
+
+ /** Whether to render in place instead of into `@element`. */
+ inline?: boolean;
+
+ /** Whether to append to `@element` rather than replace its content. */
+ append?: boolean;
+ };
+ Blocks: {
+ /** The content to render into the target. */
+ default: [];
+ };
+}
+
+const DConditionalInElement: TemplateOnlyComponent<DConditionalInElementSignature> =
+ <template>
+ {{#if @inline}}
+ {{yield}}
+ {{else if @element}}
+ {{#if @append}}
+ {{#in-element @element insertBefore=null}}{{yield}}{{/in-element}}
+ {{else}}
+ {{#in-element @element}}{{yield}}{{/in-element}}
+ {{/if}}
+ {{/if}}
+ </template>;
+
+export default DConditionalInElement;
diff --git a/frontend/discourse/app/ui-kit/d-modal.gjs b/frontend/discourse/app/ui-kit/d-modal.gts
similarity index 67%
rename from frontend/discourse/app/ui-kit/d-modal.gjs
rename to frontend/discourse/app/ui-kit/d-modal.gts
index 7a74ea869f9..7a43511e877 100644
--- a/frontend/discourse/app/ui-kit/d-modal.gjs
+++ b/frontend/discourse/app/ui-kit/d-modal.gts
@@ -5,19 +5,26 @@ import { action } from "@ember/object";
import didInsert from "@ember/render-modifiers/modifiers/did-insert";
import willDestroy from "@ember/render-modifiers/modifiers/will-destroy";
import { service } from "@ember/service";
+import type { TrustedHTML } from "@ember/template";
import { waitForPromise } from "@ember/test-waiters";
import { modifier as modifierFn } from "ember-modifier";
import htmlClass from "discourse/helpers/html-class";
import { waitForAnimationEnd } from "discourse/lib/animation-utils";
import { lock, unlock } from "discourse/lib/body-scroll-lock";
import { getMaxAnimationTimeMs } from "discourse/lib/swipe-events";
+import type Site from "discourse/models/site";
+import type AppEventsService from "discourse/services/app-events";
+import type { CapabilitiesService } from "discourse/services/capabilities";
+import type ModalService from "discourse/services/modal";
import { and, not, or } from "discourse/truth-helpers";
import DButton from "discourse/ui-kit/d-button";
import DConditionalInElement from "discourse/ui-kit/d-conditional-in-element";
-import DFlashMessage from "discourse/ui-kit/d-flash-message";
+import DFlashMessage, {
+ type FlashType,
+} from "discourse/ui-kit/d-flash-message";
import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
import dElement from "discourse/ui-kit/helpers/d-element";
-import dSwipe from "discourse/ui-kit/modifiers/d-swipe";
+import dSwipe, { type SwipeState } from "discourse/ui-kit/modifiers/d-swipe";
import dTrapTab from "discourse/ui-kit/modifiers/d-trap-tab";
export const CLOSE_INITIATED_BY_BUTTON = "initiatedByCloseButton";
@@ -31,32 +38,137 @@ const SWIPE_CLOSE_DISTANCE_RATIO = 0.25;
const SWIPE_SETTLE_EASING = "cubic-bezier(0.32, 0.72, 0, 1)";
// progressive resistance when the modal is dragged past its resting position
-function dampenedOverdrag(distance) {
+function dampenedOverdrag(distance: number) {
return Math.max(0, 8 * (Math.log(distance + 1) - 2));
}
-export default class DModal extends Component {
- @service appEvents;
- @service capabilities;
- @service modal;
- @service site;
+// The consumer's close handler. DModal invokes it with an `initiatedBy` reason, but the
+// closers consumers pass (the modal service's `close`, or a float that renders DModal as its
+// mobile fallback) accept their own argument shapes, so this is a deliberately broad relay type.
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+type CloseModalCallback = (...args: any[]) => void;
- @tracked wrapperElement;
- @tracked animating = false;
+interface DModalSignature {
+ /** The wrapper element: a `div` or `form`, per `@tagName`. */
+ Element: HTMLDivElement | HTMLFormElement;
+ Args: {
+ /**
+ * Called to close the modal, receiving the reason it was initiated by.
+ * Providing it makes the modal dismissable by default.
+ */
+ closeModal?: CloseModalCallback;
- registerModalContainer = modifierFn((el) => {
- this.modalContainer = el;
- });
+ /**
+ * Called before the modal closes, receiving the initiating reason.
+ * Returning `false` cancels the close.
+ */
+ beforeClose?: (args: {
+ initiatedBy: string;
+ }) => boolean | void | Promise<boolean | void>;
+
+ /**
+ * Whether the modal can be dismissed via the close button, Escape, a
+ * backdrop click, or a swipe down. Defaults to `true` when `@closeModal`
+ * is set.
+ */
+ dismissable?: boolean;
+
+ /** Whether to focus the first focusable element on open. Defaults to `true`. */
+ autofocus?: boolean;
+
+ /** Whether pressing Enter triggers the footer's primary action. Defaults to `true`. */
+ submitOnEnter?: boolean;
+
+ /** Whether the modal is hidden; while hidden it ignores keyboard events. */
+ hidden?: boolean;
+
+ /** Whether to render in place rather than in the modal container. */
+ inline?: boolean;
+
+ /** The wrapper element tag. Defaults to `"div"`. */
+ tagName?: "div" | "form";
+
+ /** The modal title. */
+ title?: string;
+
+ /** The subtitle shown under the title. */
+ subtitle?: string;
+
+ /** Whether to hide the header. */
+ hideHeader?: boolean;
+
+ /** Whether to hide the footer. */
+ hideFooter?: boolean;
+
+ /** Extra class applied to the header. */
+ headerClass?: string;
+
+ /** Extra class applied to the body. */
+ bodyClass?: string;
+
+ /** A flash message shown above the body. Accepts a plain string or trusted HTML. */
+ flash?: string | TrustedHTML;
- setupModalBody = modifierFn((el) => {
+ /** The severity of the `@flash` message. */
+ flashType?: FlashType;
+ };
+ Blocks: {
+ /** The modal body, used when no `body` block is provided. */
+ default: [];
+
+ /** Rendered at the top of the modal, above the header. */
+ aboveHeader: [];
+
+ /** Rendered inside the header, above the title. */
+ headerAboveTitle: [];
+
+ /** Rendered as the header's primary action, on mobile. */
+ headerPrimaryAction: [];
+
+ /** Rendered below the title. */
+ belowModalTitle: [];
+
+ /** Rendered inside the header, below the title. */
+ headerBelowTitle: [];
+
+ /** Rendered below the header, before the flash and body. */
+ belowHeader: [];
+
+ /** The modal body. Takes precedence over the default block. */
+ body: [];
+
+ /** Rendered above the footer. */
+ aboveFooter: [];
+
+ /** The footer content. */
+ footer: [];
+
+ /** Rendered below the footer. */
+ belowFooter: [];
+ };
+}
+
+export default class DModal extends Component<DModalSignature> {
+ @service declare appEvents: AppEventsService;
+ @service declare capabilities: CapabilitiesService;
+ @service declare modal: ModalService;
+ @service declare site: Site;
+
+ @tracked animating = false;
+ registerModalContainer = modifierFn((el: HTMLElement) => {
+ this.#modalContainer = el;
+ });
+ setupModalBody = modifierFn((el: HTMLElement) => {
if (this.site.desktopView) {
return;
}
- lock(el);
+ // `body-scroll-lock` is a vendored bundle whose optional `options` argument is typed as
+ // required; passing `undefined` keeps the original single-argument call.
+ lock(el, undefined);
if (this.capabilities.isIOS) {
- this.lockedScrollY = window.scrollY;
+ this.#lockedScrollY = window.scrollY;
this.appEvents.on(
"keyboard-visibility-change",
this,
@@ -65,7 +177,7 @@ export default class DModal extends Component {
}
return () => {
- unlock(el);
+ unlock(el, undefined);
if (this.capabilities.isIOS) {
this.appEvents.off(
@@ -76,9 +188,42 @@ export default class DModal extends Component {
}
};
});
+ #modalContainer: HTMLElement;
+ #lockedScrollY?: number;
+ @tracked _wrapperElement?: HTMLElement;
+
+ get autofocus() {
+ return this.args.autofocus ?? true;
+ }
+
+ get dismissable() {
+ if (!this.args.closeModal) {
+ return false;
+ } else if ("dismissable" in this.args) {
+ return this.args.dismissable;
+ } else {
+ return true;
+ }
+ }
+
+ // Could be optimised to remove classic component once RFC389 is implemented
+ // https://rfcs.emberjs.com/id/0389-dynamic-tag-names
+ @cached
+ get dynamicElement() {
+ const tagName = this.args.tagName || "div";
+ if (!["div", "form"].includes(tagName)) {
+ throw `@tagName must be form or div`;
+ }
+
+ return dElement(tagName);
+ }
+
+ get mobileDismissable() {
+ return this.site.mobileView && this.dismissable;
+ }
@action
- resetDocumentScrollOnIOS(visible) {
+ resetDocumentScrollOnIOS(visible: boolean) {
// iOS scrolls the page to the focused input when the keyboard opens
// as a result when an input is within a dropdown within a modal, the modal is scrolled out of view.
// This forces the modal back to the correct visible position.
@@ -86,23 +231,23 @@ export default class DModal extends Component {
return;
}
- window.scrollTo(0, this.lockedScrollY ?? 0);
+ window.scrollTo(0, this.#lockedScrollY ?? 0);
}
@action
- async setupModal(el) {
+ async setupModal(el: HTMLElement) {
document.documentElement.addEventListener(
"keydown",
this.handleDocumentKeydown,
{ capture: true }
);
- this.wrapperElement = el;
+ this._wrapperElement = el;
this.animating = true;
- this.modalContainer.classList.add("is-entering");
- await waitForAnimationEnd(this.modalContainer);
- this.modalContainer.classList.remove("is-entering");
+ this.#modalContainer.classList.add("is-entering");
+ await waitForAnimationEnd(this.#modalContainer);
+ this.#modalContainer.classList.remove("is-entering");
this.animating = false;
}
@@ -116,51 +261,15 @@ export default class DModal extends Component {
);
}
- get dismissable() {
- if (!this.args.closeModal) {
- return false;
- } else if ("dismissable" in this.args) {
- return this.args.dismissable;
- } else {
- return true;
- }
- }
-
- get autofocus() {
- return this.args.autofocus ?? true;
- }
-
- get mobileDismissable() {
- return this.site.mobileView && this.dismissable;
- }
-
- shouldTriggerClickOnEnter(event) {
- if (this.args.submitOnEnter === false) {
- return false;
- }
-
- // skip when in a form, textarea, or select-kit element
- if (
- event.target.closest("form") ||
- document.activeElement?.closest("form") ||
- document.activeElement?.nodeName === "TEXTAREA" ||
- document.activeElement?.closest(".select-kit")
- ) {
- return false;
- }
-
- return true;
- }
-
@action
- handleSwipeStart(swipeState, event) {
+ handleSwipeStart(swipeState: SwipeState, event: Event) {
if (this.#shouldDeferSwipeToContent(swipeState)) {
event.preventDefault();
}
}
@action
- async handleSwipe(swipeEvent) {
+ async handleSwipe(swipeEvent: SwipeState) {
if (this.animating) {
return;
}
@@ -176,7 +285,7 @@ export default class DModal extends Component {
}
@action
- async handleSwipeEnded(swipeEvent) {
+ async handleSwipeEnded(swipeEvent: SwipeState) {
if (this.animating) {
// if the modal is animating we don't want to risk resetting the position
// as the user releases the swipe at the same time
@@ -184,7 +293,7 @@ export default class DModal extends Component {
}
const closeDistance =
- this.modalContainer.clientHeight * SWIPE_CLOSE_DISTANCE_RATIO;
+ this.#modalContainer.clientHeight * SWIPE_CLOSE_DISTANCE_RATIO;
if (
swipeEvent.goingUp() ||
@@ -199,13 +308,13 @@ export default class DModal extends Component {
}
@action
- handleWrapperPointerDown(e) {
+ handleWrapperPointerDown(e: PointerEvent) {
// prevents hamburger menu to close on modal backdrop click
e.stopPropagation();
}
@action
- handleWrapperClick(e) {
+ handleWrapperClick(e: MouseEvent) {
if (e.button !== 0) {
return; // Non-default mouse button
}
@@ -218,7 +327,7 @@ export default class DModal extends Component {
}
@action
- async closeModal(initiatedBy) {
+ async closeModal(initiatedBy: string) {
if (!this.args.closeModal) {
return;
}
@@ -238,13 +347,13 @@ export default class DModal extends Component {
} else if (initiatedBy === CLOSE_INITIATED_BY_SWIPE_DOWN) {
await this.#animateSwipeDismiss();
} else {
- const backdrop = this.wrapperElement.nextElementSibling;
- this.modalContainer.classList.add("is-exiting");
+ const backdrop = this._wrapperElement?.nextElementSibling;
+ this.#modalContainer.classList.add("is-exiting");
if (backdrop) {
backdrop.classList.add("is-exiting");
}
- await waitForAnimationEnd(this.modalContainer);
+ await waitForAnimationEnd(this.#modalContainer);
}
} finally {
this.animating = false;
@@ -253,7 +362,7 @@ export default class DModal extends Component {
}
@action
- handleDocumentKeydown(event) {
+ handleDocumentKeydown(event: KeyboardEvent) {
if (this.args.hidden) {
return;
}
@@ -263,7 +372,7 @@ export default class DModal extends Component {
// or inside a float-kit portal (menu/tooltip) opened from this modal,
// since those render outside the modal DOM.
if (
- !this.wrapperElement.contains(document.activeElement) &&
+ !this._wrapperElement?.contains(document.activeElement) &&
!document.activeElement?.closest(
".d-modal, .fk-d-menu, .fk-d-menu-modal, .fk-d-tooltip"
)
@@ -277,9 +386,9 @@ export default class DModal extends Component {
this.closeModal(CLOSE_INITIATED_BY_ESC);
}
- if (event.key === "Enter" && this.shouldTriggerClickOnEnter(event)) {
- this.wrapperElement
- .querySelector(".d-modal__footer .btn-primary")
+ if (event.key === "Enter" && this.#shouldTriggerClickOnEnter(event)) {
+ this._wrapperElement
+ ?.querySelector<HTMLElement>(".d-modal__footer .btn-primary")
?.click();
event.preventDefault();
}
@@ -290,29 +399,35 @@ export default class DModal extends Component {
this.closeModal(CLOSE_INITIATED_BY_BUTTON);
}
- // Could be optimised to remove classic component once RFC389 is implemented
- // https://rfcs.emberjs.com/id/0389-dynamic-tag-names
- @cached
- get dynamicElement() {
- const tagName = this.args.tagName || "div";
- if (!["div", "form"].includes(tagName)) {
- throw `@tagName must be form or div`;
+ #shouldTriggerClickOnEnter(event: KeyboardEvent) {
+ if (this.args.submitOnEnter === false) {
+ return false;
}
- return dElement(tagName);
+ // skip when in a form, textarea, or select-kit element
+ if (
+ (event.target as HTMLElement)?.closest("form") ||
+ document.activeElement?.closest("form") ||
+ document.activeElement?.nodeName === "TEXTAREA" ||
+ document.activeElement?.closest(".select-kit")
+ ) {
+ return false;
+ }
+
+ return true;
}
// lets inner content consume the gesture instead of dragging the modal:
// horizontal swipes, and vertical swipes started within scrollable content
// that can still scroll in the gesture's direction
- #shouldDeferSwipeToContent(swipeState) {
+ #shouldDeferSwipeToContent(swipeState: SwipeState) {
if (swipeState.direction === "left" || swipeState.direction === "right") {
return true;
}
- let element = swipeState.originalEvent?.target;
+ let element = swipeState.originalEvent?.target as HTMLElement | null;
- while (element && element !== this.modalContainer) {
+ while (element && element !== this.#modalContainer) {
if (element.scrollHeight > element.clientHeight) {
const { overflowY } = window.getComputedStyle(element);
@@ -336,14 +451,14 @@ export default class DModal extends Component {
return false;
}
- #animateBackdropOpacity(position) {
- const backdrop = this.wrapperElement.nextElementSibling;
+ #animateBackdropOpacity(position: number) {
+ const backdrop = this._wrapperElement?.nextElementSibling;
if (!backdrop) {
return;
}
- const opacity = 1 - position / this.modalContainer.clientHeight;
+ const opacity = 1 - position / this.#modalContainer.clientHeight;
waitForPromise(
backdrop.animate([{ opacity: Math.max(0, Math.min(opacity, 0.6)) }], {
@@ -352,11 +467,11 @@ export default class DModal extends Component {
);
}
- async #animateWrapperPosition(position, duration) {
+ async #animateWrapperPosition(position: number, duration: number) {
this.#animateBackdropOpacity(position);
await waitForPromise(
- this.modalContainer.animate(
+ this.#modalContainer.animate(
[{ transform: `translateY(${position}px)` }],
{
fill: "forwards",
@@ -372,7 +487,7 @@ export default class DModal extends Component {
// overridden by the drag's fill-forwards animations anyway
async #animateSwipeDismiss() {
const duration = getMaxAnimationTimeMs();
- const backdrop = this.wrapperElement.nextElementSibling;
+ const backdrop = this._wrapperElement?.nextElementSibling;
if (backdrop) {
waitForPromise(
@@ -382,7 +497,7 @@ export default class DModal extends Component {
}
await waitForPromise(
- this.modalContainer.animate([{ transform: "translateY(100%)" }], {
+ this.#modalContainer.animate([{ transform: "translateY(100%)" }], {
fill: "forwards",
duration,
easing: SWIPE_SETTLE_EASING,
@@ -391,18 +506,18 @@ export default class DModal extends Component {
}
async #animatePopOff() {
- const backdrop = this.wrapperElement.nextElementSibling;
+ const backdrop = this._wrapperElement?.nextElementSibling;
if (!backdrop) {
return;
}
- this.modalContainer.classList.add("is-exiting");
+ this.#modalContainer.classList.add("is-exiting");
backdrop.classList.add("is-exiting");
await waitForPromise(
Promise.all([
- waitForAnimationEnd(this.modalContainer),
+ waitForAnimationEnd(this.#modalContainer),
waitForAnimationEnd(backdrop),
])
);
diff --git a/frontend/discourse/app/ui-kit/d-otp/index.gjs b/frontend/discourse/app/ui-kit/d-otp/index.gjs
index b60d476570c..6a567e0fc37 100644
--- a/frontend/discourse/app/ui-kit/d-otp/index.gjs
+++ b/frontend/discourse/app/ui-kit/d-otp/index.gjs
@@ -33,7 +33,7 @@ const DEFAULT_SLOTS = 6;
/** @extends {Component<DOTPSignature>} */
export default class DOTP extends Component {
/**
- * @type {import("discourse/services/capabilities").Capabilities}
+ * @type {import("discourse/services/capabilities").CapabilitiesService}
*/
// @ts-ignore (incorrect no-initialization error)
@service capabilities;
diff --git a/frontend/discourse/app/ui-kit/modifiers/d-trap-tab.js b/frontend/discourse/app/ui-kit/modifiers/d-trap-tab.ts
similarity index 50%
rename from frontend/discourse/app/ui-kit/modifiers/d-trap-tab.js
rename to frontend/discourse/app/ui-kit/modifiers/d-trap-tab.ts
index 392789c5035..0f71d085ca6 100644
--- a/frontend/discourse/app/ui-kit/modifiers/d-trap-tab.js
+++ b/frontend/discourse/app/ui-kit/modifiers/d-trap-tab.ts
@@ -1,32 +1,57 @@
import { registerDestructor } from "@ember/destroyable";
+import type Owner from "@ember/owner";
import { service } from "@ember/service";
-import Modifier from "ember-modifier";
+import Modifier, { type ArgsFor } from "ember-modifier";
import { bind } from "discourse/lib/decorators";
import { focusOffScreen } from "discourse/modifiers/prevent-scroll-on-focus";
+import type { CapabilitiesService } from "discourse/services/capabilities";
const FOCUSABLE_ELEMENTS =
"details:not(.is-disabled) summary, [autofocus], a, input, select, textarea, summary";
-export default class DTrapTabModifier extends Modifier {
- @service capabilities;
+interface DTrapTabSignature {
+ /** The element the tab trap is attached to. */
+ Element: HTMLElement;
+ Args: {
+ Named: {
+ /** Whether focusing an element should prevent scrolling. Defaults to `true`. */
+ preventScroll?: boolean;
- element = null;
+ /** Whether to focus the first focusable element on setup. Defaults to `true`. */
+ autofocus?: boolean;
+ };
+ Positional: [];
+ };
+}
+
+export default class DTrapTabModifier extends Modifier<DTrapTabSignature> {
+ @service declare capabilities: CapabilitiesService;
+
+ #element: HTMLElement | null = null;
+ #originalElement?: HTMLElement;
+ #preventScroll = true;
- constructor(owner, args) {
+ constructor(owner: Owner, args: ArgsFor<DTrapTabSignature>) {
super(owner, args);
- registerDestructor(this, (instance) => instance.cleanup());
+ registerDestructor(this, () => this.#cleanup());
}
- modify(element, _, { preventScroll, autofocus }) {
+ modify(
+ element: HTMLElement,
+ _positional: [],
+ { preventScroll, autofocus }: DTrapTabSignature["Args"]["Named"]
+ ) {
autofocus ??= true;
- this.preventScroll = preventScroll ?? true;
- this.originalElement = element;
- this.element = element.querySelector(".d-modal__container") || element;
- this.originalElement.addEventListener("keydown", this.trapTab);
+ this.#preventScroll = preventScroll ?? true;
+ this.#originalElement = element;
+ this.#element =
+ element.querySelector<HTMLElement>(".d-modal__container") || element;
+ this.#originalElement.addEventListener("keydown", this.trapTab);
// on first trap we don't allow to focus modal-close
// and apply manual focus only if we don't have any autofocus element
- const autofocusedElement = this.element.querySelector("[autofocus]");
+ const autofocusedElement =
+ this.#element.querySelector<HTMLElement>("[autofocus]");
if (
autofocus &&
@@ -37,14 +62,14 @@ export default class DTrapTabModifier extends Modifier {
// to make it possible to scroll with arrow down/up
const target =
autofocusedElement ||
- this.element.querySelector(
+ this.#element.querySelector<HTMLElement>(
FOCUSABLE_ELEMENTS + ", button:not(.modal-close)"
) ||
- this.element.querySelector(".d-modal__body");
+ this.#element.querySelector<HTMLElement>(".d-modal__body");
if (target) {
target.focus({
- preventScroll: this.preventScroll,
+ preventScroll: this.#preventScroll,
});
if (this.capabilities.isIOS) {
@@ -55,7 +80,7 @@ export default class DTrapTabModifier extends Modifier {
}
@bind
- trapTab(event) {
+ trapTab(event: KeyboardEvent) {
if (event.key !== "Tab") {
return;
}
@@ -63,7 +88,7 @@ export default class DTrapTabModifier extends Modifier {
const focusableElements = FOCUSABLE_ELEMENTS + ", button:enabled";
const filteredFocusableElements = Array.from(
- this.element.querySelectorAll(focusableElements)
+ this.#element.querySelectorAll<HTMLElement>(focusableElements)
).filter((element) => {
const tabindex = element.getAttribute("tabindex");
return tabindex !== "-1";
@@ -82,13 +107,14 @@ export default class DTrapTabModifier extends Modifier {
if (document.activeElement === lastFocusableElement) {
event.preventDefault();
(
- this.element.querySelector(".modal-close") || firstFocusableElement
- )?.focus({ preventScroll: this.preventScroll });
+ this.#element.querySelector<HTMLElement>(".modal-close") ||
+ firstFocusableElement
+ )?.focus({ preventScroll: this.#preventScroll });
}
}
}
- cleanup() {
- this.originalElement.removeEventListener("keydown", this.trapTab);
+ #cleanup() {
+ this.#originalElement?.removeEventListener("keydown", this.trapTab);
}
}