A dialog that behaves
Modals are where keyboard accessibility usually breaks.
Here's my modal: <paste> Make it behave properly: - Focus moves into it on open, and returns to the trigger on close. - Focus is trapped inside while open — Tab must not reach the page behind. - Escape closes it. So does clicking the backdrop, unless there's unsaved input, in which case confirm. - The page behind doesn't scroll, and doesn't jump when the scrollbar disappears. - Announced to screen readers as a dialog, with a label. Consider using the native dialog element rather than building this — tell me whether it fits my case.
The native <dialog> element handles focus, Escape and the backdrop for you. Check whether it fits before building any of this by hand.