Skip to content

feat(dialog, modal, popover, sheet): add options prop to customize focus-trap #11453

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Feb 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 21 additions & 5 deletions packages/calcite-components/src/components/dialog/dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { HeadingLevel } from "../functional/Heading";
import type { OverlayPositioning } from "../../utils/floating-ui";
import { useT9n } from "../../controllers/useT9n";
import type { Panel } from "../panel/panel";
import { useFocusTrap } from "../../controllers/useFocusTrap";
import { ExtendedFocusTrapOptions, useFocusTrap } from "../../controllers/useFocusTrap";
import T9nStrings from "./assets/t9n/messages.en.json";
import {
CSS,
Expand Down Expand Up @@ -70,7 +70,7 @@ export class Dialog extends LitElement implements OpenCloseComponent, LoadableCo

private dragPosition: DialogDragPosition = { ...initialDragPosition };

focusTrap = useFocusTrap<Dialog>({
focusTrap = useFocusTrap<this>({
triggerProp: "open",
focusTrapOptions: {
// scrim closes on click, so we let it take over
Expand Down Expand Up @@ -161,6 +161,16 @@ export class Dialog extends LitElement implements OpenCloseComponent, LoadableCo
*/
@property({ reflect: true }) escapeDisabled = false;

/**
* Specifies custom focus trap configuration on the component, where
*
* `"allowOutsideClick`" allows outside clicks,
* `"initialFocus"` enables initial focus,
* `"returnFocusOnDeactivate"` returns focus when not active, and
* `"extraContainers"` specifies additional focusable elements external to the trap (e.g., 3rd-party components appending elements to the document body).
*/
@property() focusTrapOptions;

/** The component header text. */
@property() heading: string;

Expand Down Expand Up @@ -272,10 +282,16 @@ export class Dialog extends LitElement implements OpenCloseComponent, LoadableCo
return this.panelEl.value?.setFocus() ?? focusFirstTabbable(this.el);
}

/** Updates the element(s) that are used within the focus-trap of the component. */
/**
* Updates the element(s) that are included in the focus-trap of the component.
*
* @param extraContainers - Additional elements to include in the focus trap. This is useful for including elements that may have related parts rendered outside the main focus trapping element.
*/
@method()
async updateFocusTrapElements(): Promise<void> {
this.focusTrap.updateContainerElements();
async updateFocusTrapElements(
extraContainers?: ExtendedFocusTrapOptions["extraContainers"],
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice, this looks good 👍

): Promise<void> {
this.focusTrap.updateContainerElements(extraContainers);
}

/** When defined, provides a condition to disable focus trapping. When `true`, prevents focus trapping. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1079,7 +1079,7 @@ export class InputTimePicker
<calcite-popover
autoClose={true}
focusTrapDisabled={this.focusTrapDisabled}
initialFocusTrapFocus={false}
focusTrapOptions={{ initialFocus: false }}
label={messages.chooseTime}
lang={this.messages._lang}
oncalcitePopoverBeforeClose={this.popoverBeforeCloseHandler}
Expand Down
87 changes: 38 additions & 49 deletions packages/calcite-components/src/components/modal/modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,6 @@ import {
slotChangeGetAssignedElements,
slotChangeHasAssignedElement,
} from "../../utils/dom";
import {
activateFocusTrap,
connectFocusTrap,
deactivateFocusTrap,
FocusTrap,
FocusTrapComponent,
updateFocusTrapElements,
} from "../../utils/focusTrapComponent";
import {
componentFocusable,
LoadableComponent,
Expand All @@ -38,6 +30,7 @@ import { Kind, Scale } from "../interfaces";
import { getIconScale } from "../../utils/component";
import { logger } from "../../utils/logger";
import { useT9n } from "../../controllers/useT9n";
import { ExtendedFocusTrapOptions, useFocusTrap } from "../../controllers/useFocusTrap";
import T9nStrings from "./assets/t9n/messages.en.json";
import { CSS, ICONS, SLOTS } from "./resources";
import { styles } from "./modal.scss";
Expand All @@ -61,10 +54,7 @@ let initialDocumentOverflowStyle: string = "";
* @slot secondary - A slot for adding a secondary button.
* @slot back - A slot for adding a back button.
*/
export class Modal
extends LitElement
implements OpenCloseComponent, FocusTrapComponent, LoadableComponent
{
export class Modal extends LitElement implements OpenCloseComponent, LoadableComponent {
// #region Static Members

static override styles = styles;
Expand All @@ -81,7 +71,21 @@ export class Modal
this.updateSizeCssVars();
});

focusTrap: FocusTrap;
focusTrap = useFocusTrap<this>({
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✨🎮 ✅✨ Nice. Brings all the rest of the components up to date!

triggerProp: "open",
focusTrapOptions: {
// scrim closes on click, so we let it take over
clickOutsideDeactivates: false,
escapeDeactivates: (event) => {
if (!event.defaultPrevented && !this.escapeDisabled) {
this.open = false;
event.preventDefault();
}

return false;
},
},
})(this);

private ignoreOpenChange = false;

Expand Down Expand Up @@ -152,6 +156,16 @@ export class Modal
/** When `true`, prevents focus trapping. */
@property({ reflect: true }) focusTrapDisabled = false;

/**
* Specifies custom focus trap configuration on the component, where
*
* `"allowOutsideClick`" allows outside clicks,
* `"initialFocus"` enables initial focus,
* `"returnFocusOnDeactivate"` returns focus when not active, and
* `"extraContainers"` specifies additional focusable elements external to the trap (e.g., 3rd-party components appending elements to the document body).
*/
@property() focusTrapOptions;

/** Sets the component to always be fullscreen. Overrides `widthScale` and `--calcite-modal-width` / `--calcite-modal-height`. */
@property({ reflect: true }) fullscreen: boolean;

Expand Down Expand Up @@ -230,10 +244,16 @@ export class Modal
focusFirstTabbable(this.el);
}

/** Updates the element(s) that are used within the focus-trap of the component. */
/**
* Updates the element(s) that are included in the focus-trap of the component.
*
* @param extraContainers - Additional elements to include in the focus trap. This is useful for including elements that may have related parts rendered outside the main focus trapping element.
*/
@method()
async updateFocusTrapElements(): Promise<void> {
updateFocusTrapElements(this);
async updateFocusTrapElements(
extraContainers?: ExtendedFocusTrapOptions["extraContainers"],
): Promise<void> {
this.focusTrap.updateContainerElements(extraContainers);
}

// #endregion
Expand Down Expand Up @@ -265,20 +285,6 @@ export class Modal
this.mutationObserver?.observe(this.el, { childList: true, subtree: true });
this.cssVarObserver?.observe(this.el, { attributeFilter: ["style"] });
this.updateSizeCssVars();
connectFocusTrap(this, {
focusTrapOptions: {
// scrim closes on click, so we let it take over
clickOutsideDeactivates: false,
escapeDeactivates: (event) => {
if (!event.defaultPrevented && !this.escapeDisabled) {
this.open = false;
event.preventDefault();
}

return false;
},
},
});
}

async load(): Promise<void> {
Expand All @@ -299,10 +305,6 @@ export class Modal
To account for this semantics change, the checks for (this.hasUpdated || value != defaultValue) was added in this method
Please refactor your code to reduce the need for this check.
Docs: https://qawebgis.esri.com/arcgis-components/?path=/docs/lumina-transition-from-stencil--docs#watching-for-property-changes */
if (changes.has("focusTrapDisabled") && (this.hasUpdated || this.focusTrapDisabled !== false)) {
this.handleFocusTrapDisabled(this.focusTrapDisabled);
}

if (
(changes.has("hasBack") && (this.hasUpdated || this.hasBack !== false)) ||
(changes.has("hasPrimary") && (this.hasUpdated || this.hasPrimary !== false)) ||
Expand All @@ -324,7 +326,6 @@ export class Modal
this.removeOverflowHiddenClass();
this.mutationObserver?.disconnect();
this.cssVarObserver?.disconnect();
deactivateFocusTrap(this);
}

// #endregion
Expand All @@ -346,18 +347,6 @@ export class Modal
}
};

private handleFocusTrapDisabled(focusTrapDisabled: boolean): void {
if (!this.open) {
return;
}

if (focusTrapDisabled) {
deactivateFocusTrap(this);
} else {
activateFocusTrap(this);
}
}

private handleHeaderSlotChange(event: Event): void {
this.titleEl = slotChangeGetAssignedElements<HTMLElement>(event)[0];
}
Expand Down Expand Up @@ -390,7 +379,7 @@ export class Modal
onOpen(): void {
this.transitionEl?.classList.remove(CSS.openingIdle, CSS.openingActive);
this.calciteModalOpen.emit();
activateFocusTrap(this);
this.focusTrap.activate();
}

onBeforeClose(): void {
Expand All @@ -401,7 +390,7 @@ export class Modal
onClose(): void {
this.transitionEl?.classList.remove(CSS.closingIdle, CSS.closingActive);
this.calciteModalClose.emit();
deactivateFocusTrap(this);
this.focusTrap.deactivate();
}

private toggleModal(value: boolean): void {
Expand Down
Loading
Loading