Skip to content
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

Updates Modal component to use dialog element #2579

Draft
wants to merge 12 commits into
base: main
Choose a base branch
from
7 changes: 7 additions & 0 deletions .changeset/soft-files-explain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@leafygreen-ui/confirmation-modal': major
'@leafygreen-ui/marketing-modal': major
'@leafygreen-ui/modal': major
---

Upgrades components to use the native `dialog` HTML element. This means we no longer have to handle focus trapping ourselves, and can rely on the browser to do that for us. The API for all modal components is not changing, but the DOM structure of the Modal components themselves have changed drastically, as well as where they are placed within the DOM itself.
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
import React, { useState } from 'react';
import {
act,
fireEvent,
render,
waitForElementToBeRemoved,
} from '@testing-library/react';
import { act, fireEvent, render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { axe } from 'jest-axe';

Expand Down Expand Up @@ -40,6 +35,26 @@ function renderModal(
}

describe('packages/confirmation-modal', () => {
beforeAll(() => {
HTMLDialogElement.prototype.show = jest.fn(function mock(
this: HTMLDialogElement,
) {
this.open = true;
});

HTMLDialogElement.prototype.showModal = jest.fn(function mock(
this: HTMLDialogElement,
) {
this.open = true;
});

HTMLDialogElement.prototype.close = jest.fn(function mock(
this: HTMLDialogElement,
) {
this.open = false;
});
});

describe('a11y', () => {
test('does not have basic accessibility issues', async () => {
const { container, getByText } = renderModal({ open: true });
Expand All @@ -55,9 +70,10 @@ describe('packages/confirmation-modal', () => {
});
});

test('does not render if closed', () => {
renderModal();
expect(document.body.innerHTML).toEqual('<div></div>');
test('is not visible when closed', () => {
const { getByRole } = renderModal();
const dialog = getByRole('dialog', { hidden: true });
expect(dialog).not.toBeVisible();
});

test('renders if open', () => {
Expand Down Expand Up @@ -188,21 +204,19 @@ describe('packages/confirmation-modal', () => {
describe('closes when', () => {
test('escape key is pressed', async () => {
const { getByRole } = renderModal({ open: true });
const modal = getByRole('dialog');

fireEvent.keyDown(document, { key: 'Escape', keyCode: 27 });

await waitForElementToBeRemoved(modal);
await waitFor(() => getByRole('dialog', { hidden: true }));
});

test('x icon is clicked', async () => {
const { getByLabelText, getByRole } = renderModal({ open: true });
const modal = getByRole('dialog');

const x = getByLabelText('Close modal');
fireEvent.click(x);

await waitForElementToBeRemoved(modal);
await waitFor(() => getByRole('dialog', { hidden: true }));
});
});

Expand Down Expand Up @@ -298,7 +312,7 @@ describe('packages/confirmation-modal', () => {

userEvent.click(buttonToClick);

await waitForElementToBeRemoved(modal);
await waitFor(() => getByRole('dialog', { hidden: true }));

rerender(
<ConfirmationModal
Expand Down Expand Up @@ -355,7 +369,7 @@ describe('packages/confirmation-modal', () => {

// Modal doesn't close when button is clicked
fireEvent.click(button);
await waitForElementToBeRemoved(modal);
await waitFor(() => getByRole('dialog', { hidden: true }));
});

test('"confirmButtonProps" has "disabled: false"', async () => {
Expand All @@ -375,7 +389,7 @@ describe('packages/confirmation-modal', () => {

// Modal doesn't close when button is clicked
fireEvent.click(button);
await waitForElementToBeRemoved(modal);
await waitFor(() => getByRole('dialog', { hidden: true }));
});
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export const ConfirmationModal = React.forwardRef(
cancelButtonProps = {},
...modalProps
}: ConfirmationModalProps,
forwardRef: React.ForwardedRef<HTMLDivElement | null>,
forwardRef: React.ForwardedRef<HTMLDialogElement | null>,
) => {
const [confirmEnabled, setConfirmEnabled] = useState(!requiredInputText);
const { theme, darkMode } = useDarkMode(darkModeProp);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
import React, { useState } from 'react';
import {
act,
fireEvent,
render,
waitForElementToBeRemoved,
} from '@testing-library/react';
import { act, fireEvent, render, waitFor } from '@testing-library/react';
import { axe } from 'jest-axe';

import MarketingModal from '..';
Expand Down Expand Up @@ -39,6 +34,26 @@ function renderModal(
}

describe('packages/marketing-modal', () => {
beforeAll(() => {
HTMLDialogElement.prototype.show = jest.fn(function mock(
this: HTMLDialogElement,
) {
this.open = true;
});

HTMLDialogElement.prototype.showModal = jest.fn(function mock(
this: HTMLDialogElement,
) {
this.open = true;
});

HTMLDialogElement.prototype.close = jest.fn(function mock(
this: HTMLDialogElement,
) {
this.open = false;
});
});

describe('a11y', () => {
test('does not have basic accessibility issues', async () => {
const { container, getByText } = renderModal({ open: true });
Expand All @@ -53,13 +68,19 @@ describe('packages/marketing-modal', () => {
expect(newResults).toHaveNoViolations();
});
});
test('does not render if closed', () => {
renderModal();
expect(document.body.innerHTML).toEqual('<div></div>');

test('is not visible when closed', () => {
const { getByRole } = renderModal();
const dialog = getByRole('dialog', { hidden: true });
expect(dialog).not.toBeVisible();
});

test('renders if open', () => {
const { getByText, getByLabelText } = renderModal({ open: true });
test('is visible if open', () => {
const { getByText, getByLabelText, getByRole } = renderModal({
open: true,
});
const dialog = getByRole('dialog');
expect(dialog).toBeVisible();
expect(getByLabelText('Image graphic')).toBeVisible();
expect(getByText('Title text')).toBeVisible();
expect(getByText('Content text')).toBeVisible();
Expand Down Expand Up @@ -112,21 +133,19 @@ describe('packages/marketing-modal', () => {
describe('closes when', () => {
test('escape key is pressed', async () => {
const { getByRole } = renderModal({ open: true });
const modal = getByRole('dialog');

fireEvent.keyDown(document, { key: 'Escape', keyCode: 27 });

await waitForElementToBeRemoved(modal);
await waitFor(() => getByRole('dialog', { hidden: true }));
});

test('x icon is clicked', async () => {
const { getByLabelText, getByRole } = renderModal({ open: true });
const modal = getByRole('dialog');

const x = getByLabelText('Close modal');
fireEvent.click(x);

await waitForElementToBeRemoved(modal);
await waitFor(() => getByRole('dialog', { hidden: true }));
});
});

Expand Down
71 changes: 32 additions & 39 deletions packages/modal/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,48 +37,40 @@ function ExampleComponent() {
}
```

**Output HTML**

```html
<button>Open Modal</button>
<div aria-modal="true" role="dialog" tabindex="-1" class="leafygreen-ui-2e4yhj">
<button
tabindex="0"
aria-disabled="false"
aria-label="Close modal"
class="leafygreen-ui-zndd6x"
>
<div class="leafygreen-ui-xhlipt">
<svg
class="leafygreen-ui-19fdo3o"
height="20"
width="20"
viewBox="0 0 16 16"
role="img"
>
<g
id="X-Copy"
stroke="none"
stroke-width="1"
fill="none"
fill-rule="evenodd"
>
<path
d="M9,7 L13.5,7 L13.5,9 L9,9 L9,13.5 L7,13.5 L7,9 L2.5,9 L2.5,7 L7,7 L7,2.5 L9,2.5 L9,7 Z"
id="Combined-Shape-Copy"
fill="currentColor"
transform="translate(8.000000, 8.000000) rotate(45.000000) translate(-8.000000, -8.000000) "
></path>
</g>
</svg>
</div></button
>Modal Content goes here.
</div>
## Notes

Portaled Elements within a Modal

Recommended Approach: `renderMode="top-layer"`
When using any LeafyGreen components that wrap a Portal or Popover component, we recommend setting the `renderMode` prop to the value "top-layer". This is the browser's default way of handling hierarchy, without worrying about the DOM or z-index collisions.

Example:

```js
<Modal>
<Select renderMode="top-layer" />
</Modal>
```

## Notes
Fallback:
If for some reason you must use a Portal with an element rendered inside of a Modal component, you can access the Modal's DOM structure by passing a ref to the `portalRef` property in the Modal component. We will set the current value of your ref to an element inside of the Modal itself.

Example:

It is HIGHLY encouraged that any children inside of `Modal` should refrain from using `usePortal={false}` because this can cause stacking context/z-indexing issues since the popover element will render relative to the parent rather than rendering in a `React portal` which is automatically appended to the `Modal`. By default any component that can use a `React portal`, like `Tooltip` or `Select`, will have `usePortal` set to `true`.
```js
const portalRef = useRef<HTMLDivElement | null>(null)
const [containerState, setContainerState] = useState<React.RefObject<HTMLDivElement>>(null)

useEffect(() => {
if (portalRef.current) {
setContainerState(portalRef)
}
}, [portalRef])

<Modal portalRef={portalRef}>
<Select renderMode="portal" portalContainer={containerState.current}/>
</Modal>
```

## Properties

Expand All @@ -94,6 +86,7 @@ It is HIGHLY encouraged that any children inside of `Modal` should refrain from
| `initialFocus` | `string` | A selector string for the element to move focus to when the modal is opened. The first focusable element in the modal will receive focus by default. | |
| `darkMode` | `boolean` | Determines if the component will appear in dark mode. | `false` |
| `closeIconColor` | `'default'`, `'dark'`, `'light'` | Determines the color of the close icon. | `default` |
| `portalRef` | `React.RefObject<HTMLDivElement>` | Current property gets set with an element inside the Modal, in order to safely portal elements inside of the dialog element | |

## Using `Clipboard.js` inside `Modal`

Expand Down
9 changes: 3 additions & 6 deletions packages/modal/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,15 @@
"@leafygreen-ui/palette": "^4.0.9",
"@leafygreen-ui/portal": "^5.1.1",
"@leafygreen-ui/tokens": "^2.8.0",
"focus-trap": "6.9.4",
"focus-trap-react": "^9.0.2",
"polished": "^4.2.2",
"prop-types": "^15.8.1",
"react-transition-group": "^4.4.5"
"prop-types": "^15.8.1"
},
"devDependencies": {
"@faker-js/faker": "8.0.2",
"@leafygreen-ui/button": "^21.2.0",
"@leafygreen-ui/code": "^14.3.3",
"@leafygreen-ui/copyable": "^8.0.25",
"@leafygreen-ui/select": "^12.1.0",
"@leafygreen-ui/copyable": "^9.0.0",
"@leafygreen-ui/select": "^13.0.0",
"@leafygreen-ui/typography": "^19.1.0",
"@lg-tools/storybook-utils": "^0.1.1"
},
Expand Down
31 changes: 31 additions & 0 deletions packages/modal/src/CloseButton/CloseButton.styles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { css } from '@leafygreen-ui/emotion';
import { Theme } from '@leafygreen-ui/lib';
import { palette } from '@leafygreen-ui/palette';

import { CloseIconColor } from '../Modal/Modal.types';

const getColor = (theme: Theme, customColor: CloseIconColor) => {
switch (customColor) {
case 'dark':
return palette.black;

case 'light':
return palette.gray.light2;

default:
return theme === Theme.Light ? palette.gray.dark1 : palette.gray.light2;
}
};

export const closeButtonStyles = (
theme: Theme,
customColor: CloseIconColor,
) => css`
position: absolute;
cursor: pointer;
// x-icon should be 24px from edge. IconButton is 28x28 and Icon is 16x16
// so there's already (28 - 16) / 2 = 6px of spacing. 24 - 6 = 18.
right: 18px;
top: 18px;
color: ${getColor(theme, customColor)};
`;
32 changes: 32 additions & 0 deletions packages/modal/src/CloseButton/CloseButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import React from 'react';

import { useIdAllocator } from '@leafygreen-ui/hooks';
import XIcon from '@leafygreen-ui/icon/dist/X';
import IconButton from '@leafygreen-ui/icon-button';
import { useDarkMode } from '@leafygreen-ui/leafygreen-provider';

import { LGIDS_MODAL } from '../constants';
import { CloseIconColor } from '../Modal/Modal.types';

import { closeButtonStyles } from './CloseButton.styles';
import { CloseButtonProps } from './CloseButton.types';

export default function CloseButton({
closeIconColor = CloseIconColor.Default,
handleClose,
}: CloseButtonProps) {
const { theme } = useDarkMode();
const closeId = useIdAllocator({ prefix: 'modal' });

return (
<IconButton
id={closeId}
data-testid={LGIDS_MODAL.close}
onClick={handleClose}
aria-label="Close modal"
className={closeButtonStyles(theme, closeIconColor)}
>
<XIcon />
</IconButton>
);
}
6 changes: 6 additions & 0 deletions packages/modal/src/CloseButton/CloseButton.types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { CloseIconColor } from '../Modal/Modal.types';

export interface CloseButtonProps {
closeIconColor?: CloseIconColor;
handleClose?: () => void;
}
1 change: 1 addition & 0 deletions packages/modal/src/CloseButton/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from './CloseButton';
Loading
Loading