Reusable stacked modal with an unsaved-changes confirmation
A profile page lets the user rename themselves in a modal dialog. If they try to close the dialog with unsaved edits, a second modal asks them to confirm before the edits are thrown away. Build one reusable modal and use it for both dialogs, so that two modals can be open at once, stacked on top of each other.
The starter code includes the saved name:
const INITIAL_NAME = 'Ada Lovelace';
Display name: {name}, starting with Display name: Ada Lovelace.Every dialog is rendered by the same modal (a component in React, a helper function in vanilla JS):
role="dialog" (or role="alertdialog" for the confirmation), aria-modal="true", and aria-labelledby pointing at the element that holds its title.keydown on document.document.body.style.overflow to hidden. When the last one closes, put back whatever value it had before the first one opened.Name cannot be empty inside it. Otherwise save the trimmed name, update the page, and close the dialog.Click "Edit name" edit dialog opens, input = "Ada Lovelace"
Type " Grace Hopper ", click Save dialog closes, page shows "Display name: Grace Hopper"
Click "Edit name", click Cancel nothing changed: dialog closes right away
Click "Edit name", type "Ada L."
Press Escape "Discard changes?" opens on top
Press Escape only the confirmation closes, input still "Ada L."
Click Cancel, then Discard both close, page still shows "Display name: Ada Lovelace"
The tests click your buttons, type into the input, and read the text on the screen like a user would. You don’t need test ids or specific class names. They check that:
Display name: {name} and an Edit name button, and no visible role="dialog" / role="alertdialog" element until it is clicked.aria-modal="true" and an aria-labelledby element whose text is its title. Its buttons and the Display name input are found inside it.keydown event with key: 'Escape' dispatched on the focused element (often document.body). It bubbles to document, so a listener on document receives it, but a React onKeyDown prop may not.mousedown, mouseup and click on the panel’s parent element. The same events on the dialog title must not close anything.document.body.style.overflow is hidden while a dialog is open and back to its earlier value after the last one closes.A closed dialog can be removed from the page or hidden (hidden, display: none, or visibility: hidden). Capitalization and extra spacing don’t matter.